[
  {
    "path": "Angular/README.md",
    "content": "# Angular Cheatsheet\r\n\r\n##### Table of Contents  \r\n[Basics](#basics)  \r\n[Loop](#loop)  \r\n[Html](#html)  \r\n[Directives](#directives)  \r\n[Services](#services)  \r\n[Routing](#routing)  \r\n[Filters](#filters)  \r\n\r\n## Basics\r\n**Setup**  \r\n0. You can use the official [Angular Seed Project](https://github.com/angular/angular-seed) for quick startup.  \r\n1. Create a new module named myApp\r\n```javascript\r\n// ja > App.js\r\nvar app = angular.module(\"myApp\", []);\r\n```\r\n2. add a directive: it tells AngularJS that the myApp module will live within the `<body>` scope (or the whole page, `<head>`) \r\n```html\r\n<!-- index.html -->\r\n<head ng-app=\"myApp\"> <!-- or -->\r\n<body ng-app=\"myApp\">\r\n```\r\nSee: [more info on ng-app](https://docs.angularjs.org/api/ng/directive/ngApp)  \r\nThis is called “Bootstrapping”. Sometimes you want to [do it manually](https://docs.angularjs.org/guide/bootstrap#manual-initialization) (if you have multiple Angular apps for instance).\r\n3. Create a new controller: manages the app's data.\r\n```javascript\r\n// js > controllers > MainController.js\r\napp.controller('MainController', ['$scope', function($scope) { \r\n  $scope.title = 'Top Sellers in Books'; \r\n}]);\r\n```\r\n4. ng-controller is a directive that defines the controller scope\r\n```html\r\n<div class=\"main\" ng-controller=\"MainController\">\r\n  <h1>{{ title }}</h1>\r\n</div>\r\n```\r\nWe access $scope.title using {{ title }}. That’s an expression: used to display values on the page.\r\n\r\n### Namings\r\n**Binding** –– {{ ... }}  \r\n**Expressions** –– something + '!'  \r\n**Directives** ––  \r\n**Template** –– (the part of the view containing the bindings and presentation logic) acts as a blueprint for how our data should be organized and presented to the user.  \r\n**Controller** –– provides the context in which the bindings are evaluated and applies behavior and logic to our template.  \r\n**Model** –– What the user sees after the page is fully rendered  \r\n**Module** –– Child on Angular (usually it is the App in an Angular point of view)  \r\n**Components** –– A combination of template + controller with an isolated scope (= no prototypal inheritance and no risk of our component affecting other parts of the application or vice versa) ([Docs](https://docs.angularjs.org/guide/component))\r\n**DI / dependency injection** –– https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection  \r\n\r\n\r\n### misc  \r\n**Price**\r\n```html\r\n<p class=\"price\">{{ product.price | currency }}</p>\r\n```\r\nAngularJS gets the value of product.price. It sends this number into the currency filter. The pipe symbol (|) takes the output on the left and \"pipes\" it to the right. The filter outputs a formatted currency with the dollar sign and the correct decimal places.  \r\n\r\n**Date**\r\n```javascript\r\npubdate: new Date('2014', '03', '08')\r\n```\r\n```html\r\n<p class=\"date\">{{ product.pubdate | date | uppercase }}</p>\r\n```\r\n\r\n## Loop\r\n```javascript\r\n$scope.products = [ \r\n  { \r\n    name: 'The Book of Trees', \r\n    price: 19, \r\n    pubdate: new Date('2014', '03', '08'), \r\n    cover: 'img/the-book-of-trees.jpg' \r\n  }, \r\n  { \r\n    name: 'Program or be Programmed', \r\n    price: 8, \r\n    pubdate: new Date('2013', '08', '01'), \r\n    cover: 'img/program-or-be-programmed.jpg' \r\n  }\r\n]\r\n```\r\n```html\r\n<div ng-repeat=\"product in products\"> \r\n  <img ng-src=\"{{ product.cover }}\">\r\n  <p class=\"title\">{{ product.name }}</p> \r\n  <p class=\"price\">{{ product.price | currency }}</p> \r\n  <p class=\"date\">{{ product.pubdate | date }}</p> \r\n  <p class=\"likes\" ng-click=\"plusOne($index)\">{{ product.likes }}</p>\r\n</div>\r\n```\r\n\r\n## Html\r\n```html\r\n<!-- loops trough every product in products -->\r\n<div ng-repeat=\"product in products\"> \r\n  \r\n<!-- include the source -->\r\n<img ng-src=\"{{ product.cover }}\"> \r\n\r\n<!-- ng-click is a directive that adds an onclick event. plusOne is the name of the function. $index passes the product number (in a loop). {{ product.likes }} displays the value -->\r\n<p ng-click=\"plusOne($index)\">{{ product.likes }}</p>\r\n```\r\n\r\n## Directives\r\nin js/directives/appInfo.js\r\n```javascript\r\napp.directive('appInfo', function() { \r\n  return { \r\n    restrict: 'E', // specifies how directive will be used in view. 'E' means it will be used as a new HTML element.\r\n    scope: { \r\n      info: '=' // specifies that we will pass information into this directive through an attribute named info. The = tells the directive to look for an attribute named info in the <app-info> element, like this: <app-info info=\"shutterbugg\"></app-info>\r\n    },          // The data in info becomes available to use in the template given by templateURL\r\n    templateUrl: 'js/directives/appInfo.html', // specifies the HTML to use in order to display the data in scope.info. Here we use the HTML in js/directives/appInfo.html.\r\n    link: function(scope, element, attrs) { // scope refers to the directive's scope. Any new properties attached to $scope will become available to use in the directive's template. element refers to the directive's HTML element. attrs contains the element's attributes. \r\n            scope.buttonText = \"Install\", // property buttonText\r\n            scope.installed = false, // property installed\r\n\r\n            scope.download = function() { // function download() \r\n              element.toggleClass('btn-active'); \r\n              if(scope.installed) { \r\n                scope.buttonText = \"Install\"; \r\n                scope.installed = false; \r\n              } else { \r\n                scope.buttonText = \"Uninstall\"; \r\n                scope.installed = true; \r\n              } \r\n            } \r\n          }\r\n\r\n  }; \r\n});\r\n```\r\nin js/directives/appInfo.html\r\n```html\r\n<!-- define HTML to display details about app. Use expressions and filters to display data. -->\r\n<img ng-src=\"{{ info.icon }}\"> \r\n<h2>{{ info.title }}</h2> \r\n<p>{{ info.developer }}</p> \r\n<p>{{ info.price | currency }}</p>\r\n<!-- part of link: function -->\r\n<button ng-click=\"download()\"> \r\n  {{ buttonText }} \r\n</button>\r\n```\r\nin index.html\r\n```html\r\n<!-- pass in objects from the controller's scope ($scope.shutterbugg) into the <app-info> element's info attribute so that it displays. -->\r\n<app-info info=\"shutterbugg\"></app-info>\r\n```\r\n\r\n## Services\r\n**js > services > forecast.js**\r\n```javascript\r\napp.factory('forecast', ['$http', function($http) { // app.factory to create a new service named forecast + AngularJS's built-in $http to fetch JSON from the server\r\n  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json') // $http construct an HTTP GET request for the weather data (a json list from codecademy).\r\n            .success(function(data) { // If the request succeeds, the weather data is returned; \r\n              return data; \r\n            }) \r\n            .error(function(err) { // otherwise the error info is returned.\r\n              return err; \r\n            }); \r\n}]);\r\n```\r\n**js > controllers > MainController.js**\r\n```javascript\r\napp.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { // add forecast into MainController as dependency so that it's available to use.\r\n  forecast.success(function(data) { // to asynchronously fetch the weather data from server\r\n    $scope.fiveDay = data; // store it into $scope.fiveDay \r\n  }); \r\n}]);\r\n// any properties attached to $scope become available to use in the view\r\n```\r\n**index.html**\r\n```html\r\n<div class=\"main\" ng-controller=\"MainController\">\r\n  <h1>{{ fiveDay.city_name }}</h1>\r\n</div>\r\n```\r\n\r\n## Routing\r\n**app.config.js**\r\n```javascript\r\n// new\r\nangular.\r\n  module('phonecatApp').\r\n  config(['$locationProvider', '$routeProvider', // the services we use\r\n    function config($locationProvider, $routeProvider) {\r\n      $locationProvider.hashPrefix('!');\r\n\r\n      $routeProvider. // to define the application routes\r\n        when('/phones', { // to map the URL /phones to\r\n          template: '<phone-list></phone-list>'\r\n        }).\r\n        when('/phones/:phoneId', { // mapp URL to phones + variable part named id to the URL\r\n          template: '<phone-detail></phone-detail>'\r\n        }).\r\n        otherwise('/phones');\r\n    }\r\n  ]);\r\n```\r\n**phone-detail/phone-detail.module.js**\r\n```javascript\r\n// new\r\nangular.module('phoneDetail', [\r\n  'ngRoute'\r\n]);\r\n```\r\n**phone-detail/phone-detail.component.js**\r\n```javascript\r\n// new\r\nangular.\r\n  module('phoneDetail').\r\n  component('phoneDetail', {\r\n    template: 'TBD: Detail view for <span>{{$ctrl.phoneId}}</span>',\r\n    controller: ['$routeParams',\r\n      function PhoneDetailController($routeParams) {\r\n        this.phoneId = $routeParams.phoneId;\r\n      }\r\n    ]\r\n  });\r\n```\r\n**js > app.js**\r\n```javascript\r\n// old\r\napp.config(function ($routeProvider) { \r\n  $routeProvider \r\n    .when('/', { \r\n      controller: 'HomeController', // to the controller HomeController \r\n      templateUrl: 'views/home.html' // and the template home.html\r\n    })\r\n    .when('/photos/:id', { \r\n  \t\tcontroller: 'PhotoController',\r\n    \ttemplateUrl: 'views/photo.html'\r\n  \t})\r\n    .otherwise({ // Otherwise if a user accidentally visits a URL other than /\r\n      redirectTo: '/' // we just redirect to /\r\n    }); \r\n});\r\n```\r\n**js > controllers > HomeController**\r\n```javascript\r\n// old\r\napp.controller('HomeController', ['$scope', 'photos', function($scope, photos) { // use photos service\r\n  photos.success(function(data) {\r\n    $scope.photos = data;\r\n  });\r\n}]);\r\n```\r\n**js > controllers > PhotoController**\r\n```javascript\r\n// old\r\n// $routeParams to retrieve id from the URL by using $routeParams.id\r\n// Notice injected both $routeParams and the photos service into the dependency array to make them available to use inside the controller.\r\napp.controller('PhotoController', ['$scope', 'photos', '$routeParams', function($scope, photos, $routeParams) {\r\n  photos.success(function(data) { // photos service to fetch the array of photos from the server\r\n    $scope.detail = data[$routeParams.id]; // $routeParams.id to access the specific photo by its index\r\n  });\r\n}]);\r\n```\r\n**js > services > photos**\r\n```javascript\r\n// old\r\n// fetch the array of all photos and stores it into $scope.photos\r\napp.factory('photos', ['$http', function($http) {\r\n  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/photos-api/photos.json')\r\n         .success(function(data) {\r\n           return data;\r\n         })\r\n         .error(function(data) {\r\n           return data;\r\n         });\r\n}]);\r\n```\r\n**views > home.html**\r\n```html\r\n<div class=\"item col-md-4\" ng-repeat=\"photo in photos\">\r\n  <a href=\"#/photos/{{$index}}\">\r\n    <img class=\"img-responsive\" ng-src=\"{{ photo.url }}\">\r\n    <p class=\"author\">by {{ photo.author }}</p>\r\n  </a>\r\n</div>\r\n```\r\n**views > photo.html**\r\n```html\r\n<img ng-src=\"{{ detail.url }}\">\r\n```\r\n**index.html**\r\n```html\r\n<!-- ow when a user visits /, a view will be constructed by injecting home.html into the <div ng-view></div> -->\r\n<div ng-view></div>\r\n```\r\n\r\n## Filters\r\n```javascript\r\ndetail.upvotes | number // 1,266\r\ndetail.pubdate | date // Oct 18, 2014 \r\n\r\n```\r\n**Filter an Array**  \r\n```html\r\nSearch: <input type=\"text\" data-ng-model=\"$ctrl.query\">\r\nSearch by Name: <input type=\"text\" data-ng-model=\"$ctrl.query.name\"> <!-- save input in $ctrl.query -->\r\n<p>Total number of phones: {{$ctrl.phones.length}}</p>\r\n<ul class=\"phones\">\r\n  <li data-ng-repeat=\"phone in $ctrl.phones | filter:$ctrl.query\"> <!-- use $ctrl.query as filter to only show matching elements -->\r\n    <span>{{phone.name}}</span>\r\n    <p>{{phone.snippet}}</p>\r\n  </li>\r\n</ul>\r\n```\r\n```html\r\n<p>\r\n  Sort by:\r\n  <select ng-model=\"$ctrl.orderProp\"> <!-- save selection in $ctrl.orderProp -->\r\n    <option value=\"name\">Alphabetical</option> <!-- save selection in $ctrl.orderProp.name -->\r\n    <option value=\"age\">Newest</option> <!-- save selection in $ctrl.orderProp.age -->\r\n    <option value=\"-age\">Oldest</option> <!-- place - in front to reverse -->\r\n  </select>\r\n</p>\r\n<ul class=\"phones\">\r\n  <li data-ng-repeat=\"phone in $ctrl.phones | orderBy:$ctrl.orderProp\"> <!-- use $ctrl.orderProp as filter to order the list -->\r\n    <!-- if a value is not available it will return to the default -->\r\n    <span>{{phone.name}}</span>\r\n    <p>{{phone.snippet}}</p>\r\n  </li>\r\n</ul>\r\n```\r\n\r\n<h1 class=\"no-toc\">More Points</h1>\r\n\r\n<div id=\"cheatsheet\">\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Bootstrapping</th>\r\n<th><p><code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code><b>platformBrowserDynamic().bootstrapModule</b>(AppModule);</code></td>\r\n<td><p>Bootstraps the app, using the root component from the specified <code>NgModule</code>. </p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>NgModules</th>\r\n<th><p><code>import { NgModule } from '@angular/core';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code>@<b>NgModule</b>({ declarations: ..., imports: ...,<br>     exports: ..., providers: ..., bootstrap: ...})<br>class MyModule {}</code></td>\r\n<td><p>Defines a module that contains components, directives, pipes, and providers.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>declarations:</b> [MyRedComponent, MyBlueComponent, MyDatePipe]</code></td>\r\n<td><p>List of components, directives, and pipes that belong to this module.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>imports:</b> [BrowserModule, SomeOtherModule]</code></td>\r\n<td><p>List of modules to import into this module. Everything from the imported modules\r\nis available to <code>declarations</code> of this module.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>exports:</b> [MyRedComponent, MyDatePipe]</code></td>\r\n<td><p>List of components, directives, and pipes visible to modules that import this module.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>providers:</b> [MyService, { provide: ... }]</code></td>\r\n<td><p>List of dependency injection providers visible both to the contents of this module and to importers of this module.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>entryComponents:</b> [SomeComponent, OtherComponent]</code></td>\r\n<td><p>List of components not referenced in any reachable template, for example dynamically created from code.</p></td>\r\n</tr><tr>\r\n<td><code><b>bootstrap:</b> [MyAppComponent]</code></td>\r\n<td><p>List of components to bootstrap when this module is bootstrapped.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Template syntax</th>\r\n<th></th>\r\n</tr>\r\n<tr>\r\n<td><code>&lt;input <b>[value]</b>=\"firstName\"&gt;</code></td>\r\n<td><p>Binds property <code>value</code> to the result of expression <code>firstName</code>.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;div <b>[attr.role]</b>=\"myAriaRole\"&gt;</code></td>\r\n<td><p>Binds attribute <code>role</code> to the result of expression <code>myAriaRole</code>.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;div <b>[class.extra-sparkle]</b>=\"isDelightful\"&gt;</code></td>\r\n<td><p>Binds the presence of the CSS class <code>extra-sparkle</code> on the element to the truthiness of the expression <code>isDelightful</code>.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;div <b>[style.width.px]</b>=\"mySize\"&gt;</code></td>\r\n<td><p>Binds style property <code>width</code> to the result of expression <code>mySize</code> in pixels. Units are optional.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;button <b>(click)</b>=\"readRainbow($event)\"&gt;</code></td>\r\n<td><p>Calls method <code>readRainbow</code> when a click event is triggered on this button element (or its children) and passes in the event object.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;div title=\"Hello <b>{{ponyName}}</b>\"&gt;</code></td>\r\n<td><p>Binds a property to an interpolated string, for example, \"Hello Seabiscuit\". Equivalent to:\r\n<code>&lt;div [title]=\"'Hello ' + ponyName\"&gt;</code></p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;p&gt;Hello <b>{{ponyName}}</b>&lt;/p&gt;</code></td>\r\n<td><p>Binds text content to an interpolated string, for example, \"Hello Seabiscuit\".</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;my-cmp <b>[(title)]</b>=\"name\"&gt;</code></td>\r\n<td><p>Sets up two-way data binding. Equivalent to: <code>&lt;my-cmp [title]=\"name\" (titleChange)=\"name=$event\"&gt;</code></p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;video <b>#movieplayer</b> ...&gt;<br>  &lt;button <b>(click)</b>=\"movieplayer.play()\"&gt;<br>&lt;/video&gt;</code></td>\r\n<td><p>Creates a local variable <code>movieplayer</code> that provides access to the <code>video</code> element instance in data-binding and event-binding expressions in the current template.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;p <b>*myUnless</b>=\"myExpression\"&gt;...&lt;/p&gt;</code></td>\r\n<td><p>The <code>*</code> symbol turns the current element into an embedded template. Equivalent to:\r\n<code>&lt;ng-template [myUnless]=\"myExpression\"&gt;&lt;p&gt;...&lt;/p&gt;&lt;/ng-template&gt;</code></p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;p&gt;Card No.: <b>{{cardNumber | myCardNumberFormatter}}</b>&lt;/p&gt;</code></td>\r\n<td><p>Transforms the current value of expression <code>cardNumber</code> via the pipe called <code>myCardNumberFormatter</code>.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;p&gt;Employer: <b>{{employer?.companyName}}</b>&lt;/p&gt;</code></td>\r\n<td><p>The safe navigation operator (<code>?</code>) means that the <code>employer</code> field is optional and if <code>undefined</code>, the rest of the expression should be ignored.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;<b>svg:</b>rect x=\"0\" y=\"0\" width=\"100\" height=\"100\"/&gt;</code></td>\r\n<td><p>An SVG snippet template needs an <code>svg:</code> prefix on its root element to disambiguate the SVG element from an HTML component.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;<b>svg</b>&gt;<br>  &lt;rect x=\"0\" y=\"0\" width=\"100\" height=\"100\"/&gt;<br>&lt;/<b>svg</b>&gt;</code></td>\r\n<td><p>An <code>&lt;svg&gt;</code> root element is detected as an SVG element automatically, without the prefix.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Built-in directives</th>\r\n<th><p><code>import { CommonModule } from '@angular/common';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code>&lt;section <b>*ngIf</b>=\"showSection\"&gt;</code></td>\r\n<td><p>Removes or recreates a portion of the DOM tree based on the <code>showSection</code> expression.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;li <b>*ngFor</b>=\"let item of list\"&gt;</code></td>\r\n<td><p>Turns the li element and its contents into a template, and uses that to instantiate a view for each item in list.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;div <b>[ngSwitch]</b>=\"conditionExpression\"&gt;<br>  &lt;ng-template <b>[<b>ngSwitchCase</b>]</b>=\"case1Exp\"&gt;...&lt;/ng-template&gt;<br>  &lt;ng-template <b>ngSwitchCase</b>=\"case2LiteralString\"&gt;...&lt;/ng-template&gt;<br>  &lt;ng-template <b>ngSwitchDefault</b>&gt;...&lt;/ng-template&gt;<br>&lt;/div&gt;</code></td>\r\n<td><p>Conditionally swaps the contents of the div by selecting one of the embedded templates based on the current value of <code>conditionExpression</code>.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;div <b>[ngClass]</b>=\"{'active': isActive, 'disabled': isDisabled}\"&gt;</code></td>\r\n<td><p>Binds the presence of CSS classes on the element to the truthiness of the associated map values. The right-hand expression should return {class-name: true/false} map.</p>\r\n</td>\r\n</tr>\r\n<tr>\r\n<td><code>&lt;div <b>[ngStyle]</b>=\"{'property': 'value'}\"&gt;</code><br><code>&lt;div <b>[ngStyle]</b>=\"dynamicStyles()\"&gt;</code></td>\r\n<td><p>Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the first example, or you can call a method from the component.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Forms</th>\r\n<th><p><code>import { FormsModule } from '@angular/forms';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code>&lt;input <b>[(ngModel)]</b>=\"userName\"&gt;</code></td>\r\n<td><p>Provides two-way data-binding, parsing, and validation for form controls.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Class decorators</th>\r\n<th><p><code>import { Directive, ... } from '@angular/core';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code><b>@Component({...})</b><br>class MyComponent() {}</code></td>\r\n<td><p>Declares that a class is a component and provides metadata about the component.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@Directive({...})</b><br>class MyDirective() {}</code></td>\r\n<td><p>Declares that a class is a directive and provides metadata about the directive.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@Pipe({...})</b><br>class MyPipe() {}</code></td>\r\n<td><p>Declares that a class is a pipe and provides metadata about the pipe.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@Injectable()</b><br>class MyService() {}</code></td>\r\n<td><p>Declares that a class has dependencies that should be injected into the constructor when the dependency injector is creating an instance of this class.\r\n</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Directive configuration</th>\r\n<th><p><code>@Directive({ property1: value1, ... })</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code><b>selector:</b> '.cool-button:not(a)'</code></td>\r\n<td><p>Specifies a CSS selector that identifies this directive within a template. Supported selectors include <code>element</code>,\r\n<code>[attribute]</code>, <code>.class</code>, and <code>:not()</code>.</p>\r\n<p>Does not support parent-child relationship selectors.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>providers:</b> [MyService, { provide: ... }]</code></td>\r\n<td><p>List of dependency injection providers for this directive and its children.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Component configuration</th>\r\n<th><p>\r\n<code>@Component</code> extends <code>@Directive</code>,\r\nso the <code>@Directive</code> configuration applies to components as well</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code><b>moduleId:</b> module.id</code></td>\r\n<td><p>If set, the <code>templateUrl</code> and <code>styleUrl</code> are resolved relative to the component.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>viewProviders:</b> [MyService, { provide: ... }]</code></td>\r\n<td><p>List of dependency injection providers scoped to this component's view.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>template:</b> 'Hello {{name}}'<br><b>templateUrl:</b> 'my-component.html'</code></td>\r\n<td><p>Inline template or external template URL of the component's view.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>styles:</b> ['.primary {color: red}']<br><b>styleUrls:</b> ['my-component.css']</code></td>\r\n<td><p>List of inline CSS styles or external stylesheet URLs for styling the component’s view.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Class field decorators for directives and components</th>\r\n<th><p><code>import { Input, ... } from '@angular/core';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code><b>@Input()</b> myProperty;</code></td>\r\n<td><p>Declares an input property that you can update via property binding (example:\r\n<code>&lt;my-cmp [myProperty]=\"someExpression\"&gt;</code>).</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@Output()</b> myEvent = new EventEmitter();</code></td>\r\n<td><p>Declares an output property that fires events that you can subscribe to with an event binding (example: <code>&lt;my-cmp (myEvent)=\"doSomething()\"&gt;</code>).</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@HostBinding('class.valid')</b> isValid;</code></td>\r\n<td><p>Binds a host element property (here, the CSS class <code>valid</code>) to a directive/component property (<code>isValid</code>).</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@HostListener('click', ['$event'])</b> onClick(e) {...}</code></td>\r\n<td><p>Subscribes to a host element event (<code>click</code>) with a directive/component method (<code>onClick</code>), optionally passing an argument (<code>$event</code>).</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@ContentChild(myPredicate)</b> myChildComponent;</code></td>\r\n<td><p>Binds the first result of the component content query (<code>myPredicate</code>) to a property (<code>myChildComponent</code>) of the class.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@ContentChildren(myPredicate)</b> myChildComponents;</code></td>\r\n<td><p>Binds the results of the component content query (<code>myPredicate</code>) to a property (<code>myChildComponents</code>) of the class.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@ViewChild(myPredicate)</b> myChildComponent;</code></td>\r\n<td><p>Binds the first result of the component view query (<code>myPredicate</code>) to a property (<code>myChildComponent</code>) of the class. Not available for directives.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>@ViewChildren(myPredicate)</b> myChildComponents;</code></td>\r\n<td><p>Binds the results of the component view query (<code>myPredicate</code>) to a property (<code>myChildComponents</code>) of the class. Not available for directives.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Directive and component change detection and lifecycle hooks</th>\r\n<th><p>(implemented as class methods)\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code><b>constructor(myService: MyService, ...)</b> { ... }</code></td>\r\n<td><p>Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngOnChanges(changeRecord)</b> { ... }</code></td>\r\n<td><p>Called after every change to input properties and before processing content or child views.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngOnInit()</b> { ... }</code></td>\r\n<td><p>Called after the constructor, initializing input properties, and the first call to <code>ngOnChanges</code>.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngDoCheck()</b> { ... }</code></td>\r\n<td><p>Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngAfterContentInit()</b> { ... }</code></td>\r\n<td><p>Called after <code>ngOnInit</code> when the component's or directive's content has been initialized.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngAfterContentChecked()</b> { ... }</code></td>\r\n<td><p>Called after every check of the component's or directive's content.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngAfterViewInit()</b> { ... }</code></td>\r\n<td><p>Called after <code>ngAfterContentInit</code> when the component's views and child views / the view that a directive is in has been initialized.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngAfterViewChecked()</b> { ... }</code></td>\r\n<td><p>Called after every check of the component's views and child views / the view that a directive is in.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><b>ngOnDestroy()</b> { ... }</code></td>\r\n<td><p>Called once, before the instance is destroyed.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Dependency injection configuration</th>\r\n<th></th>\r\n</tr>\r\n<tr>\r\n<td><code>{ <b>provide</b>: MyService, <b>useClass</b>: MyMockService }</code></td>\r\n<td><p>Sets or overrides the provider for <code>MyService</code> to the <code>MyMockService</code> class.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>{ <b>provide</b>: MyService, <b>useFactory</b>: myFactory }</code></td>\r\n<td><p>Sets or overrides the provider for <code>MyService</code> to the <code>myFactory</code> factory function.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>{ <b>provide</b>: MyValue, <b>useValue</b>: 41 }</code></td>\r\n<td><p>Sets or overrides the provider for <code>MyValue</code> to the value <code>41</code>.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n\r\n<table class=\"is-full-width is-fixed-layout\">\r\n<tbody><tr>\r\n<th>Routing and navigation</th>\r\n<th><p><code>import { Routes, RouterModule, ... } from '@angular/router';</code>\r\n</p>\r\n</th>\r\n</tr>\r\n<tr>\r\n<td><code>const routes: <b>Routes</b> = [<br>  { path: '', component: HomeComponent },<br>  { path: 'path/:routeParam', component: MyComponent },<br>  { path: 'staticPath', component: ... },<br>  { path: '**', component: ... },<br>  { path: 'oldPath', redirectTo: '/staticPath' },<br>  { path: ..., component: ..., data: { message: 'Custom' } }<br>]);<br><br>const routing = RouterModule.forRoot(routes);</code></td>\r\n<td><p>Configures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and resolve.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><br>&lt;<b>router-outlet</b>&gt;&lt;/<b>router-outlet</b>&gt;<br>&lt;<b>router-outlet</b> name=\"aux\"&gt;&lt;/<b>router-outlet</b>&gt;<br></code></td>\r\n<td><p>Marks the location to load the component of the active route.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code><br>&lt;a routerLink=\"/path\"&gt;<br>&lt;a <b>[routerLink]</b>=\"[ '/path', routeParam ]\"&gt;<br>&lt;a <b>[routerLink]</b>=\"[ '/path', { matrixParam: 'value' } ]\"&gt;<br>&lt;a <b>[routerLink]</b>=\"[ '/path' ]\" [queryParams]=\"{ page: 1 }\"&gt;<br>&lt;a <b>[routerLink]</b>=\"[ '/path' ]\" fragment=\"anchor\"&gt;<br></code></td>\r\n<td><p>Creates a link to a different view based on a route instruction consisting of a route path, required and optional parameters, query parameters, and a fragment. To navigate to a root route, use the <code>/</code> prefix; for a child route, use the <code>./</code>prefix; for a sibling or parent, use the <code>../</code> prefix.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>&lt;a [routerLink]=\"[ '/path' ]\" routerLinkActive=\"active\"&gt;</code></td>\r\n<td><p>The provided classes are added to the element when the <code>routerLink</code> becomes the current active route.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>class <b>CanActivate</b>Guard implements <b>CanActivate</b> {<br>    canActivate(<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canActivate: [<b>CanActivate</b>Guard] }</code></td>\r\n<td><p>An interface for defining a class that the router should call first to determine if it should activate this component. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>class <b>CanDeactivate</b>Guard implements <b>CanDeactivate</b>&lt;T&gt; {<br>    canDeactivate(<br>      component: T,<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canDeactivate: [<b>CanDeactivate</b>Guard] }</code></td>\r\n<td><p>An interface for defining a class that the router should call first to determine if it should deactivate this component after a navigation. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>class <b>CanActivateChild</b>Guard implements <b>CanActivateChild</b> {<br>    canActivateChild(<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canActivateChild: [CanActivateGuard],<br>    children: ... }</code></td>\r\n<td><p>An interface for defining a class that the router should call first to determine if it should activate the child route. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>class <b>Resolve</b>Guard implements <b>Resolve</b>&lt;T&gt; {<br>    resolve(<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;any&gt;|Promise&lt;any&gt;|any { ... }<br>}<br><br>{ path: ..., resolve: [<b>Resolve</b>Guard] }</code></td>\r\n<td><p>An interface for defining a class that the router should call first to resolve route data before rendering the route. Should return a value or an Observable/Promise that resolves to a value.</p>\r\n</td>\r\n</tr><tr>\r\n<td><code>class <b>CanLoad</b>Guard implements <b>CanLoad</b> {<br>    canLoad(<br>      route: Route<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canLoad: [<b>CanLoad</b>Guard], loadChildren: ... }</code></td>\r\n<td><p>An interface for defining a class that the router should call first to check if the lazy loaded module should be loaded. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>\r\n</td>\r\n</tr>\r\n</tbody></table>\r\n</div>\r\n"
  },
  {
    "path": "C++/C++ Syntax.md",
    "content": "# C++ Syntax Cheat Sheet\r\n\r\n## Table of Contents\r\n\r\n<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:0 orderedList:0 -->\r\n\r\n- [C++ Syntax Cheat Sheet](#c-syntax-cheat-sheet)\r\n\t- [Table of Contents](#table-of-contents)\r\n\t- [1.0 C++ Classes](#10-c-classes)\r\n\t\t- [1.1 Class Syntax](#11-class-syntax)\r\n\t\t\t- [1.1.1 Class Declaration (`.h` file)](#111-class-declaration-h-file)\r\n\t\t\t- [1.1.2 Class Definition (`.cpp` file)](#112-class-definition-cpp-file)\r\n\t\t\t- [1.1.3 Class Utilization (Another `.cpp` file)](#113-class-utilization-another-cpp-file)\r\n\t\t\t- [1.1.4 Getters and Setters](#114-getters-and-setters)\r\n\t\t- [1.2 Inheritance](#12-inheritance)\r\n\t\t\t- [1.2.1 `Rectangle` Declaration (`.h` file)](#121-rectangle-declaration-h-file)\r\n\t\t\t- [1.2.2 `Rectangle` Definition (`.cpp` file)](#122-rectangle-definition-cpp-file)\r\n\t\t\t- [1.2.3 `Rectangle` Utilization (Another `.cpp` file)](#123-rectangle-utilization-another-cpp-file)\r\n\t\t- [1.3 Polymorphism](#13-polymorphism)\r\n\t\t- [1.4 Templates](#14-templates)\r\n\t\t- [1.5 Constructor/Destructor/Copy Constructor](#15-constructordestructorcopy-constructor)\r\n\t\t\t- [1.5.1 Use of `explicit` in Constructors](#151-use-of-explicit-in-constructors)\r\n\t\t- [1.6 Initialization Lists](#16-initialization-lists)\r\n\t\t- [1.7 Operator Overloading](#17-operator-overloading)\r\n\t- [2.0 General C++ Syntax](#20-general-c-syntax)\r\n\t\t- [2.1 Namespaces](#21-namespaces)\r\n\t\t- [2.2 References/Pointers](#22-referencespointers)\r\n\t\t- [2.3 Keywords](#23-keywords)\r\n\t\t\t- [2.3.1 `const`](#231-const)\r\n\t\t\t- [2.3.2 `volatile`](#232-volatile)\r\n\t\t\t- [2.3.3 `inline`](#233-inline)\r\n\t\t- [2.4 Strings (find, erase, etc)](#24-strings-find-erase-etc)\r\n\t\t- [2.5 Iterators](#25-iterators)\r\n\t\t- [2.6 Exceptions](#26-exceptions)\r\n\r\n<!-- /TOC -->\r\n\r\n\r\n## 1.0 C++ Classes\r\n### 1.1 Class Syntax\r\n#### 1.1.1 Class Declaration (`.h` file)\r\nHere's a simple class representing a polygon, a shape with any number of sides.\r\n\r\nThe class *declaration* typically goes in the `.h` file. The *declaration* gives the class name, any classes it may extend, declares the members and methods, and declares which members/methods are public, private, or protected.\r\n```c++\r\nclass Polygon {\r\n\r\n// Private members and methods are only accessible via methods in the class definition\r\n// Another option is 'protected', which are members and methods only accessible in the class definition or by classes who extend this class\r\nprivate:\r\n    int num_sides;    \t// Number of sides\r\n    std::string name    // Name of the polygon\r\n\r\n// Public members and methods are accessible to anyone who creates an instance of the class\r\npublic:\r\n    // Constructors\r\n    Polygon(const int num_sides, const std::string &name);  // <--- This constructor takes the number of sides and name as arguments\r\n\r\n    // Getters and Setters\r\n    const int GetNumSides(void) const;\r\n    void SetNumSides(const int num_sides);\r\n\r\n    const std::string & GetName(void) const;\r\n    void SetName(const std::string &name);\r\n    \r\n}; // <--- Don't forget the semicolon!\r\n```\r\n\r\n#### 1.1.2 Class Definition (`.cpp` file)\r\n```c++\r\n#include \"Polygon.h\"    // <--- Obtains the class declaration\r\n\r\n// Constructor\r\n// You must scope the method definitions with the class name (Polygon::)\r\nPolygon::Polygon(const int num_sides, const std::string &name) {\r\n    this->num_sides = num_sides;\t// 'this' refers to the instance of the class. Members are accessed via pointers\r\n    this->name = name;\r\n}\r\n\r\n// Get the number of sides\r\nconst int Polygon::GetNumSides(void) const {\r\n    return this->num_sides;\r\n}\r\n\r\n// Set the number of sides\r\nvoid Polygon::SetNumSides(const int num_sides) {\r\n    this->num_sides = num_sides;\r\n}\r\n\r\n// Get the polygon name\r\nconst std::string & Polygon::GetName(void) const {\r\n    return this->name;\r\n}\r\n\r\n// Set the polygon name\r\nvoid Polygon::SetName(const std::string &name) {\r\n    this->name = name;\r\n}\r\n```\r\n\r\n#### 1.1.3 Class Utilization (Another `.cpp` file)\r\n```c++\r\n#include <string>\r\n#include \"Polygon.h\"    // <--- Obtains the class declaration\r\n\r\nint main(int argc, char *argv[]) {\r\n    // Create a polygon with 4 sides and the name \"Rectangle\"\r\n    Polygon polygon = Polygon(4, \"Rectangle\");\r\n\r\n    // Check number of sides -- Prints \"Rectangle has 4 sides\"\r\n    std::cout << polygon.GetName() << \" has \" << polygon.GetNumSides() << \" sides\"<< std::endl;\r\n\r\n    // Change number of sides to 3 and name to \"Triangle\"\r\n    polygon.SetNumSides(3);\r\n    polygon.SetName(\"Triangle\");\r\n}\r\n```\r\n\r\n#### 1.1.4 Getters and Setters\r\nA shortcut often used for Getters/Setters is to define them in the class declaration (`.h`) file as follows:\r\n```c++\r\nclass Car {\r\nprivate:\r\n\tint year;\r\n\tstd::string make;\r\n\r\npublic:\r\n\tconst int GetYear(void) const { return this->year; }\r\n\tvoid SetYear(const int year) { this->year = year; }\r\n\tconst std::string & GetMake(void) const { return this->make; }\r\n\tvoid SetMake(const std::string &make) { this->make = make; }\r\n};\r\n```\r\n\r\nAnother important consideration: If you have getters and setters for all of your members, you may want to reconsider the design of your class. It is more often than not that having getters and setters for every member is indicative of poor planning of the class design and interface. Getters are very common, but setters should be used more carefully. Should you have set the variable in the constructor? Is it set somewhere else in another method, perhaps even indirectly?\r\n\r\n### 1.2 Inheritance\r\nA class can extend another class, meaning that the new class inherits all of the data from the other class, and can also override its methods, add new members, etc. Inheritance is the key feature required for polymorphism.\r\n\r\n**Example:** the class `Rectangle` can inherit the class `Polygon`. You would then say that `Rectangle` extends `Polygon`, or that class `Rectangle` is a sub-class of `Polygon`. In plain English, this means that a `Rectangle` is a more specialized version of a `Polygon`.\r\n\r\n#### 1.2.1 `Rectangle` Declaration (`.h` file)\r\n```c++\r\n#include \"Polygon.h\"\t// <--- You must include the declaration in order to extend the class\r\n\r\nclass Rectangle: public Polygon {\r\nprivate:\t\t\t// <--- The members 'num_sides' and 'name' are already inherited from Polygon\r\n\tint length;\r\n\tint width;\r\n\r\npublic:\r\n\t// Constructors\r\n\tRectangle(const std::string &name);\r\n\tRectangle(const std::string &name, const int length, const int width);\r\n\r\n\t// Getters and Setters\t<--- The methods 'GetNumSides()', 'SetNumSides()', 'GetName()' and 'SetName()' are already inherited from Polygon\r\n\tconst int GetLength(void) const { return this->length; }\r\n\tvoid SetLength(const int) { this->length = length; }\r\n\r\n\tconst int GetWidth(void) const { return this->width; }\r\n\tvoid SetWidth(const int) { this->width = width; }\r\n\r\n\t// Other Methods\r\n\tconst int Area(void) const;\r\n};\r\n```\r\n\r\n#### 1.2.2 `Rectangle` Definition (`.cpp` file)\r\n```c++\r\n#include \"Rectangle.h\"\t// <--- Only need to include 'Rectangle', since 'Polygon' is included in 'Rectangle.h'\r\n\r\n// This constructor calls the superclass (Polygon) constructor and sets the name and number of sides to '4', and then sets the length and width\r\nRectangle::Rectangle(const std::string &name, const int length, const int width) : Polygon(4, name) {\r\n\tthis->length = length;\r\n\tthis->width = width;\r\n}\r\n\r\n// This constructor calls the superclass (Polygon) constructor, but sets the length and width to a constant value\r\nRectangle::Rectangle(const std::string &name) : Polygon(4, name) {\r\n\tthis->length = 1;\r\n\tthis->width = 1;\r\n}\r\n\r\n// Compute the area of the rectangle\r\nRectangle::Area(void) const {\r\n\treturn this->length * this->width;\r\n}\r\n```\r\n\r\n#### 1.2.3 `Rectangle` Utilization (Another `.cpp` file)\r\n```c++\r\n#include \"Rectangle.h\"\r\n\r\nint main(int argc, char *argv[]) {\r\n\tRectangle rectangle = Rectangle(\"Square\", 6, 6);\r\n\r\n\t// Prints \"Square has 4 sides, and an area of 36\"\r\n\tstd::cout << rectangle.GetName() << \" has \" << rectangle.GetNumSides() << \" sides, and an area of \" << rectangle.Area() << std::endl;\r\n}\r\n```\r\n\r\n### 1.3 Polymorphism\r\n\r\n### 1.4 Constructor/Destructor/Copy Constructor\r\n#### 1.4.1 Use of `explicit` in Constructors\r\nThe keyword `explicit` should be used in single-argument constructors to avoid the following situation. Consider the class `Array`:\r\n```c++\r\nclass Array {\r\npublic:\r\n\tArray(int size) {\r\n\t\tthis->size = size;\r\n\t}\r\n\r\nprivate:\r\n\tint size;\r\n};\r\n```\r\n\r\nThe following is now legal but ambiguous:\r\n```c++\r\nArray array = 12345;\r\n```\r\n\r\nIt ends up being the equivalent of this:\r\n```c++\r\nArray array = Array(12345);\r\n```\r\n\r\nThat's fine, one would suppose, but what about the following:\r\n```c++\r\n// Method PrintArray is defined as: Array::Print(const Array &array)\r\narray.Print(12345);\r\n```\r\n\r\nUh-oh. That's now legal, compilable code, but what does it mean? It is extremely unclear to the user.\r\n\r\nTo fix this, declare the single-argument `Array` constructor as `explicit`:\r\n```c++\r\nclass Array {\r\npublic:\r\n\texplicit Array(int size) {\r\n\t\tthis->size = size;\r\n\t}\r\n};\r\n```\r\n\r\nNow you can only use the print method as follows:\r\n```c++\r\narray.Print(Array(12345));\r\n```\r\n\r\n### 1.4 Initialization Lists\r\n\r\n### 1.5 Operator Overloading\r\n[Reference](http://en.cppreference.com/w/cpp/language/operators)\r\n\r\n### 1.6 Templates\r\n[Reference](http://en.cppreference.com/w/cpp/language/templates)\r\n\r\n## 2.0 General C++ Syntax\r\n### 2.1 Namespaces\r\n\r\n### 2.2 References and Pointers\r\n\r\n### 2.3 Keywords\r\n[Reference](http://en.cppreference.com/w/cpp/keyword)\r\n\r\n#### 2.3.1 General Keywords\r\n[`asm`](http://en.cppreference.com/w/cpp/language/asm)\r\n[`auto`](http://en.cppreference.com/w/cpp/language/auto)\r\n[`cont`](http://en.cppreference.com/w/cpp/language/cv)\r\n[`constexpr` (*since C++11*)](http://en.cppreference.com/w/cpp/language/constexpr)\r\n[`explicit`](http://en.cppreference.com/w/cpp/language/explicit)\r\n[`export` (*until C++11*)](http://en.cppreference.com/w/cpp/keyword/export)\r\n[`extern` (*language linkage*)](http://en.cppreference.com/w/cpp/language/language_linkage)\r\n[`friend`](http://en.cppreference.com/w/cpp/language/friend)\r\n[`inline`](http://en.cppreference.com/w/cpp/language/inline)\r\n[`mutable`](http://en.cppreference.com/w/cpp/language/cv)\r\n[`noexcept` (*operator*)](http://en.cppreference.com/w/cpp/language/noexcept)\r\n[`noexcept` (*function specifier*)](http://en.cppreference.com/w/cpp/language/noexcept_spec)\r\n[`nullptr`](http://en.cppreference.com/w/cpp/language/nullptr)\r\n[`override`](http://en.cppreference.com/w/cpp/language/override)\r\n[`static` (*class member specifier*)](http://en.cppreference.com/w/cpp/language/static)\r\n[`template`](http://en.cppreference.com/w/cpp/language/templates)\r\n[`this`](http://en.cppreference.com/w/cpp/language/this)\r\n[`virtual` (*function specifier*)](http://en.cppreference.com/w/cpp/language/virtual)\r\n[`virtual` (*base class specifier*)](http://en.cppreference.com/w/cpp/language/derived_class)\r\n[`volatile`](http://en.cppreference.com/w/cpp/language/cv)\r\n\r\n#### 2.3.2 Storage Class Specifiers\r\n[Reference](http://en.cppreference.com/w/cpp/language/storage_duration)\r\n* `auto` (*until C++11*)\r\n* `register` (*until C++17*)\r\n* `static`\r\n* `extern`\r\n* `thread_local` (*since C++11*)\r\n\r\n#### 2.3.3 `const` and `dynamic` Cast Conversion\r\n* [`const_cast`](http://en.cppreference.com/w/cpp/language/const_cast)\r\n* [`dynamic_cast`](http://en.cppreference.com/w/cpp/language/dynamic_cast)\r\n\r\n### 2.4 Preprocessor Tokens\r\n* `#if`: Preprocessor version of `if(...)`\r\n* `#elif`: Preprocessor version of `else if(...)`\r\n* `#else`: Preprocessor version of `else`\r\n* `#endif`: Used to end an `#if`, `#ifdef`, or `#ifndef`\r\n* `defined()`: Returns true if the macro is defined\r\n* `#ifdef`: Same as `#if defined(...)`\r\n* `#ifndef`: Same as `#if !defined(...)`\r\n* `#define`: Defines a text macro. See [here](http://en.cppreference.com/w/cpp/preprocessor/replace) for full explanation, including macro functions and predefined macros.\r\n* `#undef`: Un-defines a text macro\r\n* `#include`: Includes a source file\r\n* `#line`: Changes the current file name and line number in the preprocessor\r\n* `#error`: Prints an error message and stops compilation\r\n* `#pragma`: Non-standard, used instead of header guards (`#ifndef HEADER_H` ...)\r\n\r\n### 2.4 Strings (`std::string`)\r\n[Reference](http://en.cppreference.com/w/cpp/string/basic_string)\r\n\r\n### 2.5 Iterators (`std::iterator<...>`)\r\n[Reference](http://en.cppreference.com/w/cpp/concept/Iterator)\r\n\r\n### 2.6 Exceptions (`std::exception`)\r\n[Reference](http://en.cppreference.com/w/cpp/error/exception)\r\n"
  },
  {
    "path": "C++/Data Structures and Algorithms.md",
    "content": "# C++ Data Structures and Algorithms Cheat Sheet\r\n\r\n## Table of Contents\r\n\r\n<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 -->\r\n\r\n- [C++ Data Structures and Algorithms Cheat Sheet](#c-data-structures-and-algorithms-cheat-sheet)\r\n\t- [Table of Contents](#table-of-contents)\r\n\t- [1.0 Data Structures](#10-data-structures)\r\n\t\t- [1.1 Overview](#11-overview)\r\n\t\t- [1.2 Vector `std::vector`](#12-vector-stdvector)\r\n\t\t- [1.3 Deque `std::deque`](#13-deque-stddeque)\r\n\t\t- [1.4 List `std::list` and `std::forward_list`](#14-list-stdlist-and-stdforward_list)\r\n\t\t- [1.5 Map `std::map` and `std::unordered_map`](#15-map-stdmap-and-stdunordered_map)\r\n\t\t- [1.6 Set `std::set`](#16-set-stdset)\r\n\t\t- [1.7 Stack `std::stack`](#17-stack-stdstack)\r\n\t\t- [1.8 Queue `std::queue`](#18-queue-stdqueue)\r\n\t\t- [1.9 Priority Queue `std::priority_queue`](#19-priority-queue-stdpriority_queue)\r\n\t\t- [1.10 Heap `std::priority_queue`](#110-heap-stdpriority_queue)\r\n\t- [2.0 Trees](#20-trees)\r\n\t\t- [2.1 Binary Tree](#21-binary-tree)\r\n\t\t- [2.2 Balanced Trees](#22-balanced-trees)\r\n\t\t- [2.3 Binary Search](#23-binary-search)\r\n\t\t- [2.4 Depth-First Search](#24-depth-first-search)\r\n\t\t- [2.5 Breadth-First Search](#25-breadth-first-search)\r\n\t- [3.0 NP Complete Problems](#30-np-complete-problems)\r\n\t\t- [3.1 NP Complete](#31-np-complete)\r\n\t\t- [3.2 Traveling Salesman Problem](#32-traveling-salesman-problem)\r\n\t\t- [3.3 Knapsack Problem](#33-knapsack-problem)\r\n\t- [4.0 Algorithms](#40-algorithms)\r\n\t\t- [4.1 Insertion Sort](#41-insertion-sort)\r\n\t\t- [4.2 Selection Sort](#42-selection-sort)\r\n\t\t- [4.3 Bubble Sort](#43-bubble-sort)\r\n\t\t- [4.4 Merge Sort](#44-merge-sort)\r\n\t\t- [4.5 Quicksort](#45-quicksort)\r\n\r\n<!-- /TOC -->\r\n\r\n\r\n## 1.0 Data Structures\r\n### 1.1 Overview\r\n\r\n![Legend](General/Legend.png)\r\n\r\n![DataStructures](General/Data%20Structures.png \"Data Structures\")\r\n\r\n![ComplexityChart](General/Complexity%20Chart.png \"Complexity Chart\")\r\n\r\n![DataStructureSelection](General/Data%20Structures%20Selection.png \"Data Structures Selection\")\r\n-------------------------------------------------------\r\n### 1.2 Vector `std::vector`\r\n**Use for**\r\n* Simple storage\r\n* Adding but not deleting\r\n* Serialization\r\n* Quick lookups by index\r\n* Easy conversion to C-style arrays\r\n* Efficient traversal (contiguous CPU caching)\r\n\r\n**Do not use for**\r\n* Insertion/deletion in the middle of the list\r\n* Dynamically changing storage\r\n* Non-integer indexing\r\n\r\n**Time Complexity**\r\n\r\n| Operation    | Time Complexity |\r\n|--------------|-----------------|\r\n| Insert Head  |          `O(n)` |\r\n| Insert Index |          `O(n)` |\r\n| Insert Tail  |          `O(1)` |\r\n| Remove Head  |          `O(n)` |\r\n| Remove Index |          `O(n)` |\r\n| Remove Tail  |          `O(1)` |\r\n| Find Index   |          `O(1)` |\r\n| Find Object  |          `O(n)` |\r\n\r\n**Example Code**\r\n```c++\r\nstd::vector<int> v;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert head, index, tail\r\nv.insert(v.begin(), value);             // head\r\nv.insert(v.begin() + index, value);     // index\r\nv.push_back(value);                     // tail\r\n\r\n// Access head, index, tail\r\nint head = v.front();       // head\r\nint value = v.at(index);    // index\r\nint tail = v.back();        // tail\r\n\r\n// Size\r\nunsigned int size = v.size();\r\n\r\n// Iterate\r\nfor(std::vector<int>::iterator it = v.begin(); it != v.end(); it++) {\r\n    std::cout << *it << std::endl;\r\n}\r\n\r\n// Remove head, index, tail\r\nv.erase(v.begin());             // head\r\nv.erase(v.begin() + index);     // index\r\nv.pop_back();                   // tail\r\n\r\n// Clear\r\nv.clear();\r\n```\r\n-------------------------------------------------------\r\n### 1.3 Deque `std::deque`\r\n**Use for**\r\n* Similar purpose of `std::vector`\r\n* Basically `std::vector` with efficient `push_front` and `pop_front`\r\n\r\n**Do not use for**\r\n* C-style contiguous storage (not guaranteed)\r\n\r\n**Notes**\r\n* Pronounced 'deck'\r\n* Stands for **D**ouble **E**nded **Que**ue\r\n\r\n**Example Code**\r\n```c++\r\nstd::deque<int> d;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert head, index, tail\r\nd.push_front(value);                    // head\r\nd.insert(d.begin() + index, value);     // index\r\nd.push_back(value);                     // tail\r\n\r\n// Access head, index, tail\r\nint head = d.front();       // head\r\nint value = d.at(index);    // index\r\nint tail = d.back();        // tail\r\n\r\n// Size\r\nunsigned int size = d.size();\r\n\r\n// Iterate\r\nfor(std::vector<int>::iterator it = d.begin(); it != d.end(); it++) {\r\n    std::cout << *it << std::endl;\r\n}\r\n\r\n// Remove head, index, tail\r\nd.pop_front();                  // head\r\nd.erase(d.begin() + index);     // index\r\nd.pop_back();                   // tail\r\n\r\n// Clear\r\nd.clear();\r\n```\r\n-------------------------------------------------------\r\n### 1.4 List `std::list` and `std::forward_list`\r\n**Use for**\r\n* Insertion into the middle/beginning of the list\r\n* Efficient sorting (pointer swap vs. copying)\r\n\r\n**Do not use for**\r\n* Direct access\r\n\r\n**Time Complexity**\r\n\r\n| Operation    | Time Complexity |\r\n|--------------|-----------------|\r\n| Insert Head  |          `O(1)` |\r\n| Insert Index |          `O(n)` |\r\n| Insert Tail  |          `O(1)` |\r\n| Remove Head  |          `O(1)` |\r\n| Remove Index |          `O(n)` |\r\n| Remove Tail  |          `O(1)` |\r\n| Find Index   |          `O(n)` |\r\n| Find Object  |          `O(n)` |\r\n\r\n**Example Code**\r\n```c++\r\nstd::list<int> l;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert head, index, tail\r\nl.push_front(value);                    // head\r\nl.insert(l.begin() + index, value);     // index\r\nl.push_back(value);                     // tail\r\n\r\n// Access head, index, tail\r\nint head = l.front();                                           // head\r\nint value = std::list<int>::iterator it = l.begin() + index;    // index\r\nint tail = l.back();                                            // tail\r\n\r\n// Size\r\nunsigned int size = l.size();\r\n\r\n// Iterate\r\nfor(std::list<int>::iterator it = l.begin(); it != l.end(); it++) {\r\n    std::cout << *it << std::endl;\r\n}\r\n\r\n// Remove head, index, tail\r\nl.pop_front();                  // head\r\nl.erase(l.begin() + index);     // index\r\nl.pop_back();                   // tail\r\n\r\n// Clear\r\nl.clear();\r\n\r\n//---------------------------------\r\n// Container-Specific Operations\r\n//---------------------------------\r\n\r\n// Splice: Transfer elements from list to list\r\n//\tsplice(iterator pos, list &x)\r\n//  \tsplice(iterator pos, list &x, iterator i)\r\n//  \tsplice(iterator pos, list &x, iterator first, iterator last)\r\nl.splice(l.begin() + index, list2);\r\n\r\n// Remove: Remove an element by value\r\nl.remove(value);\r\n\r\n// Unique: Remove duplicates\r\nl.unique();\r\n\r\n// Merge: Merge two sorted lists\r\nl.merge(list2);\r\n\r\n// Sort: Sort the list\r\nl.sort();\r\n\r\n// Reverse: Reverse the list order\r\nl.reverse();\r\n```\r\n-------------------------------------------------------\r\n### 1.5 Map `std::map` and `std::unordered_map`\r\n**Use for**\r\n* Key-value pairs\r\n* Constant lookups by key\r\n* Searching if key/value exists\r\n* Removing duplicates\r\n* `std::map`\r\n    * Ordered map\r\n* `std::unordered_map`\r\n    * Hash table\r\n\r\n**Do not use for**\r\n* Sorting\r\n\r\n**Notes**\r\n* Typically ordered maps (`std::map`) are slower than unordered maps (`std::unordered_map`)\r\n* Maps are typically implemented as *binary search trees*\r\n\r\n**Time Complexity**\r\n\r\n**`std::map`**\r\n\r\n| Operation           | Time Complexity |\r\n|---------------------|-----------------|\r\n| Insert              |     `O(log(n))` |\r\n| Access by Key       |     `O(log(n))` |\r\n| Remove by Key       |     `O(log(n))` |\r\n| Find/Remove Value   |     `O(log(n))` |\r\n\r\n**`std::unordered_map`**\r\n\r\n| Operation           | Time Complexity |\r\n|---------------------|-----------------|\r\n| Insert              |          `O(1)` |\r\n| Access by Key       |          `O(1)` |\r\n| Remove by Key       |          `O(1)` |\r\n| Find/Remove Value   |              -- |\r\n\r\n**Example Code**\r\n```c++\r\nstd::map<std::string, std::string> m;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert\r\nm.insert(std::pair<std::string, std::string>(\"key\", \"value\"));\r\n\r\n// Access by key\r\nstd::string value = m.at(\"key\");\r\n\r\n// Size\r\nunsigned int size = m.size();\r\n\r\n// Iterate\r\nfor(std::map<int>::iterator it = m.begin(); it != m.end(); it++) {\r\n    std::cout << *it << std::endl;\r\n}\r\n\r\n// Remove by key\r\nm.erase(\"key\");\r\n\r\n// Clear\r\nm.clear();\r\n\r\n//---------------------------------\r\n// Container-Specific Operations\r\n//---------------------------------\r\n\r\n// Find if an element exists by key\r\nbool exists = (m.find(\"key\") != m.end());\r\n\r\n// Count the number of elements with a certain key\r\nunsigned int count = m.count(\"key\");\r\n```\r\n-------------------------------------------------------\r\n### 1.6 Set `std::set`\r\n**Use for**\r\n* Removing duplicates\r\n* Ordered dynamic storage\r\n\r\n**Do not use for**\r\n* Simple storage\r\n* Direct access by index\r\n\r\n**Notes**\r\n* Sets are often implemented with binary search trees\r\n\r\n**Time Complexity**\r\n\r\n| Operation    | Time Complexity |\r\n|--------------|-----------------|\r\n| Insert       |     `O(log(n))` |\r\n| Remove       |     `O(log(n))` |\r\n| Find         |     `O(log(n))` |\r\n\r\n**Example Code**\r\n```c++\r\nstd::set<int> s;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert\r\ns.insert(20);\r\n\r\n// Size\r\nunsigned int size = s.size();\r\n\r\n// Iterate\r\nfor(std::set<int>::iterator it = s.begin(); it != s.end(); it++) {\r\n    std::cout << *it << std::endl;\r\n}\r\n\r\n// Remove\r\ns.erase(20);\r\n\r\n// Clear\r\ns.clear();\r\n\r\n//---------------------------------\r\n// Container-Specific Operations\r\n//---------------------------------\r\n\r\n// Find if an element exists\r\nbool exists = (s.find(20) != s.end());\r\n\r\n// Count the number of elements with a certain value\r\nunsigned int count = s.count(20);\r\n```\r\n-------------------------------------------------------\r\n### 1.7 Stack `std::stack`\r\n**Use for**\r\n* First-In Last-Out operations\r\n* Reversal of elements\r\n\r\n**Time Complexity**\r\n\r\n| Operation    | Time Complexity |\r\n|--------------|-----------------|\r\n| Push         |          `O(1)` |\r\n| Pop          |          `O(1)` |\r\n| Top          |          `O(1)` |\r\n\r\n**Example Code**\r\n```c++\r\nstd::stack<int> s;\r\n\r\n//---------------------------------\r\n// Container-Specific Operations\r\n//---------------------------------\r\n\r\n// Push\r\ns.push(20);\r\n\r\n// Size\r\nunsigned int size = s.size();\r\n\r\n// Pop\r\ns.pop();\r\n\r\n// Top\r\nint top = s.top();\r\n```\r\n-------------------------------------------------------\r\n### 1.8 Queue `std::queue`\r\n**Use for**\r\n* First-In First-Out operations\r\n* Ex: Simple online ordering system (first come first served)\r\n* Ex: Semaphore queue handling\r\n* Ex: CPU scheduling (FCFS)\r\n\r\n**Notes**\r\n* Often implemented as a `std::deque`\r\n\r\n**Example Code**\r\n```c++\r\nstd::queue<int> q;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert\r\nq.push(value);\r\n\r\n// Access head, tail\r\nint head = q.front();       // head\r\nint tail = q.back();        // tail\r\n\r\n// Size\r\nunsigned int size = q.size();\r\n\r\n// Remove\r\nq.pop();\r\n```\r\n-------------------------------------------------------\r\n### 1.9 Priority Queue `std::priority_queue`\r\n**Use for**\r\n* First-In First-Out operations where **priority** overrides arrival time\r\n* Ex: CPU scheduling (smallest job first, system/user priority)\r\n* Ex: Medical emergencies (gunshot wound vs. broken arm)\r\n\r\n**Notes**\r\n* Often implemented as a `std::vector`\r\n\r\n**Example Code**\r\n```c++\r\nstd::priority_queue<int> p;\r\n\r\n//---------------------------------\r\n// General Operations\r\n//---------------------------------\r\n\r\n// Insert\r\np.push(value);\r\n\r\n// Access\r\nint top = p.top();  // 'Top' element\r\n\r\n// Size\r\nunsigned int size = p.size();\r\n\r\n// Remove\r\np.pop();\r\n```\r\n-------------------------------------------------------\r\n### 1.10 Heap `std::priority_queue`\r\n**Notes**\r\n* A heap is essentially an instance of a priority queue\r\n* A **min** heap is structured with the root node as the smallest and each child subsequently smaller than its parent\r\n* A **max** heap is structured with the root node as the largest and each child subsequently larger than its parent\r\n* A min heap could be used for *Smallest Job First* CPU Scheduling\r\n* A max heap could be used for *Priority* CPU Scheduling\r\n\r\n**Max Heap Example (using a binary tree)**\r\n\r\n![MaxHeap](General/MaxHeap.png)\r\n-------------------------------------------------------\r\n## 2.0 Trees\r\n### 2.1 Binary Tree\r\n* A binary tree is a tree with at most two (2) child nodes per parent\r\n* Binary trees are commonly used for implementing `O(log(n))` operations for ordered maps, sets, heaps, and binary search trees\r\n* Binary trees are **sorted** in that nodes with values greater than their parents are inserted to the **right**, while nodes with values less than their parents are inserted to the **left**\r\n\r\n**Binary Search Tree**\r\n\r\n![BinarySearchTree](General/BinarySearchTree.png)\r\n-------------------------------------------------------\r\n### 2.2 Balanced Trees\r\n* Balanced trees are a special type of tree which maintains its balance to ensure `O(log(n))` operations\r\n* When trees are not balanced the benefit of `log(n)` operations is lost due to the highly vertical structure\r\n* Examples of balanced trees:\r\n    * AVL Trees\r\n    * Red-Black Trees\r\n\r\n-------------------------------------------------------\r\n### 2.3 Binary Search\r\n**Idea:**\r\n1. If current element, return\r\n2. If less than current element, look left\r\n3. If more than current element, look right\r\n4. Repeat\r\n\r\n**Data Structures:**\r\n* Tree\r\n* Sorted array\r\n\r\n**Space:**\r\n* `O(1)`\r\n\r\n**Best Case:**\r\n* `O(1)`\r\n\r\n**Worst Case:**\r\n* `O(log n)`\r\n\r\n**Average:**\r\n* `O(log n)`\r\n\r\n**Visualization:**\r\n\r\n![BinarySearch](Searching/Animations/Binary%20Search.gif \"Binary Search\")\r\n-------------------------------------------------------\r\n### 2.4 Depth-First Search\r\n**Idea:**\r\n1. Start at root node\r\n2. Recursively search all adjacent nodes and mark them as searched\r\n3. Repeat\r\n\r\n**Data Structures:**\r\n* Tree\r\n* Graph\r\n\r\n**Space:**\r\n* `O(V)`, `V = number of verticies`\r\n\r\n**Performance:**\r\n* `O(E)`, `E = number of edges`\r\n\r\n**Visualization:**\r\n\r\n![DepthFirstSearch](Searching/Animations/Depth-First%20Search.gif \"Depth-First Search\")\r\n-------------------------------------------------------\r\n### 2.5 Breadth-First Search\r\n**Idea:**\r\n1. Start at root node\r\n2. Search neighboring nodes first before moving on to next level\r\n\r\n**Data Structures:**\r\n* Tree\r\n* Graph\r\n\r\n**Space:**\r\n* `O(V)`, `V = number of verticies`\r\n\r\n**Performance:**\r\n* `O(E)`, `E = number of edges`\r\n\r\n**Visualization:**\r\n\r\n![DepthFirstSearch](Searching/Animations/Breadth-First%20Search.gif \"Breadth-First Search\")\r\n-------------------------------------------------------\r\n## 3.0 NP Complete Problems\r\n### 3.1 NP Complete\r\n* **NP Complete** means that a problem is unable to be solved in **polynomial time**\r\n* NP Complete problems can be *verified* in polynomial time, but not *solved*\r\n\r\n-------------------------------------------------------\r\n### 3.2 Traveling Salesman Problem\r\n\r\n-------------------------------------------------------\r\n### 3.3 Knapsack Problem\r\n\r\n-------------------------------------------------------\r\n\r\n## 4.0 Algorithms\r\n###  4.1 Insertion Sort\r\n#### Idea\r\n1. Iterate over all elements\r\n2. For each element:\r\n    * Check if element is larger than largest value in sorted array\r\n3. If larger: Move on\r\n4. If smaller: Move item to correct position in sorted array\r\n\r\n#### Details\r\n* **Data structure:** Array\r\n* **Space:** `O(1)`\r\n* **Best Case:** Already sorted, `O(n)`\r\n* **Worst Case:** Reverse sorted, `O(n^2)`\r\n* **Average:** `O(n^2)`\r\n\r\n#### Advantages\r\n* Easy to code\r\n* Intuitive\r\n* Better than selection sort and bubble sort for small data sets\r\n* Can sort in-place\r\n\r\n#### Disadvantages\r\n* Very inefficient for large datasets\r\n\r\n#### Visualization\r\n\r\n![InsertionSort](Sorting/Animations/Insertion%20Sort.gif \"Insertion Sort\")\r\n-------------------------------------------------------\r\n### 4.2 Selection Sort\r\n#### Idea\r\n1. Iterate over all elements\r\n2. For each element:\r\n    * If smallest element of unsorted sublist, swap with left-most unsorted element\r\n\r\n#### Details\r\n* **Data structure:** Array\r\n* **Space:** `O(1)`\r\n* **Best Case:** Already sorted, `O(n^2)`\r\n* **Worst Case:** Reverse sorted, `O(n^2)`\r\n* **Average:** `O(n^2)`\r\n\r\n#### Advantages\r\n* Simple\r\n* Can sort in-place\r\n* Low memory usage for small datasets\r\n\r\n#### Disadvantages\r\n* Very inefficient for large datasets\r\n\r\n#### Visualization\r\n\r\n![SelectionSort](Sorting/Animations/Selection%20Sort.gif \"Selection Sort\")\r\n\r\n![SelectionSort](Sorting/Animations/Selection%20Sort%202.gif \"Selection Sort 2\")\r\n-------------------------------------------------------\r\n### 4.3 Bubble Sort\r\n#### Idea\r\n1. Iterate over all elements\r\n2. For each element:\r\n    * Swap with next element if out of order\r\n3. Repeat until no swaps needed\r\n\r\n#### Details\r\n* **Data structure:** Array\r\n* **Space:** `O(1)`\r\n* **Best Case:** Already sorted `O(n)`\r\n* **Worst Case:** Reverse sorted, `O(n^2)`\r\n* **Average:** `O(n^2)`\r\n\r\n#### Advantages\r\n* Easy to detect if list is sorted\r\n\r\n#### Disadvantages\r\n* Very inefficient for large datasets\r\n* Much worse than even insertion sort\r\n\r\n#### Visualization\r\n\r\n![BubbleSort](Sorting/Animations/Bubble%20Sort.gif \"Bubble Sort\")\r\n-------------------------------------------------------\r\n### 4.4 Merge Sort\r\n#### Idea\r\n1. Divide list into smallest unit (1 element)\r\n2. Compare each element with the adjacent list\r\n3. Merge the two adjacent lists\r\n4. Repeat\r\n\r\n#### Details\r\n* **Data structure:** Array\r\n* **Space:** `O(n) auxiliary`\r\n* **Best Case:** `O(nlog(n))`\r\n* **Worst Case:** Reverse sorted, `O(nlog(n))`\r\n* **Average:** `O(nlog(n))`\r\n\r\n#### Advantages\r\n* High efficiency on large datasets\r\n* Nearly always O(nlog(n))\r\n* Can be parallelized\r\n* Better space complexity than standard Quicksort\r\n\r\n#### Disadvantages\r\n* Still requires O(n) extra space\r\n* Slightly worse than Quicksort in some instances\r\n\r\n#### Visualization\r\n\r\n![MergeSort](Sorting/Animations/Merge%20Sort.gif \"Merge Sort\")\r\n\r\n![MergeSort](Sorting/Animations/Merge%20Sort%202.gif \"Merge Sort 2\")\r\n-------------------------------------------------------\r\n### 4.5 Quicksort\r\n#### Idea\r\n1. Choose a **pivot** from the array\r\n2. Partition: Reorder the array so that all elements with values *less* than the pivot come before the pivot, and all values *greater* than the pivot come after\r\n3. Recursively apply the above steps to the sub-arrays\r\n\r\n#### Details\r\n* **Data structure:** Array\r\n* **Space:** `O(n)`\r\n* **Best Case:** `O(nlog(n))`\r\n* **Worst Case:** All elements equal, `O(n^2)`\r\n* **Average:** `O(nlog(n))`\r\n\r\n#### Advantages\r\n* Can be modified to use O(log(n)) space\r\n* Very quick and efficient with large datasets\r\n* Can be parallelized\r\n* Divide and conquer algorithm\r\n\r\n#### Disadvantages\r\n* Not stable (could swap equal elements)\r\n* Worst case is worse than Merge Sort\r\n\r\n#### Optimizations\r\n* Choice of pivot:\r\n    * Choose median of the first, middle, and last elements as pivot\r\n    * Counters worst-case complexity for already-sorted and reverse-sorted\r\n\r\n#### Visualization\r\n\r\n![QuickSort](Sorting/Animations/Quicksort.gif)\r\n"
  },
  {
    "path": "C++/README.md",
    "content": "# C++ and Data Structures & Algorithms Cheat Sheet\r\n\r\nThese are two cheat sheets I put together describing both basic [C++ syntax](C++%20Syntax.md) and many common [data structures and algorithms](Data%20Structures%20and%20Algorithms.md) in C++ for my past interviews at Google, NASA, etc.\r\n\r\nHopefully you find them useful, and please open an issue or submit a PR if you find incorrect or missing information!\r\n"
  },
  {
    "path": "Command Line/README.md",
    "content": "[back to overwiev](/../..)\r\n\r\n# Command Line Cheatsheet\r\n\r\n##### Table of Contents  \r\n[Basics](#basics)  \r\n[Showing & Navigating](#showing--navigating)  \r\n[Copying/Moving/Removing](#copyingmovingremoving)  \r\n[Input & Output Redirects](#input--output-redirects)  \r\n[Sorting & Filtering](#sorting--filtering)  \r\n[Environment](#environmen)  \r\n\r\n## Basics\r\n**clear** –– clears the terminal\r\n**nano** filename –– opens the nano text editor for specific file (optional)\r\n^ –– in nano stands for ctrl\r\n~ –– usually represents the users home directory\r\n\r\n## Showing & Navigating\r\n**ls** –– lists all files (folders are called directories. files and directories are structured in a file system)  \r\n**ls -a** –– lists all files + hidden files (-a is called an option)  \r\nls -t –– orders by time last added  \r\nls -l –– with long description (access-rights, n# of hard links, owner, group-name, size in bytes, date-last-modified, name)  \r\nls -alt –– -a, -t & -l together  \r\n**pwd** –– print working directory path (the directory you’re currently in)  \r\n**cd directory-name** –– change directory  \r\ncd folder/childfolder –– two down  \r\ncd .. –– one up – cd folder/folder –– two down  \r\n**mkdir name** –– make directory  \r\n**touch name** –– creates a new file inside the working directory  \r\n**cat** filename –– outputs the content of a file to the console  \r\n**wc** filename –– outputs the number of lines, words, and characters in file  \r\n\r\n## Copying/Moving/Removing\r\n**cp** file-to-copy place-to-paste –– copies files and paste them somewhere else  \r\ncp file1 file2 file3 place-to-paste –– you can copy multiple files at once  \r\ncp * place-to-paste –– copy all files from working directory  (special characters like * are called wildcard, when you combine it with .txt for example would mean any file that ends with .txt)    \r\n**mv** file-to-move-1 place-to-move –– moves a file  \r\nmv file-to-rename new-filename –– renames a file  \r\n**rm** file-to-remove –– removes a file or directory !permanently!  \r\nrm -r dir-to-remove –– removes a dir and all its children !permanently!  \r\n\r\n##Input & Output Redirects\r\necho \"Hello\" > world.txt –– **>** redirects the standard output (Hello) into something else (world.txt)  \r\ncat file1.txt > file2.txt –– content of file1 is redirected into file2 which overrides the content of file2 by the content of file1  \r\ncat file1.txt >> file2.txt –– **>>** appends the output of file1 to file2  \r\ncat < file.txt –– takes the output from the right and inputs it into the left  \r\ncat file.txt | wc –– **|** is a \"pipe\". The | takes the standard output of the command on the left, and pipes it as standard input to the command on the right. You can think of this as \"command to command\" redirection.  \r\ncat text1.txt | wc | cat > text2.txt –– multiple pipes can be combined here the output of text1.txt is given to wc whose output is given to cat which places it into text.txt\r\n\r\n## Sorting & Filtering\r\n**sort** filename –– outputs the sortet content of the file  \r\ncat filename | sort > nameofsortedfile –– outputs the content of filename binds it to the sort function that then redirect that sorted output into a file  \r\n**uniq** filename –– filters out adjacent, duplicate lines in a file  \r\nsort file | uniq > anotherfile –– sorts a file \"pipes\" (|) the sorted content to uniq which filters out all adjacent duplicates and gives the result back to another file\r\nsort file | uniq -c > anotherfile -– counting the duplicated lines in file  \r\nsort file | uniq -c | sort -nr > anotherfile -– counting the duplicated lines in file and sort it (by frequency)\r\n**grep** keyword filename –– searches a file for lines that have the keyword and output the result (it is case sensitive)  \r\ngrep -i keyword filename –– here grep is case insensitive  \r\ngrep -R keyword folder –– searches all files in a directory and outputs filenames and lines containing matched results  \r\ngrep -Rl keyword folder –– searches all files in a directory and outputs only filenames with matched results  \r\n**sed** 's/keyword/replacement' filename –– find in file and replace s = substitution. So sed 's/find/replace' in_this_file (only replace the first finding)  \r\nsed 's/keyword/replacement/**g**' filename –– same as above but replaces all instances not only the first finding  \r\n\r\n## Environment\r\n**nano** ~/.bash_profile –– creates a file to store environment settings. Whenever a session starts it will load it's content.\r\n(within bash_profile) **alias** pd=\"pwd\" –– create keyboard shortcuts, for commonly used commands.\r\n(within bash_profile) **export** USER=\"username\" –– create a variable that can be accessed by $USER\r\n(within bash_profile) export PS1=\">> \" –– to change the command prompt from $ to >>\r\n**source** ~/.bash_profile –– makes changes available without the fuzz to open a new console.\r\n**env** –– return a list of environment variables\r\n"
  },
  {
    "path": "Django/README.md",
    "content": "# Cheatsheet for Django QuerySets\r\nCurrent Django Version: [2.0](https://docs.djangoproject.com/en/2.0/ref/models/querysets/)\r\n\r\n## Methods that return new [QuerySets](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#methods-that-return-new-querysets)\r\n\r\n**Can be chained:**\r\n\r\n```python\r\nEntry.objects.filter(**kwargs).exclude(**kwargs).order_by(**kwargs)\r\n```\r\n\r\n * [filter](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filter)\r\n * [exclude](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exclude)\r\n * [annotate](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#annotate)\r\n * [order_by](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by)\r\n * [reverse](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#reverse)\r\n * [distinct](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#distinct)\r\n * [values](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values)\r\n * [values_list](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values-list)\r\n * [dates](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#dates)\r\n * [datetimes](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#datetimes)\r\n * [none](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#none)\r\n * [all](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#all)\r\n * [union](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#union)\r\n * [intersection](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#intersection)\r\n * [difference](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#difference)\r\n * [select_related](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#select-related)\r\n * [prefetch_related](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related)\r\n * [extra](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#extra)\r\n * [defer](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#defer)\r\n * [only](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#only)\r\n * [using](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#using)\r\n * [select_for_update](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#select-for-update)\r\n * [raw](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#raw)\r\n\r\n## Methods that do not return QuerySets\r\n\r\n * [get](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get)\r\n * [create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#create)\r\n * [get_or_create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create)\r\n * [update_or_create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update-or-create)\r\n * [bulk_create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#bulk-create)\r\n * [count](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#count)\r\n * [in_bulk](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#in-bulk)\r\n * [iterator](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iterator)\r\n * [latest](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#latest)\r\n * [earliest](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#earliest)\r\n * [first](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#first)\r\n * [last](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#last)\r\n * [aggregate](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#aggregate)\r\n * [exists](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exists)\r\n * [update](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update)\r\n * [delete](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#delete)\r\n * [as_manager](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#as-manager)\r\n\r\n## Field lookups\r\n\r\n**Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as keyword arguments to the QuerySet methods *filter()*, *exclude()* and *get()*.**\r\n\r\n```python\r\nExample: Entry.objects.get(id__exact=14)  # note double underscore.\r\n```\r\n\r\n * [exact](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exact)\r\n * [iexact](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iexact)\r\n * [contains](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#contains)\r\n * [icontains](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#icontains)\r\n * [in](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#in)\r\n * [gt](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#gt)\r\n * [gte](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#gte)\r\n * [lt](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#lt)\r\n * [lte](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#lte)\r\n * [startswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#startswith)\r\n * [istartswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#istartswith)\r\n * [endswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#endswith)\r\n * [iendswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iendswith)\r\n * [range](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#range)\r\n * [date](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#date)\r\n * [year](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#year)\r\n * [month](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#month)\r\n * [day](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#day)\r\n * [week](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#week)\r\n * [week_day](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#week-day)\r\n * [quarter (new in 2.0)](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#quarter)\r\n * [time](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#time)\r\n * [hour](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#hour)\r\n * [minute](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#minute)\r\n * [second](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#second)\r\n * [isnull](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#isnull)\r\n * [regex](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#regex)\r\n * [iregex](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iregex)\r\n\r\n**Protip: Use [in](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#in) to avoid chaining [filter()](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filter) and [exclude()](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exclude)**\r\n\r\n```python\r\nEntry.objects.filter(status__in=['Hung over', 'Sober', 'Drunk'])\r\n```\r\n\r\n## Aggregation functions\r\n\r\n * [expression](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#expression)\r\n * [output_field](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#output-field)\r\n * [filter (new in 2.0)](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#id6)\r\n * [Avg](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#avg)\r\n * [Count](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#id8)\r\n * [Max](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#max)\r\n * [Min](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#min)\r\n * [StdDev](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#stddev)\r\n * [Sum](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#sum)\r\n * [Variance](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#variance)\r\n\r\n## Query-related classes\r\n\r\n * [Q() objects](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#q-objects)\r\n * [Prefetch() objects](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-objects)\r\n * [prefetch_related_objects()](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related-objects)\r\n * [FilteredRelation() objects (new in 2.0)](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filteredrelation-objects)\r\n\r\n- - -\r\n\r\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-sa/3.0/deed.en_US\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"http://i.creativecommons.org/l/by-sa/3.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" href=\"http://purl.org/dc/dcmitype/Text\" property=\"dct:title\" rel=\"dct:type\">Django-QuerySet-Cheatsheet</span> by <span xmlns:cc=\"http://creativecommons.org/ns#\" property=\"cc:attributionName\">@chrisdl and @briandant</span> is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-sa/3.0/deed.en_US\">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.<br />\r\n\r\nThe [contributors](https://github.com/chrisdl/Django-QuerySet-Cheatsheet/graphs/contributors) are as gods among ants and shall forever be remembered as such.\r\n\r\nThe Django web framework referenced in the Django-QuerySet-Cheatsheet is ​© 2005-2018 Django Software Foundation.\r\nDjango is a registered trademark of the Django Software Foundation.\r\n"
  },
  {
    "path": "Elixir/README.md",
    "content": "# Elixir Cheat Sheet\r\n\r\n```elixir\r\nelixir -v\r\n1.3.1\r\n```\r\n\r\nElixir is a dynamic functional compiled language that runs over an Erlang Virtual Machine called BEAM.\r\n\r\nErlang and its BEAM is well known for running low-lattency, distributed and fault-tolerant applications.\r\n\r\nElixir was designed to take all that advantages in a modern coding language.\r\n\r\nElixir data types are immutable.\r\n\r\nIn Elixir a function is usually described with its arity (number of arguments), such as: `is_boolean/1`.\r\n\r\n## File Types\r\n\r\n- `.exs` => Elixir script file\r\n- `.ex` => Elixir regular file\r\n- `.beam` => Compiled Elixir file\r\n\r\n## Compile and Run Elixir code\r\n\r\n- `elixir <script_file>.exs` => run a script file\r\n- `elixirc <file>.ex` => compile a file to `Elixir.<File>.beam`\r\n\r\n## Elixir Conventions\r\n\r\n- `foo function return tuple` => the result of a `foo` function is usually `{:ok, result}` or `{:error, reason}`\r\n- `foo! function may raise an error` => the result of a `foo!` is not wrapped in a tuple and it may raises an exception\r\n- Exceptions/Errors are **not used** for controlling flow\r\n- Elixir uses **fail fast** idea and the supervision trees to control process health and possible restart processes.\r\n\r\n## Comments\r\n\r\n- `#` => single line comment\r\n\r\nThere are no multi-line comment\r\n\r\n## Code Documentation\r\n\r\n- `@moduledoc` => module documentation\r\n- `@doc` => function documentation\r\n- `@spec` => function arguments/return specification\r\n- `@typedoc` => type documentation\r\n- `@type` => type definition\r\n- `@typep` => private type definition\r\n\r\n```elixir\r\ndefmodule Math do\r\n  @moduledoc \"\"\"\r\n  Provides math-related functions.\r\n\r\n  ## Examples\r\n\r\n      iex> Math.sum(1, 2)\r\n      3\r\n  \"\"\"\r\n\r\n  @spec sum(number, number) :: number\r\n  @doc \"\"\"\r\n  Calculates the sum of two numbers.\r\n  \"\"\"\r\n  def sum(a, b), do: a + b\r\nend\r\n\r\nh Math\r\nh Math.sum\r\n```\r\n\r\n## Elixir Special Unbound Variable\r\n\r\n- `_` => unbound variable\r\n\r\n## Elixir/Erlang Virtual Machine inspection\r\n\r\n- `:observer.start` => start a gui tool for inspection\r\n- `:erlang.memory` => inspect memory\r\n- `:c.memory` => inspect memory\r\n\r\n```elixir\r\n:c.memory\r\n# [\r\n#   total: 19262624,\r\n#   processes: 4932168,\r\n#   processes_used: 4931184,\r\n#   system: 14330456,\r\n#   atom: 256337,\r\n#   atom_used: 235038,\r\n#   binary: 43592,\r\n#   code: 5691514,\r\n#   ets: 358016\r\n# ]\r\n```\r\n\r\n## Interactive Elixir\r\n\r\n- `iex` => open Interactive Elixir\r\n- `iex <file>` => open Interactive Elixir loading a file\r\n- `<Ctrl>c + a` => close iex\r\n- `i <object>` => information about an object\r\n- `h <function/arity>` => help for a function\r\n- `h <operator/arity>` => help for a operator\r\n- `s <function/arity>` => specification for a function\r\n- `s <operator/arity>` => specification for a operator\r\n- `t <function/arity>` => type for a function\r\n- `c <file>` => load and compile a `.ex` file\r\n\r\n## Basic Types\r\n\r\n### Integer\r\n\r\n- `1` => integer\r\n- `1_000` => integers can use `_` to make it easy to read\r\n- `0x1F` => integer\r\n- `0b1010` => binary integer notation 10\r\n- `0o777` => octadecimal integer notation 511\r\n- `0x1F` => hexadecimal integer notation 31\r\n\r\n### Float\r\n\r\n- `-1.0` => float\r\n- `5.7e-2` => float exponent notation 0.057\r\n\r\n### Atom\r\n\r\n- `:atom` => atom / symbol\r\n\r\n- `true` => boolean (atom)\r\n\r\n### BitString\r\n\r\n- `<<97::size(2)>>` => bit string\r\n- `<<97,98>>` => binary\r\n- `\"elixir\"` => string\r\n\r\n### Tuple\r\n\r\n- `{1, 2, 3}` => tuple\r\n\r\n### List\r\n\r\n- `[1, 2, 3]` => list\r\n- `'elixir'` => char list\r\n\r\n- `[a: 5, b: 3]` => keyword list short notation\r\n- `[{:a, 5}, {:b, 3}]` => keyword list long notation\r\n\r\n### Map\r\n\r\n- `%{name: \"Mary\", age: 29}` => map short notation (keys must be atoms)\r\n- `%{:name => \"Mary\", :age => 29}` => map long notation\r\n\r\n### PID\r\n\r\n- `self() #=> #PID<0.80.0>` => current Process id\r\n\r\n### Function\r\n\r\n- `fn -> :hello end` => anonymous function\r\n\r\n### Reference\r\n\r\n- `make_ref() #=> #Reference<0.0.8.133>` => create a new reference\r\n\r\n### Port\r\n\r\n- `hd Port.list() #=> #Port<0.0>` => get first port\r\n\r\n## Type Testing\r\n\r\n- `is_nil/1`\r\n- `is_integer 1`\r\n- `is_float 4.6`\r\n- `is_number 7.8`\r\n- `is_atom :foo`\r\n- `is_boolean false`\r\n- `is_bitstring <<97:2>>`\r\n- `is_binary <<97, 98>>`\r\n- `is_list/1`\r\n- `is_tuple/1`\r\n- `is_map/1`\r\n- `is_pid self()`\r\n- `is_function(fn a, b -> a + b end)` => function\r\n- `is_function(fn a, b -> a + b end, 2)` => function with arity\r\n- `is_port hd Port.list()`\r\n- `is_reference make_ref()`\r\n- `Range.range?(1..3)`\r\n\r\n## Converting Types\r\n\r\n- `to_char_list(\"hełło\")` => convert a string to char list\r\n- `to_string('hełło')` => convert a char list to string\r\n- `Map.to_list(%{:a => 1, 2 => :b})` => convert a map to list of tuples or keyword list\r\n\r\n## Number Operators\r\n\r\n- `10 / 2 => 5.0` => division always return a float\r\n- `div(10, 2) => 5` => integer division\r\n- `rem 10, 3 => 1` => integer remain of a division\r\n- `round(3.58) => 4` => float round\r\n- `trunc(3.58) => 3` => float trunc\r\n\r\n## Boolean Operators\r\n\r\nFalsy in Elixir is `false` and `nil`, otherwise will be truthy.\r\n\r\n- `==` => equals\r\n- `!=` => different\r\n- `===` => strict equal (integer with float)\r\n- `!==` => strict different (integer with float)\r\n- `<` => less\r\n- `<=` => less or equal\r\n- `>` => greater\r\n- `>=` => greater or equal\r\n- `&&` => truthy and\r\n- `||` => truthy or\r\n- `!` => truthy not\r\n- `and` => boolean and\r\n- `or` => boolean or\r\n- `not` => boolean not\r\n\r\nIt's possible to compare different data types and that's the sorting order: `number < atom < reference < functions < port < pid < tuple < list < bit string`.\r\n\r\n## Pipe Operator\r\n\r\n- `|>` => pipe operator\r\n\r\nThe return of a function will be passed as the first argument to the following.\r\n\r\n```elixir\r\n1..100 |>\r\n  Stream.map(&(&1 * 3)) |>\r\n  Stream.filter(&(rem(&1, 2) != 0)) |>\r\n  Enum.sum\r\n#=> 7500\r\n```\r\n\r\n## Pattern Matching\r\n\r\nIn Elixir `=` sign is not just an assign operator, but a **Match Operator**.\r\n\r\nThis means that you assign variables from right side to the left based on patterns defined by the left one. If a pattern does not match a `MatchError` is raised.\r\n\r\nThis powerful tool is also used to decompose complex objects like tuples, lists, etc into smaller ones:\r\n\r\n```elixir\r\nx = 1 #=> assign 1 to x\r\n2 = x #=> ** (MatchError)\r\n1 = x #=> match and does not assign anything\r\n\r\n<<0, 1, x>> = <<0, 1, 2, 3>> #=> ** (MatchError)\r\n<<0, 1, x::binary>> = <<0, 1, 2, 3>>\r\n<<0, 1>> <> <<x::binary>> = <<0, 1, 2, 3>>\r\n<<0, 1>> <> <<x, y>> = <<0, 1, 2, 3>>\r\n<<0, 1>> <> <<x>> <> <<y>> = <<0, 1, 2, 3>>\r\n\r\n\"world\" <> x = \"hello\" #=> ** (MatchError)\r\n\"he\" <> x = \"hello\"\r\n\r\n{x, y, z} = {1, 2} #=> ** (MatchError)\r\n{} = {1, 2} #=> ** (MatchError)\r\n{:a, :b} = {:b, :a} #=> ** (MatchError)\r\n{x, y} = {1, 2}\r\n\r\nfirst..last = 1..5\r\n\r\n[x, 4] = [:a, 5] #=> ** (MatchError)\r\n[] = [:a, 5] #=> ** (MatchError)\r\n[:a, :b] = [:b, :a] #=> ** (MatchError)\r\n[x, 4] = [:a, 4]\r\n\r\n[x | y] = [] #=> ** (MatchError)\r\n[x | y] = [1]\r\n[x | y] = [1, 2, 3]\r\n\r\n[a: x] = [b: 9] #=> ** (MatchError)\r\n[a: x] = [a: 5]\r\n[{:a, x}] = [a: 5]\r\n\r\n%{a: x} = %{b: 5} #=> ** (MatchError)\r\n%{} = %{a: 5} # empty map matches any map\r\n%{a: x, b: 5} = %{b: 5, a: 7, c: 9}\r\n\r\ndefmodule User do\r\n  defstruct name: \"John\", age: 27\r\nend\r\njohn = %User{age: 29}\r\n%User{name: name} = john\r\nname #=> \"John\"\r\n```\r\n\r\nSo in other words:\r\n\r\n- non variables on the left side will be used to **restrict a pattern to match**\r\n- variables using the pin operator on the left side will have its value to be used to **restrict a pattern to match**\r\n- variables on the left side will be **assigned** with right side values\r\n\r\nSo **variables** and **non variables** behave differently with the match operator.\r\n\r\nIn order to assert an **empty map** you have to use a guard instead of pattern match, just like:\r\n\r\n```elixir\r\n(\r\n  fn m when map_size(m) == 0 ->\r\n    \"empty map\"\r\n  end\r\n).(%{}) #=> \"empty map\"\r\n```\r\n\r\n### Pin Operator\r\n\r\nThe Pin Operator `^` is used to treat variables the same way non variables with the match operator. In other words, the Pin Operator will evaluate the variable and use its value to **restrict a pattern**, preserving its original value.\r\n\r\n```elixir\r\nx = 1 #=> assign 1 to x\r\n^x = 1 #=> match x value with right side 1\r\n^x = 2 #=> ** (MatchError)\r\n```\r\n\r\n### Match Operator Limitation\r\n\r\nYou cannot make function calls on the left side of a match.\r\n\r\n- `length([1, [2], 3]) = 3 #=> ** (CompileError) illegal pattern`\r\n\r\n## Custom Operators\r\n\r\nYou can customize an Elixir Operator like the following example:\r\n\r\n```elixir\r\n1 + 2 #=> 3\r\ndefmodule WrongMath do\r\n  def a + b do\r\n    {a, b}\r\n  end\r\nend\r\nimport WrongMath\r\nimport Kernel, except: [+: 2]\r\n1 + 2 #=> {1, 2}\r\n```\r\n\r\n## Sigils\r\n\r\nAvailable delimiters for `Sigil`: `/`, `|`, `\"`, `'`, `(`, `[`, `{`, `<`.\r\n\r\n- `~r` => regular expression (modifiers: `i`)\r\n- `~r/hello/i` => `i` modifies to case insensitive\r\n- `~w` => list of string words (modifiers: )\r\n- `~w[foo bar]c` => `c` modifies to list of char lists\r\n- `~w[foo bar]a` => `c` modifies to list of atoms\r\n\r\n```elixir\r\n~w(one two three) #=> [\"one\", \"two\", \"three\"]\r\n~w(one two three)c #=> ['one', 'two', 'three']\r\n~w(one two three)a #=> [:one, :two, :three]\r\n```\r\n\r\n## Bit Strings\r\n\r\n- `<<97::4>>` => short notation with 4 bits\r\n- `<<97::size(4)>>` => long notation with 4 bits\r\n- `byte_size(<<5::4>>)` => bit string byte size\r\n\r\n### Performance for Bit Strings:\r\n\r\n#### cheap functions:\r\n\r\n- `byte_size(<<97::4>>)`\r\n\r\n#### expensive functions:\r\n\r\n## Binaries\r\n\r\nBinaries are 8 bits multiple Bit Strings. Binaries are 8 bits by default.\r\n\r\n- `<<97>>` => short notation with 8 bits\r\n- `<<97::size(8)>>` => long notation with 8 bits\r\n- `<>` => concatenate binaries/strings\r\n\r\n### Performance for Binaries:\r\n\r\n#### cheap functions:\r\n\r\n- `byte_size(<<97>>)`\r\n\r\n#### expensive functions:\r\n\r\n## Strings\r\n\r\nString is a Binary of code points where all elements are valid characters. Strings are surrounded by double-quotes and are encoded in `UTF-8` by default.\r\n\r\n- `\"hello\"` => string\r\n- `<<97, 98>>` => string \"ab\"\r\n- `<<?a, ?b>>` => string \"ab\"\r\n `?x` => code points (ASCII code) for letter `x`\r\n- `\"hello #{:world}\"` => string interpolation\r\n- `\"\\n\"` => new line\r\n- `String.length(\"hello\") #=> 5` => get the length of a string\r\n- `String.upcase(\"hello\") #=> \"HELLO\"` => upcase a string\r\n- `\"\"\"` => multi-line string begin/end\r\n\r\n### Performance for Strings:\r\n\r\n#### cheap functions:\r\n\r\n- `byte_size(\"hello\")`\r\n\r\n#### expensive functions:\r\n\r\n- `String.length(\"Hello\")`\r\n\r\n## Tuples\r\n\r\nTuple is a list that is stored contiguously in memory.\r\n\r\n- `{:ok, \"hello\"}`\r\n- `tuple_size({:ok, \"hello\"})` => tuple size\r\n- `elem({:ok, \"hello\"}, 0)` => get tuple element by index\r\n- `put_elem({:ok, \"hello\"}, 1, \"world\")`\r\n\r\n### Performance for Tuples:\r\n\r\n#### cheap functions:\r\n\r\n- `tuple_size({:ok, \"hello\"})`\r\n- `elem({:ok, \"hello\"}, 1)`\r\n\r\n#### expensive functions:\r\n\r\n- `put_elem({:ok, \"hello\"}, 1, \"world\")`\r\n\r\n## Lists\r\n\r\n**Lists** implements Enumerables protocol.\r\n\r\nList is a linked list structure where each element points to the next one in memory. When subtraction just the first ocurrence will be removed.\r\n\r\n- `[:ok, \"hello\"]`\r\n- `[97 | [1, 6, 9]]` => prepend\r\n- `[1, 5] ++ [3, 9] # [1, 5, 3, 9]` => concatenation\r\n- `[1, 5] -- [9, 5] # [1]` => subtraction first occurrences\r\n- `hd([1, 5, 7])` => head\r\n- `tl([1, 5, 7])` => tail\r\n- `:foo in [:foo, :bar] #=> true` => in operator\r\n\r\n### Performance for Lists:\r\n\r\n#### cheap functions:\r\n\r\n- `[97 | [1, 6, 9]]` => prepend\r\n- `hd([1, 5, 7])` => head\r\n- `tl([1, 5, 7])` => tail\r\n\r\n#### expensive functions:\r\n\r\n- `[1, 5] ++ [3, 9] # [1, 5, 3, 9]` => concatenation\r\n- `[1, 5] -- [9, 5] # [1]` => subtraction first occurrences\r\n- `length([1, 4])`\r\n- `:foo in [:foo, :bar] #=> true` => in operator\r\n\r\n## Char List\r\n\r\nA Char List is a List of code points where all elements are valid characters. Char Lists are surrounded by single-quote and are usually used as arguments to some old Erlang code.\r\n\r\n- `'ab'` => char list\r\n- `[97, 98]` => `'ab'`\r\n- `[?a, ?b]` => `'ab'`\r\n- `?x` => code points (ASCII code) for letter `x`\r\n- `'hello' ++ 'world' # 'helloworld'` => concatenation\r\n- `'hello' -- 'world' # 'hel'` => subtraction first occurrences\r\n- `?l in 'hello' #=> true` => in operator\r\n\r\n### Performance for Char Lists:\r\n\r\n#### cheap functions:\r\n\r\n- `[?H | 'ello']` => prepend\r\n\r\n#### expensive functions:\r\n\r\n- `'hello' ++ 'world' # 'helloworld'` => concatenation\r\n- `'hello' -- 'world' # 'hel'` => subtraction first occurrences\r\n- `length('Hello')`\r\n- `?l in 'hello' #=> true` => in operator\r\n\r\n## Keyword Lists\r\n\r\nKeyword list is a list of tuples where first elements are atoms. When fetching by key the first match will return. If a keyword list is the last argument of a function the square brackets `[` are optional.\r\n\r\n- `[a: 5, b: 3]` => keyword list short notation\r\n- `[{:a, 5}, {:b, 3}]` => keyword list long notation\r\n- `[{:a, 6} | [b: 7]] # [a: 6, b: 7]` => prepend\r\n- `[a: 5] ++ [a: 7] # [a: 5, a: 7]` => concatenation\r\n- `[a: 5, b: 7] -- [a: 5] # [b: 7]` => subtraction first ocurrences\r\n- `([a: 5, a: 7])[:a] # 5` => fetch by key\r\n- `length(a: 5, b: 7)` => optional squared brackets `[`\r\n\r\n### Performance for Keyword Lists:\r\n\r\n#### cheap functions:\r\n\r\n- `[{:a, 6} | [b: 7]] # [a: 6, b: 7]` => prepend\r\n\r\n#### expensive functions:\r\n\r\n- `[a: 5] ++ [a: 7] # [a: 5, a: 7]` => concatenation\r\n- `[a: 5, b: 7] -- [a: 5] # [b: 7]` => subtraction first ocurrences\r\n- `([a: 5, a: 7])[:a] # 5` => fetch by key\r\n- `length(a: 5, b: 7)` => optional squared brackets `[`\r\n\r\n## Maps\r\n\r\n**Maps** implements Enumerables protocol.\r\n\r\nMap holds a key value structure.\r\n\r\n- `%{name: \"Mary\", age: 29}` => map short notation (keys must be atoms)\r\n- `%{:name => \"Mary\", :age => 29}` => map long notation\r\n- `%{name: \"Mary\", age: 29}[:name]` => fetch `:name` hash notation\r\n- `%{name: \"Mary\", age: 29}[:born]` => returns nil when do not find in the hash notation\r\n- `%{name: \"Mary\", age: 29}.name` => fetch `:name` short notation\r\n- `%{name: \"Mary\", age: 29}.born # ** (KeyError)` => blows an error when key does not exists\r\n- `%{%{name: \"Mary\", age: 29} | age: 31}` => update value for existing key\r\n- `%{%{name: \"Mary\", age: 29} | born: 1990} # ** (KeyError)` => blows an error when updating non existing key\r\n- `map_size(%{name: \"Mary\"}) #=> 1` => map size\r\n\r\n### Performance for Maps:\r\n\r\n#### cheap functions:\r\n\r\n- `%{name: \"Mary\", age: 29}[:name]` => fetch `:name`\r\n- `%{name: \"Mary\", age: 29}.name` => fetch `:name` short notation\r\n- `%{%{name: \"Mary\", age: 29} | age: 31}` => update value for existing key\r\n- `map_size(%{name: \"Mary\"}) #=> 1` => map size\r\n\r\n#### expensive functions:\r\n\r\n## Structs\r\n\r\nStructs are built in top of Map.\r\n\r\n- `defstruct` => define a struct\r\n\r\n```elixir\r\ndefmodule User do\r\n  defstruct name: \"John\", age: 27\r\nend\r\njohn = %User{} #=> %User{age: 27, name: \"John\"}\r\nmary = %User{name: \"Mary\", age: 25} #=> %User{age: 25, name: \"Mary\"}\r\nmeg = %{john | name: \"Meg\"} #=> %User{age: 27, name: \"Meg\"}\r\nbill = Map.merge(john, %User{name: \"Bill\", age: 23})\r\n\r\njohn.name #=> John\r\njohn[:name] #=> ** (UndefinedFunctionError) undefined function: User.fetch/2\r\nis_map john #=> true\r\njohn.__struct__ #=> User\r\nMap.keys(john) #=> [:__struct__, :age, :name]\r\n```\r\n\r\n## Ranges\r\n\r\nRanges are `Struct`.\r\n\r\n- `range = 1..10` => range definition\r\n- `Enum.reduce(1..3, 0, fn i, acc -> i + acc end) #=> 6` => range used in a reduce function to sum them up\r\n- `Enum.count(range) #=> 10`\r\n- `Enum.member?(range, 11) #=> false`\r\n\r\n## Protocols\r\n\r\n- `defprotocol Foo` => define protocol `Foo`\r\n- `defimpl Foo, for Integer` => implement that protocol for `Integer`\r\n\r\nHere are all native data types that you can use: `Atom`, `BitString`, `Float`, `Function`, `Integer`, `List`, `Map`, `PID`, `Port`, `Reference`, `Tuple`.\r\n\r\n```elixir\r\ndefprotocol Blank do\r\n  @doc \"Returns true if data is considered blank/empty\"\r\n  def blank?(data)\r\nend\r\n\r\ndefimpl Blank, for: Integer do\r\n  def blank?(_), do: false\r\nend\r\n\r\ndefimpl Blank, for: List do\r\n  def blank?([]), do: true\r\n  def blank?(_),  do: false\r\nend\r\n\r\ndefimpl Blank, for: Map do\r\n  def blank?(map), do: map_size(map) == 0\r\nend\r\n\r\ndefimpl Blank, for: Atom do\r\n  def blank?(false), do: true\r\n  def blank?(nil),   do: true\r\n  def blank?(_),     do: false\r\nend\r\n\r\nBlank.blank?(0) #=> false\r\nBlank.blank?([]) #=> true\r\nBlank.blank?([1, 2, 3]) #=> false\r\nBlank.blank?(\"hello\") #=> ** (Protocol.UndefinedError)\r\n```\r\n\r\n`Structs` do not share `Protocol` implementations with `Map`.\r\n\r\n```elixir\r\ndefimpl Blank, for: User do\r\n  def blank?(_), do: false\r\nend\r\n```\r\n\r\nYou can also implement a `Protocol` for `Any`. And in this case you can derive any `Struct`.\r\n\r\n```elixir\r\ndefimpl Blank, for: Any do\r\n  def blank?(_), do: false\r\nend\r\n\r\ndefmodule DeriveUser do\r\n  @derive Blank\r\n  defstruct name: \"john\", age: 27\r\nend\r\n```\r\n\r\nElixir built-in most common used protocols: `Enumerable`, `String.Chars`, `Inspect`.\r\n\r\n## Nested data Structures\r\n\r\n- `put_in/2`\r\n- `update_in/2`\r\n- `get_and_update_in/2`\r\n\r\n```elixir\r\nusers = [\r\n  john: %{name: \"John\", age: 27, languages: [\"Erlang\", \"Ruby\", \"Elixir\"]},\r\n  mary: %{name: \"Mary\", age: 29, languages: [\"Elixir\", \"F#\", \"Clojure\"]}\r\n]\r\nusers[:john].age #=> 27\r\n\r\nusers = put_in users[:john].age, 31\r\nusers = update_in users[:mary].languages, &List.delete(&1, \"Clojure\")\r\n```\r\n\r\n## Enums and Streams\r\n\r\n**Lists** and **Maps** are Enumerables.\r\n\r\n`Enum` module perform **eager** operations, meanwhile `Stream` module perform **lazy** operations.\r\n\r\n```elixir\r\n# eager Enum\r\n1..100 |> Enum.map(&(&1 * 3)) |> Enum.sum #=> 15150\r\n\r\n# lazy Stream\r\n1..100 |> Stream.map(&(&1 * 3)) |> Enum.sum #=> 15150\r\n```\r\n\r\n## do/end Keyword List and Block Syntax\r\n\r\nIn Elixir you can use either **Keyword List** syntax or  **do/end Block** syntax:\r\n\r\n```elixir\r\nsky = :gray\r\n\r\nif sky == :blue do\r\n  :sunny\r\nelse\r\n  :cloudy\r\nend\r\n\r\nif sky == :blue, do: :sunny, else: :cloudy\r\n\r\nif sky == :blue, do: (\r\n  :sunny\r\n), else: (\r\n  :cloudy\r\n)\r\n```\r\n\r\n## Conditional Flows (if/else/case/cond)\r\n\r\n### if / else\r\n\r\n```elixir\r\nsky = :gray\r\nif sky == :blue, do: :sunny, else: :cloudy\r\n```\r\n\r\n### unless / else\r\n\r\n```elixir\r\nsky = :gray\r\nunless sky != :blue, do: :sunny, else: :cloudy\r\n```\r\n\r\n### case / when\r\n\r\n```elixir\r\nsky = {:gray, 75}\r\ncase sky, do: (\r\n  {:blue, _}         -> :sunny\r\n  {_, t} when t > 80 -> :hot\r\n  _                  -> :check_wheather_channel\r\n)\r\n```\r\n\r\nOn **when guards** short-circuiting operators `&&`, `||` and `!` are **not** allowed.\r\n\r\n### cond\r\n\r\n`cond` is equivalent as `if/else-if/else` statements.\r\n\r\n```elixir\r\nsky = :gray\r\ncond do: (\r\n  sky == :blue -> :sunny\r\n  true         -> :cloudy\r\n)\r\n```\r\n\r\n## The `with` macro\r\n\r\n- `with` => macro to combine multiple match clauses\r\n- `<-` => a matching clause, on the left\r\n- `=` => bare expression is allowed\r\n- `else` => if some matching clause fails\r\n\r\n```elixir\r\nopts = %{width: 10, height: 20}\r\nwith {:ok, width} <- Map.fetch(opts, :width),\r\n     {:ok, height} <- Map.fetch(opts, :height) do\r\n  {:ok, width * height}\r\nelse\r\n  :error ->\r\n    {:error, :wrong_data}\r\nend\r\n#=> {:ok, 200}\r\n```\r\n\r\n## Recursion\r\n\r\nThere is traditional **no for loop** in Elixir, due to Elixir immutability There is a macro `for` that it's also called as `Comprehension` but it works differently from a traditional for loop. If you want a simple loop iteration you'll need to use **recursion**:\r\n\r\n```elixir\r\ndefmodule Logger do\r\n  def log(msg, n) when n <= 0, do: ()\r\n  def log(msg, n) do\r\n    IO.puts msg\r\n    log(msg, n - 1)\r\n  end\r\nend\r\nLogger.log(\"Hello World!\", 3)\r\n# Hello World!\r\n# Hello World!\r\n# Hello World!\r\n```\r\n\r\nIn functional programming languages **map** and **reduce** are two major algorithm concepts. They can be implemented with **recursion** or using the `Enum` module.\r\n\r\n**reduce** will reduces the array into a single element:\r\n\r\n```elixir\r\ndefmodule Math do\r\n  def sum_list(list, sum \\\\ 0)\r\n  def sum_list([], sum), do: sum\r\n  def sum_list([head | tail], sum) do\r\n    sum_list(tail, head + sum)\r\n  end\r\nend\r\nMath.sum_list([1, 2, 3]) #=> 6\r\n\r\nEnum.reduce([1, 2, 3], 0, &+/2) #=> 6\r\n```\r\n\r\n**map** modifies an existing array (new array with new modified values):\r\n\r\n```elixir\r\ndefmodule Math do\r\n  def double([]), do: []\r\n  def double([head | tail]) do\r\n    [head * 2 | double(tail)]\r\n  end\r\nend\r\nMath.double([1, 2, 3]) #=> [2, 4, 6]\r\n\r\nEnum.map([1, 2, 3], &(&1 * 2)) #=> [2, 4, 6]\r\n```\r\n\r\n## Comprehension -> the for loop\r\n\r\n`Comprehension` is a syntax sugar for the very powerful `for special form`. You can have **generators** and **filters** in that.\r\n\r\n- `for` => `Comprehension`\r\n- `->` => **generators**\r\n- `:into` => change return to another `Collectable` type\r\n\r\nYou can iterate over `Enumerable` what makes so close to a regular `for` loop on other languages:\r\n\r\n```elixir\r\nfor n <- [1, 2, 3, 4], do: n * n\r\n#=> [1, 4, 9, 16]\r\n```\r\n\r\nYou can also iterate over multiple `Enumerable` and then create a combination between them:\r\n\r\n```elixir\r\nfor i <- [:a, :b, :c], j <- [1, 2], do:  {i, j}\r\n#=> [a: 1, a: 2, b: 1, b: 2, c: 1, c: 2]\r\n```\r\n\r\nYou can pattern match each element:\r\n\r\n```elixir\r\nvalues = [good: 1, good: 2, bad: 3, good: 4]\r\nfor {:good, n} <- values, do: n * n\r\n#=> [1, 4, 16]\r\n```\r\n\r\nGenerators use `->` and they have on the right an `Enumerable` and on the left a **pattern matchable** element variable.\r\n\r\nYou can have **filters** to filter **truthy** elements:\r\n\r\n```elixir\r\nfor dir  <- [\".\", \"/\"],\r\n    file <- File.ls!(dir),\r\n    path = Path.join(dir, file),\r\n    File.regular?(path) do\r\n  \"dir=#{dir}, file=#{file}, path=#{path}\"\r\nend\r\n#=> [\"dir=., file=README.md, path=./README.md\", \"dir=/, file=.DS_Store, path=/.DS_Store\"]\r\n```\r\n\r\nYou can use `:into` to change the return type:\r\n\r\n```elixir\r\nfor k <- [:foo, :bar], v <- 1..5, into: %{}, do: {k, v}\r\n#=> %{bar: 5, foo: 5}\r\nfor k <- [:foo, :bar], v <- 1..5, into: [], do: {k, v}\r\n#=> [foo: 1, foo: 2, foo: 3, foo: 4, foo: 5, bar: 1, bar: 2, bar: 3, bar: 4, bar: 5]\r\n```\r\n\r\n## Anonymous Functions\r\n\r\n- `fn` => define functions\r\n- `->` => one line function definition\r\n- `.` => call a function\r\n- `when` => guards\r\n\r\n```elixir\r\nadd = fn a, b -> a + b end\r\nadd.(4, 5) #=> 9\r\n```\r\n\r\nWe can have multiple clauses and guards inside functions.\r\n\r\n```elixir\r\ncalc = fn\r\n  x, y when x > 0 -> x + y\r\n  x, y -> x * y\r\nend\r\ncalc.(-1, 6) #=> 5\r\ncalc.(4, 5) #=> 45\r\n```\r\n\r\n## Modules And Named Functions\r\n\r\n- `defmodule` => define Modules\r\n- `def`  => define functions inside Modules\r\n- `defp`  => define private functions inside Modules\r\n- `when` => guards\r\n- `@` => module attributes\r\n- `__info__(:functions)` => list functions inside a module\r\n- `defdelegate` => delegate functions\r\n\r\n```eilxir\r\ndefmodule Math do\r\n  def sum(a, b) when is_integer(a) and is_integer(b), do: a + b\r\nend\r\n\r\nMath.sum(1, 2) #=> 3\r\n\r\nMath.__info__(:functions) #=> [sum: 2]\r\n```\r\n\r\nModule attribute works as constants, evaluated at compilation time:\r\n\r\n```eilxir\r\ndefmodule Math do\r\n  @foo :bar\r\n  def print, do: @foo\r\nend\r\n\r\nMath.print #=> :bar\r\n```\r\n\r\nSpecial Module attributes:\r\n\r\n- `@vsn`\r\n- `@moduledoc`\r\n- `@doc`\r\n- `@behaviour`\r\n- `@before_compile`\r\n\r\n## Default Argument\r\n\r\n- `\\\\` => default argument\r\n\r\n```elixir\r\ndefmodule Concat do\r\n  def join(a, b, sep \\\\ \" \") do\r\n    a <> sep <> b\r\n  end\r\nend\r\n\r\nIO.puts Concat.join(\"Hello\", \"world\")      #=> Hello world\r\nIO.puts Concat.join(\"Hello\", \"world\", \"_\") #=> Hello_world\r\n```\r\n\r\nDefault values are **evaluated runtime**.\r\n\r\n```elixir\r\ndefmodule DefaultTest do\r\n  def dowork(x \\\\ IO.puts \"hello\") do\r\n    x\r\n  end\r\nend\r\nDefaultTest.dowork #=> :ok\r\n# hello\r\nDefaultTest.dowork 123 #=> 123\r\nDefaultTest.dowork #=> :ok\r\n# hello\r\n```\r\n\r\nFunction with multiple clauses and a default value requires a **function head** where default values are set:\r\n\r\n```elixir\r\ndefmodule Concat do\r\n  def join(a, b \\\\ nil, sep \\\\ \" \") # head function\r\n\r\n  def join(a, b, _sep) when is_nil(b) do\r\n    a\r\n  end\r\n\r\n  def join(a, b, sep) do\r\n    a <> sep <> b\r\n  end\r\nend\r\n\r\nIO.puts Concat.join(\"Hello\")               #=> Hello\r\nIO.puts Concat.join(\"Hello\", \"world\")      #=> Hello world\r\nIO.puts Concat.join(\"Hello\", \"world\", \"_\") #=> Hello_world\r\n```\r\n\r\n## Function Capturing\r\n\r\n- `&` => function capturing\r\n- `&1` => 1st argument\r\n\r\n`&` could be used with a module function.\r\n\r\nWhen capturing you can use the function/operator with its arity.\r\n\r\n```elixir\r\n&(&1 * &2).(3, 4) #=> 12\r\n(&*/2).(3, 4) #=> 12\r\n\r\n(&Kernel.is_atom(&1)).(:foo) #=> true\r\n(&Kernel.is_atom/1).(:foo) #=> true\r\n(&{:ok, [&1]}).(:foo) #=> {:ok, [:foo, :bar]}\r\n(&[&1, &2]).(:foo, :bar) #=> [:foo, :bar]\r\n(&[&1 | [&2]]).(:foo, :bar) #=> [:foo, :bar]\r\n```\r\n\r\n## Behaviours\r\n\r\nBehaviour modules defines functions\r\n\r\n- `@callback` => defines a function to be implemented by other modules\r\n- `::` => separates the function definition to its return type\r\n\r\n```elixir\r\ndefmodule Parser do\r\n  @callback parse(String.t) :: any\r\n  @callback extensions() :: [String.t]\r\nend\r\n\r\ndefmodule JSONParser do\r\n  @behaviour Parser\r\n\r\n  def parse(str), do: # ... parse JSON\r\n  def extensions, do: [\"json\"]\r\nend\r\n```\r\n\r\n## Exceptions/Errors => raise/try/rescue\r\n\r\n**Exceptions/Errors** in Elixir are `Structs`.\r\n\r\n- `raise \"oops\" #=> ** (RuntimeError) oops` => raises error with message\r\n- `raise ArgumentError #=> ** (ArgumentError) argument error` => raises an error by module\r\n- `raise ArgumentError, message: \"oops\" #=> ** (ArgumentError) oops` => raises an error by module with message\r\n- `defexception` => define an exception\r\n- `try/rescue` => catches an error\r\n- `throw/try/catch` => can be used as circuit breaking, but should be avoided\r\n- `exit(\"my reason\")` => exiting current process\r\n- `after` => ensures some resource is cleaned up even if an exception was raised\r\n\r\n```elixir\r\ndefmodule MyError do\r\n  defexception message: \"default message\"\r\nend\r\n\r\nis_map %MyError{} #=> true\r\nMap.keys %MyError{} #=> [:__exception__, :__struct__, :message]\r\n\r\nraise MyError #=> ** (MyError) default message\r\nraise MyError, message: \"custom message\" #=> ** (MyError) custom message\r\n```\r\n\r\nYou can rescue an error with:\r\n\r\n```elixir\r\ntry do\r\n  raise \"oops\"\r\nrescue\r\n  e in RuntimeError -> e\r\nafter\r\n  IO.puts \"I can do some clean up here\"\r\nend\r\n#=> %RuntimeError{message: \"oops\"}\r\n\r\ntry do\r\n  raise \"oops\"\r\nrescue\r\n  RuntimeError -> \"Error!\"\r\nend\r\n#=> \"Error!\"\r\n```\r\n\r\n`throw/catch` sometime is used for circuit breaking, but you can usually use another better way:\r\n\r\n```elixir\r\ntry do\r\n  Enum.each -50..50, fn(x) ->\r\n    if rem(x, 13) == 0, do: throw(x)\r\n  end\r\n  \"Got nothing\"\r\ncatch\r\n  x -> \"Got #{x}\"\r\nend\r\n#=> \"Got -39\"\r\n\r\nEnum.find -50..50, &(rem(&1, 13) == 0)\r\n#=> -39\r\n```\r\n\r\n`exit` can be caught but this is rare in Elixir:\r\n\r\n```elixir\r\ntry do\r\n  exit \"I am exiting\"\r\ncatch\r\n  :exit, _ -> \"not really\"\r\nend\r\n#=> \"not really\"\r\n```\r\n\r\nYou can ommit `try` inside functions and use `rescue`, `catch`, `after` directly:\r\n\r\n```elixir\r\ndef without_even_trying do\r\n  raise \"oops\"\r\nafter\r\n  IO.puts \"cleaning up!\"\r\nend\r\n```\r\n\r\n## IO\r\n\r\n- `IO.puts/1 \"Hello\"` => prints to stdout\r\n- `IO.puts :stderr, \"Hello\"` => prints to stderr\r\n- `IO.gets \"yes/no: \"` => reads an user input\r\n\r\n## StringIO\r\n\r\n- `{:ok, pid} = StringIO.open(\"my-file.md\")` => open a file\r\n- `IO.read(pid, 2) #=> \"he\"` => read first 2 lines\r\n\r\n## File\r\n\r\n- `{:ok, file} = File.open \"hello\", [:write]` => open file for reading\r\n- `IO.binwrite file, \"world\"` => write into file\r\n- `File.close file` => close file\r\n- `File.read \"my-file.md\"` => reads a file\r\n- `File.stream!(\"my-file.md\") |> Enum.take(10)` => read the first 10 lines\r\n\r\n```elixir\r\n{:ok, file} = File.open \"my-file.md\", [:write]\r\nIO.binwrite file, \"hello world\"\r\nFile.close file\r\nFile.read \"my-file.md\" #=> {:ok, \"hello world\"}\r\n```\r\n\r\n## Path\r\n\r\n- `Path.join` => joins\r\n- `Path.expand(\"~/hello\")` => expands to full path\r\n\r\n## Processes, Tasks and Agents\r\n\r\nProcess in Elixir has the same concept as threads in a lot of other languages, but extremely lightweight in terms of memory and CPU. They are isolated from each other and communicate via message passing.\r\n\r\n- `spawn/1` => fork a process\r\n- `self()` => current process\r\n- `Process.alive?(pid)` => check if process is still running\r\n- `send/2` => send message to another process\r\n- `receive/1` => receive message from another process\r\n- `after` => receive option to work with timeout\r\n- `flush()` => prints out all messages received\r\n- `spawn_link/1` => forks a process and link them, so failures are propagated\r\n- `Task.start/1` => starts a task\r\n- `Task.start_link/1` => starts a task and link it to the current process\r\n- `Process.register(pid, :foo)` => register a name for a process\r\n\r\nThe idea is to have a supervisor that `spawn_link` new processes and when they fail the supervisor will restart them. This is the basics for **Fail Fast** and **Fault Tolerant** in Elixir.\r\n\r\nTasks are used in supervision trees.\r\n\r\n```elixir\r\nparent = self()\r\n\r\nspawn_link(fn -> send(parent, {:hello, self()}) end)\r\nreceive do: ({msg, pid} -> \"#{inspect pid} => #{msg}\"), after: (1_000 -> \"nothing after 1s\")\r\n\r\nTask.start_link(fn -> send(parent, {:hello, self()}) end)\r\nreceive do: ({msg, pid} -> \"#{inspect pid} => #{msg}\"), after: (1_000 -> \"nothing after 1s\")\r\n\r\nflush()\r\n```\r\n\r\n**State** can be stored in processes or using its abstraction: `Agent`.\r\n\r\nManual implementation of a storage using Elixir processes:\r\n\r\n```elixir\r\ndefmodule KV do\r\n  def start_link do\r\n    Task.start_link(fn -> loop(%{}) end)\r\n  end\r\n\r\n  defp loop(map) do\r\n    receive do\r\n      {:get, key, caller} ->\r\n        send caller, Map.get(map, key)\r\n        loop(map)\r\n      {:put, key, value} ->\r\n        loop(Map.put(map, key, value))\r\n    end\r\n  end\r\nend\r\n{:ok, pid} = KV.start_link\r\n\r\nsend pid, {:put, :hello, :world}\r\nsend pid, {:get, :hello, self()}\r\nflush() #=> :world\r\n```\r\n\r\nImplementation of a storage using `Agent`:\r\n\r\n```elixir\r\n{:ok, pid} = Agent.start_link(fn -> %{} end)\r\nAgent.update(pid, fn map -> Map.put(map, :hello, :world) end)\r\nAgent.get(pid, fn map -> Map.get(map, :hello) end)\r\n```\r\n\r\n## alias, require, import and use\r\n\r\nIn order to facilitate code reuse Elixir has: `alias`, `require`, `import` (directives) and `use` (macro).\r\n\r\n- `alias Foo.Bar, as: Bar` => alias module, so Bar can be called instead of Foo.Bar\r\n- `alias Foo.Bar` => `as` is optional on alias\r\n- `require Foo` => ensure the module is compiled and available (usually for macros)\r\n- `import Foo` => requires and import functions from Foo so they can be called without the `Foo.` prefix\r\n- `import List, only: [duplicate: 2]` => only option\r\n- `import List, expect: [duplicate: 2]` => except option\r\n- `import List, only: :macros` => import only macros\r\n- `import List, only: :functions` => import only functions\r\n- `use Foo` => invokes the custom code defined in Foo as an extension point\r\n- `alias MyApp.{Foo, Bar, Baz}` => multiple alias\r\n- `require MyApp.{Foo, Bar, Baz}` => multiple require\r\n- `import MyApp.{Foo, Bar, Baz}` => multiple import\r\n\r\nAll modules are defines inside `Elixir` namespace but it can be omitted for convenience.\r\n\r\n`alias`, `require` and `import` are lexically scoped, which means that it will be valid just inside the scope it was defined. This is **not a global scope**.\r\n\r\n`require` is usually used to require Elixir macro code:\r\n\r\n```elixir\r\nInteger.is_odd(3) #=> ** (CompileError): you must require Integer before invoking the macro Integer.is_odd/1\r\nrequire Integer\r\nInteger.is_odd(3) #=> true\r\n```\r\n\r\n`use` call `__using__` when the module is being used:\r\n\r\n```elixir\r\ndefmodule Fruit do\r\n  defmacro __using__(option: option) do\r\n    IO.puts \"options=#{inspect option}\"\r\n    quote do: IO.puts \"Using Fruit module\"\r\n  end\r\nend\r\n\r\ndefmodule Meal do\r\n  use Fruit, option: :hello\r\nend\r\n#=> \"Good to see you've added Fruit to your meal\"\r\n```\r\n\r\n## Meta Programming\r\n\r\n- `quote` => shows AST (Abstract Syntax Tree)\r\n\r\n```elixir\r\nquote do: 2 * 2 == 4\r\n#=> {\r\n#=>   :==,\r\n#=>   [context: Elixir, import: Kernel],\r\n#=>   [\r\n#=>     {\r\n#=>       :*,\r\n#=>       [context: Elixir, import: Kernel],\r\n#=>       [2, 2]\r\n#=>     },\r\n#=>     4\r\n#=>   ]\r\n#=> }\r\n```\r\n\r\n## Erlang libraries\r\n\r\nElixir provider some Erlang modules as atoms.\r\n\r\n- `:crypto` => crypto functions like `:crypto.hash/2`\r\n- `:io` => io functions like `:io.format/2`\r\n- `:digraph` => deal with digraphs\r\n- `:ets` => large data structure in memory\r\n- `:dets` => large data structure on disk\r\n- `:math` => math functions like `:math.pi/0`\r\n- `:queue` => first-in first-out structure\r\n- `:rand` => rand functions like `:rand.uniform/0`\r\n- `:zip` => handle zip files\r\n- `:zlib` => handle gzip files\r\n"
  },
  {
    "path": "Git/README.md",
    "content": "# git-cheat-sheet\r\nThis is my personal git cheat sheet. This is not a deep dive into how git works, just some of the simple stuff.\r\n\r\n# Contribute\r\n\r\nFeel free to add to the repo or fix any mistakes you see.  Get started by\r\n\r\n- Forking the repo.\r\n- Clone your forked repo into your local machine.\r\n- Create a new branch `git checkout -b your-contribution`.\r\n- After making your changes, `git commit -am 'small message about what you did'`.\r\n- Then push up into the remote repo with `git push origin HEAD`.\r\n- Go to GitHub, go to your forked repo and you should see a yellow bar mentioning your branch.\r\n- After hitting that button and reviewing your changes, hit the `Make Pull Request` button near the bottom.\r\n- I will get an email, notifying me of your Pull Request (PR) and if it's good, I will merge it.\r\n\r\nTo keep your fork up to date\r\n\r\n- add a remote upstream repository with \r\n\r\n  `$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git` (the original HTTPS clone Url)\r\n\r\n- see all your remotes with `git remote -v`\r\n  ```\r\n  origin  https://github.com/black-shadows/rails.git (fetch)\r\n  origin  https://github.com/black-shadows/rails.git (push)\r\n  upstream  https://github.com/rails/rails.git (fetch)\r\n  upstream  https://github.com/rails/rails.git (push) \r\n  ```\r\n  - now you have a remote called **upstream** which is the original repo\r\n\r\n- Then run `git pull upstream master`, to see your merged contribution on your local machine\r\n\r\n# Overview\r\n\r\n1. [Starting](#starting)\r\n1. [Git Structure](#git-structure)\r\n1. [Git Logs](#git-logs)\r\n1. [Undo](#undo)\r\n1. [Branches](#branches)\r\n1. [Merging](#merging)\r\n1. [Example Workflow](#example-workflow)\r\n1. [Tricks](#tricks)\r\n  - [Stripspace](#stripspace)\r\n  - [Previous Branch](#previous-branch)\r\n  - [Clean Status](#clean-status)\r\n  - [Auto Correct](#auto-correct)\r\n  - [Alias](#alias)\r\n1. [Remotes](#remotes)\r\n1. [GitHub](#github)\r\n1. [Creating a Git Repo](#creating-a-git-repo)\r\n1. [Git Clone](#git-clone)\r\n1. [Reset](#reset)\r\n1. [Update and Delete](#update-and-delete)\r\n1. [Stash](#stash)\r\n1. [Gitignore](#gitignore)\r\n1. [Compare](#compare)\r\n1. [Version Tags](#version-tags)\r\n1. [Collaborate](#collaborate)\r\n1. [Archive](#archive)\r\n1. [Troubleshooting](#troubleshooting)\r\n1. [Security](#security)\r\n1. [Large File Storage](#large-file-storage)\r\n\r\n## Starting\r\n\r\nStarting is the easy part.  Make sure you have git installed by opening up your terminal and running,\r\n```\r\ngit --version\r\n```\r\nIf you're running osx or some form of linux, chances are you already have git installed.  If you're running windows, and/or just don't have git installed (it'll be obvious since entering the above command will spit out an unknown command error), head over to the [official site](https://git-scm.com/downloads) to download and install git for your computer\r\n\r\nNow that you are sure you have a working version of git, it's time to create your working repository.\r\n\r\nGo inside your project directory (in the terminal) and run `git init`, this will let git know you want it to start keeping track of your changes for this folder.\r\n```\r\n$ cd my_project\r\n$ git init \r\n```\r\nTo verify, run `ls -al` and you should see the `.git` file, that is how you know you have git for this directory. If you no longer want to use git for this directory then simply delete the `.git` file.\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## Git Structure\r\n\r\nGit breaks things up into three 'trees' which are all maintained by git.\r\n\r\n**Working Directory** : This is your current **local** tree. This just holds what's in your repository. \r\n\r\n**Staging** : (Or sometimes known as _index_) is - as the name implies - a staging tree. This will hold all the recent changes you have selected to go into the next commit (more on that later).\r\n\r\n**HEAD** : Basically, a reference that usually points to the latest _commit_ for the repository.\r\n\r\nMoving from one tree to another is simple.\r\n```\r\n# You must first move files that you have changed to the staging area.\r\n# To specify a single file,\r\n$ git add <filename>\r\n\r\n# Alternatively, you can add all files that you have updated, added, or remove by entering,\r\n$ git add -A\r\n\r\n# This will put all the changes you've staged into a new commit. HEAD will now point to this newest commit.\r\n$ git commit -m \"commit message\"\r\n\r\n# You can do this all in online with.\r\n$ git commit -am \"commit message\"\r\n```\r\n\r\nThere is a caveat to using `git commit -am \"commit message\"`, it will not pick up on brand new files or files that have been deleted since the last commit.\r\nWe personally recommend going through this workflow:\r\n\r\n```\r\ngit add -A # add all changes to the repo.\r\ngit commit -m \"commit message\"` # creates a new commit with all the changes you made.\r\n```\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## Git logs\r\n\r\nThe `git log` command is a way to see all previous commits made to the repository (whether by you or someone else)\r\n\r\n```\r\n$ git log\r\n\r\ncommit cd62a7d33d8c20255ef4ba59da61ff21acbf903b\r\nAuthor: black-shadows <abhisheksharma.0517@gmail.com>\r\nDate:   Fri Apr 3 03:14:41 2015 -0400\r\n\r\n    one more method\r\n\r\ncommit 7b1db82140dc678eb869c742f0479ccf86168da5\r\nAuthor: rperryng <ryanperrynguyen@gmail.com>\r\nDate:   Fri Apr 3 03:14:08 2015 -0400\r\n\r\n    succesfull merges ?\r\n\r\ncommit bdc7ede1047a698955bd5b419de1ad9cada68b2c\r\nMerge: 8bc63cf cb6ae5f\r\nAuthor: black-shadows <abhisheksharma.0517@gmail.com>\r\nDate:   Fri Apr 3 03:12:54 2015 -0400\r\n\r\n    Merge branch 'master' into random-branch\r\n```\r\n\r\nThe large assortment of numbers and letters right next to the word commit is the sha_key, it's a specific hexadecimal value that references that particular commit.\r\n\r\n- The author line is simple, it's the user that made the commit\r\n\r\n- The date line is self-explanatory\r\n\r\n- and finally the commit message. The commit message helps you understand what work you did within that commit so make sure to make them as verbose as you can, especially if you are working with a team. \r\n\r\nThere is one more thing that I should point out here. If the git log is large enough, git will open it in `vim`, an editor for the terminal. To exit the git log, simply press `esc`, then `:`, then `q` and hit enter.\r\n\r\nBut if you want cleaner more readable information, definitely try the following:\r\n```\r\n$ git log --oneline -5\r\n\r\n70693a1 Merge branch 'master' into random-branch\r\n9f4b039 conflict feature 2 on master\r\naa87d8a branch conflict feature\r\n1bde9e5 added a conflict feature\r\n6f1c4d9 fourth feature was added\r\n```\r\nwhere `-5` is an option that lets you specify the number of most recent commits you want to see.  (You can use these options together with the other ones listed below).\r\n\r\nTo see all the commits made by one author,\r\n```\r\n$ git log --author=black-shadows\r\n```\r\nTo see all your merges (we will talk about what a merge is later),\r\n```\r\n$ git log --merges\r\n```\r\nTo see the repo history in a visual branching format,\r\n```\r\n$ git log --graph\r\n```\r\nTo see all the other ways of viewing git logs, you can check out the [documentation](http://git-scm.com/docs/git-log).\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## Undo\r\n\r\nOne of the most compelling reasons to use Git is that you can roll back to a previous snapshot (commit) of the repository, in case you've made a mistake.\r\nHowever, reverting back to a specific commit can be really confusing if you've never done it before. Git gives you several ways to do it, and depending on the situation, one way is easier than another.\r\n\r\nFirst, you'll want to identify which commit you want to roll back to.  enter `git log --oneline` and select the first 5-6 digits of the sha_key for the commit you want to return to.\r\nI will be using the sha_key of 184353d9 (you usually only need the first 6-7 digits of your commit).  as the commit key that we want to return to.\r\n\r\n##### Go back and checkout\r\n1. There are no changes that have not been committed.\r\n2. You just want to go back to an older commit, but you don't want to delete all your newer commits.\r\n\r\n```\r\n$ git checkout 184353d9\r\n\r\n# Or \r\n\r\n$ git checkout -b new_branch_name 184353d9\r\n```\r\n\r\n##### Delete everything and just start restart from chosen commit\r\n1. There are no changes that have not been committed.\r\n2. You made a mistake and just need to go back to that commit, erasing everything you have done since then.\r\n\r\n```\r\n$ git reset --hard  184353d9\r\n```\r\n##### Start over from head or master\r\n1. You just made some changes to files for testing ( you do not want to commit ).\r\n2. You have not committed your changes yet.\r\n\r\n```\r\n$ git reset --hard HEAD\r\n```\r\nRemember that HEAD is (almost always) a pointer to the latest commit on that branch.\r\n\r\n##### Ctrl + Z\r\n\r\n1. You have no idea what you did, no idea where you are and you just want to go back\r\n\r\n- The reflog command is the ultimate safety net. It keeps track of everything you just did, from checking out new branches, to rebases, the reflog is essentially a way to move back through time.\r\n\r\n\r\n```\r\n$ git reflog\r\n\r\n# after finding the place you want to go back to \r\n\r\n$ git reset --hard <sha_key>\r\n```\r\n\r\n##### Correcting small mistakes\r\n1. You've already made your commit and you've noticed something small that *should* have been in that commit (usually grammar, stale debug statements or comments).\r\n\r\nThis will allow you to *add* the changes to that most recent commit, as if it was there all along!\r\n```\r\n$ git commit --amend --no-edit\r\n```\r\n\r\nIt's important to note that if you've already pushed the commit before fixing your mistake, you won't be able to push the corrected commit. This is because the remote repo and the local repo have conflicting versions of the same commit.  If you've been working on a branch that *only* you have been working on, you can force the remote repository to accept the corrected commit.  **you should only do this if you know no one else has pulled the *non* corrected commit already**.  This will almost always be the case if you have been working on your own branch!\r\n```\r\n$ git push -f\r\n```\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## Branches\r\n\r\nThe Master branch is the branch that you start in and it's the branch that you should never work directly on. Anytime you want to make changes to the project, you should checkout a different branch. Once you have finished implementing said feature you can then merge your branch into master. This is great because it allows you to organize your features and keep a controlled working version of the app to compare with.\r\n\r\nBranches are a great way to start implementing new features. When you start making a new feature, you first run `git pull` on the master branch to make sure you have all the latest code.\r\n\r\n- You should never be getting a merge error when doing a `git pull`. If you find yourself in this situation that means that you made a few commits on the master branch by accident. Stop the merge and make sure you're on a clean tree, then do this:\r\n\r\n  ```\r\n  $ git checkout -b temp-changes\r\n  $ git reset --hard origin/master\r\n  ```\r\n- All your changes that should not have been on master have been moved to a separate branch (temp-changes). The second line then looks at the remote directory and just sets your local version of the master branch to the same one that is on origin (origin is the name of the remote branch, usually hosted on GitHub).\r\n\r\nTo create a new branch:\r\n```\r\n$ git checkout -b new_branch_name\r\n```\r\nBranch names should be descriptive to what you are trying to do. Their names cannot contain any spaces and its most common to use either `-` or `_` to separate the words\r\n\r\n```\r\n$ git checkout -b getting-live-messages-from-websocket\r\n```\r\nTo see which branch you are currently in:\r\n\r\n```\r\n$ git status\r\n\r\n# Or \r\n\r\n$ git branch\r\n```\r\nTo merge a branch once you are done. We will be merging the `getting-live-messages-from-websocket` branch _into_ master\r\n\r\n```\r\n$ git checkout master\r\n$ git merge getting-live-messages-from-websocket\r\n```\r\n**[⬆ back to top](#overview)**\r\n\r\n## Merging \r\n\r\n##### Merge \r\n```\r\n$ git merge branch_name\r\n```\r\n\r\nThe `git merge` command by itself just puts all the commits into master, as if the branch you made never existed.  We personally recommend using the `--no-ff` (no fast forward) flag.  This will create a commit just for the act of merging your commits.  It will also preserve the fact that those commits were made on a branch.  If you are going to use the `--no-ff` flag, I also recommend using the `--no-edit` flag with it as well.  This will automatically create the commit message for you (something like `Merge branch <branch_name>`)\r\n```\r\n$ git merge add-tests-for-app-version --no-ff --no-edit\r\n```\r\n\r\n* When merging, you are usually on the master branch and merge with your own branch\r\n\r\n##### Rebase\r\n\r\n* When rebasing, you are usually on the branch you are working on.\r\n* Rebase right before you decide merge with master\r\n\r\n```\r\n$ git rebase master\r\n```\r\n_Why Rebase?_, It's a great to make a clean looking tree, it appears as if you never created a branch to begin with. Remember a rebase is simply shifting the commit that your branch branched off of, to be the HEAD of master.\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## Tricks\r\n\r\n### Stripspace\r\n\r\n- Removes trailing whitespace\r\n- Collapse New lines\r\n- Adds new lines to end of file\r\n\r\n  - Simply pass in the file that you want to strip\r\n\r\n  ```bash\r\n  $ git stripspace < text_file.txt\r\n  ```\r\n\r\n### Previous Branch\r\n\r\n- Quickly go back to your last branch\r\n\r\n  ```bash\r\n  $ git checkout - \r\n  ```\r\n\r\n### Clean Status\r\n\r\n- Add `-sb` to get a cleaner `git status`\r\n\r\n  ```bash\r\n  $ git status -sb\r\n  ```\r\n\r\n### Auto Correct\r\n\r\n- Set auto correct to true for Git commands\r\n\r\n  ```bash\r\n  $ git config --global help.autocorrect 1\r\n  ```\r\n\r\n- Results in:\r\n\r\n  ```bash\r\n  $ git comit -m \"commit message\"\r\n  # WARNING: You called a Git command named 'comit', which does not exist.\r\n  # Continuing under the assumption that you meant 'commit'\r\n  # in 0.1 seconds automatically...\r\n  ```\r\n\r\n### Alias\r\n\r\n- Add shortcuts to reduce your typing\r\n\r\n  ```bash\r\n  $ git config --global alias.alias_command git_command\r\n  ```\r\n\r\nExamples:\r\n\r\n- Set `git stat` to `git status -sb`\r\n\r\n  ```bash\r\n  $ git config --global alias.stat 'status -sb'\r\n  ```\r\n\r\n- Combine functions with `&&`\r\n\r\n  ```bash\r\n  $ git config --global alias.ac '!git add -A  && git commit'\r\n  ```\r\n  - The commit messages needs to be entered in from the editor if using the above alias \r\n\r\n## Merge Conflicts\r\n\r\nIf you try and perform a merge, there is a chance that you will end up with a merge conflict. Before we go over how to solve these problems, an important thing to learn is how to back out of the current predicament\r\n\r\n```\r\n$ git merge --abort\r\n# or \r\n$ git rebase --abort\r\n```\r\nTo see which files contain merge conflicts (assuming you haven't backed out yet). Just run:\r\n\r\n```\r\n$ git status\r\n```\r\nThe important thing to remember here is that you have final say as to how the merge conflict is handled. If a co-worker spent hours and days on a feature that conflicted with yours, You can simply overwrite all their hard work. ( But let's try our best not to be so selfish ;) ).\r\n\r\n##### Edit Conflicts\r\n* Happens when two users edit the same lines of a file.\r\n\r\nAfter opening up the file with the conflict you should see\r\n\r\n```\r\n<<<<<<< HEAD\r\ndef function_one\r\n=======\r\ndef function_two\r\n>>>>>>> your_branch\r\n```\r\n`your_branch` is the name of the branch that you are merging, `HEAD` is the latest commit on the branch that you are merging with. Going back to our example, `HEAD` would be, and usually is, the _HEAD_ of the master branch\r\n\r\nAfter correcting the conflict,\r\n```\r\n$ git add .\r\n$ git commit -am \"fixing merge conflicts\"\r\n```\r\n\r\n* If you want to simply take the changes that are in `HEAD`\r\n\r\n```\r\n$ git checkout --theirs <file_name_that_has_merge_conflict>\r\n```\r\n\r\n* If you want to keep your own changes\r\n\r\n```\r\n$ git checkout --yours <file_name_that_has_merge_conflict>\r\n```\r\n\r\n##### Removed files conflict \r\n* One person modified the file, while another deleted the file\r\n\r\nyou actually have two choices here, delete the file, or keep the changes\r\n\r\n1. Keeping the file with new changes\r\n\r\n    Simply add the file back and commit. (let's say the README.md file was modified)\r\n\r\n    ```\r\n    $ git add README.md \r\n    $ git commit \r\n    ```\r\n\r\n2. deleting the file and disregarding the changes\r\n\r\nSimply remove the file and commit:\r\n\r\n```\r\n$ git rm REAMDE.md \r\n$ git commit\r\n```\r\n\r\nIf you had a conflict in the middle of a rebase, after fixing your conflicts run:\r\n\r\n```\r\n$ git add .\r\n$ git rebase --continue\r\n```\r\n**[⬆ back to top](#overview)**\r\n\r\n## Example Workflow\r\n\r\nNow that you've seen all the bits and pieces, it would probably be helpful to see what the workflow with all these different commands looks like.\r\n\r\nThis is the typical situation.  You're working on a project which is being tracked by git.  You want to begin adding a feature or fixing a bug.\r\nBegin by checking out a new branch with a descriptive branch name.  For demo purposes, the branch name will be `fix-readme-grammar`.\r\n```\r\n$ git checkout -b fix-readme-grammar\r\n```\r\n\r\nafter making your changes, review your changes by running\r\n```\r\n$ git status\r\n```\r\nand usually\r\n```\r\n$ git diff\r\n```\r\nThis will allow you to do a last minute review of your changes before deciding to make a new commit\r\n\r\nOnce you're satisfied, add the files to the staging area\r\n```\r\n$ git add -A\r\n```\r\n\r\nNow, create your new commit\r\n```\r\n$ git commit -m \"Restructured commit section.  Fix spelling mistakes for introductory paragraph.\"\r\n```\r\nOf course, you can always combine these by entering `git add -A && git commit -m \"commit message\"`\r\n\r\nNow you'll want to push your changes to the remote repo.  Since it's a new branch, you'll have to tell the remote repo that you want it to start tracking this new branch as well.  You can set up remote tracking and push at the same time by entering\r\n```\r\n$ git push -u origin fix-readme-grammar\r\n```\r\nAfter your first push, you can simply use `git push` for future commits on this branch.\r\n\r\nOnce you've made enough changes, commits, and pushes that you're happy enough to merge it back into master, you'll want to head over to github (or whatever service you're using for your remote repo) to submit a pull request.  Once you've got the OK to merge it back in to master,\r\n```\r\n$ git checkout master\r\n$ git pull\r\n$ git merge fix-readme-grammar --no-ff --no-edit\r\n```\r\n\r\nLastly, you'll want to delete the branches, first on your remote...\r\n```\r\n$ git push origin --delete fix-readme-grammar\r\n```\r\n\r\n...and then on your local machine\r\n```\r\n$ git branch -d fix-readme-grammar\r\n```\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## Remotes\r\n\r\nWe are nearing the GitHub section so it's time to introduce **Remotes**\r\n\r\n- When you use `git init` you just started git version control on that local directory (and child directory). But everything is maintained in your local machine. The concept of a remote is to start keeping a central version of the repository online, usually on a service like Github.\r\n\r\n- First you have to actually create the remote repository, which is very simple to do. Just go on github.com and click the `New Repository` icon the nav bar\r\n\r\n- Github will give you all the needed instructions as to how we move our project into the remote repo \r\n\r\n- By default the name of your repo and all remote repos are set to **origin**. Note that you never have to change this if you don't want to (most people don't) \r\n\r\n##### Push\r\n\r\n- To push a new branch onto the remote repo\r\n\r\n  ```\r\n  $ git push -u <remote\\_repo_name> <branch_name>\r\n  ```\r\n\r\n- Or to make things a little nicer \r\n\r\n  ```\r\n  $ git push -u origin HEAD\r\n  ```\r\n- After that, you can usually just use `git push` to push to the matching branch on remote (though you may to have tell git you want `git push` to only push to the matching branch on the remote `git config --global push.default simple`, more on this [here](http://stackoverflow.com/a/948397/3194316))\r\n\r\n  ```\r\n  $ git push \r\n  ```\r\n- This will push the current branch that you are working on \r\n\r\nThe `-u` is short for `--set-upstream`, which just means that if you ever want to `pull` the remote branch, you simply have to type \r\n`git pull` while you are currently checked out in the local branch.\r\n\r\n**[⬆ back to top](#overview)**\r\n\r\n## GitHub\r\n\r\nGithub is a website that anyone can access and a great way to work on projects with other people. You can also use Github to contribute to open source, a great way to help everyone!\r\n\r\n## Creating a Git Repo\r\n\r\n- Go to the top right of the page and click on the create new button. Then pick `New repository`. \r\n\r\n- pick the name of the repo, the name should be the name for the project that you are working on. For example the name of this repo is\r\n**git-cheat-sheet**\r\n\r\n- You'll want to initialize with a README.md file. The README.md is a file that you want other people to read before looking at your project\r\nFor example, what you are reading right now is a README.md file. If you want to learn about Markdown, which is how you can make things look cool, read here: https://help.github.com/articles/github-flavored-markdown/\r\n\r\n- And that's all! You have just created your remote repository. If you have an existing projects, you can import that project to this repo. If this is just the beginning, you can clone the remote repo to your local machine. \r\n\r\n## Git Clone\r\n\r\n- If you look at the right side of a git repo's main page, you will see its _git clone_ URL. Copy that link to your clipboard, either with just `cmd + c` or by clicking on the clipboard icon. Then go to the local directory you want to clone the project to and run:\r\n\r\n```\r\n$ git clone <clone_link>\r\n\r\n# example\r\n\r\n$ git clone https://github.com/black-shadows/git-cheat-sheet.git\r\n```\r\n\r\n## Reset\r\n\r\nGo back to commit:\r\n`git revert 073791e7dd71b90daa853b2c5acc2c925f02dbc6`\r\n\r\nSoft reset (move HEAD only; neither staging nor working dir is changed):\r\n`git reset --soft 073791e7dd71b90daa853b2c5acc2c925f02dbc6`\r\n\r\nUndo latest commit: `git reset --soft HEAD~ `\r\n\r\nMixed reset (move HEAD and change staging to match repo; does not affect working dir):\r\n`git reset --mixed 073791e7dd71b90daa853b2c5acc2c925f02dbc6`\r\n\r\nHard reset (move HEAD and change staging dir and working dir to match repo):\r\n`git reset --hard 073791e7dd71b90daa853b2c5acc2c925f02dbc6`\r\n\r\n\r\n## Update and Delete\r\n\r\nTest-Delete untracked files:\r\n`git clean -n`\r\n\r\nDelete untracked files (not staging):\r\n`git clean -f`\r\n\r\nUnstage (undo adds):\r\n`git reset HEAD index.html`\r\n\r\nUpdate most recent commit (also update the commit message):\r\n`git commit --amend -m \"New Message\"`\r\n\r\n\r\n## Stash\r\n\r\nPut in stash:\r\n`git stash save \"Message\"`\r\n\r\nShow stash:\r\n`git stash list`\r\n\r\nShow stash stats:\r\n`git stash show stash@{0}`\r\n\r\nShow stash changes:\r\n`git stash show -p stash@{0}`\r\n\r\nUse custom stash item and drop it:\r\n`git stash pop stash@{0}`\r\n\r\nUse custom stash item and do not drop it:\r\n`git stash apply stash@{0}`\r\n\r\nDelete custom stash item:\r\n`git stash drop stash@{0}`\r\n\r\nDelete complete stash:\r\n`git stash clear`\r\n\r\n\r\n## Gitignore\r\n\r\nAbout: https://help.github.com/articles/ignoring-files\r\n\r\nUseful templates: https://github.com/github/gitignore\r\n\r\nAdd or edit gitignore: \r\n`nano .gitignore`\r\n\r\nTrack empty dir: \r\n`touch dir/.gitkeep`\r\n\r\n\r\n## Compare\r\n\r\nCompare modified files:\r\n`git diff`\r\n\r\nCompare modified files and highlight changes only:\r\n`git diff --color-words index.html`\r\n\r\nCompare modified files within the staging area:\r\n`git diff --staged`\r\n\r\nCompare branches:\r\n`git diff master..branchname`\r\n\r\nCompare branches like above:\r\n`git diff --color-words master..branchname^`\r\n\r\nCompare commits:\r\n`git diff 6eb715d`\r\n`git diff 6eb715d..HEAD`\r\n`git diff 6eb715d..537a09f`\r\n\r\nCompare commits of file:\r\n`git diff 6eb715d index.html`\r\n`git diff 6eb715d..537a09f index.html`\r\n\r\nCompare without caring about spaces:\r\n`git diff -b 6eb715d..HEAD` or:\r\n`git diff --ignore-space-change 6eb715d..HEAD`\r\n\r\nCompare without caring about all spaces:\r\n`git diff -w 6eb715d..HEAD` or:\r\n`git diff --ignore-all-space 6eb715d..HEAD`\r\n\r\nUseful comparings:\r\n`git diff --stat --summary 6eb715d..HEAD`\r\n\r\nBlame:\r\n`git blame -L10,+1 index.html`\r\n\r\n\r\n## Version Tags\r\n\r\nShow all released versions:\r\n`git tag`\r\n\r\nShow all released versions with comments:\r\n`git tag -l -n1`\r\n\r\nCreate release version:\r\n`git tag v1.0.0`\r\n\r\nCreate release version with comment:\r\n`git tag -a v1.0.0 -m 'Message'`\r\n\r\nCheckout a specific release version:\r\n`git checkout v1.0.0`\r\n\r\n\r\n## Collaborate\r\n\r\nShow remote:\r\n`git remote`\r\n\r\nShow remote details:\r\n`git remote -v`\r\n\r\nAdd remote upstream from GitHub project:\r\n`git remote add upstream https://github.com/user/project.git`\r\n\r\nAdd remote upstream from existing empty project on server:\r\n`git remote add upstream ssh://root@123.123.123.123/path/to/repository/.git`\r\n\r\nFetch:\r\n`git fetch upstream`\r\n\r\nFetch a custom branch:\r\n`git fetch upstream branchname:local_branchname`\r\n\r\nMerge fetched commits:\r\n`git merge upstream/master`\r\n\r\nRemove origin:\r\n`git remote rm origin`\r\n\r\nShow remote branches:\r\n`git branch -r`\r\n\r\nShow all branches:\r\n`git branch -a`\r\n\r\nCreate and checkout branch from a remote branch:\r\n`git checkout -b local_branchname upstream/remote_branchname`\r\n\r\nCompare:\r\n`git diff origin/master..master`\r\n\r\nPush (set default with `-u`):\r\n`git push -u origin master`\r\n\r\nPush:\r\n`git push origin master`\r\n\r\nForce-Push:\r\n`git push origin master --force\r\n\r\nPull:\r\n`git pull`\r\n\r\nPull specific branch:\r\n`git pull origin branchname`\r\n\r\nFetch a pull request on GitHub by its ID and create a new branch:\r\n`git fetch upstream pull/ID/head:new-pr-branch`\r\n\r\nClone to localhost:\r\n`git clone https://github.com/user/project.git` or:\r\n`git clone ssh://user@domain.com/~/dir/.git`\r\n\r\nClone to localhost folder:\r\n`git clone https://github.com/user/project.git ~/dir/folder`\r\n\r\nClone specific branch to localhost:\r\n`git clone -b branchname https://github.com/user/project.git`\r\n\r\nDelete remote branch (push nothing):\r\n`git push origin :branchname` or:\r\n`git push origin --delete branchname`\r\n\r\n\r\n## Archive\r\n\r\nCreate a zip-archive: `git archive --format zip --output filename.zip master`\r\n\r\nExport/write custom log to a file: `git log --author=sven --all > log.txt`\r\n\r\n\r\n## Troubleshooting\r\n\r\nIgnore files that have already been committed to a Git repository: http://stackoverflow.com/a/1139797/1815847\r\n\r\n\r\n## Security\r\n\r\nHide Git on the web via `.htaccess`: `RedirectMatch 404 /\\.git` \r\n(more info here: http://stackoverflow.com/a/17916515/1815847)\r\n\r\n\r\n## Large File Storage\r\n\r\nWebsite: https://git-lfs.github.com/\r\n\r\nInstall: `brew install git-lfs`\r\n\r\nTrack `*.psd` files: `git lfs track \"*.psd\"` (init, add, commit and push as written above)"
  },
  {
    "path": "Golang/README.md",
    "content": "# Go Cheat Sheet\r\n\r\n# Index\r\n1. [Basic Syntax](#basic-syntax)\r\n2. [Operators](#operators)\r\n    * [Arithmetic](#arithmetic)\r\n    * [Comparison](#comparison)\r\n    * [Logical](#logical)\r\n    * [Other](#other)\r\n3. [Declarations](#declarations)\r\n4. [Functions](#functions)\r\n    * [Functions as values and closures](#functions-as-values-and-closures)\r\n    * [Variadic Functions](#variadic-functions)\r\n5. [Built-in Types](#built-in-types)\r\n6. [Type Conversions](#type-conversions)\r\n7. [Packages](#packages)\r\n8. [Control structures](#control-structures)\r\n    * [If](#if)\r\n    * [Loops](#loops)\r\n    * [Switch](#switch)\r\n9. [Arrays, Slices, Ranges](#arrays-slices-ranges)\r\n    * [Arrays](#arrays)\r\n    * [Slices](#slices)\r\n    * [Operations on Arrays and Slices](#operations-on-arrays-and-slices)\r\n10. [Maps](#maps)\r\n11. [Structs](#structs)\r\n12. [Pointers](#pointers)\r\n13. [Interfaces](#interfaces)\r\n14. [Embedding](#embedding)\r\n15. [Errors](#errors)\r\n16. [Concurrency](#concurrency)\r\n    * [Goroutines](#goroutines)\r\n    * [Channels](#channels)\r\n    * [Channel Axioms](#channel-axioms)\r\n17. [Printing](#printing)\r\n18. [Reflection](#reflection)\r\n    * [Type Switch](#type-switch)\r\n    * [Examples](https://github.com/a8m/reflect-examples)\r\n19. [Snippets](#snippets)\r\n    * [Http-Server](#http-server)\r\n\r\n## Credits\r\n\r\nMost example code taken from [A Tour of Go](http://tour.golang.org/), which is an excellent introduction to Go.\r\nIf you're new to Go, do that tour. Seriously.\r\n\r\n## Go in a Nutshell\r\n\r\n* Imperative language\r\n* Statically typed\r\n* Syntax tokens similar to C (but less parentheses and no semicolons) and the structure to Oberon-2\r\n* Compiles to native code (no JVM)\r\n* No classes, but structs with methods\r\n* Interfaces\r\n* No implementation inheritance. There's [type embedding](http://golang.org/doc/effective%5Fgo.html#embedding), though.\r\n* Functions are first class citizens\r\n* Functions can return multiple values\r\n* Has closures\r\n* Pointers, but not pointer arithmetic\r\n* Built-in concurrency primitives: Goroutines and Channels\r\n\r\n# Basic Syntax\r\n\r\n## Hello World\r\nFile `hello.go`:\r\n```go\r\npackage main\r\n\r\nimport \"fmt\"\r\n\r\nfunc main() {\r\n    fmt.Println(\"Hello Go\")\r\n}\r\n```\r\n`$ go run hello.go`\r\n\r\n## Operators\r\n### Arithmetic\r\n|Operator|Description|\r\n|--------|-----------|\r\n|`+`|addition|\r\n|`-`|subtraction|\r\n|`*`|multiplication|\r\n|`/`|quotient|\r\n|`%`|remainder|\r\n|`&`|bitwise and|\r\n|`\\|`|bitwise or|\r\n|`^`|bitwise xor|\r\n|`&^`|bit clear (and not)|\r\n|`<<`|left shift|\r\n|`>>`|right shift|\r\n\r\n### Comparison\r\n|Operator|Description|\r\n|--------|-----------|\r\n|`==`|equal|\r\n|`!=`|not equal|\r\n|`<`|less than|\r\n|`<=`|less than or equal|\r\n|`>`|greater than|\r\n|`>=`|greater than or equal|\r\n\r\n### Logical\r\n|Operator|Description|\r\n|--------|-----------|\r\n|`&&`|logical and|\r\n|`\\|\\|`|logical or|\r\n|`!`|logical not|\r\n\r\n### Other\r\n|Operator|Description|\r\n|--------|-----------|\r\n|`&`|address of / create pointer|\r\n|`*`|dereference pointer|\r\n|`<-`|send / receive operator (see 'Channels' below)|\r\n\r\n## Declarations\r\nType goes after identifier!\r\n```go\r\nvar foo int // declaration without initialization\r\nvar foo int = 42 // declaration with initialization\r\nvar foo, bar int = 42, 1302 // declare and init multiple vars at once\r\nvar foo = 42 // type omitted, will be inferred\r\nfoo := 42 // shorthand, only in func bodies, omit var keyword, type is always implicit\r\nconst constant = \"This is a constant\"\r\n```\r\n\r\n## Functions\r\n```go\r\n// a simple function\r\nfunc functionName() {}\r\n\r\n// function with parameters (again, types go after identifiers)\r\nfunc functionName(param1 string, param2 int) {}\r\n\r\n// multiple parameters of the same type\r\nfunc functionName(param1, param2 int) {}\r\n\r\n// return type declaration\r\nfunc functionName() int {\r\n    return 42\r\n}\r\n\r\n// Can return multiple values at once\r\nfunc returnMulti() (int, string) {\r\n    return 42, \"foobar\"\r\n}\r\nvar x, str = returnMulti()\r\n\r\n// Return multiple named results simply by return\r\nfunc returnMulti2() (n int, s string) {\r\n    n = 42\r\n    s = \"foobar\"\r\n    // n and s will be returned\r\n    return\r\n}\r\nvar x, str = returnMulti2()\r\n\r\n```\r\n\r\n### Functions As Values And Closures\r\n```go\r\nfunc main() {\r\n    // assign a function to a name\r\n    add := func(a, b int) int {\r\n        return a + b\r\n    }\r\n    // use the name to call the function\r\n    fmt.Println(add(3, 4))\r\n}\r\n\r\n// Closures, lexically scoped: Functions can access values that were\r\n// in scope when defining the function\r\nfunc scope() func() int{\r\n    outer_var := 2\r\n    foo := func() int { return outer_var}\r\n    return foo\r\n}\r\n\r\nfunc another_scope() func() int{\r\n    // won't compile because outer_var and foo not defined in this scope\r\n    outer_var = 444\r\n    return foo\r\n}\r\n\r\n\r\n// Closures\r\nfunc outer() (func() int, int) {\r\n    outer_var := 2\r\n    inner := func() int {\r\n        outer_var += 99 // outer_var from outer scope is mutated.\r\n        return outer_var\r\n    }\r\n    inner()\r\n    return inner, outer_var // return inner func and mutated outer_var 101\r\n}\r\n```\r\n\r\n### Variadic Functions\r\n```go\r\nfunc main() {\r\n\tfmt.Println(adder(1, 2, 3)) \t// 6\r\n\tfmt.Println(adder(9, 9))\t// 18\r\n\r\n\tnums := []int{10, 20, 30}\r\n\tfmt.Println(adder(nums...))\t// 60\r\n}\r\n\r\n// By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters.\r\n// The function is invoked like any other function except we can pass as many arguments as we want.\r\nfunc adder(args ...int) int {\r\n\ttotal := 0\r\n\tfor _, v := range args { // Iterates over the arguments whatever the number.\r\n\t\ttotal += v\r\n\t}\r\n\treturn total\r\n}\r\n```\r\n\r\n## Built-in Types\r\n```\r\nbool\r\n\r\nstring\r\n\r\nint  int8  int16  int32  int64\r\nuint uint8 uint16 uint32 uint64 uintptr\r\n\r\nbyte // alias for uint8\r\n\r\nrune // alias for int32 ~= a character (Unicode code point) - very Viking\r\n\r\nfloat32 float64\r\n\r\ncomplex64 complex128\r\n```\r\n\r\n## Type Conversions\r\n```go\r\nvar i int = 42\r\nvar f float64 = float64(i)\r\nvar u uint = uint(f)\r\n\r\n// alternative syntax\r\ni := 42\r\nf := float64(i)\r\nu := uint(f)\r\n```\r\n\r\n## Packages\r\n* Package declaration at top of every source file\r\n* Executables are in package `main`\r\n* Convention: package name == last name of import path (import path `math/rand` => package `rand`)\r\n* Upper case identifier: exported (visible from other packages)\r\n* Lower case identifier: private (not visible from other packages)\r\n\r\n## Control structures\r\n\r\n### If\r\n```go\r\nfunc main() {\r\n\t// Basic one\r\n\tif x > 0 {\r\n\t\treturn x\r\n\t} else {\r\n\t\treturn -x\r\n\t}\r\n\r\n\t// You can put one statement before the condition\r\n\tif a := b + c; a < 42 {\r\n\t\treturn a\r\n\t} else {\r\n\t\treturn a - 42\r\n\t}\r\n\r\n\t// Type assertion inside if\r\n\tvar val interface{}\r\n\tval = \"foo\"\r\n\tif str, ok := val.(string); ok {\r\n\t\tfmt.Println(str)\r\n\t}\r\n}\r\n```\r\n\r\n### Loops\r\n```go\r\n    // There's only `for`, no `while`, no `until`\r\n    for i := 1; i < 10; i++ {\r\n    }\r\n    for ; i < 10;  { // while - loop\r\n    }\r\n    for i < 10  { // you can omit semicolons if there is only a condition\r\n    }\r\n    for { // you can omit the condition ~ while (true)\r\n    }\r\n```\r\n\r\n### Switch\r\n```go\r\n    // switch statement\r\n    switch operatingSystem {\r\n    case \"darwin\":\r\n        fmt.Println(\"Mac OS Hipster\")\r\n        // cases break automatically, no fallthrough by default\r\n    case \"linux\":\r\n        fmt.Println(\"Linux Geek\")\r\n    default:\r\n        // Windows, BSD, ...\r\n        fmt.Println(\"Other\")\r\n    }\r\n\r\n    // as with for and if, you can have an assignment statement before the switch value\r\n    switch os := runtime.GOOS; os {\r\n    case \"darwin\": ...\r\n    }\r\n\r\n    // you can also make comparisons in switch cases\r\n    number := 42\r\n    switch {\r\n        case number < 42:\r\n            fmt.Println(\"Smaller\")\r\n        case number == 42:\r\n            fmt.Println(\"Equal\")\r\n        case number > 42:\r\n            fmt.Println(\"Greater\")\r\n    }\r\n\r\n    // cases can be presented in comma-separated lists\r\n    var char byte = '?'\r\n    switch char {\r\n        case ' ', '?', '&', '=', '#', '+', '%':\r\n            fmt.Println(\"Should escape\")\r\n    }\r\n```\r\n\r\n## Arrays, Slices, Ranges\r\n\r\n### Arrays\r\n```go\r\nvar a [10]int // declare an int array with length 10. Array length is part of the type!\r\na[3] = 42     // set elements\r\ni := a[3]     // read elements\r\n\r\n// declare and initialize\r\nvar a = [2]int{1, 2}\r\na := [2]int{1, 2} //shorthand\r\na := [...]int{1, 2} // elipsis -> Compiler figures out array length\r\n```\r\n\r\n### Slices\r\n```go\r\nvar a []int                              // declare a slice - similar to an array, but length is unspecified\r\nvar a = []int {1, 2, 3, 4}               // declare and initialize a slice (backed by the array given implicitly)\r\na := []int{1, 2, 3, 4}                   // shorthand\r\nchars := []string{0:\"a\", 2:\"c\", 1: \"b\"}  // [\"a\", \"b\", \"c\"]\r\n\r\nvar b = a[lo:hi]\t// creates a slice (view of the array) from index lo to hi-1\r\nvar b = a[1:4]\t\t// slice from index 1 to 3\r\nvar b = a[:3]\t\t// missing low index implies 0\r\nvar b = a[3:]\t\t// missing high index implies len(a)\r\na =  append(a,17,3)\t// append items to slice a\r\nc := append(a,b...)\t// concatenate slices a and b\r\n\r\n// create a slice with make\r\na = make([]byte, 5, 5)\t// first arg length, second capacity\r\na = make([]byte, 5)\t// capacity is optional\r\n\r\n// create a slice from an array\r\nx := [3]string{\"Лайка\", \"Белка\", \"Стрелка\"}\r\ns := x[:] // a slice referencing the storage of x\r\n```\r\n\r\n### Operations on Arrays and Slices\r\n`len(a)` gives you the length of an array/a slice. It's a built-in function, not a attribute/method on the array.\r\n\r\n```go\r\n// loop over an array/a slice\r\nfor i, e := range a {\r\n    // i is the index, e the element\r\n}\r\n\r\n// if you only need e:\r\nfor _, e := range a {\r\n    // e is the element\r\n}\r\n\r\n// ...and if you only need the index\r\nfor i := range a {\r\n}\r\n\r\n// In Go pre-1.4, you'll get a compiler error if you're not using i and e.\r\n// Go 1.4 introduced a variable-free form, so that you can do this\r\nfor range time.Tick(time.Second) {\r\n    // do it once a sec\r\n}\r\n\r\n```\r\n\r\n## Maps\r\n\r\n```go\r\nvar m map[string]int\r\nm = make(map[string]int)\r\nm[\"key\"] = 42\r\nfmt.Println(m[\"key\"])\r\n\r\ndelete(m, \"key\")\r\n\r\nelem, ok := m[\"key\"] // test if key \"key\" is present and retrieve it, if so\r\n\r\n// map literal\r\nvar m = map[string]Vertex{\r\n    \"Bell Labs\": {40.68433, -74.39967},\r\n    \"Google\":    {37.42202, -122.08408},\r\n}\r\n\r\n```\r\n\r\n## Structs\r\n\r\nThere are no classes, only structs. Structs can have methods.\r\n```go\r\n// A struct is a type. It's also a collection of fields\r\n\r\n// Declaration\r\ntype Vertex struct {\r\n    X, Y int\r\n}\r\n\r\n// Creating\r\nvar v = Vertex{1, 2}\r\nvar v = Vertex{X: 1, Y: 2} // Creates a struct by defining values with keys\r\nvar v = []Vertex{{1,2},{5,2},{5,5}} // Initialize a slice of structs\r\n\r\n// Accessing members\r\nv.X = 4\r\n\r\n// You can declare methods on structs. The struct you want to declare the\r\n// method on (the receiving type) comes between the the func keyword and\r\n// the method name. The struct is copied on each method call(!)\r\nfunc (v Vertex) Abs() float64 {\r\n    return math.Sqrt(v.X*v.X + v.Y*v.Y)\r\n}\r\n\r\n// Call method\r\nv.Abs()\r\n\r\n// For mutating methods, you need to use a pointer (see below) to the Struct\r\n// as the type. With this, the struct value is not copied for the method call.\r\nfunc (v *Vertex) add(n float64) {\r\n    v.X += n\r\n    v.Y += n\r\n}\r\n\r\n```\r\n**Anonymous structs:**\r\nCheaper and safer than using `map[string]interface{}`.\r\n```go\r\npoint := struct {\r\n\tX, Y int\r\n}{1, 2}\r\n```\r\n\r\n## Pointers\r\n```go\r\np := Vertex{1, 2}  // p is a Vertex\r\nq := &p            // q is a pointer to a Vertex\r\nr := &Vertex{1, 2} // r is also a pointer to a Vertex\r\n\r\n// The type of a pointer to a Vertex is *Vertex\r\n\r\nvar s *Vertex = new(Vertex) // new creates a pointer to a new struct instance\r\n```\r\n\r\n## Interfaces\r\n```go\r\n// interface declaration\r\ntype Awesomizer interface {\r\n    Awesomize() string\r\n}\r\n\r\n// types do *not* declare to implement interfaces\r\ntype Foo struct {}\r\n\r\n// instead, types implicitly satisfy an interface if they implement all required methods\r\nfunc (foo Foo) Awesomize() string {\r\n    return \"Awesome!\"\r\n}\r\n```\r\n\r\n## Embedding\r\n\r\nThere is no subclassing in Go. Instead, there is interface and struct embedding.\r\n\r\n```go\r\n// ReadWriter implementations must satisfy both Reader and Writer\r\ntype ReadWriter interface {\r\n    Reader\r\n    Writer\r\n}\r\n\r\n// Server exposes all the methods that Logger has\r\ntype Server struct {\r\n    Host string\r\n    Port int\r\n    *log.Logger\r\n}\r\n\r\n// initialize the embedded type the usual way\r\nserver := &Server{\"localhost\", 80, log.New(...)}\r\n\r\n// methods implemented on the embedded struct are passed through\r\nserver.Log(...) // calls server.Logger.Log(...)\r\n\r\n// the field name of the embedded type is its type name (in this case Logger)\r\nvar logger *log.Logger = server.Logger\r\n```\r\n\r\n## Errors\r\nThere is no exception handling. Functions that might produce an error just declare an additional return value of type `Error`. This is the `Error` interface:\r\n```go\r\ntype error interface {\r\n    Error() string\r\n}\r\n```\r\n\r\nA function that might return an error:\r\n```go\r\nfunc doStuff() (int, error) {\r\n}\r\n\r\nfunc main() {\r\n    result, err := doStuff()\r\n    if err != nil {\r\n        // handle error\r\n    } else {\r\n        // all is good, use result\r\n    }\r\n}\r\n```\r\n\r\n# Concurrency\r\n\r\n## Goroutines\r\nGoroutines are lightweight threads (managed by Go, not OS threads). `go f(a, b)` starts a new goroutine which runs `f` (given `f` is a function).\r\n\r\n```go\r\n// just a function (which can be later started as a goroutine)\r\nfunc doStuff(s string) {\r\n}\r\n\r\nfunc main() {\r\n    // using a named function in a goroutine\r\n    go doStuff(\"foobar\")\r\n\r\n    // using an anonymous inner function in a goroutine\r\n    go func (x int) {\r\n        // function body goes here\r\n    }(42)\r\n}\r\n```\r\n\r\n## Channels\r\n```go\r\nch := make(chan int) // create a channel of type int\r\nch <- 42             // Send a value to the channel ch.\r\nv := <-ch            // Receive a value from ch\r\n\r\n// Non-buffered channels block. Read blocks when no value is available, write blocks until there is a read.\r\n\r\n// Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.\r\nch := make(chan int, 100)\r\n\r\nclose(ch) // closes the channel (only sender should close)\r\n\r\n// read from channel and test if it has been closed\r\nv, ok := <-ch\r\n\r\n// if ok is false, channel has been closed\r\n\r\n// Read from channel until it is closed\r\nfor i := range ch {\r\n    fmt.Println(i)\r\n}\r\n\r\n// select blocks on multiple channel operations, if one unblocks, the corresponding case is executed\r\nfunc doStuff(channelOut, channelIn chan int) {\r\n    select {\r\n    case channelOut <- 42:\r\n        fmt.Println(\"We could write to channelOut!\")\r\n    case x := <- channelIn:\r\n        fmt.Println(\"We could read from channelIn\")\r\n    case <-time.After(time.Second * 1):\r\n        fmt.Println(\"timeout\")\r\n    }\r\n}\r\n```\r\n\r\n### Channel Axioms\r\n- A send to a nil channel blocks forever\r\n\r\n  ```go\r\n  var c chan string\r\n  c <- \"Hello, World!\"\r\n  // fatal error: all goroutines are asleep - deadlock!\r\n  ```\r\n- A receive from a nil channel blocks forever\r\n\r\n  ```go\r\n  var c chan string\r\n  fmt.Println(<-c)\r\n  // fatal error: all goroutines are asleep - deadlock!\r\n  ```\r\n- A send to a closed channel panics\r\n\r\n  ```go\r\n  var c = make(chan string, 1)\r\n  c <- \"Hello, World!\"\r\n  close(c)\r\n  c <- \"Hello, Panic!\"\r\n  // panic: send on closed channel\r\n  ```\r\n- A receive from a closed channel returns the zero value immediately\r\n\r\n  ```go\r\n  var c = make(chan int, 2)\r\n  c <- 1\r\n  c <- 2\r\n  close(c)\r\n  for i := 0; i < 3; i++ {\r\n      fmt.Printf(\"%d \", <-c)\r\n  }\r\n  // 1 2 0\r\n  ```\r\n\r\n## Printing\r\n\r\n```go\r\nfmt.Println(\"Hello, 你好, नमस्ते, Привет, ᎣᏏᏲ\") // basic print, plus newline\r\np := struct { X, Y int }{ 17, 2 }\r\nfmt.Println( \"My point:\", p, \"x coord=\", p.X ) // print structs, ints, etc\r\ns := fmt.Sprintln( \"My point:\", p, \"x coord=\", p.X ) // print to string variable\r\n\r\nfmt.Printf(\"%d hex:%x bin:%b fp:%f sci:%e\",17,17,17,17.0,17.0) // c-ish format\r\ns2 := fmt.Sprintf( \"%d %f\", 17, 17.0 ) // formatted print to string variable\r\n\r\nhellomsg := `\r\n \"Hello\" in Chinese is 你好 ('Ni Hao')\r\n \"Hello\" in Hindi is नमस्ते ('Namaste')\r\n` // multi-line string literal, using back-tick at beginning and end\r\n```\r\n\r\n## Reflection\r\n### Type Switch\r\nA type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.\r\n```go\r\nfunc do(i interface{}) {\r\n\tswitch v := i.(type) {\r\n\tcase int:\r\n\t\tfmt.Printf(\"Twice %v is %v\\n\", v, v*2)\r\n\tcase string:\r\n\t\tfmt.Printf(\"%q is %v bytes long\\n\", v, len(v))\r\n\tdefault:\r\n\t\tfmt.Printf(\"I don't know about type %T!\\n\", v)\r\n\t}\r\n}\r\n\r\nfunc main() {\r\n\tdo(21)\r\n\tdo(\"hello\")\r\n\tdo(true)\r\n}\r\n```\r\n\r\n# Snippets\r\n\r\n## HTTP Server\r\n```go\r\npackage main\r\n\r\nimport (\r\n    \"fmt\"\r\n    \"net/http\"\r\n)\r\n\r\n// define a type for the response\r\ntype Hello struct{}\r\n\r\n// let that type implement the ServeHTTP method (defined in interface http.Handler)\r\nfunc (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {\r\n    fmt.Fprint(w, \"Hello!\")\r\n}\r\n\r\nfunc main() {\r\n    var h Hello\r\n    http.ListenAndServe(\"localhost:4000\", h)\r\n}\r\n\r\n// Here's the method signature of http.ServeHTTP:\r\n// type Handler interface {\r\n//     ServeHTTP(w http.ResponseWriter, r *http.Request)\r\n// }\r\n```\r\n\r\n\r\n"
  },
  {
    "path": "Java/README.md",
    "content": "# Java Cheat Sheet\r\nReview Java 9 Concepts at Jet Speed.\r\n\r\n### Complete Java Course\r\n- https://www.udemy.com/java-programming-tutorial-for-beginners/\r\n\r\n## Introduction\r\n\r\n## Background\r\n\r\n### Popularity of Java\r\n- Platform Independent or Portable\r\n- Object Oriented Language\r\n- Security \r\n- Rich API\r\n- Great IDE's\r\n- Omnipresent \r\n   - Web Applications (Java EE (JSP, Servlets), Spring, Struts..)\r\n   - Mobile Apps(Android) \r\n   - Microservices (Spring Boot)\r\n\r\n### Platform Independence\r\n- Build once, run anywhere\r\n![alt text](images/java-write-once-run-anywhere.png)\r\n- Java bytecode is the instruction set of the Java virtual machine\r\n\r\n\r\n```\r\ngraph TD\r\nA[Java Code] -->|Compiled| B(Bytecode)\r\nB --> C{Run}\r\nC -->|bytecode| D[Windows JVM] \r\nD --> K[Windows Instructions]\r\nC -->|bytecode| E[Unix  JVM]\r\nE --> L[Unix Instructions]\r\nC -->|bytecode| F[Linux  JVM]\r\nF --> M[Linux Instructions]\r\nC -->|bytecode| G[Any other platform  JVM]\r\nG --> N[Linux Instructions]\r\n```\r\n\r\n### JDK vs JVM VS JRE\r\n\r\n- JVM (Java Virtual Machine)\r\n  - runs the Java bytecode.\r\n- JRE\r\n  - JVM + Libraries + Other Components (to run applets and other java applications)\r\n- JDK\r\n  - JRE + Compilers + Debuggers\r\n\r\n### ClassLoader\r\n\r\n- Find and Loads Java Classes!\r\n\r\nThree Types\r\n- System Class Loader - Loads all application classes from CLASSPATH\r\n- Extension Class Loader - Loads all classes from extension directory\r\n- Bootstrap Class Loader - Loads all the Java core files\r\n\r\nOrder of execution of ClassLoaders\r\n- JVM needs to find a class, it starts with System Class Loader. \r\n- If it is not found, it checks with Extension Class Loader. \r\n- If it not found, it goes to the Bootstrap Class Loader. \r\n- If a class is still not found, a ClassNotFoundException is thrown.\r\n\r\n### First Java Program\r\n\r\n```java\r\npublic class HelloWorld {\r\n    public static void main(String[] args) {\r\nSystem.out.println(\"Hello World\");\r\n    }\r\n\r\n}\r\n```\r\n\r\nNotes\r\n- Every line of code we write in Java is part of something called Class. We will talk about Class later. \r\n- First line defines a public class called HelloWorld. All the code in a class is between { and }.\r\n- When a program runs, Java should know which line of code has to be run first. public static void main(String[] args) is the first method that is run when a program is executed.\r\n\r\n\r\n> Java, like any other programming language, is particular about syntax!!\r\n\r\n\r\n### Using Java and JavaC\r\nThere are two steps involved in running a Java Program\r\n- Compilation\r\n- Execution\r\n\r\n#### Compilation\r\nWe use javac to compile java code. \r\n- Open CommandPrompt/Terminal and cd to the folder where HelloWorld.java file is present\r\n- execute the command below\r\n```\r\njavac HelloWorld.java\r\n```\r\n- You should see two files HelloWorld.java and HelloWorld.class in the folder.\r\n- HelloWorld.class contains the java bytecode\r\n\r\n#### Execution\r\n- Now we can run the program using JVM\r\n- execute the command below\r\n```\r\njava HelloWorld\r\n```\r\n- You should see the output \"Hello World\" printed in the console.\r\n\r\n### Class and Object\r\n- What is a class?\r\n- Definining an instance of a class - an object\r\n- Invoking a method on the object\r\n\r\n### Variables\r\n- Value of a variable changes during the course of a program execution.\r\n\r\n```\r\nint number;\r\nnumber = 5;\r\nSystem.out.println(number);//5\r\nnumber = number + 2;\r\nSystem.out.println(number);//7\r\nnumber = number + 2;\r\nSystem.out.println(number);//9\r\n```\r\n\r\nDeclaring and Initializing Variables\r\n- Declaration is give a variable a name and type\r\n\r\n```\r\nTYPE variableName;\r\n```\r\n\r\n#### Tips\r\n- Two or more variables of single type can be declared together.\r\n- All six numeric types in Java are signed.\r\n\r\n### Primitive Variables\r\n\r\nVariables that store value.\r\n\r\n\r\nJava defines few types like int (numbers), float(floating point numbers), char (characters). Variables of these types store the value of the variable directly. These are not objects. These are called primitive variables. \r\n\r\nAn example is shown below: Primitive Variables contains bits representing the value of the variable.\r\n\r\n```\r\nint value = 5;\r\n\r\n```\r\nDifferent primitive types in java are char, boolean, byte, short, int, long, double, or float. Because of these primitive types, Java is NOT considered to be a pure objected oriented language.\r\n\r\nNumeric Data Types\r\n- Types  : byte, short, int, long, float, double\r\n- Number of bits : 8, 16, 32, 64, 32, 64\r\n- Range  : -x to x-1 where x = Power(2, number of bits -1)\r\n\r\nchar Data Type\r\n- Used to store characters. Size of character is 16 bits.\r\n\r\nExamples\r\n\r\n```\r\nint i = 15;\r\nlong longValue = 1000000000000l;\r\nbyte b = (byte)254;\r\n\r\nfloat f = 26.012f;\r\ndouble d = 123.567;\r\nboolean isDone = true;\r\nboolean isGood = false;\r\nchar ch = 'a';\r\nchar ch2 = ';';\r\n```\r\n\r\n### Reference Variables\r\n\r\n```\r\nAnimal dog = new Animal();\r\n```\r\n\r\nThe instance of new Animal - Animal object - is created in memory. The memory address of the object created is stored in the dog reference variable.\r\n\r\nReference Variables contains a reference or a guide to get to the actual object in memory.\r\n\r\n#### Puzzles\r\n\r\n```\r\nAnimal dog1 = new Animal();\r\ndog1 = new Animal();\r\n```\r\n\r\nWhat will happen?\r\nTwo objects of type Animal are created. Only one reference variable is created.\r\n\r\n\r\n```\r\nAnimal animal1 = new Animal();\r\nAnimal animal2 = new Animal();\r\nanimal1 = animal2;\r\n\r\n```\r\n\r\nWhat will happen? What would happen if the same was done with primitive variables?\r\n\r\n### Identifiers\r\nNames given to a class, method, interface, variables are called identifiers.\r\n\r\nLegal Identifier Names\r\n- Combination of letters, numbers, $ and under-score(_)\r\n- Cannot start with a number\r\n- Cannot be a keyword\r\n- No limit on length of identifier\r\n\r\n### Java Keywords\r\nList of Java Keywords\r\n- Primitives DataTypes    : byte,short,int,long,float,double,char,boolean\r\n- Flow Control    : if, else,for,do, while, switch, case, default, break,\r\n      continue,return\r\n- Exception Handling      : try, catch, finally,throw,throws,assert\r\n- Modifiers       : public,private,protected,final,static,native,abstract,\r\n      synchronized,transient,volatile,strictfp\r\n- Class Related   : class,interface,package,extends,implements,import\r\n- Object Related  : new, instanceof,super,this\r\n- Literals    : true, false, null\r\n- Others      : void, enum\r\n- Unused  : goto,const\r\n\r\n### Literals\r\nAny primitive data type value in source code is called Literal.\r\n\r\nThere are four types of literals:\r\n- Integer & Long\r\n- Floating Point\r\n- Boolean\r\n- Double\r\n\r\n#### Literals\r\n\r\nInteger Literals\r\n- There are 3 ways of representing an Integer Literal. \r\n  - Decimal. Examples: 343, 545\r\n  - Octal. Digits 0 to 7. Place 0 before a number. Examples : 070,011\r\n  - Hexadecimal. Digits 0 to 9 and alphabets A to F (10-15). Case insensitive.\r\n- An integer literal by default is int.\r\n\r\nLong Literals \r\n- All 3 integer formats: Decimal, Octal and Hexadecimal can be used to represent long by appending with L or l.\r\n\r\nFloating point Literals\r\n- Numbers with decimal points. Example: ```double d = 123.456;```\r\n- To declare a float, append f. Example: float f = 123.456f;\r\n- Floating point literals are double by default.\r\n- Appending d or D at end of double literal is optional Example: ```double d = 123.456D;```\r\n\r\nBoolean Literals\r\n- Valid boolean values are true and false. \r\n- TRUE, FALSE or True, False are invalid.\r\n\r\nCharacter Literals\r\n- Represented by single character between single quotes  Example: ```char a = 'a'```\r\n- Unicode Representation also can be used. Prefix with \\u. Example: char letterA = '\\u0041';\r\n- A number value can also be assigned to character. Example: char letterB = 66; Numeric value can be from 0 to 65535;\r\n- Escape code can be used to represent a character that cannot be typed as literal. Example: char newLine = '\\n';\r\n\r\n#### Puzzles \r\n\r\n```\r\nint eight = 010; \r\nint nine=011;  \r\nint invalid = 089;//COMPILER ERROR! 8 and 9 are invalid in Octal\r\nint sixteen = 0x10; \r\nint fifteen = 0XF; \r\nint fourteen = 0xe;\r\nint x = 23,000;\r\nlong a = 123456789l; \r\nlong b = 0x9ABCDEFGHL; \r\nlong c = 0123456789L;\r\n\r\nfloat f = 123.456;//COMPILER ERROR! A double value cannot be assigned to a float.\r\n\r\nboolean b = true; boolean b=false;\r\nboolean b = TRUE;//COMPILATION ERROR\r\nboolean b = 0; //COMPILER ERROR. This is not C Language\r\n\r\nchar ch = a;\r\nchar a = 97;\r\nchar ch1 = 66000; //COMPILER ERROR!\r\n```\r\n\r\n### Tip - Assignment Operator\r\nAssignment operator evaluates the expression on the right hand side and copies the value into the variable on the left hand side. \r\n\r\n#### Basic Examples\r\n```\r\nint value = 35;//35 is copied into 35\r\n\r\nint squareOfValue = value * value;//value * value = 35 * 35 is stored into squareOfValue\r\n\r\nint twiceOfValue = value * 2;\r\n```\r\n\r\n#### Puzzles\r\n\r\n```\r\nint a1 = 5;\r\nint b1 = 6;\r\nb1 = a1; // value of a1 is copied into b1\r\na1 = 10; // If we change a1 or b1 after this, it would not change the other variable.. b1 will remain 6\r\n\r\nActor actor1 = new Actor();\r\nactor1.setName(\"Actor1\");\r\n//This creates new reference variable actor1 of type Actor  new Actor() on the heap assigns the new Actor on the heap to reference variable\r\n\r\nActor actor2 = actor1;\r\nactor2.setName(\"Actor2\");\r\nSystem.out.println(actor1.getName());//Actor2\r\n\r\n```\r\n\r\n### Casting -  Implicit and Explicit\r\n\r\nCasting is used when we want to convert one data type to another. \r\n\r\n- A literal integer is by default int. Operation involving int-sized or less always result in int.\r\n- Floating point literals are by default double\r\n\r\n#### Implicit Casting\r\n\r\n- Implicit Casting is done directly by the compiler.\r\n  - Example : Widening Conversions i.e. storing smaller values in larger variable types.\r\n\r\n\r\n```\r\nbyte b = 10; //byte b = (int) 10; Example below compiles because compiler introduces an implicit cast.\r\n\r\nshort n1 = 5;\r\nshort n2 = 6;\r\n//short sum = n1 + n2;//COMPILER ERROR\r\nshort sum = (short)(n1 + n2);//Needs an explicit cast\r\n\r\nbyte b = 5;\r\nb += 5; //Compiles because of implicit conversion\r\n\r\nint value = 100;\r\nlong number = value; //Implicit Casting\r\nfloat f = 100; //Implicit Casting \r\n```\r\n\r\n#### Explicit Casting\r\n- Explicit Casting needs to be specified by programmer in code.\r\n  - Example: Narrowing Conversions. Storing larger values into smaller variable types;\r\n- Explicit casting would cause truncation of value if the value stored is greater than the size of the variable.\r\n\r\n```\r\nlong number1 = 25678;\r\nint number2 = (int)number1;//Explicit Casting\r\n//int x = 35.35;//COMPILER ERROR\r\nint x = (int)35.35;//Explicit Casting\r\n\r\nint bigValue = 280;\r\nbyte small = (byte) bigValue;\r\nSystem.out.println(small);//output 24. Only 8 bits remain.\r\n\r\n//float avg = 36.01;//COMPILER ERROR. Default Double\r\nfloat avg = (float) 36.01;//Explicit Casting\r\nfloat avg1 = 36.01f;\r\nfloat avg2 = 36.01F; //f or F is fine\r\n\r\n//byte large = 128; //Literal value bigger than range of variable type causes compilation error\r\nbyte large = (byte) 128;//Causes Truncation!\r\n```\r\n\r\n#### Compound Assignment Operators\r\n\r\n- Examples : +=, -=, *= \r\n\r\n```\r\nint a = 5;\r\na += 5; //similar to a = a + 5;\r\na *= 10;//similar to a = a * 10;\r\na -= 5;//similar to a = a - 5;\r\na /= 5;//similar to a = a / 5;\r\n```\r\n\r\n\r\n### Other Operators\r\n\r\n#### Remainder(%) Operator\r\n\r\n- Remainder when one number is divided by another.\r\n\r\n```\r\nSystem.out.println(10 % 4);//2\r\nSystem.out.println(15 % 4);//3\r\n```\r\n\r\n#### Conditional Operator\r\n- Conditional Operator is a Ternary Operator (3 Operands)\r\n- syntax : ```booleanCondition ? ResultIfTrue: ResultIfFalse;```\r\n\r\n```\r\nint age = 18;\r\n\r\nSystem.out.println(\r\nage >= 18 ? \"Can Vote\": \"Cannot Vote\");//Can Vote\r\n\r\nage = 15;\r\n\r\nSystem.out.println(\r\nage >= 18 ? \"Can Vote\": \"Cannot Vote\");//Cannot Vote\r\n```\r\n\r\n### Passing Variables to Methods\r\n\r\n- All variables , primitives and references , in Java, are passed to functions using copy-of-variable-value.\r\n\r\n#### Passing Variables to Methods : Example\r\n- Passing a primitive variable and modifying the value in a method\r\n- Passing a reference variable and modifying the value in a method\r\n\r\n#### Returning a Value From Method\r\n- null is a valid return value for an object.\r\n- You can return andy type that can be implicitly coverted to return type.\r\n- You cannot return anything from a void method.\r\n\r\n### Types of Variables\r\n\r\n- Different Types of Variables: Static, Member (or instance), Local, Block\r\n\r\n#### Instance Variables\r\n- Declared inside a class outside any method.\r\n- Each instance of the class would have its own values.\r\n- Also called member value, field or property.\r\n\r\n#### Local Variables\r\n- Variables declared in a method\r\n- Local Variables can only be marked with final modifier\r\n- If the name of a Local Variable is same as the name of an instance variable, it results in shadowing.\r\n\r\n#### Member Variables\r\n- Defined at class level and without keyword static.\r\n\r\n#### Static Variable\r\n- Defined at class level and using keyword static.\r\n\r\n#### Member Variable and Static Variable\r\n- Member Variables can be accessed only through object references.\r\n- Static Variables can be accessed through a. Class Name and b. Object Reference. It is NOT recommended to use object reference to refer to static variables.\r\n\r\n#### Example Static and Member Variables\r\n```\r\npublic class StaticAndMemberVariables {\r\n    public static void main(String[] args) {\r\nActor actor1 = new Actor();\r\nactor1.name = \"ACTOR1\";\r\n//Actor.name //Compiler Error\r\n\r\n//Below statement can be written as actor1.count++\r\n//But NOT recommended.\r\nActor.count++;\r\n\r\nActor actor2 = new Actor();\r\nactor2.name = \"ACTOR2\";\r\n\r\n//Below statement can be written as actor2.count++\r\n//But NOT recommended.\r\nActor.count++;\r\n\r\nSystem.out.println(actor1.name);//ACTOR1\r\nSystem.out.println(actor2.name);//ACTOR2\r\n\r\n//Next 3 statements refer to same variable\r\nSystem.out.println(actor1.count);//2\r\nSystem.out.println(actor2.count);//2\r\nSystem.out.println(Actor.count);//2\r\n    }\r\n}\r\n\r\nclass Actor {\r\n    //RULE 1: Member Variables can be accessed \r\n    //only through object references\r\n    String name;\r\n    \r\n    //RULE 2:Static Variables can be accessed \r\n    //through a.Class Name and b.Object Reference\r\n    //It is NOT recommended to use object reference \r\n    //to refer to static variables.\r\n    static int count;    \r\n}\r\n```\r\n\r\n### Scope of a Variable\r\n- Scope of a variable defines where (which part of code) a variable can be accessed.\r\n\r\n#### Important Rules\r\n- Static Variable can be used anywhere in the class.\r\n- Member Variable can be used in any non-static method.\r\n- Local Variable can be used only in the method where it is declared.\r\n- Block Variable can be used only in the block (code between { and }) where it is declared.\r\n\r\n#### Variable Scope Examples\r\nBelow code shows all these Rules in action:\r\n```\r\n\r\npublic class VariablesExample {\r\n    //RULE 1:Static Variable can be used anywhere in the class. \r\n    static int staticVariable;\r\n    \r\n    //RULE 2:Member Variable can be used in any non-static method. \r\n    int memberVariable;\r\n    \r\n    void method1() {\r\n\t\t//RULE 3: method1LocalVariable can be used only in method1.\r\n\t\tint method1LocalVariable;\r\n\r\n\t\tmemberVariable = 5;//RULE 2\r\n\t\tstaticVariable = 5;//RULE 1\r\n\r\n\t\t//Some Code\r\n\t\t{\r\n\t\t    //RULE 4:blockVariable can be used only in this block.\r\n\t\t    int blockVariable;\r\n\t\t    //Some Code\r\n\t\t}\r\n\r\n\t\t//blockVariable = 5;//COMPILER ERROR - RULE 4\r\n    }\r\n    \r\n    void method2() {\r\n\t\t//method1LocalVariable = 5; //COMPILER ERROR - RULE3\r\n    }\r\n    \r\n    static void staticMethod() {\r\n\t\tstaticVariable = 5;//RULE 1\r\n\t\t//memberVariable = 5; //COMPILER ERROR - RULE 2\r\n    }\r\n}\r\n```\r\n\r\n#### Scope Example 1\r\n- staticVariable is declared using keyword static. \r\n- It is available in the instance method method1 and static method named staticMethod.\r\n\r\n#### Scope Example 2\r\n- memberVariable is declared directly in the class  and does NOT use keyword static. So, it is an instance variable. \r\n- It is available in the instance method method1 but not accessible in the static method named staticMethod.\r\n\r\n#### Scope Example 3\r\n- method1LocalVariable is declared in the method method1. So, it is a local variable. \r\n- It is available in the instance method method1 but available in any other  instance or static methods.\r\n\r\n#### Scope Example 4\r\n- blockVariable is declared in a block in method1. So, it is a block variable. \r\n- It is available only in the block where it is defined. \r\n- It is not accessible any where out side the block , even in the same method.\r\n\r\n### Variable Initialization\r\n- Initialization defines the default value assigned to a variable if it is not initialized.\r\n\r\n#### Important Rules\r\n- Member/Static variables are alway initialized with default values.\r\n- Default values for numeric types is 0, floating point types is 0.0, boolean is false, char  is '\\u0000' and for a object reference variable is null.\r\n- Local variables are not initialized by default by compiler. \r\n- Using a local variable before initialization results in a compilation error.\r\n- Assigning a null value is a valid initialization for reference variables.\r\n\r\n#### Variable Initialization Examples\r\nLets look at an example program to understand all the rules regarding variable initialization.\r\n\r\n```\r\npackage com.in28minutes.variables;\r\n\r\n//RULE1:Member/Static variables are alway initialized with \r\n//default values.Default values for numeric types is 0, \r\n//floating point types is 0.0, boolean is false, \r\n//char  is '\\u0000' and object reference variable is null.\r\n\r\n//RULE2:Local/block variables are NOT initialized by compiler. \r\n\r\n//RULE3    :If local variables are used before initialization, \r\n//it would result in Compilation Error\r\n\r\npublic class VariableInitialization {\r\n    public static void main(String[] args) {\r\n\t\tPlayer player = new Player();\r\n\r\n\t\t//score is an int member variable - default 0\r\n\t\tSystem.out.println(player.score);//0 - RULE1\r\n\r\n\t\t//name is a member reference variable - default null\r\n\t\tSystem.out.println(player.name);//null - RULE1\r\n\r\n\t\tint local; //not initialized\r\n\t\t//System.out.println(local);//COMPILER ERROR! RULE3\r\n\r\n\t\tString value1;//not initialized\r\n\t\t//System.out.println(value1);//COMPILER ERROR! RULE3\r\n\r\n\t\tString value2 = null;//initialized\r\n\t\tSystem.out.println(value2);//null - NO PROBLEM.\r\n    }\r\n}\r\n\r\n\r\nclass Player{\r\n    String name;\r\n    int score;\r\n}\r\n```\r\n#### Initialization Example 1\r\n- player  is an instance of the class Player. It contains member variables named name and score. \r\n- All member variables are initialized by default. Since name refers to a String i.e a reference variable it is initialized to null. score is an int variable and hence initialized to 0.\r\n\r\n#### Initialization Example 2 \r\n- local  is a local variable defined in the main method. \r\n- An attempt to access a local variable without initialization would result in a compilation error. \r\n- Same is the case with value1 which is a String local variable. \r\n- If null is assigned to a reference variable, reference variable is considered to be assigned.\r\n\r\n### Wrapper Classes\r\n- [Example 1](src/main/java/com/in28minutes/java/wrapper/WrapperExamples.java)\r\n- A wrapper class wraps (encloses) around a data type and gives it an object appearance\r\n- Wrapper: Boolean,Byte,Character,Double,Float,Integer,Long,Short \r\n- Primitive: boolean,byte,char ,double, float, int , long,short\r\n- Examples of creating wrapper classes are listed below.\r\n  - Integer number = new Integer(55);//int;\r\n  - Integer number2 = new Integer(\"55\");//String\r\n  - Float number3 = new Float(55.0);//double argument  \r\n  - Float number4 = new Float(55.0f);//float argument  \r\n  - Float number5 = new Float(\"55.0f\");//String \r\n  - Character c1 = new Character('C');//Only char constructor \r\n  - Boolean b = new Boolean(true); \r\n- Reasons\r\n  - null is a possible value\r\n  - use it in a Collection\r\n  - Object like creation from other types.. like String\r\n\r\n- A primitive wrapper class in the Java programming language is one of eight classes provided in the java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper classes in Java are immutable.\r\n\r\nWrapper classes are final and immutable.\r\n\r\n\r\n#### Creating Wrapper Classes\r\n\r\n```\r\nInteger number = new Integer(55);//int\r\nInteger number2 = new Integer(\"55\");//String\r\n\r\nFloat number3 = new Float(55.0);//double argument\r\nFloat number4 = new Float(55.0f);//float argument\r\nFloat number5 = new Float(\"55.0f\");//String\r\n\r\nCharacter c1 = new Character('C');//Only char constructor\r\n//Character c2 = new Character(124);//COMPILER ERROR\r\n\r\nBoolean b = new Boolean(true);\r\n\r\n//\"true\" \"True\" \"tRUe\" - all String Values give True\r\n//Anything else gives false\r\nBoolean b1 = new Boolean(\"true\");//value stored - true\r\nBoolean b2 = new Boolean(\"True\");//value stored - true\r\nBoolean b3 = new Boolean(\"False\");//value stored - false\r\nBoolean b4 = new Boolean(\"SomeString\");//value stored - false\r\n\r\nb = false;\r\n```\r\n#### Wrapper Class Utility Methods\r\n\r\n- A number of utility methods are defined in wrapper classes to create and convert them.\r\n\r\n#### valueOf  Methods\r\n\r\nProvide another way of creating a Wrapper Object\r\n\r\n```\r\nInteger seven = \r\n    Integer.valueOf(\"111\", 2);//binary 111 is converted to 7\r\n\r\nInteger hundred = \r\n    Integer.valueOf(\"100\");//100 is stored in variable\r\n```\r\n\r\n#### xxxValue methods \r\n\r\nxxxValue methods help in creating primitives\r\n\r\n```\r\nInteger integer = Integer.valueOf(57);\r\nint primitive = seven.intValue();//57\r\nfloat primitiveFloat = seven.floatValue();//57.0f\r\n\r\nFloat floatWrapper = Float.valueOf(57.0f);\r\nint floatToInt = floatWrapper.intValue();//57\r\nfloat floatToFloat = floatWrapper.floatValue();//57.0f\r\n```\r\n\r\n#### parseXxx methods\r\n\r\nparseXxx methods are similar to valueOf but they return primitive values\r\n\r\n```\r\nint sevenPrimitive = \r\n    Integer.parseInt(\"111\", 2);//binary 111 is converted to 7\r\n\r\nint hundredPrimitive = \r\n    Integer.parseInt(\"100\");//100 is stored in variable\r\n```\r\n\r\n#### static toString method\r\n\r\nLook at the example of the toString static method below.\r\n\r\n```\r\nInteger wrapperEight = new Integer(8);\r\nSystem.out.println(Integer.\r\ntoString(wrapperEight));//String Output: 8\r\n```\r\n\r\n#### Overloaded static toString method\r\n\r\n2nd parameter: radix\r\n\r\n```\r\nSystem.out.println(Integer\r\n.toString(wrapperEight, 2));//String Output: 1000\r\n```\r\n\r\n#### static toYyyyString methods. \r\n\r\nYyyy can be Hex,Binary,Octal\r\n\r\n```\r\nSystem.out.println(Integer\r\n.toHexString(wrapperEight));//String Output:8 \r\nSystem.out.println(Integer\r\n.toBinaryString(wrapperEight));//String Output:1000\r\nSystem.out.println(Integer\r\n.toOctalString(wrapperEight));//String Output:10\r\n```\r\n\r\n#### Wrapper Class , Auto Boxing\r\n```\r\nInteger ten = new Integer(10);\r\nten++;//allowed. Java does the work behind the screen for us\r\n\r\n```\r\n#### Boxing and new instances\r\n- Auto Boxing helps in saving memory by reusing already created Wrapper objects. However wrapper classes created using new are not reused.\r\n- Two wrapper objects created using new are not same object.\r\n\r\n```\r\nInteger nineA = new Integer(9);\r\nInteger nineB = new Integer(9);\r\nSystem.out.println(nineA == nineB);//false\r\nSystem.out.println(nineA.equals(nineB));//true\r\n```\r\n\r\n- Two wrapper objects created using boxing are same object.\r\n\r\n```\r\nInteger nineC = 9;\r\nInteger nineD = 9;\r\nSystem.out.println(nineC == nineD);//true\r\nSystem.out.println(nineC.equals(nineD));//true\r\n```\r\n\r\n### String Class\r\n\r\n- A String class can store a sequence of characters. String is not a primitive in Java but a Class in its own right.\r\n\r\n#### Strings are immutable\r\n\r\n- Value of a String Object once created cannot be modified. Any modification on a String object creates a new String object.\r\n\r\n```\r\nString str3 = \"value1\";\r\nstr3.concat(\"value2\");\r\nSystem.out.println(str3); //value1\r\n```\r\n\r\nNote that the value of str3 is not modified in the above example.  The result should be assigned to a new reference variable (or same variable can be reused).\r\n\r\n```\r\nString concat = str3.concat(\"value2\");\r\nSystem.out.println(concat); //value1value2\r\n```\r\n\r\n## Where are string literals stored in memory?\r\nAll strings literals are stored in \"String constant pool\". If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.\r\nFollowing statement creates 1 string object (created on the pool) and 1 reference variable.\r\n```\r\nString str1 = \"value\"; \r\n```\r\nHowever, if new operator is used to create string object, the new object is created on the heap. Following piece of code create 2 objects.\r\n```\r\n//1. String Literal \"value\" - created in the \"String constant pool\"\r\n//2. String Object - created on the heap\r\nString str2 = new String(\"value\");\r\n```\r\n## String vs StringBuffer vs StringBuilder\r\n- Immutability : String\r\n- Thread Safety : String(immutable), StringBuffer\r\n- Performance : StringBuilder (especially when a number of modifications are made.)\r\n- [Example 1](src/main/java/com/in28minutes/java/string/StringBufferBuilderExamples.java)\r\n\r\n\r\n#### String Constant Pool\r\n\r\n- All strings literals are stored in \"String constant pool\". If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.\r\n\r\n- Following statement creates 1 string object (created on the pool) and 1 reference variable.\r\n\r\n```\r\nString str1 = \"value\"; \r\n```\r\n\r\n- However, if new operator is used to create string object, the new object is created on the heap. Following piece of code create 2 objects.\r\n\r\n```\r\n//1. String Literal \"value\" - created in the \"String constant pool\"\r\n//2. String Object - created on the heap\r\nString str2 = new String(\"value\");\r\n```\r\n\r\n#### String Method Examples\r\n\r\nString class defines a number of methods to get information about the string content.\r\n\r\n```\r\nString str = \"abcdefghijk\";\r\n```\r\n\r\n##### Get information from String\r\n\r\nFollowing methods help to get information from a String.\r\n\r\n```\r\n//char charAt(int paramInt)\r\nSystem.out.println(str.charAt(2)); //prints a char - c\r\nSystem.out.println(\"ABCDEFGH\".length());//8\r\nSystem.out.println(\"abcdefghij\".toString()); //abcdefghij\r\nSystem.out.println(\"ABC\".equalsIgnoreCase(\"abc\"));//true\r\n\r\n//Get All characters from index paramInt\r\n//String substring(int paramInt)\r\nSystem.out.println(\"abcdefghij\".substring(3)); //cdefghij\r\n\r\n//All characters from index 3 to 6\r\nSystem.out.println(\"abcdefghij\".substring(3,7)); //defg\r\n```\r\n\r\n#### String Manipulation methods\r\n\r\nMost important thing to remember is a String object cannot be modified. When any of these methods are called, they return a new String with the modified value. The original String remains unchanged.\r\n\r\n```\r\n//String concat(String paramString)\r\nSystem.out.println(str.concat(\"lmn\"));//abcdefghijklmn\r\n\r\n//String replace(char paramChar1, char paramChar2)\r\nSystem.out.println(\"012301230123\".replace('0', '4'));//412341234123\r\n\r\n//String replace(CharSequence paramCharSequence1, CharSequence paramCharSequence2)\r\nSystem.out.println(\"012301230123\".replace(\"01\", \"45\"));//452345234523\r\n\r\nSystem.out.println(\"ABCDEFGHIJ\".toLowerCase()); //abcdefghij\r\n\r\nSystem.out.println(\"abcdefghij\".toUpperCase()); //ABCDEFGHIJ\r\n\r\n//trim removes leading and trailings spaces\r\nSystem.out.println(\" abcd  \".trim()); //abcd\r\n```\r\n### String Concatenation Operator\r\n\r\n#### Three Rules of String Concatenation\r\n- RULE1: Expressions are evaluated from left to right.Except if there are parenthesis.\r\n- RULE2: number + number = number\r\n- RULE3: number + String = String\r\n\r\n```\r\nSystem.out.println(5 + \"Test\" + 5); //5Test5\r\nSystem.out.println(5 + 5 + \"Test\"); //10Test\r\nSystem.out.println(\"5\" + 5 + \"Test\"); //55Test\r\nSystem.out.println(\"5\" + \"5\" + \"25\"); //5525\r\nSystem.out.println(5 + 5 + \"25\"); //1025\r\nSystem.out.println(\"\" + 5 + 5 + \"25\"); //5525\r\nSystem.out.println(5 + (5 + \"25\")); //5525\r\nSystem.out.println(5 + 5 + 25); //35\r\n```\r\n\r\n### Increment and Decrement Operators\r\n\r\n- Lets learn about the increment and decrement operators in Java.\r\n\r\n#### Basics of Increment and Decrement Operators\r\n\r\nExcept for a minor difference ++i,i++ is similar to i = i+1 and --i,i-- is similar to i = i-1\r\n\r\n++i is called pre-increment and i++ post increment\r\n\r\n#### Increment Operators\r\n\r\nPre increment statement returns value after increment. Post increment statement returns value before increment\r\n\r\n```\r\nint i = 25;\r\nint j = ++i;//i is incremented to 26, assigned to j\r\nSystem.out.println(i + \" \" + j);//26 26\r\n\r\ni = 25;\r\nj = i++;//i value(25) is assigned to j, then incremented to 26\r\nSystem.out.println(i + \" \" + j);//26 25\r\n```\r\n#### Decrement Operators\r\n\r\nDecrement Operators are similar to increment operators.\r\n\r\n```\r\ni = 25;\r\nj = --i;//i is decremented to 24, assigned to j\r\nSystem.out.println(i + \" \" + j);//24 24\r\n\r\ni = 25;\r\nj = i--;//i value(25) is assigned to j, then decremented to 24\r\nSystem.out.println(i + \" \" + j);//24 25\r\n```\r\n\r\n### Relational Operators\r\n\r\n- Relation Operators are used to compare operands. They a always return true or false. List of Relation Operators include <, <=, >, >=, ==, and !=.\r\n\r\n#### Relation Operators Examples\r\nLet's consider a few examples of relational operators. Let's assume a int variable named number with a value 7.\r\n\r\n```\r\nint number = 7;\r\n```\r\n\r\n#### greater than operator\r\n\r\n```\r\nSystem.out.println(number > 5);//true\r\nSystem.out.println(number > 7);//false\r\n```\r\n\r\n#### greater than equal to operator\r\n```\r\nSystem.out.println(number >= 7);//true\r\n```\r\n\r\n#### less than operator\r\n```\r\nSystem.out.println(number < 9);//true\r\nSystem.out.println(number < 7);//false\r\n```\r\n\r\n#### less than equal to operator\r\n```\r\nSystem.out.println(number <= 7);//true\r\n```\r\n\r\n#### is equal to operator\r\n```\r\nSystem.out.println(number == 7);//true\r\nSystem.out.println(number == 9);//false\r\n```\r\n\r\n#### NOT equal to operator\r\n```\r\nSystem.out.println(number != 9);//true\r\nSystem.out.println(number != 7);//false\r\n```\r\n\r\n> single = is assignment operator and == is comparison. Below statement uses =.\r\n\r\n```\r\nSystem.out.println(number = 7);//7\r\n```\r\n#### == (equals) operator\r\nLet's look at how == equals operator works with primitives and reference variables.\r\n\r\n#### Primitive Variables\r\n\r\n- Equality for Primitives only compares values\r\n\r\n```\r\nint a = 5;\r\nint b = 5;\r\n```\r\n\r\nBelow statement compares if a and b have same value.\r\n\r\n```\r\nSystem.out.println(a == b);//true\r\n```\r\n#### Reference Variables\r\n\r\n```\r\nInteger aReference = new Integer(5);\r\nInteger bReference = new Integer(5);\r\n```\r\n\r\nFor reference variables, == compares if they are referring to the same object.\r\n\r\n```\r\nSystem.out.println(aReference == bReference);//false\r\n\r\nbReference = aReference;\r\n\r\n//Now both are referring to same object\r\nSystem.out.println(aReference == bReference);//true\r\n```\r\n\r\n### Logical Operators\r\n- Logical Operators are &&, ||, |, &, ! and ^.\r\n\r\n#### Short Circuit And Operator - &&\r\n- True when both operands are true.\r\n\r\n```\r\nSystem.out.println(true && true);//true\r\nSystem.out.println(true && false);//false\r\nSystem.out.println(false && true);//false\r\nSystem.out.println(false && false);//false\r\n```\r\n#### Short Circuit Or Operator - ||\r\n\r\nTrue when atleast one of operands are true.\r\n\r\n```\r\nSystem.out.println(true || true);//true\r\nSystem.out.println(true || false);//true\r\nSystem.out.println(false || true);//true\r\nSystem.out.println(false || false);//false\r\n```\r\n\r\n> Certification Tip : Logical Operators work with boolean values but not numbers.\r\n\r\n```\r\n//System.out.println(5 || 6);//COMPILER ERROR\r\n```\r\n#### Short circuit operators are Lazy \r\n\r\n- They stop execution the moment result is clear.  \r\n   - For &&, if first expression is false,result is false.  \r\n   - For ||, if first expression is true, the result is true. \r\n   - In above 2 situations, second expressions are not executed.\r\n\r\n```\r\nint i = 10;\r\nSystem.out.println(true || ++i==11);//true\r\nSystem.out.println(false && ++i==11);//false\r\nSystem.out.println(i);//i remains 10, as ++i expressions are not executed.\r\n```\r\n\r\n#### Operator & and |\r\n- Logical Operators &, | are similar to &&, || except that they don't short ciruit. \r\n- They execute the second expression even if the result is decided.\r\n\r\n> Certification Tip : While & and | are very rarely used, it is important to understand them from a certification perspective.\r\n\r\n```\r\nint j = 10;\r\nSystem.out.println(true | ++j==11);//true\r\nSystem.out.println(false & ++j==12);//false\r\nSystem.out.println(j);//j becomes 12, as both ++j expressions are executed\r\n```\r\n\r\n#### Operator exclusive-OR (^)\r\n- Result is true only if one of the operands is true.\r\n```\r\nSystem.out.println(true ^ false);//true\r\nSystem.out.println(false ^ true);//true\r\nSystem.out.println(true ^ true);//false\r\nSystem.out.println(false ^ false);//false\r\n```\r\n#### Not Operator (!)\r\nResult is the negation of the expression.\r\n```\r\nSystem.out.println(!false);//true\r\nSystem.out.println(!true);//false\r\n```\r\n### Arrays\r\n- TODO : Why do we need arrays?\r\n\r\n```\r\n//Declaring an Array\r\nint[] marks;\r\n\r\n// Creating an array\r\nmarks = new int[5]; // 5 is size of array\r\n\r\nint marks2[] = new int[5];//Declaring and creating an array in same line.\r\n\r\nSystem.out.println(marks2[0]);//New Arrays are always initialized with default values - 0\r\n\r\n//Index of elements in an array runs from 0 to length - 1\r\nmarks[0] = 25;\r\nmarks[1] = 30;\r\nmarks[2] = 50;\r\nmarks[3] = 10;\r\nmarks[4] = 5;\r\n\r\nSystem.out.println(marks[2]);//Printing a value from array\r\n\r\n//Printing a 1D Array\r\nint marks5[] = { 25, 30, 50, 10, 5 };\r\nSystem.out.println(marks5); //[I@6db3f829\r\nSystem.out.println(\r\n    Arrays.toString(marks5));//[25, 30, 50, 10, 5]\r\n\r\nint length = marks.length;//Length of an array: Property length\r\n\r\n//Enhanced For Loop\r\nfor (int mark: marks) {\r\n    System.out.println(mark);\r\n}\r\n\r\n//Fill array with a value\r\nArrays.fill(marks, 100); //All array values will be 100\r\n\r\n//String Arrays\r\nString[] daysOfWeek = { \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\" };\r\n```\r\n\r\n#### 2D Arrays\r\n\r\nBest way to visualize a 2D array is as an array of arrays.\r\n\r\n```\r\nint[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };\r\n\r\nint[][] matrixA = new int[5][6]; \r\n\r\n//Accessing elements from 2D array:\r\nSystem.out.println(matrix[0][0]); //1\r\nSystem.out.println(matrix[1][2]); //6\r\n\r\n//Looping a 2D array\r\nfor (int[] array: matrix) {\r\n    for (int number: array) {\r\n         System.out.println(number);\r\n    }\r\n}\r\n\r\n// Printing a 2D Array\r\nint[][] matrix3 = { { 1, 2, 3 }, { 4, 5, 6 } };\r\nSystem.out.println(matrix3); //[[I@1d5a0305\r\nSystem.out.println(\r\n\r\nArrays.toString(matrix3)); \r\n//[[I@6db3f829, [I@42698403]\r\n\r\nSystem.out.println(Arrays.deepToString(matrix3)); \r\n//[[1, 2, 3], [4, 5, 6]]\r\n\r\nSystem.out.println(matrix3[0]);//[I@86c347 - matrix3[0] is a 1D Array\r\nSystem.out.println(Arrays.toString(matrix3[0]));//[1, 2, 3]\r\n```\r\n\r\n#### Other Array Operations\r\n\r\n```\r\n//Comparing Arrays\r\nint[] numbers1 = { 1, 2, 3 };\r\nint[] numbers2 = { 4, 5, 6 };\r\n\r\nSystem.out.println(Arrays\r\n.equals(numbers1, numbers2)); //false\r\n\r\nint[] numbers3 = { 1, 2, 3 };\r\n\r\nSystem.out.println(Arrays\r\n.equals(numbers1, numbers3)); //true\r\n\r\n// Sorting an Array\r\n\r\nint rollNos[] = { 12, 5, 7, 9 };\r\nArrays.sort(rollNos);\r\nSystem.out.println(Arrays.toString(rollNos));//[5, 7, 9, 12]\r\n\r\n```\r\n\r\n#### Array of Objects\r\n\r\n```\r\nPerson[] persons = new Person[3];\r\n\r\n//By default, an array of 3 reference variables is created.\r\n//The person objects are not created\r\nSystem.out.println(persons[0]);//null\r\n\r\n//Let's create the new objects\r\npersons[0] = new Person();\r\npersons[1] = new Person();\r\npersons[2] = new Person();\r\n\r\n//Creating and initializing person array in one statement\r\nPerson[] personsAgain = { new Person(),new Person(),new Person()};\r\n\r\n//Another example\r\nPerson[][] persons2D = \r\n    {\r\n\t\t{ new Person(),new Person(),new Person()},\r\n\t\t{ new Person(),new Person()}\r\n    };\r\n```\r\n\r\n\r\n#### Array Certification Tips and Puzzles\r\n```\r\n\r\n//You can Declare, Create and Initialize Array on same line.\r\nint marks3[] = { 25, 30, 50, 10, 5 };\r\n\r\n//Leaving additional comma is not a problem. (note that comma after 5)\r\nint marks4[] = { 25, 30, 50, 10, 5, };\r\n\r\n\r\nint marks[]; //Not Readable\r\nint[] runs; //Not Readable\r\n\r\n\r\n//int values[5];//Compilation Error!Declaration of an Array should not include size. \r\n\r\n//marks = new int[];//COMPILER ERROR! Size of an array is mandatory to create an array.\r\n\r\n\r\n//Declaring 2D Array Examples:\r\nint[][] matrix1; //Recommended\r\nint[] matrix2[]; //Legal but not readable. Avoid.\r\n\r\n//Access 10th element when array has only length 5\r\n//Runtime Exception: ArrayIndexOutOfBoundsException\r\n//System.out.println(marks[10]);\r\n\r\n//Array can contain only values of same type.\r\n\r\n//COMPILE ERROR!!\r\n//int marks4[] = {10,15.0}; //10 is int 15.0 is float\r\n\r\n//Cross assigment of primitive arrays is ILLEGAL\r\nint[] ints = new int[5];\r\nshort[] shorts = new short[5];\r\n//ints = shorts;//COMPILER ERROR\r\n//ints = (int[])shorts;//COMPILER ERROR\r\n\r\n\r\n//The first dimension of a 2D array is mandatory\r\nmatrixA = new int[3][];//FINE\r\n//matrixA = new int[][5];//COMPILER ERROR\r\n//matrixA = new int[][];//COMPILER ERROR\r\n\r\n//Each row in a 2D Array can have a different size. This is called a Ragged Array.\r\nmatrixA = new int[3][];//FINE\r\nmatrixA[0] = new int[3];\r\nmatrixA[0] = new int[4];\r\nmatrixA[0] = new int[5];\r\n```\r\n\r\n\r\n### If Else Condition\r\n- Conditionally execute code! \r\n- Code inside If is executed only if the condition is true.\r\n\r\n// Basic Example\r\n```\r\nif(true){\r\n    System.out.println(\"Will be printed\");\r\n}\r\n\r\nif(false){\r\n    System.out.println(\"Will NOT be printed\");//Not executed\r\n}\r\n\r\n//Example 1\r\nint x = 5;\r\n\r\nif(x==5){\r\n    System.out.println(\"x is 5\");//executed since x==5 is true\r\n}\r\n\r\n//Example 2\r\nx = 6;\r\nif(x==5){\r\n    System.out.println(\"x is 5\");//Not executed since x==5 is false\r\n}\r\n\r\n//Example 3\r\nint y = 10;\r\n\r\nif(y==10){\r\n    System.out.println(\"Y is 10\");//executed-condn y==10 is true\r\n} else {\r\n    System.out.println(\"Y is Not 10\");\r\n}\r\n\r\n//Example 4\r\ny = 11;\r\n\r\nif(y==10){\r\n    System.out.println(\"Y is 10\");//NOT executed\r\n} else {\r\n    System.out.println(\"Y is Not 10\");//executed\r\n}\r\n\r\n//Example 5\r\nint z = 15;\r\n//Only one condition is executed. Rest of the conditions are skipped.\r\nif(z==10){\r\n    System.out.println(\"Z is 10\");//NOT executed\r\n} else if(z==12){\r\n    System.out.println(\"Z is 12\");//NOT executed\r\n} else if(z==15){\r\n    System.out.println(\"Z is 15\");//executed. \r\n} else {\r\n    System.out.println(\"Z is Something Else.\");//NOT executed\r\n}\r\n\r\nz = 18;\r\nif(z==10){\r\n    System.out.println(\"Z is 10\");//NOT executed\r\n} else if(z==12){\r\n    System.out.println(\"Z is 12\");//NOT executed\r\n} else if(z==15){\r\n    System.out.println(\"Z is 15\");//NOT executed\r\n} else {\r\n    System.out.println(\"Z is Something Else.\");//executed\r\n}\r\n\r\n//If else Example: without Blocks\r\nint number = 5;\r\nif(number < 0) \r\n    number = number + 10; //Not executed\r\n    number++; //This statement is not part of if. Executed.\r\nSystem.out.println(number);//prints 6\r\n```\r\n#### If else Puzzles\r\n\r\n```\r\n//Puzzle 1\r\nint k = 15;\r\nif (k > 20) {\r\n    System.out.println(1);\r\n} else if (k > 10) {\r\n    System.out.println(2);\r\n} else if (k < 20) {\r\n    System.out.println(3);\r\n} else {\r\n    System.out.println(4);\r\n}\r\n\r\n//Output is 2. \r\n//Once a condition in nested-if-else is true the rest of the code is not executed.  \r\n\r\n\r\n//Puzzle 2\r\nint l = 15;\r\n\r\nif(l<20)\r\n    System.out.println(\"l<20\");\r\nif(l>20)\r\n    System.out.println(\"l>20\");\r\nelse\r\n    System.out.println(\"Who am I?\");\r\n```\r\n\r\n//Output is \"l<20\" followed by \"Who am I?\" on next line. \r\n//else belong to the last if before it unless brackets ({}) are used.\r\n```\r\n\r\nPuzzle 3\r\n\r\n```\r\nint m = 15;\r\n\r\nif(m>20)\r\n    if(m<20)\r\nSystem.out.println(\"m>20\");\r\n    else\r\nSystem.out.println(\"Who am I?\");\r\n\r\n//Nothing is printed to output. \r\n\r\n//Code above is similar to the code snippet shown below\r\n\r\nif(m>20) {//Condn is false. So, code in if is not executed\r\n    if(m<20)\r\nSystem.out.println(\"m>20\");\r\n    else\r\nSystem.out.println(\"Who am I?\");\r\n}\r\n```\r\n\r\nPuzzles Continued\r\n\r\n```\r\n\r\n//Puzzle 4\r\n\r\nint x1 = 0;\r\n//Condition in if should always be boolean\r\n//if(x1) {} //COMPILER ERROR\r\n//if(x1=0) {}//COMPILER ERROR. Using = instead of ==\r\n//If else condition should be boolean\r\n\r\n//Puzzle 5\r\n\r\nboolean isTrue = false;\r\n\r\nif(isTrue==true){\r\n    System.out.println(\"TRUE TRUE\");//Will not be printed\r\n}\r\n\r\nif(isTrue=true){\r\n    System.out.println(\"TRUE\");//Will be printed.\r\n}\r\n\r\n//Condition is isTrue=true. This is assignment. Returns true. So, code in if is executed.\r\n```\r\n\r\n### Switch Statement\r\n- Choose between a set of options.\r\n- From Java 6, String can be used as the switch argument.\r\n\r\n```\r\n//Example 1\r\n\r\nint number = 2;\r\nswitch (number) {\r\ncase 1:\r\n    System.out.println(1);\r\n    break;\r\ncase 2:\r\n    System.out.println(2);//PRINTED\r\n    break;\r\ncase 3:\r\n    System.out.println(3);\r\n    break;\r\ndefault:\r\n    System.out.println(\"Default\");\r\n    break;\r\n}\r\n// Output of above example is 2.The case which is matched is executed.\r\n\r\n```\r\nImportant Tips\r\n- There is a break statement in every case. If there is no break statement, switch continues to execute other cases.\r\n- There is a case named default.  If none of the cases match default case is executed.\r\n\r\n\r\n```\r\n//Switch Statement Example 2 , No Breaks\r\nnumber = 2;\r\nswitch (number) {\r\ncase 1:\r\n    System.out.println(1);\r\ncase 2:\r\n    System.out.println(2);\r\ncase 3:\r\n    System.out.println(3);\r\ndefault:\r\n    System.out.println(\"Default\");\r\n}\r\n```\r\n\r\nOutput of above switch\r\n```\r\n2\r\n3\r\nDefault\r\n```\r\n\r\nSince there is no break after case 2, execution falls through to case 3. There is no break in case 3 as well. So, execution falls through to default. \r\n\r\n> Code in switch is executed from a matching case until a break or end of switch statement is encountered.\r\n\r\n\r\nSwitch Statement Example 3 , Few Break's\r\n```\r\nnumber = 2;\r\nswitch (number) {\r\ncase 1:\r\n    System.out.println(1);\r\n    break;\r\ncase 2:\r\ncase 3:\r\n    System.out.println(\"Number is 2 or 3\");\r\n    break;\r\ndefault:\r\n    System.out.println(\"Default\");\r\n    break;\r\n}\r\n```\r\nProgram Output \r\n```\r\nNumber is 2 or 3.\r\n```\r\nCase 2 matches. Since there is no code in case 2, execution falls through to case 3, executes the println. Break statement takes execution out of the switch.\r\n\r\nSwitch Statement Example 4 , Let's Default\r\n- default is executed if none of the case's match. \r\n\r\n```\r\nnumber = 10;\r\nswitch (number) {\r\ncase 1:\r\n    System.out.println(1);\r\n    break;\r\ncase 2:\r\n    System.out.println(2);\r\n    break;\r\ncase 3:\r\n    System.out.println(3);\r\n    break;\r\ndefault:\r\n    System.out.println(\"Default\");\r\n    break;\r\n}\r\n```\r\nCode Output\r\n```\r\nDefault\r\n```\r\n\r\nSwitch Statement Example 5 - Default need not be Last \r\n```\r\nnumber = 10;\r\nswitch (number) {\r\ndefault:\r\n    System.out.println(\"Default\");\r\n    break;\r\ncase 1:\r\n    System.out.println(1);\r\n    break;\r\ncase 2:\r\n    System.out.println(2);\r\n    break;\r\ncase 3:\r\n    System.out.println(3);\r\n    break;\r\n}\r\n```\r\nOutput \r\n```\r\nDefault\r\n```\r\n#### Switch statement Example 6\r\n\r\n\r\nSwitch can be used only with char, byte, short, int, String or enum\r\n```\r\nlong l = 15;\r\n/*switch(l){//COMPILER ERROR. Not allowed.\r\n}*/\r\n\r\nCase value should be a compile time constant.\r\n```\r\nnumber = 10;\r\nswitch (number) {\r\n//case number>5://COMPILER ERROR. Cannot have a condition\r\n//case number://COMPILER ERROR. Should be constant.\r\n}    \r\n```\r\n\r\n## Loops\r\nA loop is used to run same code again and again.\r\n\r\n### While Loop\r\n```\r\nint count = 0;\r\n\r\nwhile(count < 5){//while this condn is true, loop is executed.\r\n    System.out.print(count);\r\n    count++;\r\n}\r\n//Output - 01234\r\n```\r\n\r\nWhile loop Example 2\r\n\r\n```\r\ncount = 5;\r\nwhile(count < 5){//condn is false. So, code in while is not executed.\r\n    System.out.print(count);\r\n    count++;\r\n}//Nothing is printed to output\r\n```\r\n\r\n### Do While Loop\r\n- The difference between a while and a do while is that the code in do while is executed at least once. \r\n- In a do while loop, condition check occurs after the code in loop is executed once.\r\n\r\nDo While loop Example 1\r\n```\r\nint count = 0;\r\ndo{\r\n    System.out.print(count);\r\n    count++;\r\n}while(count < 5);//while this condn is true, loop is executed.\r\n//output is 01234\r\n```\r\n\r\nDo While loop Example 2\r\n```\r\ncount = 5;\r\ndo{\r\n    System.out.print(count);\r\n    count++;\r\n}while(count < 5);\r\n//output is 5\r\n```\r\n\r\n### For Loop\r\n\r\nFor loop is used to loop code specified number of times.\r\n\r\nFor Loop Example 1\r\n```\r\nfor (int i = 0; i < 10; i++) {\r\n    System.out.print(i);\r\n}\r\n//Output - 0123456789\r\n```\r\nSyntax - For loop statement has 3 parts\r\n- Initialization => int i=0. Initialization happens the first time a for loop is run.\r\n- Condition => i<10. Condition is checked every time before the loop is executed.\r\n- Operation (Increment or Decrement usually) => i++. Operation is invoked at the start of every loop (except for first time).\r\n\r\nFor Loop Example 2: There can be multiple statements in Initialization or Operation separated by commas\r\n```\r\nfor (int i = 0,j = 0; i < 10; i++,j--) {\r\n    System.out.print(j);\r\n}\r\n//Output - 0123456789\r\n```\r\n#### Enhanced For Loop\r\nEnhanced for loop can be used to loop around array's or List's.\r\n```\r\nint[] numbers = {1,2,3,4,5};\r\n\r\nfor(int number:numbers){\r\n    System.out.print(number);\r\n}\r\n//Output - 12345\r\n```\r\nAny of 3 parts in a for loop can be empty.\r\n```\r\nfor (;;) {\r\n    System.out.print(\"I will be looping for ever..\");\r\n}\r\n//Infinite loop => Loop executes until the program is terminated.\r\n```\r\n\r\n### Break Statement\r\n\r\nBreak statement breaks out of a loop\r\n\r\nExample 1\r\n```\r\nfor (int i = 0; i < 10; i++) {\r\n    System.out.print(i);\r\n    if (i == 5) {\r\n         break;\r\n    }\r\n}\r\n//Output - 012345\r\n//Even though the for loop runs from 0 to 10, execution stops at i==5 because of the break statement. ÒBreak statementÓ stops the execution of the loop and takes execution to the first statement after the loop.\r\n```\r\n\r\nBreak can be used in a while also.\r\n```\r\nint i = 0;\r\nwhile (i < 10) {\r\n    System.out.print(i);\r\n    if (i == 5) {\r\nbreak;\r\n    }\r\n    i++;\r\n}\r\n//Output - 012345\r\n```\r\n\r\nBreak statement takes execution out of inner most loop.\r\n```java\r\nfor (int j = 0; j < 2; j++) {\r\n    for (int k = 0; k < 10; k++) {\r\nSystem.out.print(j + \"\" + k);\r\nif (k == 5) {\r\n    break;//Takes out of loop using k\r\n}\r\n    }\r\n}\r\n//Output - 000102030405101112131415\r\n//Each time the value of k is 5 the break statement is executed. \r\n//The break statement takes execution out of the k loop and proceeds to the next value of j.\r\n\r\n```\r\nLabels can be used to label and refer to specific for loop in a nested for loop.\r\n```\r\nouter:\r\n    for (int j = 0; j < 2; j++) {\r\n       for (int k = 0; k < 10; k++) {\r\n             System.out.print(j + \"\" + k);\r\n             if (k == 5) {\r\n               break outer;//Takes out of loop using j\r\n             }\r\n        }\r\n    }\r\n//Output - 000102030405\r\n```\r\n### Continue Statement\r\n- Continue statement skips rest of the statements in the loop and starts next iteration\r\n\r\n```\r\nfor (int i = 0; i < 10; i++) {\r\n    if (i == 5) {\r\n      continue;\r\n    }\r\n    System.out.print(i);\r\n}\r\n\r\n//Output => 012346789\r\n\r\n//Note that the output does not contain 5. \r\n//When i==5 continue is executed. Continue skips rest of the code and goes to next loop iteration. \r\n//So, the print statement is not executed when i==5.\r\n\r\n```\r\nContinue can be used in a while also\r\n```\r\nint i = 0;\r\nwhile (i < 10) {\r\n    i++;\r\n    if (i == 5) {\r\n        continue;\r\n    }\r\n    System.out.print(i);\r\n}\r\n//Output - 1234678910\r\n```\r\n\r\nContinue statement takes execution to next iteration of inner most loop.\r\n```\r\nfor (int j = 0; j < 2; j++) {\r\n    for (int k = 0; k < 10; k++) {\r\n       if (k == 5) {\r\n          continue;//skips to next iteration of k loop\r\n        }\r\n        System.out.print(j + \"\" + k);\r\n    }\r\n}\r\n//Output - 000102030406070809101112131416171819\r\n//When k==5 the print statement in the loop is skipped due to continue. \r\n//So 05 and 05 are not printed to the console.\r\n\r\n```\r\nLabel Example\r\n```\r\nouter:\r\n    for (int j = 0; j < 2; j++) {\r\n\t\tfor (int k = 0; k < 10; k++) {\r\n    \t\tif (k == 5) {\r\n\t\t\t\tcontinue outer;//skips to next iteration of j loop\r\n    \t\t}\r\n    \t\tSystem.out.print(j + \"\" + k);\r\n\t\t}\r\n    }\r\n//Output - 00010203041011121314\r\n//When k==5 is true, continue outer is called. \r\n//So, when value of k is 5, the loop skips to the next iteration of j. \r\n\r\n```\r\n\r\n### Enum\r\n- Enum allows specifying a list of valid values (or allowed values) for a Type. \r\n\r\n#### Enum Declaration\r\nConsider the example below. It declares an enum Season with 4 possible values.\r\n```\r\n    enum Season {\r\n       WINTER, SPRING, SUMMER, FALL\r\n    };\r\n```\r\n\r\n#### Enum Example 1\r\n```\r\n\r\n//Enum can be declared outside a class\r\nenum SeasonOutsideClass {\r\n\tWINTER, SPRING, SUMMER, FALL\r\n};\r\n\r\npublic class Enum {\r\n\t// Enum can be declared inside a class\r\n\tenum Season {\r\n\t\tWINTER, SPRING, SUMMER, FALL\r\n\t};\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\t/*\r\n\t\t * //Uncommenting gives compilation error //enum cannot be created in a\r\n\t\t * <main></main>ethod enum InsideMethodNotAllowed { WINTER, SPRING, SUMMER, FALL };\r\n\t\t */\r\n\r\n\t\t// Converting String to Enum\r\n\t\tSeason season = Season.valueOf(\"FALL\");\r\n\r\n\t\t// Converting Enum to String\r\n\t\tSystem.out.println(season.name());// FALL\r\n\r\n\t\t// Default ordinals of enum\r\n\t\t// By default java assigns ordinals in order\r\n\t\tSystem.out.println(Season.WINTER.ordinal());// 0\r\n\t\tSystem.out.println(Season.SPRING.ordinal());// 1\r\n\t\tSystem.out.println(Season.SUMMER.ordinal());// 2\r\n\t\tSystem.out.println(Season.FALL.ordinal());// 3\r\n\r\n\t\t// Looping an enum => We use method values\r\n\t\tfor (Season season1 : Season.values()) {\r\n\t\t\tSystem.out.println(season1.name());\r\n\t\t\t// WINTER SPRING SUMMER FALL (separate lines)\r\n\t\t}\r\n\r\n\t\t// Comparing two Enums\r\n\t\tSeason season1 = Season.FALL;\r\n\t\tSeason season2 = Season.FALL;\r\n\t\tSystem.out.println(season1 == season2);// true\r\n\t\tSystem.out.println(season1.equals(season2));// true\r\n\t}\r\n}\r\n```\r\nEnum Rules\r\n- Enums can be declared in a separate class(SeasonOutsideClass) or as member of a class(Season). Enums cannot be declared in a method.\r\n\r\nConversion of Enum : Function valueOf(String)  is used to convert a string to enum.\r\n```\r\n//Converting String to Enum\r\nSeason season = Season.valueOf(\"FALL\");\r\n```\r\n\r\nFunction name() is used to find String value of an enum.\r\n```\r\n//Converting Enum to String\r\nSystem.out.println(season.name());//FALL\r\n```\r\n\r\nJava assigns default ordinals to an enum in order. However, it is not recommended to use ordinals to perform logic.\r\n```\r\n//Default ordinals of enum\r\n// By default java assigns ordinals in order\r\nSystem.out.println(Season.WINTER.ordinal());//0\r\nSystem.out.println(Season.SPRING.ordinal());//1\r\nSystem.out.println(Season.SUMMER.ordinal());//2\r\nSystem.out.println(Season.FALL.ordinal());//3\r\n```\r\n\r\nLooping around an Enum - List of values allowed for an Enum can be obtained by invoking the  function values().\r\n```\r\n//Looping an enum => We use method values\r\nfor (Season season1: Season.values()) {\r\n    System.out.println(season1.name());\r\n    //WINTER SPRING SUMMER FALL (separate lines)\r\n}\r\n```\r\n\r\nComparing two Enums \r\n```\r\n//Comparing two Enums\r\nSeason season1 = Season.FALL;\r\nSeason season2 = Season.FALL;\r\nSystem.out.println(season1 == season2);//true\r\nSystem.out.println(season1.equals(season2));//true\r\n```\r\n\r\n#### Enum Example 2\r\n```\r\npackage com.in28minutes.java.beginners.concept.examples.enums;\r\n\r\npublic class EnumAdvanced {\r\n\r\n\t// Enum with a variable,method and constructor\r\n\tenum SeasonCustomized {\r\n\t\tWINTER(1), SPRING(2), SUMMER(3), FALL(4);\r\n\r\n\t\t// variable\r\n\t\tprivate int code;\r\n\r\n\t\t// method\r\n\t\tpublic int getCode() {\r\n\t\t\treturn code;\r\n\t\t}\r\n\r\n\t\t// Constructor-only private or (default)\r\n\t\t// modifiers are allowed\r\n\t\tSeasonCustomized(int code) {\r\n\t\t\tthis.code = code;\r\n\t\t}\r\n\r\n\t\t// Getting value of enum from code\r\n\t\tpublic static SeasonCustomized valueOf(int code) {\r\n\t\t\tfor (SeasonCustomized season : SeasonCustomized.values()) {\r\n\t\t\t\tif (season.getCode() == code)\r\n\t\t\t\t\treturn season;\r\n\t\t\t}\r\n\t\t\tthrow new RuntimeException(\"value not found\");// Just for kicks\r\n\t\t}\r\n\r\n\t\t// Using switch statement on an enum\r\n\t\tpublic int getExpectedMaxTemperature() {\r\n\t\t\tswitch (this) {\r\n\t\t\tcase WINTER:\r\n\t\t\t\treturn 5;\r\n\t\t\tcase SPRING:\r\n\t\t\tcase FALL:\r\n\t\t\t\treturn 10;\r\n\t\t\tcase SUMMER:\r\n\t\t\t\treturn 20;\r\n\t\t\t}\r\n\t\t\treturn -1;// Dummy since Java does not recognize this is possible :)\r\n\t\t}\r\n\r\n\t};\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tSeasonCustomized season = SeasonCustomized.WINTER;\r\n\r\n\t\t/*\r\n\t\t * //Enum constructor cannot be invoked directly //Below line would\r\n\t\t * cause COMPILER ERROR SeasonCustomized season2 = new\r\n\t\t * SeasonCustomized(1);\r\n\t\t */\r\n\r\n\t\tSystem.out.println(season.getCode());// 1\r\n\r\n\t\tSystem.out.println(season.getExpectedMaxTemperature());// 5\r\n\r\n\t\tSystem.out.println(SeasonCustomized.valueOf(4));// FALL\r\n\r\n\t}\r\n\r\n}\r\n```\r\n\r\n#### More Enum Basics\r\n\r\n- Enums can contain variables, methods, constructors. In example 2, we created a local variable called code with a getter. \r\n- We also created a constructor with code as a parameter.\r\n\r\n```\r\n//variable\r\nprivate int code;\r\n\r\n//method\r\npublic int getCode() {\r\n    return code;\r\n}\r\n\r\n//Constructor-only private or (default) \r\n//modifiers are allowed\r\nSeasonCustomized(int code) {\r\n    this.code = code;\r\n}\r\n```\r\n\r\nEach of the Season Type's is created by assigning a value for code.\r\n```\r\nWINTER(1), SPRING(2), SUMMER(3), FALL(4);\r\n```\r\n\r\nEnum constructors can only be (default) or (private) access. Enum constructors cannot be directly invoked.\r\n```\r\n/*//Enum constructor cannot be invoked directly\r\n  //Below line would cause COMPILER ERROR\r\nSeasonCustomized season2 = new SeasonCustomized(1);\r\n*/\r\n```\r\n\r\nExample below shows how we can use a switch around an enum.\r\n```\r\n// Using switch statement on an enum\r\npublic int getExpectedMaxTemperature() {\r\n\tswitch (this) {\r\n\tcase WINTER:\r\n\t\treturn 5;\r\n\tcase SPRING:\r\n\tcase FALL:\r\n\t\treturn 10;\r\n\tcase SUMMER:\r\n\t\treturn 20;\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\n```\r\n\r\n#### Enum Example 3 \r\n```\r\npackage com.in28minutes.java.beginners.concept.examples.enums;\r\n\r\npublic class EnumAdvanced2 {\r\n\r\n\t// Enum with a variable,method and constructor\r\n\tenum SeasonCustomized {\r\n\t\tWINTER(1) {\r\n\t\t\tpublic int getExpectedMaxTemperature() {\r\n\t\t\t\treturn 5;\r\n\t\t\t}\r\n\t\t},\r\n\t\tSPRING(2), SUMMER(3) {\r\n\t\t\tpublic int getExpectedMaxTemperature() {\r\n\t\t\t\treturn 20;\r\n\t\t\t}\r\n\t\t},\r\n\t\tFALL(4);\r\n\r\n\t\t// variable\r\n\t\tprivate int code;\r\n\r\n\t\t// method\r\n\t\tpublic int getCode() {\r\n\t\t\treturn code;\r\n\t\t}\r\n\r\n\t\t// Constructor-only private or (default)\r\n\t\t// modifiers are allowed\r\n\t\tSeasonCustomized(int code) {\r\n\t\t\tthis.code = code;\r\n\t\t}\r\n\r\n\t\tpublic int getExpectedMaxTemperature() {\r\n\t\t\treturn 10;\r\n\t\t}\r\n\r\n\t};\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tSeasonCustomized season = SeasonCustomized.WINTER;\r\n\r\n\t\tSystem.out.println(season.getExpectedMaxTemperature());// 5\r\n\r\n\t\tSystem.out.println(SeasonCustomized.FALL.getExpectedMaxTemperature());// 10\r\n\r\n\t}\r\n\r\n}\r\n```\r\nEnum Constant Class - In the example above, take a look at how the Winter Type is declared: It provides an overriding implementation for the getExpectedMaxTemperature method already declared in the Enum. This feature in an Enum is called a Constant Class.\r\n```\r\nWINTER(1) {\r\n    public int getExpectedMaxTemperature() {\r\n         return 5;\r\n    }\r\n}\r\n```\r\n\r\n### Inheritance\r\n\r\nInheritance allows extending a functionality of a class and also promotes reuse of existing code. \r\n\r\n#### Every Class extends Object class\r\n- Every class in Java is a sub class of the class Object. \r\n- When we create a class in Java, we inherit all the methods and properties of Object class.\r\n\r\n```\r\nString str = \"Testing\";\r\nSystem.out.println(str.toString());\r\nSystem.out.println(str.hashCode());\r\nSystem.out.println(str.clone());\r\n\r\nif(str instanceof Object){\r\n    System.out.println(\"I extend Object\");//Will be printed\r\n}\r\n```\r\n\r\nCreate a class Actor\r\n```\r\npublic class Actor {\r\n    public void act(){\r\n        System.out.println(\"Act\");\r\n    };\r\n}\r\n```\r\n\r\nWe can extend this class by using the keyword ```extends```. \r\n```Hero class extends Actor```\r\n\r\n```\r\n//IS-A relationship. Hero is-a Actor\r\npublic class Hero extends Actor {\r\n    public void fight(){\r\n       System.out.println(\"fight\");\r\n    };\r\n}\r\n```\r\n\r\nSince Hero extends Animal, the methods defined in Animal are also available through an instance of Hero class. \r\n```\r\nHero hero = new Hero();\r\n//act method inherited from Actor\r\nhero.act();//Act\r\nhero.fight();//fight\r\n```\r\n\r\nLet's look at another class extending Actor class - Comedian.\r\n```\r\n//IS-A relationship. Comedian is-a Actor\r\npublic class Comedian extends Actor {\r\n    public void performComedy(){\r\n       System.out.println(\"Comedy\");\r\n    };\r\n}\r\n```\r\n\r\nMethods in Animal class can be executed from an instance of Comedian class.\r\n\r\n```\r\nComedian comedian = new Comedian();\r\n//act method inherited from Actor\r\ncomedian.act();//Act\r\ncomedian.performComedy();//Comedy\r\n```\r\n\r\n#### Super class reference variable can hold an object of sub class\r\n\r\n```\r\nActor actor1 = new Comedian();\r\nActor actor2 = new Hero();\r\n```\r\n\r\nObject is super class of all classes. So, an Object reference variable can  hold an instance of any class.\r\n\r\n```\r\n//Object is super class of all java classes\r\nObject object = new Hero(); \r\n```\r\n\r\n#### Inheritance: IS-A Relationship\r\n\r\nWe should use inheritance only when there is an IS-A relationship between classes. For example, Comedian IS-A Actor, Hero IS-A Actor are both true. So, inheritance is correct relationship between classes.\r\n- Comedian is called a Sub Class. Actor is Super Class.\r\n\r\nMultiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.\r\n\r\n```\r\nclass Dog extends Animal, Pet { //COMPILER ERROR\r\n}\r\n```\r\n\r\nWe can create an inheritance chain.\r\n```\r\nclass Pet extends Animal {\r\n}\r\n\r\nclass Dog extends Pet {\r\n}\r\n```\r\n\r\n#### Inheritance and Polymorphism\r\n\r\nPolymorphism is defined as \"Same Code\" having \"Different Behavior\".  \r\n\r\nExample\r\n```\r\npublic class Animal {\r\n    public String shout() {\r\n        return \"Don't Know!\";\r\n    }\r\n}\r\n\r\nclass Cat extends Animal {\r\n    public String shout() {\r\n        return \"Meow Meow\";\r\n    }\r\n}\r\n\r\nclass Dog extends Animal {\r\n    public String shout() {\r\n        return \"BOW BOW\";\r\n    }\r\n\r\n    public void run(){\r\n\r\n    }\r\n}\r\n\r\n```\r\n\r\nExecution\r\n```\r\nAnimal animal1 = new Animal();\r\nSystem.out.println(animal1.shout()); //Don't Know!\r\n\r\nAnimal animal2 = new Dog();//Animal reference used to store Dog object\r\n\r\n//Reference variable type => Animal\r\n//Object referred to => Dog\r\n//Dog's bark method is called.\r\nSystem.out.println(animal2.shout()); //BOW BOW\r\n\r\n//Cannot invoke sub class method with super class reference variable.\r\n//animal2.run();//COMPILE ERROR\r\n\r\n```\r\n\r\n### Puzzle and Tips - instanceof Operator in depth\r\n\r\ninstanceof operator checks if an object is of a particular type.\r\n\r\n```\r\nclass SuperClass {\r\n};\r\n\r\nclass SubClass extends SuperClass {\r\n};\r\n\r\ninterface Interface {\r\n};\r\n\r\nclass SuperClassImplementingInteface implements Interface {\r\n};\r\n\r\nclass SubClass2 extends SuperClassImplementingInteface {\r\n};\r\n\r\nclass SomeOtherClass {\r\n};\r\n\r\nSubClass subClass = new SubClass();\r\nObject subClassObj = new SubClass();\r\n\r\nSubClass2 subClass2 = new SubClass2();\r\nSomeOtherClass someOtherClass = new SomeOtherClass();\r\n\r\n//We can run instanceof operator on the different instances created earlier.\r\nSystem.out.println(subClass instanceof SubClass);//true\r\nSystem.out.println(subClass instanceof SuperClass);//true\r\nSystem.out.println(subClassObj instanceof SuperClass);//true\r\n\r\nSystem.out.println(subClass2 instanceof SuperClassImplementingInteface);//true\r\n\r\n//instanceof can be used with interfaces as well. \r\n//Since Super Class implements the interface, below code prints true.\r\nSystem.out.println(subClass2 \r\ninstanceof Interface);//true\r\n\r\n//If the type compared is unrelated to the object, a compilation error occurs.\r\n//System.out.println(subClass \r\n//    instanceof SomeOtherClass);//Compiler Error\r\n\r\n//Object referred by subClassObj(SubClass)- NOT of type SomeOtherClass\r\nSystem.out.println(subClassObj instanceof SomeOtherClass);//false\r\n```\r\n\r\n### Class, Object, State and Behavior\r\n- In this tutorial, lets look at a few important object oriented concepts.\r\n\r\n#### Class, Object, State and Behavior Example\r\n\r\n```\r\npackage com.in28minutes;\r\n\r\npublic class CricketScorer {\r\n    //Instance Variables - constitute the state of an object\r\n    private int score;\r\n\r\n    //Behavior - all the methods that are part of the class\r\n    //An object of this type has behavior based on the \r\n    //methods four, six and getScore\r\n    public void four(){\r\nscore = score + 4;\r\n    }\r\n    \r\n    public void six(){\r\nscore = score + 6;\r\n    }\r\n    \r\n    public int getScore() {\r\nreturn score;\r\n    }\r\n    \r\n    public static void main(String[] args) {\r\nCricketScorer scorer = new CricketScorer();\r\nscorer.six();\r\n//State of scorer is (score => 6)\r\nscorer.four();\r\n//State of scorer is (score => 10)\r\nSystem.out.println(scorer.getScore());\r\n    }\r\n}\r\n```\r\n\r\n#### Class\r\nA class is a Template. \r\n- In above example, class CricketScorer is the template for creating multiple objects. \r\n\r\nA class defines state and behavior that an object can exhibit.\r\n\r\n#### Object\r\nAn instance of a class. \r\n- In the above example, we create an object using new CricketScorer(). \r\n- The reference of the created object is stored in scorer variable. \r\n- We can create multiple objects of the same class.\r\n\r\n#### State\r\nState represents the values assigned to instance variables of an object at a specific time.  \r\n\r\nConsider following code snippets from the above example. \r\n- The value in score variable is initially 0. \r\n- It changes to 6 and then 10. \r\n\r\nState of an object might change with time. \r\n\r\n```\r\nscorer.six();\r\n//State of scorer is (score => 6)\r\n\r\nscorer.four();\r\n//State of scorer is (score => 10)\r\n```\r\n\r\n#### Behavior\r\n\r\nBehaviour of an object represents the different methods that are supported by it. \r\n- Above example the behavior supported is six(), four() and getScore().\r\n\r\n### toString method\r\ntoString() method in Java is used to print the content of an object.\r\n\r\nExample\r\n```\r\nclass Animal {\r\n\r\n    public Animal(String name, String type) {\r\n      this.name = name;\r\n      this.type = type;\r\n    }\r\n\r\n    String name;\r\n    String type;\r\n\r\n}\r\n\r\n\r\n\r\nAnimal animal = new Animal(\"Tommy\", \"Dog\");\r\n\r\n//Output does not show the content of animal (what name? and what type?).\r\nSystem.out.println(animal);//com.in28minutes.Animal@f7e6a96\r\n\r\nTo show the content of the animal object, we can override the default implementation of toString method provided by Object class.\r\n\r\n//Adding toString to Animal class\r\nclass Animal {\r\n    \r\n    public Animal(String name, String type) {\r\n        this.name = name;\r\n        this.type = type;\r\n    }\r\n\r\n    String name;\r\n    String type;\r\n\r\n    public String toString() {\r\n        return \"Animal [name=\" + name + \", type=\" + type + \"]\";\r\n    }\r\n\r\n}\r\n\r\nAnimal animal = new Animal(\"Tommy\",\"Dog\");\r\n\r\n//Output now shows the content of the animal object. \r\nSystem.out.println(animal);//Animal [name=Tommy, type=Dog]\r\n```\r\n\r\n### equals method\r\n\r\nequals method is used to compare if two objects are having the same content.\r\n- Default implementation of equals method is defined in Object class. The implementation is similar to == operator. \r\n- By default, two object references are equal only if they are pointing to the same object.\r\n- However, we can override equals method and provide a custom implementation to compare the contents for an object.\r\n\r\nExample\r\n```\r\nclass Client {\r\n    private int id;\r\n\r\n    public Client(int id) {\r\n      this.id = id;\r\n    }\r\n\r\n    @Override\r\n    public int hashCode() {\r\n      final int prime = 31;\r\n      int result = 1;\r\n      result = prime * result + id;\r\n      return result;\r\n    }\r\n}\r\n\r\n// == comparison operator checks if the object references are pointing to the same object. \r\n// It does NOT look at the content of the object.\r\nClient client1 = new Client(25);\r\nClient client2 = new Client(25);\r\nClient client3 = client1;\r\n\r\n//client1 and client2 are pointing to different client objects.\r\nSystem.out.println(client1 == client2);//false\r\n\r\n//client3 and client1 refer to the same client objects.\r\nSystem.out.println(client1 == client3);//true\r\n\r\n//similar output to ==\r\nSystem.out.println(client1.equals(client2));//false\r\nSystem.out.println(client1.equals(client3));//true\r\n\r\n//overriding equals method\r\nclass Client {\r\n    private int id;\r\n\r\n    public Client(int id) {\r\n      this.id = id;\r\n    }\r\n\r\n    @Override\r\n    public boolean equals(Object obj) {\r\n      Client other = (Client) obj;\r\n      if (id != other.id)\r\n          return false;\r\n      return true;\r\n    }\r\n}\r\n```\r\n\r\nSignature of the equals method is \"public boolean equals(Object obj) \". \r\n- Note that \"public boolean equals(Client client)\" will not override the equals method defined in Object. Parameter should be of type Object.\r\n- The implementation of equals method checks if the id's of both objects are equal. If so, it returns true. \r\n- Note that this is a basic implementation of equals.\r\n\r\nExample\r\n```\r\nClient client1 = new Client(25);\r\nClient client2 = new Client(25);\r\nClient client3 = client1;\r\n\r\n//both id's are 25\r\nSystem.out.println(client1.equals(client2));//true\r\n\r\n//both id's are 25\r\nSystem.out.println(client1.equals(client3));//true\r\n```\r\nAny equals implementation should satisfy these properties:\r\n- Reflexive. For any reference value x, x.equals(x) returns true.\r\n- Symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.\r\n- Transitive. For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.\r\n- Consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, if no information used in equals is modified.\r\n- For any non-null reference value x, x.equals(null) should return false.\r\n\r\nLet's now provide an implementation of equals which satisfy these properties:\r\n\r\n```\r\n//Client class\r\n@Override\r\npublic boolean equals(Object obj) {\r\n    if (this == obj)\r\nreturn true;\r\n    if (obj == null)\r\nreturn false;\r\n    if (getClass() != obj.getClass())\r\nreturn false;\r\n    Client other = (Client) obj;\r\n    if (id != other.id)\r\nreturn false;\r\n    return true;\r\n}\r\n```\r\n\r\n### hashCode method\r\n- HashCode's are used in hashing to decide which group (or bucket) an object should be placed into. \r\n   - A group of object's might share the same hashcode. \r\n   - The implementation of hash code decides effectiveness of Hashing. \r\n   - A good hashing function evenly distributes object's into different groups (or buckets).\r\n\r\nhashCode method properties \r\n- If obj1.equals(obj2) is true, then obj1.hashCode() should be equal to obj2.hashCode()\r\n- obj.hashCode() should return the same value when run multiple times, if values of obj used in equals() have not changed.\r\n- If obj1.equals(obj2) is false, it is NOT required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.\r\n\r\nExample\r\n```\r\n//Client class\r\n@Override\r\npublic int hashCode() {\r\n    final int prime = 31;\r\n    int result = 1;\r\n    result = prime * result + id;\r\n    return result;\r\n}\r\n```\r\n\r\n### Abstract Class\r\nAn abstract class cannot be instantiated.\r\n\r\n```\r\npublic abstract class AbstractClassExample {\r\n    public static void main(String[] args) {\r\n      //An abstract class cannot be instantiated\r\n      //Below line gives compilation error if uncommented\r\n      //AbstractClassExample ex = new AbstractClassExample();\r\n    }\r\n}\r\n\r\n//Abstract class can contain instance and static variables\r\n\r\npublic abstract class AbstractClassExample {\r\n    \r\n    //Abstract class can contain instance and static variables\r\n    public int publicVariable;\r\n    private int privateVariable;\r\n    static int staticVariable;\r\n\r\n}\r\n\r\n//An Abstract method does not contain body.\r\n//Abstract Class can contain 0 or more abstract methods\r\n//Abstract method does not have a body\r\nabstract void abstractMethod1();\r\nabstract void abstractMethod2();\r\n\r\n//Abstract method can be declared only in Abstract Class. \r\nclass NormalClass{\r\n    abstract void abstractMethod();//COMPILER ERROR\r\n}\r\n\r\n// Abstract class can contain fully defined non-abstract methods. \r\npublic abstract class AbstractClassExample {\r\n    \r\n    //Abstract class can contain instance and static variables\r\n    public int publicVariable;\r\n    private int privateVariable;\r\n    static int staticVariable;\r\n    \r\n    //Abstract Class can contain 0 or more abstract methods\r\n    //Abstract method does not have a body\r\n    abstract void abstractMethod1();\r\n    abstract void abstractMethod2();\r\n    \r\n    //Abstract Class can contain 0 or more non-abstract methods\r\n    public void nonAbstractMethod(){\r\n      System.out.println(\"Non Abstract Method\");\r\n    }    \r\n    \r\n    public static void main(String[] args) {\r\n      //An abstract class cannot be instantiated\r\n      //Below line gives compilation error if uncommented\r\n      //AbstractClassExample ex = new AbstractClassExample();\r\n    }\r\n}\r\n\r\n//Extending an abstract class\r\nclass SubClass2 extends AbstractClassExample {\r\n    void abstractMethod1() {\r\n      System.out.println(\"Abstract Method1\");\r\n    }\r\n\r\n    void abstractMethod2() {\r\n      System.out.println(\"Abstract Method2\");\r\n    }\r\n}\r\n\r\n// A concrete sub class should implement all abstract methods.\r\n// Below class gives compilation error if uncommented\r\n/*\r\nclass SubClass extends AbstractClassExample {\r\n    \r\n}\r\n*/\r\n\r\n//An abstract sub class need not implement all abstract methods.\r\nabstract class AbstractSubClass extends AbstractClassExample {\r\n    void abstractMethod1() {\r\n      System.out.println(\"Abstract Method1\");\r\n    }\r\n    //abstractMethod2 is not defined.\r\n}\r\n```\r\n\r\nTips\r\n- Abstract Methods cannot be paired with final or private access modifiers.\r\n- A variable cannot be abstract.\r\n\r\n### Constructors\r\n- Constructor is invoked whenever we create an instance(object) of a Class. We cannot create an object without a constructor. If we do not provide a constructor, compiler provides a default no-argument constructor.\r\n\r\n#### Constructor Example 1: Default Constructor\r\nIn the example  below, there are no Constructors defined in the Animal class. Compiler provides us with a default constructor, which helps us create an instance of animal class.\r\n\r\n```\r\npublic class Animal {\r\n    String name;\r\n\r\n    public static void main(String[] args) {\r\n// Compiler provides this class with a default no-argument constructor.\r\n// This allows us to create an instance of Animal class.\r\nAnimal animal = new Animal();\r\n    }\r\n}\r\n```\r\n#### Constructor Example 2: Creating a Constructor\r\nIf we provide a constructor in the class, compiler will NOT provide a default constructor. In the example below we provided a constructor \"public Animal(String name)\". So, compiler will not provide the default constructor.\r\n\r\nConstructor has the same name as the class and no return type. It can accept any number of parameters.\r\n\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    // This is called a one argument constructor.\r\n    public Animal(String name) {\r\nthis.name = name;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n// Since we provided a constructor, compiler does not\r\n// provide a default constructor.\r\n// Animal animal = new Animal();//COMPILER ERROR!\r\n\r\n// The only way we can create Animal1 object is by using\r\nAnimal animal = new Animal(\"Tommy\");\r\n    }\r\n}\r\n```\r\n#### Constructor Example 3: Provide No Argument Constructor\r\nIf we want to allow creation of an object with no constructor arguments, we can provide a no argument constructor as well.\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    public Animal() {\r\nthis.name = \"Default Name\";\r\n    }\r\n\r\n    // This is called a one argument constructor.\r\n    public Animal(String name) {\r\nthis.name = name;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n// Since we provided a constructor, compiler does not\r\n// provide a default constructor.\r\n// Animal animal = new Animal();//COMPILER ERROR!\r\n\r\n// The only way we can create Animal1 object is by using\r\nAnimal animal = new Animal(\"Tommy\");\r\n    }\r\n}\r\n```\r\n\r\n#### Constructor Example 4: Calling a Super Class Constructor\r\nA constructor can invoke another constructor, or a super class constructor, but only as first statement in the constructor. Another constructor in the same class can be invoked from a constructor, using this({parameters}) method call. To call a super class constructor, super({parameters}) can be used.\r\n\r\nBoth example constructors below can replace the no argument \"public Animal() \" constructor in Example 3.\r\n\r\n```\r\npublic Animal() {\r\n    super();\r\n    this.name = \"Default Name\";\r\n}\r\n\r\npublic Animal() {\r\n    this(\"Default Name\");\r\n}\r\n```\r\n\r\n#### super() or this() should be first statements in a Constructor.\r\nBelow examples will throw a compilation error if the super or this calls are uncommented.\r\n\r\n```\r\npublic Animal() {\r\n    this.name = \"Default Name\";\r\n    //super(), if called, should always the first statement in a constructor.\r\n    //super(); //COMPILER ERROR\r\n}\r\n\r\npublic Animal() {\r\n    System.out.println(\"Creating an Animal\");\r\n    //this(string), if called, should always the first statement in a constructor.\r\n    //this(\"Default Name\");//COMPILER ERROR\r\n}\r\n```\r\n#### Constructor Example 5 \r\nMember variables/methods should not be used in constructor calls (super or this). Static variables or methods can be used.\r\n```\r\npublic Animal() {\r\n    //member variable cannot be used in a constructor call\r\n    this(name);//COMPILER ERROR since name is member variable\r\n}\r\n```\r\n#### Constructor Example 6: Constructor cannot be directly called  \r\nA constructor cannot be explicitly called from any method except another constructor.\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    public Animal() {\r\n    }\r\n\r\n    public method() {\r\nAnimal();// Compiler error\r\n    }\r\n}\r\n```\r\n#### Constructor Example 7: Super Class Constructor is invoked automatically\r\nIf a super class constructor is not explicitly called from a sub class constructor, super class (no argument) constructor is automatically invoked (as first line) from a sub class constructor.\r\n\r\nConsider the example below:\r\n\r\n```\r\nclass Animal {\r\n    public Animal() {\r\nSystem.out.println(\"Animal Constructor\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal {\r\n    public Dog() {\r\nSystem.out.println(\"Dog Constructor\");\r\n    }\r\n}\r\n\r\nclass Labrador extends Dog {\r\n    public Labrador() {\r\nSystem.out.println(\"Labrador Constructor\");\r\n    }\r\n}\r\n\r\npublic class ConstructorExamples {\r\n    public static void main(String[] args) {\r\nLabrador labrador = new Labrador();\r\n    }\r\n}\r\n//Output - Animal Constructor\r\nDog Constructor\r\nLabrador Constructor\r\n```\r\n\r\nIt is almost as if super() method is invoked as the first line of every constructor. The example code below shows how the code above behaves.\r\n\r\n```\r\nclass Animal {\r\n    public Animal() {\r\nsuper();// IMPLICIT CALL\r\nSystem.out.println(\"Animal Constructor\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal {\r\n    public Dog() {\r\nsuper();// IMPLICIT CALL\r\nSystem.out.println(\"Dog Constructor\");\r\n    }\r\n}\r\n\r\nclass Labrador extends Dog {\r\n    public Labrador() {\r\nsuper();// IMPLICIT CALL\r\nSystem.out.println(\"Labrador Constructor\");\r\n    }\r\n}\r\n```\r\n#### Constructor Example 8\r\nSince a subclass constructor explicitly calls a super class constructor with no arguments, this can cause a few compiler errors. \r\n\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    public Animal(String name) {\r\nthis.name = name;\r\nSystem.out.println(\"Animal Constructor\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal {\r\n    public Dog() { // COMPILER ERROR! No constructor for Animal()\r\nSystem.out.println(\"Dog Constructor\");\r\n    }\r\n}\r\n```\r\n\r\npublic Dog() makes an implicit super() call i.e. a call to Animal() (no argument) constructor. But no such constructor is defined in Animal class.\r\n#### Constructor Example 9\r\n\r\nSimilar example below except that the Dog no argument constructor is not provided by programmer. However, the compiler would give the no argument constructor, which would invoke super() method.  This would again result in a compilation error.\r\n\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    public Animal(String name) {\r\nthis.name = name;\r\nSystem.out.println(\"Animal Constructor\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal {// COMPILER ERROR! No constructor for Animal()\r\n}\r\n```\r\n\r\nTwo ways to fix above errors. \r\n1.Create a no arguments constructor in Animal class.\r\n2.Make a explicit super(\"Default Dog Name\") call in the Dog() constructor.\r\n\r\n#### Creating a super class no argument constructor\r\n\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    public Animal() {\r\n    }\r\n\r\n    public Animal(String name) {\r\nthis.name = name;\r\nSystem.out.println(\"Animal Constructor\");\r\n    }\r\n}\r\n```\r\n#### Making an explicity super call\r\n```\r\nclass Dog extends Animal {\r\n    public Dog() { // COMPILER ERROR! No constructor for Animal()\r\nsuper(\"Default Dog Name\");\r\nSystem.out.println(\"Dog Constructor\");\r\n    }\r\n}\r\n```\r\n#### Constructors are NOT inherited.\r\n```\r\nclass Animal {\r\n    String name;\r\n\r\n    public Animal(String name) {\r\nthis.name = name;\r\nSystem.out.println(\"Animal Constructor with name\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal {\r\n}\r\n\r\npublic class ConstructorExamples {\r\n    public static void main(String[] args) {\r\n// Dog dog = new Dog(\"Terry\");//COMPILER ERROR\r\n    }\r\n}\r\n```\r\n\r\nnew Dog(\"Terry\") is not allowed even though there is a constructor in the super class Animal with signature public Animal(String name).\r\n\r\nSolution is to create an explicit constructor in sub class invoking the super class constructor. Add below constructor to Dog class.\r\n\r\n```\r\nclass Dog extends Animal {\r\n    public Dog() {\r\nsuper(\"Default Dog Name\");\r\n    }\r\n}\r\n```\r\n### Coupling\r\n- Coupling is a measure of how much a class is dependent on other classes. There should minimal dependencies between classes. So, we should always aim for low coupling between classes.\r\n\r\n#### Coupling Example Problem\r\nConsider the example below:\r\n```\r\nclass ShoppingCartEntry {\r\n    public float price;\r\n    public int quantity;\r\n}\r\n\r\nclass ShoppingCart {\r\n    public ShoppingCartEntry[] items;\r\n}\r\n\r\nclass Order {\r\n    private ShoppingCart cart;\r\n    private float salesTax;\r\n\r\n    public Order(ShoppingCart cart, float salesTax) {\r\nthis.cart = cart;\r\nthis.salesTax = salesTax;\r\n    }\r\n\r\n    // This method know the internal details of ShoppingCartEntry and\r\n    // ShoppingCart classes. If there is any change in any of those\r\n    // classes, this method also needs to change.\r\n    public float orderTotalPrice() {\r\nfloat cartTotalPrice = 0;\r\nfor (int i = 0; i < cart.items.length; i++) {\r\n    cartTotalPrice += cart.items[i].price\r\n    * cart.items[i].quantity;\r\n}\r\ncartTotalPrice += cartTotalPrice * salesTax;\r\nreturn cartTotalPrice;\r\n    }\r\n}\r\n```\r\n\r\nMethod orderTotalPrice in Order class is coupled heavily with ShoppingCartEntry and ShoppingCart classes.  It uses different properties (items, price, quantity) from these classes. If any of these properties change, orderTotalPrice will also change. This is not good for Maintenance. \r\n#### Coupling Example Solution\r\n\r\nConsider a better implementation with lesser coupling between classes below: In this implementation, changes in ShoppingCartEntry or CartContents might not affect Order class at all.\r\n\r\n```\r\nclass ShoppingCartEntry\r\n{\r\n    float price;\r\n    int quantity;\r\n\r\n    public float getTotalPrice()\r\n    {\r\nreturn price * quantity;\r\n    }\r\n}\r\n\r\nclass CartContents\r\n{\r\n    ShoppingCartEntry[] items;\r\n\r\n    public float getTotalPrice()\r\n    {\r\nfloat totalPrice = 0;\r\nfor (ShoppingCartEntry item:items)\r\n{\r\n    totalPrice += item.getTotalPrice();\r\n}\r\nreturn totalPrice;\r\n    }\r\n}\r\n\r\nclass Order\r\n{\r\n    private CartContents cart;\r\n    private float salesTax;\r\n\r\n    public Order(CartContents cart, float salesTax)\r\n    {\r\nthis.cart = cart;\r\nthis.salesTax = salesTax;\r\n    }\r\n\r\n    public float totalPrice()\r\n    {\r\nreturn cart.getTotalPrice() * (1.0f + salesTax);\r\n    }\r\n}\r\n```\r\n### Cohesion\r\n- Cohesion is a measure of how related the responsibilities of a class are.  A class must be highly cohesive i.e. its responsibilities (methods) should be highly related to one another.\r\n\r\n#### Cohesion Example Problem\r\nExample class below is downloading from internet, parsing data and storing data to database. The responsibilities of this class are not really related. This is not cohesive class.\r\n```\r\nclass DownloadAndStore{\r\n    void downloadFromInternet(){\r\n    }\r\n    \r\n    void parseData(){\r\n    }\r\n    \r\n    void storeIntoDatabase(){\r\n    }\r\n    \r\n    void doEverything(){\r\ndownloadFromInternet();\r\nparseData();\r\nstoreIntoDatabase();\r\n    }\r\n}\r\n```\r\n#### Cohesion Example Solution\r\nThis is a better way of approaching the problem. Different classes have their own responsibilities.\r\n\r\n```\r\nclass InternetDownloader {\r\n    public void downloadFromInternet() {\r\n    }\r\n}\r\n\r\nclass DataParser {\r\n    public void parseData() {\r\n    }\r\n}\r\n\r\nclass DatabaseStorer {\r\n    public void storeIntoDatabase() {\r\n    }\r\n}\r\n\r\nclass DownloadAndStore {\r\n    void doEverything() {\r\nnew InternetDownloader().downloadFromInternet();\r\nnew DataParser().parseData();\r\nnew DatabaseStorer().storeIntoDatabase();\r\n    }\r\n}\r\n```\r\n### Encapsulation\r\n- Encapsulation is Òhiding the implementation of a Class behind a well defined interfaceÓ. Encapsulation helps us to change implementation of a class without breaking other code.\r\n\r\n#### Encapsulation Approach 1\r\nIn this approach we create a public variable score. The main method directly accesses the score variable, updates it.\r\n#### Example Class\r\n```\r\npublic class CricketScorer {\r\n    public int score;\r\n}\r\n```\r\n\r\nLet's use the CricketScorer class.\r\n```\r\npublic static void main(String[] args) {\r\nCricketScorer scorer = new CricketScorer();\r\nscorer.score = scorer.score + 4;\r\n}\r\n```\r\n#### Encapsulation Approach 2\r\nIn this approach, we make score as private and access value through get and set methods. However, the logic of adding 4 to the score is performed in the main method.\r\n#### Example Class\r\n```\r\npublic class CricketScorer {\r\n    private int score;\r\n\r\n    public int getScore() {\r\nreturn score;\r\n    }\r\n\r\n    public void setScore(int score) {\r\nthis.score = score;\r\n    }\r\n}\r\n```\r\n\r\nLet's use the CricketScorer class.\r\n\r\n```\r\npublic static void main(String[] args) {\r\nCricketScorer scorer = new CricketScorer();\r\n\r\nint score = scorer.getScore();\r\nscorer.setScore(score + 4);\r\n}\r\n```\r\n#### Encapsulation Approach 3\r\nIn this approach - For better encapsulation, the logic of doing the four operation also is moved to the CricketScorer class.\r\n#### Example Class\r\n```\r\npublic class CricketScorer {\r\n    private int score;\r\n    \r\n    public void four() {\r\nscore += 4;\r\n    }\r\n\r\n}\r\n```\r\n\r\nLet's use the CricketScorer class.\r\n```\r\npublic static void main(String[] args) {\r\n  CricketScorer scorer = new CricketScorer();\r\n  scorer.four();\r\n}\r\n```\r\n#### Encapsulation Example\r\nIn terms of encapsulation Approach 3 > Approach 2 > Approach 1. In Approach 3, the user of scorer class does not even know that there is a variable called score. Implementation of Scorer can change without changing other classes using Scorer.\r\n\r\n### Interface\r\n- An interface defines a contract for  responsibilities (methods) of a class. Let's look at a few examples of interfaces.\r\n\r\n#### Defining an Interface\r\nAn interface is declared by using the keyword interface. Look at the example below: Flyable is an interface.\r\n```\r\n//public abstract are not necessary\r\npublic abstract interface Flyable {\r\n    //public abstract are not necessary\r\n    public abstract void fly();\r\n}\r\n```\r\n#### An interface can contain abstract methods -- NOT TRUE ANY MORE\r\nIn the above example, fly method is abstract since it is only declared (No definition is provided).\r\n#### Implementing an Interface\r\nWe can define a class implementing the interface by using the implements keyword. Let us look at a couple of examples:\r\n#### Example 1\r\nClass Aeroplane implements Flyable and implements the abstract method fly().\r\n```\r\npublic class Aeroplane implements Flyable{\r\n    @Override\r\n    public void fly() {\r\nSystem.out.println(\"Aeroplane is flying\");\r\n    }\r\n}\r\n```\r\n#### Example 2\r\n```\r\npublic class Bird implements Flyable{\r\n    @Override\r\n    public void fly() {\r\nSystem.out.println(\"Bird is flying\");\r\n    }\r\n}\r\n```\r\n#### Using the Interface and Implementation\r\nThe interface classes can directly be instantiated and stored in the class reference variables\r\n```\r\nBird bird = new Bird();\r\nbird.fly();//Bird is flying\r\n\r\nAeroplane aeroplane = new Aeroplane();\r\naeroplane.fly();//Aeroplane is flying\r\n```\r\n\r\nAn interface reference variable can hold objects of any implementation of interface.\r\n```\r\nFlyable flyable1 = new Bird();\r\nFlyable flyable2 = new Aeroplane();\r\n```\r\n#### Variables in  an interface\r\nVariables in an interface are always public, static, final. Variables in an interface cannot be declared private.\r\n```\r\ninterface ExampleInterface1 {\r\n    //By default - public static final. No other modifier allowed\r\n    //value1,value2,value3,value4 all are - public static final\r\n    int value1 = 10;\r\n    public int value2 = 15;\r\n    public static int value3 = 20;\r\n    public static final int value4 = 25;\r\n    //private int value5 = 10;//COMPILER ERROR\r\n}\r\n```\r\n#### Methods in an interface\r\nInterface methods are by default public and abstract. A concrete default method (fully defined method) can be created in an interface. Consider the example below:\r\n```\r\ninterface ExampleInterface1 {\r\n    //By default - public abstract. No other modifier allowed\r\n    void method1();//method1 is public and abstract\r\n    //private void method6();//COMPILER ERROR!\r\n    \r\n}\r\n```\r\n#### Extending an Interface\r\nAn interface can extend another interface. Consider the example below:\r\n\r\n```\r\ninterface SubInterface1 extends ExampleInterface1{\r\n    void method3();\r\n}\r\n```\r\n\r\nClass implementing SubInterface1 should implement both methods - method3 and method1(from ExampleInterface1)\r\nAn interface cannot extend a class.\r\n\r\n```\r\n/* //COMPILE ERROR IF UnCommented\r\n   //Interface cannot extend a Class\r\ninterface SubInterface2 extends Integer{\r\n    void method3();\r\n}\r\n*/\r\n```\r\n\r\nA class can implement multiple interfaces. It should implement all the method declared in all Interfaces being implemented.\r\n\r\n```\r\ninterface ExampleInterface2 {\r\n    void method2();\r\n}\r\n\r\nclass SampleImpl implements ExampleInterface1,ExampleInterface2{\r\n    /* A class should implement all the methods in an interface.\r\n       If either of method1 or method2 is commented, it would \r\n       result in compilation error. \r\n     */\r\n    public void method2() {\r\nSystem.out.println(\"Sample Implementation for Method2\");\r\n    }\r\n\r\n    public void method1() {\r\nSystem.out.println(\"Sample Implementation for Method1\");\r\n    }\r\n    \r\n}\r\n```\r\n#### Interface , Things to Remember\r\nA class should implement all the methods in an interface, unless it is declared abstract.\r\nA Class can implement multiple interfaces.\r\nNo new checked exceptions can be thrown by implementations of methods in an interface.\r\n\r\n### Method Overloading\r\n- A method having the same name as another method (in same class or a sub class) but having different parameters is called an Overloaded Method.\r\n\r\n#### Method Overloading Example 1\r\ndoIt method is overloaded in the below example:\r\n```\r\nclass Foo{\r\n    public void doIt(int number){\r\n\r\n    }\r\n    public void doIt(String string){\r\n\r\n    }\r\n}\r\n```\r\n#### Method Overloading Example 2\r\nOverloading can also be done from a sub class.\r\n```\r\nclass Bar extends Foo{\r\n    public void doIt(float number){\r\n\r\n    }\r\n}\r\n```\r\n#### Overloading - Other Rules\r\nAn overloaded method should have different arguments than the original method. It can also have a different return type.\r\nA method cannot be overloaded just by only changing the return type.\r\nOverloaded methods are always treated as if they are different methods altogether.\r\nOverloading does not put any restrictions on access modifiers or exceptions thrown from the method.\r\nOverloaded method invocation is based on the Type of the Reference variable. It is NOT based on the object it refers to.\r\n\r\n- Java Example\r\n  - Constructors\r\n  - public HashMap(int initialCapacity, float loadFactor)\r\n  - public HashMap() {\r\n  - public HashMap(int initialCapacity)\r\n  - Methods  \r\n  - public boolean addAll(Collection<? extends E> c)\r\n  - public boolean addAll(int index, Collection<? extends E> c)\r\n- [Rules](src/main/java/com/in28minutes/java/oops/inheritance/overloading/OverloadingRules.java)\r\n\r\n### Method Overriding\r\n- Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method Overriding.\r\n\r\n#### Method Overriding Example 1:\r\nLet's define an Animal class with a method shout.\r\n```\r\npublic class Animal {\r\n    public String bark() {\r\nreturn \"Don't Know!\";\r\n    }\r\n}\r\n```\r\n\r\nLet's create a sub class of Animal , Cat  - overriding the existing shout method in Animal.\r\n```\r\nclass Cat extends Animal {\r\n    public String bark() {\r\nreturn \"Meow Meow\";\r\n    }\r\n}\r\n```\r\n\r\nbark method in Cat class is overriding the bark method in Animal class.\r\n\r\n- Java Example\r\n  - HashMap public int size() overrides AbstractMap public int size()\r\n- [Example](src/main/java/com/in28minutes/java/oops/inheritance/overriding/OverridingRules.java)\r\n\r\n\r\n#### Overriding Method Cannot have lesser visibility\r\nOverriding method cannot have lesser visibility than the Super Class method. Consider these two examples\r\n#### Example 1\r\n```\r\nclass SuperClass{\r\n    public void publicMethod(){\r\n\r\n    }\r\n}\r\n\r\nclass SubClass{\r\n    //Cannot reduce visibility of SuperClass Method\r\n    //So, only option is public\r\n    public void publicMethod() {\r\n\r\n    }    \r\n}\r\n```\r\n\r\npublicMethod in SubClass can only be declared as public. Keyword protected, private or (default) instead of public would result in Compilation Error.\r\n#### Example 2\r\n```\r\nclass SuperClass{\r\n    void defaultMethod(){\r\n\r\n    }\r\n}\r\n\r\nclass SubClass{\r\n    //Can be overridden with public,(default) or protected\r\n    //private would give COMPILE ERROR!\r\n    public void defaultMethod(){\r\n\r\n    }\r\n    \r\n}\r\n```\r\n\r\ndefaultMethod in SuperClass is declared with default access. Any method overriding it can have access default or greater. So default, protected and public are fine. Overriding method cannot be private.\r\n#### Overriding method cannot throw new Checked Exceptions\r\nConsider the example below:\r\n```\r\nclass SuperClass{\r\n    public void publicMethod() throws FileNotFoundException{\r\n\r\n    }\r\n}\r\n\r\nclass SubClass{\r\n    //Cannot throw bigger exceptions than Super Class\r\n    public void publicMethod() /*throws IOException*/ {\r\n\r\n    }\r\n}\r\n```\r\npublicMethod() in SuperClass throws FileNotFoundException. So, the SubClass publicMethod() can throw FileNotFoundException or any sub class of FileNotFoundException. It can also not throw an Exception (as in the example). But, it cannot throw any new Exception. For example, Òpublic void publicMethod() throws IOExceptionÓ would cause compilation error.\r\n\r\n#### Other Overriding Rules\r\nA Sub Class can override only those methods that are visible to it.\r\nMethods marked as static or final cannot be overridden.\r\nYou can call the super class method from the overriding method using keyword super.\r\n#### Overriding and Polymorphism Example\r\nOverridden method invocation is based on the object referred to. It is not based on the Type of the Reference variable. This is called Polymorphism. Consider the example below:\r\n\r\n```\r\nclass Animal{\r\n    public void bark(){\r\nSystem.out.println(\"Animal Bark\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal{\r\n    public void bark(){\r\nSystem.out.println(\"Dog Bark\");\r\n    }\r\n}\r\n\r\npublic class PolymorphismExample {\r\n    public static void main(String[] args) {\r\n\r\nAnimal[] animals = {new Dog(),new Animal()};\r\n\r\nanimals[0].bark();//Dog bark\r\nanimals[1].bark();//Animal bark\r\n    }\r\n\r\n}\r\n```\r\n\r\nanimals[0] contains a reference to Dog Object. When animals[0].bark() method is called method in Dog class is invoked even though the type of reference variable is Animal. \r\nanimals[1] contains a reference to Animal Object. When animals[1].bark() method is called method in Animal class is invoked.\r\n#### Covariant Returns\r\nA sub class is considered to be of same type as its super class. So, in interfaces or abstract class, it is fine to provide implementations using the Sub Class Types as Return Types.(com.in28minutes.SameType)\r\n### Class Modifiers\r\n- Let us learn about a few Java Class Modifiers.\r\n\r\n#### Access Modifiers\r\nAccess modifier for a class can be public or (default), It cannot be private or protected.\r\n```\r\npublic class PublicClass{\r\n    \r\n}\r\n\r\nclass DefaultClass{\r\n    \r\n}\r\n\r\nprotected class Error{//COMPILER ERROR\r\n    \r\n}\r\n\r\nprivate class Error{//COMPILER ERROR\r\n    \r\n}\r\n```\r\n#### Non-access modifiers \r\nstrictfp, final, abstract modifiers are valid on a class.\r\n### Class Access Modifiers\r\n- Lets learn about a few Java Class Access Modifiers.\r\n\r\n#### public class modifier\r\nA public class is visible to all other classes.\r\n#### default class modifier\r\nA class is called a Default Class is when there is no access modifier specified on a class. \r\nDefault classes are visible inside the same package only. \r\nDefault access is also called Package access.\r\n#### Default Class Modifier Examples\r\n#### Default Access Class Example\r\npackage com.in28minutes.classmodifiers.defaultaccess.a;\r\n\r\n```\r\n/* No public before class. So this class has default access*/\r\nclass DefaultAccessClass {\r\n//Default access is also called package access    \r\n}\r\n```\r\n\r\n#### Another Class in Same Package: Has access to default class\r\n```\r\npackage com.in28minutes.classmodifiers.defaultaccess.a;\r\n\r\npublic class AnotherClassInSamePackage {\r\n    //DefaultAccessClass and AnotherClassInSamePackage \r\n    //are in same package.\r\n    //So, DefaultAccessClass is visible.\r\n    //An instance of the class can be created.    \r\n    DefaultAccessClass defaultAccess;\r\n}\r\n```\r\n#### Class in Different Package: NO access to default class\r\n```\r\npackage com.in28minutes.classmodifiers.defaultaccess.b;\r\n\r\npublic class ClassInDifferentPackage {\r\n    //Class DefaultAccessClass and Class ClassInDifferentPackage\r\n    //are in different packages (*.a and *.b)\r\n    //So, DefaultAccessClass is not visible to ClassInDifferentPackage\r\n    \r\n    //Below line of code will cause compilation error if uncommented\r\n    //DefaultAccessClass defaultAccess; //COMPILE ERROR!!    \r\n}\r\n```\r\n### Method and Variable Access Modifiers\r\n- Method and variable access modifiers can be public, protected, private or (default)\r\n\r\n#### Two Access Modifier Questions\r\nWhen we talk about access modifiers, we would discuss two important questions\r\n#### Is Accessible through reference/instance variable?\r\nWe create an instance of the class and try to access the variables and methods declared in the class.\r\n```\r\nExampleClass example = new ExampleClass();\r\n\r\nexample.publicVariable = 5;\r\nexample.publicMethod();\r\n```\r\n#### Is Accessible through Inheritance?\r\nCan we access the super class variables and methods from a Sub Class?\r\n```\r\npublic class SubClass extends ExampleClass {    \r\n    void subClassMethod(){\r\npublicVariable = 5;\r\nprotectedVariable = 5;\r\n    }    \r\n}\r\n```\r\n#### Important Access Things to Remember\r\nA sub class trying to access through reference/instance variables, will have the same access as a normal class (non sub class).\r\nAccess modifiers cannot be applied to local variables\r\n#### Access Modifiers Example\r\nLet's consider the following class with variables and methods declared with all 4 access modifiers:\r\n```\r\npackage com.in28minutes.membermodifiers.access;\r\n\r\npublic class ExampleClass {\r\n    int defaultVariable;\r\n    public int publicVariable;\r\n    private int privateVariable;\r\n    protected int protectedVariable;\r\n    \r\n    void defaultMethod(){\r\n\r\n    }\r\n    \r\n    public void publicMethod(){\r\n\r\n    }\r\n    \r\n    private void privateMethod(){\r\n\r\n    }\r\n    \r\n    protected void protectedMethod(){\r\n\r\n    }\r\n}\r\n```\r\n#### Method Access Modifiers\r\nLet's discuss about access modifiers in order of increasing access.\r\n#### private\r\na. Private variables and methods can be accessed only in the class they are declared.\r\nb. Private variables and methods from SuperClass are NOT available in SubClass.\r\n#### default or package\r\na. Default variables and methods can be accessed in the same package Classes.\r\nb. Default variables and methods from SuperClass are available only to SubClasses in same package.\r\n#### protected\r\na. Protected variables and methods can be accessed in the same package Classes.\r\nb. Protected variables and methods from SuperClass are available to SubClass in any package\r\n#### public\r\na. Public variables and methods can be accessed from every other Java classes.\r\nb. Public variables and methods from SuperClass are all available directly in the SubClass\r\n#### Access Modifier Example: Class in Same Package\r\nLook at the code below to understand what can be accessed and what cannot be.\r\n```\r\npackage com.in28minutes.membermodifiers.access;\r\n\r\npublic class TestClassInSamePackage {\r\n    public static void main(String[] args) {\r\nExampleClass example = new ExampleClass();\r\n\r\nexample.publicVariable = 5;\r\nexample.publicMethod();\r\n\r\n//privateVariable is not visible\r\n//Below Line, uncommented, would give compiler error\r\n//example.privateVariable=5; //COMPILE ERROR\r\n//example.privateMethod();\r\n\r\nexample.protectedVariable = 5;\r\nexample.protectedMethod();\r\n\r\nexample.defaultVariable = 5;\r\nexample.defaultMethod();\r\n    }\r\n}\r\n```\r\n#### Access Modifier Example: Class in Different Package\r\nLook at the code below to understand what can be accessed and what cannot be.\r\n```\r\npackage com.in28minutes.membermodifiers.access.different;\r\n\r\nimport com.in28minutes.membermodifiers.access.ExampleClass;\r\n\r\npublic class TestClassInDifferentPackage {\r\n    public static void main(String[] args) {\r\nExampleClass example = new ExampleClass();\r\n\r\nexample.publicVariable = 5;\r\nexample.publicMethod();\r\n\r\n//privateVariable,privateMethod are not visible\r\n//Below Lines, uncommented, would give compiler error\r\n//example.privateVariable=5; //COMPILE ERROR\r\n//example.privateMethod();//COMPILE ERROR\r\n\r\n//protectedVariable,protectedMethod are not visible\r\n//Below Lines, uncommented, would give compiler error\r\n//example.protectedVariable = 5; //COMPILE ERROR\r\n//example.protectedMethod();//COMPILE ERROR\r\n\r\n//defaultVariable,defaultMethod are not visible\r\n//Below Lines, uncommented, would give compiler error\r\n//example.defaultVariable = 5;//COMPILE ERROR\r\n//example.defaultMethod();//COMPILE ERROR\r\n    }\r\n}\r\n```\r\n#### Access Modifier Example: Sub Class in Same Package\r\nLook at the code below to understand what can be accessed and what cannot be.\r\n```\r\npackage com.in28minutes.membermodifiers.access;\r\n\r\npublic class SubClassInSamePackage extends ExampleClass {\r\n    \r\n    void subClassMethod(){\r\npublicVariable = 5;\r\npublicMethod();\r\n\r\n//privateVariable is not visible to SubClass\r\n//Below Line, uncommented, would give compiler error\r\n//privateVariable=5; //COMPILE ERROR\r\n//privateMethod();\r\n\r\nprotectedVariable = 5;\r\nprotectedMethod();\r\n\r\ndefaultVariable = 5;\r\ndefaultMethod();\r\n    }    \r\n}\r\n```\r\n#### Access Modifier Example: Sub Class in Different Package\r\nLook at the code below to understand what can be accessed and what cannot be.\r\n```\r\npackage com.in28minutes.membermodifiers.access.different;\r\n\r\nimport com.in28minutes.membermodifiers.access.ExampleClass;\r\n\r\npublic class SubClassInDifferentPackage extends ExampleClass {\r\n    \r\n    void subClassMethod(){\r\npublicVariable = 5;\r\npublicMethod();\r\n\r\n//privateVariable is not visible to SubClass\r\n//Below Line, uncommented, would give compiler error\r\n//privateVariable=5; //COMPILE ERROR\r\n//privateMethod();\r\n\r\nprotectedVariable = 5;\r\nprotectedMethod();\r\n\r\n//privateVariable is not visible to SubClass\r\n//Below Line, uncommented, would give compiler error\r\n//defaultVariable = 5; //COMPILE ERROR\r\n//defaultMethod();\r\n    }    \r\n}\r\n```\r\n### Final modifier\r\n- Let's discuss about Final modifier in Java.\r\n\r\n#### Final class cannot be extended\r\nConsider the class below which is declared as final.\r\n```\r\nfinal public class FinalClass {\r\n}\r\n```\r\n\r\nBelow class will not compile if uncommented. FinalClass cannot be extended.\r\n```\r\n/*\r\nclass ExtendingFinalClass extends FinalClass{ //COMPILER ERROR\r\n    \r\n}\r\n*/\r\n```\r\n\r\nExample of Final class in Java is the String class.\r\nFinal is used very rarely as it prevents re-use of the class.\r\n#### Final methods cannot be overriden.\r\nConsider the class FinalMemberModifiersExample with method finalMethod which is declared as final.\r\n```\r\npublic class FinalMemberModifiersExample {\r\n    final void finalMethod(){\r\n    }\r\n}\r\n```\r\n\r\nAny SubClass extending above class cannot override the finalMethod().\r\n```\r\nclass SubClass extends FinalMemberModifiersExample {\r\n    //final method cannot be over-riddent\r\n    //Below method, uncommented, causes compilation Error\r\n    /*\r\n    final void finalMethod(){\r\n\r\n    }\r\n    */\r\n}\r\n```\r\n#### Final variable values cannot be changed.\r\nOnce initialized, the value of a final variable cannot be changed.\r\n```\r\nfinal int finalValue = 5;\r\n//finalValue = 10; //COMPILER ERROR\r\n```\r\n\r\n#### Final arguments value cannot be modified.\r\nConsider the example below:\r\n```\r\nvoid testMethod(final int finalArgument){\r\n    //final argument cannot be modified\r\n    //Below line, uncommented, causes compilation Error\r\n    //finalArgument = 5;//COMPILER ERROR\r\n}\r\n```\r\n### Other Non access Modifiers\r\n- A class cannot be both abstract and final\r\n\r\n#### strictfp\r\nThis modifier can be used on a class and a method. This (strictfp) cannot be used on a variable. \r\nIEEE standard for floating points would be followed in the method or class where strictfp modifier is specified.\r\n#### volatile\r\nVolatile can only be applied to instance variables.\r\nA volatile variable is one whose value is always written to and read from \"main memory\". Each thread has its own cache in Java. The volatile variable will not be stored on a Thread cache.\r\n#### native\r\nCan be applied only to methods.\r\nThese methods are implemented in native languages (like C)\r\n### Static Variables and Methods\r\n- Static variables and methods are class level variables and methods.  There is only one copy of the static variable for the entire Class. Each instance of the Class (object) will NOT have a unique copy of a static variable. Let's start with a real world example of a Class with static variable and methods.\r\n\r\n#### Static Variable/Method , Example\r\ncount variable in Cricketer class is static. The method to get the count value getCount() is also a static method. \r\n\r\n```\r\npublic class Cricketer {\r\n    private static int count;\r\n\r\n    public Cricketer() {\r\ncount++;\r\n    }\r\n\r\n    static int getCount() {\r\nreturn count;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n\r\nCricketer cricketer1 = new Cricketer();\r\nCricketer cricketer2 = new Cricketer();\r\nCricketer cricketer3 = new Cricketer();\r\nCricketer cricketer4 = new Cricketer();\r\n\r\nSystem.out.println(Cricketer.getCount());//4\r\n    }\r\n}\r\n```\r\n4 instances of the Cricketer class are created. Variable count is incremented with every instance created in the constructor. \r\n#### Static Variables and Methods Example 2\r\nExample class below explains all the rules associated with access static variables and static methods.\r\n```\r\npublic class StaticModifierExamples {\r\n    private static int staticVariable;\r\n    private int instanceVariable;\r\n\r\n    public static void staticMethod() {\r\n//instance variables are not accessible in static methods\r\n//instanceVariable = 10; //COMPILER ERROR\r\n\r\n//Also, this Keyword is not accessible. this refers to object.\r\n//static methods are class methods\r\n\r\n//static variables are accessible in static methods\r\nstaticVariable = 10;\r\n    }\r\n\r\n    public void instanceMethod() {\r\n//static and instance variables are accessible in instance methods\r\ninstanceVariable = 10;\r\nstaticVariable = 10;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n//static int i =5; //COMPILER ERROR\r\nStaticModifierExamples example = new StaticModifierExamples();\r\n\r\n//instance variables and methods are only accessible through object references\r\nexample.instanceVariable = 10;\r\nexample.instanceMethod();\r\n//StaticModifierExamples.instanceVariable = 10;//COMPILER ERROR\r\n//StaticModifierExamples.instanceMethod();//COMPILER ERROR\r\n\r\n//static variables and methods are accessible through object references and Class Name.\r\nexample.staticVariable = 10;\r\nexample.staticMethod();\r\nStaticModifierExamples.staticVariable = 10;\r\nStaticModifierExamples.staticMethod();\r\n\r\n    }\r\n}\r\n```\r\nIn a static method, instance variables are not accessible. Keyword this is also not accessible. However static variables are accessible.\r\n```\r\n    public static void staticMethod() {\r\n//instance variables are not accessible in static methods\r\n//instanceVariable = 10; //COMPILER ERROR\r\n\r\n//Also, this Keyword is not accessible. this refers to object.\r\n//static methods are class methods\r\n\r\n//static variables are accessible in static methods\r\nstaticVariable = 10;\r\n    }\r\n```\r\n\r\nIn instance methods, both static and instance variables are accessible.\r\n```\r\n    public void instanceMethod() {\r\ninstanceVariable = 10;\r\nstaticVariable = 10;\r\n    }\r\n```\r\n\r\nInstance variables and methods are only accessible through object references. \r\n```\r\nexample.instanceVariable = 10;\r\nexample.instanceMethod();\r\n//StaticModifierExamples.instanceVariable = 10;//COMPILER ERROR\r\n//StaticModifierExamples.instanceMethod();//COMPILER ERROR\r\n```\r\n\r\nStatic variables and methods are accessible through object references and Class Name.\r\n```\r\nexample.staticVariable = 10;\r\nexample.staticMethod();\r\nStaticModifierExamples.staticVariable = 10;\r\nStaticModifierExamples.staticMethod();\r\n```\r\n\r\nIt is always recommended to use Class Name to access a static variable or method. This is because static methods are class level methods. It is not appropriate to use instance references to call static methods (even though it compiles and works).\r\n#### Static methods cannot be overridden\r\nConsider the example below:\r\n\r\n```\r\nclass Animal{\r\n    static void StaticMethod(){\r\nSystem.out.println(\"Animal Static Method\");\r\n    }\r\n}\r\n\r\nclass Dog extends Animal{\r\n    static void StaticMethod(){\r\nSystem.out.println(\"Dog Static Method\");\r\n    }\r\n}\r\n```\r\n\r\nWhen code below is run, static method in Animal is executed. Static method invocation is based on the type of reference variable. It does not depend on the type of object referred to.\r\n\r\n```\r\nAnimal animal = new Dog();\r\nanimal.StaticMethod();//Animal Static Method\r\n```\r\n#### Local variables cannot be declared as static\r\nExample below:\r\n```\r\npublic static void main(String[] args) {\r\n    //static int i =5; //COMPILER ERROR\r\n}\r\n```\r\n### Class Contents\r\n- Let's discuss what a Java class can contain and what it cannot.\r\n\r\n#Section\r\nJava Source File Rules\r\nA Java Source File can contain\r\na.0 or 1 Public Classes\r\nb.0 or 1 or More Non Public Classes\r\n\r\nOrder should be\r\n1. Package Statement\r\n2. Imports\r\n3. Class Declarations\r\n\r\nComments can be anywhere in the file.\r\nIf there is a public class, file name should the (name of public class) + \".java\". \r\nIf name of public class is Scorer, name of file should be Scorer.java.\r\nIf there is no public class, there are no restrictions on file name.\r\n#### Example Class\r\n```\r\n/* Comments Anywhere*/\r\npackage com.in28minutes.classcontent;\r\nclass DefaultClass1{\r\n\t\r\n}\r\n/* Comments Anywhere*/\r\nclass DefaultClass2{\r\n\t\r\n}\r\n/* Comments Anywhere*/\r\npublic class PublicClass1 {\r\n}\r\n\r\n/* Cannot have another Public Class. \r\npublic class PublicClass2 {\r\n}\r\n*/\r\n```\r\n### Nested Class\r\n- Nested Classes are classes which are declared inside other classes.\r\n\r\n#### Nested Class Example\r\nConsider the following example:\r\n```\r\nclass OuterClass {\r\n\r\n    public class InnerClass {\r\n    }\r\n\r\n    public static class StaticNestedClass {\r\n    }\r\n\r\n    public void exampleMethod() {\r\nclass MethodLocalInnerClass {\r\n};\r\n    }\r\n\r\n}\r\n```\r\n#### Inner Class\r\nGenerally the term inner class is used to refer to a non-static class declared directly inside another class. Consider the example of class named InnerClass.\r\n#### Static Inner Class\r\nA class declared directly inside another class and declared as static. In the example above, class name StaticNestedClass is a static inner class. \r\n#### Method Inner Class\r\nA class declared directly inside a method. In the example above, class name MethodLocalInnerClass is a method inner class. \r\n### Inner Class\r\n- Inner Class is a very important Java Concept. Let's learn about it in this tutorial.\r\n\r\n#### Inner Class Example\r\nConsider the following Example:\r\n```\r\nclass OuterClass {\r\n    private int outerClassInstanceVariable;\r\n\r\n    public class InnerClass {\r\nprivate int innerClassVariable;\r\n\r\npublic int getInnerClassVariable() {\r\n    return innerClassVariable;\r\n}\r\n\r\npublic void setInnerClassVariable(\r\nint innerClassVariable) {\r\n    this.innerClassVariable = innerClassVariable;\r\n}\r\n\r\npublic void privateVariablesOfOuterClassAreAvailable() {\r\n    outerClassInstanceVariable = 5; // we can access the value\r\n    System.out.println(\"Inner class ref is \" + this); \r\n    \r\n    //Accessing outer class reference variable\r\n    System.out.println(\"Outer class ref is \" + OuterClass.this);\r\n}\r\n    }\r\n\r\n    public void createInnerClass(){\r\n//Just use the inner class name to create it\r\nInnerClass inner = new InnerClass();\r\n    }\r\n    \r\n}\r\n\r\npublic class InnerClassExamples {\r\n    public static void main(String[] args) {\r\n\r\n// COMPILER ERROR! You cannot create an inner class on its own.\r\n// InnerClass innerClass = new InnerClass();\r\nOuterClass example = new OuterClass();\r\n\r\n// To create an Inner Class you need an instance of Outer Class\r\nOuterClass.InnerClass innerClass = example.new InnerClass();\r\n\r\n    }\r\n}\r\n```\r\nInner class cannot be directly instantiated.\r\n```\r\n// InnerClass innerClass = new InnerClass(); //Compiler Error\r\n```\r\n\r\nTo create an Inner Class you need an instance of Outer Class.\r\n```\r\nOuterClass example = new OuterClass();\r\nOuterClass.InnerClass innerClass = example.new InnerClass();\r\n```\r\n#### Creating an Inner Class instance in outer class\r\nConsider the method createInnerClass from the example above:  This method shows how to create an inner class instance.\r\n```\r\npublic void createInnerClass(){\r\n    //Just use the inner class name to create it\r\n    InnerClass inner = new InnerClass();\r\n}\r\n```\r\n#### Instance variables of Outer Class are available in inner class\r\nConsider the method privateVariablesOfOuterClassAreAvailable from InnerClass declared above:\r\n```\r\npublic void privateVariablesOfOuterClassAreAvailable() {\r\n    outerClassInstanceVariable = 5; // we can access the value\r\n    System.out.println(\"Inner class ref is \" + this); \r\n    \r\n    //Accessing outer class reference variable\r\n    System.out.println(\"Outer class ref is \" + OuterClass.this);\r\n}\r\n```\r\n### Static Inner Nested Class\r\n- Let's learn about Static Inner Nested Class in this Java tutorial.\r\n\r\n#### Static Inner Nested Class Example\r\nConsider the example below: \r\n```\r\nclass OuterClass {\r\n    private int outerClassInstanceVariable;\r\n\r\n    public static class StaticNestedClass {\r\nprivate int staticNestedClassVariable;\r\n\r\npublic int getStaticNestedClassVariable() {\r\n    return staticNestedClassVariable;\r\n}\r\n\r\npublic void setStaticNestedClassVariable(\r\nint staticNestedClassVariable) {\r\n    this.staticNestedClassVariable = staticNestedClassVariable;\r\n}\r\n\r\npublic void privateVariablesOfOuterClassAreNOTAvailable() {\r\n    // outerClassInstanceVariable = 5; //COMPILE ERROR\r\n}\r\n    }\r\n\r\n}\r\n\r\npublic class InnerClassExamples {\r\n    public static void main(String[] args) {\r\n// Static Nested Class can be created without needing to create its\r\n// parent. Without creating NestedClassesExample, we created\r\n// StaticNestedClass\r\nOuterClass.StaticNestedClass staticNestedClass1 = new OuterClass.StaticNestedClass();\r\nstaticNestedClass1.setStaticNestedClassVariable(5);\r\n\r\nOuterClass.StaticNestedClass staticNestedClass2 = new OuterClass.StaticNestedClass();\r\nstaticNestedClass2.setStaticNestedClassVariable(10);\r\n\r\n// Static Nested Class member variables are not static. They can have\r\n// different values.\r\nSystem.out.println(staticNestedClass1\r\n.getStaticNestedClassVariable()); //5\r\nSystem.out.println(staticNestedClass2\r\n.getStaticNestedClassVariable()); //10\r\n    }\r\n} \r\n```\r\n#### Creating Static Nested Class\r\nStatic Nested Class can be created without needing to create its parent. Without creating NestedClassesExample, we createdStaticNestedClass.\r\n```\r\nOuterClass.StaticNestedClass staticNestedClass1 = new OuterClass.StaticNestedClass();\r\n```\r\n#### Member variables are not static\r\nStatic Nested Class member variables are not static. They can have different values.\r\n```\r\nSystem.out.println(staticNestedClass1\r\n.getStaticNestedClassVariable()); //5\r\nSystem.out.println(staticNestedClass2\r\n.getStaticNestedClassVariable()); //10\r\n```\r\n#### Outer class instance variables are not accessible.\r\nInstance variables of outer class are not available in the Static Class.\r\n```\r\npublic void privateVariablesOfOuterClassAreNOTAvailable() {\r\n    // outerClassInstanceVariable = 5; //COMPILE ERROR\r\n}\r\n```\r\n### Method Inner Class\r\n- Let us learn about Method Inner Class in this tutorial.\r\n\r\n#### Method Inner Class Example\r\nConsider the example below: MethodLocalInnerClass is declared in exampleMethod();\r\n```\r\nclass OuterClass {\r\n    private int outerClassInstanceVariable;\r\n\r\n    public void exampleMethod() {\r\nint localVariable;\r\nfinal int finalVariable = 5;\r\nclass MethodLocalInnerClass {\r\n    public void method() {\r\n//Can access class instance variables\r\nSystem.out\r\n.println(outerClassInstanceVariable);\r\n\r\n//Cannot access method's non-final local variables\r\n//localVariable = 5;//Compiler Error\r\nSystem.out.println(finalVariable);//Final variable is fine..\r\n    }\r\n}\r\n\r\n//MethodLocalInnerClass can be instantiated only in this method\r\nMethodLocalInnerClass m1 = new MethodLocalInnerClass();\r\nm1.method();\r\n    }\r\n\r\n    //MethodLocalInnerClass can be instantiated only in the method where it is declared\r\n    //MethodLocalInnerClass m1 = new MethodLocalInnerClass();//COMPILER ERROR\r\n\r\n}\r\n```\r\n#### Method inner class is not accessible outside the method\r\nLook at the commented code below exampleMethod. MethodLocalInnerClass can be instantiated only in the method where it is declared.\r\n#### Method inner class can access class instance variables\r\n```\r\n//Can access class instance variables\r\nSystem.out.println(outerClassInstanceVariable);\r\n```\r\n#### Method inner class cannot access method's non-final local variables\r\n```\r\n//Cannot access method's non-final local variables\r\n//localVariable = 5;//Compiler Error\r\nSystem.out.println(finalVariable);//Final variable is fine..\r\n```\r\n### Variable Arguments\r\n- Variable Arguments allow calling a method with different number of parameters.\r\n\r\n#### Variable Arguments Example\r\n\r\n```\r\n    //int(type) followed ... (three dot's) is syntax of a variable argument. \r\n    public int sum(int... numbers) {\r\n//inside the method a variable argument is similar to an array.\r\n//number can be treated as if it is declared as int[] numbers;\r\nint sum = 0;\r\nfor (int number: numbers) {\r\n    sum += number;\r\n}\r\nreturn sum;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\nVariableArgumentExamples example = new VariableArgumentExamples();\r\n//3 Arguments\r\nSystem.out.println(example.sum(1, 4, 5));//10\r\n//4 Arguments\r\nSystem.out.println(example.sum(1, 4, 5, 20));//30\r\n//0 Arguments\r\nSystem.out.println(example.sum());//0\r\n    }\r\n```\r\n#### Variable Arguments Syntax\r\nData Type followed ... (three dot's) is syntax of a variable argument. \r\n```\r\npublic int sum(int... numbers) {\r\n```\r\n\r\nInside the method a variable argument is similar to an array. For Example: number can be treated in below method as if it is declared as int[] numbers;\r\n```\r\n    public int sum(int... numbers) {\r\nint sum = 0;\r\nfor (int number: numbers) {\r\n    sum += number;\r\n}\r\nreturn sum;\r\n    }\r\n```\r\n#### Variable Argument: only Last Parameter\r\nVariable Argument should be always the last parameter (or only parameter) of a method. Below example gives a compilation error\r\n```\r\n    public int sum(int... numbers, float value) {//COMPILER ERROR\r\n    }\r\n```\r\n#### Variable Argument of Type Custom Class\r\nEven a class can be used a variable argument. In the example below, bark method is overloaded with a variable argument method.\r\n```\r\n    class Animal {\r\nvoid bark() {\r\n    System.out.println(\"Bark\");\r\n}\r\nvoid bark(Animal... animals) {\r\n    for (Animal animal: animals) {\r\nanimal.bark();\r\n    }\r\n}\r\n    }\r\n```\r\n### Exception Handling\r\n- In this tutorial, let's understand the need for exception handling and learn how to handle exceptions. \r\n\r\n#### Example without Exception Handling\r\nLet's first look an example without exception handling. Method main throws an exception because toString method is invoked on a null object.\r\n```\r\n    public static void main(String[] args) {\r\nString str = null;\r\nstr.toString();\r\n    }\r\n```\r\n\r\nOutput of above program is\r\n```\r\nException in thread \"main\" java.lang.NullPointerException at\r\ncom.in28minutes.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:6)\r\n```\r\n#### Exception Example 2 , Propagation of an Exception\r\nIn this example, main invokes method1, which invokes method2 which throws a NullPointerException. Check the output of this program.\r\n```\r\n    public static void main(String[] args) {\r\nmethod1();\r\n    }\r\n\r\n    private static void method1() {\r\nmethod2();\r\n    }\r\n\r\n    private static void method2() {\r\nString str = null;\r\nstr.toString();\r\n    }\r\n//Output - Exception in thread \"main\" java.lang.NullPointerException at\r\ncom.in28minutes.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:15)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:10)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:6)\r\n```\r\n\r\nLook at the stack trace. Exception which is thrown in method2 is propagating to method1 and then to main. This is because there is no exception handling in all 3 methods - main, method1 and method2\r\n#### Exception Example 3: Execution of method stopped\r\nLook at the example below:  A println method call is added after every method call.\r\n```\r\n    public static void main(String[] args) {\r\nmethod1();\r\nSystem.out.println(\"Line after Exception - Main\");\r\n    }\r\n\r\n    private static void method1() {\r\nmethod2();\r\nSystem.out.println(\"Line after Exception - Method 1\");\r\n    }\r\n\r\n    private static void method2() {\r\nString str = null;\r\nstr.toString();\r\nSystem.out.println(\"Line after Exception - Method 2\");\r\n    }\r\n//Output - Exception in thread \"main\" java.lang.NullPointerException\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:18)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:12)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:7)\r\n```\r\n\r\nNote that none of the lines with text \"Line after Exception - ****\" are executed. If an exception occurs, lines after the line where exception occurred are not executed. Since all three methods main, method1() and method2() do not have any Exception Handling, exception propagates from method2 to method1 to main.\r\n#### Exception Handling Example 4: Try catch block\r\n\r\nLet's add a try catch block in method2\r\n\r\n```\r\n    public static void main(String[] args) {\r\nmethod1();\r\nSystem.out.println(\"Line after Exception - Main\");\r\n    }\r\n\r\n    private static void method1() {\r\nmethod2();\r\nSystem.out.println(\"Line after Exception - Method 1\");\r\n    }\r\n\r\n    private static void method2() {\r\ntry {\r\n    String str = null;\r\n    str.toString();\r\n    System.out.println(\"Line after Exception - Method 2\");\r\n} catch (Exception e) {\r\n    // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE\r\n    System.out.println(\"Exception Handled - Method 2\");\r\n}\r\n    }\r\n```\r\n\r\nOutput\r\n```\r\nException Handled - Method 2\r\nLine after Exception - Method 1\r\nLine after Exception - Main\r\n```\r\n\r\nSince Exception Handling is added in the method method2, the exception did not propogate to method1. You can see the \"Line after Exception - **\" in the output for main, method1 since they are not affected by the exception thrown. Since the exception was handled in method2, method1 and main are not affected by it. This is the main essence of exception handling. However, note that the line after the line throwing exception in method2 is not executed.\r\n\r\nFew important things to remember from this example.\r\n1.If exception is handled, it does not propogate further.\r\n2.In a try block, the lines after the line throwing the exception are not executed.\r\n#### Exception Handling Example 5: Need for Finally\r\nConsider the example below: In method2, a connection is opened. However, because of the exception thrown, connection is not closed. This results in unclosed connections.\r\n\r\n```\r\npackage com.in28minutes.exceptionhandling;\r\n\r\nclass Connection {\r\n    void open() {\r\nSystem.out.println(\"Connection Opened\");\r\n    }\r\n\r\n    void close() {\r\nSystem.out.println(\"Connection Closed\");\r\n    }\r\n}\r\n\r\npublic class ExceptionHandlingExample1 {\r\n\r\n    // Exception Handling Example 1\r\n    // Let's add a try catch block in method2\r\n    public static void main(String[] args) {\r\nmethod1();\r\nSystem.out.println(\"Line after Exception - Main\");\r\n    }\r\n\r\n    private static void method1() {\r\nmethod2();\r\nSystem.out.println(\"Line after Exception - Method 1\");\r\n    }\r\n\r\n    private static void method2() {\r\ntry {\r\n    Connection connection = new Connection();\r\n    connection.open();\r\n\r\n    // LOGIC\r\n    String str = null;\r\n    str.toString();\r\n\r\n    connection.close();\r\n} catch (Exception e) {\r\n    // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE\r\n    System.out.println(\"Exception Handled - Method 2\");\r\n}\r\n    }\r\n}\r\n```\r\n\r\nOutput\r\n```\r\nConnection Opened\r\nException Handled - Method 2\r\nLine after Exception - Method 1\r\nLine after Exception - Main\r\n```\r\n\r\nConnection that is opened is not closed. Because an exception has occurred in method2, connection.close() is not run. This results in a dangling (un-closed) connection.\r\n#### Exception Handling Example 6 - Finally\r\nFinally block is used when code needs to be executed irrespective of whether an exception is thrown. Let us now move connection.close(); into a finally block. Also connection declaration is moved out of the try block to make it visible in the finally block.\r\n\r\n```\r\n    private static void method2() {\r\nConnection connection = new Connection();\r\nconnection.open();\r\ntry {\r\n    // LOGIC\r\n    String str = null;\r\n    str.toString();\r\n\r\n} catch (Exception e) {\r\n    // NOT PRINTING EXCEPTION TRACE - BAD PRACTICE\r\n    System.out.println(\"Exception Handled - Method 2\");\r\n} finally {\r\n    connection.close();\r\n}\r\n    }\r\n```\r\n\r\nOutput\r\n```\r\nConnection Opened\r\nException Handled - Method 2\r\nConnection Closed\r\nLine after Exception - Method 1\r\nLine after Exception - Main\r\n```\r\n\r\nConnection is closed even when exception is thrown. This is because connection.close() is called in the finally block.\r\nFinally block is always executed (even when an exception is thrown). So, if we want some code to be always executed we can move it to finally block.\r\n\r\nCode in finally is NOT executed only in two situations.\r\nIf exception is thrown in finally.\r\nIf JVM Crashes in between (for example, System.exit()).\r\n#### finally is executed even if there is a return statement in catch or try\r\n```\r\nprivate static void method2() {\r\nConnection connection = new Connection();\r\nconnection.open();\r\ntry {\r\n    // LOGIC    \r\n    String str = null;\r\n    str.toString();\r\n    return;\r\n} catch (Exception e) {\r\n    // NOT PRINTING EXCEPTION TRACE - BAD PRACTICE\r\n    System.out.println(\"Exception Handled - Method 2\");\r\n    return;\r\n} finally {\r\n    connection.close();\r\n}\r\n    }\r\n```\r\n#### Exception Handling Syntax\r\nLet's look at a few quirks about Exception Handling syntax.\r\n#### try without a catch is allowed\r\n```\r\nprivate static void method2() {\r\nConnection connection = new Connection();\r\nconnection.open();\r\ntry {\r\n    // LOGIC\r\n    String str = null;\r\n    str.toString();\r\n} finally {\r\n    connection.close();\r\n}\r\n    }\r\n```\r\n\r\nOutput:\r\n```\r\nConnection Opened\r\nConnection Closed\r\nException in thread \"main\" java.lang.NullPointerException at com.in28minutes.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:33) at com.in28minutes.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:22) at com.in28minutes.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:17)\r\n```\r\n\r\nTry without a catch is useful when you would want to do something (close a connection) even if an exception occurred without handling the exception.\r\n#### Try without both catch and finally is not allowed. \r\nBelow method would give a Compilation Error!! (End of try block)\r\n```\r\n    private static void method2() {\r\nConnection connection = new Connection();\r\nconnection.open();\r\ntry {\r\n    // LOGIC\r\n    String str = null;\r\n    str.toString();\r\n}//COMPILER ERROR!!\r\n    }\r\n```\r\n#### Exception Handling Hierarchy\r\nThrowable is the highest level of Error Handling classes.\r\n\r\nBelow class definitions show the pre-defined exception hierarchy in Java.\r\n\r\n```\r\n//Pre-defined Java Classes\r\nclass Error extends Throwable{}\r\nclass Exception extends Throwable{}\r\nclass RuntimeException extends Exception{}\r\n```\r\n\r\nBelow class definitions show creation of a programmer defined exception in Java.\r\n```\r\n//Programmer defined classes\r\nclass CheckedException1 extends Exception{}\r\nclass CheckedException2 extends CheckedException1{}\r\n\r\nclass UnCheckedException extends RuntimeException{}\r\nclass UnCheckedException2 extends UnCheckedException{}\r\n```\r\n#### Errors\r\nError is used in situations when there is nothing a programmer can do about an error. Ex: StackOverflowError, OutOfMemoryError.\r\n#### Exception\r\nException is used when a programmer can handle the exception.\r\n#### Un-Checked Exception\r\nRuntimeException and classes that extend RuntimeException are called unchecked exceptions. For Example: RuntimeException,UnCheckedException,UnCheckedException2 are unchecked or RunTime Exceptions. There are subclasses of RuntimeException (which means they are subclasses of Exception also.)\r\n#### Checked Exception\r\nOther Exception Classes (which don't fit the earlier definition). These are also called Checked Exceptions. Exception, CheckedException1,CheckedException2 are checked exceptions. They are subclasses of Exception which are not subclasses of RuntimeException.\r\n\r\n#### Throwing RuntimeException in method\r\n\r\nMethod addAmounts in Class AmountAdder adds amounts. If amounts are of different currencies it throws an exception.\r\n\r\n```\r\nclass Amount {\r\n    public Amount(String currency, int amount) {\r\nthis.currency = currency;\r\nthis.amount = amount;\r\n    }\r\n\r\n    String currency;// Should be an Enum\r\n    int amount;// Should ideally use BigDecimal\r\n}\r\n\r\n// AmountAdder class has method addAmounts which is throwing a RuntimeException\r\nclass AmountAdder {\r\n    static Amount addAmounts(Amount amount1, Amount amount2) {\r\nif (!amount1.currency.equals(amount2.currency)) {\r\n    throw new RuntimeException(\"Currencies don't match\");\r\n}\r\nreturn new Amount(amount1.currency, amount1.amount + amount2.amount);\r\n    }\r\n}\r\n\r\npublic class ExceptionHandlingExample2 {\r\n\r\n    public static void main(String[] args) {\r\nAmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\", 5));\r\n    }\r\n\r\n}\r\n```\r\n#### Output\r\n```\r\nException in thread \"main\" java.lang.RuntimeException: Currencies don't match\r\nat com.in28minutes.exceptionhandling.AmountAdder.addAmounts(ExceptionHandlingExample2.java:17)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:28)\r\n```\r\n\r\nException message shows the type of exception(java.lang.RuntimeException) and the string message passed to the RuntimeException constructor(\"Currencies don't match\");\r\n#### Throwing Exception (Checked Exception) in method\r\nLet us now try to change the method addAmounts to throw an Exception instead of RuntimeException. It gives us a compilation error.\r\n\r\n```\r\nclass AmountAdder {\r\n    static Amount addAmounts(Amount amount1, Amount amount2) {\r\nif (!amount1.currency.equals(amount2.currency)) {\r\n    throw new Exception(\"Currencies don't match\");// COMPILER ERROR!// Unhandled exception type Exception\r\n}\r\nreturn new Amount(amount1.currency, amount1.amount + amount2.amount);\r\n    }\r\n}\r\n```\r\n\r\nAll classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown. Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the method should declare that it throws the exception\r\n#### Throws Exception Example\r\nLet's look at how to declare throwing an exception from a method.\r\n\r\n```\r\nclass AmountAdder {\r\n    static Amount addAmounts(Amount amount1, Amount amount2) throws Exception {\r\nif (!amount1.currency.equals(amount2.currency)) {\r\n    throw new Exception(\"Currencies don't match\");\r\n}\r\nreturn new Amount(amount1.currency, amount1.amount + amount2.amount);\r\n    }\r\n}\r\n```\r\n\r\nLook at the line \"static Amount addAmounts(Amount amount1, Amount amount2) throws Exception\". This is how we declare that a method throws Exception. This results in compilation error in main method. This is because Main method is calling a method which is declaring that it might throw Exception. Main method again has two options a. Throw b. Handle\r\n\r\nCode with main method throwing the exception below\r\n\r\n```\r\n    public static void main(String[] args) throws Exception {\r\nAmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\", 5));\r\n    }\r\n```\r\n#### Output\r\n```\r\nException in thread \"main\" java.lang.Exception: Currencies don't match\r\nat com.in28minutes.exceptionhandling.AmountAdder.addAmounts(ExceptionHandlingExample2.java:17)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:28)\r\n```\r\n#### Handling an Exception\r\nmain can also handle the exception instead of declaring throws. Code for it below.\r\n```\r\npublic static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\",5));\r\n} catch (Exception e) {\r\n    System.out.println(\"Exception Handled in Main\");\r\n}\r\n    }\r\n```\r\n#### Output\r\n```\r\nException Handled in Main\r\n```\r\n#### Custom Defined Exception Classes\r\nFor the scenario above we can create a customized exception, CurrenciesDoNotMatchException. If we want to make it a Checked Exception, we can make it extend Exception class. Otherwise, we can extend RuntimeException class.\r\n#### Extending Exception Class\r\n```\r\nclass CurrenciesDoNotMatchException extends Exception{\r\n}\r\n```\r\n\r\nNo we can change the method addAmounts to throw CurrenciesDoNotMatchException - even the declaration of the method changed.\r\n\r\n```\r\nclass AmountAdder {\r\n    static Amount addAmounts(Amount amount1, Amount amount2)\r\n    throws CurrenciesDoNotMatchException {\r\nif (!amount1.currency.equals(amount2.currency)) {\r\n    throw new CurrenciesDoNotMatchException();\r\n}\r\nreturn new Amount(amount1.currency, amount1.amount + amount2.amount);\r\n    }\r\n}\r\n```\r\n\r\nmain method needs to be changed to catch: CurrenciesDoNotMatchException\r\n\r\n```\r\npublic class ExceptionHandlingExample2 {\r\n    public static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\",\r\n    5));\r\n} catch (CurrenciesDoNotMatchException e) {\r\n    System.out.println(\"Exception Handled in Main\" + e.getClass());\r\n}\r\n    }\r\n}\r\n```\r\n\r\nOutput: \r\n```\r\nException Handled in Mainclass com.in28minutes.exceptionhandling.CurrenciesDoNotMatchException\r\n```\r\n\r\nLet's change main method to handle Exception instead of CurrenciesDoNotMatchException \r\n\r\n```\r\npublic class ExceptionHandlingExample2 {\r\n    public static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\",5));\r\n} catch (Exception e) {\r\n    System.out.println(\"Exception Handled in Main\" + e.getClass());\r\n}\r\n    }\r\n}\r\n```\r\n\r\nOutput: \r\n```\r\nException Handled in Mainclass com.in28minutes.exceptionhandling.CurrenciesDoNotMatchException\r\n```\r\n\r\nThere is no change in output from the previous example. This is because Exception catch block can catch Exception and all subclasses of Exception.\r\n#### Extend RuntimeException\r\nLet's change the class CurrenciesDoNotMatchException to extend RuntimeException instead of Exception\r\n```\r\nclass CurrenciesDoNotMatchException extends RuntimeException{\r\n}\r\n```\r\n\r\nOutput: \r\n```\r\nException Handled in Mainclass com.in28minutes.exceptionhandling.CurrenciesDoNotMatchException\r\n```\r\n\r\nChange methods addAmounts in AmountAdder to remove the declaration \" throws CurrenciesDoNotMatchException\"\r\n\r\nNo compilation error occurs since RuntimeException and subclasses of RuntimeException are not Checked Exception's. So, they don't need to be handled or declared. If you are interested in handling them, go ahead and handle them. But, java does not require you to handle them.\r\n\r\nRemove try catch from main method. It is not necessary since CurrenciesDoNotMatchException is now a RuntimeException.\r\n\r\n```\r\npublic class ExceptionHandlingExample2 {\r\n    public static void main(String[] args) {\r\nAmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\", 5));\r\n    }\r\n}\r\n```\r\n\r\nOutput:\r\n```\r\nException in thread \"main\" com.in28minutes.exceptionhandling.CurrenciesDoNotMatchException at com.in28minutes.exceptionhandling.AmountAdder.addAmounts(ExceptionHandlingExample2.java:21)\r\nat com.in28minutes.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:30)\r\n```\r\n#### Multiple Catch Blocks\r\nNow, let's add two catch blocks to the main \r\n```\r\npublic class ExceptionHandlingExample2 {\r\n    public static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\",\r\n    5));\r\n} catch (CurrenciesDoNotMatchException e) {\r\n    System.out.println(\"Handled CurrenciesDoNotMatchException\");\r\n} catch (Exception e) {\r\n    System.out.println(\"Handled Exception\");\r\n}\r\n    }\r\n}\r\n```\r\n\r\nOutput: \r\n```\r\nHandled CurrenciesDoNotMatchException\r\n```\r\n\r\nWe can have two catch blocks for a try. Order of Handling of exceptions: a. Same Class b. Super Class.\r\n\r\n#### Specific Exceptions before Generic Exceptions\r\nSpecific Exception catch blocks should be before the catch block for a Generic Exception. For example, CurrenciesDoNotMatchException should be before Exception. Below code gives a compilation error.\r\n```\r\n    public static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"DOLLAR\",\r\n    5));\r\n} catch (Exception e) { // COMPILER ERROR!!\r\n    System.out.println(\"Handled Exception\");\r\n} catch (CurrenciesDoNotMatchException e) {\r\n    System.out.println(\"Handled CurrenciesDoNotMatchException\");\r\n}\r\n    }\r\n```\r\n#### Catch block handles only specified Exceptions (and sub types)\r\nA catch block of type ExceptionType can only catch types ExceptionType and sub classes of ExceptionType. For Example: Let us change the main method code as shown below. Main method throws a NullPointerException.\r\n\r\n```\r\n    public static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"RUPEE\",\r\n    5));\r\n    String string = null;\r\n    string.toString();\r\n} catch (CurrenciesDoNotMatchException e) {\r\n    System.out.println(\"Handled CurrenciesDoNotMatchException\");\r\n}\r\n    }\r\n\r\n\t//Output : Exception in thread \"main\" java.lang.NullPointerException at com.in28minutes.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:34)\r\n```\r\n\r\nSince NullPointerException is not a sub class of CurrenciesDoNotMatchException it wouldn't be handled by the catch block. Instead a NullPointerException would be thrown out by the main method.\r\n\r\n#### Exception Handling Best Practices\r\nIn all above examples we have not followed an Exception Handling good practice(s). Never Completely Hide Exceptions. At the least log them. printStactTrace method prints the entire stack trace when an exception occurs. If you handle an exception, it is always a good practice to log the trace.\r\n```\r\n    public static void main(String[] args) {\r\ntry {\r\n    AmountAdder.addAmounts(new Amount(\"RUPEE\", 5), new Amount(\"RUPEE\",\r\n    5));\r\n    String string = null;\r\n    string.toString();\r\n} catch (CurrenciesDoNotMatchException e) {\r\n    System.out.println(\"Handled CurrenciesDoNotMatchException\");\r\n    e.printStackTrace();\r\n}\r\n    }\r\n```\r\n### Console\r\n- Console is used to read input from keyboard and write output.\r\n\r\n#### Getting a Console reference\r\n```\r\n//Console console = new Console(); //COMPILER ERROR\r\nConsole console = System.console();\r\n```\r\n#### Console utility methods \r\n```\r\nconsole.printf(\"Enter a Line of Text\");\r\n\r\nString text = console.readLine();\r\nconsole.printf(\"Enter a Password\");\r\n```\r\n\r\nPassword doesn't show what is being entered\r\n```\r\nchar[] password = console.readPassword();\r\n\r\nconsole.format(\"\\nEntered Text is %s\", text);\r\n```\r\n### Format or Printf\r\n- Format or Printf functions help us in printing formatted output to the console.\r\n\r\n#### Format/Printf Examples\r\nLet's look at a few examples to quickly understand printf function. \r\n```\r\nSystem.out.printf(\"%d\", 5);//5\r\nSystem.out.printf(\"My name is %s\", \"Rithu\");//My name is Rithu\r\nSystem.out.printf(\"%s is %d Years old\", \"Rithu\", 5);//Rithu is 5 Years old\r\n```\r\n\r\nIn the simplest form, string to be formatted starts with % followed by conversion indicator => b - boolean c - char d - integer f - floating point s - string.\r\n\r\n#### Other Format/Printf Examples\r\n```\r\n//Prints 12 using minimum 5 character spaces.\r\nSystem.out.printf(\"|%5d|\", 12); //prints |   12| \r\n\r\n//Prints 1234 using minimum 5 character spaces.\r\nSystem.out.printf(\"|%5d|\", 1234); //prints | 1234|\r\n//In above example 5 is called width specifier.\r\n\r\n//Left Justification can be done by using -\r\nSystem.out.printf(\"|%-5d|\", 12); //prints |12   |\r\n\r\n//Using 0 pads the number with 0's\r\nSystem.out.printf(\"%05d\", 12); //prints 00012\r\n\r\n//Using , format the number using comma's\r\nSystem.out.printf(\"%,d\", 12345); //prints 12,345\r\n\r\n//Using ( prints negative numbers between ( and )\r\nSystem.out.printf(\"%(d\", -12345); //prints (12345)\r\nSystem.out.printf(\"%(d\", 12345); //prints 12345\r\n\r\n//Using + prints + or - before the number\r\nSystem.out.printf(\"%+d\", -12345); //prints -12345\r\nSystem.out.printf(\"%+d\", 12345); //prints +12345\r\n```\r\n\r\nFor floating point numbers, precision can be specified after dot(.). Below example uses a precision of 2, so .5678 gets changed to .57\r\n```\r\nSystem.out.printf(\"%5.2f\", 1234.5678); //prints 1234.57\r\n```\r\n\r\nAn error in specifying would give a RuntimeException. In below example a string is passed to %d argument. \r\n```\r\nSystem.out.printf(\"%5d\",\"Test\");\r\n//Throws java.util.IllegalFormatConversionException\r\n\r\n//To change the order of printing and passing of arguments, argument index can be used\r\nSystem.out.printf(\"%3$.1f %2$s %1$d\", 123, \"Test\", 123.4); //prints 123.4 Test 123\r\n\r\n//format method has the same behavior as printf method \r\nSystem.out.format(\"%5.2f\", 1234.5678);//prints 1234.57\r\n```\r\n### String Buffer & String Builder\r\n- StringBuffer and StringBuilder are used when you want to modify values of a string frequently. String Buffer class is thread safe where as String Builder is NOT thread safe.\r\n\r\n#### String Buffer Examples\r\n```\r\nStringBuffer stringbuffer = new StringBuffer(\"12345\");\r\nstringbuffer.append(\"6789\");\r\nSystem.out.println(stringbuffer); //123456789\r\n//All StringBuffer methods modify the value of the object.\r\n```\r\n#### String Builder Examples\r\n```\r\nStringBuilder sb = new StringBuilder(\"0123456789\");\r\n\r\n//StringBuilder delete(int startIndex, int endIndexPlusOne)\r\nSystem.out.println(sb.delete(3, 7));//012789\r\n\r\nStringBuilder sb1 = new StringBuilder(\"abcdefgh\");\r\n\r\n//StringBuilder insert(int indext, String whatToInsert)\r\nSystem.out.println(sb1.insert(3, \"ABCD\"));//abcABCDdefgh\r\n\r\nStringBuilder sb2 = new StringBuilder(\"abcdefgh\");\r\n//StringBuilder reverse()\r\nSystem.out.println(sb2.reverse());//hgfedcba\r\n```\r\n\r\nSimilar functions exist in StringBuffer also.\r\n#### Method Chaining\r\nAll functions also return a reference to the object after modifying it.This allows a concept called method chaining.\r\n```\r\nStringBuilder sb3 = new StringBuilder(\"abcdefgh\");\r\nSystem.out.println(sb3.reverse().delete(5, 6).insert(3, \"---\"));//hgf---edba\r\n```\r\n### Date\r\n- Date is no longer the class Java recommends for storing and manipulating date and time. Most of methods in Date are deprecated. Use Calendar class instead. Date internally represents date-time as number of milliseconds (a long value) since 1st Jan 1970.\r\n\r\n#### Creating Date Object\r\n```\r\n//Creating Date Object\r\nDate now = new Date();\r\nSystem.out.println(now.getTime());\r\n```\r\n#### Manipulating Date Object\r\nLets now look at adding a few hours to a date object. All date manipulation to date needs to be done by adding milliseconds to the date. For example, if we want to add 6 hour, we convert 6 hours into millseconds. 6 hours = 6 * 60 * 60 * 1000 milliseconds. Below examples shows specific code.\r\n\r\n```\r\nDate date = new Date();\r\n\r\n//Increase time by 6 hrs\r\ndate.setTime(date.getTime() + 6 * 60 * 60 * 1000);\r\nSystem.out.println(date);\r\n\r\n//Decrease time by 6 hrs\r\ndate = new Date();\r\ndate.setTime(date.getTime() - 6 * 60 * 60 * 1000);\r\nSystem.out.println(date);\r\n```\r\n#### Formatting Dates\r\nFormatting Dates is done by using DateFormat class. Let's look at a few examples.\r\n```\r\n//Formatting Dates\r\nSystem.out.println(DateFormat.getInstance().format(\r\ndate));//10/16/12 5:18 AM\r\n```\r\n\r\nFormatting Dates with a locale\r\n```\r\nSystem.out.println(DateFormat.getDateInstance(\r\nDateFormat.FULL, new Locale(\"it\", \"IT\"))\r\n.format(date));//martedÒ 16 ottobre 2012\r\n\r\nSystem.out.println(DateFormat.getDateInstance(\r\nDateFormat.FULL, Locale.ITALIAN)\r\n.format(date));//martedÒ 16 ottobre 2012\r\n\r\n//This uses default locale US\r\nSystem.out.println(DateFormat.getDateInstance(\r\nDateFormat.FULL).format(date));//Tuesday, October 16, 2012\r\n\r\nSystem.out.println(DateFormat.getDateInstance()\r\n.format(date));//Oct 16, 2012\r\nSystem.out.println(DateFormat.getDateInstance(\r\nDateFormat.SHORT).format(date));//10/16/12\r\nSystem.out.println(DateFormat.getDateInstance(\r\nDateFormat.MEDIUM).format(date));//Oct 16, 2012\r\n\r\nSystem.out.println(DateFormat.getDateInstance(\r\nDateFormat.LONG).format(date));//October 16, 2012\r\n```\r\n#### Format Date's using SimpleDateFormat \r\nLet's look at a few examples of formatting dates using SimpleDateFormat.\r\n```\r\nSystem.out.println(new SimpleDateFormat(\"yy-MM-dd\")\r\n.format(date));//12-10-16\r\nSystem.out\r\n.println(new SimpleDateFormat(\"yy-MMM-dd\")\r\n.format(date));//12-Oct-16\r\nSystem.out.println(new SimpleDateFormat(\r\n\"yyyy-MM-dd\").format(date));//2012-10-16\r\n\r\n//Parse Dates using DateFormat\r\nDate date2 = DateFormat.getDateInstance(\r\nDateFormat.SHORT).parse(\"10/16/12\");\r\nSystem.out.println(date2);//Tue Oct 16 00:00:00 GMT+05:30 2012\r\n\r\n//Creating Dates using SimpleDateFormat\r\nDate date1 = new SimpleDateFormat(\"yy-MM-dd\")\r\n.parse(\"12-10-16\");\r\nSystem.out.println(date1);//Tue Oct 16 00:00:00 GMT+05:30 2012\r\n```\r\n#### Default Locale\r\n```\r\nLocale defaultLocale = Locale.getDefault();\r\n\r\nSystem.out.println(defaultLocale\r\n.getDisplayCountry());//United States\r\nSystem.out.println(defaultLocale\r\n.getDisplayLanguage());//English\r\n```\r\n### Calendar\r\n- Calendar class is used in Java to manipulate Dates. Calendar class provides easy ways to add or reduce days, months or years from a date. It also provide lot of details about a date (which day of the year? Which week of the year? etc.)\r\n\r\n#### Calendar is abstract\r\nCalendar class cannot be created by using new Calendar. The best way to get an instance of Calendar class is by using getInstance() static method in Calendar. \r\n```\r\n//Calendar calendar = new Calendar(); //COMPILER ERROR\r\nCalendar calendar = Calendar.getInstance();\r\n```\r\n#### Calendar set day, month and year\r\nSetting day, month or year on a calendar object is simple. Call the set method with appropriate Constant for Day, Month or Year. Next parameter is the value.\r\n```\r\ncalendar.set(Calendar.DATE, 24);\r\ncalendar.set(Calendar.MONTH, 8);//8 - September\r\ncalendar.set(Calendar.YEAR, 2010);\r\n```\r\n#### Calendar get method\r\nLet's get information about a particular date - 24th September 2010. We use the calendar get method. The parameter passed indicates what value we would want to get from the calendar , day or month or year or .. Few examples of the values you can obtain from a calendar are listed below.\r\n```\r\nSystem.out.println(calendar.get(Calendar.YEAR));//2010\r\nSystem.out.println(calendar.get(Calendar.MONTH));//8\r\nSystem.out.println(calendar.get(Calendar.DATE));//24\r\nSystem.out.println(calendar.get(Calendar.WEEK_OF_MONTH));//4\r\nSystem.out.println(calendar.get(Calendar.WEEK_OF_YEAR));//39\r\nSystem.out.println(calendar.get(Calendar.DAY_OF_YEAR));//267\r\nSystem.out.println(calendar.getFirstDayOfWeek());//1 -> Calendar.SUNDAY\r\n```\r\n#### Calendar - Modify a Date\r\nWe can use the calendar add and roll methods to modify a date. Calendar add method can be used to find a date 5 days or 5 months before the date by passing a ,5 i.e. a negative 5. \r\n```\r\ncalendar.add(Calendar.DATE, 5);\r\nSystem.out.println(calendar.getTime());//Wed Sep 29 2010\r\ncalendar.add(Calendar.MONTH, 1);\r\nSystem.out.println(calendar.getTime());//Fri Oct 29 2010\r\ncalendar.add(Calendar.YEAR, 2);\r\nSystem.out.println(calendar.getTime());//Mon Oct 29 2012\r\n```\r\n#### Roll method\r\nRoll method will only the change the value being modified. YEAR remains unaffected when MONTH is changed, for instance.\r\n```\r\ncalendar.roll(Calendar.MONTH, 5);\r\nSystem.out.println(calendar.getTime());//Mon Mar 29 2012\r\n```\r\n#### Creating calendar: Example 2\r\n```\r\nCalendar gregorianCalendar = new GregorianCalendar(\r\n2011, 7, 15);\r\n```\r\n#### Formatting Calendar object.\r\nDone by getting the date using calendar.getTime() and using the usual formatting of dates.\r\n```\r\nSystem.out.println(DateFormat.getInstance().format(\r\ncalendar.getTime()));//3/29/12 11:39 AM\r\n```\r\n### Number Format\r\n- Number format is used to format a number to different locales and different formats.\r\n\r\n#### Format number Using Default locale\r\n```\r\nSystem.out.println(NumberFormat.getInstance().format(321.24f));//321.24\r\n```\r\n#### Format number using locale\r\nFormatting a number using Netherlands locale\r\n```\r\nSystem.out.println(NumberFormat.getInstance(new Locale(\"nl\")).format(4032.3f));//4.032,3\r\n```\r\n\r\nFormatting a number using Germany locale\r\n```\r\nSystem.out.println(NumberFormat.getInstance(Locale.GERMANY).format(4032.3f));//4.032,3\r\n```\r\n#### Formatting a Currency using Default locale\r\n```\r\nSystem.out.println(NumberFormat.getCurrencyInstance().format(40324.31f));//$40,324.31\r\n```\r\n#### Format currency using locale\r\n```\r\nFormatting a Currency using Netherlands locale\r\nSystem.out.println(NumberFormat.getCurrencyInstance(new Locale(\"nl\")).format(40324.31f));//? 40.324,31\r\n```\r\n\r\nSetting maximum fraction digits for a float\r\n```\r\nNumberFormat numberFormat = NumberFormat.getInstance();\r\nSystem.out.println(numberFormat.getMaximumFractionDigits());//3\r\nnumberFormat.setMaximumFractionDigits(5);\r\nSystem.out.println(numberFormat.format(321.24532f));//321.24533\r\n```\r\n#### Parsing using NumberFormat\r\nParsing a float value using number format\r\n```\r\nSystem.out.println(numberFormat.parse(\"9876.56\"));//9876.56\r\n```\r\n\r\nParsing only number value using number format\r\n```\r\nnumberFormat.setParseIntegerOnly(true);\r\nSystem.out.println(numberFormat.parse(\"9876.56\"));//9876\r\n```\r\n### Collection Interfaces\r\n- Arrays are not dynamic. Once an array of a particular size is declared, the size cannot be modified. To add a new element to the array, a new array has to be created with bigger size and all the elements from the old array copied to new array. Collections are used in situations where data is dynamic. Collections allow adding an element, deleting an element and host of other operations. There are a number of Collections in Java allowing to choose the right Collection for the right context. Before looking into Collection classes, let's take a quick look at all the important collection interfaces and the operations they allow. \r\n\r\n#### Collection Interface\r\nMost important methods declared in the collection interface are the methods to add and remove an element.  add method allows adding an element to a collection and delete method allows deleting an element from a collection.\r\nsize() methods returns number of elements in the collection. Other important methods defined as part of collection interface are shown below. \r\n```\r\ninterface Collection<E> extends Iterable<E>\r\n{\r\n  boolean add(E paramE);\r\n  boolean remove(Object paramObject);\r\n\r\n  int size();\r\n  boolean isEmpty();\r\n  void clear();\r\n\r\n  boolean contains(Object paramObject);\r\n  boolean containsAll(Collection<?> paramCollection);\r\n  \r\n  boolean addAll(Collection<? extends E> paramCollection);\r\n  boolean removeAll(Collection<?> paramCollection);\r\n  boolean retainAll(Collection<?> paramCollection);\r\n  \r\n\r\n  Iterator<E> iterator();\r\n\r\n  //A NUMBER OF OTHER METHODS AS WELL..\r\n}\r\n```\r\n#### List Interface \r\nList interface extends Collection interface. So, it contains all methods defined in the Collection interface. In addition, List interface allows operation specifying the position of the element in the Collection.\r\nAny implementation of the List interface would maintain the insertion order.  When a new element is inserted, it is inserted at the end of the list of elements. We can also use the  void add(int paramInt, E paramE); method to insert an element at a specific position. We can also set and get the elements at a particular index in the list using corresponding methods.\r\n\r\nOther important methods are listed below:\r\n\r\n```\r\ninterface List<E> extends Collection<E>\r\n{\r\n  boolean addAll(int paramInt, Collection<? extends E> paramCollection);\r\n\r\n  E get(int paramInt);\r\n  E set(int paramInt, E paramE);\r\n\r\n  void add(int paramInt, E paramE);\r\n  E remove(int paramInt);\r\n\r\n  int indexOf(Object paramObject);\r\n  int lastIndexOf(Object paramObject);\r\n\r\n  ListIterator<E> listIterator();\r\n  ListIterator<E> listIterator(int paramInt);\r\n  List<E> subList(int paramInt1, int paramInt2);\r\n}\r\n```\r\n#### Map Interface\r\nFirst and foremost, Map interface does not extend Collection interface.  So, it does not inherit any of the methods from the Collection interface.\r\nA Map interface supports Collections that use a key value pair. A key-value pair is a set of linked data items: a key, which is a unique identifier for some item of data, and the value, which is either the data or a pointer to the data. Key-value pairs are used in lookup tables, hash tables and configuration files. A key value pair in a Map interface is called an Entry.\r\nPut method allows to add a key, value pair to the Map. \r\n```\r\n  V put(K paramK, V paramV);\r\n```\r\n\r\nGet method allows to get a value from the Map based on the key.\r\n```\r\n  V get(Object paramObject);\r\n```\r\nOther important methods are shown below:\r\n```\r\ninterface Map<K, V>\r\n{\r\n  int size();\r\n  boolean isEmpty();\r\n\r\n  boolean containsKey(Object paramObject);\r\n  boolean containsValue(Object paramObject);\r\n\r\n  V get(Object paramObject);\r\n  V put(K paramK, V paramV);\r\n  V remove(Object paramObject);\r\n\r\n  void putAll(Map<? extends K, ? extends V> paramMap);\r\n  void clear();\r\n\r\n  Set<K> keySet();\r\n  Collection<V> values();\r\n  Set<Entry<K, V>> entrySet();\r\n\r\n  boolean equals(Object paramObject);\r\n  int hashCode();\r\n\r\n  public static abstract interface Entry<K, V>\r\n  {\r\n    K getKey();\r\n    V getValue();\r\n    V setValue(V paramV);\r\n    boolean equals(Object paramObject);\r\n    int hashCode();\r\n  }\r\n}\r\n```\r\n#### Set Interface\r\nSet Interface extends Collection Interface. Set interface only contains the methods from the Collection interface with added restriction that it cannot contain duplicates.\r\n```\r\n// Unique things only - Does not allow duplication.\r\n// If obj1.equals(obj2) then only one of them can be in the Set.\r\ninterface Set<E> extends Collection<E>\r\n{\r\n}\r\n```\r\n#### SortedSet Interface\r\nSortedSet Interface extends the Set Interface. So, it does not allow duplicates.\r\nIn addition, an implementation of SortedSet interface maintains its elements in a sorted order. It adds operations that allow getting a range of values (subSet, headSet, tailSet).    \r\nImportant Operations listed below:\r\n```\r\npublic interface SortedSet<E> extends Set<E> {\r\n    \r\n    SortedSet<E> subSet(E fromElement, E toElement);\r\n    SortedSet<E> headSet(E toElement);\r\n    SortedSet<E> tailSet(E fromElement);\r\n    \r\n    E first();\r\n    E last();\r\n\r\n    Comparator<? super E> comparator();\r\n}\r\n```\r\n#### SortedMap Interface\r\nSortedMap interface extends the Map interface. In addition, an implementation of SortedMap interface maintains keys in a sorted order.\r\nMethods are available in the interface to get a ranges of values based on their keys.\r\n```\r\npublic interface SortedMap<K, V> extends Map<K, V> {\r\n    Comparator<? super K> comparator();\r\n\r\n    SortedMap<K, V> subMap(K fromKey, K toKey);\r\n\r\n    SortedMap<K, V> headMap(K toKey);\r\n\r\n    SortedMap<K, V> tailMap(K fromKey);\r\n\r\n    K firstKey();\r\n\r\n    K lastKey();\r\n}\r\n```\r\n#### Queue Interface\r\nQueue Interface extends Collection interface. Queue Interface is typically used for implementation holding elements in order for some processing.  \r\nQueue interface offers methods peek() and poll() which get the element at head of the queue. The difference is that poll() method removes the head from queue also. peek() would keep head of the queue unchanged.\r\n\r\n```\r\ninterface Queue<E> extends Collection<E>\r\n{\r\n  boolean offer(E paramE);\r\n  E remove();\r\n  E poll();\r\n  E element();\r\n  E peek();\r\n}\r\n```\r\n#### Iterator interface\r\nIterator interface enables us to iterate (loop around) a collection. All collections define a method iterator() that gets an iterator of the collection. \r\nhasNext() checks if there is another element in the collection being iterated. next() gets the next element.\r\n```\r\npublic interface Iterator<E> {\r\n    boolean hasNext();\r\n\r\n    E next();\r\n}\r\n```\r\n### Collections\r\n- Collections can only hold Objects - not primitives.\r\n\r\n#### ArrayList\r\nArrayList implements the list interface. So, ArrayList stores the elements in insertion order (by default). Element's can be inserted into and removed from ArrayList based on their position.\r\nLet's look at how to instantiate an ArrayList of integers.\r\n```\r\nList<Integer> integers = new ArrayList<Integer>();\r\n```\r\n\r\nCode like below is permitted because of auto boxing. 5 is auto boxed into Integer object and stored in ArrayList.\r\n```\r\nintegers.add(5);//new Integer(5)\r\n```\r\n\r\nAdd method (by default) adds the element at the end of the list.\r\n#### ArrayList of String Example\r\nBelow example shows how to create and use a String ArrayList. ArrayList can have duplicates (since List can have duplicates). size() method gets number of elements in the ArrayList. contains(Object) method checks if an element is present in the arraylist. \r\n```\r\nList<String> arraylist = new ArrayList<String>();\r\n\r\n//adds at the end of list\r\narraylist.add(\"Sachin\");//[Sachin]\r\n\r\n//adds at the end of list\r\narraylist.add(\"Dravid\");//[Sachin, Dravid]\r\n\r\n//adds at the index 0\r\narraylist.add(0, \"Ganguly\");//[Ganguly, Sachin, Dravid]\r\n\r\n//List allows duplicates - Sachin is present in the list twice\r\narraylist.add(\"Sachin\");//[ Ganguly, Sachin, Dravid, Sachin]\r\n\r\nSystem.out.println(arraylist.size());//4\r\nSystem.out.println(arraylist.contains(\"Dravid\"));//true\r\n```\r\n#### Iterating around a list\r\n```\r\nIterator<String> arraylistIterator = arraylist\r\n.iterator();\r\nwhile (arraylistIterator.hasNext()) {\r\n    String str = arraylistIterator.next();\r\n    System.out.println(str);//Prints the 4 names in the list on separate lines.\r\n}\r\n```\r\n\r\n#### Other ArrayList (List) methods\r\nindexOf() function - returns index of element if element is found. Negative number otherwise.\r\n```\r\n//example1 - value is present\r\nSystem.out.println(arraylist.indexOf(\"Dravid\"));//2\r\n//example2 - value is not present\r\nSystem.out.println(arraylist.indexOf(\"Bradman\"));//-1\r\n```\r\n\r\nget() function - get value at specified index.\r\n```\r\nSystem.out.println(arraylist.get(1));//Sachin\r\n```\r\n#### remove() function\r\nremove() function has two variations.\r\n```\r\n//Using the object as parameter\r\n//Dravid is removed from the list\r\narraylist.remove(\"Dravid\");//[Ganguly, Sachin, Sachin]\r\n\r\n//Using index as argument. \r\n//Object at index 1 (Sachin) is removed\r\narraylist.remove(1);//[Ganguly, Sachin]\r\n```\r\n#### Sorting Collections\r\n```\r\nList<String> numbers = new ArrayList<String>();\r\nnumbers.add(\"one\");\r\nnumbers.add(\"two\");\r\nnumbers.add(\"three\");\r\nnumbers.add(\"four\");\r\nSystem.out.println(numbers);//[one, two, three, four]\r\n\r\n//Strings - By Default - are sorted alphabetically\r\nCollections.sort(numbers);\r\n\r\nSystem.out.println(numbers);//[four, one, three, two]\r\n```\r\n#### List of Objects of a Custom Class\r\nConsider the following class Cricketer.\r\n```\r\nclass Cricketer{\r\n    int runs;\r\n    String name;\r\n\r\n    public Cricketer(String name, int runs) {\r\nsuper();\r\nthis.name = name;\r\nthis.runs = runs;\r\n    }\r\n\r\n    @Override\r\n    public String toString() {\r\nreturn name + \" \" + runs;\r\n    }\r\n}\r\n```\r\n\r\nLet's now try to sort a list containing objects of Cricketer class.\r\n```\r\nList<Cricketer> cricketers = new ArrayList<Cricketer>();\r\ncricketers.add(new Cricketer(\"Bradman\", 9996));\r\ncricketers.add(new Cricketer(\"Sachin\", 14000));\r\ncricketers.add(new Cricketer(\"Dravid\", 12000));\r\ncricketers.add(new Cricketer(\"Ponting\", 11000));\r\nSystem.out.println(cricketers);\r\n//[Bradman 9996, Sachin 14000, Dravid 12000, Ponting 11000]\r\n\r\n//Cricketer class does not implement Comparable Interface \r\n//Collections.sort(cricketers); //COMPILER ERROR\r\n```\r\n\r\nWe get a compiler error since Cricketer class does not implement Comparable interface. We were able to sort numbers in earlier example because String class implements Comparable.\r\nLet's make the Cricketer class implement the Comparable Interface.\r\n```\r\nclass Cricketer implements Comparable<Cricketer> {\r\n    //OTHER CODE/PROGRAM same as previous\r\n\r\n    //compareTo takes an argument of the same type of the class\r\n    //compareTo returns -1 if this < that\r\n    //   1 if this > that\r\n    //   0 if this = that\r\n    @Override\r\n    public int compareTo(Cricketer that) {\r\nif (this.runs > that.runs) {\r\n    return 1;\r\n}\r\nif (this.runs < that.runs) {\r\n    return -1;\r\n}\r\nreturn 0;\r\n    }\r\n\r\n}\r\n```\r\n\r\nNow let's try to sort the cricketers.\r\n```\r\nCollections.sort(cricketers);\r\nSystem.out.println(cricketers);\r\n//[Bradman 9996, Ponting 11000, Dravid 12000, Sachin 14000]\r\n```\r\n\r\nOther option to sort collections is by creating a separate class which implements Comparator interface.\r\nExample below:\r\n```\r\nclass DescendingSorter implements Comparator<Cricketer> {\r\n\r\n    //compareTo returns -1 if cricketer1 < cricketer2\r\n    //   1 if cricketer1 > cricketer2\r\n    //   0 if cricketer1 = cricketer2\r\n\r\n    //Since we want to sort in descending order, \r\n    //we should return -1 when runs are more\r\n    @Override\r\n    public int compare(Cricketer cricketer1,\r\n    Cricketer cricketer2) {\r\nif (cricketer1.runs > cricketer2.runs) {\r\n    return -1;\r\n}\r\nif (cricketer1.runs < cricketer2.runs) {\r\n    return 1;\r\n}\r\nreturn 0;\r\n    }\r\n\r\n}\r\n```\r\n\r\nLet's now try to sort the previous defined collection:\r\n```\r\nCollections\r\n.sort(cricketers, new DescendingSorter());\r\n\r\nSystem.out.println(cricketers);\r\n//[Sachin 14000, Dravid 12000, Ponting 11000, Bradman 9996]\r\n```\r\n#### Convert List to Array\r\nThere are two ways. First is to use toArray(String) function. Example below. This creates an array of String's\r\n```\r\nList<String> numbers1 = new ArrayList<String>();\r\nnumbers1.add(\"one\");\r\nnumbers1.add(\"two\");\r\nnumbers1.add(\"three\");\r\nnumbers1.add(\"four\");\r\nString[] numbers1Array = new String[numbers1.size()];\r\nnumbers1Array = numbers1.toArray(numbers1Array);\r\nSystem.out.println(Arrays.toString(numbers1Array));\r\n//prints [one, two, three, four]\r\n```\r\n\r\nOther is to use toArray() function. Example below. This creates an array of Objects.\r\n```\r\nObject[] numbers1ObjArray = numbers1.toArray();\r\nSystem.out.println(Arrays\r\n.toString(numbers1ObjArray));\r\n//[one, two, three, four]\r\n```\r\n#### Convert Array to List\r\n```\r\nString values[] = { \"value1\", \"value2\", \"value3\" };\r\nList<String> valuesList = Arrays.asList(values);\r\nSystem.out.println(valuesList);//[value1, value2, value3]\r\n```\r\n#### Other List interface implementations\r\nOther classes that implement List interface are Vector and LinkedList.\r\n#### Vector\r\nVector has the same operations as an ArrayList. However, all methods in Vector are synchronized. So, we can use Vector if we share a list between two threads and we would want to them synchronized.\r\n#### LinkedList\r\nLinked List extends List and Queue.Other than operations exposed by the Queue interface,  LinkedList has the same operations as an ArrayList. However, the underlying implementation of Linked List is different from that of an ArrayList. \r\nArrayList uses an Array kind of structure to store elements. So, inserting and deleting from an ArrayList are expensive operations. However, search of an ArrayList is faster than LinkedList.\r\nLinkedList uses a linked representation. Each object holds a link to the next element. Hence, insertion and deletion are faster than ArrayList. But searching is slower.\r\n### Set Interface\r\n- HashSet, LinkedHashSet and TreeSet implement the Set interface. Let's look at examples of these collection classes.\r\n\r\n#### HashSet\r\nHashSet implements set interface. Sets do not allow duplicates. HashSet does not support ordering.\r\n#### HashSet Example\r\n```\r\nSet<String> hashset = new HashSet<String>();\r\n\r\nhashset.add(\"Sachin\");\r\nSystem.out.println(hashset);//[Sachin]\r\n\r\nhashset.add(\"Dravid\");\r\nSystem.out.println(hashset);//[Sachin, Dravid]\r\n```\r\n\r\nLet's try to add Sachin to the Set now. Sachin is Duplicate. So will not be added. returns false.\r\n```\r\nhashset.add(\"Sachin\");//returns false since element is not added\r\nSystem.out.println(hashset);//[Sachin, Dravid]\r\n```\r\n#### LinkedHashSet\r\nLinkedHashSet implements set interface and exposes similar operations to a HashSet. Difference is that LinkedHashSet maintains insertion order. When we iterate a LinkedHashSet, we would get the elements back in the order in which they were inserted.\r\n#### TreeSet\r\nTreeSet implements Set, SortedSet and NavigableSet interfaces.TreeSet is similar to HashSet except that it stores element's in Sorted Order.\r\n```\r\nSet<String> treeSet = new TreeSet<String>();\r\n\r\ntreeSet.add(\"Sachin\");\r\nSystem.out.println(treeSet);//[Sachin]\r\n```\r\n\r\nNotice that the list is sorted after inserting Dravid.\r\n```\r\n//Alphabetical order\r\ntreeSet.add(\"Dravid\");\r\nSystem.out.println(treeSet);//[Dravid, Sachin]\r\n```\r\n\r\nNotice that the list is sorted after inserting Ganguly.\r\n```\r\ntreeSet.add(\"Ganguly\");\r\nSystem.out.println(treeSet);//[Dravid, Ganguly, Sachin]\r\n\r\n//Sachin is Duplicate. So will not be added. returns false.\r\ntreeSet.add(\"Sachin\");//returns false since element is not added\r\nSystem.out.println(treeSet);//[Dravid, Ganguly, Sachin]\r\n```\r\nObjects that are inserted into a TreeSet should be comparable.\r\n#### TreeSet - NavigableSet interface examples 1\r\nTreeSet implements this interface. Let's look at an example with TreeSet. Note that elements in TreeSet are sorted.\r\n```\r\nTreeSet<Integer> numbersTreeSet = new TreeSet<Integer>();\r\nnumbersTreeSet.add(55);\r\nnumbersTreeSet.add(25);\r\nnumbersTreeSet.add(35);\r\nnumbersTreeSet.add(5);\r\nnumbersTreeSet.add(45);\r\n```\r\n\r\nNavigableSet interface has following methods. \r\nLower method finds the highest element lower than specified element. Floor method finds the highest element lower than or equal to specified element.  Corresponding methods for finding lowest number higher than specified element are higher and ceiling. A few examples using the Set created earlier below.\r\n```\r\n//Find the highest number which is lower than 25\r\nSystem.out.println(numbersTreeSet.lower(25));//5\r\n\r\n//Find the highest number which is lower than or equal to 25\r\nSystem.out.println(numbersTreeSet.floor(25));//25\r\n\r\n//Find the lowest number higher than 25\r\nSystem.out.println(numbersTreeSet.higher(25));//35\r\n\r\n//Find the lowest number higher than or equal to 25\r\nSystem.out.println(numbersTreeSet.ceiling(25));//25\r\n```\r\n#### NavigableSet subSet,headSet,tailSet Methods in TreeSet \r\n```\r\nTreeSet<Integer> exampleTreeSet = new TreeSet<Integer>();\r\nexampleTreeSet.add(55);\r\nexampleTreeSet.add(25);\r\nexampleTreeSet.add(105);\r\nexampleTreeSet.add(35);\r\nexampleTreeSet.add(5);\r\n\r\nSystem.out.println(exampleTreeSet);//[5, 25, 35, 55, 105]\r\n```\r\n\r\nAll the three methods - subSet,headSet,tailSet - are inclusive with Lower Limit and NOT inclusive with higher limit.\r\nIn the sub set below, Lower Limit is inclusive - 25 included. Higher limit is not inclusive - 55 excluded.\r\n```\r\n//Get sub set with values >=25 and <55\r\nSortedSet<Integer> subTreeSet = exampleTreeSet\r\n.subSet(25, 55);\r\nSystem.out.println(subTreeSet);//[25, 35]\r\n```\r\n\r\nIn the sub set below, Higher limit not inclusive - 55 excluded.\r\n```\r\n//Get sub set with values <55\r\nSortedSet<Integer> headTreeSet = exampleTreeSet\r\n.headSet(55);\r\nSystem.out.println(headTreeSet);//[5, 25, 35]\r\n\r\n//Get sub set with values >=35\r\nSortedSet<Integer> tailTreeSet = exampleTreeSet\r\n.tailSet(35);\r\nSystem.out.println(tailTreeSet);//[35, 55, 105]\r\n//In the sub set, Lower limit inclusive - 35 included.\r\n\r\n//Get sub set with value >=25 and <=55 (both inclusive parameters - true)\r\nSortedSet<Integer> subTreeSetIncl = exampleTreeSet\r\n.subSet(25, true, 55, true);\r\nSystem.out.println(subTreeSetIncl);//[25, 35, 55]\r\n\r\n//Get sub set with value >25 and <55 (both inclusive parameters - false)\r\nSortedSet<Integer> subTreeSetNotIncl = exampleTreeSet\r\n.subSet(25, false, 55, false);\r\nSystem.out.println(subTreeSetNotIncl);//[35]\r\n\r\n//Get sub set with values <=55. Inclusive set to true.\r\nSortedSet<Integer> headTreeSetIncl = exampleTreeSet\r\n.headSet(55, true);\r\nSystem.out.println(headTreeSetIncl);//[5, 25, 35, 55]\r\n\r\n//Get sub set with values >35. Inclusive set to false.\r\nSortedSet<Integer> tailTreeSetNotIncl = exampleTreeSet\r\n.tailSet(35, false);\r\nSystem.out.println(tailTreeSetNotIncl);//[55, 105]\r\n```\r\n\r\nAll the sub set methods  - subSet,headSet,tailSet - return dynamic sub sets. When original set is modified (addition or deletion), corresponding changes can affect the sub sets as well. \r\n```\r\nSystem.out.println(exampleTreeSet);//[5, 25, 35, 55, 105]\r\nSystem.out.println(subTreeSet);//[25, 35]\r\nSystem.out.println(headTreeSet);//[5, 25, 35]\r\nSystem.out.println(tailTreeSet);//[35, 55, 105]\r\n```\r\n\r\nLet's now insert a value 30 into the exampleTreeSet. Remember that subTreeSet, headTreeSet, tailTreeSet are sub sets of exampleTreeSet.\r\n```\r\nexampleTreeSet.add(30);\r\n\r\nSystem.out.println(exampleTreeSet);//[5, 25, 30, 35, 55, 105]\r\nSystem.out.println(subTreeSet);//[25, 30, 35]\r\nSystem.out.println(headTreeSet);//[5, 30, 25, 35]\r\nSystem.out.println(tailTreeSet);//[35, 55, 105]\r\n```\r\n\r\n30 is in the range of subTreeSet and headTreeSet. So, it is printed as part of exampleTreeSet, subTreeSet and headTreeSet.\r\n```\r\n//Let's now add 65 to the set\r\nexampleTreeSet.add(65);\r\n\r\nSystem.out.println(exampleTreeSet);//[5, 25, 30, 35, 55, 65, 105]\r\nSystem.out.println(subTreeSet);//[25, 30, 35]\r\nSystem.out.println(headTreeSet);//[5, 30, 25, 35]\r\nSystem.out.println(tailTreeSet);//[35, 55, 65, 105]\r\n```\r\n\r\n65 is printed as part of exampleTreeSet and tailTreeSet.\r\nKey thing to remember is that all the sub sets are dynamic. If you modify the original set,the sub set might be affected.\r\n#### TreeSet - NavigableSet interface methods  - pollFirst,  pollLast and more\r\n```\r\nTreeSet<Integer> treeSetOrig = new TreeSet<Integer>();\r\ntreeSetOrig.add(55);\r\ntreeSetOrig.add(25);\r\ntreeSetOrig.add(35);\r\ntreeSetOrig.add(5);\r\n\r\nSystem.out.println(treeSetOrig);//[5, 25, 35, 55]\r\n//descendingSet method returns the tree set in reverse order\r\nTreeSet<Integer> treeSetDesc = (TreeSet<Integer>) treeSetOrig\r\n.descendingSet();\r\nSystem.out.println(treeSetDesc);//[55, 35, 25, 5]\r\n```\r\n\r\npollFirst returns the first element and removes it from the set.\r\n```\r\nSystem.out.println(treeSetOrig);//[5, 25, 35, 55]\r\nSystem.out.println(treeSetOrig.pollFirst());//5\r\nSystem.out.println(treeSetOrig);//[25, 35, 55]\r\n//In above example element 5 is removed from the set and also removed from the tree set.\r\n```\r\n\r\npollLast returns the last element and removes it from the set.\r\n```\r\nSystem.out.println(treeSetOrig);//[25, 35, 55]\r\nSystem.out.println(treeSetOrig.pollLast());//55\r\nSystem.out.println(treeSetOrig);//[25, 35]\r\n```\r\n### Map Interface\r\n- Let's take a look at different implementations of the Map interface.\r\n\r\n#### HashMap\r\nHashMap implements Map interface , there by supporting key value pairs. \r\n#### HashMap Example\r\n```\r\nMap<String, Cricketer> hashmap = new HashMap<String, Cricketer>();\r\nhashmap.put(\"sachin\",\r\nnew Cricketer(\"Sachin\", 14000));\r\nhashmap.put(\"dravid\",\r\nnew Cricketer(\"Dravid\", 12000));\r\nhashmap.put(\"ponting\", new Cricketer(\"Ponting\",\r\n11500));\r\nhashmap.put(\"bradman\", new Cricketer(\"Bradman\",\r\n9996));\r\n```\r\n#### Hash Map Methods\r\nget method gets the value of the matching key.\r\n```\r\nSystem.out.println(hashmap.get(\"ponting\"));//Ponting 11500\r\n\r\n//if key is not found, returns null.\r\nSystem.out.println(hashmap.get(\"lara\"));//null\r\n```\r\n\r\nIf existing key is reused, it would replace existing value with the new value passed in.\r\n```\r\n//In the example below, an entry with key \"ponting\" is already present. \r\n//Runs are updated to 11800.\r\nhashmap.put(\"ponting\", new Cricketer(\"Ponting\",\r\n11800));\r\n\r\n//gets the recently updated value\r\nSystem.out.println(hashmap.get(\"ponting\"));//Ponting 11800\r\n```\r\n#### TreeMap\r\nTreeMap is similar to HashMap except that it stores keys in sorted order. It implements NavigableMap interface and SortedMap interfaces along with the Map interface.\r\n```\r\nMap<String, Cricketer> treemap = new TreeMap<String, Cricketer>();\r\ntreemap.put(\"sachin\",\r\nnew Cricketer(\"Sachin\", 14000));\r\nSystem.out.println(treemap);\r\n//{sachin=Sachin 14000}\r\n```\r\n\r\nWe will now insert a Cricketer with key dravid. In sorted order,dravid comes before sachin. So, the value with key dravid is inserted at the start of the Map.\r\n```\r\ntreemap.put(\"dravid\",\r\nnew Cricketer(\"Dravid\", 12000));\r\nSystem.out.println(treemap);\r\n//{dravid=Dravid 12000, sachin=Sachin 14000}\r\n```\r\n\r\nWe will now insert a Cricketer with key ponting. In sorted order, ponting fits in between dravid and sachin. \r\n```\r\ntreemap.put(\"ponting\", new Cricketer(\"Ponting\",\r\n11500));\r\nSystem.out.println(treemap);\r\n//{dravid=Dravid 12000, ponting=Ponting 11500, sachin=Sachin 14000}\r\n\r\ntreemap.put(\"bradman\", new Cricketer(\"Bradman\",\r\n9996));\r\nSystem.out.println(treemap);\r\n//{bradman=Bradman 9996, dravid=Dravid 12000, ponting=Ponting 11500, sachin=Sachin 14000}\r\n```\r\n#### NavigableMap Interface Examples (TreeMap) Set I\r\nLet's look at an example with TreeMap. Note that keys in TreeMap are sorted.\r\n```\r\nTreeMap<Integer, Cricketer> numbersTreeMap = new TreeMap<Integer, Cricketer>();\r\nnumbersTreeMap.put(55, new Cricketer(\"Sachin\",\r\n14000));\r\nnumbersTreeMap.put(25, new Cricketer(\"Dravid\",\r\n12000));\r\nnumbersTreeMap.put(35, new Cricketer(\"Ponting\",\r\n12000));\r\nnumbersTreeMap.put(5,\r\nnew Cricketer(\"Bradman\", 9996));\r\nnumbersTreeMap\r\n.put(45, new Cricketer(\"Lara\", 10000));\r\n```\r\n\r\nlowerKey method finds the highest key lower than specified key. floorKey method finds the highest key lower than or equal to specified key.  Corresponding methods for finding lowest key higher than specified key are higher and ceiling. A few examples using the Map created earlier below.\r\n```\r\n//Find the highest key which is lower than 25\r\nSystem.out.println(numbersTreeMap.lowerKey(25));//5\r\n\r\n//Find the highest key which is lower than or equal to 25\r\nSystem.out.println(numbersTreeMap.floorKey(25));//25\r\n\r\n//Find the lowest key higher than 25\r\nSystem.out.println(numbersTreeMap.higherKey(25));//35\r\n\r\n//Find the lowest key higher than or equal to 25\r\nSystem.out.println(numbersTreeMap.ceilingKey(25));//25\r\n```\r\n#### NavigableMap Interface Examples (TreeMap) Set II\r\nMethods similar to subSet,headSet,tailSet (of TreeSet) are available in TreeMap as well. They are called subMap, headMap, tailMap.They have the similar signatures and results as the corresponding TreeSet Methods. They are inclusive with Lower Limit and NOT inclusive with higher limit - unless the (optional) inclusive flag is passed. The resultant sub map's are dynamic. If original map get modified, the sub map might be affected as well.\r\n```\r\nTreeMap<Integer, Cricketer> exampleTreeMap = new TreeMap<Integer, Cricketer>();\r\nexampleTreeMap.put(55, new Cricketer(\"Sachin\",\r\n14000));\r\nexampleTreeMap.put(25, new Cricketer(\"Dravid\",\r\n12000));\r\nexampleTreeMap.put(5,\r\nnew Cricketer(\"Bradman\", 9996));\r\nexampleTreeMap\r\n.put(45, new Cricketer(\"Lara\", 10000));\r\n\r\n//Lower limit (5) inclusive, Uppper Limit(25) NOT inclusive\r\nSystem.out.println(exampleTreeMap.subMap(5, 25));//{5=Bradman 9996}\r\n\r\nSystem.out.println(exampleTreeMap.headMap(30));\r\n//{5=Bradman 9996, 25=Dravid 12000}\r\n\r\nSystem.out.println(exampleTreeMap.tailMap(25));\r\n//{25=Dravid 12000, 45=Lara 10000, 55=Sachin 14000}\r\n```\r\n#### NavigableMap Interface Examples (TreeMap) Set III\r\nConsider the next set of method examples below:\r\n```\r\nTreeMap<Integer, Cricketer> treeMapOrig = new TreeMap<Integer, Cricketer>();\r\ntreeMapOrig.put(55, new Cricketer(\"Sachin\", 14000));\r\ntreeMapOrig.put(25, new Cricketer(\"Dravid\", 12000));\r\ntreeMapOrig.put(5, new Cricketer(\"Bradman\", 9996));\r\ntreeMapOrig.put(45, new Cricketer(\"Lara\", 10000));\r\n\r\nSystem.out.println(treeMapOrig);\r\n//{5=Bradman 9996, 25=Dravid 12000, 45=Lara 10000, 55=Sachin 14000}\r\n```\r\n\r\ndescendingMap method returns the tree set in reverse order.\r\n```\r\nNavigableMap<Integer, Cricketer> treeMapDesc = treeMapOrig\r\n.descendingMap();\r\nSystem.out.println(treeMapDesc);\r\n//{55=Sachin 14000, 45=Lara 10000, 25=Dravid 12000, 5=Bradman 9996}\r\n```\r\n\r\npollFirstEntry returns the first entry in the map and removes it from the map.\r\n```\r\nSystem.out.println(treeMapOrig);\r\n//{5=Bradman 9996, 25=Dravid 12000, 45=Lara 10000, 55=Sachin 14000}\r\nSystem.out.println(treeMapOrig.pollFirstEntry());//5=Bradman 9996\r\nSystem.out.println(treeMapOrig);\r\n//{25=Dravid 12000, 45=Lara 10000, 55=Sachin 14000}\r\n//In above example element 5 is removed from the set and also removed from the tree set.\r\n```\r\n\r\npollLastEntry returns the last entry from the map and removes it from the map.\r\n```\r\nSystem.out.println(treeMapOrig);\r\n//{25=Dravid 12000, 45=Lara 10000, 55=Sachin 14000}\r\nSystem.out.println(treeMapOrig.pollLastEntry());//55=Sachin 14000\r\nSystem.out.println(treeMapOrig);\r\n//{25=Dravid 12000, 45=Lara 10000}\r\n```\r\n### PriorityQueue\r\n- PriorityQueue implements the Queue interface.\r\n\r\n#### PriorityQueue Example\r\n```\r\n//Using default constructor - uses natural ordering of numbers\r\n//Smaller numbers have higher priority\r\nPriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();\r\n```\r\n#### Adding an element into priority queue - offer method\r\n```\r\npriorityQueue.offer(24);\r\npriorityQueue.offer(15);\r\npriorityQueue.offer(9);\r\npriorityQueue.offer(45);\r\n\r\nSystem.out.println(priorityQueue);//[9, 24, 15, 45]\r\n```\r\n#### Peek method examples\r\n```\r\n//peek method get the element with highest priority.\r\nSystem.out.println(priorityQueue.peek());//9\r\n//peek method does not change the queue\r\nSystem.out.println(priorityQueue);//[9, 24, 15, 45]\r\n\r\n//poll method gets the element with highest priority.\r\nSystem.out.println(priorityQueue.poll());//9\r\n//peek method removes the highest priority element from the queue.\r\nSystem.out.println(priorityQueue);//[24, 15, 45]\r\n\r\n//This comparator gives high priority to the biggest number.\r\nComparator reverseComparator = new Comparator<Integer>() {\r\n    public int compare(Integer paramT1,\r\n    Integer paramT2) {\r\nreturn paramT2 - paramT1;\r\n    }\r\n\r\n};\r\n```\r\n#### Priority Queue and Comparator\r\nWe can create priority queue using a comparator class i.e. custom defined priority.\r\n```\r\nPriorityQueue<Integer> priorityQueueDesc = new PriorityQueue<Integer>(\r\n20, reverseComparator);\r\n\r\npriorityQueueDesc.offer(24);\r\npriorityQueueDesc.offer(15);\r\npriorityQueueDesc.offer(9);\r\npriorityQueueDesc.offer(45);\r\n\r\n//45 is the largest element. Our custom comparator gives priority to highest number.\r\nSystem.out.println(priorityQueueDesc.peek());//45\r\n```\r\n\r\n#### Collections static methods\r\n```\r\nstatic int binarySearch(List, key) //Can be used only on sorted list\r\nstatic int binarySearch(List, key, Comparator)\r\nstatic void reverse(List)//Reverse the order of elements in a List.\r\nstatic Comparator reverseOrder();\r\n//Return a Comparator that sorts the reverse of the collection current sort sequence. \r\nstatic void sort(List)\r\nstatic void sort(List, Comparator)\r\n```\r\n### Generics\r\n- Generics are used to create Generic Classes and Generic methods which can work with different Types(Classes).\r\n\r\n#### Need for Generics , Example\r\nConsider the class below:\r\n```\r\nclass MyList {\r\n    private List<String> values;\r\n\r\n    void add(String value) {\r\nvalues.add(value);\r\n    }\r\n\r\n    void remove(String value) {\r\nvalues.remove(value);\r\n    }\r\n}\r\n```\r\n\r\nMyList can be used to store a list of Strings only.\r\n```\r\nMyList myList = new MyList();\r\nmyList.add(\"Value 1\");\r\nmyList.add(\"Value 2\");\r\n```\r\n\r\nTo store integers, we need to create a new class. This is problem that Generics solve. Instead of hard-coding String class as the only type the class can work with, we make the class type a parameter to the class.\r\n#### Generics Example\r\nLet's replace String with T and create a new class.\r\n```\r\nclass MyListGeneric<T> {\r\n    private List<T> values;\r\n\r\n    void add(T value) {\r\nvalues.add(value);\r\n    }\r\n\r\n    void remove(T value) {\r\nvalues.remove(value);\r\n    }\r\n\r\n    T get(int index) {\r\nreturn values.get(index);\r\n    }\r\n}\r\n```\r\n\r\nNote the declaration  of class:\r\n```\r\nclass MyListGeneric<T>\r\n```\r\nInstead of T, We can use any valid identifier\r\nIf a generic is declared as part of class declaration, it can be used any where a type can be used in a class - method (return type or argument), member variable etc. For Example: See how T is used as a parameter and return type in the class MyListGeneric.\r\nNow the MyListGeneric class can be used to create a list of Integers or a list of Strings\r\n```\r\nMyListGeneric<String> myListString = new MyListGeneric<String>();\r\nmyListString.add(\"Value 1\");\r\nmyListString.add(\"Value 2\");\r\n\r\nMyListGeneric<Integer> myListInteger = new MyListGeneric<Integer>();\r\nmyListInteger.add(1);\r\nmyListInteger.add(2);\r\n```\r\n#### Generics Restrictions\r\nIn MyListGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the example class below:\r\n```\r\nclass MyListRestricted<T extends Number> {\r\n    private List<T> values;\r\n\r\n    void add(T value) {\r\nvalues.add(value);\r\n    }\r\n\r\n    void remove(T value) {\r\nvalues.remove(value);\r\n    }\r\n\r\n    T get(int index) {\r\nreturn values.get(index);\r\n    }\r\n}\r\n```\r\n\r\nIn declaration of the class, we specified a constraint \"T extends Number\". We can use the class MyListRestricted with any class extending Number - Float, Integer, Double etc. \r\n```\r\nMyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>();\r\nrestrictedListInteger.add(1);\r\nrestrictedListInteger.add(2);\r\n```\r\n\r\nString not valid substitute for constraint \"T extends Number\".\r\n```\r\n//MyListRestricted<String> restrictedStringList = \r\n//new MyListRestricted<String>();//COMPILER ERROR\r\n```\r\n#### Generic Method Example\r\nA generic type can be declared as part of method declaration as well. Then the generic type can be used anywhere in the method (return type, parameter type, local or block variable type).\r\nConsider the method below:\r\n```\r\n    static <X extends Number> X doSomething(X number){\r\nX result = number;\r\n//do something with result\r\nreturn result;\r\n    }\r\n```\r\n\r\nThe method can now be called with any Class type extend Number.\r\n```\r\nInteger i = 5;\r\nInteger k = doSomething(i);\r\n```\r\n#### Generics and Collections Example 1\r\nConsider the classes below:\r\n```\r\nclass Animal {\r\n}\r\n\r\nclass Dog extends Animal {\r\n}\r\n```\r\n\r\nLet's create couple of Arrays and Lists as shown below:\r\n```\r\nAnimal[] animalsArray = { new Animal(), new Dog() };\r\nDog[] dogsArray = { new Dog(), new Dog() };\r\n\r\nList<Animal> animalsList = Arrays.asList(animalsArray); \r\nList<Dog> dogsList = Arrays.asList(dogsArray); \r\n```\r\n\r\nLet's create a couple of static methods as shown below:\r\n```\r\n    static void doSomethingArray(Animal[] animals) {\r\n//do Something with Animals\r\n    }\r\n\r\n    static void doSomethingList(List<Animal> animals) {\r\n//do Something with Animals\r\n    }\r\n```\r\n\r\n\r\nArray method can be called with Animal[] or Dog[]\r\n```\r\ndoSomethingArray(animalsArray);\r\ndoSomethingArray(dogsArray);\r\n```\r\n\r\nList method works with List<Animal>. Gives compilation error with List<Dog>.\r\n```\r\ndoSomethingList(animalsList);\r\n//List<Dog> not compatible with List<Animal>\r\n//doSomethingList(dogsList);//COMPILER ERROR\r\n```\r\n\r\nSummary :  List<Dog> not compatible with List<Animal> even thought Dog extends Animal. However, Dog[] is compatible with Animal[].\r\n#### Generics and Collections Example 2 - extends\r\nConsider the methods below:\r\n```\r\n    static void doSomethingListModified(List<? extends Animal> animals) {\r\n//Adding an element into  a list declared with ? is prohibited.\r\n\r\n//animals.add(new Animal());//COMPILER ERROR!\r\n//animals.add(new Dog());//COMPILER ERROR!\r\n    }\r\n```\r\n\r\nMethod declared with List<? extends Animal> compiles with both List<Animal> and List<Dog>\r\n```\r\ndoSomethingListModified(animalsList);\r\ndoSomethingListModified(dogsList);\r\n```\r\n#### Generics and Collections Example 3 - Super\r\nMethod declared with List<? super Dog> compiles with both List<Animal> and List<Dog>.\r\n```\r\n    static void doSomethingListModifiedSuper(List<? super Dog> animals) {\r\n//Adding an element into  a list declared with ? is prohibited.\r\n//animals.add(new Animal());//COMPILER ERROR!\r\n//animals.add(new Dog());//COMPILER ERROR!\r\n    }\r\n```\r\n\r\nList of any super class of Dog is fine. List of any Subclass of Dog is not valid parameter.\r\n```\r\ndoSomethingListModifiedSuper(animalsList);    \r\ndoSomethingListModifiedSuper(dogsList);\r\n```\r\n\r\n#### Generics and Collections Example 4 , extends with interface\r\nBelow method can be called with a List declared with any type implementing the interface Serializable.\r\n```\r\n    static void doSomethingListInterface(List<? extends Serializable> animals) {\r\n//Adding an element into  a list declared with ? is prohibited.\r\n\r\n//animals.add(new Animal());//COMPILER ERROR!\r\n//animals.add(new Dog());//COMPILER ERROR!\r\n    }\r\n```\r\n#### Generics and Collections , Few more Examples and Rules\r\nA method declared with List<Object> can only be called with a List declared with type Object. None of the other classes are valid.\r\nA method declared with List<?> can be called with a List of any type.\r\n//A method declared with List<? extends Object> can be called with a List of any type - since all classes are sub classes of Object.\r\n? can only be used in Declaring a type. Cannot be used as part of definition.\r\n```\r\nList<? extends Animal> listAnimals = new ArrayList<Dog>(); //COMPILES\r\n//List<?> genericList = new ArrayList<? extends Animal>(); //COMPILER ERROR\r\n```\r\n#### Generics and Collection , Compatibility with old code\r\nConsider the method below: It is declared to accept a Generic ArrayList. The method adds a string to the arraylist.\r\n```\r\n    static void addElement(ArrayList something){\r\nsomething.add(new String(\"String\"));\r\n    }\r\n```\r\n\r\nConsider the code below:\r\n```\r\nArrayList<Integer> numbers = new ArrayList<Integer>();\r\nnumbers.add(5);\r\nnumbers.add(6);\r\naddElement(numbers);\r\n```\r\n\r\nWe are passing a ArrayList<Integer> to a method accepting ArrayList as parameter. We are trying to a add a string to it as well, inside the method.\r\nCompiling this class would give a warning: javac gives warning because multiplyNumbersBy2(ArrayList) is invoked with a Specific ArrayList<Integer> and in the method addElement an element is added to ArrayList.\r\n```\r\n//com/rithus/generics/GenericsExamples.java uses unchecked or unsafe operations.\r\n//Recompile with -Xlint:unchecked for details.\r\n```\r\n\r\nTo get more details run javac specifying the parameter Xlint:unchecked.\r\n```\r\njavac -Xlint:unchecked com/rithus/generics/GenericsExamples.java\r\n//com/rithus/generics/GenericsExamples.java:21: warning: [unchecked] \r\n//unchecked call to add(E) as a member of the raw type java.util.ArrayList\r\n//something.add(new String(\"String\"));\r\n//     ^\r\n```\r\n### Files\r\n- Let us first look at the File class which helps us to create and delete files and directories. File class cannot be used to modify the content of a file.\r\n\r\n#### File Class\r\n#### Create a File Object\r\n```\r\nFile file = new File(\"FileName.txt\");\r\n```\r\n#### File basic Methods\r\nCheck if the file exists.\r\n```\r\nSystem.out.println(file.exists());\r\n```\r\nIf file does not exist creates it and returns true. If file exists, returns false.\r\n```\r\nSystem.out.println(file.createNewFile());\r\n```\r\n\r\nGetting full path of file.\r\n```\r\nSystem.out.println(file.getAbsolutePath());\r\nSystem.out.println(file.isFile());//true\r\nSystem.out.println(file.isDirectory());//false\r\n```\r\n\r\nRenaming a file\r\n```\r\nFile fileWithNewName = new File(\"NewFileName.txt\");\r\nfile.renameTo(fileWithNewName);\r\n//There is no method file.renameTo(\"NewFileName.txt\");\r\n```\r\n#### File Class - Directory\r\nA File class in Java represents a file and directory.\r\n```\r\nFile directory = new File(\"src/com/rithus\");\r\n```\r\n\r\nPrint full directory path\r\n```\r\nSystem.out.println(directory.getAbsolutePath());\r\nSystem.out.println(directory.isDirectory());//true\r\n```\r\n\r\nThis does not create the actual file.\r\n```\r\nFile fileInDir = new File(directory,\"NewFileInDirectory.txt\");\r\n```\r\n\r\nActual file is created when we invoke createNewFile method.\r\n```\r\nSystem.out.println(fileInDir.createNewFile()); //true - First Time\r\n```\r\n\r\nPrint the files and directories present in the folder.\r\n```\r\nSystem.out.println(Arrays.toString(directory.list()));\r\n```\r\n#### Creating a directory\r\n```\r\nFile newDirectory = new File(\"newfolder\");\r\nSystem.out.println(newDirectory.mkdir());//true - First Time\r\n```\r\n#### Creating a file in a new directory\r\n```\r\nFile notExistingDirectory = new File(\"notexisting\");\r\nFile newFile = new File(notExistingDirectory,\"newFile\");\r\n\r\n//Will throw Exception if uncommented: No such file or directory\r\n//newFile.createNewFile();\r\n\r\nSystem.out.println(newDirectory.mkdir());//true - First Time\r\n```\r\n#### Read and write from a File\r\nImplementations of Writer and Reader abstract classes help us to write and read (content of) files.\r\nWriter methods - flush, close, append (text)\r\nReader methods - read, close (NO FLUSH) \r\nWriter implementations - FileWriter,BufferedWriter,PrintWriter\r\nReader implementations - FileReader,BufferedReader\r\n### FileWriter and FileReader\r\n- FileWriter and FileReader provide basic file writing and reading operations. Let's  write an example to write and read from a file using FileReader and FileWriter.\r\n\r\n#### FileWriter Class\r\nWe can write to a file using FileWriter class.\r\n#### Write a string to a file using FileWriter\r\n```\r\n//FileWriter helps to write stuff into the file\r\nFileWriter fileWriter = new FileWriter(file);\r\nfileWriter.write(\"How are you doing?\");\r\n//Always flush before close. Writing to file uses Buffering.\r\nfileWriter.flush();\r\nfileWriter.close();\r\n```\r\n#### FileWriter Constructors\r\nFileWriter Constructors can accept file(File) or the path to file (String) as argument. When a writer object is created, it creates the file - if it does not exist. \r\n```\r\nFileWriter fileWriter2 = new FileWriter(\"FileName.txt\");\r\nfileWriter2.write(\"How are you doing Buddy?\");\r\n//Always flush before close. Writing to file uses Buffering.\r\nfileWriter2.flush();\r\nfileWriter2.close();\r\n```\r\n#### FileReader Class\r\nFile Reader can be used to read entire content from a file at one go.\r\n#### Read from file using FileReader\r\n```\r\nFileReader fileReader = new FileReader(file);\r\nchar[] temp = new char[25];\r\n\r\n//fileReader reads entire file and stores it into temp\r\nSystem.out.println(fileReader.read(temp));//18 - No of characters Read from file\r\n\r\nSystem.out.println(Arrays.toString(temp));//output below\r\n//[H, o, w,  , a, r, e,  , y, o, u,  , d, o, i, n, g, ?, , , , , ,]\r\n\r\nfileReader.close();//Always close anything you opened:)\r\n```\r\n#### FileReader Constructors\r\nFileReader constructors can accept file(File) or the path to file (String) as argument.\r\n```\r\nFileReader fileReader2 = new FileReader(\"FileName.txt\");\r\nSystem.out.println(fileReader2.read(temp));//24\r\nSystem.out.println(Arrays.toString(temp));//output below\r\n```\r\n\r\n### BufferedWriter and BufferedReader\r\n- BufferedWriter and BufferedReader provide better buffering in addition to basic file writing and reading operations. For example, instead of reading the entire file, we can read a file line by line.  Let's  write an example to write and read from a file using FileReader and FileWriter.\r\n\r\n#### BufferedWriter Class\r\nBufferedWriter class helps writing to a class with better buffering than FileWriter.\r\n#### BufferedWriter Constructors\r\nBufferedWriter Constructors only accept another Writer as argument\r\n```\r\nFileWriter fileWriter3 = new FileWriter(\"BufferedFileName.txt\");\r\nBufferedWriter bufferedWriter = new BufferedWriter(fileWriter3); \r\n```\r\n#### Using BufferedWriter class\r\n```\r\nbufferedWriter.write(\"How are you doing Buddy?\");\r\nbufferedWriter.newLine();\r\nbufferedWriter.write(\"I'm Doing Fine\");\r\n//Always flush before close. Writing to file uses Buffering.\r\nbufferedWriter.flush();\r\nbufferedWriter.close();\r\nfileWriter3.close();\r\n```\r\n#### BufferedReader Class\r\nBufferedReader helps to read the file line by line\r\n#### BufferedReader Constructors\r\nBufferedReader Constructors only accept another Reader as argument.\r\n```\r\nFileReader fileReader3 = new FileReader(\"BufferedFileName.txt\");\r\nBufferedReader bufferedReader = new BufferedReader(fileReader3);\r\n```\r\n#### BufferedReader , Reading a file\r\n```\r\nString line;\r\n//readLine returns null when reading the file is completed.\r\nwhile((line=bufferedReader.readLine()) != null){\r\n    System.out.println(line);\r\n}\r\n```\r\n### PrintWriter\r\n- PrintWriter provides advanced methods to write formatted text to the file. It supports printf function.\r\n\r\n#### PrintWriter constructors \r\nPrintWriter constructors supports varied kinds of arguments , File, String (File Path) and Writer.\r\n```\r\nPrintWriter printWriter = new PrintWriter(\"PrintWriterFileName.txt\");\r\n```\r\n#### PrintWriter , Write to a file\r\nOther than write function you can use format, printf, print, println functions to write to PrintWriter file.\r\n```\r\n//writes \"My Name\" to the file\r\nprintWriter.format(\"%15s\", \"My Name\");\r\n\r\nprintWriter.println(); //New Line\r\nprintWriter.println(\"Some Text\");\r\n\r\n//writes \"Formatted Number: 4.50000\" to the file\r\nprintWriter.printf(\"Formatted Number: %5.5f\", 4.5);\r\nprintWriter.flush();//Always flush a writer\r\nprintWriter.close();\r\n```\r\n#### Reading the file created using BufferedReader\r\n```\r\nFileReader fileReader4 = new FileReader(\"PrintWriterFileName.txt\");\r\nBufferedReader bufferedReader2 = new BufferedReader(fileReader4);\r\n\r\nString line2;\r\n//readLine returns null when reading the file is completed.\r\nwhile((line2=bufferedReader2.readLine()) != null){\r\n    System.out.println(line2);\r\n}\r\n```\r\n### Serialization\r\n- Serialization helps us to save and retrieve the state of an object.\r\n\r\n#### Serialization and De-Serialization - Important methods\r\nSerialization => Convert object state to some internal object representation.\r\nDe-Serialization => The reverse. Convert internal representation to object.\r\n\r\nTwo important methods\r\n1.ObjectOutputStream.writeObject() // serialize and write to file\r\n2.ObjectInputStream.readObject() // read from file and deserialize\r\n\r\n#### Implementing Serializable Interface\r\nTo serialize an object it should implement Serializable interface. In the example below, Rectangle class implements Serializable interface. Note that Serializable interface does not declare any methods to be implemented.\r\n```\r\nclass Rectangle implements Serializable {\r\n    public Rectangle(int length, int breadth) {\r\nthis.length = length;\r\nthis.breadth = breadth;\r\narea = length * breadth;\r\n    }\r\n\r\n    int length;\r\n    int breadth;\r\n    int area;\r\n}\r\n```\r\n#### Serializing an object - Example\r\nBelow example shows how an instance of an object can be serialized. We are creating a new Rectangle object and serializing it to a file Rectangle.ser.\r\n\r\n```\r\nFileOutputStream fileStream = new FileOutputStream(\"Rectangle.ser\");\r\nObjectOutputStream objectStream = new ObjectOutputStream(fileStream);\r\nobjectStream.writeObject(new Rectangle(5, 6));\r\nobjectStream.close();\r\n```\r\n#### De-serializing an object , Example\r\nBelow example show how a object can be deserialized from a serialized file. A rectangle object is deserialized from the file Rectangle.ser\r\n\r\n```\r\nFileInputStream fileInputStream = new FileInputStream(\"Rectangle.ser\");\r\nObjectInputStream objectInputStream = new ObjectInputStream(\r\nfileInputStream);\r\nRectangle rectangle = (Rectangle) objectInputStream.readObject();\r\nobjectInputStream.close();\r\nSystem.out.println(rectangle.length);// 5\r\nSystem.out.println(rectangle.breadth);// 6\r\nSystem.out.println(rectangle.area);// 30\r\n```\r\n#### Serialization , Transient variables\r\nArea in the previous example is a calculated value. It is unnecessary to serialize and deserialize. We can calculate it when needed. In this situation, we can make the variable transient. Transient variables are not serialized. (transient int area;)\r\n\r\n```\r\n//Modified Rectangle class\r\n\r\nclass Rectangle implements Serializable {\r\n    public Rectangle(int length, int breadth) {\r\nthis.length = length;\r\nthis.breadth = breadth;\r\narea = length * breadth;\r\n    }\r\n\r\n    int length;\r\n    int breadth;\r\n    transient int area;\r\n}\r\n```\r\n\r\nIf you run the program again, you would get following output\r\n\r\n```\r\nSystem.out.println(rectangle.length);// 5\r\nSystem.out.println(rectangle.breadth);// 6\r\nSystem.out.println(rectangle.area);// 0\r\n```\r\n\r\nNote that the value of rectangle.area is set to 0. Variable area is marked transient. So, it is not stored into the serialized file. And when de-serialization happens area value is set to default value i.e. 0.\r\n#### Serialization , readObject method\r\nWe need to recalculate the area when the rectangle object is deserialized. This can be achieved by adding readObject method to Rectangle class. In addition to whatever java does usually while deserializing, we can add custom code for the object.\r\n```\r\n    private void readObject(ObjectInputStream is) throws IOException,\r\n    ClassNotFoundException {\r\n// Do whatever java does usually when de-serialization is called\r\nis.defaultReadObject();\r\n// In addition, calculate area also\r\narea = this.length * this.breadth;\r\n    }\r\n```\r\n\r\nWhen an object of Rectangle class is de-serialized, Java invokes the readObject method. The area is recalculated in this method. If we run the program again, we get the calculated area value back. Remember that area is not part of the serialized file. It is re-calculated in the readObject method.\r\n\r\n```\r\nSystem.out.println(rectangle.length);// 5\r\nSystem.out.println(rectangle.breadth);// 6\r\nSystem.out.println(rectangle.area);// 30\r\n```\r\n#### Serialization , writeObject method\r\n\r\nWe can also write custom code when serializing the object by adding the writeObject method to Rectange class. writeObject method accepts an ObjectOutputStream as input parameter. To the writeObject method we can add the custom code that we want to run during Serialization.\r\n\r\n```\r\n    private void writeObject(ObjectOutputStream os) throws IOException {\r\n//Do whatever java does usually when serialization is called\r\nos.defaultWriteObject();\r\n    }\r\n```\r\n\r\nIf you run the above program again, you would get following output\r\n```\r\nSystem.out.println(rectangle.length);//5\r\nSystem.out.println(rectangle.breadth);//6\r\nSystem.out.println(rectangle.area);//30\r\n```\r\n#### Serializing an Object chain\r\nObjects of one class might contain objects of other classes. When serializing and de-serializing, we might need to serialize and de-serialize entire object chain. Look at the class below. An object of class House contains an object of class Wall.\r\n\r\n```\r\nclass House implements Serializable {\r\n    public House(int number) {\r\nsuper();\r\nthis.number = number;\r\n    }\r\n\r\n\r\n    Wall wall;\r\n    int number;\r\n}\r\n\r\nclass Wall{\r\n    int length;\r\n    int breadth;\r\n    int color;\r\n}\r\n```\r\n\r\nHouse implements Serializable where Wall doesn't.\r\n\r\nLet's run this example program:\r\n```\r\npublic class SerializationExamples2 {\r\n    public static void main(String[] args)\r\n    throws IOException {\r\n\r\nFileOutputStream fileStream = new FileOutputStream(\r\n\"House.ser\");\r\nObjectOutputStream objectStream = new ObjectOutputStream(\r\nfileStream);\r\nHouse house = new House(10);\r\nhouse.wall = new Wall();\r\n//Exception in thread \"main\" java.io.NotSerializableException: \r\n//com.in28minutes.serialization.Wall\r\nobjectStream.writeObject(house);\r\nobjectStream.close();\r\n    }\r\n}\r\n\r\n//Output:\r\n//Exception in thread \"main\" java.io.NotSerializableException: com.in28minutes.serialization.Wall\r\n//    at java.io.ObjectOutputStream.writeObject0(Unknown Source)\r\n//    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)\r\n```\r\n\r\nThis is because Wall is not serializable. Two solutions are possible.\r\nMake Wall transient => wall will not be serialized. This causes the wall object state to be lost.\r\nMake Wall implement Serializable => wall object will also be serialized and the state of wall object along with the house will be stored.\r\n#### Serialization Program 1: Make Wall transient\r\n```\r\nclass House implements Serializable {\r\n    public House(int number) {\r\nsuper();\r\nthis.number = number;\r\n    }\r\n\r\n    transient Wall wall;\r\n    int number;\r\n}\r\n```\r\n#### Serialization Program 2: Make Wall implement Serializable\r\n```\r\nclass Wall implements Serializable {\r\n    int length;\r\n    int breadth;\r\n    int color;\r\n}\r\n```\r\n\r\nWith both these programs, earlier main method would run without throwing an exception. \r\n\r\nIf you try de-serializing, In Example2, state of wall object is retained whereas in Example1, state of wall object is lost.\r\n#### Serialization and Initialization\r\nWhen a class is Serialized, initialization (constructor's, initializer's) does not take place. The state of the object is retained as it is. \r\n#### Serialization and inheritance\r\nHowever in the case of inheritance ( a sub class and super class relationship), interesting things happen.\r\nLet's consider the example code below:\r\n\r\nHero class extends Actor and Hero class implements Serializable. However, Actor class does not implement Serializable.\r\n```\r\nclass Actor {\r\n    String name;\r\n\r\n    public Actor(String name) {\r\nsuper();\r\nthis.name = name;\r\n    }\r\n\r\n    Actor() {\r\nname = \"Default\";\r\n    }\r\n}\r\n\r\nclass Hero extends Actor implements Serializable {\r\n    String danceType;\r\n\r\n    public Hero(String name, String danceType) {\r\nsuper(name);\r\nthis.danceType = danceType;\r\n    }\r\n\r\n    Hero() {\r\ndanceType = \"Default\";\r\n    }\r\n}\r\n```\r\n\r\nLet's run the code below:\r\n```\r\nFileOutputStream fileStream = new FileOutputStream(\"Hero.ser\");\r\nObjectOutputStream objectStream = new ObjectOutputStream(fileStream);\r\n\r\nHero hero = new Hero(\"Hero1\", \"Ganganam\");\r\n\r\n// Before -> DanceType:Ganganam Name:Hero1\r\nSystem.out.println(\"Before -> DanceType:\" + hero.danceType + \" Name:\"\r\n+ hero.name);\r\n\r\nobjectStream.writeObject(hero);\r\nobjectStream.close();\r\n\r\nFileInputStream fileInputStream = new FileInputStream(\"Hero.ser\");\r\nObjectInputStream objectInputStream = new ObjectInputStream(\r\nfileInputStream);\r\nhero = (Hero) objectInputStream.readObject();\r\nobjectInputStream.close();\r\n\r\n// After -> DanceType:Ganganam Name:Default\r\nSystem.out.println(\"After -> DanceType:\" + hero.danceType + \" Name:\"\r\n+ hero.name);\r\n```\r\n\r\nCode executes successfully but after de-serialization, the values of super class instance variables are not retained. They are set to their initial values. \r\nWhen subclass is serializable and superclass is not, the state of subclass variables is retained. However, for the super class, initialization (constructors and initializers) happens again.\r\n#### Serialization and Static Variables\r\nStatic Variables are not part of the object. They are not serialized.\r\n### Threads\r\n- Threads allow Java code to run in parallel. Let's first understand the need for threading and then look into how to create a thread and what is synchronization?\r\n\r\n#### Need for Threads\r\nWe are creating a Cricket Statistics Application. Let's say the steps involved in the application are\r\nSTEP I: Download and Store Bowling Statistics => 60 Minutes\r\nSTEP II: Download and Store Batting Statistics => 60 Minutes\r\nSTEP III: Download and Store Fielding Statistics => 15 Minutes\r\nSTEP IV: Merge and Analyze => 25 Minutes\r\nSteps I, II and III are independent and can be run in parallel to each other. Run individually this program takes 160 minutes.  We would want to run this program in lesser time. Threads can be a solution to this problem. Threads allow us to run STEP I, II and III in parallel and run Step IV when all Steps I, II and III are completed.\r\n#### Need for Threads Example\r\nBelow example shows the way we would write code usually , without using Threads. \r\n```\r\nThreadExamples example = new ThreadExamples();\r\nexample.downloadAndStoreBattingStatistics();\r\nexample.downloadAndStoreBowlingStatistics();\r\nexample.downloadAndStoreFieldingStatistics();\r\n\r\nexample.mergeAndAnalyze();\r\n```\r\n\r\ndownloadAndStoreBowlingStatistics starts only after downloadAndStoreBattingStatistics completes execution. downloadAndStoreFieldingStatistics starts only after downloadAndStoreBowlingStatistics completes execution. What if I want to run them in parallel without waiting for the others to complete?\r\nThis is where Threads come into picture.\r\n#### Creating a Thread Class\r\nCreating a Thread class in Java can be done in two ways. Extending Thread class and implementing Runnable interface. Let's create the BattingStatisticsThread extending Thread class and BowlingStatisticsThread implementing Runnable interface.\r\n#### Creating a Thread By Extending Thread class\r\nThread class can be created by extending Thread class and implementing the public void run() method.\r\nLook at the example below: A dummy implementation for BattingStatistics is provided which counts from 1 to 1000.\r\n```\r\nclass BattingStatisticsThread extends Thread {\r\n    //run method without parameters\r\n    public void run() {\r\nfor (int i = 0; i < 1000; i++)\r\n    System.out\r\n    .println(\"Running Batting Statistics Thread \"\r\n    + i);\r\n    }\r\n}\r\n```\r\n#### Creating a Thread by Implementing Runnable interface\r\nThread class can also be created by implementing Runnable interface and implementing the method declared in Runnable interface Òpublic void run()Ó. Example below shows the Batting Statistics Thread implemented by implementing Runnable interface.\r\n```\r\nclass BowlingStatisticsThread implements Runnable {\r\n    //run method without parameters\r\n    public void run() {\r\nfor (int i = 0; i < 1000; i++)\r\n    System.out\r\n    .println(\"Running Bowling Statistics Thread \"\r\n    + i);\r\n    }\r\n}\r\n```\r\n#### Running a Thread\r\nRunning a Thread in Java is slightly different based on the approach used to create the thread.\r\n#### Thread created Extending Thread class\r\nWhen using inheritance, An object of the thread needs be created and start() method on the thread needs to be called. Remember that the method that needs to be called is not run() but it is start().\r\n```\r\nBattingStatisticsThread battingThread1 = new BattingStatisticsThread();\r\nbattingThread1.start();\r\n```\r\n#### Thread created implementing RunnableInterface. \r\nThree steps involved.\r\n1. Create an object of the BowlingStatisticsThread(class implementing Runnable).\r\n2. Create a Thread object with the earlier object as constructor argument.\r\n3. Call the start method on the thread.\r\n```\r\nBowlingStatisticsThread battingInterfaceImpl = new BowlingStatisticsThread();\r\nThread battingThread2 = new Thread(\r\nbattingInterfaceImpl);\r\nbattingThread2.start();\r\n```\r\n#### Thread Example , Complete Program\r\nLet's consider the complete example using all the snippets of code created above. \r\n```\r\npublic class ThreadExamples {\r\n    public static void main(String[] args) {\r\nclass BattingStatisticsThread extends Thread {\r\n    // run method without parameters\r\n    public void run() {\r\nfor (int i = 0; i < 1000; i++)\r\n    System.out.println(\"Running Batting Statistics Thread \" + i);\r\n    }\r\n}\r\n\r\nclass BowlingStatisticsThread implements Runnable {\r\n    // run method without parameters\r\n    public void run() {\r\nfor (int i = 0; i < 1000; i++)\r\n    System.out.println(\"Running Bowling Statistics Thread \" + i);\r\n    }\r\n}\r\n\r\nBattingStatisticsThread battingThread1 = new BattingStatisticsThread();\r\nbattingThread1.start();\r\n\r\nBowlingStatisticsThread battingInterfaceImpl = new BowlingStatisticsThread();\r\nThread battingThread2 = new Thread(battingInterfaceImpl);\r\nbattingThread2.start();\r\n\r\n    }\r\n\r\n}\r\n```\r\nOutput:\r\n```\r\nRunning Batting Statistics Thread 0\r\nRunning Batting Statistics Thread 1\r\n..\r\n..\r\nRunning Batting Statistics Thread 10\r\nRunning Bowling Statistics Thread 0\r\n..\r\n..\r\nRunning Bowling Statistics Thread 948\r\nRunning Bowling Statistics Thread 949\r\nRunning Batting Statistics Thread 11\r\nRunning Batting Statistics Thread 12\r\n..\r\n..\r\nRunning Batting Statistics Thread 383\r\nRunning Batting Statistics Thread 384\r\nRunning Bowling Statistics Thread 950\r\nRunning Bowling Statistics Thread 951\r\n..\r\nRunning Bowling Statistics Thread 998\r\nRunning Bowling Statistics Thread 999\r\nRunning Batting Statistics Thread 385\r\n..\r\nRunning Batting Statistics Thread 998\r\nRunning Batting Statistics Thread 999 \r\n```\r\n#### Discussion about Thread Example\r\nAbove output shows sample execution of the thread. The output will not be the same with every run.\r\nWe can notice that Batting Statistics Thread and the Bowling Statistics Threads are alternating in execution.  Batting Statistics Thread runs upto 10, then Bowling Statistics Thread runs upto 949, Batting Statistics Thread picks up next and runs up to 384 and so on. There is no usual set pattern when Threads run (especially when they have same priority , more about this later..). \r\nJVM decides which Thread to run at which time. If a Thread is waiting for user input or a network connection, JVM runs the other waiting Threads.\r\n#### Thread Synchronization\r\nSince Threads run in parallel, a new problem arises. i.e. What if thread1 modifies data which is being accessed by thread2? How do we ensure that different threads don't leave the system in an inconsistent state? This problem is usually called Thread Synchronization Problem.\r\nLet's first look at an example where this problem can occur.\r\n#### Example Program:\r\nConsider the SpreadSheet class below. It consists of three cells and also a method setAndGetSum which sets the values into the cell and sums them up.\r\n```\r\nclass SpreadSheet {\r\n    int cell1, cell2, cell3;\r\n\r\n    int setandGetSum(int a1, int a2, int a3) {\r\ncell1 = a1;\r\nsleepForSomeTime();\r\ncell2 = a2;\r\nsleepForSomeTime();\r\ncell3 = a3;\r\nsleepForSomeTime();\r\nreturn cell1 + cell2 + cell3;\r\n    }\r\n\r\n    void sleepForSomeTime() {\r\ntry {\r\n    Thread.sleep(10 * (int) (Math.random() * 100));\r\n} catch (InterruptedException e) {\r\n    e.printStackTrace();\r\n}\r\n    }\r\n}\r\n```\r\n#### Serial Run\r\nLet's first run the above example in a serial way and see what the output would be.\r\n```\r\npublic static void main(String[] args) {\r\n    SpreadSheet spreadSheet = new SpreadSheet();\r\n    for (int i = 0; i < 4; i++) {\r\nSystem.out.print(spreadSheet.setandGetSum(i, i * 2, i * 3) + \" \");\r\n    }\r\n}\r\n//Output - 0 6 12 18\r\n```\r\nOutput would contain a multiple of 6 always because we are calling with i, i*2 and i*3 and summing up. So, the result should generally be i*6 with i running from 0 to 3.\r\n#### Example Program using Threads \r\nLet's now run the SpreadSheet class in a Thread. Example Code below:\r\n```\r\npublic class ThreadExampleSynchronized implements Runnable {\r\n\r\n    SpreadSheet spreadSheet = new SpreadSheet();\r\n\r\n    public void run() {\r\nfor (int i = 0; i < 4; i++) {\r\n    System.out.print(\r\n    spreadSheet.setandGetSum(i,i * 2, i * 3)\r\n    + \" \");\r\n}\r\n    }\r\n\r\n    public static void main(String[] args) {\r\nThreadExampleSynchronized r = new ThreadExampleSynchronized();\r\nThread one = new Thread(r);\r\nThread two = new Thread(r);\r\none.start();\r\ntwo.start();\r\n    }\r\n}\r\n```\r\n\r\nWe are creating 2 instances of the Thread using the interface , one and two. And start method is invoked to run the thread. Both threads share the instance of SpreadSheet class , spreadsheet.\r\nOutput\r\n```\r\nFIRST RUN    : 0 1 6 9 12 15 18 18\r\nSECOND RUN    : 0 3 6 6 12 15 18 18\r\nTHIRD RUN    : 0 3 6 9 12 15 18 18\r\n```\r\nOutput Discussion\r\nWhat we see is that different runs have different results. That's expected with threads. What is not expected is to see numbers like 1, 9, 15 and 3 in the output. We are expecting to see multiples of 6 in the output(as in the earlier serial run) but we see numbers which are not multiples of 6. Why is this happening?\r\nThis is a result of having two threads run in parallel without synchronization. Consider the code in the setAndGetSum method.\r\n```\r\nint setandGetSum(int a1, int a2, int a3) {\r\n    cell1 = a1;\r\n    sleepForSomeTime();\r\n    cell2 = a2;\r\n    sleepForSomeTime();\r\n    cell3 = a3;\r\n    sleepForSomeTime();\r\n    return cell1 + cell2 + cell3;\r\n}\r\n```\r\n\r\nAfter setting the value to each cell, there is a call for the Thread to sleep for some time. After Thread 1 sets the value of cell1, it goes to Sleep. So, Thread2 starts executing. If Thread 2 is executing Òreturn cell1 + cell2 + cell3;Ó, it uses cell1 value set by Thread 1 and cell2 and cell3 values set by Thread 2. This results in the unexpected results that we see when the method is run in parallel. What is explained is one possible scenario. There are several such scenarios possible.\r\nThe way you can prevent multiple threads from executing the same method is by using the synchronized keyword on the method. If a method is marked synchronized, a different thread gets access to the method only when there is no other thread currently executing the method.\r\nLet's mark the method as synchronized:\r\n```\r\nsynchronized int setandGetSum(int a1, int a2, int a3) {\r\n    cell1 = a1;\r\n    sleepForSomeTime();\r\n    cell2 = a2;\r\n    sleepForSomeTime();\r\n    cell3 = a3;\r\n    sleepForSomeTime();\r\n    return cell1 + cell2 + cell3;\r\n}\r\n```\r\n\r\nOutput of the program now is Ò0 0 6 6 12 12 18 18Ó. This is expected output , all numbers are multiples of 6.\r\n#### Threads & Synchronized Keyword\r\nA method or part of the method can be marked as synchronized. JVM will ensure that there is only thread running the synchronized part of code at any time.\r\nHowever, thread synchronization is not without consequences. There would be a performance impact as the rest of threads wait for the current thread executing a synchronized block. So, as little code as possible should be marked as synchronized.\r\n#### Synchronized method Example\r\n```\r\n    synchronized void synchronizedExample1() {\r\n//All code goes here..\r\n    }\r\n```\r\n#### Synchronized block Example\r\nAll code which goes into the block is synchronized on the current object.\r\n```\r\n    void synchronizedExample2() {\r\nsynchronized (this){\r\n//All code goes here..\r\n}\r\n    }\r\n```\r\n####  Synchronized static method Example\r\n```\r\n    synchronized static int getCount(){\r\nreturn count;\r\n    }\r\n```\r\n#### Static synchronized block Example\r\nStatic blocks are synchronized on the class.\r\n```\r\n    static int getCount2(){\r\nsynchronized (SynchronizedSyntaxExample.class) {\r\n    return count;\r\n}\r\n    }\r\n```\r\n#### Static and non static synchronized methods and blocks\r\nStatic methods and block are synchronized on the class. Instance methods and blocks are synchronized on the instance of the class i.e. an object of the class. Static synchronized methods and instance synchronized methods don't affect each other. This is because they are synchronized on two different things.\r\n#### States of a Thread\r\nDifferent states that a thread can be in are defined the class State.\r\n- NEW;\r\n- RUNNABLE;\r\n- RUNNING;\r\n- BLOCKED/WAITING;\r\n- TERMINATED/DEAD;\r\nLet's consider the example that we discussed earlier.\r\n#### Example Program\r\n```\r\nLINE 1: BattingStatisticsThread battingThread1 = new BattingStatisticsThread();\r\nLINE 2: battingThread1.start();\r\n\r\nLINE 3: BowlingStatisticsThread battingInterfaceImpl = new BowlingStatisticsThread();\r\nLINE 4: Thread battingThread2 = new Thread(battingInterfaceImpl);\r\nLINE 5:battingThread2.start();\r\n//Output - Running Batting Statistics Thread 0\r\nRunning Batting Statistics Thread 1\r\n..\r\n..\r\nRunning Batting Statistics Thread 10\r\nRunning Bowling Statistics Thread 0\r\n..\r\n..\r\nRunning Bowling Statistics Thread 948\r\nRunning Bowling Statistics Thread 949\r\nRunning Batting Statistics Thread 11\r\nRunning Batting Statistics Thread 12\r\n..\r\n..\r\nRunning Batting Statistics Thread 383\r\nRunning Batting Statistics Thread 384\r\nRunning Bowling Statistics Thread 950\r\nRunning Bowling Statistics Thread 951\r\n..\r\nRunning Bowling Statistics Thread 998\r\nRunning Bowling Statistics Thread 999\r\nRunning Batting Statistics Thread 385\r\n..\r\nRunning Batting Statistics Thread 998\r\nRunning Batting Statistics Thread 999 \r\n```\r\n#### States of a Thread - Examples\r\nA thread is in NEW state when an object of the thread is created but the start method is not yet called. At the end of line 1, battingThread1 is in NEW state.\r\nA thread is in RUNNABLE state when it is eligible to run, but not running yet. (A number of Threads can be in RUNNABLE state. Scheduler selects which Thread to move to RUNNING state). In the above example, sometimes the Batting Statistics thread is running and at other time, the Bowling Statistics Thread is running. When Batting Statistics thread is Running, the Bowling Statistics thread is ready to run. It's just that the scheduler picked Batting Statistics thread to run at that instance and vice-versa.  When Batting Statistics thread is Running, the Bowling Statistics Thread is in Runnable state (Note that the Bowling Statistics Thread is not waiting for anything except for the Scheduler to pick it up and run it).\r\nA thread is RUNNING state when it's the one that is currently , what else to say, Running.\r\nA thread is in BLOCKED/WAITING/SLEEPING state when it is not eligible to be run by the Scheduler. Thread is alive but is waiting for something. An example can be a Synchronized block. If Thread1 enters synchronized block, it blocks all the other threads from entering synchronized code on the same instance or class. All other threads are said to be in Blocked state.\r\nA thread is in DEAD/TERMINATED state when it has completed its execution. Once a thread enters dead state, it cannot be made active again.\r\n#### Thread Priority\r\nScheduler can be requested to allot more CPU to a thread by increasing the threads priority. Each thread in Java is assigned a default Priority 5. This priority can be increased or decreased (Range 1 to 10).\r\nIf two threads are waiting, the scheduler picks the thread with highest priority to be run. If all threads have equal priority, the scheduler then picks one of them randomly. Design programs so that they don't depend on priority.\r\n#### Thread Priority Example\r\nConsider the thread example declared below:\r\n```\r\nclass ThreadExample extends Thread {\r\n    public void run() {\r\nfor (int i = 0; i < 1000; i++)\r\n    System.out\r\n    .println( this.getName() + \" Running \"\r\n    + i);\r\n    }\r\n}\r\n```\r\n\r\nPriority of thread can be changed by invoking setPriority method on the thread.\r\n```\r\nThreadExample thread1 = new ThreadExample();\r\nthread1.setPriority(8);\r\n```\r\n\r\nJava also provides predefined constants Thread.MAX_PRIORITY(10), Thread.MIN_PRIORITY(1), Thread.NORM_PRIORITY(5) which can be used to assign priority to a thread.\r\n#### Thread Join method\r\nJoin method is an instance method on the Thread class. Let's see a small example to understand what join method does.\r\nLet's consider the thread's declared below: thread2, thread3, thread4\r\n```\r\nThreadExample thread2 = new ThreadExample();\r\nThreadExample thread3 = new ThreadExample();\r\nThreadExample thread4 = new ThreadExample();\r\n```\r\n\r\nLet's say we would want to run thread2 and thread3 in parallel but thread4 can only run when thread3 is finished. This can be achieved using join method.\r\n#### Join method example\r\nLook at the example code below:\r\n```\r\nthread3.start();\r\nthread2.start();\r\nthread3.join();//wait for thread 3 to complete\r\nSystem.out.println(\"Thread3 is completed.\");\r\nthread4.start();\r\n```\r\n\r\nthread3.join() method call force the execution of main method to stop until thread3 completes execution. After that, thread4.start() method is invoked, putting thread4 into a Runnable State.\r\n#### Overloaded Join method\r\nJoin method also has an overloaded method accepting time in milliseconds as a parameter. \r\n```\r\nthread4.join(2000);\r\n```\r\nIn above example, main method thread would wait for 2000 ms or the end of execution of thread4, whichever is minimum.\r\n#### Thread , Static methods\r\n#### Thread yield method\r\nYield is a static method in the Thread class. It is like a thread saying \" I have enough time in the limelight. Can some other thread run next?\". \r\nA call to yield method changes the state of thread from RUNNING to RUNNABLE. However, the scheduler might pick up the same thread to run again, especially if it is the thread with highest priority.\r\nSummary is yield method is a request from a thread to go to Runnable state. However, the scheduler can immediately put the thread back to RUNNING state.\r\n#### Thread sleep method\r\nsleep is a static method in Thread class. sleep method can throw a InterruptedException. sleep method causes the thread in execution to go to sleep for specified number of milliseconds.\r\n#### Thread and Deadlocks\r\nLet's consider a situation where thread1 is waiting for thread2 ( thread1 needs an object whose synchronized code is being executed by thread1) and thread2 is waiting for thread1. This situation is called a Deadlock. In a Deadlock situation, both these threads would wait for one another for ever.\r\n#### Deadlock Example\r\nConsider the example classes below:  Resource represents any resource that you need access to. A network connection, database connection etc. Operation represents an operation that can be done on these resources. Let's say that Operation need two resources, resource1 and resource2 and offer two operations method1 and method2. Look at the program below:\r\n```\r\nclass Resource {\r\n}\r\n\r\nclass SomeOperation {\r\n    Resource resource1 = new Resource();\r\n    Resource resource2 = new Resource();\r\n\r\n    void method1() throws InterruptedException {\r\nsynchronized (resource1) {\r\n    Thread.sleep(1000);\r\n    //code using resource1\r\n    synchronized (resource2) {\r\n//code using resource2\r\n    }\r\n}\r\n    }\r\n\r\n    void method2() throws InterruptedException {\r\nSystem.out.println(Thread.currentThread().getName()\r\n+ \"is in method2\");\r\nsynchronized (resource2) {\r\n    //code using resource2\r\n    Thread.sleep(1000);\r\n    synchronized (resource1) {\r\n//code using resource1\r\n    }\r\n}\r\n    }\r\n\r\n}\r\n```\r\n\r\nMethod1 executes some code on resource1 first and then executes some code on resource2. Method2 does the reverse. We use the sleep method call to simulate the fact that these operation could take some time to complete.\r\nLet's create two threads sharing the above operation using the code below: Threads one and two now share object operation.  The thread code runs both operations method1 and method2.\r\n```\r\npublic class ThreadDeadlock implements Runnable {\r\n\r\n    SomeOperation operation = new SomeOperation();\r\n\r\n    @Override\r\n    public void run() {\r\ntry {\r\n    operation.method1();\r\n    operation.method2();\r\n} catch (InterruptedException e) {\r\n    e.printStackTrace();\r\n}\r\n    }\r\n\r\n    public static void main(String[] args) {\r\nThreadDeadlock r = new ThreadDeadlock();\r\nThread one = new Thread(r);\r\nThread two = new Thread(r);\r\none.start();\r\ntwo.start();\r\n    }\r\n}\r\n```\r\n\r\nWhen executed this program just hangs, because of a deadlock.\r\nTo make what is happening behind the screens more clear, Let's add in a few sysout's in the Operation class.\r\n```\r\nclass SomeOperation {\r\n    Resource resource1 = new Resource();\r\n    Resource resource2 = new Resource();\r\n\r\n    void method1() throws InterruptedException {\r\nsynchronized (resource1) {\r\n    System.out.println(\"Method1 - got resource1\");\r\n    Thread.sleep(1000);\r\n    //code using resource1\r\n    System.out.println(\"Method1 - waiting for resource2\");\r\n    synchronized (resource2) {\r\nSystem.out.println(\"Method1 - got resource2\");\r\n//code using resource2\r\n    }\r\n}\r\n    }\r\n\r\n    void method2() throws InterruptedException {\r\nsynchronized (resource2) {\r\n    System.out.println(\"Method2 - got resource2\");\r\n    //code using resource2\r\n    Thread.sleep(1000);\r\n    System.out.println(\"Method2 - waiting for resource1\");\r\n    synchronized (resource1) {\r\nSystem.out.println(\"Method2 - got resource1\");\r\n//code using resource1\r\n    }\r\n}\r\n    }\r\n\r\n}\r\n```\r\n#### Output:\r\n```\r\nMethod1 - got resource1\r\nMethod1 - waiting for resource2\r\nMethod1 - got resource2\r\nMethod1 - got resource1\r\nMethod2 - got resource2\r\nMethod1 - waiting for resource2\r\nMethod2 - waiting for resource1\r\nHANGSÉÉÉÉÉÉÉÉ\r\n```\r\nNow we have two threads waiting for resources held by one another. This results in a deadlock.\r\n#### Thread - wait, notify and notifyAll methods\r\nConsider the example below: Calculator thread calculates two values: Sum upto Million and Sum upto 10 Million. Main program uses the output of sum upto million.\r\n#### Example 1\r\n```\r\nclass Calculator extends Thread {\r\n    long sumUptoMillion;\r\n    long sumUptoTenMillion;\r\n    public void run() {\r\ncalculateSumUptoMillion();\r\ncalculateSumUptoTenMillion();\r\n    }\r\n    \r\n    private void calculateSumUptoMillion() {\r\nfor (int i = 0; i < 1000000; i++) {\r\n    sumUptoMillion += i;\r\n}\r\n    }\r\n    private void calculateSumUptoTenMillion() {\r\nfor (int i = 0; i < 10000000; i++) {\r\n    sumUptoTenMillion += i;\r\n}\r\n    }\r\n}\r\n\r\npublic class ThreadWaitAndNotify {\r\n    public static void main(String[] args) {\r\nCalculator thread = new Calculator();\r\nthread.start();\r\nSystem.out.println(thread.sumUptoMillion);\r\n    }\r\n}\r\n```\r\n#### Output\r\n```\r\n0\r\n```\r\nOutput printed is 0. This is because the thread has not finished calculating the value of sumUptoMillion when the main method prints the value to the output.\r\nWe have to find a way to stop the main method from running until sumUptoMillion is calculated. One option is to use the join method. But, join method would make the main method wait until both the operations (sumUptoMillion and sumUptoTenMillion) are completed. But, we want main method to wait only for sumUptoMillion. We can achieve this using wait and notify methods.\r\nwait and notify methods can only be used in a synchronized context.\r\n#### Example with wait and notify methods\r\n```\r\npackage com.in28minutes.threads;\r\n\r\nclass Calculator extends Thread {\r\n    long sumUptoMillion;\r\n    long sumUptoTenMillion;\r\n\r\n    public void run() {\r\nsynchronized (this) {\r\n    calculateSumUptoMillion();\r\n    notify();\r\n}\r\ncalculateSumUptoTenMillion();\r\n    }\r\n\r\n    private void calculateSumUptoMillion() {\r\nfor (int i = 0; i < 1000000; i++) {\r\n    sumUptoMillion += i;\r\n}\r\nSystem.out.println(\"Million done\");\r\n    }\r\n\r\n    private void calculateSumUptoTenMillion() {\r\nfor (int i = 0; i < 10000000; i++) {\r\n    sumUptoTenMillion += i;\r\n}\r\nSystem.out.println(\"Ten Million done\");\r\n    }\r\n}\r\n\r\npublic class ThreadWaitAndNotify {\r\n    public static void main(String[] args) throws InterruptedException {\r\nCalculator thread = new Calculator();\r\nsynchronized(thread){\r\n    thread.start();\r\n    thread.wait();\r\n}\r\nSystem.out.println(thread.sumUptoMillion);\r\n    }\r\n}\r\n```\r\n\r\n#### Output\r\n```\r\nMillion done\r\n499999500000\r\nTen Million done\r\n```\r\n#### Wait method example\r\nBelow snippet shows how wait is used in earlier program. wait method is defined in the Object class. This causes the thread to wait until it is notified.\r\n```\r\nsynchronized(thread){\r\n    thread.start();\r\n    thread.wait();\r\n}\r\n```\r\n#### Notify method example\r\nBelow snippet shows how notify is used in earlier program. notify method is defined in the Object class. This causes the object to notify other waiting threads.\r\n```\r\nsynchronized (this) {\r\ncalculateSumUptoMillion();\r\nnotify();\r\n    }\r\n```\r\n\r\nA combination of wait and notify methods make the main method to wait until the sum of million is calculated. However, not the main method does not wait for Sum of Ten Million to be calculated.\r\n#### notifyAll method\r\nIf more than one thread is waiting for an object, we can notify all the threads by using notifyAll method.\r\n```\r\nthread.notifyAll();\r\n```\r\n### Assert\r\n- Assertions are introduced in Java 1.4. They enable you to validate assumptions. If an assert fails (i.e. returns false), AssertionError is thrown (if assertions are enabled).  assert is a keyword in java since 1.4. Before 1.4, assert can be used as identifier.\r\n\r\n#### Assert Details\r\nTo compile code using 1.3 you can use the command below\r\njavac -source 1.3 OldCode.java => assert can be used as identifier\r\n  with -source 1.4,1.5,5,1.6,6 => assert cannot be used as identifier\r\n\r\nAssertions can easily be enabled and disabled. Assertions are disabled by default.\r\n#### Enabling Assertions\r\nEnable assertions: java -ea com.in28minutes.AssertExamples\r\n (OR) java -enableassertions com.in28minutes.AssertExamples\r\n#### Disable Assertions\r\nDisable assertions: java -da com.in28minutes.AssertExamples\r\n(OR) java -disableassertions com.in28minutes.AssertExamples\r\n#### Enable Assertions in specific packages\r\nSelectively enable assertions in a package only\r\njava -ea:com.rithus\r\n\r\nSelectively enable assertions in a package and its subpackages only\r\njava -ea:com.in28minutes...\r\n#### Enable assertions including system classes\r\njava -ea -esa\r\n#### Basic assert condition example\r\nBasic assert is shown in the example below\r\n```\r\nprivate int computerSimpleInterest(int principal,float interest,int years){\r\n    assert(principal>0);\r\n    return 100;\r\n}\r\n```\r\n#### Assert with debugging information: Example\r\nIf needed - debugging information can be added to an assert. Look at the example below.\r\n```\r\nprivate int computeCompoundInterest(int principal,float interest,int years){\r\n    //condition is always boolean\r\n    //second parameter can be anything that converts to a String.\r\n    assert(principal>0): \"principal is \" + principal;\r\n    return 100;\r\n}\r\n\r\npublic static void main(String[] args) {\r\n    AssertExamples examples = new AssertExamples();\r\n    System.out.println(examples.computerSimpleInterest(-1000,1.0f,5));\r\n}\r\n```\r\n#### Asserts - Not for validation\r\nAssertions should not be used to validate input data to a public method or command line argument. IllegalArgumentException would be a better option.\r\n\r\nIn public method, only use assertions to check for cases which are never supposed to happen.\r\n### Garbage Collection\r\n- Garbage Collection is a name given to automatic memory management in Java.  Aim of Garbage Collection is to Keep as much of heap available (free) for the program as possible. JVM removes objects on the heap which no longer have references from the heap.\r\n\r\n#### Garbage Collection Example\r\nLet's say the below method is called from a function.\r\n\r\n```\r\nvoid method(){\r\n    Calendar calendar = new GregorianCalendar(2000,10,30);\r\n    System.out.println(calendar);\r\n}\r\n```\r\n\r\nAn object of the class GregorianCalendar is created on the heap by the first line of the function with one reference variable calendar.\r\n\r\nAfter the function ends execution, the reference variable calendar is no longer valid. Hence, there are no references to the object created in the method.\r\n\r\nJVM recognizes this and removes the object from the heap. This is called Garbage Collection.\r\n#### When is Garbage Collection run?\r\nGarbage Collection runs at the whims and fancies of the JVM (it isn't as bad as that). Possible situations when Garbage Collection might run are \r\n1.when available memory on the heap is low\r\n2.when cpu is free\r\n#### Garbage Collection , Important Points\r\nProgrammatically, we can request (remember it's just a request - Not an order) JVM to run Garbage Collection by calling System.gc() method.\r\n\r\nJVM might throw an OutOfMemoryException when memory is full and no objects on the heap are eligible for garbage collection.\r\n\r\nfinalize() method on the objected is run before the object is removed from the heap from the garbage collector. We recommend not to write any code in finalize();\r\n### Initialization Blocks\r\n- Initialization Blocks - Code which runs when an object is created or a class is loaded\r\n\r\n#### Types of Initialization Blocks\r\nThere are two types of Initialization Blocks\r\nStatic Initializer: Code that runs when a class is loaded.\r\nInstance Initializer: Code that runs when a new object is created.\r\n\r\n#### Static Initializer\r\n\r\n```\r\npublic class InitializerExamples {\r\n    static int count;\r\n    int i;\r\n\r\n    static{\r\n//This is a static initializers. Run only when Class is first loaded.\r\n//Only static variables can be accessed\r\nSystem.out.println(\"Static Initializer\");\r\n//i = 6;//COMPILER ERROR\r\nSystem.out.println(\"Count when Static Initializer is run is \" + count);\r\n    }\r\n\r\n    public static void main(String[] args) {\r\nInitializerExamples example = new InitializerExamples();\r\nInitializerExamples example2 = new InitializerExamples();\r\nInitializerExamples example3 = new InitializerExamples();\r\n    }\r\n}\r\n```\r\n\r\nCode within static{ and } is called a static initializer. This is run only when class is first loaded. Only static variables can be accessed in a static initializer.\r\n#### Example Output\r\n```\r\nStatic Initializer\r\nCount when Static Initializer is run is 0\r\n```\r\n\r\nEven though three instances are created static initializer is run only once.\r\n#### Instance Initializer Block\r\nLet's look at an example\r\n```\r\npublic class InitializerExamples {\r\n    static int count;\r\n    int i;\r\n    {\r\n//This is an instance initializers. Run every time an object is created.\r\n//static and instance variables can be accessed\r\nSystem.out.println(\"Instance Initializer\");\r\ni = 6;\r\ncount = count + 1;\r\nSystem.out.println(\"Count when Instance Initializer is run is \" + count);\r\n    }\r\n\r\n    public static void main(String[] args) {\r\nInitializerExamples example = new InitializerExamples();\r\nInitializerExamples example1 = new InitializerExamples();\r\nInitializerExamples example2 = new InitializerExamples();\r\n    }\r\n\r\n}\r\n```\r\n\r\nCode within instance initializer is run every time an instance of the class is created.\r\n#### Example Output\r\n```\r\nInstance Initializer\r\nCount when Instance Initializer is run is 1\r\nInstance Initializer\r\nCount when Instance Initializer is run is 2\r\nInstance Initializer\r\nCount when Instance Initializer is run is 3\r\n```\r\n### Java Bean Conventions\r\n- When is a java class called a bean? Let's find an answer to this question.\r\n\r\n#### Java Bean Example\r\nConsider the code example below:\r\n```\r\npublic class JavaBeansStandards {    \r\n\r\nprivate String name;\r\nprivate boolean good;\r\n\r\npublic String getName() {\r\n    return name;\r\n}\r\n\r\npublic boolean isGood() {\r\n    return good;\r\n}\r\n\r\npublic void setName(String name) {\r\n    this.name = name;\r\n}\r\n\r\npublic void setGood(boolean isGood) {\r\n    this.good = isGood;\r\n}\r\n\r\npublic void addSomeListener(MyListener listener){\r\n}\r\n\r\npublic void removeSomeListener(MyListener listener){\r\n}\r\n\r\n}\r\n```\r\n#### Private Member Variables\r\nGood practice is to have all member variables in a class declared as private.\r\n```\r\nprivate String name;\r\nprivate boolean good;\r\n```\r\n#### Naming setter and getter methods\r\n- To modify and access values of properties we use setter and getter methods. Getters and setters should be public. \r\n- Getters should not have any arguments passed.\r\n- Setters should take one argument (the property value) with same type as the return value of getter.\r\n- Non boolean getter name should be (get + PropertyName)\r\n- boolean getter name can be (get + PropertyName) or (is + PropertyName)\r\n- All setters should be named (set + PropertyName)\r\n\r\n#### Examples\r\n```\r\npublic String getName() {\r\n    return name;\r\n}\r\n\r\npublic boolean isGood() {\r\n    return good;\r\n}\r\n\r\npublic void setName(String name) {\r\n    this.name = name;\r\n}\r\npublic void setGood(boolean isGood) {\r\n    this.good = isGood;\r\n}\r\n```\r\n#### Listener naming conventions\r\nMethods to register/add a listener should use prefix \"add\" and suffix \"Listener\". They should accept 1 parameter - the listener object to be added.\r\n#### Example\r\n```\r\npublic void addSomeListener(MyListener listener){\r\n}\r\n```\r\n\r\nMethods to de-register/remove a listener should use prefix \"remove\" and suffix \"Listener\". They should accept 1 parameter - the listener object to be removed\r\n#### Example\r\n```\r\npublic void removeSomeListener(MyListener listener){\r\n}\r\n```\r\n### Regular Expressions\r\n- Regular Expressions make parsing, scanning and splitting a string very easy. We will first look at how you can evaluate a regular expressions in Java , using Patter, Matcher and Scanner classes. We will then look into how to write a regular expression.\r\n#### Regular Expression in Java , Matcher and Pattern Example\r\nCode below shows how to execute a regular expression in java.\r\n```\r\nprivate static void regex(String regex, String string) {\r\n    Pattern p = Pattern.compile(regex);\r\n    Matcher m = p.matcher(string);\r\n    List<String> matches = new ArrayList<String>();\r\n    while (m.find()) {\r\nmatches.add(m.start() + \"<\" + m.group() + \">\");\r\n    }\r\n    System.out.println(matches);\r\n}\r\n```\r\n#### Matcher class\r\nMatcher class has the following utility methods: find(), start(), group().\r\nfind() method returns true until there is a match for the regular expression in the string.\r\nstart() method gives the starting index of the match.\r\ngroup() method returns the matching part of the string.\r\n#### Examples\r\nLet's run this method with a regular expression to search for Ò12Ó in the string Ò122345612Ó.\r\n```\r\nregex(\"12\", \"122345612\");\r\n```\r\n\r\nOutput\r\n```\r\n[0<12>, 7<12>]\r\n```\r\nOutput shows the matching strings 12, 12. Also, shown in the output is the starting index of each match. First 12 is present starting at index 0. The next 12 in the string starts at index 7.\r\n#### Creating Regular Expressions for Java\r\nLet's test regular expressions by using the method we created earlier: regex().\r\n#### Simple Regular Expressions\r\nSearch for 12 in the string\r\n```\r\nregex(\"12\", \"122345612\");//[0<12>, 7<12>]\r\n```\r\n\r\nCertain characters escaped by \\ have special meaning in regular expressions. For example, /s matches a whitespace character.  Remember that to represent \\ in a string, we should prepend \\ to it. Let us see a few examples below.\r\n```\r\nSystem.out.println(\"\\\\\");//prints \\ (only one slash)\r\n```\r\n\r\nSpace character - \\s\r\n```\r\nregex(\"\\\\s\", \"12 1234 123 \");//[2< >, 7< >, 11< >]\r\n```\r\n\r\nDigit - \\d\r\n```\r\nregex(\"\\\\d\", \"12 12\");//[0<1>, 1<2>, 3<1>, 4<2>]\r\n```\r\n\r\nWord character (letter, digits or underscore) - \\w\r\n```\r\nregex(\"\\\\w\", \"ab 12 _\");//[0<a>, 1<b>, 3<1>, 4<2>, 6<_>]\r\n```\r\n\r\nSquare brackets are used in regular expressions to search for a range of characters. Few examples below.\r\nlook for a,b,c,d,1,2,3,4 =>Note that this does not look for capital A,B,C,D\r\n```\r\nregex(\"[a-d1-4]\", \"azbkdm 15AB\");//[0<a>, 2<b>, 4<d>, 7<1>]\r\nregex(\"[a-dA-D]\", \"abyzCD\");//[0<a>, 1<b>, 4<C>, 5<D>]\r\n```\r\n#### Regular Expressions , Multiple Characters\r\n+ is used in regular expression to look for 1 or more characters. For example a+ looks for 1 or more character a's.\r\n```\r\nregex(\"a+\", \"aaabaayza\");//[0<aaa>, 4<aa>, 8<a>]\r\n```\r\n\r\nLook for one or more characters from a to z (only small case).\r\n```\r\nregex(\"[a-z]+\", \"abcZ2xyzN1yza\");//[0<abc>, 5<xyz>, 10<yza>]\r\n//0123456789012\r\n```\r\n#### Regular Expressions , Look for Repetitions\r\nRegular expressions can be joined together to look for a combination.\r\na+b+ looks 1 or more a's and 1 or more b's next to each other. Notice that only a's or only b's do not match.\r\n```\r\nregex(\"a+b+\", \"aabcacaabbbcbb\");//[0<aab>, 6<aabbb>]\r\n```\r\n#### * - 0 or more repetitions.\r\nBelow expression looks for 1 or more a's followed by 0 or more b's followed by 1 or more c's. abc => match. ac=> match (since we used * for b). ab => does not match.\r\n```\r\nregex(\"a+b*c+\", \"abcdacdabdbc\");//[0<abc>, 4<ac>]\r\n```\r\n#### ? - 0 or 1 repetitions.\r\na+b*c? looks for 1 or more a's followed by 0 or more b's followed by 0 or 1 c's. a => matches. ab => matches. abc=>matches. abcc => does not match (only 0 or 1 c's)\r\n```\r\nregex(\"a+b*c?\", \"adabdabcdabccd\");//[0<a>, 2<ab>, 5<abc>, 9<abc>]\r\n```\r\n\r\n^a looks for anything other than a\r\n```\r\nregex(\"[^a]+\", \"bcadefazyx\");//[0<bc>, 3<def>, 7<zyx>]\r\n```\r\n\r\n[^abcd]+a looks for anything which is not a or b or c or d, repeated 0 or more times, followed by a\r\n```\r\nregex(\"[^abcd]+a\", \"efgazyazyzb\");//[0<efga>, 4<zya>]\r\n```\r\n#### . matches any character\r\na.c looks for Ôa' followed by any character followed by Ôc'. abc => match abbc => no match (. matches 1 character only)\r\n```\r\nregex(\"a.c\", \"abca ca!cabbc\");//[0<abc>, 3<a c>, 6<a!c>]\r\n```\r\n#### Greedy Regular Expressions\r\na+ matches a, aa,aaa,aaaa, aaaaa. If you look at the output of the below expression, it matches the biggest only aaaaa. This is called greedy behaviour. similar behavior is shown by *.\r\n```\r\nregex(\"a+\", \"aaaaab\");//[0<aaaaa>]\r\n```\r\n\r\nYou can make + reluctant (look for smallest match) by appending ?\r\n```\r\nregex(\"a+?\", \"aaaaab\");//[0<a>, 1<a>, 2<a>, 3<a>, 4<a>]\r\n```\r\n\r\nSimilarly *? is reluctant match for the greedy *\r\nIf you want to look for characters . or * in a regular expression, then you should escape them.\r\nExample: If I want to look for ...(3 dots), we should use \\.\\.\\. To represent \\.\\.\\. as string we should put two \\'s instead of 1.\r\n```\r\nregex(\"\\\\.\\\\.\\\\.\", \"...a....b...c\");//[0<...>, 4<...>, 9<...>]\r\n```\r\n#### Regular Expression using Scanner class\r\nBelow code shows how Scanner class can be used to execute regular expression.  findInLine method in Scanner returns the match , if a match is found. Otherwise, it returns null.\r\n```\r\nprivate static void regexUsingScanner(String regex,\r\nString string) {\r\n    Scanner s = new Scanner(string);\r\n    List<String> matches = new ArrayList<String>();\r\n\r\n    String token;\r\n    while ((token = s.findInLine(regex)) != null) {\r\nmatches.add(token);\r\n    }\r\n    ;\r\n    System.out.println(matches);\r\n}\r\n```\r\n#### Example\r\n```\r\nregexUsingScanner(\"a+?\", \"aaaaab\");//[a, a, a, a, a]\r\n```\r\n### Tokenizing\r\n- Tokenizing means splitting a string into several sub strings based on delimiters. For example, delimiter ; splits the string ac;bd;def;e into four sub strings ac, bd, def and e. Delimiter can in itself be any of the regular expression(s) we looked at earlier. String.split(regex) function takes regex as an argument.\r\n#### Example method for Tokenizing\r\n```\r\nprivate static void tokenize(String string,String regex) {\r\n    String[] tokens = string.split(regex);\r\n    System.out.println(Arrays.toString(tokens));\r\n}\r\n```\r\n#### Example:\r\n```\r\ntokenize(\"ac;bd;def;e\",\";\");//[ac, bd, def, e]\r\n```\r\n#### Tokenizing using Scanner Class\r\n```\r\nprivate static void tokenizeUsingScanner(String string,String regex) {\r\n    Scanner scanner = new Scanner(string);\r\n    scanner.useDelimiter(regex);\r\n    List<String> matches = new ArrayList<String>();\r\n    while(scanner.hasNext()){\r\nmatches.add(scanner.next());\r\n    }\r\n    System.out.println(matches);\r\n}\r\n```\r\n#### Example:\r\n```\r\ntokenizeUsingScanner(\"ac;bd;def;e\",\";\");//[ac, bd, def, e]\r\n```\r\n#### Scanner Class: Other Functions\r\n```\r\nprivate static void lookForDifferentThingsUsingScanner(\r\nString string) {\r\n    Scanner scanner = new Scanner(string);\r\n    while(scanner.hasNext()){\r\nif(scanner.hasNextBoolean()){\r\n    System.out.println(\"Found Boolean:\" + scanner.nextBoolean());\r\n} else if(scanner.hasNextInt()){\r\n    System.out.println(\"Found Integer:\" + scanner.nextInt());\r\n} else {\r\n    System.out.println(\"Different thing:\" + scanner.next());\r\n}\r\n    }\r\n}\r\n```\r\n\r\nScanner has more useful functions other than just looking for a delimiter\r\n#### Example:\r\n```\r\nlookForDifferentThingsUsingScanner(\"true false 12 3 abc true 154\");\r\n```\r\n#### Output\r\n```\r\n//Found Boolean:true\r\n//Found Boolean:false\r\n//Found Integer:12\r\n//Found Integer:3\r\n//Different thing:abc\r\n//Found Boolean:true\r\n//Found Integer:154\r\n```\r\n\r\n### Expressions\r\n\r\nWhere are objects created? Where are strings created?\r\n\r\n### TODO\r\n- replace ``` with ```java at start of code\r\n- //Getters and Setters are eliminated to keep the example short\r\n- Java SE vs ME vs EE \r\n- Check for long lines which are cut off in pdf\r\n- Notes from Venkat's Talk\r\n  - Designed for a different world - PEnguins\r\n  - OOPS - Terrible - 1970s\r\n  - FP - Lambda calculus-1929\r\n  - Complexity from problems vs Complexity from solutions\r\n  - Structured Programming - One Start One Exit????\r\n  - Functional Programming\r\n    - Assignment LEss \r\n    - Statements vs Expressions\r\n    - Pure Function - No side effects and Zero dependencies that change\r\n    - Referential Transparency\r\n    - Pure Functions\r\n      - idempotent\r\n      - referenctial transparency\r\n      - memorizable\r\n      - easier to testt\r\n      - may be lazily evaluated\r\n    - Higher order function\r\n      - take/create/return object vs take/create/return function\r\n    - Java Future - imperative + oops -> functional + oops\r\n    - Stream - Does not evaluate the function on all the data. It takes a collection of functions (fusing - intermediate operations combined) and executes them on each piece of data..\r\n      - Functional Pipeline, Function\r\n      - \"Coolection pipeline pattern\" -> Martin Fowler\r\n    - Lambda - Stateless\r\n    - Closure has State\r\n  - Code is Liability not an asset!\r\n  - Exception Handling - Promise\r\n  - Reactive Programming\r\n    - Error, Data and End channels\r\n    - Error is a first class citizen\r\n    - Handle errors down stream\r\n\r\n### Complete Java Course\r\n- https://www.udemy.com/java-programming-tutorial-for-beginners/\r\n\r\n### More Courses and Videos From in28Minutes\r\n- https://github.com/in28minutes/learn\r\n"
  },
  {
    "path": "Java/todo.md",
    "content": "## Java Certification\r\n\r\nSource - https://education.oracle.com/education/pdf/JavaCertificationMap.pdf\r\n\r\nThe Oracle Certification track now consists of levels \r\n– Associate (OCA)\r\n- Professional (OCP)\r\n- Master (OCM)\r\n- & a few others - Talk about complexity\r\n\r\n### Java 8\r\n- Oracle Certified Associate, Java SE 8 Programmer\t1Z0-808\r\n- Oracle Certified Professional, Java SE 8 Programmer II, 1Z0-809\r\n- You have other upgrade options from earlier versions\r\n- There is NO Oracle Certified Master for Java SE 8\r\n  - The last master certification for Java - Oracle Certified Master, Java SE 6 Developer 1Z0-855 (includes an assignment and an essay) - is discontinued\r\n     \t- The Oracle Certified Master, Java SE 6 Developer certification retires on November 30, 2016.\r\n     \t- At this time, there is no plan to release a new version of the certification. Through careful job task analysis with the Java SE 8 certification release, it was determined that the OCM Developer role was no longer appropriate to keep as a separate certification and the that skills of that role should be included in the Programmer certifications.\r\n\r\n## Upgrade to Java SE 8 OCP ( Java SE 6 and all prior versions)\r\n\r\nFrom https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-813\r\n\r\n\r\n#### TOPICS\r\n\r\n##### Language Enhancements\r\n\r\n- Develop code that uses String objects in the switch statement, binary literals, and numeric literals, including underscores in literals\r\n- Develop code that uses try-with-resources statements, including using classes that implement the AutoCloseable interface\r\n- Develop code that handles multiple Exception types in a single catch block\r\n- Use static and default methods of an interface including inheritance rules for a default method\r\n\r\n#####  Concurrency\r\n\r\n- Use classes from the java.util.concurrent package including CyclicBarrier and CopyOnWriteArrayList with a focus on the advantages over and differences from the traditional java.util collections \r\n- Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks and java.util.concurrent.atomic packages to support lock-free thread-safe programming on single variables\r\n- Use Executor, ExecutorService, Executors, Callable, and Future to execute tasks using thread pools\r\n- Use the parallel Fork/Join Framework\r\n\r\n##### Localization\r\n\r\n- Describe the advantages of localizing an application and developing code that defines, reads, and sets the locale with a Locale object\r\n- Build a resource bundle for a locale and call a resource bundle from an application\r\n- Create and manage date- and time-based events by using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration, including a combination of date and time in a single object\r\n- Format dates, numbers, and currency values for localization with the NumberFormat and DateFormat classes, including number and date format patterns\r\n- Work with dates and times across time zones and manage changes resulting from daylight savings\r\n\r\n##### Java File I/O (NIO.2)\r\n\r\n- Operate on file and directory paths by using the Paths class\r\nCheck, delete, copy, or move a file or directory by using the Files class \r\nRecursively access a directory tree by using the DirectoryStream and FileVisitor interfaces\r\n- Find a file by using the PathMatcher interface, and use Java SE 8 I/O improvements, including Files.find(), Files.walk(), and lines() methods\r\nObserve the changes in a directory by using the WatchService interface\r\n\r\n##### Lambda\r\n\r\n- Define and write functional interfaces and describe the interfaces of the java.util.function package\r\n- Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing\r\n- Develop code that uses the built-in interfaces included in the java.util.function package, such as Function, Consumer, Supplier, UnaryOperator, Predicate, and Optional APIs, including the primitive and binary variations of the interfaces\r\n- Develop code that uses a method reference, including refactoring a lambda expression to a method reference\r\n\r\n##### Java Collections\r\n\r\n- Develop code that uses diamond with generic declarations\r\n- Develop code that iterates a collection, filters a collection, and sorts a collection by using lambda expressions\r\n- Search for data by using methods, such as findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch()\r\n- Perform calculations on Java Streams by using count, max, min, average, and sum methods and save results to a collection by using the collect method and Collector class, including the averagingDouble, groupingBy, joining, partitioningBy methods\r\n- Develop code that uses Java SE 8 collection improvements, including the Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), and Map.computeIfPresent() methods\r\n- Develop  code that uses the merge(), flatMap(), and map() methods on Java Streams\r\n\r\n##### Java Streams\r\n\r\n- Describe the Stream interface and pipelines; create a stream by using the Arrays.stream() and  IntStream.range() methods; identify the lambda operations that are lazy\r\n- Develop code that uses parallel streams, including decomposition operation and reduction operation in streams\r\n\r\n## Java New Features Course Objectives\r\n\r\n\r\nIntroducing Lambda Expressions\r\n\r\n- Describing the purpose of an anonymous inner class\r\n- Describing drawbacks to anonymous inner classes\r\n- Describing the components of a lambda expression\r\n- Defining a functional interface\r\n- Creating programs that use lambda expressions\r\n\r\nA Case for Lambda Expressions\r\n\r\n- Discussing the reasons for adding lambda expressions to the Java language\r\n- Reviewing the standard way of extracting data in Java\r\n- Refactoring code to reduce redundancy\r\n- Refactoring code to use inner classes\r\n- Refactoring code to use lambda expressions\r\n- Listing the benefits of lambda expressions\r\n\r\nFiltering Collections with Lambdas\r\n\r\n- Iterating though a collection with forEach\r\n- Iterating through a collection using lambda syntax\r\n- Describing the Stream interface\r\n- Filtering a collection using lambda expressions\r\n- Calling an existing method using a method reference\r\n- Chaining multiple methods together\r\n- Comparing function and imperative programming\r\n- Defining pipelines in terms of lambdas and collections\r\n\r\nUsing Built in Lambda Types\r\n\r\n- Listing the built in interfaces included in java.util.function\r\n- Determining true or false with a Predicate\r\n- Processing an object and return nothing with Consumer\r\n- Processing one object and return another with Function\r\n- Generating a new object with Supplier\r\n- Using primitive versions of the base interfaces\r\n- Using binary versions of the base interfaces\r\n\r\nCollection Operations with Lambda\r\n\r\n- Extracting data from an object using map\r\n- Searching for data using search methods\r\n- Describing the types of stream operations\r\n- Describing the Optional class\r\n- Performing calculations using methods\r\n- Describing lazy processing\r\n- Sorting a stream\r\n- Saving results to a collection using the collect method\r\n- Parallel Streams\r\n- Reviewing the key characteristics of streams\r\n\r\nContrasting old style loop operations with streams\r\n- Describing how to make a stream pipeline execute in parallel\r\n- Listing the key assumptions needed to use a parallel pipeline\r\n- Defining reduction\r\n- Describing why reduction requires an associative function\r\n- Calculating a value using reduce\r\n- Describing the process for decomposing and then merging work\r\n\r\nLambda Cookbook\r\n\r\n- Modifying a list using removeIf\r\n- Updating a list using replaceAll\r\n- Updating a map using computeIfAbsent, computerIfPresent, and merge\r\n- Sending the keys and values from a map to a stream\r\n- Reading a file to a stream\r\n- Reading a text file into an ArrayList\r\n- List, walk, and search a directory structure using a stream\r\n- Flattening a stream using flatMap\r\n\r\nMethod Enhancements\r\n\r\n- Considering the importance of building good libraries\r\n- Using static methods in Interfaces\r\n- Using default methods\r\n- Understanding default method inheritance rules\r\n\r\n\r\nUsing the Date/Time API: Working with Local Dates and Times\r\n\r\n- Listing the goals of the Date/Time API (JSR-310)\r\n- Creating and manage date-based events\r\n- Creating and manage time-based events\r\n- Combining date and time into a single object\r\n\r\nUsing the Date/Time API: Working with Time Zones\r\n\r\n- Working with dates and times across time-zones and manage changes resulting from daylight savings\r\n\r\nUsing the Date/Time API: Working with Date and Time Amounts\r\n- Defining and create timestamps, periods and durations\r\n- Applying formatting to local and zoned dates and times\r\n\r\nJavaScript on Java with Nashorn: Creating and executing shell scripts\r\n- Creating and execute shell scripts using JavaScript and Nashorn\r\n- JavaScript on Java with Nashorn: Writing JavaScript Applications\r\n- Developing JavaScript applications that leverage Java code using Nashorn\r\n- JavaScript on Java with Nashorn: Writing JavaFX Applications Using \r\n\r\nJavaScript\r\n\r\n- Running JavaScript script from Java applications usingJSR-223\r\n- Prototype JavaFX applications using Nashorn and JavaScript\r\n\r\nIntro to Mission Control\r\n\r\n- Describing JMX and Managed Beans with Mission Control\r\n- Monitoring CPU utilization with Mission Control\r\n- Analyzing JVM characteristics with Mission Control\r\n- Analyzing heap memory with Mission Control\r\n- Intro to Flight Recorder\r\n\r\nDescribing the Java Flight Recorder\r\n- Describing the Java Flight Recorder Architecture\r\n- Starting a Java Flight Recording\r\n- Managing a Java Flight Recording\r\n- Analyzing a Java Flight Recording\r\n\r\n\r\n## Java SE 6 Programmer Certified Professional\r\n\r\nSection 1: Declarations, Initialization and Scoping\r\n\r\n- Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).\r\n- Develop code that declares an interface. Develop code that implements or extends one or more interfaces.\r\n- Develop code that declares an abstract class. Develop code that extends an abstract class.\r\n- Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.\r\n- Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.\r\n- Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.\r\n\r\nSection 2: Flow Control\r\n\r\n- Develop code that implements an if or switch statement; and identify legal argument types for these statements.\r\n- Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.\r\n- Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.\r\n- Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.\r\n- Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.\r\n- Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.\r\n\r\nSection 3: API Contents\r\n\r\n- Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.\r\n- Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.\r\n- Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.\r\n- Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \\d, \\s, \\w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.\r\n\r\nSection 4: Concurrency\r\n\r\n- Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.\r\n- Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.\r\n- Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.\r\n\r\nSection 5: OO Concepts\r\n\r\n- Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.\r\n- Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.\r\n- Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.\r\n- Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.\r\n- Develop code that implements \"is-a\" and/or \"has-a\" relationships.\r\n\r\nSection 6: Collections / Generics\r\n- Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.\r\n- Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.\r\n- Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.\r\n- Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.\r\n- Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the \"natural ordering\" of primitive wrapper classes and java.lang.String on sorting.\r\n\r\nSection 7: Fundamentals\r\n\r\n- Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.\r\n- Given an example of a class and a command-line, determine the expected runtime behavior.\r\n- Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.\r\n- Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.\r\n- Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.\r\n- Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.\r\n\r\n## Preparation Course For Java Certification 1\r\n\r\nGetting Started\r\n- Examine Java technology\r\n- Analyze a simple Java technology application \r\n- Execute a Java technology application\r\n\r\nObject-Oriented Programming\r\n- Define modeling concepts: abstraction, encapsulation, and packages\r\n- Discuss Java technology application code reuse\r\n- Define class, member, attribute, method, constructor, and package\r\n- Use the access modifiers private and public as appropriate for the guidelines of encapsulation Invoke a method on a particular object\r\n- Use the Java technology API online documentation\r\n\r\nIdentifiers, Keywords, and Types\r\n- Use comments in a source program\r\n- Distinguish between valid and invalid identifiers\r\n- Use the eight primitive types\r\n- Define literal values for numeric and textual types\r\n- Define the terms primitive variable and reference variable \r\n- Declare variables of class type\r\n- Construct an object using new and describe default initialization \r\n- Describe the significance of a reference variable\r\n\r\nExpressions and Flow Control\r\n- Distinguish between instance and local variables\r\n- Describe how to initialize instance variables\r\n- Recognize, describe, and use Java software operators\r\n- Distinguish between legal and illegal assignments of primitive types\r\n- Identify boolean expressions and their requirements in control constructs\r\n- Recognize assignment compatibility and required casts in fundamental types\r\n- Use if, switch, for, while, and do constructions and the labeled forms of break and continue as flow control structures in a progra\r\n\r\nArrays\r\n- Declare and create arrays of primitive, class, or array types Explain why elements of an array are initialized\r\n- Explain how to initialize the elements of an array Determine the number of elements in an array\r\n- Create a multidimensional array\r\n- Write code to copy array values from one array to another\r\n\r\nClass Design\r\n- Define inheritance, polymorphism, overloading, overriding, and virtual method invocation\r\n- Use the access modifiers protected and the default (package-friendly)\r\n- Describe the concepts of constructor and method overloading\r\n- Describe the complete object construction and initialization operation\r\n\r\nAdvanced Class Features\r\n- Create static variables, methods, and initializers\r\n- Create final classes, methods, and variables Create and use enumerated types\r\n- Use the static import statement\r\n- Create abstract classes and methods Create and use an interface\r\n\r\nExceptions and Assertions\r\n- Define exceptions\r\n- Use try, catch, and finally statements\r\n- Describe exception categories\r\n- Identify common exceptions\r\n- Develop programs to handle your own exceptions\r\n- Use assertions\r\n- Distinguish appropriate and inappropriate uses of assertions \r\n- Enable assertions at runtime\r\n\r\nCollections and Generics Framework\r\n- Describe the general purpose implementations of the core interfaces in the Collections framework \r\n- Examine the Map interface\r\n- Examine the legacy collection classes\r\n- Create natural and custom ordering by implementing the Comparable and Comparator interfaces\r\n- Use generic collections and type parameters in generic classes\r\n- Refactor existing non-generic code\r\n- Write a program to iterate over a collection\r\n- Examine the enhanced for loop\r\n\r\nI/O Fundamentals\r\n- Write a program that uses command-line arguments and system properties\r\n- Examine the Properties class\r\n- Construct node and processing streams, and use them appropriately\r\n- Serialize and deserialize objects\r\n- Distinguish readers and writers from streams, and select appropriately between them\r\n\r\nConsole I/ O and File I/O\r\n- Read data from the console Write data to the console Describe files and file I/O\r\n\r\nThreads\r\n- Define a thread\r\n- Create separate threads in a Java technology program, controlling the code and data that are used by that thread\r\n- Control the execution of a thread and write platform-independent code with threads\r\n- Describe the difficulties that might arise when multiple threads share data\r\n- Use wait and notify to communicate between threads\r\n- Use synchronized to protect data from corruption\r\n\r\n## Preparation Course For Java Certification 2\r\n\r\nExplaining Java Technology\r\n\r\n- Describe key concepts of the Java programming language\r\n- List the three Java technology product groups\r\n- Summarize each of the seven stages of the product life cycle\r\n\r\nAnalyzing a Problem and Designing a Solution\r\n\r\n- Analyze a problem using object-oriented analysis\r\n- Design classes from which objects will be created\r\n\r\nDeveloping and Testing a Java Technology Program\r\n\r\n- Identify the four components of a class in the Java programming language\r\n- Use the main method in a test class to run a Java technology program from the command line\r\n- Compile and execute a Java technology program\r\n\r\nDeclaring, Initializing, and Using Variables\r\n\r\n- Identify the use the syntax for variables and define the syntax for a variable\r\n- List the eight Java programming language primitive data types\r\n- Declare, initialize, and use variables and constants according to Java programming language guidelines and coding standards\r\n- Modify variable values using operators\r\n- Use promotion and type casting\r\n\r\nCreating and Using Objects\r\n\r\n- Declare, instantiate, and initialize object reference variables\r\n- Compare how object reference variables are stored in relation to primitive variables\r\n- Use a class (the String class) included in the Java Software Developer Kit (SDK)\r\n- Use the Java 2 Platform, Standard Edition (J2SE) class library specification to learn about other classes in this application programming interface (API)\r\n\r\nUsing Operators and Decision Constructs\r\n\r\n- Identify relational and conditional operators\r\n- Create if and if/else constructs\r\n- Use the switch construct\r\n\r\nUsing Loop Constructs\r\n\r\n- Create while loops\r\n- Develop for loops\r\n- Create do/while loops\r\n\r\nDeveloping and Using Methods\r\n\r\n- Describe the advantages of methods and define worker and calling methods\r\n- Declare and invoke a method\r\n- Compare object and static methods\r\n- Use overloaded methods\r\n\r\nImplementing Encapsulation and Constructors\r\n\r\n- Use encapsulation to protect data\r\n- Create constructors to initialize objects\r\n\r\nCreating and Using Arrays\r\n\r\n- Code one-dimensional arrays\r\n- Set array values using length attribute and a loop\r\n- Pass arguments to the main method for use in a program\r\n- Create two-dimensional arrays\r\n\r\nImplementing Inheritance\r\n\r\n- Define and test your use of inheritance\r\n- Explain abstraction\r\n- Explicitly identify class libraries used in your code\r\n\r\n## Oracle Certified Associate or Java SE 8 Programmer I : 1Z0-808\r\n\r\nJava Basics\t\r\n- Define the scope of variables\r\n- Define the structure of a Java class\r\n- Create executable Java applications with a main method; run a Java program from the command line; including console output.\r\n- Import other Java packages to make them accessible in your code\r\n- Compare and contrast the features and components of Java such as: platform independence, object orientation, encapsulation, etc.\r\n\r\nWorking With Java Data Types\t\r\n- Declare and initialize variables (including casting of primitive data types)\r\n- Differentiate between object reference variables and primitive variables\r\n- Know how to read or write to object fields\r\n- Explain an Object's Lifecycle (creation, \"dereference by reassignment\" and garbage collection)\r\n- Develop code that uses wrapper classes such as Boolean, Double, and Integer.\r\n\r\nUsing Operators and Decision Constructs\t\r\n- Use Java operators; including parentheses to override operator precedence\r\n- Test equality between Strings and other objects using == and equals ()\r\n- Create if and if/else and ternary constructs\r\n- Use a switch statement\r\n\r\nCreating and Using Arrays\t\r\n- Declare, instantiate, initialize and use a one-dimensional array\r\n- Declare, instantiate, initialize and use multi-dimensional array\r\n\r\nUsing Loop Constructs\t\r\n- Create and use while loops\r\n- Create and use for loops including the enhanced for loop\r\n- Create and use do/while loops\r\n- Compare loop constructs\r\n- Use break and continue\r\n\r\nWorking with Methods and Encapsulation\t\r\n- Create methods with arguments and return values; including overloaded methods\r\n- Apply the static keyword  to methods and fields\r\n- Create and overload constructors; including impact on default constructors\r\n- Apply access modifiers\r\n- Apply encapsulation principles to a class\r\n- Determine the effect upon object references and primitive values when they are passed  into methods that change the values\r\n\r\nWorking with Inheritance\t\r\n- Describe inheritance and its benefits\r\n- Develop code that demonstrates the use of polymorphism; including overriding and object type versus reference type\r\n- Determine when casting is necessary\r\n- Use super and this to access objects and constructors\r\n- Use abstract classes and interfaces\r\n\r\nHandling Exceptions\t\r\n- Differentiate among checked exceptions, unchecked exceptions, and Errors\r\n- Create a try-catch block and determine how exceptions alter normal program flow\r\n- Describe the advantages of Exception handling\r\n- Create and invoke a method that throws an exception\r\n- \"Recognize common exception classes (such as NullPointerException, ArithmeticExcpetion, ArrayIndexOutOfBoundsException, ClassCastException)\"\r\n\r\nWorking with Selected classes from the Java API\t\r\n- Manipulate data using the StringBuilder class and its methods\r\n- Creating and manipulating Strings\r\n- Create and manipulate calendar data using classes from java.time.LocalDateTime,  java.time.LocalDate, java.time.LocalTime, java.time.format.DateTimeFormatter, java.time.Period\r\n- Declare and use an ArrayList of a given type\r\n- Write a simple Lambda expression that consumes a Lambda Predicate expression\r\n\r\n\r\n## Oracle Certified Professional or Java SE 8 Programmer II - 1Z0-809\r\n\r\nJava Class Design\t\r\n- Implement encapsulation\r\n- Implement inheritance including visibility modifiers and composition\r\n- Implement polymorphism\r\n- Override hashCode, equals, and toString methods from Object class\r\n- Create and use singleton classes and immutable classes\r\n- Develop code that uses static keyword on initialize blocks, variables, methods, and classes\r\n\r\nAdvanced Java Class Design\t\r\n- Develop code that uses abstract classes and methods\r\n- Develop code that uses final keyword\r\n- Create inner classes including static inner class, local class, nested class, and anonymous inner class\r\n- Use enumerated types including methods, and constructors in an enum type\r\n- Develop code that declares, implements and/or extends interfaces and use the atOverride annotation.\r\n- Create and use Lambda expressions\r\n\r\nGenerics and Collections\t\r\n- Create and use a generic class\r\n- Create and use ArrayList, TreeSet, TreeMap, and ArrayDeque objects\r\n- Use java.util.Comparator and java.lang.Comparable interfaces\r\n- Collections Streams and Filters\r\n- Iterate using forEach methods of Streams and List\r\n- Describe Stream interface and Stream pipeline\r\n- Filter a collection by using lambda expressions\r\n- Use method references with Streams\r\n\r\nLambda Built-in Functional Interfaces\t\r\n- Use  the built-in interfaces included in the java.util.function package such as Predicate, Consumer, Function, and Supplier\r\n- Develop code that uses primitive versions of functional interfaces\r\n- Develop code that uses binary versions of functional interfaces\r\n- Develop code that uses the UnaryOperator interface\r\n\r\nJava Stream API\t\r\n- Develop code to extract data from an object using peek() and map() methods including primitive versions of the map() method\r\n- Search for data by using search methods of the Stream classes including findFirst, findAny, anyMatch, allMatch, noneMatch\r\n- Develop code that uses the Optional class\r\n- Develop code that uses Stream data methods and calculation methods\r\n- Sort a collection using Stream API\r\n- Save results to a collection using the collect method and group/partition data using the Collectors class\r\n- Use flatMap() methods in the Stream API\r\n\r\nExceptions and Assertions\t\r\n- Use try-catch and throw statements\r\n- Use catch, multi-catch, and finally clauses\r\n- Use Autoclose resources with a try-with-resources statement\r\n- Create custom exceptions and Auto-closeable resources\r\n- Test invariants by using assertions\r\n\r\nUse Java SE 8 Date/Time API\t\r\n- Create and manage date-based and time-based events including a combination of date and time into a single object using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration\r\n- Work with dates and times across timezones and manage changes resulting from daylight savings including Format date and times values\r\n- Define and create and manage date-based and time-based events using Instant, Period, Duration, and TemporalUnit\r\n\r\nJava I/O Fundamentals\t\r\n- Read and write data from the console\r\n- Use BufferedReader, BufferedWriter, File, FileReader, FileWriter, FileInputStream, FileOutputStream, ObjectOutputStream, ObjectInputStream, and PrintWriter in the java.iopackage.\r\n\r\nJava File I/O (NIO.2)\t\r\n- Use Path interface to operate on file and directory paths\r\n- Use Files class to check, read, delete, copy, move, manage metadata of a file or directory\r\n- Use Stream API with NIO.2\r\n\r\nJava Concurrency\t\r\n- Create worker threads using Runnable, Callable and use an ExecutorService to concurrently execute tasks\r\n- Identify potential threading problems among deadlock, starvation, livelock, and race conditions\r\n- Use synchronized keyword and java.util.concurrent.atomic package to control the order of thread execution\r\n- Use java.util.concurrent collections and classes including CyclicBarrier and CopyOnWriteArrayList\r\n- Use parallel Fork/Join Framework\r\n- Use parallel Streams including reduction, decomposition, merging processes, pipelines and performance.\r\n\r\nBuilding Database Applications with JDBC\t\r\n- Describe the interfaces that make up the core of the JDBC API including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations\r\n- Identify the components required to connect to a database using the DriverManager class including the JDBC URL\r\n- Submit queries and read results from the database including creating statements, returning result sets, iterating through the results, and properly closing result sets, statements, and connections\r\n\r\nLocalization\t\r\n- Read and set the locale by using the Locale object\r\n- Create and read a Properties file\r\n- Build a resource bundle for each locale and load a resource bundle in an application"
  },
  {
    "path": "JavaScript/README.md",
    "content": "# Modern JavaScript Cheatsheet\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n\r\n## Introduction\r\n\r\n### Motivation\r\n\r\nThis document is a cheatsheet for JavaScript you will frequently encounter in modern projects and most contemporary sample code.\r\n\r\nThis guide is not intended to teach you JavaScript from the ground up, but to help developers with basic knowledge who may struggle to get familiar with modern codebases (or let's say to learn React for instance) because of the JavaScript concepts used.\r\n\r\nBesides, I will sometimes provide personal tips that may be debatable but will take care to mention that it's a personal recommendation when I do so.\r\n\r\n> **Note:** Most of the concepts introduced here are coming from a JavaScript language update (ES2015, often called ES6). You can find new features added by this update [here](http://es6-features.org); it's very well done.\r\n\r\n### Complementary Resources\r\n\r\nWhen you struggle to understand a notion, I suggest you look for answers on the following resources:\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/en-US/search?q=)\r\n- [You don't know JS (book)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Features with examples](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Javascript Basics for Beginners](https://www.udacity.com/course/javascript-basics--ud804) - a free Udacity course\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) to find specific blog and resources\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript)\r\n\r\n## Table of Contents\r\n\r\n- [Modern JavaScript cheatsheet](#modern-javascript-cheatsheet)\r\n  * [Introduction](#introduction)\r\n    + [Motivation](#motivation)\r\n    + [Complementary resources](#complementary-resources)\r\n  * [Table of contents](#table-of-contents)\r\n  * [Notions](#notions)\r\n    + [Variable declaration: var, const, let](#variable-declaration-var-const-let)\r\n      - [Short explanation](#short-explanation)\r\n      - [Sample code](#sample-code)\r\n      - [Detailed explanation](#detailed-explanation)\r\n      - [External resource](#external-resource)\r\n    + [Arrow function](#-arrow-function)\r\n      - [Sample code](#sample-code-1)\r\n      - [Detailed explanation](#detailed-explanation-1)\r\n        * [Concision](#concision)\r\n        * [*this* reference](#this-reference)\r\n      - [Useful resources](#useful-resources)\r\n    + [Function default parameter value](#function-default-parameter-value)\r\n      - [External resource](#external-resource-1)\r\n    + [Destructuring objects and arrays](#destructuring-objects-and-arrays)\r\n      - [Explanation with sample code](#explanation-with-sample-code)\r\n      - [Useful resources](#useful-resources-1)\r\n    + [Array methods - map / filter / reduce](#array-methods---map--filter--reduce)\r\n      - [Sample code](#sample-code-2)\r\n      - [Explanation](#explanation)\r\n        * [Array.prototype.map()](#arrayprototypemap)\r\n        * [Array.prototype.filter()](#arrayprototypefilter)\r\n        * [Array.prototype.reduce()](#arrayprototypereduce)\r\n      - [External Resource](#external-resource-2)\r\n    + [Spread operator \"...\"](#spread-operator-)\r\n      - [Sample code](#sample-code-3)\r\n      - [Explanation](#explanation-1)\r\n        * [In iterables (like arrays)](#in-iterables-like-arrays)\r\n        * [Function rest parameter](#function-rest-parameter)\r\n        * [Object properties spreading](#object-properties-spreading)\r\n      - [External resources](#external-resources)\r\n    + [Object property shorthand](#object-property-shorthand)\r\n      - [Explanation](#explanation-2)\r\n      - [External resources](#external-resources-1)\r\n    + [Promises](#promises)\r\n      - [Sample code](#sample-code-4)\r\n      - [Explanation](#explanation-3)\r\n        * [Create the promise](#create-the-promise)\r\n        * [Promise handlers usage](#promise-handlers-usage)\r\n      - [External Resources](#external-resources-2)\r\n    + [Template literals](#template-literals)\r\n      - [Sample code](#sample-code-5)\r\n      - [External resources](#external-resources-3)\r\n    + [Tagged Template Literals](#tagged-template-literals)\r\n      - [External resources](#external-resources-4)\r\n    + [Imports / Exports](#imports--exports)\r\n      - [Explanation with sample code](#explanation-with-sample-code-1)\r\n        * [Named exports](#named-exports)\r\n        * [Default import / export](#default-import--export)\r\n      - [External resources](#external-resources-5)\r\n    + [JavaScript *this*](#-javascript-this)\r\n      - [External resources](#external-resources-6)\r\n    + [Class](#class)\r\n      - [Samples](#samples)\r\n      - [External resources](#external-resources-7)\r\n    + [Extends and super keywords](#extends-and-super-keywords)\r\n      - [Sample Code](#sample-code-6)\r\n      - [External Resources](#external-resources-8)\r\n    + [Async Await](#async-await)\r\n      - [Sample code](#sample-code-7)\r\n      - [Explanation with sample code](#explanation-with-sample-code-2)\r\n      - [Error handling](#error-handling)\r\n      - [External resources](#external-resources-9)\r\n    + [Truthy / Falsy](#truthy--falsy)\r\n      - [External resources](#external-resources-10)\r\n    + [Anamorphisms / Catamporphisms](#anamorphisms-and-catamorphisms)\r\n      - [Anamorphisms](#anamorphisms)\r\n      - [Catamorphisms](#catamorphisms)\r\n      - [External resources](#external-resources-11)\r\n    + [Generators](#generators)\r\n      - [External resources](#external-resources-12)\r\n    + [Static Methods](#static-methods)\r\n      - [Short Explanation](#short-explanation-1)\r\n      - [Sample Code](#sample-code-8)\r\n      - [Detailed Explanation](#detailed-explanation-2)\r\n        * [Calling other static methods from a static method](#calling-other-static-methods-from-a-static-method)\r\n        * [Calling static methods from non-static methods](#calling-static-methods-from-non-static-methods)\r\n      - [External resources](#external-resources-13)\r\n  * [Glossary](#glossary)\r\n    + [Scope](#-scope)\r\n    + [Variable mutation](#-variable-mutation)\r\n\r\n## Notions\r\n\r\n### Variable declaration: var, const, let\r\n\r\nIn JavaScript, there are three keywords available to declare a variable, and each has its differences. Those are ```var```, ```let``` and ```const```.\r\n\r\n#### Short explanation\r\n\r\nVariables declared with ```const``` keyword can't be reassigned, while ```let``` and ```var``` can.\r\n\r\nI recommend always declaring your variables with ```const``` by default, and with ```let``` if you need to *mutate* it or reassign it later.\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>Scope</th>\r\n    <th>Reassignable</th>\r\n    <th>Mutable</th>\r\n   <th><a href=\"#tdz_sample\">Temporal Dead Zone</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>const</th>\r\n    <td>Block</td>\r\n    <td>No</td>\r\n    <td><a href=\"#const_mutable_sample\">Yes</a></td>\r\n    <td>Yes</td>\r\n  </tr>\r\n  <tr>\r\n    <th>let</th>\r\n    <td>Block</td>\r\n    <td>Yes</td>\r\n    <td>Yes</td>\r\n    <td>Yes</td>\r\n  </tr>\r\n   <tr>\r\n    <th>var</th>\r\n    <td>Function</td>\r\n    <td>Yes</td>\r\n    <td>Yes</td>\r\n    <td>No</td>\r\n  </tr>\r\n</table>\r\n\r\n#### Sample code\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // Will raise an error, person can't be reassigned\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", reassignment is allowed with let\r\n```\r\n\r\n#### Detailed explanation\r\n\r\nThe [*scope*](#scope_def) of a variable roughly means \"where is this variable available in the code\".\r\n\r\n##### var\r\n\r\n```var``` declared variables are *function scoped*, meaning that when a variable is created in a function, everything in that function can access that variable. Besides, a *function scoped* variable created in a function can't be accessed outside this function.\r\n\r\nI recommend you to picture it as if an *X scoped* variable meant that this variable was a property of X.\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar is accessible inside the function\r\n}\r\nconsole.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.\r\n```\r\n\r\nStill focusing on the variable scope, here is a more subtle example:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // actually, myVar being function scoped, we just erased the previous myVar value \"Nick\" for \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - see how the instructions in the if block affected this value\r\n}\r\nconsole.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.\r\n```\r\n\r\nBesides, *var* declared variables are moved to the top of the scope at execution. This is what we call [var hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting).\r\n\r\nThis portion of code:\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- no error raised\r\nvar myVar = 2;\r\n```\r\n\r\nis understood at execution like:\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- no error raised\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n```var``` and ```let ``` are about the same, but ```let``` declared variables\r\n\r\n- are *block scoped*\r\n- are **not** accessible before they are assigned\r\n- can't be re-declared in the same scope\r\n\r\nLet's see the impact of block-scoping taking our previous example:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // actually, myVar being block scoped, we just created a new variable myVar.\r\n    // this variable is not accessible outside this block and totally independent\r\n    // from the first myVar created !\r\n  }\r\n  console.log(myVar); // \"Nick\", see how the instructions in the if block DID NOT affect this value\r\n}\r\nconsole.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> Now, what it means for *let* (and *const*) variables for not being accessible before being assigned:\r\n\r\n```js\r\nconsole.log(myVar) // raises a ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\nBy contrast with *var* variables, if you try to read or write on a *let* or *const* variable before they are assigned an error will be raised. This phenomenon is often called [*Temporal dead zone*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) or *TDZ*.\r\n\r\n> **Note:** Technically, *let* and *const* variables declarations are being hoisted too, but not their assignation. Since they're made so that they can't be used before assignation, it intuitively feels like there is no hoisting, but there is. Find out more on this [very detailed explanation here](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified) if you want to know more.\r\n\r\nIn addition, you can't re-declare a *let* variable:\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // Raises a SyntaxError\r\n```\r\n\r\n##### const\r\n\r\n```const``` declared variables behave like *let* variables, but also they can't be reassigned.\r\n\r\nTo sum it up, *const* variables:\r\n\r\n- are *block scoped*\r\n- are not accessible before being assigned\r\n- can't be re-declared in the same scope\r\n- can't be reassigned\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // raises an error, reassignment is not allowed\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // raises an error, re-declaration is not allowed\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> But there is a subtlety : ```const``` variables are not [**immutable**](#mutation_def) ! Concretely, it means that *object* and *array* ```const``` declared variables **can** be mutated.\r\n\r\nFor objects:\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // this will work ! person variable is not completely reassigned, but mutated\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // raises an error, because reassignment is not allowed with const declared variables\r\n```\r\n\r\nFor arrays:\r\n```js\r\nconst person = [];\r\nperson.push('John'); // this will work ! person variable is not completely reassigned, but mutated\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // raises an error, because reassignment is not allowed with const declared variables\r\n```\r\n\r\n#### External resource\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"arrow_func_concept\"></a> Arrow function\r\n\r\nThe ES6 JavaScript update has introduced *arrow functions*, which is another way to declare and use functions. Here are the benefits they bring:\r\n\r\n- More concise\r\n- *this* is picked up from surroundings\r\n- implicit return\r\n\r\n#### Sample code\r\n\r\n- Concision and implicit return\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // Traditional way\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // Same function written as an arrow function with implicit return\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- *this* reference\r\n\r\nIn an arrow function, *this* is equal to the *this* value of the enclosing execution context. Basically, with arrow functions, you don't have to do the \"that = this\" trick before calling a function inside a function anymore.\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### Detailed explanation\r\n\r\n##### Concision\r\n\r\nArrow functions are more concise than traditional functions in many ways. Let's review all the possible cases:\r\n\r\n- Implicit VS Explicit return\r\n\r\nAn **explicit return** is a function where the *return* keyword is used in its body.\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // this function explicitly returns x * 2, *return* keyword is used\r\n  }\r\n```\r\n\r\nIn the traditional way of writing functions, the return was always explicit. But with arrow functions, you can do *implicit return* which means that you don't need to use the keyword *return* to return a value.\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // Explicit return here\r\n  }\r\n```\r\n\r\nSince this function only returns something (no instructions before the *return* keyword) we can do an implicit return.\r\n\r\n```js\r\n  const double = (x) => x * 2; // Correct, returns x*2\r\n```\r\n\r\nTo do so, we only need to **remove the brackets** and the **return** keyword. That's why it's called an *implicit* return, the *return* keyword is not there, but this function will indeed return ```x * 2```.\r\n\r\n> **Note:** If your function does not return a value (with *side effects*), it doesn't do an explicit nor an implicit return.\r\n\r\nBesides, if you want to implicitly return an *object* you **must have parentheses around it** since it will conflict with the block braces:\r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- object implicitly returned by arrow function\r\n```\r\n\r\n- Only one argument\r\n\r\nIf your function only takes one parameter, you can omit the parentheses around it. If we take back the above *double* code:\r\n\r\n```js\r\n  const double = (x) => x * 2; // this arrow function only takes one parameter\r\n```\r\n\r\nParentheses around the parameter can be avoided:\r\n\r\n```js\r\n  const double = x => x * 2; // this arrow function only takes one parameter\r\n```\r\n\r\n- No arguments\r\n\r\nWhen there is no argument provided to an arrow function, you need to provide parentheses, or it won't be valid syntax.\r\n\r\n```js\r\n  () => { // parentheses are provided, everything is fine\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // No parentheses, this won't work!\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### *this* reference\r\n\r\nTo understand this subtlety introduced with arrow functions, you must know how [this](#this_def) behaves in JavaScript.\r\n\r\nIn an arrow function, *this* is equal to the *this* value of the enclosing execution context. What it means is that an arrow function doesn't create a new *this*, it grabs it from its surrounding instead.\r\n\r\nWithout arrow function, if you wanted to access a variable from *this* in a function inside a function, you had to use the *that = this* or *self = this* trick.\r\n\r\nFor instance, using setTimeout function inside myFunc:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // that = this trick\r\n  setTimeout(\r\n    function() { // A new *this* is created in this function scope\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- see function declaration above\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\nBut with arrow function, *this* is taken from its surrounding:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this taken from surrounding, meaning myFunc here\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### Useful resources\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n### Function default parameter value\r\n\r\nStarting from ES2015 JavaScript update, you can set default value to your function parameters using the following syntax:\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- no value is provided so x default value 10 is assigned to x in myFunc\r\nconsole.log(myFunc(5)) // 5 -- a value is provided so x is equal to 5 in myFunc\r\n\r\nconsole.log(myFunc(undefined)) // 10 -- undefined value is provided so default value is assigned to x\r\nconsole.log(myFunc(null)) // null -- a value (null) is provided, see below for more details\r\n```\r\n\r\nThe default parameter is applied in two and only two situations:\r\n\r\n- No parameter provided\r\n- *undefined* parameter provided\r\n\r\nIn other words, if you pass in *null* the default parameter **won't be applied**.\r\n\r\n> **Note:** Default value assignment can be used with destructured parameters as well (see next notion to see an example)\r\n\r\n#### External resource\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Default parameters - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\r\n\r\n### Destructuring objects and arrays\r\n\r\n*Destructuring* is a convenient way of creating new variables by extracting some values from data stored in objects or arrays.\r\n\r\nTo name a few use cases, *destructuring* can be used to destructure function parameters or *this.props* in React projects for instance.\r\n\r\n#### Explanation with sample code\r\n\r\n- Object\r\n\r\nLet's consider the following object for all the samples:\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\nWithout destructuring\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\nWith destructuring, all in one line:\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // That's it !\r\n\r\nconsole.log(age) // 35 -- A new variable age is created and is equal to person.age\r\nconsole.log(first) // \"Nick\" -- A new variable first is created and is equal to person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName exists BUT the new variable created is named first\r\nconsole.log(city) // \"Paris\" -- A new variable city is created and since person.city is undefined, city is equal to the default value provided \"Paris\".\r\n```\r\n\r\n**Note :** In ```const { age } = person;```, the brackets after *const* keyword are not used to declare an object nor a block but is the *destructuring* syntax.\r\n\r\n- Function parameters\r\n\r\n*Destructuring* is often used to destructure objects parameters in functions.\r\n\r\nWithout destructuring\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nIn destructuring the object parameter *person*, we get a more concise function:\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { // we create firstName and lastName variables by destructuring person parameter\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nDestructuring is even more pleasant to use with [arrow functions](#arrow_func_concept):\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- Array\r\n\r\nLet's consider the following array:\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\nWithout destructuring\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\nWith destructuring\r\n\r\n```js\r\nconst [x, y] = myArray; // That's it !\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n#### Useful resources\r\n\r\n- [ES6 Features - Destructuring Assignment](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)\r\n\r\n### Array methods - map / filter / reduce\r\n\r\n*Map*, *filter* and *reduce* are array methods that are coming from a programming paradigm named [*functional programming*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0).\r\n\r\nTo sum it up:\r\n\r\n- **Array.prototype.map()** takes an array, does something on its elements and returns an array with the transformed elements.\r\n- **Array.prototype.filter()** takes an array, decides element by element if it should keep it or not and returns an array with the kept elements only\r\n- **Array.prototype.reduce()** takes an array and aggregates the elements into a single value (which is returned)\r\n\r\nI recommend to use them as much as possible in following the principles of functional programming because they are composable, concise and elegant.\r\n\r\nWith those three methods, you can avoid the use of *for* and *forEach* loops in most situations. When you are tempted to do a *for* loop, try to do it with *map*, *filter* and *reduce* composed. You might struggle to do it at first because it requires you to learn a new way of thinking, but once you've got it things get easier.\r\n\r\n#### Sample code\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // 21\r\n```\r\n\r\nCompute total grade sum for students with grades 10 or above by composing map, filter and reduce:\r\n\r\n```js\r\nconst students = [\r\n  { name: \"Nick\", grade: 10 },\r\n  { name: \"John\", grade: 15 },\r\n  { name: \"Julia\", grade: 19 },\r\n  { name: \"Nathalie\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // we map the students array to an array of their grades\r\n  .filter(grade => grade >= 10) // we filter the grades array to keep those 10 or above\r\n  .reduce((prev, next) => prev + next, 0); // we sum all the grades 10 or above one by one\r\n\r\nconsole.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie below 10 is ignored\r\n```\r\n\r\n#### Explanation\r\n\r\nLet's consider the following array of numbers for our examples:\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n##### Array.prototype.map()\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\nWhat's happening here? We are using .map on the *numbers* array, the map is iterating on each element of the array and passes it to our function. The goal of the function is to produce and return a new value from the one passed so that map can replace it.\r\n\r\nLet's extract this function to make it more clear, just for this once:\r\n\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n**Note** : You will frequently encounter this method used in combination with [arrow functions](#-arrow-function)\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(n => n * 2);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n```numbers.map(doubleN)``` produces ```[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]``` which is equal to ```[0, 2, 4, 6, 8, 10, 12]```.\r\n\r\n> **Note:** If you do not need to return a new array and just want to do a loop that has side effects, you might just want to use a for / forEach loop instead of a map.\r\n\r\n##### Array.prototype.filter()\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // true if \"n\" is par, false if \"n\" isn't\r\n});\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\n**Note** : You will frequently encounter this method used in combination with [arrow functions](#-arrow-function)\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0);\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\nWe are using .filter on the *numbers* array, filter is iterating on each element of the array and passes it to our function. The goal of the function is to return a boolean that will determine whether the current value will be kept or not. Filter then returns the array with only the kept values.\r\n\r\n##### Array.prototype.reduce()\r\n\r\nThe reduce method goal is to *reduce* all elements of the array it iterates on into a single value. How it aggregates those elements is up to you.\r\n\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n  0 // accumulator variable value at first iteration step\r\n);\r\n\r\nconsole.log(sum) // 21\r\n```\r\n\r\n**Note** : You will frequently encounter this method used in combination with [arrow functions](#-arrow-function)\r\n\r\n```js\r\nconst sum = numbers.reduce((acc, n) => acc + n, 0);\r\nconsole.log(sum) // 21\r\n```\r\n\r\nJust like for .map and .filter methods, .reduce is applied on an array and takes a function as the first parameter.\r\n\r\nThis time though, there are changes:\r\n\r\n- .reduce takes two parameters\r\n\r\nThe first parameter is a function that will be called at each iteration step.\r\n\r\nThe second parameter is the value of the accumulator variable (*acc* here) at the first iteration step (read next point to understand).\r\n\r\n- Function parameters\r\n\r\nThe function you pass as the first parameter of .reduce takes two parameters. The first one (*acc* here) is the accumulator variable, whereas the second parameter (*n*) is the current element.\r\n\r\nThe accumulator variable is equal to the return value of your function at the **previous** iteration step. At the first step of the iteration, *acc* is equal to the value you passed as .reduce second parameter.\r\n\r\n###### At first iteration step\r\n\r\n```acc = 0``` because we passed in 0 as the second parameter for reduce\r\n\r\n```n = 0``` first element of the *number* array\r\n\r\nFunction returns *acc* + *n* --> 0 + 0 --> 0\r\n\r\n###### At second iteration step\r\n\r\n```acc = 0``` because it's the value the function returned at the previous iteration step\r\n\r\n```n = 1``` second element of the *number* array\r\n\r\nFunction returns *acc* + *n* --> 0 + 1 --> 1\r\n\r\n###### At third iteration step\r\n\r\n```acc = 1``` because it's the value the function returned at the previous iteration step\r\n\r\n```n = 2``` third element of the *number* array\r\n\r\nFunction returns *acc* + *n* --> 1 + 2 --> 3\r\n\r\n###### At fourth iteration step\r\n\r\n```acc = 3``` because it's the value the function returned at the previous iteration step\r\n\r\n```n = 3``` fourth element of the *number* array\r\n\r\nFunction returns *acc* + *n* --> 3 + 3 --> 6\r\n\r\n###### [...] At last iteration step\r\n\r\n```acc = 15``` because it's the value the function returned at the previous iteration step\r\n\r\n```n = 6``` last element of the *number* array\r\n\r\nFunction returns *acc* + *n* --> 15 + 6 --> 21\r\n\r\nAs it is the last iteration step, **.reduce** returns 21.\r\n\r\n#### External Resource\r\n\r\n- [Understanding map / filter / reduce in JS](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464)\r\n\r\n### Spread operator \"...\"\r\n\r\nThe spread operator ```...``` has been introduced with ES2015 and is used to expand elements of an iterable (like an array) into places where multiple elements can fit.\r\n\r\n#### Sample code\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x);\r\n  console.log(y);\r\n  console.log(params)\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n#### Explanation\r\n\r\n##### In iterables (like arrays)\r\n\r\nIf we have the two following arrays:\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\n\r\n*arr2* the first element is an array because *arr1* is injected as is into *arr2*. But what we want is *arr2* to be an array of letters. To do so, we can *spread* the elements of *arr1* into *arr2*.\r\n\r\nWith spread operator\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n##### Function rest parameter\r\n\r\nIn function parameters, we can use the rest operator to inject parameters into an array we can loop in. There is already an **arguments** object bound to every function that is equal to an array of all the parameters passed into the function.\r\n\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\n\r\nmyFunc(\"Nick\", \"Anderson\", 10, 12, 6);\r\n// \"Nick\"\r\n// \"Anderson\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\n\r\nBut let's say that we want this function to create a new student with its grades and with its average grade. Wouldn't it be more convenient to extract the first two parameters into two separate variables, and then have all the grades in an array we can iterate over?\r\n\r\nThat's exactly what the rest operator allows us to do!\r\n\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  // firstName = \"Nick\"\r\n  // lastName = \"Anderson\"\r\n  // [10, 12, 6] -- \"...\" takes all other parameters passed and creates a \"grades\" array variable that contains them\r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // computes average grade from grades\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Nick\", \"Anderson\", 10, 12, 6);\r\nconsole.log(student);\r\n// {\r\n//   firstName: \"Nick\",\r\n//   lastName: \"Anderson\",\r\n//   grades: [10, 12, 6],\r\n//   avgGrade: 9,33\r\n// }\r\n```\r\n\r\n> **Note:** createStudent function is bad because we don't check if grades.length exists or is different from 0. But it's easier to read this way, so I didn't handle this case.\r\n\r\n##### Object properties spreading\r\n\r\nFor this one, I recommend you read previous explanations about the rest operator on iterables and function parameters.\r\n\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // object destructuring here\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\n// z is the rest of the object destructured: myObj object minus x and y properties destructured\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// Here z object properties are spread into n\r\n```\r\n\r\n#### External resources\r\n\r\n- [TC39 - Object rest/spread](https://github.com/tc39/proposal-object-rest-spread)\r\n- [Spread operator introduction - WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md)\r\n- [JavaScript & the spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca)\r\n- [6 Great uses of the spread operator](https://davidwalsh.name/spread-operator)\r\n\r\n### Object property shorthand\r\n\r\nWhen assigning a variable to an object property, if the variable name is equal to the property name, you can do the following:\r\n\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // 10\r\n```\r\n\r\n#### Explanation\r\n\r\nUsually (pre-ES2015) when you declare a new *object literal* and want to use variables as object properties values, you would write this kind of code:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // assigning x variable value to myObj.x\r\n  y: y // assigning y variable value to myObj.y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\nAs you can see, this is quite repetitive because the properties name of myObj are the same as the variable names you want to assign to those properties.\r\n\r\nWith ES2015, when the variable name is the same as the property name, you can do this shorthand:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n#### External resources\r\n\r\n- [Property shorthand - ES6 Features](http://es6-features.org/#PropertyShorthand)\r\n\r\n### Promises\r\n\r\nA promise is an object which can be returned synchronously from an asynchronous function ([ref](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0)).\r\n\r\nPromises can be used to avoid [callback hell](http://callbackhell.com/), and they are more and more frequently encountered in modern JavaScript projects.\r\n\r\n#### Sample code\r\n\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n    .done(posts => res(posts))\r\n    .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n#### Explanation\r\n\r\nWhen you do an *Ajax request* the response is not synchronous because you want a resource that takes some time to come. It even may never come if the resource you have requested is unavailable for some reason (404).\r\n\r\nTo handle that kind of situation, ES2015 has given us *promises*. Promises can have three different states:\r\n\r\n- Pending\r\n- Fulfilled\r\n- Rejected\r\n\r\nLet's say we want to use promises to handle an Ajax request to fetch the resource X.\r\n\r\n##### Create the promise\r\n\r\nWe firstly are going to create a promise. We will use the jQuery get method to do our Ajax request to X.\r\n\r\n```js\r\nconst xFetcherPromise = new Promise( // Create promise using \"new\" keyword and store it into a variable\r\n  function(resolve, reject) { // Promise constructor takes a function parameter which has resolve and reject parameters itself\r\n    $.get(\"X\") // Launch the Ajax request\r\n      .done(function(X) { // Once the request is done...\r\n        resolve(X); // ... resolve the promise with the X value as parameter\r\n      })\r\n      .fail(function(error) { // If the request has failed...\r\n        reject(error); // ... reject the promise with the error as parameter\r\n      });\r\n  }\r\n)\r\n```\r\n\r\nAs seen in the above sample, the Promise object takes an *executor* function which takes two parameters **resolve** and **reject**. Those parameters are functions which when called are going to move the promise *pending* state to respectively a *fulfilled* and *rejected* state.\r\n\r\nThe promise is in pending state after instance creation and its *executor* function is executed immediately. Once one of the function *resolve* or *reject* is called in the *executor* function, the promise will call its associated handlers.\r\n\r\n##### Promise handlers usage\r\n\r\nTo get the promise result (or error), we must attach to it handlers by doing the following:\r\n\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err)\r\n  })\r\n```\r\n\r\nIf the promise succeeds, *resolve* is executed and the function passed as ```.then``` parameter is executed.\r\n\r\nIf it fails, *reject* is executed and the function passed as ```.catch``` parameter is executed.\r\n\r\n> **Note :** If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Description)\r\n\r\n#### External Resources\r\n\r\n- [JavaScript Promises for dummies - Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies)\r\n- [JavaScript Promise API - David Walsh](https://davidwalsh.name/promises)\r\n- [Using promises - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\r\n- [What is a promise - Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)\r\n- [JavaScript Promises: an Introduction - Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises)\r\n- [Promise documentation - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\r\n\r\n### Template literals\r\n\r\nTemplate literals is an [*expression interpolation*](https://en.wikipedia.org/wiki/String_interpolation) for single and multiple-line strings.\r\n\r\nIn other words, it is a new string syntax in which you can conveniently use any JavaScript expressions (variables for instance).\r\n\r\n#### Sample code\r\n\r\n```js\r\nconst name = \"Nick\";\r\n`Hello ${name}, the following expression is equal to four : ${2+2}`;\r\n\r\n// Hello Nick, the following expression is equal to four: 4\r\n```\r\n\r\n#### External resources\r\n\r\n- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)\r\n- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)\r\n\r\n### Tagged template literals\r\n\r\nTemplate tags are *functions that can be prefixed to a [template literal](#template-literals)*. When a function is called this way, the first parameter is an array of the *strings* that appear between the template's interpolated variables, and the subsequent parameters are the interpolated values. Use a spread operator `...` to capture all of them. [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals).\r\n\r\n> **Note :** A famous library named [styled-components](https://www.styled-components.com/) heavily relies on this feature.\r\n\r\nBelow is a toy example on how they work.\r\n```js\r\nfunction highlight(strings, ...values) {\r\n  const interpolation = strings.reduce((prev, current) => {\r\n    return prev + current + (values.length ? \"<mark>\" + values.shift() + \"</mark>\" : \"\");\r\n  }, \"\");\r\n\r\n  return interpolation;\r\n}\r\n\r\nconst condiment = \"jam\";\r\nconst meal = \"toast\";\r\n\r\nhighlight`I like ${condiment} on ${meal}.`;\r\n// \"I like <mark>jam</mark> on <mark>toast</mark>.\"\r\n```\r\n\r\nA more interesting example:\r\n```js\r\nfunction comma(strings, ...values) {\r\n  return strings.reduce((prev, next) => {\r\n    let value = values.shift() || [];\r\n    value = value.join(\", \");\r\n    return prev + next + value;\r\n  }, \"\");\r\n}\r\n\r\nconst snacks = ['apples', 'bananas', 'cherries'];\r\ncomma`I like ${snacks} to snack on.`;\r\n// \"I like apples, bananas, cherries to snack on.\"\r\n```\r\n\r\n#### External resources\r\n- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)\r\n- [Library of common template tags](https://github.com/declandewet/common-tags)\r\n\r\n### Imports / Exports\r\n\r\nES6 modules are used to access variables or functions in a module explicitly exported by the modules it imports.\r\n\r\nI highly recommend to take a look at MDN resources on import/export (see external resources below), it is both straightforward and complete.\r\n\r\n#### Explanation with sample code\r\n\r\n##### Named exports\r\n\r\nNamed exports are used to export several values from a module.\r\n\r\n> **Note :** You can only name-export [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen) that have a name.\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js'; // Named import -- destructuring-like syntax\r\nconsole.log(pi) // 3.14\r\nconsole.log(exp) // 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js'; // Inject all exported values into constants variable\r\nconsole.log(constants.pi) // 3.14\r\nconsole.log(constants.exp) // 2.7\r\n```\r\n\r\nWhile named imports looks like *destructuring*, they have a different syntax and are not the same. They don't support default values nor *deep* destructuring.\r\n\r\nBesides, you can do aliases but the syntax is different from the one used in destructuring:\r\n\r\n```js\r\nimport { foo as bar } from 'myFile.js'; // foo is imported and injected into a new bar variable\r\n```\r\n\r\n##### Default import / export\r\n\r\nConcerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is considered the \"main\" exported value since it will be the simplest to import. [Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Description)\r\n\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n// Default export, independently from its name, is automatically injected into number variable;\r\nconsole.log(number) // 42\r\n```\r\n\r\nFunction exporting:\r\n\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // 3\r\n```\r\n\r\n#### External resources\r\n\r\n- [ES6 Modules in bulletpoints](https://ponyfoo.com/articles/es6#modules)\r\n- [Export - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\r\n- [Import - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/)\r\n- [Destructuring special case - import statements](https://ponyfoo.com/articles/es6-destructuring-in-depth#special-case-import-statements)\r\n- [Misunderstanding ES6 Modules - Kent C. Dodds](https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0)\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript)\r\n\r\n### <a name=\"this_def\"></a> JavaScript *this*\r\n\r\n*this* operator behaves differently than in other languages and is in most cases determined by how a function is called. ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)).\r\n\r\nThis notion is having many subtleties and being quite hard, I highly suggest you to deep dive in the external resources below. Thus, I will provide what I personally have in mind to determine what *this* is equal to. I have learned this tip from [this article written by Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/).\r\n\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// After each statement, you find the value of *this* in myFunc\r\n\r\nmyFunc.call(\"myString\", \"hello\") // \"myString\" -- first .call parameter value is injected into *this*\r\n\r\n// In non-strict-mode\r\nmyFunc(\"hello\") // window -- myFunc() is syntax sugar for myFunc.call(window, \"hello\")\r\n\r\n// In strict-mode\r\nmyFunc(\"hello\") // undefined -- myFunc() is syntax sugar for myFunc.call(undefined, \"hello\")\r\n```\r\n\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\") // person Object -- first call parameter is injected into *this*\r\nperson.myFunc(\"test\") // person Object -- person.myFunc() is syntax sugar for person.myFunc.call(person, \"test\")\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"hello\") // Creates a new function in which we inject \"hello\" in *this* value\r\nperson.myFunc(\"test\") // person Object -- The bind method has no effect on the original method\r\nmyBoundFunc(\"test\") // \"hello\" -- myBoundFunc is person.myFunc with \"hello\" bound to *this*\r\n```\r\n\r\n#### External resources\r\n\r\n- [Understanding JavaScript Function Invocation and \"this\" - Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)\r\n- [JavaScript this - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\r\n\r\n### Class\r\n\r\nJavaScript is a [prototype-based](https://en.wikipedia.org/wiki/Prototype-based_programming) language (whereas Java is [class-based](https://en.wikipedia.org/wiki/Class-based_programming) language, for instance). ES6 has introduced JavaScript classes which are meant to be a syntactic sugar for prototype-based inheritance and **not** a new class-based inheritance model ([ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)).\r\n\r\nThe word *class* is indeed error prone if you are familiar with classes in other languages. If you do, avoid assuming how JavaScript classes work on this basis and consider it an entirely different notion.\r\n\r\nSince this document is not an attempt to teach you the language from the ground up, I will believe you know what prototypes are and how they behave. If you do not, see the external resouces listed below the sample code.\r\n\r\n#### Samples\r\n\r\nBefore ES6, prototype syntax:\r\n\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n}\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n}\r\n```\r\n\r\nWith ES6 class syntax:\r\n\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return `Hello, my name is ${this.name} and I am ${this.age}`;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Manu\", 23);\r\nconsole.log(myPerson.age) // 23\r\nconsole.log(myPerson.stringSentence()) // \"Hello, my name is Manu and I'm 23\r\n```\r\n\r\n#### External resources\r\n\r\nFor prototype understanding:\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\nFor classes understanding:\r\n\r\n- [ES6 Classes in Depth - Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features - Classes](http://es6-features.org/#ClassDefinition)\r\n- [JavaScript Classes - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\r\n\r\n### `Extends` and `super` keywords\r\n\r\nThe `extends` keyword is used in class declarations or class expressions to create a class which is a child of another class ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)). The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones.\r\n\r\nThe `super` keyword is used to call functions on an object's parent, including its constructor.\r\n\r\n- `super` keyword must be used before the `this` keyword is used in constructor\r\n- Invoking `super()` calls the parent class constructor. If you want to pass some arguments in a class's constructor to its parent's constructor, you call it with `super(arguments)`.\r\n- If the parent class have a method (even static) called `X`, you can use `super.X()` to call it in a child class.\r\n\r\n#### Sample Code\r\n\r\n```js\r\nclass Polygon {\r\n  constructor(height, width) {\r\n    this.name = 'Polygon';\r\n    this.height = height;\r\n    this.width = width;\r\n  }\r\n\r\n  getHelloPhrase() {\r\n    return `Hi, I am a ${this.name}`;\r\n  }\r\n}\r\n\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    // Here, it calls the parent class' constructor with lengths\r\n    // provided for the Polygon's width and height\r\n    super(length, length);\r\n    // Note: In derived classes, super() must be called before you\r\n    // can use 'this'. Leaving this out will cause a reference error.\r\n    this.name = 'Square';\r\n    this.length = length;\r\n  }\r\n\r\n  getCustomHelloPhrase() {\r\n    const polygonPhrase = super.getHelloPhrase(); // accessing parent method with super.X() syntax\r\n    return `${polygonPhrase} with a length of ${this.length}`;\r\n  }\r\n\r\n  get area() {\r\n    return this.height * this.width;\r\n  }\r\n}\r\n\r\nconst mySquare = new Square(10);\r\nconsole.log(mySquare.area) // 100\r\nconsole.log(mySquare.getHelloPhrase()) // 'Hi, I am a Square' -- Square inherits from Polygon and has access to its methods\r\nconsole.log(mySquare.getCustomHelloPhrase()) // 'Hi, I am a Square with a length of 10'\r\n```\r\n\r\n**Note :** If we had tried to use `this` before calling `super()` in Square class, a ReferenceError would have been raised:\r\n\r\n```js\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    this.height; // ReferenceError, super needs to be called first!\r\n\r\n    // Here, it calls the parent class' constructor with lengths\r\n    // provided for the Polygon's width and height\r\n    super(length, length);\r\n\r\n    // Note: In derived classes, super() must be called before you\r\n    // can use 'this'. Leaving this out will cause a reference error.\r\n    this.name = 'Square';\r\n  }\r\n}\r\n```\r\n\r\n#### External Resources\r\n\r\n- [Extends - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)\r\n- [Super operator - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super)\r\n- [Inheritance - MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance)\r\n\r\n### Async Await\r\n\r\nIn addition to [Promises](#promises), there is a new syntax you might encounter to handle asynchronous code named *async / await*.\r\n\r\nThe purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises. Async functions *always* return a Promise. ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function))\r\n\r\n> **Note :** You must understand what promises are and how they work before trying to understand async / await since they rely on it.\r\n\r\n> **Note 2:** [*await* must be used in an *async* function](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0), which means that you can't use await in the top level of our code since that is not inside an async function.\r\n\r\n#### Sample code\r\n\r\n```js\r\nasync function getGithubUser(username) { // async keyword allows usage of await in the function and means function returns a promise\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Execution is paused here until the Promise returned by fetch is resolved\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user)) // logging user response - cannot use await syntax since this code isn't in async function\r\n  .catch(err => console.log(err)); // if an error is thrown in our async function, we will catch it here\r\n```\r\n\r\n#### Explanation with sample code\r\n\r\n*Async / Await* is built on promises but they allow a more imperative style of code.\r\n\r\nThe *async* operator marks a function as asynchronous and will always return a *Promise*. You can use the *await* operator in an *async* function to pause execution on that line until the returned Promise from the expression either resolves or rejects.\r\n\r\n```js\r\nasync function myFunc() {\r\n  // we can use await operator because this function is async\r\n  return \"hello world\";\r\n}\r\n\r\nmyFunc().then(msg => console.log(msg)) // \"hello world\" -- myFunc's return value is turned into a promise because of async operator\r\n```\r\n\r\nWhen the *return* statement of an async function is reached, the Promise is fulfilled with the value returned. If an error is thrown inside an async function, the Promise state will turn to *rejected*. If no value is returned from an async function, a Promise is still returned and resolves with no value when execution of the async function is complete.\r\n\r\n*await* operator is used to wait for a *Promise* to be fulfilled and can only be used inside an *async* function body. When encountered, the code execution is paused until the promise is fulfilled.\r\n\r\n> **Note :** *fetch* is a function that returns a Promise that allows to do an AJAX request\r\n\r\nLet's see how we could fetch a github user with promises first:\r\n\r\n```js\r\nfunction getGithubUser(username) {\r\n  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\nHere's the *async / await* equivalent:\r\n\r\n```js\r\nasync function getGithubUser(username) { // promise + await keyword usage allowed\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Execution stops here until fetch promise is fulfilled\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n*async / await* syntax is particularly convenient when you need to chain promises that are interdependent.\r\n\r\nFor instance, if you need to get a token in order to be able to fetch a blog post on a database and then the author informations:\r\n\r\n> **Note :** *await* expressions needs to be wrapped in parentheses to call its resolved value's methods and properties on the same line.\r\n\r\n```js\r\nasync function fetchPostById(postId) {\r\n  const token = (await fetch('token_url')).json().token;\r\n  const post = (await fetch(`/posts/${postId}?token=${token}`)).json();\r\n  const author = (await fetch(`/users/${post.authorId}`)).json();\r\n\r\n  post.author = author;\r\n  return post;\r\n}\r\n\r\nfetchPostById('gzIrzeo64')\r\n  .then(post => console.log(post))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n##### Error handling\r\n\r\nUnless we add *try / catch* blocks around *await* expressions, uncaught exceptions – regardless of whether they were thrown in the body of your *async* function or while it’s suspended during *await* – will reject the promise returned by the *async* function. Using the `throw` statement in an async function is the same as returning a Promise that rejects. [(Ref: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).\r\n\r\n> **Note :** Promises behave the same!\r\n\r\nWith promises, here is how you would handle the error chain:\r\n\r\n```js\r\nfunction getUser() { // This promise will be rejected!\r\n  return new Promise((res, rej) => rej(\"User not found !\"));\r\n}\r\n\r\nfunction getAvatarByUsername(userId) {\r\n  return getUser(userId).then(user => user.avatar);\r\n}\r\n\r\nfunction getUserAvatar(username) {\r\n  return getAvatarByUsername(username).then(avatar => ({ username, avatar }));\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\nThe equivalent with *async / await*:\r\n\r\n```js\r\nasync function getUser() { // The returned promise will be rejected!\r\n  throw \"User not found !\";\r\n}\r\n\r\nasync function getAvatarByUsername(userId) => {\r\n  const user = await getUser(userId);\r\n  return user.avatar;\r\n}\r\n\r\nasync function getUserAvatar(username) {\r\n  var avatar = await getAvatarByUsername(username);\r\n  return { username, avatar };\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\n#### External resources\r\n\r\n- [Async/Await - JavaScript.Info](https://javascript.info/async-await)\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/)\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9)\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits)\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n- [Async Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\r\n- [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\r\n- [Using async / await in express with node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n\r\n### Truthy / Falsy\r\n\r\nIn JavaScript, a truthy or falsy value is a value that is being casted into a boolean when evaluated in a boolean context. An example of boolean context would be the evaluation of an ```if``` condition:\r\n\r\nEvery value will be casted to ```true``` unless they are equal to:\r\n\r\n- ```false```\r\n- ```0```\r\n- ```\"\"``` (empty string)\r\n- ```null```\r\n- ```undefined```\r\n- ```NaN```\r\n\r\nHere are examples of *boolean context*:\r\n\r\n- ```if``` condition evaluation\r\n\r\n```js\r\nif (myVar) {}\r\n```\r\n\r\n```myVar``` can be any [first-class citizen](https://en.wikipedia.org/wiki/First-class_citizen) (variable, function, boolean) but it will be casted into a boolean because it's evaluated in a boolean context.\r\n\r\n- After logical **NOT** ```!``` operator\r\n\r\nThis operator returns false if its single operand can be converted to true; otherwise, returns true.\r\n\r\n```js\r\n!0 // true -- 0 is falsy so it returns true\r\n!!0 // false -- 0 is falsy so !0 returns true so !(!0) returns false\r\n!!\"\" // false -- empty string is falsy so NOT (NOT false) equals false\r\n```\r\n\r\n- With the *Boolean* object constructor\r\n\r\n```js\r\nnew Boolean(0) // false\r\nnew Boolean(1) // true\r\n```\r\n\r\n- In a ternary evaluation\r\n\r\n```js\r\nmyVar ? \"truthy\" : \"falsy\"\r\n```\r\n\r\nmyVar is evaluated in a boolean context.\r\n\r\nBe careful when comparing 2 values. The object values (that should be cast to true) is **not** being casted to Boolean but it forced to convert into a primitive value one using [ToPrimitives specification](http://javascript.info/object-toprimitive). Internally, when an object is compared to Boolean value like `[] == true`, it does `[].toString() == true` so...\r\n\r\n```js\r\nlet a = [] == true // a is false since [].toString() give \"\" back.\r\nlet b = [1] == true // b is true since [1].toString() give \"1\" back.\r\nlet c = [2] == true // c is false since [2].toString() give \"2\" back.\r\n```\r\n\r\n#### External resources\r\n\r\n- [Truthy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)\r\n- [Falsy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)\r\n- [Truthy and Falsy values in JS - Josh Clanton](http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html)\r\n\r\n### Anamorphisms and Catamorphisms\r\n\r\n#### Anamorphisms\r\n\r\nAnamorphisms are functions that map from some object to a more complex structure containing the type of the object. It is the process of *unfolding* a simple structure into a more complex one. Consider unfolding an integer to a list of integers. The integer is our initial object and the list of integers is the more complex structure.\r\n\r\n**Sample code**\r\n\r\n```js\r\nfunction downToOne(n) {\r\n  const list = [];\r\n\r\n  for (let i = n; i > 0; --i) {\r\n    list.push(i);\r\n  }\r\n\r\n  return list;\r\n}\r\n\r\ndownToOne(5)\r\n  //=> [ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\n#### Catamorphisms\r\n\r\nCatamorphisms are the opposite of Anamorphisms, in that they take objects of more complex structure and *fold* them into simpler structures. Take the following example `product` which take a list of integers and returns a single integer.\r\n\r\n**Sample code**\r\n\r\n```js\r\nfunction product(list) {\r\n  let product = 1;\r\n\r\n  for (const n of list) {\r\n    product = product * n;\r\n  }\r\n\r\n  return product;\r\n}\r\n\r\nproduct(downToOne(5)) // 120\r\n```\r\n\r\n#### External resources\r\n\r\n* [Anamorphisms in JavaScript](http://raganwald.com/2016/11/30/anamorphisms-in-javascript.html)\r\n* [Anamorphism](https://en.wikipedia.org/wiki/Anamorphism)\r\n* [Catamorphism](https://en.wikipedia.org/wiki/Catamorphism)\r\n\r\n### Generators\r\n\r\nAnother way to write the `downToOne` function is to use a Generator. To instantiate a `Generator` object, one must use the `function *` declaration. Generators are functions that can be exited and later re-entered with its context (variable bindings) saved across re-entrances.\r\n\r\nFor example, the `downToOne` function above can be rewritten as:\r\n\r\n```js\r\nfunction * downToOne(n) {\r\n  for (let i = n; i > 0; --i) {\r\n    yield i;\r\n  }\r\n}\r\n\r\n[...downToOne(5)] // [ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\nGenerators return an iterable object. When the iterator's `next()` function is called, it is executed until the first `yield` expression, which specifies the value to be returned from the iterator or with `yield*`, which delegates to another generator function. When a `return` expression is called in the generator, it will mark the generator as done and pass back as the return value. Further calls to `next()` will not return any new values.\r\n\r\n**Sample code**\r\n\r\n```js\r\n// Yield Example\r\nfunction * idMaker() {\r\n  var index = 0;\r\n  while (index < 2) {\r\n    yield index;\r\n    index = index + 1;\r\n  }\r\n}\r\n\r\nvar gen = idMaker();\r\n\r\ngen.next().value; // 0\r\ngen.next().value; // 1\r\ngen.next().value; // undefined\r\n```\r\n\r\nThe `yield*` expression enables a generator to call another generator function during iteration.\r\n\r\n```js\r\n// Yield * Example\r\nfunction * genB(i) {\r\n  yield i + 1;\r\n  yield i + 2;\r\n  yield i + 3;\r\n}\r\n\r\nfunction * genA(i) {\r\n  yield i;\r\n  yield* genB(i);\r\n  yield i + 10;\r\n}\r\n\r\nvar gen = genA(10);\r\n\r\ngen.next().value; // 10\r\ngen.next().value; // 11\r\ngen.next().value; // 12\r\ngen.next().value; // 13\r\ngen.next().value; // 20\r\n```\r\n\r\n```js\r\n// Generator Return Example\r\nfunction* yieldAndReturn() {\r\n  yield \"Y\";\r\n  return \"R\";\r\n  yield \"unreachable\";\r\n}\r\n\r\nvar gen = yieldAndReturn()\r\ngen.next(); // { value: \"Y\", done: false }\r\ngen.next(); // { value: \"R\", done: true }\r\ngen.next(); // { value: undefined, done: true }\r\n```\r\n\r\n#### External resources\r\n\r\n* [Mozilla MDN Web Docs, Iterators and Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators)\r\n\r\n### Static Methods\r\n\r\n#### Short explanation\r\n\r\nThe `static` keyword is used in classes to declare static methods. Static methods are functions in a class that belongs to the class object and are not available to any instance of that class.\r\n\r\n#### Sample code\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n}\r\n\r\n// Note that we did not have to create an instance of the Repo class\r\nconsole.log(Repo.getName()) // Repo name is modern-js-cheatsheet\r\n\r\nlet r = new Repo();\r\nconsole.log(r.getName()) // Uncaught TypeError: r.getName is not a function\r\n```\r\n\r\n#### Detailed explanation\r\n\r\nStatic methods can be called within another static method by using the `this` keyword, this doesn't work for non-static methods though. Non-static methods cannot directly access static methods using the `this` keyword.\r\n\r\n##### Calling other static methods from a static method.\r\n\r\nTo call a static method from another static method, the `this` keyword can be used like so;\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  static modifyName(){\r\n    return this.getName() + '-added-this'\r\n  }\r\n}\r\n\r\nconsole.log(Repo.modifyName()) // Repo name is modern-js-cheatsheet-added-this\r\n```\r\n\r\n##### Calling static methods from non-static methods.\r\n\r\nNon-static methods can call static methods in 2 ways;\r\n1. ###### Using the class name.\r\n\r\nTo get access to a static method from a non-static method we use the class name and call the static method like a property. e.g `ClassName.StaticMethodName`\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    return Repo.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// we need to instantiate the class to use non-static methods\r\nlet r = new Repo()\r\nconsole.log(r.useName()) // Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n2. ###### Using the constructor\r\n\r\nStatic methods can be called as properties on the constructor object.\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    // Calls the static method as a property of the constructor\r\n    return this.constructor.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// we need to instantiate the class to use non-static methods\r\nlet r = new Repo()\r\nconsole.log(r.useName()) // Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n#### External resources\r\n- [static keyword- MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)\r\n- [Static Methods- Javascript.info](https://javascript.info/class#static-methods)\r\n- [Static Members in ES6- OdeToCode](http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx)\r\n\r\n## Glossary\r\n\r\n### <a name=\"scope_def\"></a> Scope\r\n\r\nThe context in which values and expressions are \"visible,\" or can be referenced. If a variable or other expression is not \"in the current scope,\" then it is unavailable for use.\r\n\r\nSource: [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\r\n\r\n### <a name=\"mutation_def\"></a> Variable mutation\r\n\r\nA variable is said to have been mutated when its initial value has changed afterward.\r\n\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // myArray is being mutated\r\n```\r\n\r\nA variable is said to be *immutable* if it can't be mutated.\r\n\r\n[Check MDN Mutable article](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) for more details.\r\n"
  },
  {
    "path": "JavaScript/_config.yml",
    "content": "theme: jekyll-theme-cayman\r\ntitle: Modern JS Cheatsheet\r\n"
  },
  {
    "path": "JavaScript/translations/fr-FR.md",
    "content": "# Modern JavaScript Cheatsheet\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Crédits de l’image: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## Introduction\r\n\r\n### Motivation\r\n\r\nCe document est un condensé de tout ce que vous devriez savoir sur le JavaScript que vous allez rencontrer dans des projets modernes.\r\n\r\nCe guide n’a pas été conçu pour vous apprendre JavaScript à partir de rien, mais pour aider les développeurs ayant des connaissances basiques qui ont des problèmes avec les codebases modernes (ou pour apprendre React, par exemple) à cause des concepts JavaScript utilisés.\r\n\r\nDe plus, je vous donnerai parfois des conseils personnels qui pourraient porter à débat, mais je prendrai le soin de le mentionner lorsque je le ferai.\r\n\r\n> **Note :** La plupart des concepts introduits ici viennent d’une mise à jour du langage JavaScript (ES2015, souvent appelé ES6. Vous pouvez trouver les nouvelles fonctionnalités. ajoutées par cette mise à jour [ici](http://es6-features.org) (ce site est vraiment bien fait !).\r\n\r\n### Ressources complémentaires\r\n\r\nLorsque vous avez de la peine à comprendre une notion, je vous suggère de chercher des réponses dans les ressources suivantes :\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/en-US/search?q=)\r\n- [You don't know JS (livre)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Features with examples](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Javascript Basics for Beginners](https://www.udacity.com/course/javascript-basics--ud804) - a free Udacity course\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) pour trouver des blogs et des ressources spécifiques\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript)\r\n\r\n> **Note :** Presque toutes les ressources externes listées dans ce document sont en anglais, à l’exception des liens menant vers le Mozilla Developer Network (MDN) qui lui est traduit en français.\r\n\r\n## Table des matières\r\n* [Modern JavaScript Cheatsheet](#modern-javascript-cheatsheet)\r\n   * [Introduction](#introduction)\r\n      * [Motivation](#motivation)\r\n      * [Ressources complémentaires](#ressources-complémentaires)\r\n   * [Table des matières](#table-des-matières)\r\n   * [Notions](#notions)\r\n      * [Déclaration des variables : var, const, let](#déclaration-des-variables--var-const-let)\r\n         * [Explication brève](#explication-brève)\r\n         * [Code d’exemple](#code-dexemple)\r\n         * [Explication détaillée](#explication-détaillée)\r\n            * [var](#var)\r\n            * [let](#let)\r\n            * [const](#const)\r\n         * [Ressources externes](#ressources-externes)\r\n      * [<a name=\"user-content-arrow_func_concept\"></a> Fonction fléchée](#-fonction-fléchée)\r\n         * [Code d'exemple](#code-dexemple-1)\r\n         * [Explication détaillée](#explication-détaillée-1)\r\n            * [Concision](#concision)\r\n            * [Référence de <em>this</em>](#référence-de-this)\r\n         * [Ressources utiles](#ressources-utiles)\r\n      * [Valeur par défaut d'un paramètre dans une fonction](#valeur-par-défaut-dun-paramètre-dans-une-fonction)\r\n         * [External resource](#external-resource)\r\n      * [Déstructurer des objets et des tableaux](#déstructurer-des-objets-et-des-tableaux)\r\n         * [Explication avec du code](#explication-avec-du-code)\r\n         * [Ressources utiles](#ressources-utiles-1)\r\n      * [Méthodes de tableau : map / filter / reduce](#méthodes-de-tableau--map--filter--reduce)\r\n         * [Code d'exemple](#code-dexemple-2)\r\n         * [Explication](#explication)\r\n            * [Array.prototype.map()](#arrayprototypemap)\r\n            * [Array.prototype.filter()](#arrayprototypefilter)\r\n            * [Array.prototype.reduce()](#arrayprototypereduce)\r\n               * [À la première étape d'itération](#À-la-première-étape-ditération)\r\n               * [À la deuxième étape d'itération](#À-la-deuxième-étape-ditération)\r\n               * [À la troisième étape d'itération](#À-la-troisième-étape-ditération)\r\n               * [À la quatrième étape d'itération](#À-la-quatrième-étape-ditération)\r\n               * [[...] À la dernière étape d'itération](#-À-la-dernière-étape-ditération)\r\n         * [Ressource externe](#ressource-externe)\r\n      * [Opérateur de décomposition \"...\"](#opérateur-de-décomposition-)\r\n         * [Code d'exemple](#code-dexemple-3)\r\n         * [Explication](#explication-1)\r\n            * [Dans des tableaux (comme des tableaux)](#dans-des-tableaux-comme-des-tableaux)\r\n            * [Paramètre de reste d'une fonction](#paramètre-de-reste-dune-fonction)\r\n            * [Décomposition des propriétés d'un objet](#décomposition-des-propriétés-dun-objet)\r\n         * [Ressources externes](#ressources-externes-1)\r\n      * [Raccourci pour les propriétés d'objet](#raccourci-pour-les-propriétés-dobjet)\r\n         * [Explication](#explication-2)\r\n         * [Ressources externes](#ressources-externes-2)\r\n      * [Promesses](#promesses)\r\n         * [Code d'exemple](#code-dexemple-4)\r\n         * [Explication](#explication-3)\r\n            * [Créer la promesse](#créer-la-promesse)\r\n            * [Utilisation des déclencheurs de promesse](#utilisation-des-déclencheurs-de-promesse)\r\n         * [Ressources externes](#ressources-externes-3)\r\n      * [Littéraux de modèle](#littéraux-de-modèle)\r\n         * [Code d'exemple](#code-dexemple-5)\r\n         * [Ressources externes](#ressources-externes-4)\r\n      * [Littéraux de modèle étiquetés](#littéraux-de-modèle-étiquetés)\r\n         * [Ressources externes](#ressources-externes-5)\r\n      * [Imports / exports](#imports--exports)\r\n         * [Explication avec un code d'exemple](#explication-avec-un-code-dexemple)\r\n            * [Exports nommés](#exports-nommés)\r\n            * [Import/export par défaut](#importexport-par-défaut)\r\n         * [Ressources externes](#ressources-externes-6)\r\n      * [<em>this</em> en JavaScript](#-this-en-javascript)\r\n         * [Ressources externes](#ressources-externes-7)\r\n      * [Classe](#classe)\r\n         * [Exemples](#exemples)\r\n         * [Ressources externes](#ressources-externes-8)\r\n      * [Mots clés extends et <code>super</code>](#mots-clés-extends-et-super)\r\n         * [Code d’exemple](#code-dexemple-6)\r\n         * [Ressources](#ressources)\r\n      * [Async Await](#async-await)\r\n         * [Code d’exemple](#code-dexemple-7)\r\n         * [Explication avec un code d’exemple](#explication-avec-un-code-dexemple-1)\r\n            * [Gestion d’erreur](#gestion-derreur)\r\n         * [Ressources externes](#ressources-externes-9)\r\n      * [Vérité / fausseté](#vérité--fausseté)\r\n         * [Ressources externes](#ressources-externes-10)\r\n      * [Méthodes statiques](#méthodes-statiques)\r\n         * [Explication courte](#explication-courte)\r\n         * [Code d’exemple](#code-dexemple-8)\r\n         * [Explication détaillée](#explication-détaillée-2)\r\n            * [Appeler d’autres méthodes statiques depuis une méthode statique](#appeler-dautres-méthodes-statiques-depuis-une-méthode-statique)\r\n            * [Appeler des méthodes statiques depuis des méthodes non statiques](#appeler-des-méthodes-statiques-depuis-des-méthodes-non-statiques)\r\n               * [En utilisant le nom de la classe](#en-utilisant-le-nom-de-la-classe)\r\n               * [Avec le constructeur](#avec-le-constructeur)\r\n         * [Ressources externes](#ressources-externes-11)\r\n   * [Glossaire](#glossaire)\r\n      * [Portée (<em>scope</em>)](#-portée-scope)\r\n      * [Mutation de variable](#-mutation-de-variable)\r\n\r\n## Notions\r\n\r\n### Déclaration des variables : var, const, let\r\n\r\nEn JavaScript, il y a trois mots-clés disponibles pour déclarer une variable, et chacun a ses différences. Ces mots-clés sont ```var```, ```let``` et ```const```.\r\n\r\n#### Explication brève\r\n\r\nLes variables déclarées avec le mot-clé ```const``` ne peuvent pas être réassignées, alors que celles déclarées avec ```let``` et ```var``` le peuvent.\r\n\r\nJe vous recommande de toujours déclarer vos variables avec ```const``` par défaut, et avec ```let``` si vous avez besoin de la *muter* ou de la réassigner plus tard.\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>Portée</th>\r\n    <th>Réassignable</th>\r\n    <th>Mutable</th>\r\n   <th><a href=\"#tdz_sample\">Temporal Dead Zone</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>const</th>\r\n    <td>Bloc</td>\r\n    <td>Non</td>\r\n    <td><a href=\"#const_mutable_sample\">Oui</a></td>\r\n    <td>Oui</td>\r\n  </tr>\r\n  <tr>\r\n    <th>let</th>\r\n    <td>Bloc</td>\r\n    <td>Oui</td>\r\n    <td>Oui</td>\r\n    <td>Oui</td>\r\n  </tr>\r\n   <tr>\r\n    <th>var</th>\r\n    <td>Fonction</td>\r\n    <td>Oui</td>\r\n    <td>Oui</td>\r\n    <td>Non</td>\r\n  </tr>\r\n</table>\r\n\r\n#### Code d’exemple\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // Déclenchera une erreur, person ne pouvant pas être réassigné\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", le réassignement est permis avec let\r\n```\r\n\r\n#### Explication détaillée\r\n\r\nLa [*portée*](#scope_def) d’une variable définit \"où la variable est disponible dans le code\".\r\n\r\n##### var\r\n\r\nLa portée des variables déclarées avec ```var``` s’étend à la fonction qui la contient, ce qui signifie que lorsqu‘une variable est créée dans une fonction, tout dans cette fonction peut y accéder. De plus, on ne pourra pas accéder à cette variable de l’extérieur de cette fonction. \r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar est accessible à l'intérieur de la fonction\r\n}\r\nconsole.log(myVar); // Émet une ReferenceError, myVar n'est pas accessible en dehors de la fonction\r\n```\r\n\r\nVoici un exemple plus subtil, toujours sur la portée des variables :\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // La portée de myVar s'étendant à toute la fonction, nous venons d'écraser la valeur précédente de myVar (\"Nick\"), qui est devenue \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - les instructions dans le bloc if ont affecté cette valeur\r\n}\r\nconsole.log(myVar); // Produit une ReferenceError, myVar n'étant pas disponible en dehors de la fonction\r\n```\r\n\r\nDe plus, les variables déclarées avec *var* sont déplacées tout en haut de leur portée à l'exécution. Ce comportement est appelé [var hoisting](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/var#La_remontée_de_variables_(hoisting)).\r\n\r\nCe bout de code :\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- aucune erreur produite\r\nvar myVar = 2;\r\n```\r\n\r\nest compris à l'exécution comme :\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- aucune erreur produite\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n```var``` et ```let ``` sont presque identiques, mais les variables déclarées avec ```let```\r\n\r\n- ont leur portée qui est limitée au bloc qui les entoure\r\n- ne sont **pas** accessibles avant d'être assignées\r\n- ne peuvent pas être redéclarées dans la même portée\r\n\r\nObservons l'impact de la nouvelle portée dans l'exemple précédent :\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // la portée de myVar étant limitée au bloc if, nous venons de crééer une nouvelle variable myVar.\r\n    // cette variable n'est pas accessible en dehors du bloc if\r\n    // et est totalement indépendante du premier myVar créé.\r\n  }\r\n  console.log(myVar); // \"Nick\" - les instructions dans le bloc if n'ont PAS affecté cette valeur\r\n}\r\nconsole.log(myVar); // Produit une ReferenceError, myVar n'étant pas disponible en dehors de la fonction\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> Maintenant, observons ce que signifie pour les variables créées avec *let* (et *const*) de ne pas être accessibles avant d'avoir été assignées :\r\n\r\n```js\r\nconsole.log(myVar) // déclenche une ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\nContrairement aux variables *var*, si vous essayez de lire ou d'écrire dans une variable *let* ou *const* avant d'être assignées une erreur se produira. Ce phénomène est souvent appelé [*Temporal dead zone*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) ou *TDZ*.\r\n\r\n> **Note :** Techniquement, les déclarations de variables *let* and *const*sont aussi affectées par le *var hoisting*, mais pas leur assignation. Vu qu'elles sont faite pour ne pas pouvoir être utilisées avant l'assignation, on a l'impression qu'il n'y a pas de *hoisting*, mais il y en a un. Si vous voulez en savoir plus, vous pouvez lire cette [explication très détaillée](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified).\r\n\r\nPar ailleurs, vous ne pouvez pas re-déclarer une variable *let* :\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // Produit une SyntaxError\r\n```\r\n\r\n##### const\r\n\r\nLes variables déclarées avec```const``` se comportent comme des variables *let*, mais elles ne peuvent pas être réassignées.\r\n\r\nPour résumer, les variables *const* :\r\n\r\n- ont leur portée qui est limitée au bloc qui les entoure\r\n- ne sont pas accessibles avant leur assignation\r\n- ne peuvent pas être redéclarées dans la même portée\r\n- ne peuvent pas être réassignées\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // cause une erreur, le réassignement n'est pas permis\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // cause une erreur, la redéclaration n'est pas permise\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> Mais il y a une subtilité : les variables ```const``` ne sont pas [**immutables**](#mutation_def) ! Concrètement, cela signifie que les *objets* et *tableaux* ```const``` **peuvent** être mutées.\r\n\r\nPour les objets :\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // ceci fonctionnera ! la variable person n'est pas complètement réassignée, mais mutée\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // cause une erreur, car le réassignement n'est pas autorisé avec les variables déclarées avec const\r\n```\r\n\r\nPour les tableaux :\r\n```js\r\nconst person = [];\r\nperson.push('John'); // ceci fonctionnera ! la variable person n'est pas complètement réassignée, mais mutée\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"]  // cause une erreur, car le réassignement n'est pas autorisé avec les variables déclarées avec const\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"arrow_func_concept\"></a> Fonction fléchée\r\n\r\nAvec la mise à jour ES6 de JavaScript, nous pouvons utiliser des *fonctions fléchées*, qui sont un autre moyen de déclarer et d'utiliser des fonctions. Voici les bénéfices qu'elles apportent :\r\n\r\n- Plus concis\r\n- *this* se réfère à l'extérieur de la fonction fléchée\r\n- ```return``` implicite\r\n\r\n#### Code d'exemple\r\n\r\n- Concision et retour implicite\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // Manière traditionnelle\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // Même fonction écrite sous forme de fonction fléchée avec un retour implicite\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- Référence de *this*\r\n\r\nDans une fonction fléchée, *this* est égal à la valeur de *this* dans le contexte d'exécution alentour. Basiquement, avec les fonctions fléchées, vous n'êtes plus obligé d'utiliser l'astuce \"that = this\" avant d'appeler une fonction à l'intérieur d'une fonction.\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### Explication détaillée\r\n\r\n##### Concision\r\n\r\nLes fonctions fléchées sont plus concises que les fonctions traditionnelles par plusieurs aspects. Voyons tous les cas possibles :\r\n\r\n- Retour implicite VS explicite\r\n\r\nUn **retour explicite** est une fonction où le mot-clé ```return``` est utilisé dans son corps.\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // cette fonction retourne explicitement x * 2, le mot-clé return est utilisé\r\n  }\r\n```\r\n\r\nDans l'écriture de foncitons traditionnelle, le retour était toujours explicite. Mais avec les fonctions fléchées, vous pouvez faire un *retour implicite* ce qui signifie que vous n'êtes pas obligés d'utiliser le mot-clé *return* pour retourner une valeur.\r\n\r\nPour faire un retour implicite, le code doit être écrit en une ligne.\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // Ce retour est explicite\r\n  }\r\n```\r\n\r\nComme il n'y a qu'un retour de valeur ici, nous pouvons utiliser un retour implicite.\r\n\r\n```js\r\n  const double = (x) => x * 2;\r\n```\r\n\r\nPour ce faire, il nous suffit de **supprimer les accolades** et le mot-clé **return**. C'est pour cette raison qu'on qualifie ce retour d'*implicite* : le mot-clé *return* n'est pas là. mais la fonction va bien retourner ```x * 2```.\r\n\r\n> **Note :** Si votre fonction ne retourne aucune valeur (avec des *effets secondaires*), elle ne fait ni retour implicite ni explicite.\r\n\r\nDe plus, si vous voulez retourner un *objet* vous **devez mettre des parenthèses autour** pour éviter un conflit avec les accolades de bloc :\r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- l'objet est implicitement retourné par la fonction fléchée\r\n```\r\n\r\n- Uniquement un argument\r\n\r\nSi votre fonction ne prend qu'un paramètre, vous pouvez omettre les parenthèses autour. En reprenant un exemple au dessus :\r\n\r\n```js\r\n  const double = (x) => x * 2; // cette fonction fléchée ne prend qu'un paramètre\r\n```\r\n\r\nLes parenthèses autour du paramètre peuvent être évitées :\r\n\r\n```js\r\n  const double = x => x * 2; // cette fonction fléchée ne prend qu'un paramètre\r\n```\r\n\r\n- Pas de paramètres\r\n\r\nLorsqu'une fonction fléchée ne prend aucun paramètre, vous devez obligatoirement mettre des parenthèses pour que la syntaxe soit valide :\r\n\r\n```js\r\n  () => { // avec des parenthèses, tout fonctionne\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // pas de parenthèses, ceci ne fonctionnera pas !\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### Référence de *this*\r\n\r\nPour comprendre cette subtilité des fonctions fléchées, vous devez savoir comment [this](#this_def) fonctionne en JavaScript.\r\n\r\nDans une fonction fléchée, *this* est égal à la valeur de *this* dans le contexte d'exécution alentour. Cela signifie qu'une fonction fléchée ne créée pas de nouveau *this*, mais le prend autour à la place.\r\n\r\nSans une fonction fléchée, pour accéder à une variable présente dans *this* dans une fonction à l'intérieur d'une fonction, vous deviez utiliser l'astuce de *that = this* ou *self = this*.\r\n\r\nPar exemple, voici comment utiliser setTimeout à l'intérieur de myFunc :\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // astuce that = this\r\n  setTimeout(\r\n    function() { // Un nouveau *this* est créé dans la portée de cette fonction\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- voir la déclaration de fonction au-dessus\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\nMais avec une fonction fléchée, *this* est pris de l'extérieur :\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this pris de l'extérieur, signifiant myFunc ici\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### Ressources utiles\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [Fonction fléchées - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Fonctions/Fonctions_fl%C3%A9ch%C3%A9es)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n### Valeur par défaut d'un paramètre dans une fonction\r\n\r\nÀ partir de la mise à jour de JavaScript ES2015, vous pouvez assigner une valeur par défaut à un paramètre de fonction en utilisant la syntaxe suivante\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- aucune valeur n'étant donnée, la valeur par défaut est utilisée\r\nconsole.log(myFunc(5)) // 5 -- une valeur est donnée donc x est égal à 5 dans myFunc\r\n\r\nconsole.log(myFunc(undefined)) // 10 -- la valeur undefined est donnée, donc x est assigné à la valeur par défaut\r\nconsole.log(myFunc(null)) // null -- une valeur (null) étant donnée, voir plus bas pour plus de détails\r\n```\r\n\r\nLe paramètre par défaut est utilisé dans deux et uniquement deux situations :\r\n\r\n- Aucun paramètre n'est fourni\r\n- Le paramèter *undefined* est fourni\r\n\r\nAutrement dit, si vous passez *null* le paramètre par défaut **ne sera pas appliqué**.\r\n\r\n> **Note :** Un assignement de valeur par défaut peut être utilisé avec des paramètres déstructurés également (voyez la notion suivante pour avoir un exemple).\r\n\r\n#### External resource\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Valeurs par défaut des arguments - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Fonctions/Valeurs_par_d%C3%A9faut_des_arguments)\r\n\r\n### Déstructurer des objets et des tableaux\r\n\r\nLa *déstructuration* un moyen pratique de créer de nouvelles variables en extrayant des valeurs des données enregistrées dans des objets ou des tableaux.\r\n\r\nPour nommer quelque cas d'utilisation, la *déstructuration* peut être utilisée pour déstructurer des paramètres de fonction ou *this.props* dans des projets React par exemple.\r\n\r\n#### Explication avec du code\r\n\r\n- Objet\r\n\r\nPrenons l'objet suivant pour tous les exemples\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\nSans déstructuration :\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\nAvec la déstructuration, tout en une ligne :\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // Et voilà !\r\n\r\nconsole.log(age) // 35 -- Une nouvelle variable age est créée et est égale à person.age\r\nconsole.log(first) // \"Nick\" -- Une nouvelle variable first est créée et est égale à person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName existe MAIS la nouvelle variable créée est nommée first\r\nconsole.log(city) // \"Paris\" -- Une nouvelle variable city est créée et comme person.city n'est pas défini, city est égal à la valeur par défaut donnée, à savoir \"Paris\"\r\n```\r\n\r\n**Note :** Dans ```const { age } = person;```, les accolades après le mot-clé *const* ne sont pas utilisées pour déclarer un objet ou un bloc, mais font partie de la syntaxe de *déstructuration*.\r\n\r\n- Paramètres de fonction\r\n\r\nLa *destructuring* est souvent utilisée pour déstructurer les paramètres de fonction sous la forme d'objets.\r\n\r\nSans déstructuration :\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nEn déstructurant le paramètre objet *person*, nous obtenons une fonction plus concise :\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { // nous crééons les variables firstName et lastName en déstructurant le paramètre person\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nLa déstructuration est encore plus agréable à utiliser avec les [fonctions fléchées](#arrow_func_concept) :\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- Tableau\r\n\r\nUtilisons le tableau suivant :\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\nSans la destructuration :\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\nAvec :\r\n\r\n```js\r\nconst [x, y] = myArray; // Et voilà !\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n#### Ressources utiles\r\n\r\n- [ES6 Features - Destructuring Assignment](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)\r\n\r\n### Méthodes de tableau : map / filter / reduce\r\n\r\n*Map*, *filter* et *reduce* sont des méthodes de tableau qui viennent avec un paradigme de programmation appelé la [*programmation fonctionnelle*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0).\r\n\r\nPour résumer :\r\n\r\n- **Array.prototype.map()** prend un tableau, fait quelque chose sur ses éléments et retourne un tableau contenant les éléments transformés.\r\n- **Array.prototype.filter()** prend un tableau, décide élément par élément s'il faut le garder ou non et retourne un tableau contenant uniquement les éléments conservés.\r\n- **Array.prototype.reduce()** prend un tableau et agrège ses éléments en une seule valeur (qui est retournée).\r\n\r\nJe recommande de les utiliser autant que possibles pour suivre les principes de la programmation fonctionelle car ils sont composables, concis et élégants.\r\n\r\nAvec toutes ces méthodes, vous pouvez éviter l'utilisation des boucles *for* et *forEach* dans la plupart des situations. Vous pouvez avoir de la peine au début à les utiliser car ils vous obligent à apprendre une nouvelle façon de penser, mais une fois que vous avez compris comment cela fonctionne tout devient plus facile.\r\n\r\n#### Code d'exemple\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // 21\r\n```\r\n\r\nCalculer la somme des notes (```grades```) des étudiants ayant eu plus que 10 en utilisant map, filter et reduce :\r\n```js\r\nconst students = [\r\n  { name: \"Nick\", grade: 10 },\r\n  { name: \"John\", grade: 15 },\r\n  { name: \"Julia\", grade: 19 },\r\n  { name: \"Nathalie\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // nous transformons le tableau students en un tableau contenant leurs notes\r\n  .filter(grade => grade >= 10) // nous filtrons le tableau des notes pour ne conserver que celles supérieures ou égales à 10\r\n  .reduce((prev, next) => prev + next, 0); // nous additionnons toutes les notes au dessus de 10 une par une\r\n\r\nconsole.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie étant ignorée car sa note est inférieure à 10\r\n```\r\n\r\n#### Explication\r\n\r\nPrenons le tableau de nombres pour nos exemples :\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n##### Array.prototype.map()\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\nQue se passe-t-il ici ? Nous utilisons .map sur le tableau *numbers*, le map itère sur chaque élément du tableau et le passe à notre fonction. Le but de la fonction est de produire et de retourner une nouvelle valeur pour chaque valeur donnée pour que le map puisse la remplacer.\r\n\r\nExtrayons cette fonction pour la rendre plus claire, juste pour cette fois-ci :\r\n\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n```numbers.map(doubleN)``` produit ```[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]``` ce qui est égal à ```[0, 2, 4, 6, 8, 10, 12]```.\r\n\r\n> **Note :** Si vous n'avez pas besoin d'un nouveau tableau et que vous voulant juste avoir une boucle ayant des effets secondaires, vous pourriez juste avoir besoin d'une boucle for / forEach à la place d'un map.\r\n\r\n##### Array.prototype.filter()\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // true si \"n\" est pair, false si \"n\" est impair\r\n});\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\nNous utilisons .filter sur le tableau *numbers* : filter itère sur chaque élément du tableau et le passe à notre fonction. Le but de la fonction est de retourner un booléen qui déterminera si la valeur actuelle sera conservée. Filter retourne ensuite le tableau avec uniquement les valeurs conservées.\r\n\r\n##### Array.prototype.reduce()\r\n\r\nLe but de la méthode reduce est de réduire tous les éléments du tableau sur lequel elle itère à une seule valeur. Vous décidez de la manière dont les éléments sont agrégés.\r\n\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n  0 // valeur de l'accumulateur à la première itération\r\n);\r\n\r\nconsole.log(sum) //21\r\n```\r\n\r\nTout comme pour les méthodes .map et .filter, .reduce est appliqué sur un tableau et prend une fonction en premier paramètre.\r\n\r\nCette fois cependant, il y a des changements :\r\n\r\n- .reduce prend deux paramètres\r\n\r\nLe premier paramètre est une fonction qui sera appelée à chaque étape d'itéraiton.\r\n\r\nLe second paramètre est la valeur de la variable d'accumulation (*acc* ici) à la première étape d'itération (lisez le point suivant pour comprendre).\r\n\r\n- Paramèters de fonction\r\n\r\nLa fonction que vous passez comme premier paramètre de .reduce prend deux paramètres. Le premier (*acc* ici) est la variable d'accumulateur, tandis que le second paramètre (*n*) est l'élément actuel.\r\n\r\nLa variable d'accumulateur est égale à la valeur retournée par votre fonction à l'étape d'itération **précédente**. À la première étape de l'itération, *acc* est égale à la valeur que vous avez passé au second paramètre de .reduce.\r\n\r\n###### À la première étape d'itération\r\n\r\n```acc = 0``` car nous avons passé 0 comme second paramètre à reduce.\r\n\r\n```n = 0``` premier élément du tableau *number*\r\n\r\nLa fonction retourne *acc* + *n* --> 0 + 0 --> 0\r\n\r\n###### À la deuxième étape d'itération\r\n\r\n```acc = 0``` car c'est la valeur retournée par la fonction à l'étape d'itération précédente\r\n\r\n```n = 1``` deuxième élément du tableau *number*\r\n\r\nLa fonction retourne *acc* + *n* --> 0 + 1 --> 1\r\n\r\n###### À la troisième étape d'itération\r\n\r\n```acc = 1``` car c'est la valeur retournée par la fonction à l'étape d'itération précédente\r\n\r\n```n = 2``` troisième élément du tableau *number*\r\n\r\nLa fonction retourne *acc* + *n* --> 1 + 2 --> 3\r\n\r\n###### À la quatrième étape d'itération\r\n\r\n```acc = 3``` car c'est la valeur retournée par la fonction à l'étape d'itération précédente\r\n\r\n```n = 3``` quatrième élément du tableau *number*\r\n\r\nLa fonction retourne *acc* + *n* --> 3 + 3 --> 6\r\n\r\n###### [...] À la dernière étape d'itération\r\n\r\n```acc = 15``` car c'est la valeur retournée par la fonction à l'étape d'itération précédente\r\n\r\n```n = 6``` dernier élément du tableau *number*\r\n\r\nLa fonction retourne *acc* + *n* --> 15 + 6 --> 21\r\n\r\nComme c'est la dernière étape d'itération, **.reduce** retourne 21.\r\n\r\n#### Ressource externe\r\n\r\n- [Understanding map / filter / reduce in JS](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464)\r\n\r\n### Opérateur de décomposition \"...\"\r\n\r\nL'opérateur de décomposition ```...``` existe depuis ES2015 et est utilisé pour décomposer les éléments d'un itérable (comme un tableau) dans des emplacements qui peuvent contenir plusieurs éléments.\r\n\r\n#### Code d'exemple\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x);\r\n  console.log(y);\r\n  console.log(params)\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n#### Explication\r\n\r\n##### Dans des tableaux (comme des tableaux)\r\n\r\nSi nous avons les deux tableaux suivants :\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\n\r\nLe premier élément d'*arr2* est un tableau, car *arr1* est injecté tel quel dans *arr2*. Cependant, nous voulons que *arr2* soit un tableau de lettres. Pour ce faire, nous pouvons *décomposer* les éléments d'*arr1* dans *arr2*.\r\n\r\nAvec l'opérateur de décomposition :\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n##### Paramètre de reste d'une fonction\r\n\r\nDans les paramètres d'une fonction, nous pouvons utiliser l'opérateur de reste pour injecter les paramètres dans un tableau dans lequel nous pouvons faire une bocle. Il existe déjà un objet **arguments** lié à chaque fonction, qui est un tableau contenant tous les paramètres passés à la fonction.\r\n\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\n\r\nmyFunc(\"Nick\", \"Anderson\", 10, 12, 6);\r\n// \"Nick\"\r\n// \"Anderson\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\n\r\nMais imaginons que nous voulons que cette fonction créée un nouvel édudiant avec ses notes et sa note moyenne. Ne serait-il pas plus pratique d'extraire les deux premiers paramètres dans deux variables séparées, et d'avoir les notes dans un tableau sur lequel nous pourrions effectuer une boucle ?\r\n\r\nC'est exactement ce que l'opérateur de reste nous permet de faire !\r\n\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  // firstName = \"Nick\"\r\n  // lastName = \"Anderson\"\r\n  // [10, 12, 6] -- \"...\" prend tous les autres paramètres passés, créée une variable grades qui contient un tableau contenant les paramètres\r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // calculer la note moyenne à partir des notes\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Nick\", \"Anderson\", 10, 12, 6);\r\nconsole.log(student);\r\n// {\r\n//   firstName: \"Nick\",\r\n//   lastName: \"Anderson\",\r\n//   grades: [10, 12, 6],\r\n//   avgGrade: 9,33\r\n// }\r\n```\r\n\r\n> **Note :** la fonction createStudent est mauvaise car nous ne vérifions pas si grades.length existe ou est différent de 0. Cependant, je n'ai pas prévu ce cas pour rendre l'exemple plus facile à lire.\r\n\r\n##### Décomposition des propriétés d'un objet\r\n\r\nPour celui-ci, je vous recommande de lire les explications précédentes concernant l'opérateur de reste sur les itérables et les paramètres de fonction auparavant.\r\n\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // l'objet est déstructuré ici\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\n// z est le reste de l'objet déstructuré : c'est myObj sans les propriétés x et y qui ont été déstructurées\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// Ici, les propriétés de l'objet z sont étendues dans n\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [TC39 - Object rest/spread](https://github.com/tc39/proposal-object-rest-spread)\r\n- [Spread operator introduction - WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md)\r\n- [JavaScript & the spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca)\r\n- [6 Great uses of the spread operator](https://davidwalsh.name/spread-operator)\r\n\r\n### Raccourci pour les propriétés d'objet\r\n\r\nLorsque l'on assigne une variable à la propriété d'un objet, si le nom de la variable est le même que le nom de la propriété, vous pouvez faire la chose suivante :\r\n\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // 10\r\n```\r\n\r\n#### Explication\r\n\r\nD'habitude (avant ES2015), lorsque l'on déclare un *litéral d'objet* et que l'on veut utiliser des variables comme propriétés de l'objet, on écrit ce genre de code :\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // on assigne le contenu de la variable x à myObj.x\r\n  y: y // on assigne le contenu de la variable y à myObj.y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\nComme vous pouvez le voir, c'est assez répétitif car les noms des propriétés de myObj sont identiques aux noms des variables que vous voulez assigner à ces propriétés.\r\n\r\nAvec ES2015, quand le nom de la variable est identique au nom de la propriété, vous pouvez utiliser ce raccourci :\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [Property shorthand - ES6 Features](http://es6-features.org/#PropertyShorthand)\r\n\r\n### Promesses\r\n\r\nUne promesse est un objet qui peut être retourné de manière synchrone depuis une fonction asynchrone ([ref](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0)).\r\n\r\nLes promesses peuvent être utilisées pour éviter un [enfer de callbacks](http://callbackhell.com/), et elles sont rencontrées de plus en plus fréquemment dans les projets JavaScript modernes.\r\n\r\n#### Code d'exemple\r\n\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n    .done(posts => res(posts))\r\n    .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n#### Explication\r\n\r\nQuand vous faites une *requête AJAX*, la réponse n'est pas synchrone car vous voulez une ressource qui prend du temps à venir. Elle ne pourriat même jamais arriver si la ressource que vous avez demandée est indisponible pour une raison quelconque (404).\r\n\r\nPour gérer ce type de situations, ES2015 nous a offert les *promesses*. Les promesses peuvent avoir trois états différents :\r\n\r\n- En attente\r\n- Complété\r\n- Rejeté\r\n\r\nImagions que nous voulions utiliser les promesses pour gérer une requête AJAX pour récupérer la ressource *X*.\r\n\r\n##### Créer la promesse\r\n\r\nNous allons commencer par crééer une promesse. Nous allons utiliser la méthode ```$.get()``` de jQuery pour faire notre requête AJAX vers *X*.\r\n\r\n```js\r\nconst xFetcherPromise = new Promise( // Créer une promesse avec le mot-clé new et la stocker dans une variable\r\n  function(resolve, reject) { // Le constructeur de Promise prend une fonction comme paramètre qui a elle-même deux paramètres, resolve et reject\r\n    $.get(\"X\") // Démarrer la requête AJAX\r\n      .done(function(X) { // Quand la requête est terminée...\r\n        resolve(X); // ...résoudre la promesse avec la valeur X comme paramètre\r\n      })\r\n      .fail(function(error) { // Si la requête a échoué...\r\n        reject(error); // ...rejeter la promesse avec l'erreur comme paramètre\r\n      });\r\n  }\r\n)\r\n```\r\n\r\nComme vu dans l'exemple ci-dessus, l'objet Promise prend une fonction *exécuteur* qui prend les deux paramètres **resolve** et **reject**. Ces paramètres sont des fonctions qui lorsqu'elles sont appelées, vont modifier l'état de la promesse d'*en attente* à respectivement l'état *complété* et *résolu*.\r\n\r\nLa promesse est dans l'état *en attente* à sa création et sa fonction *éxécuteur* est appelée immédiatement. Quand une des deux fonctions *resolve* ou *reject* est appelée depuis la fonction *éxécuteur*, la promesse appelera les déclencheurs associés.\r\n\r\n##### Utilisation des déclencheurs de promesse\r\n\r\nPour obtenir le résultat (ou l'erreur) de la promesse, nous devons y attacher des déclencheurs en faisant la chose suivante :\r\n\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err)\r\n  })\r\n```\r\n\r\nSi la promesse réussit, ```resolve()``` sera exécuté et la fonction passée à ```.then``` est appelée.\r\n\r\nSi elle échoue, ```reject()``` sera exécuté et la fonction passée à ```.catch``` est appelée.\r\n\r\n> **Note : ** Si la promesse a déjà été accomplie ou rejetée lorsqu'un déclencheur y est attaché, le déclencheur sera appelé, afin de ne pas avoir une course entre une opération asynchrone se complétant et ses déclencheurs s'y faisant attacher [(référence: MDN)](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise#Description).\r\n\r\n#### Ressources externes\r\n\r\n- [JavaScript Promises for dummies - Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies)\r\n- [JavaScript Promise API - David Walsh](https://davidwalsh.name/promises)\r\n- [Utiliser les promesses - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Guide/Utiliser_les_promesses)\r\n- [What is a promise - Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)\r\n- [JavaScript Promises: an Introduction - Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises)\r\n- [Documentation sur l'objet Promise - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise)\r\n\r\n### Littéraux de modèle\r\n\r\nLes littéraux de modèle (*template literals*) sont une [*interpolation d'expression*](https://en.wikipedia.org/wiki/String_interpolation) pour les chaînes de caractère d'une ligne ou multilignes.\r\n\r\nAutrement dit, c'est une nouvelle syntaxe de chaîne de caractère qui est particulièrement pratique pour y utiliser des expressions JavaScript (des variables, par exemple).\r\n\r\n#### Code d'exemple\r\n\r\n```js\r\nconst name = \"Nick\";\r\n`Bonjour ${name}, l'expression suivante vaut 4 : ${2+2}`;\r\n\r\n// Bonjour Nick, l'expression suivante vaut 4 : 4\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)\r\n- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)\r\n\r\n### Littéraux de modèle étiquetés\r\n\r\nLes étiquettes de modèle sont des *fonctions qui peuvent être préfixées à un [littéral de modèle](#litteraux-de-modele)*.  Quand une fonction est appelée ainsi, le premier paramètre est un tableau des *chaînes de caractère* qui apparaissent entre les variables interpolées du modèle, et les paramètres suivants sont les valeurs interpolées. Vous pouuvez utiliser l'opérateur de décomposition `...` pour les récupérer. [(Références: MDN)](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Litt%C3%A9raux_gabarits#Les_littéraux_de_modèle_étiquetés).\r\n\r\n> **Note :** Certaines librairies, comme [styled-components](https://www.styled-components.com/), se basent entièrement sur cette fonctionnalité.\r\n\r\nVoici un petit exemple de leur fonctionnement :\r\n```js\r\nfunction highlight(strings, ...values) {\r\n  const interpolation = strings.reduce((prev, current) => {\r\n    return prev + current + (values.length ? \"<mark>\" + values.shift() + \"</mark>\" : \"\");\r\n  }, \"\");\r\n\r\n  return interpolation;\r\n}\r\n\r\nconst condiment = \"confiture\";\r\nconst meal = \"toast\";\r\n\r\nhighlight`J'aime mettre de la ${condiment} sur mon ${meal}.`;\r\n// \"J'aime mettre de la <mark>confiture</mark> sur mon <mark>toast</mark>.\"\r\n```\r\n\r\nUn autre exemple plus intéressant :\r\n```js\r\nfunction comma(strings, ...values) {\r\n  return strings.reduce((prev, next) => {\r\n    let value = values.shift() || [];\r\n    value = value.join(\", \");\r\n    return prev + next + value;\r\n  }, \"\");\r\n}\r\n\r\nconst snacks = ['pommes', 'bananes', 'cerises'];\r\ncomma`J'aime grignoter des ${snacks}.`;\r\n// \"J'aime grignoter des pommes, bananes, cerises.\"\r\n```\r\n\r\n#### Ressources externes\r\n- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)\r\n- [Library of common template tags](https://github.com/declandewet/common-tags)\r\n\r\n### Imports / exports\r\n\r\nLes modules ES6 sont utilisés pour accéder à des variables et à des fonctions explicitement exportées depuis les modules importés.\r\n\r\nJe vous recommande de regardes la documentation sur MDN concernant import/export (voir les ressources externes plus bas), elles sont à la fois simples et complètes.\r\n\r\n#### Explication avec un code d'exemple\r\n\r\n##### Exports nommés\r\n\r\nLes exports nommés sont utilisés pour exporter plusieurs valeurs d'un module.\r\n\r\n> **Note :** Vous ne pouvez exporter avec un nom que des [objets de première classe](https://fr.wikipedia.org/wiki/Objet_de_premi%C3%A8re_classe) qui ont un nom.\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js'; // Import nommé -- syntaxe ressemblant à la destructuration\r\nconsole.log(pi) // 3.14\r\nconsole.log(exp) // 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js'; // Injecter toutes les valeurs exportées dans la variable constants\r\nconsole.log(constants.pi) // 3.14\r\nconsole.log(constants.exp) // 2.7\r\n```\r\n\r\nBien que les imports nommés ressemblent à une *destructuration*, ils ont une syntaxe différente et ne sont pas identiques. Ils ne supportent ni les valeurs par défaut ni la destructuration *profonde*.\r\n\r\nDe plus, vous pouvez créer des alias mais la syntaxe est différente de celle utilisée avec la destructuration :\r\n\r\n```js\r\nimport { foo as bar } from 'myFile.js'; // foo est importé et injecté dans une nouvelle variable bar\r\n```\r\n\r\n##### Import/export par défaut\r\n\r\nConcernant l'export par défaut, il ne peut y en avoir qu'un seul par module. Un export par défaut peut être une fonction, une classe, un objet, ou quoi que ce soit d'autre. Cette valeur est considérée comme étant la valeur exportée \"principale\" car elle sera la plus simple à importer.\r\nConcerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is considered the \"main\" exported value since it will be the simplest to import. [Référence: MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/export#Description)\r\n\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n// L'export par défaut, peu importe son nom, est automatiquement injecté dans la variable number\r\nconsole.log(number) // 42\r\n```\r\n\r\nExporter une fonction :\r\n\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // 3\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [ES6 Modules in bulletpoints](https://ponyfoo.com/articles/es6#modules)\r\n- [Export - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\r\n- [Import - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/)\r\n- [Destructuring special case - import statements](https://ponyfoo.com/articles/es6-destructuring-in-depth#special-case-import-statements)\r\n- [Misunderstanding ES6 Modules - Kent C. Dodds](https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0)\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript)\r\n\r\n### <a name=\"this_def\"></a> *this* en JavaScript\r\n\r\nL'opérateur *this* se comporte différemment que dans d'autres langages et est dans la plupart des cas déterminé par la manière dont une fonction est appelée. ([Ref: MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Op%C3%A9rateurs/L_op%C3%A9rateur_this)).\r\n\r\nCette notion a beaucoup de subtilités et comme elle est assez complexe, je vous recommande donc fortement de lire avec attention les ressources externes ci-dessous. Par conséquent, je vais utiliser l’idée personnelle que j’ai en tête pour déterminer ce qu’est *this*. J’ai appris cette astuce de [cet article écrit par Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/).\r\n\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// Après chaque ligne, vous trouverez la valeur de *this* dans myFunc\r\n\r\nmyFunc.call(\"myString\", \"hello\") // \"myString\" -- la valeur du premier paramètre de .call est injectée dans *this*\r\n\r\n// En mode non-strict\r\nmyFunc(\"hello\") // window -- myFunc() est un sucre syntaxique pour myFunc.call(window, \"hello\")\r\n\r\n// En mode strict\r\nmyFunc(\"hello\") // undefined -- myFunc() est un sucre syntaxique pour myFunc.call(undefined, \"hello\")\r\n```\r\n\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\") // objet person -- le premier paramètre de call est injecté dans *this*\r\nperson.myFunc(\"test\") // objet person -- person.myFunc() est un sucre syntaxique pour person.myFunc.call(person, \"test\")\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"hello\") // Créée une nouvelle fonction dans laquelle nous injectons “hello” comme valeur de *this*\r\nperson.myFunc(\"test\") // objet Person -- La méthode bind n’a aucun effet sur la méthode originale\r\nmyBoundFunc(\"test\") // \"hello\" -- myBoundFunc est person.myFunc avec “hello” comme valeur de *this*\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [Understanding JavaScript Function Invocation and \"this\" - Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)\r\n- [L’opérateur this - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Opérateurs/L_opérateur_this)\r\n\r\n### Classe\r\n\r\nJavaScript est un language [basé sur les prototypes](https://fr.wikipedia.org/wiki/Programmation_orientée_prototype) (alors que Java, par exemple, est [basé sur les classes]((https://en.wikipedia.org/wiki/Prototype-based_programming))). ES6 a introduit les classes JavaScript qui sont un sucre syntaxique pour de l’héritage et **non** un nouveau modèle d’héritage basé sur des classes \r\n\r\nJavaScript is a [prototype-based](https://en.wikipedia.org/wiki/Prototype-based_programming) language (whereas Java is [class-based](https://en.wikipedia.org/wiki/Class-based_programming) language, for instance). ES6 has introduced JavaScript classes which are meant to be a syntactic sugar for prototype-based inheritance and **not** a new class-based inheritance model ([référence : MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Classes)).\r\n\r\nLe mot *classe* est évidemment source de confusion si vous êtes habitué aux classes dans d’autres langages. Dans ce cas, évitez de penser que les classes JavaScript fonctionnent de la même manière et considérez-les comme une notion totalement différente.\r\n\r\nComme ce document n’est pas fait pour vous apprendre le langage à partir de zéro, je vais partir du fait que vous savez déjà ce que sont les prototypes et comment ils se comportement. Dans le cas contraire, voyez les ressources externes listées en dessous des exemples.\r\n\r\n#### Exemples\r\n\r\nAvant ES6, la syntaxe de prototype :\r\n\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n}\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n}\r\n```\r\n\r\nAvec la syntaxe ES6 de classe :\r\n\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Manu\", 23);\r\nconsole.log(myPerson.age) // 23\r\nconsole.log(myPerson.stringSentence()) // \"Hello, my name is Manu and I'm 23\r\n```\r\n\r\n#### Ressources externes\r\n\r\nPour comprendre les prototypes :\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Héritage et chaîne de prototypes - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Héritage_et_chaîne_de_prototypes)\r\n\r\nPour comprendre les classes\r\n\r\n- [ES6 Classes in Depth - Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features - Classes](http://es6-features.org/#ClassDefinition)\r\n- [Classes - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Classes)\r\n\r\n### Mots clés `extends` et `super`\r\n\r\nLe mot-clé `extends` est utilisé dans les déclarations de classe ou les expressions de classe pour créer une classe qui est une fille d’une autre classe ([référence: MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Classes/extends)). La sous-classe hérite de toutes les propriétés de la classe supérieure et peut aussi ajouter de nouvelles propriétés ou modifier celles héritées.\r\n\r\nLe mot-clé `super` est utilisé pour appeler des fonctions sur le parent d’un objet, y compris son constructeur.\r\n\r\n- Le mot-clé `super` doit être utilisé avant que le mot-clé `this` soit utilisé dans le constructeur\r\n- Invoquer `super()` appelle le constructeur de la classe parente. Si vous voulez passer des arguments au constructeur de la classe parente, vous pouvez l’appeler avec `super(arguments)`.\r\n- Si la classe parente a une méthode (même statique) appelée `X`, vous pouvez utiliser `super.X()` pour l’appeler depuis la classe fille.\r\n\r\n#### Code d’exemple\r\n\r\n```js\r\nclass Polygon {\r\n  constructor(height, width) {\r\n    this.name = 'Polygon';\r\n    this.height = height;\r\n    this.width = width;\r\n  }\r\n\r\n  getHelloPhrase() {\r\n    return `Hi, I am a ${this.name}`;\r\n  }\r\n}\r\n\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    // Ici, le constructeur de la classe parente est appelé avec\r\n    // les longueurs données pour la hauteur et largeur du Polygon\r\n    super(length, length);\r\n    // Note : dans les classes dérivées, super() doit être appelé avant que vous ne\r\n    // puissiez utiliser 'this'. Ne pas respecter cette règle causera une ReferenceError.\r\n    this.name = 'Square';\r\n    this.length = length;\r\n  }\r\n\r\n  getCustomHelloPhrase() {\r\n    const polygonPhrase = super.getHelloPhrase(); // accéder à une méthode de la classe parente avec la syntaxe super.X()\r\n    return `${polygonPhrase} with a length of ${this.length}`;\r\n  }\r\n\r\n  get area() {\r\n    return this.height * this.width;\r\n  }\r\n}\r\n\r\nconst mySquare = new Square(10);\r\nconsole.log(mySquare.area) // 100\r\nconsole.log(mySquare.getHelloPhrase()) // 'Hi, I am a Square' -- Square hérite de Polygon et a accès à ses méthodes\r\nconsole.log(mySquare.getCustomHelloPhrase()) // 'Hi, I am a Square with a length of 10'\r\n```\r\n\r\n**Note :** Si nous avions essayé d’utiliser `this`avant d’appeler `super()` dans la classe Square, une ReferenceError aurait été déclenchée :\r\n\r\n```js\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    this.height; // ReferenceError, super doit être appelé d’abord !\r\n\r\n    // Ici, le constructeur de la classe parente est appelé avec\r\n    // les longueurs données pour la hauteur et largeur du Polygon\r\n    super(length, length);\r\n    \r\n    // Note : dans les classes dérivées, super() doit être appelé avant que vous ne\r\n    // puissiez utiliser 'this'. Ne pas respecter cette règle causera une ReferenceError.\r\n    this.name = 'Square';\r\n  }\r\n}\r\n```\r\n\r\n#### Ressources\r\n\r\n- [extends - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Classes/extends)\r\n- [super - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Opérateurs/super)\r\n- [L’héritage au sein de JavaScript - MDN](https://developer.mozilla.org/fr/docs/Learn/JavaScript/Objects/Heritage)\r\n\r\n### Async Await\r\n\r\nEn plus des [Promises](#promesses), il y a une nouvelle syntaxe que vous pourriez rencontrer pour gérer le code asynchrone nommée *async / await*.\r\n\r\nLe but des fonctions async/await est de simplifier le comportement de l’utilisation des promesses de manière synchrone et d’exécuter un comportemnet sur un groupe de promesses. Tout comme les promesses sont similaires aux callbacks structurés, asnyc/await est similaire à la combinaison de générateurs et de promesses. Les fonctions asynchrones renvoient *toujours* une Promise. ([référence: MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/async_function))\r\n\r\n> **Note :** Vous devez comprendre ce que sont les promesses et comment elles fonctionnent avant d’essayer de comprendre async/await car elles dépendent dessus.\r\n\r\n> **Note 2:** [*await* doit être utilisé dans une fonction *async*](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0), ce qui signifie que vous ne pouvez pas utiliser await dans le premier niveau de votre code car ce n’est pas une fonction async.\r\n\r\n#### Code d’exemple\r\n\r\n```js\r\nasync function getGithubUser(username) { // le mot-clé async autorise l’utilisation de await dans la fonction et signifie que la fonction retourne une promesse\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // L’exécution est mise en pause ici jusqu’à ce que la Promise retournée par fetch soit résolue\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user)) // afficher dans la console la réponse - on ne peut pas utiliser la syntaxe await car ce code n’est pas une fonction async\r\n  .catch(err => console.log(err)); // si notre fonction async lève une erreur, nous la récupérons ici\r\n```\r\n\r\n#### Explication avec un code d’exemple\r\n\r\n*Async / Await* fonctionnent avec les promises mais ils permettent d’utiliser un style de code plus impératif.\r\n\r\nL’opérateur *async* marque une fonction comme étant asynchrone et retournera toujours une *Promise*. Vous pouvez utiliser l’opérateur *await* dans une fonction *async* pour mettre en pause l’exécution sur cette ligne jusqu’à ce que la promise retournée par l’expression se fasse résoudre ou rejeter.\r\n\r\n```js\r\nasync function myFunc() {\r\n  // nous pouvons utiliser l’opérateur await car cette fonction est asynchrone\r\n  return \"hello world\";\r\n}\r\n\r\nmyFunc().then(msg => console.log(msg)) // \"hello world\" -- la valeur de retour de myFunc se fait transformer en promesse à cause de l’opérateur async\r\n```\r\n\r\nLorsque l’expression *return* d’une fonction async est atteint, la Promise est remplie avec la valeur retournée. Si une erreur est levée à l’intérieur de la fonction async, la l’état de la promesse passera à *rejeté*. Si aucune valeur n’est retournée par une fonction async, une promesse est quand même retournée et sera résolue sans valeur lorsque l’exécution de la fonction async est terminée.\r\n\r\nL’opérateur *await* est utilisé pour attendre qu’une primesse se fasse résoudre et ne peut être utilisé qu’à l’intérieur du corps d’une fonction async. Lorsqu’il est rencontré, l’exécution du code est mise en pause jusqu’à ce que la promise se fasse résoudre.\r\n\r\n> **Note :** *fetch* est une fonction qui retourne une Promise qui nous permet de faire une requête AJAX\r\n\r\nVoyons d’abord comment nous pourrions récupérer un utilisateur sur GitHub avec des promesses.\r\n\r\n```js\r\nfunction getGithubUser(username) {\r\n  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\nVoici l’équivalent avec async/await\r\n\r\n```js\r\nasync function getGithubUser(username) { // utilisation d’une promesse + du mot-clé await autorisé\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // L’exécution s’arrête ici jusqu’à ce que la promesse fetch soit résolue\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\nLa syntaxe *async/await* est particulièrement utile lorsque vous avez besoin d’enchaîner des promesses qui sont mutuellement dépendantes.\r\n\r\nPar exemple, si vous avez besoin d’obtenir un jeton d’accps pour pouvoir récupérer un post de blog sur une base de données puis les informations sur l’auteur :\r\n\r\n> **Note :** les expressions *await* ont besoin d’êtres entourées de parenthèses pour appeler leur valeur résolue et leurs propriétés sur la même ligne.\r\n\r\n```js\r\nasync function fetchPostById(postId) {\r\n  const token = (await fetch('token_url')).json().token;\r\n  const post = (await fetch(`/posts/${postId}?token=${token}`)).json();\r\n  const author = (await fetch(`/users/${post.authorId}`)).json();\r\n\r\n  post.author = author;\r\n  return post;\r\n}\r\n\r\nfetchPostById('gzIrzeo64')\r\n  .then(post => console.log(post))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n##### Gestion d’erreur\r\n\r\nÀ moins d’ajouter des blocs *try / catch* autour des expressions *await*, les exceptions non gérées – peu importe de si elles ont été levées dans le corps de votre fonction *async* ou lorsque le code est en pause pendant *await* – vont rejeter la promesse retournée par la fonction *async*. Utiliser l’expression `thrown` dans une fonction asynchrone donne le même résultat que retourner une promesse qui se fait rejeter [(référence : PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).\r\n\r\n> **Note :** Les promesses se comportent de la même manière !\r\n\r\nAvec les promesses, voici comment on gérerait la chaîne d’erreur :\r\n\r\n```js\r\nfunction getUser() { // Cette promesse se fera rejeter !\r\n  return new Promise((res, rej) => rej(\"Utilisateur non trouvé !\"));\r\n}\r\n\r\nfunction getAvatarByUsername(userId) {\r\n  return getUser(userId).then(user => user.avatar);\r\n}\r\n\r\nfunction getUserAvatar(username) {\r\n  return getAvatarByUsername(username).then(avatar => ({ username, avatar }));\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"Utilisateur non trouvé !\"\r\n```\r\n\r\nÉquivalent avec *async / await*:\r\n\r\n```js\r\nasync function getUser() { // La promesse retournée se fera rejeter\r\n  throw \"Utilisateur non trouvé !\";\r\n}\r\n\r\nasync function getAvatarByUsername(userId) => {\r\n  const user = await getUser(userId);\r\n  return user.avatar;\r\n}\r\n\r\nasync function getUserAvatar(username) {\r\n  var avatar = await getAvatarByUsername(username);\r\n  return { username, avatar };\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"Utilisateur non trouvé !\"\r\n```\r\n\r\n#### Ressources externes\r\n\r\n- [Async/Await - JavaScript.Info](https://javascript.info/async-await)\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/)\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9)\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits)\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n- [Async Function](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Statements/async_function)\r\n- [Await](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Operators/await)\r\n- [Using async / await in express with node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n\r\n### Vérité / fausseté\r\n\r\nEn JavaScript, une valeur `truthy` ou `falsy` est une valeur qui se fait caster en un booléen lorsqu’elle est évaluée dans un contexte booléen. Un exemple de contexte booléen serait l’évaluation d’une condition ```if```.\r\n\r\nChaque valeur sera transformée en ```true```, à part si elles sont égales à :\r\n\r\n- ```false```\r\n- ```0```\r\n- ```\"\"``` (chaîne de caractères vide)\r\n- ```null```\r\n- ```undefined```\r\n- ```NaN```\r\n\r\nVoici des exemples de *contexte booléen* :\r\n\r\n- Évaluation de condition ```if```\r\n\r\n```js\r\nif (myVar) {}\r\n```\r\n\r\n```myVar``` peut être n’importe quel [objets de première classe](https://fr.wikipedia.org/wiki/Objet_de_premi%C3%A8re_classe) (variable, fonction, booléen) mais il sera transformé en booléen car il est évalué dans un contexte booléen.\r\n\r\n- Après l’opérateur logique **NOT** ```!```\r\n\r\nCet opérateur retourne ```false``` si son opérande peut être converti à ```true``` ; dans le cas contraire, il retourne ```true```\r\n\r\n```js\r\n!0 // true -- 0 est falsy, donc retourne true\r\n!!0 // false -- 0 est falsy, donc !0 retourne true, et donc !(!0) retourne false\r\n!!\"\" // false -- une chaîne vide est falsy donc NOT (NOT false) est égal à false\r\n```\r\n\r\n- Avec le constructeur d’objet *Boolean*\r\n\r\n```js\r\nnew Boolean(0) // false\r\nnew Boolean(1) // true\r\n```\r\n\r\n- Dans une expression ternaire\r\n\r\n```js\r\nmyVar ? \"truthy\" : \"falsy\"\r\n```\r\n\r\nmyVar se fait évaluer dans un contexte booléen.\r\n\r\n#### Ressources externes\r\n\r\n- [Truthy (MDN)](https://developer.mozilla.org/fr/docs/Glossary/Truthy)\r\n- [Falsy (MDN)](https://developer.mozilla.org/fr/docs/Glossary/Falsy)\r\n- [Truthy and Falsy values in JS - Josh Clanton](http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html)\r\n\r\n### Méthodes statiques\r\n\r\n#### Explication courte\r\n\r\nLe mot-clé `static` est utilisé dans les classes pour déclarer des méthodes statiques. Les méthodes statiques sont des fonctions dans une classe qui appartiennent à l’objet classe et ne sont pas disponible dans les instances de la classe.\r\n\r\n#### Code d’exemple\r\n\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Le nom du repo est modern-js-cheatsheet\"\r\n  }\r\n}\r\n\r\n// Notez que nous n’avons pas créé d’instance de la classe Repo\r\nconsole.log(Repo.getName()) // \"Le nom du repo est modern-js-cheatsheet\"\r\n\r\nlet r = new Repo();\r\nconsole.log(r.getName()) // Uncaught TypeError: repo.getName is not a function\r\n```\r\n\r\n#### Explication détaillée\r\n\r\nLes méthodes statiques peuvent être appelées à l’intérieur d’une autre méthode statique en utilisant le mot-clé `this`. Ceci ne fonctionne pas avec les méthodes non statiques, qui ne peuvent pas y accéder directement en utilisant le mot-clé `this`.\r\n\r\n##### Appeler d’autres méthodes statiques depuis une méthode statique\r\n\r\nPour appeler une méthode statique depuis une autre méthode statique, le mot-clé `this` peut être utilisé comme ceci :\r\n\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Le nom du repo est modern-js-cheatsheet\"\r\n  }\r\n\r\n  static modifyName(){\r\n    return this.getName() + '-ajout'\r\n  }\r\n}\r\n\r\nconsole.log(Repo.modifyName()) // Le nom du repo est modern-js-cheatsheet-ajout\r\n```\r\n\r\n##### Appeler des méthodes statiques depuis des méthodes non statiques\r\n\r\nLes méthodes non statiques peuvent appeler des méthodes statiques de deux façons :\r\n1. ###### En utilisant le nom de la classe\r\n\r\nPour accéder à une méthode statique depuis une méthode non statique, nous pouvons utiliser le nom de la classe et appeler la méthode statique comme une propriété, par exemple `NomClasse.NomMethodeStatique()`\r\n\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Le nom du repo est modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName() {\r\n    return Repo.getName() + ' et il contient des trucs vraiment importants'\r\n  }\r\n}\r\n\r\n// Nous devons instancier la classe pour utiliser les méthodes non statiques\r\nlet r = new Repo()\r\nconsole.log(r.useName()) // Le nom du repo est modern-js-cheatsheet et il contient des trucs vraiment importants\r\n```\r\n\r\n2. ###### Avec le constructeur\r\n\r\nLes méthodes statiques peuvent être appelées en tant que propriétés sur l’objet constructor\r\n\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName() {\r\n    // Appelle la méthode statique comme une propriété du constructeur\r\n    return this.constructor.getName() + ' et il contient des trucs vraiment importants'\r\n  }\r\n}\r\n\r\n// Nous devons instancier la classe pour utiliser les méthodes non statiques\r\nlet r = new Repo()\r\nconsole.log(r.useName()) // Le nom du repo est modern-js-cheatsheet et il contient des trucs vraiment importants\r\n```\r\n\r\n#### Ressources externes\r\n- [static - MDN](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Classes/static)\r\n- [Static Methods - Javascript.info](https://javascript.info/class#static-methods)\r\n- [Static Members in ES6 - OdeToCode](http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx)\r\n\r\n## Glossaire\r\n\r\n### <a name=\"scope_def\"></a> Portée (*scope*)\r\n\r\nLe contexte dans lequel les valeurs et expressions sont “visibles”, ou peuvent être référencées. Si une variable ou une autre expression n’est pas “dans la portée actuelle”, alors son utilisation ne sera pas possible.\r\n\r\nSource : [MDN](https://developer.mozilla.org/fr/docs/Glossaire/Portée)\r\n\r\n### <a name=\"mutation_def\"></a> Mutation de variable\r\n\r\nOn dit d’une variable qu’elle a été *mutée* lorsque sa valeur initiale a été changée après coup.\r\n\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // myArray s’est fait muter\r\n```\r\n\r\nUne variable est dite *immutable* si elle ne peut être mutée.\r\n\r\nVous pouvez lire [l’article Mutable de MDN](https://developer.mozilla.org/fr/docs/Glossary/Mutable) pour plus de détails.\r\n"
  },
  {
    "path": "JavaScript/translations/ja-JP.md",
    "content": "# <a name=\"modern-javascript-cheatsheet\"></a> モダン JavaScript チートシート\r\n\r\n![モダン JavaScript チートシート](https://i.imgur.com/aexPxMb.png)\r\n<small>画像クレジット: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## <a name=\"introduction\"></a> イントロダクション\r\n\r\n### <a name=\"motivation\"></a> 動機\r\n\r\nこのドキュメントはモダンなプロジェクトでよく見られる JavaScript のチートシートと最新のサンプルコードです。\r\n\r\nこのガイドは読者に JavaScript をゼロから教えるものではありません。\r\n基礎知識は持っていて、モダンなコードベースに慣れる（例えば React を学ぶ）のに苦労している開発者を助けるためのものです。\r\n説明の中で JavaScript の諸概念が使われています。\r\n\r\nまた、議論の余地のあるポイントについてときどき個人的な tips を載せますが、その際はあくまでも個人的なおすすめであることを述べるように気をつけます。\r\n\r\n> **メモ:** ここで紹介されている概念のほとんどは JavaScript 言語のアップデート（ ES2015 、しばしば ES6 と呼ばれるもの）によるものです。そのアップデートで追加された新しい機能の説明は[こちらのページ](http://es6-features.org)で見つけることができます。このページはとてもわかりやすく書かれています。\r\n\r\n### <a name=\"complementary-resources\"></a> 補完的なリソース\r\n\r\n概念がうまく理解できない場合は、以下のリソースで答えを探すことをおすすめします:\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/en-US/search?q=)\r\n- [You don't know JS (book)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Features with examples](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Javascript Basics for Beginners](https://www.udacity.com/course/javascript-basics--ud804) - Udacity の無料コース\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) （ブログとリソースを見つけるために）\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript)\r\n\r\n## <a name=\"table-of-contents\"></a> 目次\r\n\r\n- [モダン JavaScript チートシート](#modern-javascript-cheatsheet)\r\n  * [イントロダクション](#introduction)\r\n    + [動機](#motivation)\r\n    + [補完的なリソース](#complementary-resources)\r\n  * [目次](#table-of-contents)\r\n  * [各種概念](#notions)\r\n    + [変数宣言: `var` / `const` / `let`](#variable-declaration-var-const-let)\r\n      - [短い説明](#short-explanation)\r\n      - [サンプルコード](#sample-code)\r\n      - [詳細な説明](#detailed-explanation)\r\n      - [外部のリソース](#external-resource)\r\n    + [アロー関数](#-arrow-function)\r\n      - [サンプルコード](#sample-code-1)\r\n      - [詳細な説明](#detailed-explanation-1)\r\n        * [簡潔さ](#concision)\r\n        * [*`this`* 参照](#this-reference)\r\n      - [有用なリソース](#useful-resources)\r\n    + [関数の引数のデフォルト値](#function-default-parameter-value)\r\n      - [外部のリソース](#external-resource-1)\r\n    + [オブジェクトや配列の分割](#destructuring-objects-and-arrays)\r\n      - [サンプルコード付きの説明](#explanation-with-sample-code)\r\n      - [有用なリソース](#useful-resources-1)\r\n    + [配列のメソッド - `map` / `filter` / `reduce`](#array-methods---map--filter--reduce)\r\n      - [サンプルコード](#sample-code-2)\r\n      - [説明](#explanation)\r\n        * [`Array.prototype.map()`](#arrayprototypemap)\r\n        * [`Array.prototype.filter()`](#arrayprototypefilter)\r\n        * [`Array.prototype.reduce()`](#arrayprototypereduce)\r\n      - [外部のリソース](#external-resource-2)\r\n    + [スプレッド演算子「 `...` 」](#spread-operator-)\r\n      - [サンプルコード](#sample-code-3)\r\n      - [説明](#explanation-1)\r\n        * [イテラブル（配列など）の中での使用](#in-iterables-like-arrays)\r\n        * [関数のレスト引数](#function-rest-parameter)\r\n        * [オブジェクトプロパティのスプレッディング](#object-properties-spreading)\r\n      - [外部のリソース](#external-resources)\r\n    + [オブジェクトプロパティの省略形](#object-property-shorthand)\r\n      - [説明](#explanation-2)\r\n      - [外部のリソース](#external-resources-1)\r\n    + [プロミス](#promises)\r\n      - [サンプルコード](#sample-code-4)\r\n      - [説明](#explanation-3)\r\n        * [プロミスの作成](#create-the-promise)\r\n        * [プロミスハンドラーの使用](#promise-handlers-usage)\r\n      - [外部のリソース](#external-resources-2)\r\n    + [テンプレートリテラル](#template-literals)\r\n      - [サンプルコード](#sample-code-5)\r\n      - [外部のリソース](#external-resources-3)\r\n    + [タグ付きテンプレートリテラル](#tagged-template-literals)\r\n      - [外部のリソース](#external-resources-4)\r\n    + [インポート / エクスポート](#imports--exports)\r\n      - [サンプルコード付きの説明](#explanation-with-sample-code-1)\r\n        * [名前付きエクスポート](#named-exports)\r\n        * [デフォルトインポート / エクスポート](#default-import--export)\r\n      - [外部のリソース](#external-resources-5)\r\n    + [JavaScript の *`this`*](#-javascript-this)\r\n      - [外部のリソース](#external-resources-6)\r\n    + [クラス](#class)\r\n      - [サンプルコード](#samples)\r\n      - [外部のリソース](#external-resources-7)\r\n    + [`extends` キーワードと `super` キーワード](#extends-and-super-keywords)\r\n      - [サンプルコード](#sample-code-6)\r\n      - [外部のリソース](#external-resources-8)\r\n    + [Async Await](#async-await)\r\n      - [サンプルコード](#sample-code-7)\r\n      - [サンプルコード付きの説明](#explanation-with-sample-code-2)\r\n      - [エラーハンドリング](#error-handling)\r\n      - [外部のリソース](#external-resources-9)\r\n    + [True になるもの / False になるもの](#truthy--falsy)\r\n      - [外部のリソース](#external-resources-10)\r\n    + [アナモルフィズム / カタモルフィズム](#anamorphisms-and-catamorphisms)\r\n      - [アナモルフィズム](#anamorphisms)\r\n      - [カタモルフィズム](#catamorphisms)\r\n      - [外部のリソース](#external-resources-11)\r\n    + [ジェネレーター](#generators)\r\n      - [外部のリソース](#external-resources-12)\r\n    + [スタティックメソッド](#static-methods)\r\n      - [短い説明](#short-explanation-1)\r\n      - [サンプルコード](#sample-code-8)\r\n      - [詳細な説明](#detailed-explanation-2)\r\n        * [スタティックメソッドから別のスタティックメソッドを呼ぶ](#calling-other-static-methods-from-a-static-method)\r\n        * [スタティックでないメソッドからスタティックメソッドを呼ぶ](#calling-static-methods-from-non-static-methods)\r\n      - [外部のリソース](#external-resources-13)\r\n  * [用語集](#glossary)\r\n    + [スコープ](#-scope)\r\n    + [変数ミューテーション](#-variable-mutation)\r\n\r\n## <a name=\"notions\"></a> 各種概念\r\n\r\n### <a name=\"variable-declaration-var-const-let\"></a> 変数宣言: `var` / `const` / `let`\r\n\r\nJavaScript には、変数の宣言に利用できるキーワードが 3 つあり、それぞれ違いがあります。\r\nその 3 つのキーワードとは、 ```var``` と ```let``` と ```const``` です。\r\n\r\n#### <a name=\"short-explanation\"></a> 短い説明\r\n\r\n```const``` キーワードで宣言された変数は再代入ができません。\r\n```let``` と ```var``` は再代入ができます。\r\n\r\n基本的に、変数はいつも ```const``` で宣言するようにして、変数を *変更* したり（訳注: 原文では「 mutate 」です）後から再代入したりする必要がある場合に ```let``` を使うことをおすすめします。\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>スコープ</th>\r\n    <th>再代入可能</th>\r\n    <th>ミュータブル</th>\r\n   <th><a href=\"#tdz_sample\">テンポラルデッドゾーン</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>`const`</th>\r\n    <td>ブロック</td>\r\n    <td>×</td>\r\n    <td><a href=\"#const_mutable_sample\">○</a></td>\r\n    <td>○</td>\r\n  </tr>\r\n  <tr>\r\n    <th>`let`</th>\r\n    <td>ブロック</td>\r\n    <td>○</td>\r\n    <td>○</td>\r\n    <td>○</td>\r\n  </tr>\r\n   <tr>\r\n    <th>`var`</th>\r\n    <td>関数</td>\r\n    <td>○</td>\r\n    <td>○</td>\r\n    <td>×</td>\r\n  </tr>\r\n</table>\r\n\r\n#### <a name=\"sample-code\"></a> サンプルコード\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // Will raise an error, person can't be reassigned\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", reassignment is allowed with let\r\n```\r\n\r\n#### <a name=\"detailed-explanation\"></a> 詳細な説明\r\n\r\n変数の [*スコープ*](#scope_def) とは、ざっくり言うと、「コードの中でその変数が利用できる範囲」のことです。\r\n\r\n##### <a name=\"\"></a> `var`\r\n\r\n```var``` で宣言された変数のスコープは *関数スコープ* になります。\r\nこれは、ある変数が関数の中で作成されているとき、その関数の中のすべてのパーツがその変数にアクセスできることを意味します。\r\n加えて、ある関数の中で作成された *関数スコープ* の変数はその関数の外側ではアクセスすることができません。\r\n\r\n*X スコープ* 変数ということばの意味は、その変数が X のプロパティであるような感じでイメージすることをおすすめします。\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar is accessible inside the function\r\n}\r\nconsole.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.\r\n```\r\n\r\n変数のスコープに引き続き着目し、もう少しわかりづらい例を見てみましょう:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // actually, myVar being function scoped, we just erased the previous myVar value \"Nick\" for \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - see how the instructions in the if block affected this value\r\n}\r\nconsole.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.\r\n```\r\n\r\n加えて、 *`var`* で宣言された変数は実行時にスコープの一番上に移動されます。\r\nこの処理のことを [`var` ホイスティング](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) と呼びます。\r\n\r\n次のコードは\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- no error raised\r\nvar myVar = 2;\r\n```\r\n\r\n実行時に次のように解釈されます。\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- no error raised\r\nmyVar = 2;\r\n```\r\n\r\n##### <a name=\"\"></a> `let`\r\n\r\n```var``` と ```let``` は大体同じですが、 ```let``` で宣言された変数には次の特徴があります。\r\n\r\n- *ブロックスコープ* である\r\n- 代入の前にアクセスすることが *できない*\r\n- 同じスコープの中で再宣言できない\r\n\r\n上の例を使ってブロックスコープのインパクトを見てみましょう:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // actually, myVar being block scoped, we just created a new variable myVar.\r\n    // this variable is not accessible outside this block and totally independent\r\n    // from the first myVar created !\r\n  }\r\n  console.log(myVar); // \"Nick\", see how the instructions in the if block DID NOT affect this value\r\n}\r\nconsole.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> ここで、 *`let`* （と *`const`* ）で宣言された変数に関して、代入前にアクセスできないというのは次のコードに示すとおりの意味です:\r\n\r\n```js\r\nconsole.log(myVar) // raises a ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\n*`var`* とは対照的に、 *`let`* や *`const`* の変数では代入前に読み込みあるいは書き込みをしようとするとエラーが上がります。\r\nこの現象はしばしば [*テンポラルデッドゾーン*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) あるいは *TDZ* と呼ばれます。\r\n\r\n> **メモ:** 技術的には、 *`let`* と *`const`* の変数宣言もホイストされています。\r\nこれらは代入前に使用されないように作られているため、直感的にはホスティングが起こっていないように感じられますが、実際には起こっています。\r\n詳しく知りたい場合は[こちらの非常に詳しい説明](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)をご覧ください。\r\n\r\n加えて、 *`let`* 変数は再宣言することができません:\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // Raises a SyntaxError\r\n```\r\n\r\n##### <a name=\"\"></a> `const`\r\n\r\n```const``` で宣言された変数は *`let`* 変数のように振る舞いますが、再代入ができません。\r\n\r\nまとめると、 *`const`* 変数には次の特徴があります:\r\n\r\n- *ブロックスコープ* である\r\n- 代入前にアクセスすることができない\r\n- 同じスコープの中で再宣言できない\r\n- 再代入できない\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // raises an error, reassignment is not allowed\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // raises an error, re-declaration is not allowed\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> しかし、微妙なポイントがあります: ```const``` 変数は [**イミュータブル**](#mutation_def) ではありません！\r\n具体的に言うと、 ```const``` で宣言された *オブジェクト* と *配列* は変更することが **できます** 。\r\n\r\nオブジェクトの場合:\r\n\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // this will work ! person variable is not completely reassigned, but mutated\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // raises an error, because reassignment is not allowed with const declared variables\r\n```\r\n\r\n配列の場合:\r\n\r\n```js\r\nconst person = [];\r\nperson.push('John'); // this will work ! person variable is not completely reassigned, but mutated\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // raises an error, because reassignment is not allowed with const declared variables\r\n```\r\n\r\n#### <a name=\"external-resource\"></a> 外部のリソース\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"-arrow-function\"></a> <a name=\"arrow_func_concept\"></a> アロー関数\r\n\r\nES6 JavaScript のアップデートで *アロー関数* が導入されました。\r\nこれは、変数を宣言し利用するもうひとつの方法です。\r\nアロー関数がもたらすメリットは次のとおりです:\r\n\r\n- より簡潔である\r\n- *`this`* が周辺のスコープからピックアップされる\r\n- 暗黙的な `return`\r\n\r\n#### <a name=\"sample-code-1\"></a> サンプルコード\r\n\r\n- 簡潔さと暗黙的な `return`\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // Traditional way\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // Same function written as an arrow function with implicit return\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- *`this`* 参照\r\n\r\nアロー関数の中では、 *`this`* はその周りにある実行コンテキストの *`this`* と同じものになります。\r\nアロー関数を使えば、基本的に、関数の中で関数を呼び出す前に `that = this` とするトリックを使う必要がありません。\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### <a name=\"detailed-explanation-1\"></a> 詳細な説明\r\n\r\n##### <a name=\"concision\"></a> 簡潔さ\r\n\r\nアロー関数は、従来の関数よりも多くの点において簡潔です。\r\nすべての起こりうるケースを見てみましょう:\r\n\r\n- 暗黙的な `return`  vs. 明示的な `return`\r\n\r\n**明示的な `return`** は、 *`return`* キーワードがボディの中で使われている関数のことです。\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // this function explicitly returns x * 2, *return* keyword is used\r\n  }\r\n```\r\n\r\n関数を書く従来の方法では、 `return` は常に明示的に書く形になります。\r\nしかし、アロー関数では、 *暗黙的な `return`* を使うことができます。\r\nこれは、値を返すのに *`return`* キーワードを使う必要がないという意味です。\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // Explicit return here\r\n  }\r\n```\r\n\r\nこの関数は何かを返すだけのものなので（ *`return`* キーワードの前に他の処理が無いので）、暗黙的な `return` を使うことができます。\r\n\r\n```js\r\n  const double = (x) => x * 2; // Correct, returns x*2\r\n```\r\n\r\nこうするためには、 **かっこと `return` キーワードを削除** しさえすれば OK です。\r\nそのため、これは *暗黙的な* `return` と呼ばれています。\r\n*`return`* キーワードは書かれていませんが、この関数は実際には ```x * 2``` を返します。\r\n\r\n> **メモ:** もしある関数が値を返さなければ、それは暗黙的な `return` も明示的な `return` も行っていません。\r\n\r\n加えて、 *オブジェクト* を暗黙的に返したい場合は、ブロックのかっことの衝突を防ぐために **その周りにかっこを付ける必要があります**:\r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- object implicitly returned by arrow function\r\n```\r\n\r\n- 引数が 1 つだけの場合\r\n\r\n引数を 1 つだけ受け取る関数の場合は、引数の周りのかっこを省略することができます\r\n上の *`double`* のコードをもう一度取り上げましょう:\r\n\r\n```js\r\n  const double = (x) => x * 2; // this arrow function only takes one parameter\r\n```\r\n\r\n引数のかっこは省略できます:\r\n\r\n```js\r\n  const double = x => x * 2; // this arrow function only takes one parameter\r\n```\r\n\r\n- 引数が無い場合\r\n\r\nアロー関数が引数を取らない場合、かっこを付ける必要があります。\r\nかっこをつけないと正しいシンタックスではなくなります。\r\n\r\n```js\r\n  () => { // parentheses are provided, everything is fine\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // No parentheses, this won't work!\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### <a name=\"this-reference\"></a> *`this`* 参照\r\n\r\nアロー関数といっしょに導入されたこの微妙なポイントを理解するためには、 JavaScript における [`this`](#this_def) の振る舞いを知っておく必要があります。\r\n\r\nアロー関数では、 *`this`* はひとつ外側にある実行コンテキストの *`this`* の値に等しくなります。\r\nこれはつまり、アロー関数は新しい *`this`* を作成せず代わりに周囲の環境から *`this`* を取得します。\r\n\r\nアロー関数がなかった頃は、関数内の関数で *`this`* の値にアクセスしたい場合は、 *`that = this`* または *`self = this`* のトリックを使う必要がありました。\r\n\r\n例えば、 `setTimeout` 関数を `myFunc` の中で利用する場合は次のようにする必要がありました:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // that = this trick\r\n  setTimeout(\r\n    function() { // A new *this* is created in this function scope\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- see function declaration above\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\nアロー関数があれば、 *`this`* はその外部の環境から取得されます:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this taken from surrounding, meaning myFunc here\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### <a name=\"useful-resources\"></a> 有用なリソース\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n### <a name=\"function-default-parameter-value\"></a> 関数の引数のデフォルト値\r\n\r\nES2015 の JavaScript アップデート以降、関数の引数のデフォルト値を次のシンタックスでセットできます:\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- no value is provided so x default value 10 is assigned to x in myFunc\r\nconsole.log(myFunc(5)) // 5 -- a value is provided so x is equal to 5 in myFunc\r\n\r\nconsole.log(myFunc(undefined)) // 10 -- undefined value is provided so default value is assigned to x\r\nconsole.log(myFunc(null)) // null -- a value (null) is provided, see below for more details\r\n```\r\n\r\nデフォルト引数は次の 2 つの状況でのみ適用されます:\r\n\r\n- 引数が渡されなかった\r\n- *`undefined`* 引数が渡された\r\n\r\n言い換えると、 *`null`* を渡した場合はデフォルト引数は **適用されません** 。\r\n\r\n> **メモ:** デフォルト値の代入は、分割引数（訳注: 原文では「 destructured parameters 」です）でも使用することができます（例は、次の概念をご覧ください）\r\n\r\n#### <a name=\"external-resource-1\"></a> 外部のリソース\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Default parameters - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\r\n\r\n### <a name=\"destructuring-objects-and-arrays\"></a> オブジェクトや配列の分割\r\n\r\n*分割* （訳注: 原文では「 destructuring 」です）はオブジェクトまたは配列に格納されたデータから値を抽出して新しい変数を作成する便利な方法です。\r\n\r\nいくつかユースケースをあげるなら、 *分割* は関数の引数を分割するために使用することもできますし、 React プロジェクトの *`this.props`* で使用することもできます。\r\n\r\n#### <a name=\"explanation-with-sample-code\"></a> サンプルコード付きの説明\r\n\r\n- オブジェクト\r\n\r\n以下すべてのサンプルに対して次のオブジェクトについて考えてみましょう:\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\n分割がない場合、次のようになります。\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\n分割がある場合は、ワンラインで書くことができます:\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // That's it !\r\n\r\nconsole.log(age) // 35 -- A new variable age is created and is equal to person.age\r\nconsole.log(first) // \"Nick\" -- A new variable first is created and is equal to person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName exists BUT the new variable created is named first\r\nconsole.log(city) // \"Paris\" -- A new variable city is created and since person.city is undefined, city is equal to the default value provided \"Paris\".\r\n```\r\n\r\n**メモ:** ```const { age } = person;``` において、 *`const`* キーワードの後のかっこは、オブジェクトやブロックの宣言として使用されるのではなく、 *分割* のシンタックスとなります。\r\n\r\n- 関数の引数\r\n\r\n*分割* は関数のオブジェクト引数を分割するためにしばしば使用されます。\r\n\r\n分割を使わない場合、次のようになります。\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nオブジェクト引数 *`person`* を分割すれば、より簡潔な関数を書くことができます:\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { // we create firstName and lastName variables by destructuring person parameter\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n分割は[アロー関数](#arrow_func_concept)といっしょに使うとぐっといい感じになります:\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- 配列\r\n\r\n次の配列について考えてみましょう:\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\n分割を使わない場合、次のようになります。\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\n分割を使うと、次のように書けます。\r\n\r\n```js\r\nconst [x, y] = myArray; // That's it !\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n#### <a name=\"useful-resources-1\"></a> 有用なリソース\r\n\r\n- [ES6 Features - Destructuring Assignment](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)\r\n\r\n### <a name=\"array-methods---map--filter--reduce\"></a> 配列のメソッド - `map` / `filter` / `reduce`\r\n\r\n*`map`* 、 *`filter`* 、 *`reduce`* は [*関数プログラミング*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0) という名前のプログラミングパラダイムに由来する配列のメソッドです。\r\n\r\nまとめ:\r\n\r\n- **Array.prototype.map()** 配列を受け取り、各要素に対して何かをして、変更された要素を持つ配列を返す。\r\n- **Array.prototype.filter()** 配列を受け取り、要素ごとに保持するかどうかを決めて、保持する要素のみからなる配列を返す。\r\n- **Array.prototype.reduce()** 配列を受け取り、要素を 1 つの値に集約する（その値が返される）。\r\n\r\nこれらは組み合わせ可能で、簡潔でエレガントなので、関数プログラミングは原則に則ってできるかぎりこれらを使用することをおすすめします。\r\n\r\nこれら 3 つのメソッドを使えば、ほとんどの状況で *`for`* ループと *`forEach`* ループを使用しなくてよくなります。\r\n*`for`* ループが使いたい場合は、 *`map`* と *`filter`* と *`reduce`* を組み合わせて処理を実現することを試みてください。\r\n新しい考え方を身につける必要があるので最初は苦労するかもしれませんが、一度馴れればものごとはよりかんたんになります。\r\n\r\n#### <a name=\"sample-code-2\"></a> サンプルコード\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // 21\r\n```\r\n\r\n`map` 、 `filter` 、 `reduce` を使って、グレードが 10 以上の学生のグレードの合計値を計算してみます:\r\n\r\n```js\r\nconst students = [\r\n  { name: \"Nick\", grade: 10 },\r\n  { name: \"John\", grade: 15 },\r\n  { name: \"Julia\", grade: 19 },\r\n  { name: \"Nathalie\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // we map the students array to an array of their grades\r\n  .filter(grade => grade >= 10) // we filter the grades array to keep those 10 or above\r\n  .reduce((prev, next) => prev + next, 0); // we sum all the grades 10 or above one by one\r\n\r\nconsole.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie below 10 is ignored\r\n```\r\n\r\n#### <a name=\"explanation\"></a> 説明\r\n\r\n例として、数値からなる次の配列について考えてみましょう:\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n##### <a name=\"arrayprototypemap\"></a> `Array.prototype.map()`\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\nここでは何が起こっているのでしょうか。\r\n`.map` を配列 *`numbers`* に対して使用しています。\r\n`map` は渡された関数を配列の各要素に適用します。\r\nこの関数のゴールは、 `map` が利用できるように、渡された値から新しい値を生成して返すことです。\r\n\r\nわかりやすくするために、今回は特別にこの関数を抽出しましょう:\r\n\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n```numbers.map(doubleN)``` は ```[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]``` を生成します。\r\nそしてこれは ```[0, 2, 4, 6, 8, 10, 12]``` になります。\r\n\r\n> **メモ:** 新しい配列を返すのではなく副作用のあるループを回したいだけの場合は、 `map` の代わりの `for` / `forEach` ループを使いたくなるかもしれません。\r\n\r\n##### <a name=\"arrayprototypefilter\"></a> `Array.prototype.filter()`\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // true if \"n\" is par, false if \"n\" isn't\r\n});\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\n配列 *`numbers`* に対して `.filter()` を使用しています。\r\n`filter` は指定された関数に配列の各要素を渡します。\r\nこの関数のゴールは、現在の値を保持すべきかどうかを決める真偽値を返すことです。\r\n`filter` は保持すべき値のみを格納した配列を返します。\r\n\r\n##### <a name=\"arrayprototypereduce\"></a> `Array.prototype.reduce()`\r\n\r\n`reduce` メソッドのゴールは、配列のすべての要素を走査してひとつの値に *縮減* することです。\r\nどのように集約するかのロジックはあなた次第です。\r\n\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n  0 // accumulator variable value at first iteration step\r\n);\r\n\r\nconsole.log(sum) //21\r\n```\r\n\r\n`.map` メソッドと `.filter` メソッドのように、 `.reduce` は配列に対して適用されるもので、第 1 引数に関数を受け取ります。\r\n\r\nただしこの場合は違いがあります:\r\n\r\n- `.reduce` は 2 つの引数を受け取ります\r\n\r\n第 1 引数は、ループの各ステップで呼び出される関数です。\r\n\r\n第 2 引数は、ループの最初のステップにおける蓄積用の変数（訳注: 原文では「 accumulator variable 」です）の値です（これを理解するには次のポイントを読んでください）。\r\n\r\n- 関数引数\r\n\r\n`.reduce` の第 1 引数として渡す関数は、 2 つの引数を受け取ります。\r\n1 つめの引数（ここでは *`acc`* ）は、蓄積用の変数で、 2 つめの引数（ *`n`* ）は現在の要素です。\r\n\r\n蓄積用の変数は、 **ひとつ前の** ループのステップにおける関数の戻り値と等しいものです。\r\nループの最初のステップでは *`acc`* は `.reduce` の第 2 引数に渡された値に等しくなります。\r\n\r\n###### <a name=\"\"></a> ループの最初のステップ\r\n\r\n`reduce` の第 2 引数に `0` を渡しているので、 ```acc = 0``` となります。\r\n\r\n*`numbers`* 配列の最初の要素を取るので、 ```n = 0``` となります。\r\n\r\n関数は *`acc + n`* を返すので、これは `0 + 0` で `0` になります。\r\n\r\n###### <a name=\"\"></a> ループの第 2 ステップ\r\n\r\nひとつ前のループのステップで関数が返した値が使われるので、 ```acc = 0``` となります。\r\n\r\n*`numbers`* 配列の 2 番目の要素を取るので、 ```n = 1``` となります。\r\n\r\n関数は *`acc + n`* を返すので、これは `0 + 1` で `1` になります。\r\n\r\n###### <a name=\"\"></a> ループの第 3 ステップ\r\n\r\nひとつ前のループのステップで関数が返した値が使われるので、 ```acc = 1``` となります。\r\n\r\n*`numbers`* 配列の 2 番目の要素を取るので、 ```n = 2``` となります。\r\n\r\n関数は *`acc + n`* を返すので、これは `1 + 2` で `3` になります。\r\n\r\n###### <a name=\"\"></a> ループの第 4 ステップ\r\n\r\nひとつ前のループのステップで関数が返した値が使われるので、 ```acc = 3``` となります。\r\n\r\n*`numbers`* 配列の 2 番目の要素を取るので、 ```n = 3``` となります。\r\n\r\n関数は *`acc + n`* を返すので、これは `3 + 3` で `6` になります。\r\n\r\n###### <a name=\"\"></a> ループの最後のステップ\r\n\r\nひとつ前のループのステップで関数が返した値が使われるので、 ```acc = 15``` となります。\r\n\r\n*`numbers`* 配列の最後の要素を取るので、 ```n = 6``` となります。\r\n\r\n関数は *`acc + n`* を返すので、これは `15 + 6` で `21` になります。\r\n\r\nこれがループの最後のステップなので、 **`.reduce`** は `21` を返します。\r\n\r\n#### <a name=\"external-resource-2\"></a> 外部のリソース\r\n\r\n- [Understanding map / filter / reduce in JS](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464)\r\n\r\n### <a name=\"spread-operator-\"></a> スプレッド演算子「 `...` 」\r\n\r\nスプレッド演算子（訳注: 原文では「 spread operator 」です）は ES2015 で導入されました。\r\nイテラブルなオブジェクト（訳注: 原文では「 iterable 」です）（配列など）の要素を、複数の要素が来るべきところに展開するために使用されます。\r\n\r\n#### <a name=\"sample-code-3\"></a> サンプルコード\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x);\r\n  console.log(y);\r\n  console.log(params)\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n#### <a name=\"explanation-1\"></a> 説明\r\n\r\n##### <a name=\"in-iterables-like-arrays\"></a> イテラブル（配列など）の中での使用\r\n\r\n次の 2 つの配列があるものとします:\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\n\r\n*`arr1`* がそのまま *`arr2`* にインジェクトされたので、 *`arr2`* の第 1 要素は配列です。\r\nしかし、実際は *`arr2`* をすべて文字からなる配列にしたいものとしましょう。\r\nそうしたい場合は、 *`arr1`* の要素を *スプレッド* して *`arr2`* に入れることができます。\r\n\r\nスプレッド演算子を使うと、次のように書けます。\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n##### <a name=\"function-rest-parameter\"></a> 関数のレスト引数\r\n\r\n関数の引数において、レスト演算子（訳注: 原文では「 rest operator 」です）を使って引数をまとめて、ループ可能なひとつの配列に入れ込むことができます。\r\nすでに、関数に渡されたすべての引数を格納した配列に等しい **`arguments`** オブジェクトが関数にはバインドされています。\r\n\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\n\r\nmyFunc(\"Nick\", \"Anderson\", 10, 12, 6);\r\n// \"Nick\"\r\n// \"Anderson\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\n\r\nしかし、仮に、この関数に、グレードと平均グレードを持つ新しい学生のオブジェクトを作成させたい場合を考えましょう。\r\n最初の 2 つの引数を個別の 2 つの変数に抽出しておいて、すべてのグレードを格納したループ可能な配列が取得できるなら、便利ですよね。\r\n\r\nまさにこれがレスト演算子でできることなのです！\r\n\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  // firstName = \"Nick\"\r\n  // lastName = \"Anderson\"\r\n  // [10, 12, 6] -- \"...\" takes all other parameters passed and creates a \"grades\" array variable that contains them\r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // computes average grade from grades\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Nick\", \"Anderson\", 10, 12, 6);\r\nconsole.log(student);\r\n// {\r\n//   firstName: \"Nick\",\r\n//   lastName: \"Anderson\",\r\n//   grades: [10, 12, 6],\r\n//   avgGrade: 9,33\r\n// }\r\n```\r\n\r\n> **メモ:** `grades.length` が存在するかどうか、あるいは `0` と異なるかどうかをチェックしていないので、 `createStudent` 関数はよくありません。\r\nしかし、この形だと読みやすいので、そのケースは処理していません。\r\n\r\n##### <a name=\"object-properties-spreading\"></a> オブジェクトプロパティのスプレッディング\r\n\r\nここを読む場合は、イテラブルオブジェクトに対するレスト演算子と関数の引数に関するひとつ前の説明を先に読むことをおすすめします。\r\n\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // object destructuring here\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\n// z is the rest of the object destructured: myObj object minus x and y properties destructured\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// Here z object properties are spread into n\r\n```\r\n\r\n#### <a name=\"external-resources\"></a> 外部のリソース\r\n\r\n- [TC39 - Object rest/spread](https://github.com/tc39/proposal-object-rest-spread)\r\n- [Spread operator introduction - WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md)\r\n- [JavaScript & the spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca)\r\n- [6 Great uses of the spread operator](https://davidwalsh.name/spread-operator)\r\n\r\n### <a name=\"object-property-shorthand\"></a> オブジェクトプロパティの省略形\r\n\r\n変数をオブジェクトのプロパティに代入するとき、変数名がプロパティ名と同じ場合は、次の形で書くことができます:\r\n\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // 10\r\n```\r\n\r\n#### <a name=\"explanation-2\"></a> 説明\r\n\r\n新しい *オブジェクトリテラル* を宣言して、プロパティの値として変数を使用したい場合は、（ ES2015 以前は）たいてい次のようなコードを書いたことでしょう:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // assigning x variable value to myObj.x\r\n  y: y // assigning y variable value to myObj.y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\nご覧のとおり、 `myObj` のプロパティ名はそこに値を割り当てたい変数の名前と同じなので、非常にくどい感じになります。\r\n\r\nES2015 では、変数名がプロパティ名と同じ場合は、次の省略形を使うことができます:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n#### <a name=\"external-resources-1\"></a> 外部のリソース\r\n\r\n- [Property shorthand - ES6 Features](http://es6-features.org/#PropertyShorthand)\r\n\r\n### <a name=\"promises\"></a> プロミス\r\n\r\nプロミスとは、非同期的な関数（訳注: 原文では「 asynchronous function 」です）から同期的に（訳注: 原文では「 synchronously 」です）返すことができるオブジェクトです（[参考](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0))）。\r\n\r\nプロミスは[コールバック地獄](http://callbackhell.com/)（訳注: 原文では「 callback hell 」です）を避けるために使用することができます。\r\nモダンな JavaScript プロジェクトで出会うますます頻繁に使われるようになっています。\r\n\r\n#### <a name=\"sample-code-4\"></a> サンプルコード\r\n\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n    .done(posts => res(posts))\r\n    .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n#### <a name=\"explanation-3\"></a> 説明\r\n\r\n*Ajax リクエスト* を行う場合は、時間のかかるリソースが求められることもあるので、レスポンスは同期的ではありません。\r\nリクエストされたリソースが何らかの理由で利用不可の場合（ 404 の場合）、レスポンスが戻ってこないこともあります。\r\n\r\nこのような状況を扱うために、 ES2015 は *プロミス* を提供しました。\r\nプロミスは異なる 3 つの状態を持つことができます:\r\n\r\n- ペンディング（訳注: 原文では「 Pending 」です）\r\n- フルフィルド（訳注: 原文では「 Fulfilled 」です）\r\n- リジェクテッド（訳注: 原文では「 Rejected 」です）\r\n\r\nプロミスを使って、リソース X をフェッチするために Ajax リクエストを扱う場合を考えてみましょう。\r\n\r\n##### <a name=\"create-the-promise\"></a> プロミスの作成\r\n\r\n最初にプロミスを作成します。\r\nX への Ajax リクエストを行うために jQuery の `get` メソッドを使います。\r\n\r\n```js\r\nconst xFetcherPromise = new Promise( // Create promise using \"new\" keyword and store it into a variable\r\n  function(resolve, reject) { // Promise constructor takes a function parameter which has resolve and reject parameters itself\r\n    $.get(\"X\") // Launch the Ajax request\r\n      .done(function(X) { // Once the request is done...\r\n        resolve(X); // ... resolve the promise with the X value as parameter\r\n      })\r\n      .fail(function(error) { // If the request has failed...\r\n        reject(error); // ... reject the promise with the error as parameter\r\n      });\r\n  }\r\n)\r\n```\r\n\r\n上の例のとおり、プロミスオブジェクトは、 2 つの引数 **`resolve`** と **`reject`** を受け取る *エクセキューター* 関数（訳注: 原文では「 executor function 」です）を受け取ります。\r\nこれらの引数は、プロミスの *ペンディング* ステートを *フルフィルド* ステートと *リジェクテッド* ステートのそれぞれに移行させるときに呼び出されます。\r\n\r\nプロミスはインスタンスが作成された後はペンディングステートになっており、 *エクセキューター* 関数が即座に実行されます。\r\n*エクセキューター* 関数の中で *`resolve`* か *`reject`* の一方が呼び出されたら、プロミスは関連づけられたハンドラーを呼び出します。\r\n\r\n##### <a name=\"promise-handlers-usage\"></a> プロミスハンドラーの使用\r\n\r\nプロミスの結果（もしくはエラー）を取得するには、次のようにしてハンドラーをアタッチする必要があります:\r\n\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err)\r\n  })\r\n```\r\n\r\nプロミスが成功すれば、 *`resolve`* が実行され ```.then``` の引数として渡された関数が実行されます。\r\n\r\nプロミスが失敗すれば、 *`reject`* が実行され、 ```.catch``` の引数として渡された関数が実行されます。\r\n\r\n> **メモ:** もし、対応するハンドラーがアタッチされたときにプロミスがすでにフルフィルドやリジェクテッドの状態になっていれば、そのハンドラーは呼び出されます。非同期の操作の完了とアタッチされるハンドラの間で競合状態は発生しません。（[参考: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Description)）\r\n\r\n#### <a name=\"external-resources-2\"></a> 外部のリソース\r\n\r\n- [JavaScript Promises for dummies - Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies)\r\n- [JavaScript Promise API - David Walsh](https://davidwalsh.name/promises)\r\n- [Using promises - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\r\n- [What is a promise - Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)\r\n- [JavaScript Promises: an Introduction - Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises)\r\n- [Promise documentation - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\r\n\r\n### <a name=\"template-literals\"></a> テンプレートリテラル\r\n\r\nテンプレートリテラルとは、単一行・複数行の文字列に対する [*式補完*](https://en.wikipedia.org/wiki/String_interpolation) （訳注: 原文は「 expression interpolation 」です）です。\r\n\r\n言い換えると、テンプレートリテラルは、 JavaScript の式（例えば変数）をその中で使える新しい文字列シンタックスです。\r\n\r\n#### <a name=\"sample-code-5\"></a> サンプルコード\r\n\r\n```js\r\nconst name = \"Nick\";\r\n`Hello ${name}, the following expression is equal to four : ${2+2}`;\r\n\r\n// Hello Nick, the following expression is equal to four: 4\r\n```\r\n\r\n#### <a name=\"external-resources-3\"></a> 外部のリソース\r\n\r\n- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)\r\n- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)\r\n\r\n### <a name=\"tagged-template-literals\"></a> タグ付きテンプレートリテラル\r\n\r\nテンプレートタグは *[テンプレートリテラル](#template-literals)にプリフィックスされる関数* です。\r\n関数がこの形で呼び出されたとき、第 1 引数はテンプレートの補完を行う変数と変数の間に現れる *文字列* からなる配列で、その後の引数は補完に使われる値です。\r\nこれをすべて捉えるにはスプレッド演算子を使用します。\r\n（[参考: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals)）\r\n\r\n> **メモ:** [styled-components](https://www.styled-components.com/) という有名なライブラリはこの機能を多用しています。\r\n\r\n次のコードは、タグ付きテンプレートリテラルがどのように動作するかを示す遊びのサンプルです。\r\n\r\n```js\r\nfunction highlight(strings, ...values) {\r\n  const interpolation = strings.reduce((prev, current) => {\r\n    return prev + current + (values.length ? \"<mark>\" + values.shift() + \"</mark>\" : \"\");\r\n  }, \"\");\r\n\r\n  return interpolation;\r\n}\r\n\r\nconst condiment = \"jam\";\r\nconst meal = \"toast\";\r\n\r\nhighlight`I like ${condiment} on ${meal}.`;\r\n// \"I like <mark>jam</mark> on <mark>toast</mark>.\"\r\n```\r\n\r\n次はもっとおもしろいサンプルです:\r\n\r\n```js\r\nfunction comma(strings, ...values) {\r\n  return strings.reduce((prev, next) => {\r\n    let value = values.shift() || [];\r\n    value = value.join(\", \");\r\n    return prev + next + value;\r\n  }, \"\");\r\n}\r\n\r\nconst snacks = ['apples', 'bananas', 'cherries'];\r\ncomma`I like ${snacks} to snack on.`;\r\n// \"I like apples, bananas, cherries to snack on.\"\r\n```\r\n\r\n#### <a name=\"external-resources-4\"></a> 外部のリソース\r\n\r\n- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)\r\n- [Library of common template tags](https://github.com/declandewet/common-tags)\r\n\r\n### <a name=\"imports--exports\"></a> インポート / エクスポート\r\n\r\nES6 モジュールは、他のモジュールが明示的にエクスポートした変数や関数にモジュールがアクセスするために使用するための方法です。\r\n\r\nインポート / エクスポートに関する MDN のリソース（下の外部のリソースのところをご覧ください）を見ることを強くおすすめします。\r\nそのリソースはわかりやすいと同時に、ポイントが網羅されています。\r\n\r\n#### <a name=\"explanation-with-sample-code-1\"></a> サンプルコード付きの説明\r\n\r\n##### <a name=\"named-exports\"></a> 名前付きエクスポート\r\n\r\n名前付きエクスポート（訳注: 原文では「 named exports 」です）は、モジュールから複数の値をエクスポートするための方法です。\r\n\r\n> **メモ:** 名前付きエクスポートは、名前の付いた[第一級オブジェクト](https://en.wikipedia.org/wiki/First-class_citizen)に対してのみ可能です。\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js'; // Named import -- destructuring-like syntax\r\nconsole.log(pi) // 3.14\r\nconsole.log(exp) // 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js'; // Inject all exported values into constants variable\r\nconsole.log(constants.pi) // 3.14\r\nconsole.log(constants.exp) // 2.7\r\n```\r\n\r\n名前付きインポートは *分割* に似ていますが、シンタックスが異なり、分割と同じものではありません。\r\n名前付きインポートは、デフォルト値や *深い* （訳注: 原文では「 deep 」です）分割をサポートしていません。\r\n\r\n加えて、エイリアスを使うことができますが、そのシンタックスは分割のものとは異なります:\r\n\r\n```js\r\nimport { foo as bar } from 'myFile.js'; // foo is imported and injected into a new bar variable\r\n```\r\n\r\n##### <a name=\"default-import--export\"></a> デフォルトインポート / エクスポート\r\n\r\nデフォルトエクスポートに関しては、モジュールごとにひとつだけデフォルトエクスポートがあります。\r\nデフォルトエクスポートは、関数、クラス、オブジェクトその他どんなものにもすることができます。\r\nデフォルトエクスポートはインポートするときの最もシンプルな形なので、その値は「メイン」のエクスポート値とみなされます。\r\n（[参考: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Description)）\r\n\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n// Default export, independently from its name, is automatically injected into number variable;\r\nconsole.log(number) // 42\r\n```\r\n\r\n関数のエクスポート:\r\n\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // 3\r\n```\r\n\r\n#### <a name=\"external-resources-5\"></a> 外部のリソース\r\n\r\n- [ES6 Modules in bulletpoints](https://ponyfoo.com/articles/es6#modules)\r\n- [Export - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\r\n- [Import - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/)\r\n- [Destructuring special case - import statements](https://ponyfoo.com/articles/es6-destructuring-in-depth#special-case-import-statements)\r\n- [Misunderstanding ES6 Modules - Kent C. Dodds](https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0)\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript)\r\n\r\n### <a name=\"-javascript-this\"></a> <a name=\"this_def\"></a>  JavaScript の *`this`*\r\n\r\n*`this`* 演算子の振る舞いは他の言語とは異なり、ほとんどの場合、関数の呼び出し方によって決まります。\r\n（[参考: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)）\r\n\r\nこの概念にはややこしいポイントがたくさんあり非常に難しいので、以下にあげる外部のリソースを深く読むことを強くおすすめします。\r\nそのため、ここでは *`this`* の中身が何になるかを理解するための個人的なアイデアを紹介することにします。\r\nこの考え方は [Yehuda Katz が書いた記事](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) からのものです。\r\n\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// After each statement, you find the value of *this* in myFunc\r\n\r\nmyFunc.call(\"myString\", \"hello\") // \"myString\" -- first .call parameter value is injected into *this*\r\n\r\n// In non-strict-mode\r\nmyFunc(\"hello\") // window -- myFunc() is syntax sugar for myFunc.call(window, \"hello\")\r\n\r\n// In strict-mode\r\nmyFunc(\"hello\") // undefined -- myFunc() is syntax sugar for myFunc.call(undefined, \"hello\")\r\n```\r\n\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\") // person Object -- first call parameter is injected into *this*\r\nperson.myFunc(\"test\") // person Object -- person.myFunc() is syntax sugar for person.myFunc.call(person, \"test\")\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"hello\") // Creates a new function in which we inject \"hello\" in *this* value\r\nperson.myFunc(\"test\") // person Object -- The bind method has no effect on the original method\r\nmyBoundFunc(\"test\") // \"hello\" -- myBoundFunc is person.myFunc with \"hello\" bound to *this*\r\n```\r\n\r\n#### <a name=\"external-resources-6\"></a> 外部のリソース\r\n\r\n- [Understanding JavaScript Function Invocation and \"this\" - Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)\r\n- [JavaScript this - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\r\n\r\n### <a name=\"class\"></a> クラス\r\n\r\nJavaScript は [プロトタイプベース](https://en.wikipedia.org/wiki/Prototype-based_programming) の言語です（例えば、 Java は [クラスベース](https://en.wikipedia.org/wiki/Class-based_programming) の言語です）。\r\nES6 は、プロトタイプベースの継承に対するシンタックスシュガー（訳注: 原文では「 syntactic sugar 」です）としての JavaScript のクラスを導入しました。\r\nこれは新しいクラスベースの継承モデルでは **ありません** 。\r\n\r\nもしあなたが他の言語のクラスに馴れていれば、 *クラス* ということばは混乱を招く可能性があります。\r\nもし他の言語のクラスに馴れているなら、 JavaScript のクラスも同じようなものだと考えたりはせず、まったく別物の概念だと考えましょう。\r\n\r\nこのドキュメントは JavaScript についてゼロから教えようとするものではないため、読者は、プロトタイプが何であって、どのように振る舞うかを知っているものとします。\r\nもしプロトタイプについてよく知らなければ、次のサンプルコードの下に記載された外部のリソースをご覧ください。\r\n\r\n#### <a name=\"samples\"></a> サンプルコード\r\n\r\nES6 以前のプロトタイプ構文:\r\n\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n}\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n}\r\n```\r\n\r\nES6 のクラス構文:\r\n\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Manu\", 23);\r\nconsole.log(myPerson.age) // 23\r\nconsole.log(myPerson.stringSentence()) // \"Hello, my name is Manu and I'm 23\r\n```\r\n\r\n#### <a name=\"external-resources-7\"></a> 外部のリソース\r\n\r\nプロトタイプの理解のためのリソース:\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\nクラスの理解のためのリソース:\r\n\r\n- [ES6 Classes in Depth - Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features - Classes](http://es6-features.org/#ClassDefinition)\r\n- [JavaScript Classes - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\r\n\r\n### <a name=\"extends-and-super-keywords\"></a> `extends` キーワードと `super` キーワード\r\n\r\n`extends` キーワードは、他のクラスの子どもとなるクラスを作成するために、クラス宣言あるいはクラス式に使われます（[参考: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)）。\r\nサブクラスはスーパークラスのすべてのプロパティを継承し、追加で新しいプロパティを追加したり継承したプロパティを変更したりすることができます。\r\n\r\n`super` キーワードはオブジェクトの親の関数を呼び出すために使用します。\r\nこれにはコンストラクターも含まれます。\r\n\r\n- コンストラクターの中では、 `super` キーワードは `this` キーワードが使われる前に使わなくてはなりません。\r\n- `super()` を呼び出すと親クラスのコンストラクターが呼ばれます。クラスのコンストラクターに引数を渡したいときは、 `super(arguments)` という形で呼び出します。\r\n- 親クラスが `X` というメソッドを持つ場合は（スタティックメソッドでもよい）、子クラスの中で `super.X()` とすればそれを呼び出すことができます。\r\n\r\n#### <a name=\"sample-code-6\"></a> サンプルコード\r\n\r\n```js\r\nclass Polygon {\r\n  constructor(height, width) {\r\n    this.name = 'Polygon';\r\n    this.height = height;\r\n    this.width = width;\r\n  }\r\n\r\n  getHelloPhrase() {\r\n    return `Hi, I am a ${this.name}`;\r\n  }\r\n}\r\n\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    // Here, it calls the parent class' constructor with lengths\r\n    // provided for the Polygon's width and height\r\n    super(length, length);\r\n    // Note: In derived classes, super() must be called before you\r\n    // can use 'this'. Leaving this out will cause a reference error.\r\n    this.name = 'Square';\r\n    this.length = length;\r\n  }\r\n\r\n  getCustomHelloPhrase() {\r\n    const polygonPhrase = super.getHelloPhrase(); // accessing parent method with super.X() syntax\r\n    return `${polygonPhrase} with a length of ${this.length}`;\r\n  }\r\n\r\n  get area() {\r\n    return this.height * this.width;\r\n  }\r\n}\r\n\r\nconst mySquare = new Square(10);\r\nconsole.log(mySquare.area) // 100\r\nconsole.log(mySquare.getHelloPhrase()) // 'Hi, I am a Square' -- Square inherits from Polygon and has access to its methods\r\nconsole.log(mySquare.getCustomHelloPhrase()) // 'Hi, I am a Square with a length of 10'\r\n```\r\n\r\n**メモ:** `Square` クラスの中で `super()` を呼ぶ前に `this` を使おうとすると、 `ReferenceError` が発生します:\r\n\r\n```js\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    this.height; // ReferenceError, super needs to be called first!\r\n\r\n    // Here, it calls the parent class' constructor with lengths\r\n    // provided for the Polygon's width and height\r\n    super(length, length);\r\n\r\n    // Note: In derived classes, super() must be called before you\r\n    // can use 'this'. Leaving this out will cause a reference error.\r\n    this.name = 'Square';\r\n  }\r\n}\r\n```\r\n\r\n#### <a name=\"external-resources-8\"></a> 外部のリソース\r\n\r\n- [Extends - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)\r\n- [Super operator - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super)\r\n- [Inheritance - MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance)\r\n\r\n### <a name=\"async-await\"></a> Async Await\r\n\r\n[プロミス](#promises) に加えて、 *`async`* / *`await`* という非同期なコードを扱うための新しい構文を見ることがあるかもしれません。\r\n\r\n`async` / `await` 関数の目的は、プロミスを同期的に利用する振る舞いをシンプルにすることです。\r\nそして、プロミスのグループを扱うことです。\r\nプロミスが構造化されたコールバックに似ているのと同じように、 `async` / `await` もジェネレーターとプロミスの組み合わせに似ています。\r\n`async` 関数は *常に* プロミスを返します。\r\n（[参考: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)）\r\n\r\n> **メモ:** `async` / `await` はプロミスをベースにしているため、 `async` / `await` を理解しようとする前に、プロミスがどんなもので、どのように動作するのかを理解する必要があります。\r\n\r\n> **メモ 2:** [*`await`* は *`async`* 関数の中で使わなくてはなりません](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0) 。これは、 `await` はコードのトップレベルでは使えない（コードのトップレベルは `async` 関数の中に入っていないので）、という意味です。\r\n\r\n#### <a name=\"sample-code-7\"></a> サンプルコード\r\n\r\n```js\r\nasync function getGithubUser(username) { // async keyword allows usage of await in the function and means function returns a promise\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Execution is paused here until the Promise returned by fetch is resolved\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user)) // logging user response - cannot use await syntax since this code isn't in async function\r\n  .catch(err => console.log(err)); // if an error is thrown in our async function, we will catch it here\r\n```\r\n\r\n#### <a name=\"explanation-with-sample-code-2\"></a> サンプルコード付きの説明\r\n\r\n*`async`* / *`await`* はプロミスの上に構築されていますが、これらを使うとより命令型のスタイルでコードを書くことができます。\r\n\r\n*`async`* 演算子は関数に非同期のマークを付けて、常に *プロミス* を返す形にします。\r\n *`async`* 関数の中で *`await`* 演算子を使うことで、その式の戻り値のプロミスがリゾルブかリジェクトのどちらかをするまで（原文では「 until the returned Promise from the expression either resolves or rejects 」です）その行で処理を一時停止することができます。\r\n\r\n```js\r\nasync function myFunc() {\r\n  // we can use await operator because this function is async\r\n  return \"hello world\";\r\n}\r\n\r\nmyFunc().then(msg => console.log(msg)) // \"hello world\" -- myFunc's return value is turned into a promise because of async operator\r\n```\r\n\r\n`async` 関数の *`return`* 文に到達したときに、プロミスは戻り値を持ってフルフィルされます（訳注: 原文では「 is fullfilled with the value returned 」）。\r\n`async` 関数の中でエラーが発生したら、プロミスのステートは *リジェクテッド* に変わります。\r\n`async` 関数に戻り値が無い場合も、 `async` 関数の実行が完了したときにはプロミスが返され、値を持たずにリゾルブが発生します。\r\n\r\n*`await`* 演算子は *プロミス* がフルフィルドになるのを待つために使用するものであり、 *`async`* 関数のボディの中でのみ使用することができます。\r\n処理が *`await`* のところに来たら、プロミスがフルフィルされるまで処理が一時停止されます。\r\n\r\n> **メモ:** *`fetch`* は Ajax リクエストができるプロミスを返す関数です。\r\n\r\nまず、プロミスを使うと GitHub ユーザー情報の取得がどのようにできたかを見てみましょう:\r\n\r\n```js\r\nfunction getGithubUser(username) {\r\n  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n*`async`* / *`await`* で同じことをすると次のようになります:\r\n\r\n```js\r\nasync function getGithubUser(username) { // promise + await keyword usage allowed\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Execution stops here until fetch promise is fulfilled\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n*`async`* / *`await`* 構文は依存関係のある複数のプロミスをチェインするときに特に便利です。\r\n\r\n例えば、データベースにあるブログ投稿と作成者情報をフェッチするためのトークンを取得する必要がある場合は次のようになります:\r\n\r\n> **メモ:** リゾルブされた値のメソッドやプロパティを同一行で利用する場合、 *`await`* 式はかっこで囲う必要があります。\r\n\r\n```js\r\nasync function fetchPostById(postId) {\r\n  const token = (await fetch('token_url')).json().token;\r\n  const post = (await fetch(`/posts/${postId}?token=${token}`)).json();\r\n  const author = (await fetch(`/users/${post.authorId}`)).json();\r\n\r\n  post.author = author;\r\n  return post;\r\n}\r\n\r\nfetchPostById('gzIrzeo64')\r\n  .then(post => console.log(post))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n##### <a name=\"error-handling\"></a> エラーハンドリング\r\n\r\n*`await`* 式の周りに *`try`* / *`catch`* のブロックを追加しておかないと、キャッチされない例外がーー *`async`* 関数のボディの中で投げられたかどうかにかかわらず、また、 *`await`* でサスペンドされていても ーー *`async`* 関数が返したプロミスをリジェクトします。\r\n`async` 関数の中で `throw` 文を使うことは、リジェクトするプロミスを返すことと同じ意味です。\r\n（[(参考: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling)）\r\n\r\n> **メモ:** プロミスは同じように振る舞います！\r\n\r\nプロミスを使った場合、エラーチェインの処理は次のようにしていました:\r\n\r\n```js\r\nfunction getUser() { // This promise will be rejected!\r\n  return new Promise((res, rej) => rej(\"User not found !\"));\r\n}\r\n\r\nfunction getAvatarByUsername(userId) {\r\n  return getUser(userId).then(user => user.avatar);\r\n}\r\n\r\nfunction getUserAvatar(username) {\r\n  return getAvatarByUsername(username).then(avatar => ({ username, avatar }));\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\n*`async`* / *`await`* で同じことをすると次のようになります:\r\n\r\n```js\r\nasync function getUser() { // The returned promise will be rejected!\r\n  throw \"User not found !\";\r\n}\r\n\r\nasync function getAvatarByUsername(userId) => {\r\n  const user = await getUser(userId);\r\n  return user.avatar;\r\n}\r\n\r\nasync function getUserAvatar(username) {\r\n  var avatar = await getAvatarByUsername(username);\r\n  return { username, avatar };\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\n#### <a name=\"external-resources-9\"></a> 外部のリソース\r\n\r\n- [Async/Await - JavaScript.Info](https://javascript.info/async-await)\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/)\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9)\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits)\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n- [Async Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\r\n- [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\r\n- [Using async / await in express with node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n\r\n### <a name=\"truthy--falsy\"></a> True になるもの / False になるもの\r\n\r\nJavaScript では、 `true` になる値と `false` になる値は、真偽判定のコンテキストで評価されたとき（訳注: 原文では「 when evaluated in a boolean context 」です）に真偽値にキャストされます。\r\n真偽判定のコンテキストの例は、 ```if``` 条件での判定です。\r\n\r\n次の値に等しくない値はすべて ```true``` にキャストされます:\r\n\r\n- ```false```\r\n- ```0```\r\n- ```\"\"``` （空文字列）\r\n- ```null```\r\n- ```undefined```\r\n- ```NaN```\r\n\r\n*真偽判定のコンテキスト* の例は次のとおりです:\r\n\r\n- ```if``` 条件評価\r\n\r\n```js\r\nif (myVar) {}\r\n```\r\n\r\n```myVar``` にはどんな[第一級市民](https://en.wikipedia.org/wiki/First-class_citizen)（変数、関数、真偽値）を置くこともできますが、真偽判定のコンテキストで評価されているため真偽値にキャストされます。\r\n\r\n- 論理 **否定** 演算子 ```!``` の後\r\n\r\nこの演算子はそのオペランドが `true` に変換できる場合は `false` を返します。\r\n逆の場合は `true` を返します。\r\n\r\n```js\r\n!0 // true -- 0 is falsy so it returns true\r\n!!0 // false -- 0 is falsy so !0 returns true so !(!0) returns false\r\n!!\"\" // false -- empty string is falsy so NOT (NOT false) equals false\r\n```\r\n\r\n- *真偽値* オブジェクトコンストラクターでの使用\r\n\r\n```js\r\nnew Boolean(0) // false\r\nnew Boolean(1) // true\r\n```\r\n\r\n- 三項演算子の評価部分（訳注: 原文では「 In a ternary evaluation 」です）\r\n\r\n```js\r\nmyVar ? \"truthy\" : \"falsy\"\r\n```\r\n\r\n`myVar` は真偽判定コンテキストで評価されます。\r\n\r\n2 つの値の比較には注意が必要です。\r\n\r\n（最終的に真偽値にキャストされる）比較対象のオブジェクトの値は、真偽値にキャストされるのでは **なく** 、 [プリミティブへの変換仕様](http://javascript.info/object-toprimitive) に基いて、プリミティブ値に変換されます。\r\n内部的には、 `[] == true` のようにオブジェクトが真偽値と比較された場合、 `[].toString() == true` という比較が行われます。\r\n\r\n```js\r\nlet a = [] == true // a is false since [].toString() give \"\" back.\r\nlet b = [1] == true // b is true since [1].toString() give \"1\" back.\r\nlet c = [2] == true // c is false since [2].toString() give \"2\" back.\r\n```\r\n\r\n#### <a name=\"external-resources-10\"></a> 外部のリソース\r\n\r\n- [Truthy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)\r\n- [Falsy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)\r\n- [Truthy and Falsy values in JS - Josh Clanton](http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html)\r\n\r\n### <a name=\"anamorphisms-and-catamorphisms\"></a> アナモルフィズム / カタモルフィズム\r\n\r\n#### <a name=\"anamorphisms\"></a> アナモルフィズム\r\n\r\nアナモルフィズム（訳注: 原文では「 anamorphisms 」です）とは、あるオブジェクトを、オブジェクト型を含むより複雑な構造体にマップする関数のことです。\r\nそれは、シンプルな構造体を複雑な構造体に *アンフォールド* する（訳注: 原文では「 unfolding 」です）処理です。\r\n整数を、整数のリストにアンフォールドする場合を考えてみましょう。\r\nこの場合、整数が最初のオブジェクトで、整数のリストがより複雑な構造体です。\r\n\r\n**サンプルコード**\r\n\r\n```js\r\nfunction downToOne(n) {\r\n  const list = [];\r\n\r\n  for (let i = n; i > 0; --i) {\r\n    list.push(i);\r\n  }\r\n\r\n  return list;\r\n}\r\n\r\ndownToOne(5)\r\n  //=> [ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\n#### <a name=\"catamorphisms\"></a> カタモルフィズム\r\n\r\nカタモルフィズム（訳注: 原文では「 catamorphisms 」です）とは、アナモルフィズムの逆で、複雑な構造体であるオブジェクトをよりシンプルな構造体に *フォールド* する（訳注: 原文では「 fold 」です）ことです。\r\n次の `product` のサンプルを見てください。\r\n`product` は整数のリストを受け取り単一の整数を返します。\r\n\r\n**サンプルコード**\r\n\r\n```js\r\nfunction product(list) {\r\n  let product = 1;\r\n\r\n  for (const n of list) {\r\n    product = product * n;\r\n  }\r\n\r\n  return product;\r\n}\r\n\r\nproduct(downToOne(5)) // 120\r\n```\r\n\r\n#### <a name=\"external-resources-11\"></a> 外部のリソース\r\n\r\n* [Anamorphisms in JavaScript](http://raganwald.com/2016/11/30/anamorphisms-in-javascript.html)\r\n* [Anamorphism](https://en.wikipedia.org/wiki/Anamorphism)\r\n* [Catamorphism](https://en.wikipedia.org/wiki/Catamorphism)\r\n\r\n### <a name=\"generators\"></a> ジェネレーター\r\n\r\n`downToOne` 関数を書く別の方法として、ジェネレーターを使ったものがあります。\r\n`Generator` オブジェクトを生成するには、 `function *` 宣言を使わなくてはいけません。\r\nジェネレーターは、一度脱出した後に、コンテキスト（変数バインディング）を保った形で再突入できる関数です（訳注: 原文では「 Generators are functions that can be exited and later re-entered with its context (variable bindings) saved across re-entrances 」です）。\r\n\r\n例えば、上の `downToOne` 関数は次のように書き直すことができます:\r\n\r\n```js\r\nfunction * downToOne(n) {\r\n  for (let i = n; i > 0; --i) {\r\n    yield i;\r\n  }\r\n}\r\n\r\n[...downToOne(5)] //[ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\nジェネレーターはイテラブルオブジェクトを返します。\r\nイテレーターの `next()` 関数が呼ばれると、最初の `yield` 式までが実行されます。\r\n`yield` 式はイテレーターから返すべき値を指定します。\r\n`yield*` を使えば、その処理が別のジェネレーター関数に委譲されます。\r\nジェネレーター式の中で `return` 式が呼ばれると、それはジェネレーターに完了済みという印を付けて、戻り値として返します。\r\nさらに `next()` を呼び出しても新しい値が返されることはありません。\r\n\r\n**サンプルコード**\r\n\r\n```js\r\n// Yield Example\r\nfunction * idMaker() {\r\n  var index = 0;\r\n  while (index < 2) {\r\n    yield index;\r\n    index = index + 1;\r\n  }\r\n}\r\n\r\nvar gen = idMaker();\r\n\r\ngen.next().value; // 0\r\ngen.next().value; // 1\r\ngen.next().value; // undefined\r\n```\r\n\r\n`yield*` 式を使えば、ジェネレーターの繰り返しの中で別のジェネレーターを呼び出すことができます。\r\n\r\n```js\r\n// Yield * Example\r\nfunction * genB(i) {\r\n  yield i + 1;\r\n  yield i + 2;\r\n  yield i + 3;\r\n}\r\n\r\nfunction * genA(i) {\r\n  yield i;\r\n  yield* genB(i);\r\n  yield i + 10;\r\n}\r\n\r\nvar gen = genA(10);\r\n\r\ngen.next().value; // 10\r\ngen.next().value; // 11\r\ngen.next().value; // 12\r\ngen.next().value; // 13\r\ngen.next().value; // 20\r\n```\r\n\r\n```js\r\n// Generator Return Example\r\nfunction* yieldAndReturn() {\r\n  yield \"Y\";\r\n  return \"R\";\r\n  yield \"unreachable\";\r\n}\r\n\r\nvar gen = yieldAndReturn()\r\ngen.next(); // { value: \"Y\", done: false }\r\ngen.next(); // { value: \"R\", done: true }\r\ngen.next(); // { value: undefined, done: true }\r\n```\r\n\r\n#### <a name=\"external-resources-12\"></a> 外部のリソース\r\n\r\n* [Mozilla MDN Web Docs, Iterators and Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators)\r\n\r\n### <a name=\"static-methods\"></a> スタティックメソッド\r\n\r\n#### <a name=\"short-explanation-1\"></a> 短い説明\r\n\r\n`static` キーワードは、スタティックメソッドを宣言するためにクラスの中で使用します。\r\nスタティックメソッドはクラスの中の関数であり、クラスオブジェクトに所属します。\r\nそのクラスのインスタンスからは利用することができません。\r\n\r\n#### <a name=\"sample-code-8\"></a> サンプルコード\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n}\r\n\r\n//Note that we did not have to create an instance of the Repo class\r\nconsole.log(Repo.getName()) //Repo name is modern-js-cheatsheet\r\n\r\nlet r = new Repo();\r\nconsole.log(r.getName()) //Uncaught TypeError: repo.getName is not a function\r\n```\r\n\r\n#### <a name=\"detailed-explanation-2\"></a> 詳細な説明\r\n\r\nスタティックメソッドは、 `this` キーワードを使えば別のスタティックメソッドの中から呼ぶことができます。\r\nしかし、スタティックではないメソッド（訳注: 原文では「 non-static methods 」です）の場合はこれはできません。\r\nスタティックでないメソッドが `this` キーワードを使ってスタティックメソッドに直接アクセスすることはできません。\r\n\r\n##### <a name=\"calling-other-static-methods-from-a-static-method\"></a> スタティックメソッドから別のスタティックメソッドを呼ぶ\r\n\r\nスタティックメソッドを別のスタティックメソッドから呼び出すには、次のように `this` キーワードを使うことができます:\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  static modifyName(){\r\n    return this.getName() + '-added-this'\r\n  }\r\n}\r\n\r\nconsole.log(Repo.modifyName()) //Repo name is modern-js-cheatsheet-added-this\r\n```\r\n\r\n##### <a name=\"calling-static-methods-from-non-static-methods\"></a> スタティックでないメソッドからスタティックメソッドを呼ぶ\r\n\r\nスタティックでないメソッドからはスタティックメソッドを呼ぶ方法が 2 つあります:\r\n\r\nNon-static methods can call static methods in 2 ways;\r\n\r\n1. クラス名を使う\r\n\r\nスタティックでないメソッドからスタティックメソッドにアクセスするには、クラス名を使って、プロパティのような形でスタティックメソッドを呼び出します。\r\n例: `ClassName.StaticMethodName`\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    return Repo.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// we need to instantiate the class to use non-static methods\r\nlet r = new Repo()\r\nconsole.log(r.useName()) //Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n2. コンストラクターを使う\r\n\r\nスタティックメソッドは `constructor` オブジェクトのプロパティとして呼ぶことができます。\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    //Calls the static method as a property of the constructor\r\n    return this.constructor.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// we need to instantiate the class to use non-static methods\r\nlet r = new Repo()\r\nconsole.log(r.useName()) //Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n#### <a name=\"external-resources-13\"></a> 外部のリソース\r\n\r\n- [static keyword- MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)\r\n- [Static Methods- Javascript.info](https://javascript.info/class#static-methods)\r\n- [Static Members in ES6- OdeToCode](http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx)\r\n\r\n## <a name=\"glossary\"></a> 用語集\r\n\r\n### <a name=\"-scope\"></a> <a name=\"scope_def\"></a> スコープ\r\n\r\n値と式が「見え」て、参照可能な場合なコンテキストのこと。\r\n変数やその他の式が「カレントスコープ」に無い場合は、それらは利用することができません。\r\n\r\nソース: [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\r\n\r\n### <a name=\"-variable-mutation\"></a> <a name=\"mutation_def\"></a> 変数ミューテーション\r\n\r\n初期値が後から変更されたとき、その変数はミューテートされた（訳注: 原文では「 have been mutated 」です）と言います。\r\n\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // myArray is being mutated\r\n```\r\n\r\nもしある変数がミューテートできなければ、その変数は *イミュータブル* である（訳注: 原文では「 immutable 」です）と言います。\r\n\r\n詳しくは、 [MDN の Mutable の記事](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) をご覧ください。\r\n"
  },
  {
    "path": "JavaScript/translations/pl_PL.md",
    "content": "﻿﻿# <a name=\"modern-javascript-cheatsheet\"></a>Współczesny JavaScript - ściągawka\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Image Credits: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## <a name=\"introduction\"></a>Wstęp\r\n\r\n### <a name=\"motivation\"></a>Motywacja\r\n\r\nW tym dokumencie zebrane zostały elementy języka JavaScript, z którymi często można się spotkać we współczesnych projektach i najnowszych przykładach kodu.\r\n\r\nCelem tego przewodnika nie jest nauka JavaScriptu od zera, ale pomoc posiadającym podstawową wiedzę developerom, którzy pracując ze współczesnymi bazami kodu (powiedzmy, ucząc się React) napotykają trudności, wynikające z użytych tam konceptów języka JavaScript.\r\n\r\nPrócz tego, od czasu do czasu będę zamieszczał własne porady, z którymi niekoniecznie trzeba się zgadzać, ale postaram się za każdym razem podkreślać, że chodzi tylko o moja opinię.\r\n\r\n> **Uwaga:** Większość omawianych tu pojęć pochodzi z nowej wersji języka JavaScript (ES2015, często nazywanego ES6). Bardzo dobre omówienie nowych możliwości wprowadzonych w tej wersji można znaleźć [tutaj](http://es6-features.org).\r\n\r\n### <a name=\"complementary-resources\"></a>Materiały uzupełniające\r\n\r\nJeśli masz problem ze zrozumieniem jakiegoś pojęcia, proponuję poszukać odpowiedzi w poniższych źródłach:\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/en-US/search?q=)\r\n- [You don't know JS (book)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Features with examples](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Javascript Basics for Beginners](https://www.udacity.com/course/javascript-basics--ud804) - bezpłatny kurs od Udacity\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) - dla znalezienia specjalistycznych blogów i innych źródeł\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript)\r\n\r\n## <a name=\"table-of-contents\"></a>Spis treści\r\n\r\n- [Współczesny JavaScript - ściągawka](#modern-javascript-cheatsheet)\r\n  * [Wstęp](#introduction)\r\n    + [Motywacja](#motivation)\r\n    + [Materiały uzupełniające](#complementary-resources)\r\n  * [Spis treści](#table-of-contents)\r\n  * [Pojęcia](#notions)\r\n    + [Deklaracja zmiennych: var, const, let](#variable-declaration-var-const-let)\r\n      - [Krótkie wyjaśnienie](#short-explanation)\r\n      - [Przykładowy kod](#sample-code)\r\n      - [Szczegółowe wyjaśnienie](#detailed-explanation)\r\n      - [Dodatkowe źródła](#external-resource)\r\n    + [Funkcje strzałkowe (arrow functions)](#-arrow-function)\r\n      - [Przykładowy kod](#sample-code-1)\r\n      - [Szczegółowe wyjaśnienie](#detailed-explanation-1)\r\n        * [Zwięzłość](#concision)\r\n        * [Użycie *this*](#this-reference)\r\n      - [Pomocne źródła](#useful-resources)\r\n    + [Domyślna wartość argumentów funkcji](#function-default-parameter-value)\r\n      - [Dodatkowe źródła](#external-resource-1)\r\n    + [Destrukturyzacja obiektów i tablic](#destructuring-objects-and-arrays)\r\n      - [Wyjaśnienie z przykładowym kodem](#explanation-with-sample-code)\r\n      - [Pomocne źródła](#useful-resources-1)\r\n    + [Metody tablicowe - map / filter / reduce](#array-methods---map--filter--reduce)\r\n      - [Przykładowy kod](#sample-code-2)\r\n      - [Wyjaśnienie](#explanation)\r\n        * [Array.prototype.map()](#arrayprototypemap)\r\n        * [Array.prototype.filter()](#arrayprototypefilter)\r\n        * [Array.prototype.reduce()](#arrayprototypereduce)\r\n      - [Dodatkowe źródła](#external-resource-2)\r\n    + [Operator rozwijania \"...\"](#spread-operator-)\r\n      - [Przykładowy kod](#sample-code-3)\r\n      - [Wyjaśnienie](#explanation-1)\r\n        * [W obiektach iterowalnych (np. w tablicach)](#in-iterables-like-arrays)\r\n        * [Parametry rest](#function-rest-parameter)\r\n        * [Rozwijanie własności obiektów](#object-properties-spreading)\r\n      - [Dodatkowe źródła](#external-resources)\r\n    + [Skrócony zapis własności obiektów](#object-property-shorthand)\r\n      - [Wyjaśnienie](#explanation-2)\r\n      - [Dodatkowe źródła](#external-resources-1)\r\n    + [Obietnice (promises)](#promises)\r\n      - [Przykładowy kod](#sample-code-4)\r\n      - [Wyjaśnienie](#explanation-3)\r\n        * [Tworzenie obietnicy (promise)](#create-the-promise)\r\n        * [Użycie procedur obsługi](#promise-handlers-usage)\r\n      - [Dodatkowe źródła](#external-resources-2)\r\n    + [Łańcuchy szablonowe (template literals)](#template-literals)\r\n      - [Przykładowy kod](#sample-code-5)\r\n      - [Dodatkowe źródła](#external-resources-3)\r\n    + [Oznaczone łańcuchy szablonowe (tagged template literals)](#tagged-template-literals)\r\n      - [Dodatkowe źródła](#external-resources-4)\r\n    + [Importy / eksporty](#imports--exports)\r\n      - [Wyjaśnienie z przykładowym kodem](#explanation-with-sample-code-1)\r\n        * [Nazwane eksporty (named exports)](#named-exports)\r\n        * [Domyślny import / eksport](#default-import--export)\r\n      - [Dodatkowe źródła](#external-resources-5)\r\n    + [*this* w JavaScript](#-javascript-this)\r\n      - [Dodatkowe źródła](#external-resources-6)\r\n    + [Klasa](#class)`\r\n      - [Przykłady](#samples)\r\n      - [Dodatkowe źródła](#external-resources-7)\r\n    + [Słowa kluczowe extends i super](#extends-and-super-keywords)\r\n      - [Przykładowy kod](#sample-code-6)\r\n      - [Dodatkowe źródła](#external-resources-8)\r\n    + [Składnia async/await](#async-await)\r\n      - [Przykładowy kod](#sample-code-7)\r\n      - [Wyjaśnienie z przykładowym kodem](#explanation-with-sample-code-2)\r\n      - [Obsługa błędów](#error-handling)\r\n      - [Dodatkowe źródła](#external-resources-9)\r\n    + [Prawda / Fałsz](#truthy--falsy)\r\n      - [Dodatkowe źródła](#external-resources-10)\r\n    + [Anamorfizmy i Katamorfizmy](#anamorphisms-and-catamorphisms)\r\n      - [Anamorfizmy](#anamorphisms)\r\n      - [Katamorfizmy](#catamorphisms)\r\n      - [Dodatkowe źródła](#external-resources-11)\r\n    + [Generatory](#generators)\r\n      - [Dodatkowe źródła](#external-resources-12)\r\n    + [Metody statyczne](#static-methods)\r\n      - [Krótkie wyjaśnienie](#short-explanation-1)\r\n      - [Przykładowy kod](#sample-code-8)\r\n      - [Szczegółowe wyjaśnienie](#detailed-explanation-2)\r\n        * [Wzywanie innych metod statycznych z metody statycznej](#calling-other-static-methods-from-a-static-method)\r\n        * [Wzywanie metod statycznych z metod niestatycznych](#calling-static-methods-from-non-static-methods)\r\n      - [Dodatkowe źródła](#external-resources-13)\r\n  * [Słowniczek](#glossary)\r\n    + [Zakres widoczności (scope)](#-scope)\r\n    + [Przekształcenie zmiennej (variable mutation)](#-variable-mutation)\r\n\r\n## <a name=\"notions\"></a>Pojęcia\r\n\r\n### <a name=\"variable-declaration-var-const-let\"></a>Deklaracja zmiennych: var, const, let\r\n \r\nW języku JavaScript mamy do dyspozycji trzy słowa kluczowe, za pomocą których deklarowane są zmienne. Są to ```var```, ```let``` and ```const```.\r\n\r\n#### <a name=\"short-explanation\"></a>Krótkie wyjaśnienie\r\n\r\nZmienne deklarowane z użyciem ```const``` nie moga być ponownie przypisane, natomiast ```let``` i ```var``` mogą.\r\n\r\nRadziłbym zawsze deklarować zmienne za pomocą ```const```, a ```let``` stosować, kiedy zamierzamy *przekształcać* zmienne bądź przypisywać im inną wartość.\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>Zakres widoczności</th>\r\n    <th>Można nadpisać</th>\r\n    <th>Można zmienić</th>\r\n   <th><a href=\"#tdz_sample\">Czasowo martwa strefa</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>const</th>\r\n    <td>Blok</td>\r\n    <td>Nie</td>\r\n    <td><a href=\"#const_mutable_sample\">Tak</a></td>\r\n    <td>Tak</td>\r\n  </tr>\r\n  <tr>\r\n    <th>let</th>\r\n    <td>Blok</td>\r\n    <td>Tak</td>\r\n    <td>Tak</td>\r\n    <td>Tak</td>\r\n  </tr>\r\n   <tr>\r\n    <th>var</th>\r\n    <td>Funkcja</td>\r\n    <td>Tak</td>\r\n    <td>Tak</td>\r\n    <td>Nie</td>\r\n  </tr>\r\n</table>\r\n\r\n#### <a name=\"sample-code\"></a>Przykładowy kod\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // Wywoła błąd, person nie może być przepisane\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", przepisanie jest dozwolone z let\r\n```\r\n\r\n#### <a name=\"detailed-explanation\"></a>Szczegółowe wyjaśnienie\r\n\r\n[*Zakres widoczności*] zmiennej oznacza mniej więcej \"to, gdzie zmienna jest dostępna w kodzie\". \r\n\r\n##### var\r\n\r\nZakresem widoczności zmiennych deklarowanych za pomocą ```var``` jest funkcja. Oznacza to, że jeśli zmienna była stworzona wewnątrz funkcji, to wszystko w ciele tej funkcji ma dostęp do danej zmiennej. Poza tym, zmienna o opisanym zakresie nie jest dostępna poza funkcją.\r\n\r\nMożna myśleć o tym następująco: jeśli zakres widoczności zmiennej to *X*, to zmienna ta stanowi jak gdyby własność X.\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar dostępna wewnątrz funkcji.\r\n}\r\nconsole.log(myVar); // ReferenceError, myVar nie jest dostępna poza funkcją.\r\n```\r\n\r\nA oto mniej oczywisty przykład:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // ponieważ zakresem myVar jest funkcja, zastępujemy wcześniejszą wartość \"Nick\" wartością \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - zwróć uwagę, jak instrukcje w bloku if wpłynęły na wartość\r\n}\r\nconsole.log(myVar); // ReferenceError, myVar nie jest dostępna poza funkcją.\r\n```\r\n\r\nPoza tym, zmienne zadeklarowane poprzez *var* przy wykonaniu kodu przemieszczają się na początek zakresu widoczności. Proces ten nazywamy [var hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting).\r\n\r\nTen fragment kodu:\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- brak błędu\r\nvar myVar = 2;\r\n```\r\n\r\nw momencie wykonania rozumiany jest tak:\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- brak błędu\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n```var``` i ```let ``` znaczą mniej więcej to samo, ale w przypadku zmiennych zadeklarowanych za pomocą ```let``` \r\n\r\n- zakres widoczności stanowi blok\r\n- są **niedostępne** przed przypisaniem\r\n- nie mogą być ponownie zadeklarowane w tym samym zakresie widoczności\r\n\r\nPrzyjrzyjmy się blokowemu zakresu widoczności, używając poprzedniego przykładu:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // ponieważ zakresem widoczności myVar jest blok, \r\n    // właśnie stworzyliśmy nową zmienną myVar.\r\n    // zmienna ta jest niedostępna poza blokiem i zupełnie \r\n    // niezależna od pierwszej zmiennej myVar.\r\n  }\r\n  console.log(myVar); // \"Nick\", instrukcje bloku if NIE wpłynęły na tę zmienną\r\n}\r\nconsole.log(myVar); //  ReferenceError, myVar nie jest dostępna poza funkcją.\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> A teraz rozpatrzmy, co oznacza, że zmienne zadeklarowane z *let* (i *const*) są niedostępne przed przypisaniem:\r\n\r\n```js\r\nconsole.log(myVar) // wywołuje ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\nW odróżnieniu od zmiennych zadeklarowanych poprzez *var*, próba odczytu bądź nadpisania zmiennej stworzonej za pomocą *let* lub *const* przed przypisaniem wywoła błąd. Zjawisko to nazywane jest często [*Czasowo martwą strefą*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) albo *TDZ*\r\n\r\n> **Uwaga:** Ściśle rzecz biorąc zmienne zadeklarowane przy pomocy *let* i *const* też są windowane, ale nie przypisywane. Ponieważ nie mogą one być użyte przed przypisaniem, może się wydawać, że nie dochodzi do windowania (hoistingu), co nie jest prawdą. Jeśli chcesz dowiedzieć się więcej, możesz zapoznać się z [dokładnym omówieniem tego zjawiska](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified).\r\n\r\nPonadto nie można ponownie zadeklarować zmiennej stworzonej z *let*\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // SyntaxError\r\n```\r\n\r\n##### const\r\n\r\nZmienne zadeklarowane poprzez słowo kluczowe ```const``` zachowują się, jak te zadeklarowane z *let*, ale nie mogą być ponownie przypisane.\r\n\r\nPodsumowując, zmienne stworzone z *const*:\r\n\r\n- ich zakresem widoczności jest blok\r\n- nie są dostępne przed przypisaniem\r\n- nie mogą być ponownie zadeklarowane w tym samym zakresie widoczności\r\n- nie mogą być ponownie przypisane\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // wywołuje błąd, ponowne przypisanie jest niedozwolone\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // wywołuje błąd, ponowna deklaracja jest niedozwolone\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> Jest jednak pewien szczegół : zmienne zadeklarowane z ```const``` nie są [**niezmienne**](#mutation_def) ! Konkretnie, oznacza to, że *objekty* i *tablice* zadeklarowane poprzez ```const``` **mogą** podlegać modyfikacjom.\r\n\r\nW przypadku obiektów:\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // działa! Zmienna person nie jest ponownie przypisywana, ale ulega zmianie.\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // wywoła błąd, ponieważ nie można nadpisywać zmiennych deklarowanych poprzez const\r\n```\r\n\r\nW przypadku tablic:\r\n```js\r\nconst person = [];\r\nperson.push('John'); // działa! Zmienna person nie jest ponownie przypisywana, ale ulega zmianie.\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // wywoła błąd, ponieważ nie można nadpisywać zmiennych deklarowanych poprzez const\r\n```\r\n\r\n#### <a name=\"external-resource\"></a>Dodatkowe źródła\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"-arrow_func\"></a> Funkcje strzałkowe (arrow functions)\r\n\r\nW wersji ES6 JavaScript wprowadzone zostały *funkcje strzałkowe* (*arrow functions*) - nowy sposób zapisu funkcji. Oto niektóre jego zalety:\r\n\r\n- większa zwięzłość\r\n- *this* pobierane jest z otaczającego kontekstu\r\n- niejawny zwrot (implicit return)\r\n\r\n#### <a name=\"sample-code-1\"></a>Przykładowy kod\r\n\r\n- Zwięzłość i niejawny zwrot\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // Tradycyjny sposób\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // Ta sama funkcja jako funkcja strzałkowa z niejawnym zwrotem\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- Użycie *this*\r\n\r\nW funkcji strzałkowej *this* jest równe wartości *this* w otaczającym zakresie widoczności. Zasadniczo, dzięki funkcjom strzałkowym, nie ma już potrzeby używania tricku \"that = this\" przed wywołaniem funkcji wewnątrz funkcji.\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### <a name=\"detailed-explanation-1\"></a>Szczegółowe wyjaśnienie\r\n\r\n##### <a name=\"concision\"></a>Zwięzłość\r\n\r\nFunkcje strzałkowe są w wielu aspektach bardziej zwięzłe niż tradycyjne funkcje. Rozpatrzmy kilka przypadków:\r\n\r\n- Jawny vs niejawny zwrot\r\n\r\n**Jawny zwrot** (**explicit return**) to funkcja, w której ciele użyte jest słowo kluczowe *return*. \r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // this function explicitly returns x * 2, *return* keyword is used\r\n  }\r\n```\r\n\r\nPrzy tradycyjnym sposobie pisania funkcji zwrot był zawsze jawny. Jednak arrow functions pozwalają na *niejawny zwrot*, czyli taki, w którym słowo kluczowe *return* nie jest konieczne przy zwrocie wartości.\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // Jawny zwrot\r\n  }\r\n```\r\n\r\nPonieważ funkcja ta ogranicza się do zwrotu pewnej wartości (poza tym brak innych instrukcji), możemy użyć niejawnego zwrotu.\r\n\r\n```js\r\n  const double = (x) => x * 2; // Correct, returns x*2\r\n```\r\n\r\nBy to zrobić, musimy ***usunąć nawiasy* i słowo **return**. Stąd też nazwa *niejawny* (implicit) zwrot - mimo braku słowa kluczowego **return**, funkcja i tak zwróci ```x * 2```.\r\n\r\n> **Uwaga:** Jeśli funkcja nie zwraca żadnej wartości (z *efektami ubocznymi*), nie ma w niej ani jawnego ani niejawnego zwrotu.\r\n\r\nPoza tym, jeśli chcemy niejawnie zwrócić *obiekt*, należy **otoczyć go okrągłymi nawiasami**, by nie dopuścić do konfliktu z nawiasami samego bloku.\r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- obiekt niejawnie zwracany przez arrow function\r\n```\r\n\r\n- Tylko jeden argument\r\n\r\nJeśli funkcja posiada tylko jeden argument, możemy ominąć nawiasy wokół niego. Przyjrzyjmy się ponownie funkcji *double* z poprzedniego kodu:\r\n\r\n```js\r\n  const double = (x) => x * 2; // arrow function ma jeden argument\r\n```\r\n\r\nNawiasy wokół argumentu można usunąć:\r\n\r\n```js\r\n  const double = x => x * 2; // arrow function ma jeden argument\r\n```\r\n\r\n- Brak argumentów\r\n\r\nGdy funkcja nie ma argumentu, należy użyć okrągłych nawiasów, jeśli chcemy zachować poprawną składnię.\r\n\r\n```js\r\n  () => { // są nawiasy, wszystko w porządku\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // brak nawiasów, kod nie będzie działać!\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### <a name=\"this-reference\"></a>Użycie *this*\r\n\r\nAby w pełni zrozumieć działanie funkcji strzałkowych, trzeba wiedzieć, jak w JavaScript zachowuje się [this](#this_def).\r\n\r\nW funckji strzałkowej *this* jest równe wartości *this* w otaczającym kontekście. Oznacza to, że funkcja strzałkowa nie tworzy nowego *this*, ale zamiast tego pobiera je z otoczenia.\r\n\r\nBez funkcji strzałkowej, jeśli chcemy otrzymać dostęp do zmiennej przez *this* w funkcji znajdującej się w innej funkcji musimy użyć tricku *that = this* lub *self = this*.\r\n\r\nNa przykład, używając funkcji setTimeout w myFunc:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // that = this trick\r\n  setTimeout(\r\n    function() { // Nowy *this* tworzony w tym zakresie widoczności\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- zobacz: deklaracja funkcji wyżej\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\nAle w przypadku funkcji strzałkowej, *this* pobierane jest z otoczenia:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this pobierane z otoczenia. W tym przypadku - z myFunc.\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### <a name=\"useful-resources\"></a>Pomocne źródła\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n### <a name=\"function-default-parameter-value\"></a>Domyślna wartość argumentów funkcji\r\n\r\nPocząwszy od wersji ES2015, możliwe jest ustawienie domyślnej wartości argumentów funkcji przy użyciu następującej składni: \r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- żadna wartość nie jest podana, x otrzymuje wartość domyślną, czyli 10\r\nconsole.log(myFunc(5)) // 5 -- wartość podana, więc x otrzymuje wartość 5\r\n\r\nconsole.log(myFunc(undefined)) // 10 -- podana wartość undefined, więc x otrzymuje wartość domyślną, czyli 10\r\nconsole.log(myFunc(null)) // null -- wartość (null) jest podana, zobacz: niżej.\r\n```\r\n\r\nDomyślny argument będzie użyty jedynie w dwóch sytuacjach:\r\n\r\n- żaden argument nie jest podany\r\n- jako argument podano *undefined*\r\n\r\nInnymi słowami, jeśli jako argument podamy *null*, wartość domyślna **nie zostanie użyta**.\r\n\r\n> **Note:** Przypisanie wartości domyślnej można zastować także z destrukturyzowanymi parametrami (patrz: następna sekcja)\r\n\r\n#### <a name=\"external-resource-1\"></a>Dodatkowe źródła\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Default parameters - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\r\n\r\n### <a name=\"destructuring-objects-and-arrays\"></a>Destrukturyzacja obiektów i tablic\r\n\r\n*Destrukturyzacja* to wygodny sposób tworzenia nowych zmiennych poprzez wydobycie pewnych wartości z danych przechowywanych w obiektach i tablicach.\r\n\r\n*Destrukturyzacja* może być użyta do przypisania zmiennym rozbitych na części parametrów funkcji lub *this.props* w projektach React.\r\n\r\n#### <a name=\"explanation-with-sample-code\"></a>Wyjaśnienie z przykładowym kodem\r\n\r\n- Obiekt\r\n\r\nWe wszystkich przykładach używać będziemy następującego obiektu:\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\nBez destrukturyzacji:\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\nZ destrukturyzacją, wszystko w jednej linijce:\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // Gotowe !\r\n\r\nconsole.log(age) // 35 -- Stworzono nową zmienną równą person.age\r\nconsole.log(first) // \"Nick\" -- Stworzono nową zmienną równą person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName istnieje, ale nowo stworzona zmienna nazywa się first\r\nconsole.log(city) // \"Paris\" -- Stworzono nową zmienną city i, ponieważ person.city jest równe undefined, zmienna jest równa domyślnej wartość \"Paris\".\r\n```\r\n\r\n**Uwaga:** W ```const { age } = person;``` nawiasy po słowie *const* nie są użyte do deklaracji obiektu ani jako blok, ale jako składnia *destrukturyzacji*.\r\n\r\n- Argumenty funkcji\r\n\r\n*Destrukturyzacja* jest często używana do rozbicia parametrów funkcji na części.\r\n\r\nBez destrukturyzacji:\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nJeśli destrukturyzujemy parametr *person*, otrzymujemy znacznie bardziej zwięzłą funkcję:\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { // tworzymy zmienne firstName i lastName z części argumentu person.\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nDestrukturyzacja jest jeszcze przyjemniejsza, gdy użyjemy [funkcji strzałkowych](#arrow_func_concept):\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- Tablica\r\n\r\nRozpatrzmy następującą tablicę:\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\nBez destrukturyzacji\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\nZ destrukturyzacją\r\n\r\n```js\r\nconst [x, y] = myArray; // Gotowe !\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n#### <a name=\"useful-resources-1\"></a>Pomocne źródła\r\n\r\n- [ES6 Features - Destructuring Assignment](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)\r\n\r\n### <a name=\"array-methods---map--filter--reduce\"></a>Metody tablicowe - map / filter / reduce\r\n\r\n*Map*, *filter* i *reduce* to metody tablicowe zapożyczone z paradygmatu [*programowania funkcyjnego*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0).\r\n\r\nOpiszmy je krótko:\r\n\r\n- **Array.prototype.map()** przyjmuje jako argument tablicę, modyfikuje jej elementy i zwraca nową tablicę ze zmienionymi elementami.\r\n- **Array.prototype.filter()** przyjmuje jako argument tablicę, decyduje, które elementy zatrzymać a które usunąć. Zwraca tablicę z zachowanymi elementami.\r\n- **Array.prototype.reduce()** przyjmuje jako argument tablicę, wylicza z jej elementów jedną wspólną wartość, którą zwraca.\r\n\r\nPolecam używać ich jak najczęściej, zgodnie z zasadami programowania funkcyjnego, ponieważ metody tablicowe są zwięzłe, eleganckie i można je ze sobą łączyć.\r\n\r\nWykorzystując trzy powyższe metody możemy uniknąć użycia pętli *for* i *forEach* w większości sytuacji. Kiedy następnym razem będziesz chciał skorzystać z pętli *for*, spróbuj zamiast niej użyć kompozycji *map*, *filter* i *reduce*. Z początku może to sprawiać problemy, bo wymaga przyzwyczajenia sie do nowego sposobu myślenia, ale jeśli już go przyswoisz, wszystko będzie prostsze.\r\n\r\n#### <a name=\"sample-code-2\"></a>Przykładowy kod\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // 21\r\n```\r\n\r\nObliczmy sumę ocen wszystkich studentów z oceną powyżej 10 łącząc *map*, *filter* i *reduce*:\r\n\r\n```js\r\nconst students = [\r\n  { name: \"Nick\", grade: 10 },\r\n  { name: \"John\", grade: 15 },\r\n  { name: \"Julia\", grade: 19 },\r\n  { name: \"Nathalie\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // tworzymy tablicę ocen z tablicy studentów za pomocą map \r\n  .filter(grade => grade >= 10) // filtrujemy tablicę ocen, by pozostawić większe lub równe 10\r\n  .reduce((prev, next) => prev + next, 0); // sumujemy wszystkie oceny powyżej 10\r\n\r\nconsole.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie poniżej 10 - ignorowana\r\n```\r\n\r\n#### <a name=\"explanation\"></a>Wyjaśnienie\r\n\r\nW przykładach wykorzystywać będziemy poniższą tablicę:\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n##### <a name=\"arrayprototypemap\"></a>Array.prototype.map()\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\nCo tu się dzieje? Używamy *map* na tablicy *numbers*, *map* iteruje przez każdy element i używa go jako argumentu funkcji. Celem funkcji jest przeprowadzenie kalkulacji i zwrot nowej wartości, która zastąpi wartość użytą jako argument.\r\n\r\nWydzielmy funkcję z tablicy, żeby przyjrzeć się jej bliżej:\r\n\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n```numbers.map(doubleN)``` tworzy ```[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]```, które są równe ```[0, 2, 4, 6, 8, 10, 12]```.\r\n.\r\n> **Uwaga:** Jeśli nie potrzebujesz zwrotu nowej tablicy i chcesz po prostu użyć pętli posiadającej efekty uboczne, możesz rozważyć użycie pętli for / forEach zamiast map.\r\n\r\n##### <a name=\"arrayprototypefilter\"></a>Array.prototype.filter()\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // true jeśli n jest parzyste, false jeśli nie jest\r\n});\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\nUżywamy *filter* na tablicy *numbers*, *filter* iteruje przez każdy element i używa go jako argumentu funkcji. Celem funkcji jest zwrot zmiennej typu boolowskiego, która określi, czy daną wartość należy zachować, czy też nie. Następnie funkcja zwraca tablicę, zawierającą jedynie zachowane wartości.\r\n\r\n##### <a name=\"arrayprototypereduce\"></a>Array.prototype.reduce()\r\n\r\nCelem metody *reduce* jest wyliczenie na podstawie tablicy pewnej pojedynczej wartości. Jakie wyliczenia przeprowadzi metoda, zależy tylko od ciebie.\r\n\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n  0 // wartość zmiennej akumulującej po pierwszej iteracji\r\n);\r\n\r\nconsole.log(sum) //21\r\n```\r\n\r\nTak jak metody .map i .filter, .reduce wykorzystuje tablicę i jako pierwszy argument przyjmuje funkcję.\r\n\r\nSą jednak pewne różnice:\r\n\r\n- .reduce przyjmuje dwa argumenty\r\n\r\nPierwszy argument to funkcja, która będzie stosowana przy każdej iteracji.\r\n\r\nDrugi argument to wartość zmiennej akumulującej (w naszym przypadku *acc*) w pierwszej iteracji (by lepiej zrozumieć, czytaj dalej).\r\n\r\n- Argumenty funkcji\r\n\r\nFunkcja używana jako pierwszy argument .reduce przyjmuje dwa argumenty. Pierwszy (w naszym przypadku *acc*) to zmienna akumulująca, drugi (*n*) - obecny element.\r\n\r\nZmienna akumulująca równa jest wartości zwróconej przez naszą funkcję w **poprzedniej** iteracji. Na początku każdej iteracji *acc* równa jest wartości, która była przekazana jako drugi argument .reduce.\r\n\r\n###### W pierwszej iteracji\r\n\r\n```acc = 0``` ponieważ jako drugi element *reduce* podaliśmy 0\r\n\r\n```n = 0``` pierwszy element tablicy *array*\r\n\r\nFunkcja zwraca *acc* + *n* --> 0 + 0 --> 0\r\n\r\n###### W drugiej iteracji\r\n\r\n```acc = 0``` ponieważ taką wartość funkcja zwróciła przy poprzedniej iteracji\r\n\r\n```n = 1``` drugi element tablicy *array*\r\n\r\nFunkcja zwraca *acc* + *n* --> 0 + 1 --> 1\r\n\r\n###### W trzeciej iteracji\r\n\r\n```acc = 1``` ponieważ taką wartość funkcja zwróciła przy poprzedniej iteracji\r\n\r\n```n = 2``` trzeci element tablicy *array*\r\n\r\nFunkcja zwraca *acc* + *n* --> 1 + 2 --> 3\r\n\r\n###### W czwartej iteracji\r\n\r\n```acc = 3``` ponieważ taką wartość funkcja zwróciła przy poprzedniej iteracji\r\n\r\n```n = 3``` czwarty element tablicy *array*\r\n\r\nFunkcja zwraca *acc* + *n* --> 3 + 3 --> 6\r\n\r\n###### [...] W ostatniej iteracji\r\n\r\n```acc = 15``` ponieważ taką wartość funkcja zwróciła przy poprzedniej iteracji\r\n\r\n```n = 6``` ostatni element tablicy *array*\r\n\r\nFunkcja zwraca *acc* + *n* --> 15 + 6 --> 21\r\n\r\nPonieważ to ostatnia iteracja, **.reduce** zwraca 21.\r\n\r\n#### <a name=\"external-resource-2\"></a>Dodatkowe źródła\r\n\r\n- [Understanding map / filter / reduce in JS](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464)\r\n\r\n### <a name=\"spread-operator-\"></a>Operator rozwijania \"...\"\r\n\r\nOperator rozwijania ```...``` został wprowadzony z ES2015 i przeznaczony jest do \"rozwijania\" elementów obiektów iterowalnych (np. tablic) tam, gdzie można zmieścić kilka elementów\r\n\r\n#### <a name=\"sample-code-3\"></a>Przykładowy kod\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x);\r\n  console.log(y);\r\n  console.log(params)\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n#### <a name=\"explanation-1\"></a>Wyjaśnienie\r\n\r\n##### <a name=\"in-iterables-like-arrays\"></a>W obiektach iterowalnych (np. tablicach)\r\n\r\nJeśli mamy dwie następujące tablice:\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\n\r\nPierwszy element tablicy *arr2* jest tablicą, ponieważ *arr1* został wprowadzony do *arr2* bezpośrednio. Co jednak, jeśli chcemy, by *arr2* było tablicą liter? Możemy rozwinąć (*spread*) elementy *arr1* w tablicy *arr2*.\r\n\r\nZ operatorem rozwijania\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n##### <a name=\"function-rest-parameter\"></a>Parametry rest\r\n\r\nOperator rest pozwala przedstawić dowolna liczbę argumentów w postaci tablicy, po elementach której można iterować. Istnieje już obiekt **arguments** związany z każdą funkcją i równy tablicy wszystkich argumentów przekazanych do danej funkcji.\r\n\r\n\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\n\r\nmyFunc(\"Nick\", \"Anderson\", 10, 12, 6);\r\n// \"Nick\"\r\n// \"Anderson\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\n\r\nWyobraźmy sobie teraz, że chcemy, żeby nasza funkcja tworzyła nowego ucznia z ocenami i średnią. Czy nie byłoby wygodniej zapisać dwa pierwsze argumenty jako dwie oddzielne zmienne, a wszystkie oceny umieścić w iterowalnej tablicy?\r\n\r\nWłaśnie na to pozwala nam operator rest!\r\n\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  // firstName = \"Nick\"\r\n  // lastName = \"Anderson\"\r\n  // [10, 12, 6] -- \"...\" bierze wszystkie pozostałe argumenty przekazane funkcji i tworzy zmienną \"grades\" z przechowującą je tablicą \r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // oblicza średnią z ocen\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Nick\", \"Anderson\", 10, 12, 6);\r\nconsole.log(student);\r\n// {\r\n//   firstName: \"Nick\",\r\n//   lastName: \"Anderson\",\r\n//   grades: [10, 12, 6],\r\n//   avgGrade: 9,33\r\n// }\r\n```\r\n\r\n> **Uwaga:** funkcja createStudent jest zła, bo nie sprawdzamy, czy grades.length istnieje i czy jest różna od zera. Nie ująłem tej sytuacji w kodzie, żeby funkcja była bardziej czytelna.\r\n\r\n##### <a name=\"object-properties-spreading\"></a>Rozwijanie własności obiektów\r\n\r\nAby zrozumieć tę część, polecam najpierw przeczytać poprzednie sekcje dotyczące użycia operatora rest na iterowalnych obiektach i parametrach funkcji.\r\n\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // destrukturyzacja obiektu\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\n// z to reszta destrukturyzowanego obiektu: myObj object minus destrukturyzowane własności x i y\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// Własności obiektu z są rozwinięte w n\r\n```\r\n\r\n#### <a name=\"external-resources\"></a>Dodatkowe źródła\r\n\r\n- [TC39 - Object rest/spread](https://github.com/tc39/proposal-object-rest-spread)\r\n- [Spread operator introduction - WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md)\r\n- [JavaScript & the spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca)\r\n- [6 Great uses of the spread operator](https://davidwalsh.name/spread-operator)\r\n\r\n### <a name=\"object-property-shorthand\"></a>Skrócony zapis własności obiektów\r\n\r\nKiedy przypisujemy zmienną do własności obiektu, jeśli nazwa zmiennej jest taka sama, jak nazwa własności, możemy zrobić coś takiego:\r\n\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // 10\r\n```\r\n\r\n#### <a name=\"explanation-2\"></a>Wyjaśnienie\r\n\r\nDotychczas (przed ES2015), kiedy chcieliśmy przy deklaracji nowego literału obiektowego (*object literal*) zastosować zmienne jako jego własności, zapisalibyśmy to w ten sposób:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // przypisanie wartości zmiennej x do myObj.x\r\n  y: y // przypisanie wartości zmiennej y do myObj.y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\nJak widać, jest to dość powtarzalne, bo nazwy własności myObj są takie same, jak nazwy zmiennych, które chcemy przypisać do tych własności.\r\n\r\nZ ES2015, jeśli nazwa zmiennej jest taka sama jak własności, możemy skorzystać ze skróconego zapisu:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n#### <a name=\"external-resources-1\"></a>Dodatkowe źródła\r\n\r\n- [Property shorthand - ES6 Features](http://es6-features.org/#PropertyShorthand)\r\n\r\n### <a name=\"promises\"></a>Obietnice (promises)\r\n\r\nObietnica (promise) to obiekt, który może być zwrócony synchronicznie z asynchronicznej funkcji. ([ref](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0)).\r\n\r\nObietnice pozwalają zapobiec tzw. [callback hell](http://callbackhell.com/), i stosowane są coraz częściej we współczesnych projektach tworzonych w języku JavaScript.\r\n\r\n#### <a name=\"sample-code-4\"></a>Przykładowy kod\r\n\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n    .done(posts => res(posts))\r\n    .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n#### <a name=\"explanation-3\"></a>Wyjaśnienie\r\n\r\nKiedy wykonujemy **zapytanie Ajax** odpowiedź nie jest synchroniczna, ponieważ żądamy zasobu, którego pobranie wymaga czasu. Może się nawet zdarzyć, że z jakiegoś powodu (404) zasób nigdy nie zostanie pobrany.\r\n\r\nAby radzić sobie w tego typu sytuacjach, ES2015 daje nam obietnice (*promises*). Obietnice mogą mieć trzy różne stany:\r\n\r\n- oczekujący (pending)\r\n- zakończony (fulfilled)\r\n- odrzucony (rejected)\r\n\r\nPowiedzmy, że chcemy wykorzystać obietnice dla obsługi zapytania Ajax w celu pobrania zasobu X.\r\n\r\n##### <a name=\"create-the-promise\"></a>Tworzenie obietnicy\r\n\r\nNajpierw musimy stworzyć obietnicę. Dla stworzenia zapytania Ajax do zasobu X użyjemy metody GET jQuery.\r\n\r\n```js\r\nconst xFetcherPromise = new Promise( // Tworzymy obietnicę poprzez słowo kluczowe new i zapisujemy go do zmiennej \r\n  function(resolve, reject) { // Konstruktor obietnicy przyjmuje jako argument funkcję, która sama przyjmuje dwa argumenty: resolve i reject\r\n    $.get(\"X\") // Uruchamiamy zapytanie Ajax\r\n      .done(function(X) { // Kiedy zapytanie jest gotowe...\r\n        resolve(X); // ... wypełniamy obietnicę z wartością X jako argumentem\r\n      })\r\n      .fail(function(error) { // Jeśli zapytanie się nie udało...\r\n        reject(error); // ... odrzucamy obietnicę z wartością X jako argumentem\r\n      });\r\n  }\r\n)\r\n```\r\n\r\nJak widać na przykładzie, obiekt Promise przyjmuje funkcję-*executor*, która z kolei przy dwa argumenty **resolve** i **reject**. Argumenty te są funkcjami, które przy wezwaniu zmieniają stan obietnicy oczekujący (*pending*) na, odpowiednio, zakończony (*fulfilled*) i odrzucony (*rejected*). \r\n\r\nObietnica znajduje się w stanie oczekiwania po stworzeniu instancji, a jej funkcja-*executor* jest natychmiast wykonywana. Kiedy jedna z funkcji *resolve* bądź *reject* zostanie wezwana w funkcji-*executor*, obietnica wywoła związane z nią procedury obsługi.\r\n\r\n##### <a name=\"promise-handlers-usage\"></a>Użycie procedur obsługi\r\n\r\nBy otrzymać rezultat obietnicy (lub błąd), musimy podpiąć ją pod procedury obsługi używając następującego kodu:\r\n\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err)\r\n  })\r\n```\r\n\r\nJeśli wszystko przebiegło prawidłowo, zostaje wywołane *resolve* i wykonana zostaje funkcja przekazana jako argument ```.then```. \r\n\r\nJeśli zapytanie się nie udało, zostaje wywołane *reject* i wykonana zostaje funkcja przekazana jako argument ```.catch```. \r\n \r\n> **Uwaga:** Jeśli obietnica została już wypełniona lub odrzucona w momencie podpięcia odpowiedniej procedury obsługi, procedura będzie wywołana, tak więc nie wyniknie wyścig (race condition) między wykonaniem operacji asynchronicznej i wyznaczeniem procedur obsługi. [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Description)\r\n\r\n#### <a name=\"external-resources-2\"></a>Dodatkowe źródła\r\n\r\n- [JavaScript Promises for dummies - Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies)\r\n- [JavaScript Promise API - David Walsh](https://davidwalsh.name/promises)\r\n- [Using promises - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\r\n- [What is a promise - Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)\r\n- [JavaScript Promises: an Introduction - Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises)\r\n- [Promise documentation - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\r\n\r\n### <a name=\"template-literals\"></a>Łańcuchy szablonowe (template literals)\r\n\r\nŁańcuchy szablonowe to [*interpolacja wyrażenia*](https://en.wikipedia.org/wiki/String_interpolation) dla jedno- i wieloliniowych stringów.\r\n\r\nInaczej mówiąc, jest to nowa składnia stringów, pozwalająca na wygodne użycie dowolnych wyrażeń JavaScript (np. zmiennych).\r\n\r\n#### <a name=\"sample-code-5\"></a>Przykładowy kod\r\n\r\n```js\r\nconst name = \"Nick\";\r\n`Hello ${name}, następujące wyrażenie jest równe czterem: ${2+2}`;\r\n\r\n// Hello Nick, następujące wyrażenie jest równe czterem: 4\r\n```\r\n\r\n#### <a name=\"external-resources-3\"></a>Dodatkowe źródła\r\n\r\n- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)\r\n- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)\r\n\r\n### <a name=\"tagged-template-literals\"></a>Oznaczone łańcuchy szablonowe\r\n\r\nTagi szablonowe to *funkcje które mogą być prefiksem dla [łańcucha szablonowego](#template-literals)*. Kiedy funkcja zostaje wezwana w ten sposób, pierwszy argument stanowi tablica *stringów*, które pojawiają się między interpolowanymi zmiennymi, a kolejne parametry to znaczenia wyrażeń wstawionych w string. Dla przechwycenia ich wszystkich można użyć operatora rozwijania. [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals).\r\n\r\n> **Uwaga :** Słynna biblioteka [styled-components](https://www.styled-components.com/) w dużej mierze polega na tej funkcjonalności.\r\n\r\nPoniżej znajduje się przykład działania tagów szablonowych:\r\n```js\r\nfunction highlight(strings, ...values) {\r\n  const interpolation = strings.reduce((prev, current) => {\r\n    return prev + current + (values.length ? \"<mark>\" + values.shift() + \"</mark>\" : \"\");\r\n  }, \"\");\r\n\r\n  return interpolation;\r\n}\r\n\r\nconst condiment = \"jam\";\r\nconst meal = \"toast\";\r\n\r\nhighlight`I like ${condiment} on ${meal}.`;\r\n// \"I like <mark>jam</mark> on <mark>toast</mark>.\"\r\n```\r\n\r\nI jeszcze jeden - ciekawszy - przykład:\r\n```js\r\nfunction comma(strings, ...values) {\r\n  return strings.reduce((prev, next) => {\r\n    let value = values.shift() || [];\r\n    value = value.join(\", \");\r\n    return prev + next + value;\r\n  }, \"\");\r\n}\r\n\r\nconst snacks = ['apples', 'bananas', 'cherries'];\r\ncomma`I like ${snacks} to snack on.`;\r\n// \"I like apples, bananas, cherries to snack on.\"\r\n```\r\n\r\n#### <a name=\"external-resources-4\"></a>Dodatkowe źródła\r\n- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)\r\n- [Library of common template tags](https://github.com/declandewet/common-tags)\r\n\r\n### <a name=\"imports--exports\"></a>Importy / eksporty\r\n\r\nModuły ES6 są używane dla otrzymania dostępu do zmiennych lub funkcji z drugich modułów, przy czym eksport powinien być jasno oznaczony w wyjściowym module.\r\n\r\nBardzo polecam zapoznać się z zasobami MDN dotyczącymi importów i eksportów (zobacz: Dodatkowe materiały), znajdziecie tam dokładne i przystępne wyjaśnienie.\r\n\r\n#### <a name=\"explanation-with-sample-code-1\"></a>Wyjaśnienie z przykładowym kodem\r\n\r\n##### <a name=\"named-exports\"></a>Nazwane eksporty (named exports)\r\n\r\nNazwane eksporty są używane do eksportu kilku wartości z modułu.\r\n\r\n> **Uwaga :** W nazwanych eksportach można stosować jedynie [typy pierwszoklasowe](https://en.wikipedia.org/wiki/First-class_citizen), które posiadają nazwę.\r\n\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js'; // Nazwany import - składnia podobna do destrukturyzacji\r\nconsole.log(pi) // 3.14\r\nconsole.log(exp) // 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js'; // Wszystkie eksportowane wartości przypisane są do stałych\r\nconsole.log(constants.pi) // 3.14\r\nconsole.log(constants.exp) // 2.7\r\n```\r\n\r\nChociaż nazwane importy przypominają *destrukturyzację*, posiadają inną składnią i nie są tym samym. Nie wspierają ani wartości domyślnych, ani *głębokiej* destrukturyzacji.\r\n\r\nPoza tym, można tworzyć aliasy, ale składnia wygląda inaczej niż przy destrukturyzacji:\r\n\r\n```js\r\nimport { foo as bar } from 'myFile.js'; // foo jest importowane i przypisane do nowej zmiennej bar\r\n```\r\n\r\n##### <a name=\"default-import--export\"></a>Domyślny import / export\r\n\r\nW przypadku domyślnego eksportu na jeden moduł przypada jeden domyślny eksport. Domyślny eksport może być funkcją, klasą, obiektem itp. Wartość ta jest traktowana jako \"główna\" eksportowana wartość, ponieważ importowanie jej jest najprostsze. [Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Description)\r\n\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n// Eksport domyślny, niezależnie od swojej nazwy w wyjściowym module, automatycznie przypisywany jest do zmiennej number;\r\nconsole.log(number) // 42\r\n```\r\n\r\nEksport funkcji:\r\n\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // 3\r\n```\r\n\r\n#### <a name=\"external-resources-5\"></a>Dodatkowe źródła\r\n\r\n- [ES6 Modules in bulletpoints](https://ponyfoo.com/articles/es6#modules)\r\n- [Export - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\r\n- [Import - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/)\r\n- [Destructuring special case - import statements](https://ponyfoo.com/articles/es6-destructuring-in-depth#special-case-import-statements)\r\n- [Misunderstanding ES6 Modules - Kent C. Dodds](https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0)\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript)\r\n\r\n### <a name=\"-javascript-this\"></a> *this* w JavaScript\r\n\r\nOperator *this* zachowuje się inaczej niż w innych językach. W większości przypadków jego zachowanie zależy od tego, jak wywoływana jest funkcja.\r\n\r\nZagadnienie to może być dość trudne do zrozumienia, dlatego polecam zapoznać się dokładnie z dodatkowymi materiałami podanymi niżej. Postaram się wyjaśnić, jak sam rozumiem działanie *this*. Nauczyłem się tego z [artykułu Yehudy Katza](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/).\r\n\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// Po każdym wyrażeniu postaramy się określić znaczenie this w myFunc\r\n\r\nmyFunc.call(\"myString\", \"hello\") // \"myString\" -- pierwszy parametr .call zapisywany jest w *this*\r\n\r\n// W trybie non-strict\r\nmyFunc(\"hello\") // window -- myFunc() to cukier syntaktyczny dla myFunc.call(window, \"hello\")\r\n\r\n// W trybie strict\r\nmyFunc(\"hello\") // undefined -- myFunc() to cukier syntaktyczny dla myFunc.call(undefined, \"hello\")\r\n```\r\n\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\") // person Object -- pierwszy parametr .call zapisywany jest w *this*\r\nperson.myFunc(\"test\") // person Object -- person.myFunc() to cukier syntaktyczny dla person.myFunc.call(person, \"test\")\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"hello\") // Tworzy nową funkcję, w której \"hello\" zapisywane jest w *this*\r\nperson.myFunc(\"test\") // person Object -- Metoda bind nie ma wpływu na oryginalną metodę\r\nmyBoundFunc(\"test\") // \"hello\" -- myBoundFunc to person.myFunc z \"hello\" przywiązanym do *this*\r\n```\r\n\r\n#### <a name=\"external-resources-6\"></a>Dodatkowe źródła\r\n\r\n- [Understanding JavaScript Function Invocation and \"this\" - Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)\r\n- [JavaScript this - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\r\n\r\n### <a name=\"class\"></a>Klasa\r\n\r\nJavaScript jest językiem [opartym na prototypach](https://en.wikipedia.org/wiki/Prototype-based_programming) (podczas gdy, na przykład, Java jest [oparta na klasach](https://en.wikipedia.org/wiki/Class-based_programming)). ES6 wprowadza klasy JavaScript, które mają być cukrem syntaktycznym dla dziedziczenia opartego na prototypach a *nie* nowym modelem dziedziczenia opartego na klasach ([ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)).\r\n\r\nUżycie słowa *class* może istotnie prowadzić do błędów, jeśli jesteśmy przyzwyczajeni do klas stosowanych w innych językach. Dlatego też klasy w JavaScript lepiej traktować jak zupełnie odrębne zagadnienie.\r\n\r\nPonieważ nasz przewodnik nie ma na celu nauki języka od podstaw, zakładam, że wiesz, czym są prototypy i jak działają. Jeśli nie, zapoznaj się z dodatkowymi materiałami znajdującymi się pod kodem przykładowym.\r\n\r\n#### <a name=\"samples\"></a>Przykłady\r\n\r\nSkładnia prototypu sprzed ES6:\r\n\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n}\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n}\r\n```\r\n\r\nSkładnia klasy z ES6:\r\n\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Manu\", 23);\r\nconsole.log(myPerson.age) // 23\r\nconsole.log(myPerson.stringSentence()) // \"Hello, my name is Manu and I'm 23\r\n```\r\n\r\n#### <a name=\"external-resources-7\"></a>Dodatkowe źródła\r\n\r\nOmówienie prototypów:\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\nOmówienie klas:\r\n\r\n- [ES6 Classes in Depth - Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features - Classes](http://es6-features.org/#ClassDefinition)\r\n- [JavaScript Classes - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\r\n\r\n### <a name=\"extends-and-super-keywords\"></a>Słowa kluczowe `extends` i `super`\r\n\r\nSłowo kluczowe `extends` używane jest w deklaracji klas w celu stworzenia klasy dziedziczącej od innej klasy ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)). Klasa pochodna dziedziczy wszystkie własności klasy bazowej, może dodawać nowe lub modyfikować odziedziczone własności.\r\n\r\nSłowo kluczowe `super` służy do wzywania funkcji na klasie bazowej obiektu, włącznie z jej konstruktorem. \r\n\r\n- słowo kluczowe `super` musi być użyte przed słowem `this` w konstruktorze\r\n- Wezwanie `super()` wywołuje konstruktor klasy bazowej. Jeśli chcesz przekazać argumenty w konstruktorze klasy do konstruktora klasy bazowej, użyj `super(arguments)`.\r\n- Jeśli klasa bazowa posiada metodę (także statyczną) o nazwie `X`, można użyć `super.X()`, by wywołać ją w klasie pochodnej.\r\n\r\n#### <a name=\"sample-code-6\"></a>Przykładowy kod\r\n\r\n```js\r\nclass Polygon {\r\n  constructor(height, width) {\r\n    this.name = 'Polygon';\r\n    this.height = height;\r\n    this.width = width;\r\n  }\r\n\r\n  getHelloPhrase() {\r\n    return `Hi, I am a ${this.name}`;\r\n  }\r\n}\r\n\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    // Wzywany jest konstruktor klasy bazowej z szerokością i długością przekazanymi przez Polygon\r\n    super(length, length);\r\n    // Uwaga: W klasach pochodnych super() musi zostać wezwane przed 'this'. W przeciwnym razie pojawi się błąd.\r\n    this.name = 'Square';\r\n    this.length = length;\r\n  }\r\n\r\n  getCustomHelloPhrase() {\r\n    const polygonPhrase = super.getHelloPhrase(); // super.X() daje dostęp do metody klasy bazowej\r\n    return `${polygonPhrase} with a length of ${this.length}`;\r\n  }\r\n\r\n  get area() {\r\n    return this.height * this.width;\r\n  }\r\n}\r\n\r\nconst mySquare = new Square(10);\r\nconsole.log(mySquare.area) // 100\r\nconsole.log(mySquare.getHelloPhrase()) // 'Hi, I am a Square' -- Square dziedziczy od Polygon i ma dostęp do jego metod\r\nconsole.log(mySquare.getCustomHelloPhrase()) // 'Hi, I am a Square with a length of 10'\r\n```\r\n\r\n**Uwaga :** Jeśli spróbujemy użyć `this` przed wezwaniem `super()` w klasie Square, pojawi się ReferenceError \r\n\r\n```js\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    this.height; // ReferenceError, najpierw trzeba wezwać super!\r\n\r\n    // Wzywany jest konstruktor klasy bazowej z szerokością i długością przekazanymi przez Polygon\r\n    super(length, length);\r\n\r\n    // Uwaga: W klasach pochodnych super() musi zostać wezwane przed 'this'. W przeciwnym razie pojawi się błąd.\r\n    this.name = 'Square';\r\n  }\r\n}\r\n```\r\n\r\n#### <a name=\"external-resources-8\"></a>Dodatkowe źródła\r\n\r\n- [Extends - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)\r\n- [Super operator - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super)\r\n- [Inheritance - MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance)\r\n\r\n### <a name=\"async-await\"></a>Składnia async/await\r\n\r\nOprócz [Obietnic (Promises)](#promises), możesz spotkać jeszcze jeden rodzaj składni dla obsługi kodu asynchronicznego, a mianowicie *async / await*.\r\n \r\nRolą funkcji async/await jest uproszczenie zachowania używanych synchronicznie obietnic oraz by używać grup Obietnic. Async/await przypomina połączenie generatorów i obietnic. Funkcje async *zawsze* zwracają Obietnicę ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function))\r\n\r\n> **Uwaga :** Ponieważ funkcje async / await bazują na obietnicach, aby prawidłowo stosować wspomniane funkcje, musisz najpierw dobrze rozumieć działanie obietnic.\r\n\r\n> **Uwaga 2:** [*await* musi zostać użyte w funkcji *async*](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0), co oznacza, że await nie można użyć na wyższym poziomie kodu, nie znajdującym się wewnątrz funkcji async.\r\n\r\n#### <a name=\"sample-code-7\"></a>Przykładowy kod\r\n\r\n```js\r\nasync function getGithubUser(username) { // słowo kluczowe async pozwala użyć await w funkcji i oznacza, że funkcja zwraca obietnicę\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Czeka na obietnicę przed przejściem do reszty kodu\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user)) // logowanie użytkownika - nie można użyć await, bo nie znajduje się w funkcji async\r\n  .catch(err => console.log(err)); // jeśli w funkcji async pojawi się błąd, wyłapujemy go tutaj\r\n```\r\n\r\n#### <a name=\"explanation-with-sample-code-2\"></a>Wyjaśnienie z przykładowym kodem\r\n\r\n*Async / Await* jest zbudowany na obietnicach, ale pozwala na bardziej imperatywny styl kodu.\r\n\r\nOperator *async* oznacza funkcję jako asynchroniczną. Dana funkcja zawsze zwraca Obietnicę. W funkcji *async* można użyć operatora *async*, aby zatrzymać wykonanie kodu na danej linijce dopóki zwracana Obietnica nie zostanie wypełniona bądź odrzucona.\r\n\r\n```js\r\nasync function myFunc() {\r\n  // ponieważ to funkcja async, możemy użyć operatora await\r\n  return \"hello world\";\r\n}\r\n\r\nmyFunc().then(msg => console.log(msg)) // \"hello world\" -- wartość zwracana przez myFunc jest przekształcana w obietnicę ze względu na operator async\r\n```\r\n\r\nKiedy zostaje osiągnięte wyrażenie *return* w funkcji async, Obietnica zostaje wypełniona ze zwracaną wartością. Jeśli wewnątrz funkcji async pojawia się błąd, stan Obietnicy zmienia się na *odrzucony* (*rejected*). Jeśli funkcja async nie zwraca żadnej wartości, Obietnica zostanie zwrócona i wypełniona bez wartości, kiedy zakończy się wykonanie funkcji async.\r\n\r\n\r\nOperator *await* jest używany do oczekiwania na wypełnienie Obietnicy i może być użyty jedynie w ciele funkcji *async*. Kiedy zostanie osiągnięty, następuje wstrzymanie wypełnienia kodu do chwili wypełnienia obietnicy.\r\n\r\n> **Uwaga :** *fetch* to funkcja, która zwraca Obietnicę i pozwala na wykonania zapytania Ajax.\r\n\r\nRozpatrzmy przykład użycia fetch z obietnicami:\r\n\r\n```js\r\nfunction getGithubUser(username) {\r\n  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\nA oto ekwiwalent z *async / await*:\r\n\r\n```js\r\nasync function getGithubUser(username) { // dozwolone użycie obietnicy + await\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Wykonanie wstrzymane do czasu wypełnienia obietnicy fetch\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\nSkładnia *async / await* jest wyjątkowo użyteczna, gdy chcemy połączyć w łańcuch wzajemnie zależne od siebie obietnice.\r\n\r\nNa przykład, kiedy potrzebujemy tokena, by pobrać z bazy danych post na blogu i informacje o autorze:\r\n\r\n> **Uwaga :** wyrażenia *await* muszą być otoczone nawiasami, aby można było wezwać wartości ich metod i własności w jednej linijce.\r\n\r\n```js\r\nasync function fetchPostById(postId) {\r\n  const token = (await fetch('token_url')).json().token;\r\n  const post = (await fetch(`/posts/${postId}?token=${token}`)).json();\r\n  const author = (await fetch(`/users/${post.authorId}`)).json();\r\n\r\n  post.author = author;\r\n  return post;\r\n}\r\n\r\nfetchPostById('gzIrzeo64')\r\n  .then(post => console.log(post))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n##### <a name=\"error-handling\"></a>Obsługa błędów\r\n\r\nJeśli nie dodamy bloków *try / catch* wokół wyrażeń *await*, nieschwytane wyjątki - niezależnie od tego, czy pojawią się w ciele funkcji *async*, czy zostaną wstrzymane w czasie *await* - doprowadzą do odrzucenia obietnicy zwracanej przez funkcję *async*. Użycie wyrażenia `throw` w funkcji async sprowadza się do tego samego, co zwrot odrzuconej obietnicy. [(Ref: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).  \r\n\r\n> **Uwaga :** Obietnice zachowują się tak samo!\r\n\r\nOto jak obsługujemy błędy z pomocą obietnic:\r\n\r\n```js\r\nfunction getUser() { // Obietnica będzie odrzucona!\r\n  return new Promise((res, rej) => rej(\"User not found !\"));\r\n}\r\n\r\nfunction getAvatarByUsername(userId) {\r\n  return getUser(userId).then(user => user.avatar);\r\n}\r\n\r\nfunction getUserAvatar(username) {\r\n  return getAvatarByUsername(username).then(avatar => ({ username, avatar }));\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\nEkwiwalent z *async / await*:\r\n\r\n```js\r\nasync function getUser() { // Zwrócona obietnica zostanie odrzucona!\r\n  throw \"User not found !\";\r\n}\r\n\r\nasync function getAvatarByUsername(userId) => {\r\n  const user = await getUser(userId);\r\n  return user.avatar;\r\n}\r\n\r\nasync function getUserAvatar(username) {\r\n  var avatar = await getAvatarByUsername(username);\r\n  return { username, avatar };\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\n#### <a name=\"external-resources-9\"></a>Dodatkowe źródła\r\n\r\n- [Async/Await - JavaScript.Info](https://javascript.info/async-await)\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/)\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9)\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits)\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n- [Async Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\r\n- [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\r\n- [Using async / await in express with node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n\r\n### <a name=\"truthy--falsy\"></a>Prawda / fałsz\r\n\r\nW JavaScript wartości \"prawda\" lub \"fałsz\" określane są w kontekście boolowskim. Przykładem kontekstu boolowskiego może być określenie warunku ```if```: \r\n\r\nJako prawda (```true```) określona będzie każda wartość, jeśli nie jest równa:\r\n\r\n- ```false```\r\n- ```0```\r\n- ```\"\"``` (empty string)\r\n- ```null```\r\n- ```undefined```\r\n- ```NaN```\r\n\r\nPrzykłady *kontekstu boolowskiego*:\r\n\r\n- określenie warunku ```if```\r\n\r\n```js\r\nif (myVar) {}\r\n```\r\n\r\n```myVar``` może być dowolnym [obiektem pierwszoklasowym](https://en.wikipedia.org/wiki/First-class_citizen) (zmienna, funkcja, typ boolowski) ale będzie przekształcona w typ boolowski, ponieważ określana jest w kontekście boolowskim.\r\n\r\n- Po operatorze logicznym **NOT** ```!```\r\n\r\nThis operator returns false if its single operand can be converted to true; otherwise, returns true.\r\nOperator ten zwraca \"fałsz\" jeśli jego jedyny operand może być przekształcony w znaczenie \"prawda\"; w przeciwnym razie zwraca \"prawdę\"\r\n\r\n```js\r\n!0 // true -- 0 to \"fałsz\", więc zwraca \"prawdę\"\r\n!!0 // false -- 0 to \"fałsz\", więc !0 zwraca \"prawdę\", więc !(!0) zwraca \"fałsz\"\r\n!!\"\" // false -- pusty string to \"fałsz\", więc NOT (NOT false) równe jest \"fałszowi\"\r\n```\r\n\r\n- Z konstruktorem obiektu *Boolean*\r\n\r\n```js\r\nnew Boolean(0) // false\r\nnew Boolean(1) // true\r\n```\r\n\r\n- Z operatorem warunkowym\r\n\r\n```js\r\nmyVar ? \"prawda\" : \"fałsz\"\r\n```\r\n\r\nmyVar jest określana w kontekście boolowskim.\r\n\r\n```\r\n\r\n#### <a name=\"external-resources-10\"></a>Dodatkowe źródła\r\n\r\n- [Truthy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)\r\n- [Falsy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)\r\n- [Truthy and Falsy values in JS - Josh Clanton](http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html)\r\n\r\n### <a name=\"anamorphisms-and-catamorphisms\"></a>Anomorfizmy i katamorfizmy\r\n\r\n#### <a name=\"anamorphisms\"></a>Anamorfizmy\r\n\r\nAnamorfizmy to funkcje, które mapują pewien obiekt to bardziej złożonej struktury zawierającej typ tego obiektu. Jest to proces *rozwijania* (*unfolding*) prostej struktury do bardziej złożonej. Rozpatrzmy rozwijanie liczby całkowitej do listy liczb całkowitych. Początkowym obiektem jest liczba całkowita, bardziej złożoną strukturą - lista liczb całkowitych.\r\n\r\n**Przykładowy kod**\r\n\r\n```js\r\nfunction downToOne(n) {\r\n  const list = [];\r\n\r\n  for (let i = n; i > 0; --i) {\r\n    list.push(i);\r\n  }\r\n\r\n  return list;\r\n}\r\n\r\ndownToOne(5)\r\n  //=> [ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\n#### <a name=\"catamorphisms\"></a>Katamorfizmy\r\n\r\nKatamorfizmy to przeciwieństwo anamorfizmów - \"zwijają\" bardziej skomplikowane struktury do prostszych. Przyjrzyjmy się funkcji `product`, która przyjmuje listę liczb całkowitych i zwraca pojedynczą liczbę całkowitą. \r\n\r\n**Przykładowy kod**\r\n\r\n```js\r\nfunction product(list) {\r\n  let product = 1;\r\n\r\n  for (const n of list) {\r\n    product = product * n;\r\n  }\r\n\r\n  return product;\r\n}\r\n\r\nproduct(downToOne(5)) // 120\r\n```\r\n\r\n#### <a name=\"external-resources-11\"></a>Dodatkowe źródła\r\n\r\n* [Anamorphisms in JavaScript](http://raganwald.com/2016/11/30/anamorphisms-in-javascript.html)\r\n* [Anamorphism](https://en.wikipedia.org/wiki/Anamorphism)\r\n* [Catamorphism](https://en.wikipedia.org/wiki/Catamorphism)\r\n\r\n### <a name=\"generators\"></a>Generatory\r\n\r\nInnym sposobem zapisania funkcji `downToOne` jest użycie Generatora. Stworzenie instancji obiektu `Generator` wymaga użycia deklaracji funkcji `function *`. Generatory to funkcje, które mogą być zamknięte i później uruchomione ponownie z zachowaniem kontekstu między kolejnymi uruchomieniami.\r\n\r\nNa przykład funkcja `downToOne` może być zapisana tak:\r\n\r\n```js\r\nfunction * downToOne(n) {\r\n  for (let i = n; i > 0; --i) {\r\n    yield i;\r\n  }\r\n}\r\n\r\n[...downToOne(5)] //[ 1, 2, 3, 4, 5 ]\r\n```\r\n\r\nGeneratory zwracają obiekt iterowalny. Kiedy wzywana jest funkcja iteratora `next()`, jest ona wykonywana aż do perwszego wyrażenia `yield`, które określa wartość, jaka zostanie zwrócona przez iterator lub z `yield*`, które odsyła do kolejnej funkcji-generatora. Jeśli w generatorze wezwane jest wyrażenie `return`, generator zostanie oznaczony jako wyczerpany i przekazany jako wartość do zwrotu. Kolejne wezwania `next()` nie zwrócą żadnych nowych wartości. \r\n\r\n**Przykładowy kod**\r\n\r\n```js\r\n// Przykład Yield\r\nfunction * idMaker() {\r\n  var index = 0;\r\n  while (index < 2) {\r\n    yield index;\r\n    index = index + 1;\r\n  }\r\n}\r\n\r\nvar gen = idMaker();\r\n\r\ngen.next().value; // 0\r\ngen.next().value; // 1\r\ngen.next().value; // undefined\r\n```\r\n\r\nWyrażenie `yield*` pozwala generatorowi wzywać inną funkcję-generator w czasie iteracji. \r\n\r\n```js\r\n// Yield * Example\r\nfunction * genB(i) {\r\n  yield i + 1;\r\n  yield i + 2;\r\n  yield i + 3;\r\n}\r\n\r\nfunction * genA(i) {\r\n  yield i;\r\n  yield* genB(i);\r\n  yield i + 10;\r\n}\r\n\r\nvar gen = genA(10);\r\n\r\ngen.next().value; // 10\r\ngen.next().value; // 11\r\ngen.next().value; // 12\r\ngen.next().value; // 13\r\ngen.next().value; // 20\r\n```\r\n\r\n```js\r\n// Przykład Generator Return\r\nfunction* yieldAndReturn() {\r\n  yield \"Y\";\r\n  return \"R\";\r\n  yield \"unreachable\";\r\n}\r\n\r\nvar gen = yieldAndReturn()\r\ngen.next(); // { value: \"Y\", done: false }\r\ngen.next(); // { value: \"R\", done: true }\r\ngen.next(); // { value: undefined, done: true }\r\n```\r\n\r\n#### <a name=\"external-resources-12\"></a>Dodatkowe źródła\r\n\r\n* [Mozilla MDN Web Docs, Iterators and Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators)\r\n\r\n### <a name=\"static-methods\"></a>Metody statyczne\r\n\r\n#### <a name=\"short-explanation-1\"></a>Krótkie wyjaśnienie\r\n\r\nSłowo kluczowe `static` jest używane w klasach dla deklaracji metod statycznych. Metody statyczne to funkcje klasy, które należą do obiektu klasy, ale nie są dostępne dla instancji tej klasy.\r\n\r\n#### <a name=\"sample-code-8\"></a>Przykładowy kod\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n}\r\n\r\n//Zauważ, że nie musieliśmy tworzyć instancji klasy Repo\r\nconsole.log(Repo.getName()) //Repo name is modern-js-cheatsheet\r\n\r\nlet r = new Repo();\r\nconsole.log(r.getName()) //Nieprzechwycony TypeError: repo.getName nie jest funkcją\r\n```\r\n\r\n#### <a name=\"detailed-explanation-2\"></a>Szczegółowe wyjaśnienie\r\n\r\nMetody statyczne mogą być wezwane z innych metod statycznych za pomocą słowa kluczowego `this`, co nie działa w przypadku metod niestatycznych. Metody niestatyczne nie mają bezpośredniego dostępu do metod statycznych z użyciem `this`.\r\n\r\n##### <a name=\"calling-other-static-methods-from-a-static-method\"></a>Wzywanie innych metod statycznych z metod statycznych\r\n\r\nAby wezwać metodę statyczną z innej metody statycznej, należy użyć słowa kluczowego `this`:\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  static modifyName(){\r\n    return this.getName() + '-added-this'\r\n  }\r\n}\r\n\r\nconsole.log(Repo.modifyName()) //Repo name is modern-js-cheatsheet-added-this\r\n```\r\n\r\n##### <a name=\"calling-static-methods-from-non-static-methods\"></a>Wzywanie metod statycznych z metod niestatycznych\r\n\r\nMetody niestatyczne mogą wzywać metody statyczne na dwa sposoby;\r\n1. ###### Używając nazwy klasy.\r\n\r\nAby zyskać dostęp do metody statycznej z metody niestatycznej używamy nazwy klasy i wzywamy metodę statyczną jak własność, np. `ClassName.StaticMethodName`\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    return Repo.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// musimy stworzyć instancję klasy, by mieć dostęp do metod niestatycznych\r\nlet r = new Repo()\r\nconsole.log(r.useName()) //Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n2. ###### Używając konstruktora\r\n\r\nMetody statyczne mogą być wzywane jak własności na obiekcie konstruktora.\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    //Wzywa metodę statyczną jako własność konstruktora\r\n    return this.constructor.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// musimy stworzyć instancję klasy, by mieć dostęp do metod niestatycznych\r\nlet r = new Repo()\r\nconsole.log(r.useName()) //Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n#### <a name=\"external-resources-13\"></a>Dodatkowe źródła\r\n- [static keyword- MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)\r\n- [Static Methods- Javascript.info](https://javascript.info/class#static-methods)\r\n- [Static Members in ES6- OdeToCode](http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx)\r\n\r\n## <a name=\"glossary\"></a>Słowniczek\r\n\r\n### <a name=\"-scope\"></a>Zakres widoczności (scope)\r\n\r\nKontekst, w którym wartości i wyrażenia są \"widoczne\" lub można się do nich odwoływać. Jeśli zmienna lub inne wyrażenie \"nie znajduje się w aktualnym zakresie widoczności\", oznacza to, że jest niedostępna do użytku.\r\n\r\nŹródło: [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\r\n\r\n### <a name=\"-variable-mutation\"></a>Przekształcenie zmiennej (variable mutation)\r\n\r\nMówimy, że zmienna została przekształcona, kiedy jej wartość jest inna niż wartość początkowa.\r\n\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // myArray została przekształcona\r\n```\r\n\r\nZmienna jest określana jako \"niemodyfikowalna\" (*immutable*), kiedy nie może być przekształcana.\r\n\r\n[Zobacz artykuł](https://developer.mozilla.org/en-US/docs/Glossary/Mutable).\r\n"
  },
  {
    "path": "JavaScript/translations/pt-BR.md",
    "content": "# Cheatsheet de JavaScript Moderno\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Crédito da Imagem: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## Introdução\r\n\r\n### Motivação\r\n\r\nEsse documento é um conjunto de \"cheatsheet\" para javascript que você frequentemente encontrará em projetos modernos e na maioria de exemplos de códigos atuais.\r\n\r\nEsse guia não tem a intenção de te ensinar Javascript do zero, mas sim ajudar desenvolvedores com conhecimentos básicos a se familiarizarem com códigos modernos.\r\n\r\nAlém disso, eu @mbeaudru ocasionalmente forneço dicas que podem ser discutidas, mas tomarei o cuidado de avisar quando eu fizer uma recomendação pessoal.\r\n\r\n> **Nota:** Muito dos conceitos apresentados aqui vem de uma atualização do Javascript (ES2015, chamada também de ES6). Você pode achar as novas funcionalidades adicionadas nessa atualização [aqui](http://es6-features.org).\r\n\r\n### Material Complementar\r\n\r\nSe você estiver com dificuldades em entender alguma coisa, eu sugiro que você procure por respostas nos seguintes lugares:\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/fr/search?q=)\r\n- [You don't know JS (livro)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Funcionalidades e exemplos](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) para encontrar blogs e recursos específicos\r\n\r\n## Sumário\r\n\r\n- [Modern JavaScript cheatsheet](#modern-javascript-cheatsheet)\r\n  * [Introdução](#Introdução)\r\n    + [Motivação](#Motivação)\r\n    + [Material Complementar](#Material-Complementar)\r\n  * [Tabela de Conteúdos](#Sumário)\r\n  * [Noções](#Noções)\r\n    + [Declaração de variáveis: var, const, let](#declaração-de-variáveis-var-const-let)\r\n      - [Breve explicação](#breve-explicação)\r\n      - [Exemplo](#exemplo)\r\n      - [Explicação Detalhada](#explicação-detalhada)\r\n      - [Material Complementar](#material-complementar)\r\n    + [Função de Seta](#função-de-seta)\r\n      - [Exemplo](#exemplo-de-codigo)\r\n      - [Explicação Detalhada](#detailed-explanation-1)\r\n        * [Concisão](#concisão)\r\n        * [Referência *this*](#referência-this)\r\n      - [Material Útil](#material-útil)\r\n    + [Parametros padrão de uma Function](#parametros-padrão-de-uma-function)\r\n      - [Material Complementar](#material-complementar)\r\n    + [Desestruturação de objetos e arrays](#desestruturação-de-objetos-e-arrays)\r\n      - [Explicação com exemplo de código](#explicação-com-exemplo-de-código)\r\n      - [Material Útil](#material-útil-1)\r\n    + [Metodos de lista - map / filter / reduce](#array-methods---map--filter--reduce)\r\n      - [Exemplo](#sample-code-2)\r\n      - [Explicação](#explanation)\r\n        * [Array.prototype.map()](#arrayprototypemap)\r\n        * [Array.prototype.filter()](#arrayprototypefilter)\r\n        * [Array.prototype.reduce()](#arrayprototypereduce)\r\n      - [Material Complementar](#external-resource)\r\n    + [Spread operator \"...\"](#spread-operator-)\r\n      - [Exemplo](#sample-code-3)\r\n      - [Explicação](#explanation-1)\r\n        * [Em interações (como arrays)](#in-iterables-like-array)\r\n        * [Function rest parameter](#function-rest-parameter)\r\n        * [Object properties spreading](#object-properties-spreading)\r\n      - [Material Complementar](#external-resources)\r\n    + [Object property shorthand](#object-property-shorthand)\r\n      - [Explicação](#explanation-2)\r\n      - [Material Complementar](#external-resources-1)\r\n    + [Promises](#promises)\r\n      - [Exemplo](#sample-code-4)\r\n      - [Explicação](#explanation-3)\r\n        * [Criando uma promise](#create-the-promise)\r\n        * [Usando uma promise](#use-the-promise)\r\n      - [External Resources](#external-resources)\r\n    + [Template literals](#template-literals)\r\n      - [Sample code](#sample-code-5)\r\n      - [External resources](#external-resources-2)\r\n    + [Imports / Exports](#imports--exports)\r\n      - [Explanation with sample code](#explanation-with-sample-code-1)\r\n      - [External resources](#external-resources-3)\r\n    + [JavaScript *this*](#-javascript-this)\r\n      - [External resources](#external-resources-4)\r\n    + [Class](#class)\r\n      - [Samples](#samples)\r\n      - [External resources](#external-resources-5)\r\n    + [Async Await](#async-await)\r\n      - [Sample code](#sample-code-6)\r\n      - [Explanation](#explanation-4)\r\n      - [External resources](#external-resources-7)\r\n  * [Glossary](#glossary)\r\n    + [Scope](#-scope)\r\n    + [Variable mutation](#-variable-mutation)\r\n\r\n## Noções\r\n\r\n### Declaração de variáveis: var, const, let\r\n\r\nEm JavaScript, existem três palavras-chave disponíveis para declarar uma variável, e cada uma tem suas diferenças. São elas ```var```, ```let``` e ```const```.\r\n\r\n#### Breve explicação\r\n\r\nVariáveis declaradas com a palavra-chave ```const``` não podem ser reatribuídas, enquanto ```let``` e ```var``` podem.\r\n\r\nEu recomendo sempre declarar suas variáveis com ```const``` por padrão, e com ```let``` se você precisar *modifica-lo* ou reatribuí-lo mais tarde.\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>Escopo</th>\r\n    <th>Reatribuível</th>\r\n    <th>Mutável</th>\r\n   <th><a href=\"#tdz_sample\">Zona Temporal Inoperante</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>const</th>\r\n    <td>Bloco</td>\r\n    <td>Não</td>\r\n    <td><a href=\"#const_mutable_sample\">Sim</a></td>\r\n    <td>Sim</td>\r\n  </tr>\r\n  <tr>\r\n    <th>let</th>\r\n    <td>Bloco</td>\r\n    <td>Sim</td>\r\n    <td>Sim</td>\r\n    <td>Sim</td>\r\n  </tr>\r\n   <tr>\r\n    <th>var</th>\r\n    <td>Função</td>\r\n    <td>Sim</td>\r\n    <td>Sim</td>\r\n    <td>Não</td>\r\n  </tr>\r\n</table>\r\n\r\n#### Exemplo\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // Irá ocorrer um erro, person não pode ser reatribuída\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", a reatribuição é permitida com let\r\n```\r\n\r\n#### Explicação Detalhada\r\n\r\nO [*escopo*](#scope_def) de uma variável grosseiramente significa \"onde esta variável está disponível no código\".\r\n\r\n##### var\r\n\r\nVariáveis declaradas com ```var``` são *função escopada*, significando que quando uma variável é criada em uma função, tudo naquela função pode acessar essa variável. Além disso, uma variável de *função escopada* criada em uma função não pode ser acessada fora desta função.\r\n\r\nEu recomendo que você imagine isso, como se uma variável *X escopada* significasse que essa variável era uma propriedade de X.\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar é acessível dentro da função.\r\n}\r\nconsole.log(myVar); // Lança um ReferenceError, myVar não está acessível fora da função.\r\n```\r\n\r\nAinda focado na variável de escopo, aqui está um exemplo mais sutil:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // na verdade, sendo myVar do escopo da função, nós simplesmente apagamos o valor anterior do myVar \"Nick\" para \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - veja como as instruções no bloco if afetaram esse valor\r\n}\r\nconsole.log(myVar); // Lança um ReferenceError, myVar não é acessível fora da função.\r\n```\r\n\r\nAlém disso, variáveis declaradas *var* são movidas para o topo do escopo na execução. É o que chamamos de [içando a var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting).\r\n\r\nEsta parte do código:\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- sem erro lançado\r\nvar myVar = 2;\r\n```\r\n\r\né entendido na execução como:\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- sem erro lançado\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n```var``` e ```let ``` são quase os mesmos, mas variáveis declaradas com ```let```\r\n\r\n- são *escopado em bloco*\r\n- **não** são acessíveis antes de serem atribuídas\r\n- não podem ser re-declaradas no mesmo escopo\r\n\r\nVamos ver o impacto do escopo em bloco em nosso exemplo anterior:\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // na verdade, myVar sendo escopada em bloco, nós criamos uma nova variável myVar.\r\n    // essa variável não é acessível fora do bloco e é totalmente independente\r\n    // da primeira myVar criada !\r\n  }\r\n  console.log(myVar); // \"Nick\", veja como as instruções no bloco IF NÃO afetou este valor\r\n}\r\nconsole.log(myVar); // lançado um ReferenceError, myVar não é acessível fora da fucnção.\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> Agora, o que significa para as variáveis *let* (e *const*) não estarem acessíveis antes de serem atribuídas:\r\n\r\n```js\r\nconsole.log(myVar) // lança um ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\nEm contraste com as variáveis *var*, se você tentar ler ou escrever em uma variável *let* ou *const* antes de serem atribuídos, um erro será gerado. Esse fenômeno é freqüentemente chamado [*Zona Temporal Inoperante*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) ou *TDZ*.\r\n\r\n> **Nota:** Tecnicamente, as declarações de *let* e *const* também estão sendo içadas, mas não a sua atribuição. Uma vez que elas são feitas para que elas não possam ser usados antes da atribuição, ela intuitivamente parece que não há içamento, mas existe. Saiba mais sobre isso [explicação muito detalhada aqui](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified) se quiser saber mais.\r\n\r\nAlém disso, você não pode re-declarar uma variável *let*:\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // Retorna um SyntaxError\r\n```\r\n\r\n##### const\r\n\r\nVariáveis declaradas ```const``` agem como variáveis *let*, mas elas não podem ser reatribuídas.\r\n\r\nPara resumir, variáveis *const*:\r\n\r\n- são *escopado em bloco*\r\n- não são acessíveis antes de serem atribuídos\r\n- não podem ser re-declaradas no mesmo escopo\r\n- não podem ser reatribuídas\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // lança um erro, reatribuição não é permitido\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // lança um erro, re-declaração não é permitida\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> Mas há uma sutileza : variáveis ```const``` não são [**imutáveis**](#mutation_def) ! Concretamente, Isto significa que variáveis *objetos* e *arrays* declaradas com ```const``` **podem** ser mutadas.\r\n\r\nPara objetos:\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // isto irá funcionar! A variável objeto person não é completamente reatribuída, mas mutada\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // lança um erro, porque a reatribuição não é permitida com variáveis declaradas com const\r\n```\r\n\r\nPara arrays:\r\n```js\r\nconst person = [];\r\nperson.push('John'); // isto irá funcionar! A variável array person não é completamente reatribuída, mas mutada\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // lança um erro, porque a reatribuição não é permitida com variáveis declaradas com array\r\n```\r\n\r\n#### Material Complementar\r\n\r\n- [Como let e const são escopados em JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Zona temporal Inoperante (TDZ) desmistificada](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"função-de-seta\"></a> Função de seta\r\n\r\nA atualização do JavaScript ES6 introduziu *funções de seta*, que é outra maneira de declarar e usar funções. Aqui estão os benefícios que elas trazem:\r\n\r\n- Mais conciso\r\n- *this* é retirado dos arredores\r\n- retorno implícito\r\n\r\n#### Exemplo de código\r\n\r\n- Concisão e retorno implícito\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // Forma tradicional\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // A mesma função escrita como uma função de seta com retorno implícito\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- Referência *this*\r\n\r\nEm uma função de seta, *this* é igual ao valor *this* do contexto de execução envolvente. Basicamente, com as funções de seta, você não precisa fazer o truque \"that/self = this\" antes de chamar uma função dentro de uma função.\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### Explicação detalhada\r\n\r\n##### Concisão\r\n\r\nAs funções de seta são mais concisas do que as funções tradicionais em diversas maneiras. Vamos rever todos os casos possíveis:\r\n\r\n- Retorno implícito VS explícito\r\n\r\nUm **retorno explícito** é uma função em que a palavra-chave *return* é usada em seu corpo.\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // esta função retorna explicitamente x * 2, a palavra-chave *retorno*  é usada\r\n  }\r\n```\r\n\r\nNa maneira tradicional de escrever funções, o retorno sempre foi explícito. Mas com funções de seta, você pode fazer *retorno implícito*, o que significa que você não precisa usar a palavra-chave *return* para retornar um valor.\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // um retorno explícito aqui\r\n  }\r\n```\r\n\r\nUma vez que esta função apenas retorna algo (sem instruções antes da palavra-chave *return*), podemos fazer um retorno implícito.\r\n\r\n```js\r\n  const double = (x) => x * 2; // Correto, retorna x*2\r\n```\r\n\r\nPara fazer isso, só precisamos **remover os colchetes** e a palavra-chave **return**. É por isso que é chamado de *retorno implícito*, a palavra-chave *return* não existe, mas essa função retornará ```x * 2```.\r\n\r\n> **Nota:** Se sua função não retornar um valor (com *efeitos colaterais*), ele não faz um retorno explícito nem implícito.\r\n\r\nAlém disso, se você quiser retornar implicitamente um *objeto*, você **deve ter parênteses em torno dele**, pois isso entrará em conflito com as chaves do bloco:\r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- objeto implicitamente retornado pela função de seta\r\n```\r\n\r\n- Só um argumento\r\n\r\nSe a sua função apenas tiver um parâmetro, você pode omitir os parênteses à sua volta. Se pegarmos o código *double* acima:\r\n\r\n```js\r\n  const double = (x) => x * 2; // esta função de seta apenas leva um parâmetro\r\n```\r\n\r\nParênteses ao redor do parâmetro podem ser evitados:\r\n\r\n```js\r\n  const double = x => x * 2; // esta função de seta tem apenas um parâmetro\r\n```\r\n\r\n- Nenhum argumento\r\n\r\nQuando não há argumento fornecido para uma função de seta, você precisa fornecer parênteses, ou não será uma sintaxe válida.\r\n\r\n```js\r\n  () => { // parênteses são fornecidos, tudo está ok\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // Sem parênteses, isso não funcionará!\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### Referência *this*\r\n\r\nPara entender essa sutileza introduzida com funções de seta, você deve saber como [this](#this_def) se comporta em JavaScript.\r\n\r\nEm funções de seta, *this* é igual ao valor *this* do contexto de execução envolvente. O que significa que uma função de seta não cria um novo *this*, Ela pega do seu entorno em vez disso.\r\n\r\nSem uma função de seta, se você quisesse acessar uma variável de *this* em uma função dentro de outra função, você tinha que usar *that = this* ou *self = this*.\r\n\r\nPor exemplo, usando a função setTimeout dentro de myFunc:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // that = this (truque)\r\n  setTimeout(\r\n    function() { // Um novo *this* é criado neste escopo de função\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- veja a declaração da função acima\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\nMas com função de seta, *this* é retirado do seu entorno:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this é retirado do entorno, o que significa de myFunc aqui\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### Material Útil\r\n\r\n- [Arrow functions introduction (Introdução à Funções de Seta) - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n### Parametros padrão de uma Function\r\n\r\nA partir da atualização do JavaScript ES2015, você pode definir um valor padrão para os parâmetros da função usando a seguinte sintaxe:\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- nenhum valor é fornecido então o valor padrão de x que é 10 será atribuído a x em myFunc\r\nconsole.log(myFunc(5)) // 5 -- um valor é fornecido então x é igual a 5 em myFunc\r\n\r\nconsole.log(myFunc(undefined)) // 10 -- um valor undefined é fornecido então o valor padrão é atribuído para x\r\nconsole.log(myFunc(null)) // null -- um valor (null) é fornecido, veja abaixo para mais detalhes neste caso\r\n```\r\n\r\nO valor de parâmetro padrão é aplicado em duas e somente duas situações:\r\n\r\n- Nenhum parâmetro fornecido\r\n- *undefined* parâmetro fornecido\r\n\r\nEm outras palavras, se você passar um *null* o parâmetro padrão **não irá ser aplicado**.\r\n\r\n> **Nota:** Atribuição de valor padrão também pode ser usada com parâmetros desestruturados (veja o próximo conceito para ver um exemplo)\r\n\r\n#### Material Complementar\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Default parameters - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\r\n\r\n### Desestruturação de objetos e arrays\r\n\r\n*Desestruturação* é uma maneira conveniente de criar novas variáveis extraindo alguns valores de dados armazenados em objetos ou arrays (matrizes).\r\n\r\nPara nomear alguns casos de uso, *desestruturação* pode ser usado para desestruturar parâmetros de função ou *this.props* em projetos React, por exemplo.\r\n\r\n#### Explicação com exemplo de código\r\n\r\n- Objeto\r\n\r\nVamos considerar o seguinte objeto para todos os exemplos:\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\nSem desestruturação\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\nCom desestruturação, tudo em uma única linha:\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // É isso ! :)\r\n\r\nconsole.log(age) // 35 -- uma nova variável age é criada e é igual a person.age\r\nconsole.log(first) // \"Nick\" -- uma nova variável first é criada e é igual person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName existe MAS a nova variável criada é nomeada primeiro\r\nconsole.log(city) // \"Paris\" -- uma nova variável city é criada e uma vez que person.city é indefinida, city é igual ao valor padrão fornecido \"Paris\".\r\n```\r\n\r\n**Nota :** Em ```const { age } = person;```, os colchetes depois da palavra-chave *const* não são usados para declarar um objeto nem um bloco, mas é a sintaxe da *desestruturação*.\r\n\r\n- Parâmetros de função\r\n\r\n*Desestruturação* é freqüentemente usado para desestruturar parâmetros de objetos em funções.\r\n\r\nSem desestruturação\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nAo desestruturar o parâmetro de objeto *person*, obtemos uma função mais concisa:\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { // criamos variáveis firstName e lastName por desestruturação person parameter\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nA desestruturação é ainda mais agradável para usar com [funções de seta] (#função-de-seta):\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- Array (Matriz)\r\n\r\nVamos considerar a seguinte array:\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\nSem desestruturação\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\nCom desestruturação\r\n\r\n```js\r\nconst [x, y] = myArray; // É isso !\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n#### Material Útil\r\n\r\n- [ES6 Features - Destructuring Assignment (Funcionalidades ES6 - Atribuição de Destruturação)](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)"
  },
  {
    "path": "JavaScript/translations/ru-RU.md",
    "content": "# Памятка по современному JavaScript\r\n![Памятка по современному JavaScript](https://i.imgur.com/aexPxMb.png)\r\n<small>За картинку спасибо [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## Введение\r\n\r\n### Мотивация\r\nВ этом документе собраны возможности языка JavaScript, с которыми вы наверняка столкнетесь в современных проектах и примерах кода.\r\n\r\nЦель этого руководства — не обучить вас JavaScript с нуля, а помочь разработчикам с базовыми знаниями, которые при изучении современных кодовых баз (или, скажем, React) сталкиваются со сложностями из-за использованных в них концепций JavaScript.\r\n\r\nИногда я буду давать личные советы, которые могут быть спорными, но постараюсь упоминать, что это личное мнение.\r\n> **Примечание:** Большинство представленных здесь понятий взяты из обновления языка JavaScript (ES2015, которое часто называют ES6). Вы можете найти новые возможности из этого обновления [здесь](http://es6-features.org); они хорошо описаны.\r\n\r\n### Дополнительные ресурсы\r\nЕсли вам сложно разобраться с каким-то понятием, рекомендую искать ответы на вопросы на следующих ресурсах:\r\n- [MDN (сеть разработчиков Mozilla)](https://developer.mozilla.org/ru/search?q=).\r\n- [Вы не знаете JS (серия книг)](https://github.com/azat-io/you-dont-know-js-ru).\r\n- [ES6 Features with examples](http://es6-features.org).\r\n- [Блог WesBos (ES6)](http://wesbos.com/category/es6/).\r\n- [Javascript Basics for Beginners](https://www.udacity.com/course/javascript-basics--ud804) — бесплатный курс от Udacity.\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/).\r\n- [Google](https://www.google.com/) для поиска специализированных блогов и ресурсов.\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript).\r\n\r\n## Содержание\r\n- [Памятка по современному JavaScript](#Памятка-по-современному-javascript)\r\n  * [Введение](#Введение)\r\n    + [Мотивация](#Мотивация)\r\n    + [Дополнительные ресурсы](#Дополнительные-ресурсы)\r\n  * [Содержание](#Содержание)\r\n  * [Понятия](#Понятия)\r\n    + [Объявление переменных: `var`, `const`, `let`](#Объявление-переменных-var-const-let)\r\n      - [Краткое объяснение](#Краткое-объяснение)\r\n      - [Пример кода](#Пример-кода)\r\n      - [Подробное объяснение](#Подробное-объяснение)\r\n      - [Дополнительные материалы](#Дополнительные-материалы)\r\n    + [Стрелочные функции](#-Стрелочные-функции)\r\n      - [Пример кода](#Пример-кода-1)\r\n      - [Подробное объяснение](#Подробное-объяснение-1)\r\n        * [Краткость](#Краткость)\r\n        * [Использование `this`](#Использование-this)\r\n      - [Полезные ресурсы](#Полезные-ресурсы)\r\n    + [Значение аргументов функции по умолчанию](#Значение-аргументов-функции-по-умолчанию)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-1)\r\n    + [Деструктуризация объектов и массивов](#Деструктуризация-объектов-и-массивов)\r\n      - [Объяснение с помощью примера кода](#Объяснение-с-помощью-примера-кода)\r\n      - [Полезные ресурсы](#Полезные-ресурсы-1)\r\n    + [Методы массивов - `map` / `filter` / `reduce`](#Методы-массивов--map--filter--reduce)\r\n      - [Пример кода](#Пример-кода-2)\r\n      - [Объяснение](#Объяснение)\r\n        * [`Array.prototype.map()`](#arrayprototypemap)\r\n        * [`Array.prototype.filter()`](#arrayprototypefilter)\r\n        * [`Array.prototype.reduce()`](#arrayprototypereduce)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-2)\r\n    + [Оператор расширения `...`](#Оператор-расширения-)\r\n      - [Пример кода](#Пример-кода-3)\r\n      - [Объяснение](#Объяснение-1)\r\n        * [В итерируемых объектах (например, массивах)](#В-итерируемых-объектах-например-массивах)\r\n        * [Оставшиеся аргументы функции](#Оставшиеся-аргументы-функции)\r\n        * [Расширение свойств объектов](#Расширение-свойств-объектов)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-3)\r\n    + [Сокращенная запись свойств объектов](#Сокращенная-запись-свойств-объектов)\r\n      - [Объяснение](#Объяснение-2)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-4)\r\n    + [Промисы](#Промисы)\r\n      - [Пример кода](#Пример-кода-4)\r\n      - [Пояснение](#Пояснение)\r\n        * [Создание промиса](#Создание-промиса)\r\n        * [Использование обработчиков промисов](#Использование-обработчиков-промисов)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-5)\r\n    + [Шаблонные строки](#Шаблонные-строки)\r\n      - [Пример кода](#Пример-кода-5)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-6)\r\n    + [Тегированные шаблонные строки](#Тегированные-шаблонные-строки)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-7)\r\n    + [Импорт / экспорт](#Импорт--экспорт)\r\n      - [Объяснение с помощью примера кода](#Объяснение-с-помощью-примера-кода)\r\n        * [Именованный экспорт](#Именованный-экспорт)\r\n        * [Импорт / экспорт по умолчанию](#Импорт--экспорт-по-умолчанию)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-8)\r\n    + [`this` в JavaScript](#-this-в-javascript)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-9)\r\n    + [Класс](#Класс)\r\n      - [Примеры](#Примеры)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-10)\r\n    + [Ключевые слова Extends и super](#Ключевые-слова-extends-и-super)\r\n      - [Пример кода](#Пример-кода-6)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-11)  \r\n    + [Async Await](#async-await)\r\n      - [Пример кода](#Пример-кода-7)\r\n      - [Объяснение с помощью примера кода](#Объяснение-с-помощью-примера-кода-1)\r\n      - [Обработка ошибок](#Обработка-ошибок)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-12)\r\n    + [Истина / Ложь](#Истина--Ложь)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-13)\r\n    + [Анаморфизмы и катаморфизмы](#Анаморфизмы-и-катаморфизмы)\r\n      - [Анаморфизмы](#Анаморфизмы)\r\n        * [Пример кода](#Пример-кода-8)\r\n      - [Катаморфизмы](#Катаморфизмы)\r\n        * [Пример кода](#Пример-кода-9)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-14)\r\n    + [Генераторы](#Генераторы)\r\n      - [Пример кода](#Пример-кода-10)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-15)  \r\n    + [Статические методы](#Статические-методы)\r\n      - [Краткое объяснение](#Краткое-объяснение-1)\r\n      - [Пример кода](#Пример-кода-11)\r\n      - [Подробное объяснение](#Подробное-объяснение-2)\r\n        * [Вызов статических методов из статического метода](#Вызов-статических-методов-из-статического-метода)\r\n        * [Вызов статических методов из нестатических методов](#Вызов-статических-методов-из-нестатических-методов)\r\n      - [Дополнительные материалы](#Дополнительные-материалы-16)\r\n  * [Глоссарий](#Глоссарий)\r\n    + [Область видимости](#-Область-видимости)\r\n    + [Изменение переменных](#-Изменение-переменных)\r\n\r\n## Понятия\r\n\r\n### Объявление переменных: `var`, `const`, `let`\r\nВ JavaScript есть три ключевых слова, отвечающих за объявление переменных, и у каждого из них свои особенности. Эти слова − `var`, `let` и `const`.\r\n\r\n#### Краткое объяснение\r\nПеременным, объявленным с помощью ключевого слова `const`, нельзя позже присвоить новое значение, в то время как переменным, объявленным с помощью `let` или `var`, можно.\r\n\r\nЯ рекомендую всегда объявлять переменные ключевым словом `const`, а `let` использовать только в том случае, если позже эту переменную понадобится *изменить* или переопределить.\r\n<table>\r\n<tr>\r\n<th></th>\r\n<th>Область видимости</th>\r\n<th>Можно переопределять</th>\r\n<th>Можно изменять</th>\r\n<th><a href=\"#tdz_sample\">Временная мертвая зона</a></th>\r\n</tr>\r\n<tr>\r\n<th>`const`</th>\r\n<td>Блок</td>\r\n<td>Нет</td>\r\n<td><a href=\"#const_mutable_sample\">Да</a></td>\r\n<td>Да</td>\r\n</tr>\r\n<tr>\r\n<th>`let`</th>\r\n<td>Блок</td>\r\n<td>Да</td>\r\n<td>Да</td>\r\n<td>Да</td>\r\n</tr>\r\n<tr>\r\n<th>`var`</th>\r\n<td>Функция</td>\r\n<td>Да</td>\r\n<td>Да</td>\r\n<td>Нет</td>\r\n</tr>\r\n</table>\r\n\r\n#### Пример кода\r\n```js\r\nconst person = \"Коля\";\r\nperson = \"Ваня\" // Вызовет ошибку, переменной person нельзя присвоить новое значение.\r\n```\r\n```js\r\nlet person = \"Коля\";\r\nperson = \"Ваня\";\r\nconsole.log(person) // -> \"Ваня\", присвоение нового значения разрешено в случае с let.\r\n```\r\n\r\n#### Подробное объяснение\r\n[*Область видимости*](#scope_def) переменной определяет, где эта переменная доступна в коде.\r\n\r\n##### `var`\r\nОбластью видимости переменных, объявленных с помощью `var`, является функция. Это означает, что если переменная была создана внутри функции, то у всего внутри этой функции есть доступ к данной переменной. Кроме того, переменная с областью видимости внутри функции недоступна за пределами этой функции.\r\n\r\nМожно думать об этом вот так: если у переменной область видимости *Х*, то эта переменная — как бы свойство Х.\r\n```js\r\nfunction myFunction() {\r\n  var myVar = \"Коля\";\r\n  console.log(myVar); // -> \"Коля\" — myVar доступна внутри функции.\r\n}\r\nconsole.log(myVar); // ReferenceError, myVar недоступна снаружи функции.\r\n```\r\nВот менее очевидный пример области видимости переменных:\r\n```js\r\nfunction myFunction() {\r\n  var myVar = \"Коля\";\r\n  if (true) {\r\n      var myVar = \"Ваня\";\r\n      console.log(myVar); // -> \"Ваня\"\r\n      /* На самом деле, область видимости myVar — функция,\r\n      мы всего лишь удалили предыдущее значение переменной myVar \"Коля\"\r\n      и заменили его на \"Ваня\". */\r\n    }\r\n    console.log(myVar); // -> \"Ваня\" — обратите внимание, как код в блоке if повлиял на это значение.\r\n  }\r\n  console.log(myVar); // ->  \r\n  /* ReferenceError, переменная myVar недоступна\r\n  за пределами функции, в которой определена. */\r\n```\r\nКроме этого, переменные, объявленные с помощью ключевого слова `var`, при выполнении кода перемещаются в начало области видимости. Это называется [поднятие переменных](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/var#Поднятие_переменных).\r\n\r\nЭтот фрагмент кода:\r\n```js\r\nconsole.log(myVar) // -> undefined — ошибок нет.\r\nvar myVar = 2;\r\n```\r\nпри выполнении понимается как:\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // -> undefined — ошибок нет.\r\nmyVar = 2;\r\n```\r\n\r\n##### `let`\r\n`var` и `let` примерно одинаковы, в то время как переменные, объявленные словом `let`:\r\n- имеют в качестве области видимости блок;\r\n- **недоступны** до объявления;\r\n- не могут быть повторно объявлены в той же области видимости.\r\n\r\nДавайте разберемся, в чем особенности блочной области видимости, используя предыдущий пример:\r\n```js\r\nfunction myFunction() {\r\n  let myVar = \"Коля\";\r\n  if (true) {\r\n    let myVar = \"Ваня\";\r\n    console.log(myVar); // -> \"Ваня\"\r\n    /* Поскольку myVar имеет блочную область видимости,\r\n    здесь мы только что создали новую переменную myVar.\r\n    Эта переменная недоступна вне блока и никак не зависит\r\n    от первой переменной myVar, которую мы создали до этого! */\r\n  }\r\n  console.log(myVar); // -> \"Коля\" — обратите внимание: инструкции в блоке if НЕ повлияли на значение переменной.\r\n}\r\nconsole.log(myVar); // -> ReferenceError, myVar недоступна за пределами функции.\r\n```\r\n<a name=\"tdz_sample\"></a> Теперь разберемся, что значит «переменные, объявленные с помощью `let` и `const`, недоступны до их объявления»:\r\n```js\r\nconsole.log(myVar) // Вызовет ReferenceError!\r\nlet myVar = 2;\r\n```\r\nВ отличие от переменных, объявленных через `var`, попытка обратиться к переменной `let` или `const` до её объявления вызовет ошибку. Этот феномен часто называют  [*Временной мёртвой зоной*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let).  \r\n> **Примечание:** строго говоря, объявления переменных с использованием `let` и `const` тоже поднимаются, однако их инициализация — нет. Они сделаны так, что использовать их до инициализации нельзя. Поэтому интуитивно кажется, что такие переменные не поднимаются, но на самом деле это не так. Больше информации можно найти в [этом очень подробном объяснении](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified).\r\n\r\nВ дополнение к сказанному: нельзя повторно объявить переменную, объявленную с помощью `let`:\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // Вызовет SyntaxError.\r\n```\r\n\r\n##### `const`\r\nПеременные, объявленные через `const`, ведут себя так же, как переменные, объявленные через `let`, но к тому же их нельзя переопределять.\r\n\r\nИтак, переменные, объявленные с помощью `const`:\r\n- имеют в качестве области видимости блок;\r\n- недоступны до объявления;\r\n- не могут быть повторно объявлены в той же области видимости;\r\n- не могут быть переопределены.\r\n```js\r\nconst myVar = \"Коля\";\r\nmyVar = \"Ваня\" // Вызовет ошибку, переопределять переменную нельзя.\r\n```\r\n```js\r\nconst myVar = \"Коля\";\r\nconst myVar = \"Ваня\" // Вызовет ошибку, объявить переменную можно только один раз.\r\n```\r\n<a name=\"const_mutable_sample\"></a> Но есть одна тонкость: переменные, объявленные с помощью `const`, не являются [**неизменными**](#mutation_def)! А именно, это означает, что *объекты* и *массивы*, объявленные с помощью `const`, **могут** быть изменены.\r\n\r\nВ случае объектов:\r\n```js\r\nconst person = {\r\n  name: 'Коля',\r\n};\r\nperson.name = 'Ваня'; // Сработает! Переменная person не полностью переопределяется, а просто меняется.\r\nconsole.log(person.name); // -> \"Ваня\"\r\nperson = \"Сандра\"; // Вызовет ошибку, потому что переменные, объявленные через const, переопределять нельзя.\r\n```\r\nВ случае массивов:\r\n```js\r\nconst person = [];\r\nperson.push('Ваня'); // Сработает!  Переменная person не полностью переопределяется, а просто меняется.\r\nconsole.log(person[0]); // -> \"Ваня\"\r\nperson = [\"Коля\"]; // Вызовет ошибку, потому что переменные, объявленные через const, переопределять нельзя.\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [How let and const are scoped in JavaScript — WesBos](http://wesbos.com/javascript-scoping/).\r\n- [Temporal dead zone (tdz) demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified).\r\n\r\n### <a name=\"arrow_func_concept\"></a> Стрелочные функции\r\nВ обновлении JavaScript ES6 добавлены *стрелочные функции* — новый синтаксис записи функций. Вот некоторые их преимущества:\r\n- краткость;\r\n- `this` берется из окружающего контекста;\r\n- неявный возврат.\r\n\r\n#### Пример кода\r\n- Краткость и неявный возврат.\r\n```js\r\nfunction double(x) { return x * 2; } // Обычный способ.\r\nconsole.log(double(2)); // -> 4\r\n```\r\n```js\r\nconst double = x => x * 2; /* Та же функция, записанная в виде стрелочной функции с неявным возвратом. */\r\nconsole.log(double(2)); // -> 4\r\n```\r\n- Использование `this`.\r\n\r\nВнутри стрелочной функции значение `this` такое же, как и во внешней области видимости. В принципе, со стрелочными функциями вам больше не нужно прибегать к хаку `that = this` перед вызовом функции внутри функции.\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar); // -> 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### Подробное объяснение\r\n\r\n##### Краткость\r\nСтрелочные функции во многих отношениях более краткие, чем обычные. Рассмотрим все возможные случаи:\r\n- Явный и неявный возврат.\r\n\r\nФункция может **явно возвращать** результат с использованием ключевого слова `return`.\r\n```js\r\nfunction double(x) {\r\n  return x * 2; // Эта функция явно возвращает x * 2, использовано ключевое слово *return*.\r\n}\r\n```\r\nПри обычном способе написания функций возврат всегда был явным. Со стрелочными функциями его можно сделать *неявным*. Это значит, что для возврата значения не нужно использовать ключевое слово `return`.\r\n\r\n```js\r\nconst double = (x) => {\r\n  return x * 2; // Явный возврат.\r\n}\r\n```\r\nПоскольку здесь нет ничего, кроме возвращаемого значения, можно вернуть значение без явного указания.\r\n```js\r\nconst double = (x) => x * 2; // Всё верно, вернётся x * 2.\r\n```\r\nДля этого нам просто нужно **убрать фигурные скобки** и ключевое слово `return`. Поэтому это и называется *неявным* возвратом: ключевого слова `return` нет, но функция все равно вернет `x * 2`.\r\n> **Примечание**: Если ваша функция не возвращает никакого значения (с *побочными эффектами*), то в ней нет ни явного, ни неявного возврата.\r\n\r\nКроме того, если вы хотите неявно вернуть *объект*, вы **должны заключить его в круглые скобки**, так как иначе он будет конфликтовать с фигурными скобками блоков:\r\n```js\r\nconst getPerson = () => ({ name: \"Коля\", age: 24 })\r\nconsole.log(getPerson())\r\n// { name: \"Коля\", age: 24 } — объект, неявно возвращенный стрелочной функцией.\r\n```\r\n\r\n- Только один аргумент.\r\n\r\nЕсли ваша функция принимает только один аргумент, то скобки вокруг него можно опустить. Возвращаясь к функции `double` в коде выше:  \r\n```js\r\nconst double = (x) => x * 2; // Эта стрелочная функция принимает только один аргумент.\r\n```\r\nСкобки вокруг этого аргумента можно опустить:\r\n```js\r\nconst double = x => x * 2; // Эта стрелочная функция принимает только один аргумент.\r\n```\r\n- Без аргументов.\r\n\r\nКогда стрелочная функция вообще не принимает никаких аргументов, нужно использовать пустые круглые скобки, иначе синтаксис будет неправильным.\r\n```js\r\n() => { // Скобки есть, все хорошо.\r\n  const x = 2;\r\n  return x;\r\n}\r\n```\r\n```js\r\n=> { // Скобок нет, так работать не будет!\r\n  const x = 2;\r\n  return x;\r\n}\r\n```\r\n\r\n##### Использование `this`\r\nЧтобы понять эту тонкость поведения стрелочных функций, нужно понимать, как [`this`](#this_def) ведёт себя в JavaScript.\r\n\r\nВнутри стрелочной функции значение `this` равно значению `this` внешнего окружения. Это значит, что стрелочная функция не создает новый `this`, а получает его из окружения.\r\n\r\nБез использования стрелочных функций для получения доступа к переменной через `this` в функции, вложенной в другую функцию, придется использовать хак `that = this` или `self = this`.\r\n\r\nВот, к примеру, использование функции `setTimeout` внутри функции `myFunc`:\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // Тот самый хак *that = this*\r\n  setTimeout(\r\n    function() { // В этой области видимости функции создается новый *this*.\r\n      that.myVar++;\r\n      console.log(that.myVar); // -> 1\r\n      console.log(this.myVar); // -> undefined — см. объявление функции выше.\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\nНо в случае стрелочных функций `this` берется из окружения:\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this берется из окружения. В данном случае — из myFunc.\r\n      this.myVar++;\r\n      console.log(this.myVar); // -> 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### Полезные ресурсы\r\n- [JavaScript Arrow Functions Introduction — WesBos](http://wesbos.com/arrow-functions/).\r\n- [Стрелочные функции в JavaScript — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions).\r\n- [Javascript ES6 — Arrow Functions and Lexical `this`](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4).\r\n\r\n### Значение аргументов функции по умолчанию\r\nНачиная с обновления JavaScript ES2015, аргументам функции можно присваивать значения по умолчанию, используя следующий синтаксис:\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()); /* -> 10 — никакое значение не передается,\r\nпоэтому в myFunc х присваивается значение по умолчанию, т.е. 10 */\r\nconsole.log(myFunc(5)); /* -> 5 — передается значение,\r\nпоэтому в myFunc х присваивается значение 5 */\r\n\r\nconsole.log(myFunc(undefined)); /* -> 10 — передается значение undefined,\r\nпоэтому х присваивается значение по умолчанию */\r\nconsole.log(myFunc(null)); // -> null — передается значение null. Подробнее см. ниже.\r\n```\r\nЗначения по умолчанию применяются только в двух случаях:\r\n- значение не передано;\r\n- передано значение `undefined`.\r\n\r\nДругими словами, если передать в функцию параметр `null`, то параметр по умолчанию **не применится**.\r\n> **Примечание:** Присваивать значение по умолчанию можно в том числе и при работе с деструктурированными параметрами (см. пример в следующем понятии).\r\n\r\n#### Дополнительные материалы\r\n- [Extended Parameter Handling](http://es6-features.org/#DefaultParameterValues).\r\n- [Параметры по умолчанию — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Default_parameters).\r\n\r\n### Деструктуризация объектов и массивов\r\n**Деструктуризация** — это удобный способ создания новых переменных путем извлечения значений из объектов или массивов.\r\n\r\nНа практике *деструктуризацию* можно использовать, чтобы присваивать переменным разбитые на части параметры функции или `this.props` в React-проектах.\r\n\r\n#### Объяснение с помощью примера кода\r\n- Объект.\r\n\r\nДавайте использовать во всех примерах следующий объект:\r\n```js\r\nconst person = {\r\n  firstName: \"Коля\",\r\n  lastName: \"Андреев\",\r\n  age: 35,\r\n  sex: \"М\",\r\n};\r\n```\r\nБез деструктуризации:\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Санкт-Петербург\";\r\n```\r\nС деструктуризацией всё поместится в одну строку:\r\n```js\r\nconst { firstName: first, age, city = \"Санкт-Петербург\" } = person; // И всё!\r\nconsole.log(age); /* -> 35 — Создана новая переменная age,\r\nи ей присвоено значение, равное person.age. */\r\nconsole.log(first); /* -> \"Коля\" — Создана новая переменная first,\r\nи ей присвоено значение, равное person.firstName. */\r\nconsole.log(firstName); /* -> ReferenceError — person.firstName существует,\r\nНО новая созданная переменная называется first. */\r\nconsole.log(city); /* -> \"Санкт-Петербург\" — Создана новая переменная city,\r\nи, поскольку свойство person.city ранее не было определено,\r\nпеременной присвоено альтернативное значение \"Санкт-Петербург\". */\r\n```\r\n> **Примечание:** В `const { age } = person;` скобки после ключевого слова `const` используются не для обозначения объекта или блока. Это синтаксис *деструктуризации*.\r\n\r\n- Параметры функции.\r\n\r\nДеструктуризация часто используется для разбиения параметров функции на части.\r\n\r\nБез деструктуризации:\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return `${firstName}—${lastName}`;\r\n}\r\njoinFirstLastName(person); // -> \"Коля-Андреев\"\r\n```\r\nЕсли деструктурировать параметр `person`, то функция получится куда более лаконичной:\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { /* Мы создали переменные firstName и lastName\r\n  из частей параметра person. */\r\n  return `${firstName}—${lastName}`;\r\n}\r\njoinFirstLastName(person); // -> \"Коля-Андреев\"\r\n```\r\nЕщё удобнее использовать деструктуризацию со [стрелочными функциями](#arrow_func_concept):\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => `${firstName}—${lastName}`;\r\njoinFirstLastName(person); // -> \"Коля-Андреев\"\r\n```\r\n- Массив.\r\n\r\nДавайте рассмотрим следующий массив:\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\nБез деструктуризации:\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\nС использованием деструктуризации:\r\n```js\r\nconst [x, y] = myArray; // Вот и всё!\r\n\r\nconsole.log(x); // -> \"a\"\r\nconsole.log(y); // -> \"b\"\r\n```\r\n\r\n#### Полезные ресурсы\r\n- [Destructuring Assignment](http://es6-features.org/#ArrayMatching).\r\n- [Destructuring Assignment - WesBos](http://wesbos.com/destructuring-objects/).\r\n- [ExploringJS — Destructuring](http://exploringjs.com/es6/ch_destructuring.html).\r\n\r\n### Методы массивов — `map` / `filter` / `reduce`\r\n`map`, `filter` и `reduce` — это методы массивов, пришедшие из парадигмы [*функционального программирования*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0).\r\n\r\nПеречислю их:\r\n- `Array.prototype.map()` принимает массив, каким-нибудь образом преобразует его элементы и возвращает новый массив трансформированных элементов.\r\n- `Array.prototype.filter()` принимает массив, просматривает каждый элемент и решает, убрать его или оставить. Возвращает массив оставшихся значений.\r\n- `Array.prototype.reduce()` принимает массив и вычисляет на основе его элементов какое-то единое значение, которое и возвращает.\r\n\r\nЯ рекомендую пользоваться ими как можно чаще, следуя принципам функционального программирования, потому что они лаконичные, элегантные и их можно комбинировать.\r\n\r\nВооружившись этими тремя методами, вы можете обойтись без использования `for` и `forEach` в большинстве ситуаций. Когда в следующий раз соберётесь запустить цикл `for`, попробуйте решить задачу с помощью `map`, `filter` и `reduce`. Поначалу это будет трудно, потому что вам придётся научиться мыслить по-другому, но, разобравшись один раз, вы сможете применять эти методы без особых усилий.\r\n\r\n#### Пример кода\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // -> [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // -> [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // -> 21\r\n```\r\nДавайте посчитаем сумму баллов всех студентов, которые набрали больше 10 баллов, используя `map`, `filter` и `reduce`:\r\n```js\r\nconst students = [\r\n  { name: \"Коля\", grade: 10 },\r\n  { name: \"Ваня\", grade: 15 },\r\n  { name: \"Юля\", grade: 19 },\r\n  { name: \"Наташа\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // Создаём массив оценок из массива студентов с помощью метода map.\r\n  .filter(grade => grade >= 10) // Выбираем только оценки выше 10 при помощи метода filter.\r\n  .reduce((prev, next) => prev + next, 0); // Суммируем все оценки выше 10 друг с другом.\r\n\r\nconsole.log(aboveTenSum); /* -> 44: 10 (Коля) + 15 (Ваня) + 19 (Юля),\r\nоценка Наташи меньше 10 и была проигнорирована */\r\n```\r\n\r\n#### Объяснение\r\nДавайте использовать в качестве примера следующий массив:\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n##### `Array.prototype.map()`\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // -> [0, 2, 4, 6, 8, 10, 12]\r\n```\r\nЧто же здесь происходит? Мы применяем к массиву `numbers` метод `map`, который взаимодействует с каждым элементом массива, передавая его в нашу функцию. Цель функции — произвести расчёт и вернуть новое значение, чтобы `map` мог подставить его вместо переданного в функцию.\r\n\r\nДавайте даже вынесем функцию из массива, чтобы было понятнее, что происходит:\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // -> [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n`numbers.map(doubleN)` создаёт `[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]`, что равняется `[0, 2, 4, 6, 8, 10, 12]`.\r\n> **Примечание:** Если вам не нужно возвращать новый массив и вы просто хотите перебрать существующий массив, совершая с его элементами некоторые действия, можете просто использовать `for` / `forEach` вместо метода `map`.\r\n\r\n##### `Array.prototype.filter()`\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // Истинно, если n чётное; ложно, если n нечётное.\r\n});\r\nconsole.log(evenNumbers); // -> [0, 2, 4, 6]\r\n```\r\nМы применяем `filter` к массиву `numbers`. Метод `filter` взаимодействует с каждым элементом массива и передаёт его в нашу функцию. Функция возвращает булево значение, определяющее, будет ли элемент сохранён в массиве. Затем `filter` возвращает массив отфильтрованных значений.\r\n\r\n##### `Array.prototype.reduce()`\r\nЦель метода `reduce` заключается в том, чтобы вычислить на основе массива какое-то одно значение. Какие именно вычисления метод произведет с элементами, зависит только от вас.\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n0 // Значение аккумулирующей переменной на первом шаге цикла.\r\n);\r\nconsole.log(sum); // -> 21\r\n```\r\nТак же, как методы `.map` и `.filter`, метод `.reduce` применяется к массиву и в качестве первого параметра принимает функцию.\r\n\r\nНа этот раз, впрочем, кое-что изменилось:\r\n- `.reduce` принимает два параметра.\r\n\r\nПервый параметр — это функция, которая будет вызываться на каждом шаге цикла.\r\n\r\nВторой параметр — это значение аккумулирующей переменной (`acc` в нашем случае) на первом шаге цикла (чтобы разобраться, читайте далее).\r\n- Параметры функции.\r\n\r\nФункция, которую вы передаёте в качестве первого параметра метода `.reduce`, принимает два аргумента. Первый аргумент — это аккумулирующая переменная (`acc` в нашем примере), второй аргумент — текущий элемент.\r\n\r\nАккумулирующая переменная равна значению, возвращённому нашей функцией на **предыдущем** шаге цикла. В самом начале каждого цикла `acc` равна значению, которое было передано в качестве второго параметра `.reduce`.\r\n\r\n###### На первом шаге\r\n`acc = 0`, потому что мы передали `0` в качестве второго параметра метода `reduce`.\r\n\r\n`n = 0` — первый элемент массива `number`.\r\n\r\nФункция возвращает `acc` + `n` --> 0 + 0 --> 0.\r\n\r\n###### На втором шаге\r\n`acc = 0`, потому что это значение функция вернула на предыдущем шаге.\r\n\r\n`n = 1` — второй элемент массива `number`.\r\n\r\nФункция возвращает `acc` + `n` --> 0 + 1 --> 1.\r\n\r\n###### На третьем шаге\r\n`acc = 1`, потому что это значение функция вернула на предыдущем шаге.\r\n\r\n`n = 2` — третий элемент массива `number`.\r\n\r\nФункция возвращает `acc` + `n` --> 1 + 2 --> 3.\r\n\r\n###### На четвертом шаге\r\n`acc = 3`, потому что это значение функция вернула на предыдущем шаге.\r\n\r\n`n = 3` — четвёртый элемент массива `number`.\r\n\r\nФункция возвращает `acc` + `n` --> 3 + 3 --> 6.\r\n\r\n###### На последнем шаге\r\n`acc = 15`, потому что это значение функция вернула на предыдущем шаге.\r\n\r\n`n = 6` — последний элемент массива `number`.\r\n\r\nФункция возвращает `acc` + `n` --> 15 + 6 --> 21.\r\n\r\nПоскольку это был последний шаг, `.reduce` возвращает `21`.\r\n\r\n#### Дополнительные материалы\r\n- [Understanding map, filter and reduce in JavaScript](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464).\r\n\r\n### Оператор расширения `...`\r\nОператор расширения `...`, появившийся в ES2015, предназначен для развертывания итерируемых объектов (например, массивов) в тех местах, где можно поместить несколько элементов.\r\n\r\n#### Пример кода\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // -> [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x); // -> \"a\"\r\n  console.log(y); // -> \"b\"\r\n  console.log(params); // -> [\"c\", \"d\", \"e\", \"f\"]\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // -> 1\r\nconsole.log(y); // -> 2\r\nconsole.log(z); // -> { a: 3, b: 4 }\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // -> { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n#### Объяснение\r\n\r\n##### В итерируемых объектах (например, массивах)\r\nЕсли у нас есть два следующих массива:\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // -> [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\nПервый элемент массива `arr2` — это массив, потому что `arr1` напрямую вставляется в `arr2`. Но мы хотим, чтобы `arr2` состоял только из букв. Чтобы добиться этого, мы можем *развернуть* элементы массива `arr1` в массиве `arr2`.\r\n\r\nС использованием оператора расширения:\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // -> [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n##### Оставшиеся аргументы функции\r\nДля объединения аргументов можно использовать оператор оставшихся аргументов функции. Этот оператор позволяет представить любое число аргументов в виде массива, элементы которого можно перебрать при помощи цикла. Вообще, к каждой функции уже привязан объект `arguments` — массив, состоящий из всех аргументов, переданных функции.\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\nmyFunc(\"Коля\", \"Андреев\", 10, 12, 6);\r\n// \"Коля\"\r\n// \"Андреев\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\nНо давайте представим, что мы хотим, чтобы наша функция создала нового студента со своими оценками и средним баллом. Удобнее будет записать первые два аргумента в две отдельные переменные, а все оценки поместить в массив, который можно перебирать.\r\n\r\nИменно это позволяет нам сделать оператор оставшихся аргументов!\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  /* firstName = \"Коля\"\r\n  lastName = \"Андреев\"\r\n  [10, 12, 6] — оператор `...` берет все остальные параметры, переданные функции,\r\n  и создает переменную grades с массивом, в котором они хранятся. */\r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length;\r\n  // Вычисляет средний балл из всех оценок.\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade,\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Коля\", \"Андреев\", 10, 12, 6);\r\nconsole.log(student);\r\n/* {\r\nfirstName: \"Коля\",\r\nlastName: \"Андреев\",\r\ngrades: [10, 12, 6],\r\navgGrade: 9,33\r\n} */\r\n```\r\n> **Примечание:** `createStudent` — плохая функция, потому что мы не проверяем, существует ли `grades.length` и отличается ли от 0. Но так функцию легче прочитать, поэтому я не учитывал эти случаи.\r\n\r\n##### Расширение свойств объектов\r\nЧтобы понять эту часть, рекомендую прочитать предыдущие объяснения о применении оператора оставшихся аргументов к итерируемым объектам и параметрам функций.\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // Деструктуризация объекта.\r\nconsole.log(x); // -> 1\r\nconsole.log(y); // -> 2\r\nconsole.log(z); // -> { a: 3, b: 4 }\r\n\r\n// z - это остаток от деструктурированного объекта: объект myObj минус деструктурированные свойства х и у.\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // -> { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// Здесь свойства объекта z расширяются в n\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [TC39 — Object Rest/Spread Properties for ECMAScript](https://github.com/tc39/proposal-object-rest-spread).\r\n- [Spread Operator Introduction — WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md).\r\n- [JavaScript & The spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca).\r\n- [6 Great Uses of the Spread Operator](https://davidwalsh.name/spread-operator).\r\n\r\n### Сокращенная запись свойств объектов\r\nПри записи переменной в свойство объекта, если у переменной то же имя, что и у свойства, можно сделать следующее:\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // -> 10\r\n```\r\n\r\n#### Объяснение\r\nРаньше (до ES2015), если вы хотели при объявлении нового *литерала объекта* использовать переменные в качестве его свойств, вам пришлось бы писать подобный код:\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // Запись значения переменной х в myObj.x.\r\n  y: y, // Запись значения переменной у в myObj.y.\r\n};\r\n\r\nconsole.log(myObj.x); // -> 10\r\nconsole.log(myObj.y); // -> 20\r\n```\r\nКак видите, приходится повторять одно и то же, потому что имена свойств объекта совпадают с именами переменных, которые вы хотите записать в эти свойства.\r\n\r\nС ES2015, если имя переменной совпадает с именем свойства, можно использовать такую сокращенную запись:\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y,\r\n};\r\n\r\nconsole.log(myObj.x); // -> 10\r\nconsole.log(myObj.y); // -> 20\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [Enhanced Object Properties — ES6 Features](http://es6-features.org/#PropertyShorthand).\r\n\r\n### Промисы\r\n**Промис (promise)** — это объект, который может быть синхронно возвращён из асинхронной функции ([Ссылка](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0)).\r\n\r\nПромисы могут использоваться, чтобы избежать [«ада обратных вызовов»](http://callbackhell.com/), и они всё чаще и чаще используются в современных JavaScript-проектах.\r\n\r\n#### Пример кода\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n  .done(posts => res(posts))\r\n  .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n#### Пояснение\r\nКогда вы делаете *AJAX-запрос*, ответ будет несинхронным, так как вы запрашиваете ресурс, на обработку которого требуется некоторое время. Ответ может быть вообще не получен, если запрашиваемый ресурс недоступен по какой-то причине (404).\r\n\r\nЧтобы избежать таких ситуаций, в ES2015 были добавлены *промисы*. Промисы могут иметь 3 различных состояния:\r\n- выполняется;\r\n- выполнено;\r\n- отклонено.\r\n\r\nПредположим, мы хотим использовать промисы для обработки AJAX-запроса для получения ресурса X.\r\n\r\n##### Создание промиса\r\nСначала создадим промис. Будем использовать GET-метод jQuery для создания AJAX-запроса к ресурсу X.\r\n```js\r\nconst xFetcherPromise = new Promise(\r\n// Создаём промис с помощью ключевого слова new и сохраняем его в переменную\r\n  function(resolve, reject) {\r\n    /* Конструктор промиса принимает в виде параметра функцию, которая, в свою очередь,\r\n    принимает 2 параметра: resolve и reject. */\r\n    $.get(\"X\") // Запускаем AJAX-запрос\r\n      .done(function(X) { // Как только запрос выполнен...\r\n        resolve(X); // ... выполняем промис со значением X в качестве параметра.\r\n      })\r\n      .fail(function(error) { // Если запрос не прошёл...\r\n        reject(error); // ... отклоняем промис со значением error.\r\n      });\r\n  }\r\n)\r\n```\r\nКак видно из рассмотренного примера, объект Promise принимает функцию-*исполнитель*, в свою очередь принимающую два параметра: `resolve` и `reject`. Эти параметры — функции, которые при вызове изменяют состояние промиса со значения *выполняется* на *выполнено* или *отклонено* соответственно.\r\n\r\nПромис находится в состоянии *выполняется* после создания экземпляра, и его функция-*исполнитель* выполняется немедленно. Как только одна из функций *выполнено* или *отклонено* вызвана в функции-*исполнителе*, промис вызовет связанные с ним обработчики.\r\n\r\n##### Использование обработчиков промисов\r\nЧтобы получить результат (или ошибку) промиса, нужно назначить ему обработчики следующим образом:\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err);\r\n  })\r\n```\r\nЕсли вызов прошёл успешно, вызывается `resolve` и выполняется функция, переданная в метод `.then`.\r\n\r\nЕсли вызов не прошёл, вызывается `reject` и выполняется функция, переданная в `.catch`.\r\n> **Примечание:** Если промис уже выполнен или отклонён на момент назначения соответствующего обработчика, обработчик всё равно будет вызван. Так что между выполнением асинхронной операции и назначением обработчиков не возникает состояние гонки. [(Ссылка: MDN)](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise)\r\n\r\n#### Дополнительные материалы\r\n- [JavaScript Promises for Dummies — Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies).\r\n- [JavaScript Promise API — David Walsh](https://davidwalsh.name/promises).\r\n- [Using promises — MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises).\r\n- [Master the JavaScript Interview: What is a Promise? — Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261).\r\n- [JavaScript Promises: an Introduction — Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises).\r\n- [Документация по промисам — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise).\r\n\r\n### Шаблонные строки\r\n**Шаблонные строки** — это конструкции, позволяющие использовать вставку, или [*интерполяцию выражений*](https://en.wikipedia.org/wiki/String_interpolation), в однострочных и многострочных строках.\r\n\r\nДругими словами, это новый синтаксис записи строк, с которым удобно использовать любые выражения JavaScript (например, переменные).\r\n\r\n#### Пример кода\r\n```js\r\nconst name = \"Коля\";\r\n`Привет, ${name}, следующее выражение равно четырем: ${2+2}.`;\r\n\r\n// -> Привет, Коля, следующее выражение равно четырем: 4.\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [String Interpolation — Особенности ES6](http://es6-features.org/#StringInterpolation).\r\n- [Getting Literal With ES6 Template Strings — Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings).\r\n\r\n### Тегированные шаблонные строки\r\n**Шаблонные теги** — это *функции, которые могут быть префиксом к [шаблонной строке](#Шаблонные-строки)*. Когда функция вызывается таким образом, первый параметр представляет собой массив *строк*, которые выводятся между интерполированными переменными, а последующие параметры — значения выражений, вставленных в строку. Для захвата всех этих значений используйте оператор расширения `...`. [(Ссылка: MDN)](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals).\r\n> **Примечание:** Известная библиотека, которая называется [стилизованные компоненты](https://www.styled-components.com/), основана на этой возможности.\r\n\r\nНиже приведен пример работы тегированных шаблонных строк:\r\n```js\r\nfunction highlight(strings, ...values) {\r\n  const interpolation = strings.reduce((prev, current) => {\r\n    return prev + current + (values.length ? \"<mark>\" + values.shift() + \"</mark>\" : \"\");\r\n  }, \"\");\r\n\r\n  return interpolation;\r\n}\r\n\r\nconst meal = \"круассаны\";\r\nconst drink = \"кофе\";\r\n\r\nhighlight`Я люблю ${meal} с ${drink}.`;\r\n// -> <mark>Я люблю круассаны с кофе.</mark>\r\n```\r\nБолее интересный пример:\r\n```js\r\nfunction comma(strings, ...values) {\r\n  return strings.reduce((prev, next) => {\r\n    let value = values.shift() || [];\r\n    value = value.join(\", \");\r\n    return prev + next + value;\r\n  }, \"\");\r\n}\r\n\r\nconst snacks = [\"яблоки\", \"бананы\", \"апельсины\"];\r\ncomma`Я люблю ${snacks} на десерт.`;\r\n// -> Я люблю яблоки, бананы, апельсины на десерт.\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [Tagged Template Literals — Wes Bos](http://wesbos.com/tagged-template-literals/).\r\n- [Библиотека common-tags](https://github.com/declandewet/common-tags).\r\n\r\n### Импорт / экспорт\r\nМодули в ES6 используются для получения доступа к переменным и функциям из других модулей (файлов с кодом), причем экспорт этих переменных и функций должен быть четко обозначен в исходном модуле.\r\n\r\nКрайне рекомендую почитать ресурсы MDN об экспорте/импорте (см. Дополнительные материалы ниже), в них содержится четкая и полная информация.\r\n\r\n#### Объяснение с примером кода\r\n##### Именованный экспорт\r\nИменованный экспорт используется для экспорта нескольких значений из модуля.\r\n> **Примечание:** Вы можете именовать экспорт только [объектами первого класса](https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%8A%D0%B5%D0%BA%D1%82_%D0%BF%D0%B5%D1%80%D0%B2%D0%BE%D0%B3%D0%BE_%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0), у которых есть имя.\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js';\r\n// Именованный импорт — с синтаксисом, похожим на деструктуризацию.\r\nconsole.log(pi) // -> 3.14\r\nconsole.log(exp) // -> 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js';\r\n// Все экспортированные значения записываются в переменную constants.\r\nconsole.log(constants.pi) // -> 3.14\r\nconsole.log(constants.exp) // -> 2.7\r\n```\r\nХотя именованный импорт выглядит как *деструктуризация*, это не одно и то же. Кроме того, именованный импорт имеет другой синтаксис, не поддерживает значения по умолчанию и *глубокую* деструктуризацию.\r\n\r\nКроме того, можно создавать псевдонимы, но их синтаксис будет отличаться от синтаксиса, используемого при деструктуризации:\r\n```js\r\nimport { foo as bar } from 'myFile.js';\r\n// foo импортируется и записывается в новую переменную bar.\r\n```\r\n\r\n##### Импорт / экспорт по умолчанию\r\nЧто касается экспорта по умолчанию, то для каждого модуля (файла) может быть только один экспорт. Экспортом по умолчанию может быть функция, класс, объект или что-то еще. Это значение считается «основным», поскольку его будет проще всего импортировать. [Ссылка: MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/export#Description).\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n/* В переменную number автоматически попадает экспорт по умолчанию —\r\nвне зависимости от его имени в исходном модуле. */\r\nconsole.log(number) // -> 42\r\n```\r\nЭкспорт функций:\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // -> 3\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [ES6 Modules in bulletpoints](https://ponyfoo.com/articles/es6#modules)\r\n- [Экспорт — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/export).\r\n- [Импорт — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/import).\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/).\r\n- [Destructuring special case — import statements](https://ponyfoo.com/articles/es6-destructuring-in-depth#special-case-import-statements).\r\n- [Misunderstanding ES6 Modules — Kent C. Dodds](https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0).\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript).\r\n\r\n### <a name=\"this_def\"></a> `this` в JavaScript\r\nОператор `this` в JavaScript ведет себя не так, как в других языках. В большинстве случаев он определяется тем, как вызвана функция ([Ссылка: MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/this)).\r\n\r\nЭто сложное понятие с множеством тонкостей, так что я крайне рекомендую вам тщательно изучить приведенные ниже Дополнительные материалы. Я покажу вам, как сам лично определяю, чему равно `this`. Этому меня научила [вот эта статья Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/).\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// После каждого выражения находим значение this в myFunc.\r\n\r\nmyFunc.call(\"myString\", \"привет\");\r\n// myString — в this записывается значение первого параметра .call.\r\n\r\n// В non-strict-режиме.\r\nmyFunc(\"привет\");\r\n// window — myFunc() — это синтаксический сахар для myFunc.call(window, \"привет\").\r\n\r\n// В strict-режиме.\r\nmyFunc(\"привет\");\r\n// undefined — myFunc() — это синтаксический сахар для myFunc.call(undefined, \"привет\").\r\n```\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\");\r\n// person Object — в this записывается значение первого параметра call.\r\nperson.myFunc(\"test\");\r\n// person Object — person.myFunc() — это синтаксический сахар для person.myFunc.call(person, \"test\").\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"привет\");\r\n// Создает новую функцию, в которой мы записываем \"привет\" в значение this.\r\nperson.myFunc(\"test\");\r\n// person Object — Метод bind не влияет на первоначальный метод.\r\nmyBoundFunc(\"test\");\r\n// \"hello\" — myBoundFunc — это person.myFunc, в которой this привязана к \"привет\".\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [Understanding JavaScript Function Invocation and \"this\" — Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/).\r\n- [`this` в JavaScript — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/this).\r\n\r\n### Класс\r\nJavaScript — это язык, [основанный на прототипах](https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%82%D0%BE%D1%82%D0%B8%D0%BF%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) (в то время как, например, Java — язык, [основанный на классах](https://en.wikipedia.org/wiki/Class-based_programming)). В обновлении ES6 представлены классы JavaScript, которые являются синтаксическим сахаром для наследования на основе прототипов, а **не** новой моделью наследования на основе классов ([Ссылка](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes)).\r\n\r\nЕсли вы знакомы с классами в других языках, слово «класс» может ввести вас в заблуждение. Постарайтесь не делать предположений о работе классов в JavaScript на основе других языков. Считайте это совершенно другим понятием.\r\n\r\nПоскольку этот документ не является попыткой научить вас языку с нуля, я надеюсь, что вы знаете, что такое прототипы и как они себя ведут. Если нет, смотрите дополнительные материалы после примеров.\r\n\r\n#### Примеры\r\nДо ES6, синтаксис на основе прототипов:\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n};\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Привет, меня зовут \" + this.name + \" и мне \" + this.age;\r\n};\r\n```\r\nНачиная с ES6, синтаксис на основе классов:\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return `Привет, меня зовут ${this.name} и мне ${this.age}`;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Маша\", 23);\r\nconsole.log(myPerson.age); // -> 23\r\nconsole.log(myPerson.stringSentence()); // -> \"Привет, меня зовут Маша и мне 23\r\n```\r\n\r\n#### Дополнительные материалы\r\nДля понимания прототипов:\r\n- [Understanding Prototypes in JS — Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes — Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Наследование и цепочка прототипов — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).\r\n\r\nДля понимания классов:\r\n- [ES6 Classes in Depth — Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features — Classes](http://es6-features.org/#ClassDefinition)\r\n- [Классы JavaScript — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes).\r\n\r\n### Ключевые слова `Extends` и `super`\r\n\r\nКлючевое слово `extends` используется в объявлении класса или в выражениях класса для создания дочернего класса ([Ссылка: MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes/extends)). Дочерний класс наследует все свойства родительского класса и дополнительно может добавлять новые свойства или изменять унаследованные.\r\n\r\nКлючевое слово `super` используется для вызова функций родителя объекта, включая его конструктор.\r\n\r\n- В конструкторе ключевое слово `super` должно использоваться раньше, чем ключевое слово `this`.\r\n- Вызов `super()` вызывает конструктор родительского класса. Если вы хотите передать какие-то аргументы из конструктора класса в конструктор родительского класса, то нужно вызывать функцию следующим образом: `super(arguments)`.\r\n- Если у родительского класса есть метод `X` (даже статический), для его вызова в дочернем классе можно использовать `super.X()`.\r\n\r\n#### Пример кода\r\n\r\n```js\r\nclass Polygon {\r\n  constructor(height, width) {\r\n    this.name = 'Многоугольник';\r\n    this.height = height;\r\n    this.width = width;\r\n  }\r\n\r\n  getHelloPhrase() {\r\n    return `Привет, я — ${this.name}`;\r\n  }\r\n}\r\n\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    /* Здесь вызывается конструктор родительского класса со значением length,\r\n    передаваемым для переменных width и height класса Polygon. */\r\n\r\n    super(length, length);\r\n    /* Примечание: в производных классах перед тем, как использовать 'this',\r\n    нужно вызвать функцию super(), иначе это приведёт к ошибке. */\r\n\r\n    this.name = 'Квадрат';\r\n    this.length = length;\r\n  }\r\n\r\n  getCustomHelloPhrase() {\r\n    const polygonPhrase = super.getHelloPhrase();\r\n    // Получение доступа к родительскому методу с помощью синтаксиса super.X().\r\n    return `${polygonPhrase} с длиной стороны ${this.length}`;\r\n  }\r\n\r\n  get area() {\r\n    return this.height * this.width;\r\n  }\r\n}\r\n\r\nconst mySquare = new Square(10);\r\nconsole.log(mySquare.area) // -> 100\r\nconsole.log(mySquare.getHelloPhrase())\r\n/* -> 'Привет, я — Квадрат'\r\nКласс Square наследуется от класса Polygon и имеет доступ к его методам.*/\r\nconsole.log(mySquare.getCustomHelloPhrase())\r\n// -> 'Привет, я — Квадрат с длиной стороны'\r\n```\r\n\r\n> **Примечание**: Если бы мы попытались использовать `this` перед вызовом `super()` в классе Square, произошёл бы ReferenceError:\r\n\r\n```js\r\nclass Square extends Polygon {\r\n  constructor(length) {\r\n    this.height;\r\n    // ReferenceError, сначала нужно вызывать super!\r\n\r\n    /* Здесь вызывается конструктор родительского класса со значением length\r\n    в качестве значений width и height класса Polygon. */\r\n    // Here, it calls the parent class' constructor with lengths\r\n    super(length, length);\r\n\r\n    /* Примечание: в производных класса super() должен быть вызван до использования 'this'.\r\n    Иначе это приведёт к ошибке. */\r\n    this.name = 'Квадрат';\r\n  }\r\n}\r\n```\r\n\r\n#### Дополнительные материалы\r\n\r\n- [Extends — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes/extends).\r\n- [Оператор Super — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/super).\r\n- [Inheritance — MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance).\r\n\r\n### Async Await\r\nПомимо [Промисов](#Промисы) вам может встретиться еще один синтаксис для обработки асинхронного кода — `async`/`await`.\r\n\r\nЦель функций `async`/`await` — упростить синхронное использование промисов и выполнить какое-либо действие над группой промисов. Точно так же, как промисы похожи на структурированные функции обратного вызова, `async`/`await` похожи на комбинацию генераторов и промисов. ([Ссылка: MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/async_function))\r\n> **Примечание:** перед тем как пытаться понять `async`/`await`, вы должны понимать, что такое промисы и как они работают, поскольку `async`/`await` основаны на промисах.\r\n\r\n> **Примечание 2:** [`await` должен использоваться в `async` функции](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0), что означает, что вы не можете использовать `await` на верхнем уровне вашего кода, так как он не находится внутри async-функции.\r\n\r\n#### Пример кода\r\n```js\r\nasync function getGithubUser(username) {\r\n  // Ключевое слово async позволяет использовать await в функции и означает, что функция возвращает промис.\r\n  const response = await fetch(`https://api.github.com/users/${username}`);\r\n  // «Синхронное» ожидание промиса перед переходом на новую строку.\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  /* Логирование пользователя — не может использовать синтаксис await,\r\n  так как этот код не находится внутри async-функции. */\r\n  .catch(err => console.log(err));\r\n  // Если в нашей асинхронной функции возникнет ошибка, то мы перехватим ее здесь.\r\n```\r\n\r\n#### Объяснение с помощью примера кода\r\n`async`/`await` построены на промисах, но позволяют использовать более императивный стиль кода.\r\n\r\nОператор `async` объявляет функцию как асинхронную, и данная функция всегда будет возвращать *промис*. В async-функции можно использовать оператор `await` для приостановки выполнения до тех пор, пока возвращаемый промис либо выполнится, либо будет отклонен.\r\n```js\r\nasync function myFunc() {\r\n  // Можно использовать оператор await, так как это async-функция.\r\n  return \"hello world\";\r\n}\r\n\r\nmyFunc().then(msg => console.log(msg));\r\n// \"Привет, мир!\" — возвращаемое значение myFunc превращается в промис из-за оператора async.\r\n```\r\nКогда будет достигнут оператор `return` async-функции, промис выполняется с возвращаемым значением. Если внутри async-функции генерируется ошибка, состояние промиса изменится на `rejected`. Если async-функция не возвращает никакого значения, промис всё равно будет возвращен и выполнится без значения, когда выполнение async-функции будет завершено.\r\n\r\nОператор `await` используется для ожидания выполнения *Промиса* и может быть использован только в теле async-функции. При этом выполнение кода приостанавливается, пока не будет выполнен промис.\r\n> **Примечание:** `fetch` — это функция, возвращающая промис, который позволяет выполнить AJAX-запрос.\r\n\r\nДавайте сначала посмотрим, как мы можем получить пользователя github с помощью промисов:\r\n```js\r\nfunction getGithubUser(username) {\r\n  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\nВот эквивалент с использованием  `async`/`await`:\r\n```js\r\nasync function getGithubUser(username) {\r\n  // Превращение в промис + разрешено использование ключевого слова await.\r\n  const response = await fetch(`https://api.github.com/users/${username}`);\r\n  // Выполнение останавливается здесь, пока не закончится выполнение промиса.\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\nСинтаксис `async`/`await` особенно удобен для построения цепочек взаимозависимых промисов.\r\n\r\nНапример, вам нужно получить токен для того, чтобы получить публикацию в блоге из базы данных, а затем информацию об авторе.\r\n> **Примечание:** Выражение `await` должно быть заключено в круглые скобки для вызова методов и свойств разрешенных значений в одной строке.\r\n\r\n```js\r\nasync function fetchPostById(postId) {\r\n  const token = (await fetch('token_url')).json().token;\r\n  const post = (await fetch(`/posts/${postId}?token=${token}`)).json();\r\n  const author = (await fetch(`/users/${post.authorId}`)).json();\r\n\r\n  post.author = author;\r\n  return post;\r\n}\r\n\r\nfetchPostById('gzIrzeo64')\r\n  .then(post => console.log(post))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n##### Обработка ошибок\r\nЕсли мы не добавим блок `try` / `catch` вокруг выражения `await`, неперехваченные исключения — неважно, были ли они выброшены в теле вашей async-функции или во время ожидания выполнения `await` — отклонят промис, возвращенный из async-функции. Использование состояния `throw` в асинхронной функции — то же самое, что возврат промиса, который был отклонен. [(Ссылка: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).\r\n> **Примечание:** Промисы ведут себя так же!\r\n\r\nС помощью промисов вот как бы мы обработали ошибки:\r\n```js\r\nfunction getUser() { // Этот промис будет отклонен!\r\n  return new Promise((res, rej) => rej(\"Пользователь не найден!\"));\r\n}\r\n\r\nfunction getAvatarByUsername(userId) {\r\n  return getUser(userId).then(user => user.avatar);\r\n}\r\n\r\nfunction getUserAvatar(username) {\r\n  return getAvatarByUsername(username).then(avatar => ({ username, avatar }));\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // -> \"Пользователь не найден!\"\r\n```\r\nЭквивалент с использованием `async`/`await`:\r\n```js\r\nasync function getUser() {\r\n  // Возвращенный промис будет отклонен!\r\n  throw \"User not found !\";\r\n}\r\n\r\nasync function getAvatarByUsername(userId) => {\r\n  const user = await getUser(userId);\r\n  return user.avatar;\r\n}\r\n\r\nasync function getUserAvatar(username) {\r\n  var avatar = await getAvatarByUsername(username);\r\n  return { username, avatar };\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // -> \"Пользователь не найден!\"\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [Async/Await — JavaScript.Info](https://javascript.info/async-await).\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/).\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9).\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits).\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016).\r\n- [Функция Async](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/async_function).\r\n- [Await](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/await).\r\n- [Using async / await in express with node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016).\r\n\r\n### Истина / Ложь\r\nВ JavaScript «истинность» или «ложность» значения определяется при вычислении этого значения в булевом контексте. Примером булева контекста может быть вычисление в условии `if`.\r\n\r\nЛюбое значение будет приведено к `true` (истина), кроме:\r\n- `false` (ложь);\r\n- `0`;\r\n- `\"\"` (пустая строка);\r\n- `null`;\r\n- `undefined`;\r\n- `NaN`.\r\n\r\nВот примеры *булева контекста*:\r\n- значение условия `if`.\r\n```js\r\nif (myVar) {}\r\n```\r\n\r\nЗначение `myVar` может быть любым [объектом первого класса](https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%8A%D0%B5%D0%BA%D1%82_%D0%BF%D0%B5%D1%80%D0%B2%D0%BE%D0%B3%D0%BE_%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0) (переменная, функция, логическое значение), но оно будет преобразовано в логическое значение, поскольку вычисляется в булевом контексте.\r\n\r\n- После логического оператора **NOT** `!`.\r\n\r\nЭтот оператор возвращает значение «ложь», если его единственный операнд может быть преобразован к значению «истина»; иначе он возвращает значение «истина».\r\n```js\r\n!0 // -> «истина»: 0 — это «ложь», поэтому вернется \"истина\".\r\n!!0 // -> «ложь»: 0 — это «ложь», следовательно !0 возвращает истину, а !(!0) возвращает «ложь».\r\n!!\"\" // -> «ложь»: пустая строка — «ложь», поэтому НЕ (НЕ «ложь») равно «ложь».\r\n```\r\n- Конструктор объектов типа `Boolean`.\r\n\r\n```js\r\nnew Boolean(0); // «ложь»\r\nnew Boolean(1); // «истина»\r\n```\r\n- Тернарный оператор.\r\n\r\n```js\r\nmyVar ? \"истина\" : \"ложь\"\r\n```\r\n\r\nЗначение `myVar` вычисляется в булевом контексте.\r\n\r\nБудьте внимательны при сравнении двух значений. Значения объектов (которые должны быть приведены к истине), **не** приводятся к булеву типу, а приводятся к примитивному типу в соответствии со [спецификацией](http://javascript.info/object-toprimitive). Внутри, когда объект сравнивается с булевым значением, например, `[] == true`, выполняется `[].toString() == true`, происходит следующее:\r\n\r\n```js\r\nlet a = [] == true // a ложно, так как [].toString() возвращает пустую строку (\"\").\r\nlet b = [1] == true // b истинно, так как [1].toString() возвращает \"1\".\r\nlet c = [2] == true // c ложно, так как [2].toString() возвращает \"2\".\r\n```\r\n\r\n#### Дополнительные материалы\r\n\r\n- [Truthy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).\r\n- [Falsy (MDN)](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).\r\n- [Truthy and Falsy values in JS — Josh Clanton](http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html).\r\n\r\n### Анаморфизмы и катаморфизмы\r\n\r\n#### Анаморфизмы\r\n\r\nАнаморфизмы — это фунции, которые отображают некоторый объект на более сложную структуру, содержащую тип объекта. Это процесс *разворачивания* простой структуры в более сложную.\r\n\r\nРассмотрим разворачивание целого числа в список целых чисел. Целое число — наш изначальный объект, а список целых чисел — более сложная структура.\r\n\r\n##### Пример кода\r\n\r\n```js\r\nfunction downToOne(n) {\r\n  const list = [];\r\n\r\n  for (let i = n; i > 0; --i) {\r\n    list.push(i);\r\n  }\r\n\r\n  return list;\r\n}\r\n\r\ndownToOne(5)\r\n  //-> [ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\n#### Катаморфизмы\r\n\r\nКатаморфизмы противоположны анаморфизмам: они берут объекты более сложной структуры и *складывают* их в более простые структуры.\r\n\r\nРассмотрим следующий пример функции `product`, которая принимает список целых чисел и возвращает простое целое число.\r\n\r\n##### Пример кода\r\n\r\n```js\r\nfunction product(list) {\r\n  let product = 1;\r\n\r\n  for (const n of list) {\r\n    product = product * n;\r\n  }\r\n\r\n  return product;\r\n}\r\n\r\nproduct(downToOne(5)) // -> 120\r\n```\r\n\r\n#### Дополнительные материалы\r\n\r\n- [Anamorphisms in JavaScript](http://raganwald.com/2016/11/30/anamorphisms-in-javascript.html).\r\n- [Anamorphism](https://en.wikipedia.org/wiki/Anamorphism).\r\n- [Catamorphism](https://en.wikipedia.org/wiki/Catamorphism).\r\n\r\n### Генераторы\r\n\r\nДругой способ написания функции `downToOne` — использование генератора. Чтобы создать объект типа `Generator`, нужно использовать объявление `function *`. Генераторы — это функции, выполнение которых может быть прервано, а затем продолжено с тем же контекстом (привязками переменных), сохраняющимся при всех вызовах.\r\n\r\nНапример, функция `downToOne` может быть переписана следующим образом:\r\n\r\n```js\r\nfunction * downToOne(n) {\r\n  for (let i = n; i > 0; --i) {\r\n    yield i;\r\n  }\r\n}\r\n\r\n[...downToOne(5)] // -> [ 5, 4, 3, 2, 1 ]\r\n```\r\n\r\nГенераторы возвращают итерируемый объект. Когда вызывается метод `next()` итератор, она выполняется до первого выражения `yield`, которое указывает значение, которое должно быть возвращено из итератора или с помощью `yield*`, которое дегегирует выполнение другому генератору. Когда в генераторе вызывается выражение `return`, он будет помечать генератор как выполненный и возвращать значение из выражения `return`. Дальнейшие вызовы `next()` не будут возвращать никаких новых значений.\r\n\r\n#### Пример кода\r\n\r\n```js\r\n// Пример использования\r\nfunction * idMaker() {\r\n  var index = 0;\r\n  while (index < 2) {\r\n    yield index;\r\n    index = index + 1;\r\n  }\r\n}\r\n\r\nvar gen = idMaker();\r\n\r\ngen.next().value; // -> 0\r\ngen.next().value; // -> 1\r\ngen.next().value; // -> undefined\r\n```\r\n\r\nВыражение `yield*` позволяет генератору вызывать другую функцию-генератор во время итерации.\r\n\r\n```js\r\n// Пример использования yield *\r\nfunction * genB(i) {\r\n  yield i + 1;\r\n  yield i + 2;\r\n  yield i + 3;\r\n}\r\n\r\nfunction * genA(i) {\r\n  yield i;\r\n  yield* genB(i);\r\n  yield i + 10;\r\n}\r\n\r\nvar gen = genA(10);\r\n\r\ngen.next().value; // -> 10\r\ngen.next().value; // -> 11\r\ngen.next().value; // -> 12\r\ngen.next().value; // -> 13\r\ngen.next().value; // -> 20\r\n```\r\n\r\n```js\r\n// Пример возврата из генератора\r\nfunction* yieldAndReturn() {\r\n  yield \"Y\";\r\n  return \"R\";\r\n  yield \"unreachable\";\r\n}\r\n\r\nvar gen = yieldAndReturn()\r\ngen.next(); // -> { value: \"Y\", done: false }\r\ngen.next(); // -> { value: \"R\", done: true }\r\ngen.next(); // -> { value: undefined, done: true }\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [Итераторы и генераторы — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Guide/Iterators_and_Generators#%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D1%82%D0%BE%D1%80%D1%8B).\r\n\r\n### Статические методы\r\n\r\n#### Краткое объяснение\r\nКлючевое слово `static` используется в классах для объявления статических методов. Статические методы — это функции в классе, которые принадлежат объекту класса и недоступны никаким экземплярам этого класса.\r\n\r\n#### Пример кода\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\";\r\n  }\r\n}\r\n\r\n// Обратите внимание, что нам не пришлось создавать экземпляр класса Repo.\r\nconsole.log(Repo.getName()); // Repo name is modern-js-cheatsheet\r\n\r\nlet r = new Repo();\r\nconsole.log(r.getName()); // Не пойманный TypeError: repo.getName не является функцией.\r\n```\r\n\r\n#### Подробное объяснение\r\nСтатические методы можно вызвать в другом статическом методе, используя ключевое слово `this`, однако это не работает для нестатических методов. Нестатические методы не могут напрямую обращаться к статическим методам, используя ключевое слово `this`.\r\n\r\n##### Вызов статических методов из статического метода.\r\nДля вызова статического метода из другого статического метода можно использовать ключевое слово `this` следующим образом:\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\";\r\n  }\r\n\r\n  static modifyName(){\r\n    return `${this.getName()}-added-this`;\r\n  }\r\n}\r\n\r\nconsole.log(Repo.modifyName()); // Repo name is modern-js-cheatsheet-added-this\r\n```\r\n\r\n##### Вызов статических методов из нестатических методов\r\nНестатические методы могут вызывать статические двумя способами:\r\n\r\n1. Используя имя класса.\r\n\r\nЧтобы получить доступ к статическому методы из нестатического, используем имя класса и вызываем статический метод как обычное свойство, например, `ClassName.StaticMethodName`:\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    return `${Repo.getName()} and it contains some really important stuff`;\r\n  }\r\n}\r\n\r\n// Нужно создать экземпляр класса для использования нестатических методов.\r\nlet r = new Repo();\r\nconsole.log(r.useName()); // Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n2. Используя конструктор.\r\n\r\nСтатические методы можно вызвать как свойства объекта-конструктора класса.\r\n```js\r\nclass Repo {\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\nuseName(){\r\n// Вызывает статический метод как обычное свойство конструктора.\r\n  return `${this.constructor.getName()} and it contains some really important stuff`;\r\n  }\r\n}\r\n\r\n// Нужно создать экземпляр класса для использования нестатических функций.\r\nlet r = new Repo();\r\nconsole.log(r.useName()); // Repo name is modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n#### Дополнительные материалы\r\n- [Ключевое слово static — MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes/static).\r\n- [Static Methods- Javascript.info](https://javascript.info/class#static-methods).\r\n- [Static Members in ES6 — OdeToCode](http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx).\r\n\r\n## Глоссарий\r\n\r\n### <a name=\"scope_def\"></a> Область видимости\r\nКонтекст, в котором переменная и выражения являются «видимыми» или могут быть получены. Если переменная или выражение находятся «вне текущей области видимости», значит, их нельзя использовать.\r\n\r\nИсточник: [MDN](https://developer.mozilla.org/ru/docs/Glossary/Scope)\r\n\r\n### <a name=\"mutation_def\"></a> Изменение переменных\r\nГоворят, что переменная изменилась, когда её значение изменилось относительно начального.\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // Значение myArray изменено.\r\n```\r\nПеременная называется *неизменяемой*, если она не может быть изменена.\r\n\r\nБолее подробно [смотрите в статье на MDN](https://developer.mozilla.org/ru/docs/Glossary/Mutable).\r\n"
  },
  {
    "path": "JavaScript/translations/th-TH.md",
    "content": "# Modern JavaScript Cheatsheet\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>เครดิตรูปภาพ: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## เกริ่นนำ\r\n\r\n### จุดประสงค์\r\n\r\nเอกสารนี้เป็น cheatsheet ชุดคำสั่งของภาษา JavaScript ที่คุณได้พบเจอเป็นประจำใน​โปรเจ็คและโค้ดตัวอย่างใหม่ๆ\r\n\r\nบทความนี้ไม่ได้มีจุดประสงค์ในการสอน Javascript ตั้งแต่พื้นฐาน แต่ต้องการจะช่วยให้ Developer ที่มีพื้นฐานอยู่แล้วแต่อาจจะติดปัญหาในการเข้าใจในโค้ด Javascript สมัยใหม่ (ยกตัวอย่างเช่นกำลังเรียนรู้ React อยู่) เนื่องจากมีการใช้ concept ของ Javascript สมัยใหม่\r\n\r\nนอกจากนี้ผมจะแนะนำเคล็ดลับส่วนตัว(ซึ่งอาจจะมีบางคนไม่เห็นด้วย)ใส่ไว้ในบางส่วน โดยจะมีหมายเหตุบอกเอาไว้\r\n\r\n> **หมายเหตุ:** คอนเซปส่วนใหญ่ในนี้จะมาจากการอัปเดตใหม่ๆของ JavaScript (ES2015, หรือโดยทั่วไปเรียกว่า ES6). คุณสามารถดูฟีเจอร์ใหม่ๆของ Javascript ที่เพิ่มเข้ามาโดยสามารถติดตามได้จาก [ที่นี่](http://es6-features.org); ซึ่งเป็นเว็บไซต์ที่ดีทีเดียว\r\n\r\n### แหล่งเรียนรู้ฟรีที่แนะนำเพิ่มเติม\r\n\r\nเมื่อติดปัญหาในการเข้าใจตรงจุดไหนแนะนำให้ลองหาคำตอบจากแหล่งข้อมูลเพิ่มเติมเหล่านี้ดูก่อน:\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/en-US/search?q=)\r\n- [You don't know JS (book)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Features with examples](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Javascript Basics for Beginners](https://www.udacity.com/course/javascript-basics--ud804) - คอร์สฟรีจาก Udacity\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) to find specific blog and resources\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript)\r\n\r\n## สารบัญ\r\n\r\n- [Modern JavaScript cheatsheet](#modern-javascript-cheatsheet)\r\n  * [เกริ่นนำ](#เกริ่นนำ)\r\n    + [จุดประสงค์](#จุดประสงค์)\r\n    + [แหล่งเรียนรู้ฟรีที่แนะนำเพิ่มเติม](#แหล่งเรียนรู้ฟรีที่แนะนำเพิ่มเติม)\r\n  * [สารบัญ](#สารบัญ)\r\n  * [เนื้อหา](#เนื้อหา)\r\n    + [การประกาศตัวแปร: var, const, let](#การประกาศตัวแปร-var-const-let)\r\n      - [อธิบายสั้นๆ](#อธิบายสั้นๆ)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด)\r\n      - [อธิบายรายละเอียด](#อธิบายรายละเอียด)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก)\r\n    + [Arrow ฟังก์ชั่น](#-arrow-ฟังก์ชั่น)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-1)\r\n      - [อธิบายรายละเอียด](#อธิบายรายละเอียด-1)\r\n        * [การย่อสั้น](#การย่อสั้น)\r\n        * [การอ้างอิงของ *this*](#การอ้างอิงของ-this)\r\n      - [แหล่งข้อมูลที่มีประโยชน์](#แหล่งข้อมูลที่มีประโยชน์)\r\n    + [ค่า default parameter ของฟังก์ชั่น](#ค่า-default-parameter-ของฟังก์ชั่น)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-1)\r\n    + [Destructuring objects และ arrays](#destructuring-objects-และ-arrays)\r\n      - [อธิบายตัวอย่างโค้ด](#อธิบายตัวอย่างโค้ด)\r\n      - [แหล่งข้อมูลที่มีประโยชน์](#แหล่งข้อมูลที่มีประโยชน์-1)\r\n    + [Array methods - map / filter / reduce](#array-methods---map--filter--reduce)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-2)\r\n      - [อธิบาย](#อธิบาย)\r\n        * [Array.prototype.map()](#arrayprototypemap)\r\n        * [Array.prototype.filter()](#arrayprototypefilter)\r\n        * [Array.prototype.reduce()](#arrayprototypereduce)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-2)\r\n    + [Spread operator \"...\"](#spread-operator-)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-3)\r\n      - [อธิบาย](#อธิบาย-1)\r\n        * [ใช้กับสิ่งที่สามารถวนลูปได้ (iterables) (แบบ arrays)](#ใช้กับสิ่งที่สามารถวนลูปได้-iterables-แบบ-arrays)\r\n        * [Rest parameter ของฟังก์ชั่น](#rest-parameter-ของฟังก์ชั่น)\r\n        * [Object properties spreading](#object-properties-spreading)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก)\r\n    + [Object property shorthand](#object-property-shorthand)\r\n      - [อธิบาย](#อธิบาย-2)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-1)\r\n    + [Promises](#promises)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-4)\r\n      - [อธิบาย](#อธิบาย-3)\r\n        * [การสร้าง Promise](#create-the-promise)\r\n        * [การใช้งาน Promise handlers](#การใช้งาน-promise-handlers)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-2)\r\n    + [Template literals](#template-literals)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-5)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-3)\r\n    + [Tagged Template Literals](#tagged-template-literals)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-4)\r\n    + [Imports / Exports](#imports--exports)\r\n      - [อธิบายตัวอย่างโค้ด](#อธิบายตัวอย่างโค้ด-1)\r\n        * [Named exports](#named-exports)\r\n        * [Default import / export](#default-import--export)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-5)\r\n    + [JavaScript *this*](#-javascript-this)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-6)\r\n    + [Class](#class)\r\n      - [ตัวอย่าง](#samples)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-7)\r\n    + [Async Await](#async-await)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-6)\r\n      - [อธิบายตัวอย่างโค้ด](#อธิบายตัวอย่างโค้ด-2)\r\n      - [การจัดการกับ Error](#การจัดการกับ-error)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-8)\r\n    + [Truthy / Falsy](#truthy--falsy)\r\n    + [Static Methods](#static-methods)\r\n      - [อธิบายสั้นๆ](#อธิบายสั้นๆ-1)\r\n      - [ตัวอย่างโค้ด](#ตัวอย่างโค้ด-7)\r\n      - [อธิบายรายละเอียด](#อธิบายรายละเอียด-2)\r\n        * [เรียก static methods อื่นจาก static method](#เรียก-static-methods-อื่นจาก-static-method)\r\n        * [เรียก static methods จาก non-static method](#เรียก-static-methods-จาก-non-static-method)\r\n      - [ข้อมูลเพิ่มเติมจากภายนอก](#ข้อมูลเพิ่มเติมจากภายนอก-9)\r\n  * [คำศัพธ์](#คำศัพธ์)\r\n    + [Scope](#-scope)\r\n    + [Variable mutation](#-variable-mutation)\r\n\r\n## เนื้อหา\r\n\r\n### การประกาศตัวแปร: var, const, let\r\n\r\nใน JavaScript มีวิธีการประกาศตัวแปรได้ 3 แบบคือ ```var```, ```let``` และ ```const``` ซึ่งแต่ละแบบมีความแตกต่างกัน\r\n\r\n#### อธิบายสั้นๆ\r\n\r\nตัวแปรที่ประกาศโดยใช้ ```const``` จะไม่สามารถถูก assign ค่าให้กับตัวแปรใหม่ได้ ในขณะที่ ```let``` กับ ```var``` สามารถทำได้\r\n\r\nผมแนะนำให้ประกาศตัวแปรด้วย ```const``` เสมอและค่อยเปลี่ยนเป็น ```let``` ถ้าคุณต้องการ*เปลี่ยนแปลงค่า (mutate)* หรือ assign ค่าให้ตัวแปรในภายหลัง\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>Scope</th>\r\n    <th>สามารถ Assign ค่าใหม่ได้</th>\r\n    <th>สามารถเปลี่ยนแปลงค่าได้</th>\r\n   <th><a href=\"#tdz_sample\">Temporal Dead Zone</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>const</th>\r\n    <td>Block</td>\r\n    <td>ไม่ใช่</td>\r\n    <td><a href=\"#const_mutable_sample\">ใช่</a></td>\r\n    <td>ใช่</td>\r\n  </tr>\r\n  <tr>\r\n    <th>let</th>\r\n    <td>Block</td>\r\n    <td>ใช่</td>\r\n    <td>ใช่</td>\r\n    <td>ใช่</td>\r\n  </tr>\r\n   <tr>\r\n    <th>var</th>\r\n    <td>Function</td>\r\n    <td>ใช่</td>\r\n    <td>ใช่</td>\r\n    <td>ไม่ใช่</td>\r\n  </tr>\r\n</table>\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // จะ thrown error เพราะว่า person ไม่สามารถ assign ค่าใหม่ได้\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", let จะยอมให้สามารถ assign ค่าใหม่ได้\r\n```\r\n\r\n#### อธิบายรายละเอียด\r\n\r\nอธิบาย [*scope*](#scope_def) ของตัวแปรได้อย่างคร่าวๆ หมายถึง \"ขอบเขตที่ตัวแปรสามารถใช้งานได้ภายในโค้ด\"\r\n\r\n##### var\r\n\r\nตัวแปรที่ถูกประกาศด้วย ```var``` จะเป็น *function scoped* เมื่อตัวแปรถูกสร้างภายใน function โค้ดใน function นั้นสามารถเข้าถึงตัวแปรนั้นได้ และตัวแปร *function scoped* ที่ถูกสร้างใน function จะไม่สามารถถูกเข้าถึงจากภายนอก function ได้\r\n\r\nแนะนำให้ลองจินตนาการดูว่าถ้าตัวแปรเป็นตัวแปร *X scoped* หมายความว่าตัวแปรนี้เป็น property ของ X เท่านั้น\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar จะสามารถเข้าถึงได้จากภายใน function\r\n}\r\nconsole.log(myVar); // จะเกิด ReferenceError เพราะ myVar ไม่สามารถเข้าถึงได้จากภายนอก function\r\n```\r\n\r\nตัวอย่างเพิ่มเติมสำหรับเรื่อง scope ของตัวแปร\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // จริงๆ แล้ว myvar เป็นตัวแปร function scoped เราแค่ได้ลบค่าตัวแปร myVar จาก \"Nick\" และเปลี่ยนเป็น \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - จะเห็นได้ว่าค่าได้ถูกเปลี่ยนไปแล้ว\r\n}\r\nconsole.log(myVar); // จะเกิด ReferenceError เพราะ myVar ไม่สามารถเข้าถึงได้จากภายนอก function\r\n```\r\n\r\nนอกจากนี้ตัวแปรที่ประกาสด้วย *var* จะถูกย้ายตอน execution ไปอยู่ด้านบนสุดของ scope และนี่คือสิ่งที่เราเรียกว่า [var hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting).\r\n\r\nโค้ดตัวอย่างกรณีนี้:\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- ไม่มีการเกิด error\r\nvar myVar = 2;\r\n```\r\n\r\nเพราะว่าตามความเข้าใจเวลา Execution จะเป็นแบบนี้:\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- ไม่มีการเกิด error\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n```var``` และ ```let ``` จะคล้ายกันแต่ตัวแปรที่ประกาศด้วย ```let``` จะ\r\n\r\n- เป็น *block scoped*\r\n- จะ**ไม่สามารถ**เข้าถึงก่อนที่มันจะถูก assign ค่าได้\r\n- ไม่สามารถประกาศตัวแปรซ้ำใน scope เดียวกันได้\r\n\r\nลองดูตัวอย่างเรื่องผลกระทบ (side effect) ของ block-scoping จากตัวอย่างก่อนหน้า\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // จริงๆ แล้ว myVar เป็น block scoped เราสามารถสร้างตัวแปร myVar ใหม่ได้\r\n    // ตัวแปรนี้จะไม่สามารถเข้าถึงได้จากภายนอก block นี้และเป็นอิสระจากกัน\r\n    // กับตัวแปร myVar ตัวแรกที่เราสร้าง !\r\n  }\r\n  console.log(myVar); // \"Nick\", จะเห็นตามที่อธิบายข้างต้นว่าภายใน block ไม่ส่งผลกระทบกับค่านี้\r\n}\r\nconsole.log(myVar); // จะเกิด ReferenceError เพราะ myVar จะไม่สามารถเข้าถึงได้จากภายนอก function\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> ตอนนี้น่าจะเข้าใจเหตุผลแล้วว่าทำไมตัวแปรที่ประกาศโดยใช้ *let* (และ *const*) ไม่สามารถเข้าถึงได้ก่อนจะถูก assign ค่า\r\n\r\n```js\r\nconsole.log(myVar) // เกิด ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\nสิ่งนี้จะแตกต่างกับตัวแปรที่ประกาศโดยใช้ *var* ถ้าเราพยายามที่จะอ่านหรือเขียนตัวแปรที่ประกาศโดย *let* หรือ *const* ก่อนที่ทำการ assign ค่าจะเกิด Error ทันที ปรากฏการณ์นี้มักถูกเรียกว่า [*Temporal dead zone*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) หรือ *TDZ*.\r\n\r\n> **หมายเหตุ:** ในทางเทคนิคแล้ว การประกาศตัวแปร *let* กับ *const* เป็น hoisted เหมือนกัน, แต่ไม่ใช่กับการ assign ค่า ดังนั้นเมื่อมันไม่สามารถใช้งานได้ก่อน assign ค่าได้ทำให้ดูเหมือนว่าไม่มี hoisting แต่จริงๆ แล้วมันมี อ่าน[คำอธิบายเพิ่มเติมแบบละเอียดที่นี่](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified) ถ้าคุณต้องการ\r\n\r\nเพิ่มเติม คุณไม่สามารถประกาศตัวแปรที่ประกาศด้วย *let* ซ้ำได้:\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // เกิด SyntaxError\r\n```\r\n\r\n##### const\r\n\r\nการประกาศตัวแปรโดยใช้ ```const``` จะเหมือนกับ *let* แต่ต่างตรงที่พวกมันจะไม่สามารถ assign ค่าซ้ำได้\r\n\r\nสรุปสั้นๆ สำหรับตัวแปรที่ประกาศแบบ *const*:\r\n\r\n- เป็น *block scoped*\r\n- ไม่สามารถเข้าถึงได้ก่อนถูก assign ค่า\r\n- ไม่สามารถประกาศซ้ำได้ใน scope เดียวกัน\r\n- ไม่สามารถ assign ซ้ำได้\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // เกิด error เพราะไม่สามารถ assign ค่าซ้ำได้\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // เกิด error เพราะไม่สามารถประกาศตัวแปรซ้ำได้\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> มีบางจุดที่ต้องระวัง: ตัวแปร ```const``` ไม่ใช่ [**immutable**](#mutation_def) ! อธิบายเพิ่มเติมคือตัวแปรที่ประกาศโดย ```const``` ที่เก็บค่าเป็น *object* และ *array* ค่าข้างใน**สามารถ**เปลี่ยนแปลงได้\r\n\r\nสำหรับ objects:\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // สามารถทำได้ ! ตัวแปร person ไม่ได้ถูก assign ใหม่ แต่ถูกแปลงค่าข้างใน\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // เกิด error เพราะว่าไม่สามารถ assign ค่าซ้ำได้สำหรับตัวแปรที่ประกาศด้วย const\r\n```\r\n\r\nสำหรับ arrays:\r\n```js\r\nconst person = [];\r\nperson.push('John'); // สามารถทำได้ ! ตัวแปร person ไม่ได้ถูก assign ใหม่ แต่ถูกแปลงค่าข้างใน\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // เกิด error เพราะว่าไม่สามารถ assign ค่าซ้ำได้สำหรับตัวแปรที่ประกาศด้วย const\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"arrow_func_concept\"></a> Arrow ฟังก์ชั่น\r\n\r\nใน JavaScript อัปเดต ES6 มี *arrow ฟังก์ชั่น* ซึ่งเป็นการประกาศและใช้ฟังก์ชั่นในรูปแบบใหม่ และมีความสามารถที่มาเพิ่มเติมดังนี้\r\n\r\n- เขียนสั้นกระชับมากขึ้น\r\n- *this* อ้างอิงถึงภายนอกรอบๆ\r\n- การ return ค่าทันทีได้แบบตรงไปตรงมา\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n- การ return ที่สั้นกระชัดและตรงไปตรงมามากขึ้น\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // วิธีปกติ\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // ฟังก์ชั่นเดียวกันที่เปลี่ยนมาเขียนโดยใช้ arrow ฟังก์ชั่นและ return ทันที\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- การอ้างอิงเมื่อใช้ *this*\r\n\r\nใน arrow ฟังก์ชั่น *this* จะอ้างอิงถึงค่าของ *this* ที่อยู่บริบทที่ครอบอยู่ พูดง่ายๆ คือเมื่อใช้ arrow ฟังก์ชั่นคุณไม่จำเป็นต้องทำทริค \"that = this\" ก่อนเรียกฟังก์ชั่นอื่นภายในฟังก์ชั่นอีกทีอีกต่อไป\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### อธิบายรายละเอียด\r\n\r\n##### การย่อสั้น\r\n\r\nArrow ฟังก์ชั่นจะสั้นกระชับกว่าฟังก์ชั่นแบบปกติทั่วไป ลองมาดูวิธีการเขียนแบบที่สามารถเขียนได้ดังนี้:\r\n\r\n- Implicit VS Explicit return\r\n\r\n**Explicit return** หมายถึง function ที่ต้องมีการใช้คีย์เวิร์ด *return* ข้างในตัวมัน\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // ฟังก์ชั่นนี้เป็น explicitly returns x * 2, ดังนั้นต้องมีคีย์เวิร์ด *return*\r\n  }\r\n```\r\n\r\nโดยวิธีเขียนฟังก์ชั่นแบบปกติแล้ว การ return จะเป็น explicit จะเสมอ แต่สำหรับ arrow ฟังก์ชั่นคุณสามารถทำ *implicit return* ซึ่งหมายความว่าคุณไม่จำเป็นต้องใช้คีย์เวิร์ด *return* เพื่อ return ค่าได้เลย\r\n\r\nในการเขียน implicit return จะทำให้สามารถเขียนโค้ดได้เหลือเพียง 1 บรรทัด\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // Explicit return ตรงนี้\r\n  }\r\n```\r\n\r\nเมื่อมันทำแค่ return ค่าตรงนั้นทันที เราสามารถเขียนแบบ implicit return ได้ข้างล่าง\r\n\r\n```js\r\n  const double = (x) => x * 2;\r\n```\r\n\r\nและจากข้างบน ที่เราต้องทำมีแค่ **เอาปีกกา** กับคีย์เวิร์ด **return** ออก แบบนี้เลยเรียกว่า *implicit* return เพราะว่าไม่จำเป็นต้องใช้คีย์เวิร์ด return แต่ฟังก์ชั่นก็ยัง return ```x * 2``` อยู่\r\n\r\n> **หมายเหตุ:** ถ้าฟังก์ชั่นของคุณไม่ได้ต้องการการ return ค่า (พร้อมกับ *side effects*) จะใช้แบบไหนก็ไม่ต่างกัน\r\n\r\nนอกจากนี้ ถ้าคุณใช้ implicit return ค่าเป็น *object* คุณ**ต้องใช้วงเล็บครอบ** เพื่อป้องกันการสับสนกับ block scope ตามข้างล่าง\r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- object implicitly return ค่าโดยใช้ arrow function\r\n```\r\n\r\n- มี argument แค่ตัวเดียว\r\n\r\nถ้า function รับ parameter เพียงแค่ตัวเดียว สามารถเอาวงเล็บออกได้ ถ้าเราปรับปรุงจากโค้ด *double* ก่อนหน้าจะได้ดังนี้\r\n\r\n```js\r\n  const double = (x) => x * 2; // arrow ฟังก์ชั่นนี้รับเพียง 1 parameter\r\n```\r\n\r\nวงเล็บสามารถเอาออกได้ดังนี้:\r\n\r\n```js\r\n  const double = x => x * 2; // arrow ฟังก์ชั่นนี้รับเพียง 1 parameter\r\n```\r\n\r\n- ไม่มี argument\r\n\r\nเมื่อไม่ต้องการ argument ใดๆ เลยใน arrow function คุณจำเป็นต้องใส่วงเล็บ ไม่อย่างนั้นมันจะไม่ใช่ syntax ที่ถูกต้อง\r\n\r\n```js\r\n  () => { // ถ้ามีวงเล็บ ทุกอย่างจะปกติ\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // ถ้าไม่มีวงเล็บ จะใช้งานไม่ได้!\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### การอ้างอิงของ *this*\r\n\r\nเพื่อที่จะเข้าใจเรื่อง this กับ arrow ฟังก์ชั่นคุณต้องเข้าใจก่อนว่า [this](#this_def) ทำงานยังไงใน JavaScript\r\n\r\nใน arrow function *this* มีค่าเท่าที่ค่าของ *this* ที่เป็นบริบทที่ครอบมันอยู่ นั่หมายถึงว่า arrow ฟังก์ชั่นไม่สร้าง *this* ขึ้นมาใหม่ แต่ว่ามันเอาค่าที่อยู่รอบนอกของมันมาใช้แทน\r\n\r\nถ้าไม่ใช่ arrow ฟังก์ชั่นถ้าคุณต้องการใช้งานตัวแปร *this* ของฟังก์ชั่นเมื่ออยู่ภายใน function อีกที เพื่ออ้างอิงถึง *this* ภายนอก คุณจะต้องใช้ *that = this* หรือว่า *self = this* เป็นทริคเพื่ออ้างอิงถึง\r\n\r\nยกตัวอย่างเช่น เมื่อใช้ฟังก์ชั่น setTimeout ภายใน myFunc:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // ทริค that = this\r\n  setTimeout(\r\n    function() { // *this* ใหม่ถูกสร้างภายใน function scope นี้\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- เพราะว่าไปหาที่ฟังก์ชั่นที่อยู่นี้ ไม่ใช่ myFunc\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\nแต่เมื่อใช้ arrow ฟังก์ชั่น *this* จะอ้างอิงถึงที่อยู่รอบๆ ตัวมัน:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this มาจากรอบๆ นั่นหมายถึง myFunc ในกรณีนี้\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### หล่งข้อมูลที่มีประโยชน์\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n### ค่า Default Parameter ของฟังก์ชั่น\r\n\r\nตั้งแต่อัปเดตของ ES2015 JavaScript คุณสามารถตั้งค่า default ให้กับ parameter ของฟังก์ชั่นได้แล้วโดยใช้ syntax ตามข้างล่างนี้:\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- ไม่ได้มีค่าโยนเข้าไปใน parameter ดังนั้นค่า x จะถูก assign เป็นค่า default ของ myFunc นั่นก็คือ 10\r\nconsole.log(myFunc(5)) // 5 -- มีค่าโยนเข้าไปใน paramter ดังนั้นค่า x จะมีค่าเท่ากับ 5 ใน myFunc\r\n\r\nconsole.log(myFunc(undefined)) // 10 -- โยนค่าเป็น undefined ไป ดังนั้นจะนำค่า default มาใช้ซึ่งก็คือ 10\r\nconsole.log(myFunc(null)) // null -- โยนค่า null เข้าไปจึงได้ค่า x เป็น null, ดูรายละเอียดเพิ่มเติมข้างล่าง\r\n```\r\n\r\nค่า default paramter จะถูกเรียกใช้ในสองกรณีนี้เท่านั้น:\r\n\r\n- ไม่โย parameter มาให้\r\n- รับค่า parameter เป็น *undefined*\r\n\r\nหรือในอีกความหมายนึงคือ ถ้าคุณส่งค่าเป็น *null* จะไม่มีการใช้งาน default parameter\r\n\r\n> **หมายเหตุ:** ค่า Default สามารถใช้ร่วมกับ destructured parameters ได้ (อันนี้จะอยู่ในเนื้อห้าถัดไป)\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Default parameters - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\r\n\r\n### Destructuring objects และ arrays\r\n\r\n*Destructuring* เป็นวิธีในการสร้างตัวแปรใหม่จากการแยกค่าบางค่าจากข้างในของ objects หรือ arrays ซึ่งทำให้สะดวกมากยิ่งขึ้น\r\n\r\nยกตัวอย่างสำหรับการใช้งานเช่น *destructuring* สามารถใช้ในการแยกส่วน parameters ของฟังก์ชั่น หรือว่า *this.props* ที่มักเจอประจำในโปรเจ็คที่เป็น React\r\n\r\n#### อธิบายตัวอย่างโค้ด\r\n\r\n- Object\r\n\r\nลองพิจารณา object ข้างล่างเป็นตัวอย่าง:\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\nเมื่อไม่ใช้ destructuring:\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\nเมื่อใช้ destructuring สามารถเขียนในบรรทัดเดียวได้แบบนี้:\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // แบบนี้ !\r\n\r\nconsole.log(age) // 35 -- ตัวแปร age ถูกสร้างขึ้นมาใหม่และมีค่าเท่ากับ person.age\r\nconsole.log(first) // \"Nick\" -- ตัวแปร first ถูกสร้างขึ้นมาใหม่และมีค่าเท่ากับ person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName มีอยู่จริง แต่ตัวแปรที่ถูกสร้างขึ้นใหม่ถูกตั้งชื่อว่า first\r\nconsole.log(city) // \"Paris\" -- ตัวแปร city ถูกสร้างขึ้นใหม่ และ person.city มีค่าเป็น undefined เพราะฉะนั้น city จะมีค่าเท่ากับ default ที่ระบุไว้คือ \"Paris\"\r\n```\r\n\r\n**หมายเหตุ :** ใน ```const { age } = person;```, ปีกกาหลังคีย์เวิร์ด *const* มีได้หมายถึงเป็นการประกาศ object หรือว่า block แต่มันหมายถึงเป็น *destructuring* syntax\r\n\r\n- Parameters ของฟังก์ชั่น\r\n\r\n*Destructuring* จะใช้บ่อยในการ destructure objects parameters ในฟังก์ชั่น\r\n\r\nถ้าไม่มี destructuring\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n*person* สามารถทำ destructuring เพื่อให้สั้นกระชับขึ้นได้ดังนี้:\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { // สร้างตัวแปร firstName กับ lastName โดยการ destructuring ตัวแปร\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\nDestructuring ยังถูกใช้บ่อยควบคู่กับ [arrow ฟังก์ชั่น](#arrow_func_concept):\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- Array\r\n\r\nจาก array ข้างล่างต่อไปนี้:\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\nเมื่อไม่มี destructuring\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\nเมื่อมี destructuring\r\n\r\n```js\r\nconst [x, y] = myArray; // แบบนี้ !\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n#### แหล่งข้อมูลที่มีประโยชน์\r\n\r\n- [ES6 Features - Destructuring Assignment](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)\r\n\r\n### Array methods - map / filter / reduce\r\n\r\n*Map*, *filter* และ *reduce* เป็น method ของ array ที่มาจาก programming paradigm ที่ชื่อว่า [*functional programming*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0).\r\n\r\nสรุปแบบสั้นๆ:\r\n\r\n- **Array.prototype.map()** นำ array มาวนลูป ทำอะไรบางอย่างกับค่าของมันแต่ละค่าแล้ว return กลับกลายเป็น array ที่แปลงค่าแล้ว.\r\n- **Array.prototype.filter()** นำ array มาวนลูป เลิอกว่าค่าไหนเก็บไว้และค่าไหนทิ้ง และ return กลับไปเป็น array ที่ถูกเลือกแล้ว\r\n- **Array.prototype.reduce()** นำ array มาวนลูปและประกอบกันแต่ละค่าเหลือเพียงค่าเดียวเพื่อ return กลับไป\r\n\r\nแนะนำให้ใช้พวกนี้มากที่สุดเท่าที่จะทำได้ตามทฤษฐีของ functional programming เพราะว่ามันสั้นกระชับและสวยกว่า\r\n\r\nเมื่อมี 3 methods นี้ คุณสามารถละการใช้ *for* และ *forEach* ลูปในสถานการณ์ส่วนใหญ่ได้ เมื่อคุณจะใช้ *for* ลูป ลองเปลี่ยนมาใช้ *map*, *filter* และ *reduce* แทน แรกๆ อาจจะติดเพราะว่าต้องเปลี่ยนวิธีในการคิดแต่หลังจากเข้าใจและใช้ไปซักระยะจะสามารถใช้งานได้อย่างง่ายดาย\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // 21\r\n```\r\n\r\nคำนวณผลรวมเกรดทั้งหมดของนักเรียนโดยใช้ map, filter และ reduce:\r\n\r\n```js\r\nconst students = [\r\n  { name: \"Nick\", grade: 10 },\r\n  { name: \"John\", grade: 15 },\r\n  { name: \"Julia\", grade: 19 },\r\n  { name: \"Nathalie\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // เรา map ข้อมูลนักเรียนให้กลายเป็น array ที่มีแต่เกรด\r\n  .filter(grade => grade >= 10) // เรา filter เกรดให้เก็บไว้เฉพาะที่มีค่ามากกว่าเท่ากับ 10\r\n  .reduce((prev, next) => prev + next, 0); // เรารวมผลรวมของทุกเกรดทีละคน\r\n\r\nconsole.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie ได้เกรดต่ำกว่า 10 จะถูกข้ามไป\r\n```\r\n\r\n#### อธิบาย\r\n\r\nลองดู array ของตัวเลขต่อไปนี้ที่จะใช้ในตัวอย่าง:\r\n\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n##### Array.prototype.map()\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\nเกิดอะไรขึ้นในข้างบนบ้าง? เราใช้ .map กับ array ที่เก็บ *ตัวเลข* โดย map จะทำการวนรอบ (iterate) ทุกๆ ค่าที่อยู่ภายใน array และส่งค่าต่อเข้าไปในฟังก์ชั่นของเรา เป้าหมายของฟังก์ชั่นนี้คือต้องการสร้างค่าใหม่จากค่าเดิมที่ส่งเข้ามาและส่งกลับไป\r\n\r\nถ้ากระจายฟังก์ชั่นให้อ่านง่ายขึ้นจะเป็นตามภาพดังนี้:\r\n\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n```numbers.map(doubleN)``` produces ```[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]``` จะเท่ากับ ```[0, 2, 4, 6, 8, 10, 12]```.\r\n\r\n> **หมายเหตุ:** ถ้าคุณไม่ต้องการ return array ใหม่ แต่ต้องการทำลูปที่สร้าง side effects การใช้ for / forEach ลูปน่าจะเหมาะมากกว่าใช้ map\r\n\r\n##### Array.prototype.filter()\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // ถ้า n เป็นเลขคู่จะเป็น true, และ false ถ้า n ไม่ใช่\r\n});\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\nเราใช้ .filter กับ array ที่เก็บ *ตัวเลข* ชุดเดิม, filter จะทำการวนรอบ (iterate) ทุกค่าใน array และส่งเข้าไปในฟังก์ชั่นของเรา เป้าหมายของฟังก์ชั่นนี้คือการ return เป็น boolean ว่าค่านั้นๆ จะต้องการเก็บเอาไว้หรือทิ้ง ผลสุดท้ายของ filter จะ return array ที่เหลือแต่ค่าที่เลือกเก็บเท่านั้น\r\n\r\n##### Array.prototype.reduce()\r\n\r\nreduce method จะทำหน้าที่ *reduce* ทุกค่าใน array โดยมันจะวนรอบ (iterate) ค่าทั้งหมดให้กลายเหลือเป็นค่าเดียว โดยวิธีการประกอบค่าต่างๆ ยังไงอยู่ที่เรากำหนดในฟังก์ชั่น\r\n\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n  0 // ตัวสะสมค่าตัวแปรสำหรับการวนลูปรอบแรก\r\n);\r\n\r\nconsole.log(sum) //21\r\n```\r\n\r\nเหมือนกับ method ของ .map และ .filter เพียงแต่ว่า .reduce จะนำค่าที่ได้จากรอบก่อนหน้ามาส่งต่อเป็น parameter แรกของฟังก์ชั่น\r\n\r\nมาดูความแตกต่าง:\r\n\r\n- .reduce รับ parameter สองตัว\r\n\r\nparameter แรกจะเป็นฟังก์ชั่นสำหรับการวนรอบ (itelation)\r\n\r\nparameter ที่สองจะเป็นค่าตัวแปรสะสม (ในที่นี้หมายถึง *acc*) สำหรับการวนรอบรอบแรก (คำข้อถัดไปจะมีอธิบายว่าทำไมต้องมี)\r\n\r\n- Parameters ของฟังก์ชั่น\r\n\r\nฟังก์ชั่นที่ส่งเข้าไปใน parameter แรกของ .reduce จะได้รับ parameter ทั้งหมด 2 ตัว โดยตัวแรก (ในที่นี้คือ *acc*) คือตัวแปรสะสม ในขณะที่ตัวแปรที่สอง (*n*) คือค่าปัจจุบันของรอบลูปนั้นๆ\r\n\r\nตัวแปรสะสมจะเท่ากับค่าที่ return ในฟังก์ชั่นของการวนรอบ (iteration) ก่อนหน้า ในการวนรอบแรก *acc* จะมีค่าเท่ากับค่าที่คุณส่งเป็น parameter ที่สองให้กับ .reduce นั่นเลยจำเป็นต้องโยนค่า 0 เข้าไปเป็น parameter ที่สองของ reduce นั่นเอง\r\n\r\n###### ในการวนรอบรอบแรก\r\n\r\n```acc = 0``` เพราะเราส่งค่า 0 เป็น parameter ที่สองให้กับ reduce\r\n\r\n```n = 0``` ค่าแรกของ array ที่เก็บ *ตัวเลข*\r\n\r\nฟังก์ชั่นจะ returns *acc* + *n* --> 0 + 0 --> 0\r\n\r\n###### ในการวนรอบรอบที่สอง\r\n\r\n```acc = 0``` เพราะว่ามันคือค่าที่มาจากการ return ของฟังก์ชั่นในการวนรอบก่อนหน้า\r\n\r\n```n = 1``` ค่าที่สองของ array ที่เก็บ *ตัวเลข*\r\n\r\nฟังก์ชั่นจะ returns *acc* + *n* --> 0 + 1 --> 1\r\n\r\n###### ในการวนรอบรอบที่สาม\r\n\r\n```acc = 1``` เพราะว่ามันคือค่าที่มาจากการ return ของฟังก์ชั่นในการวนรอบก่อนหน้า\r\n\r\n```n = 2``` ค่าที่สามของ array ที่เก็บ *ตัวเลข*\r\n\r\nฟังก์ชั่นจะ returns *acc* + *n* --> 1 + 2 --> 3\r\n\r\n###### ในการวนรอบรอบที่สี่\r\n\r\n```acc = 3``` เพราะว่ามันคือค่าที่มาจากการ return ของฟังก์ชั่นในการวนรอบก่อนหน้า\r\n\r\n```n = 3``` ค่าที่สี่ของ array ที่เก็บ *ตัวเลข*\r\n\r\nฟังก์ชั่นจะ returns *acc* + *n* --> 3 + 3 --> 6\r\n\r\n###### [...] ในการวนรอบสุดท้าย\r\n\r\n```acc = 15``` เพราะว่ามันคือค่าที่มาจากการ return ของฟังก์ชั่นในการวนรอบก่อนหน้า\r\n\r\n```n = 6``` ค่าสุดท้ายของ array ที่เก็บ *ตัวเลข*\r\n\r\nฟังก์ชั่นจะ returns *acc* + *n* --> 15 + 6 --> 21\r\n\r\nในการวนรอบสุดท้าย **.reduce** จะคืนค่า 21 กลับไป\r\n\r\n#### ข้อมูลเพิ่มเติมภายนอก\r\n\r\n- [Understanding map / filter / reduce in JS](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464)\r\n\r\n### Spread operator \"...\"\r\n\r\nspread operator ```...``` เป็นของใหม่ใน ES2015 และใช้สำหรับแผ่ขยายค่าของสิ่งที่สามารถนำมาวนรอบได้ (อย่างเช่น array) แตกออกเป็นชิ้นๆ และนำไปใส่ที่อื่น\r\n\r\n#### โค้ดตัวอย่าง\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x);\r\n  console.log(y);\r\n  console.log(params)\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n#### อธิบาย\r\n\r\n##### ใช้กับสิ่งที่สามารถวนลูปได้ (iterables) (แบบ arrays)\r\n\r\nถ้าเรามี array สองตัวดังนี้:\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\n\r\nใน *arr2* ค่าแรกจะเป็น array เพราะว่า *arr1* ถูกนำเข้าไปใส่ใน *arr2* แต่ถ้าเราต้องให้ *arr2* เป็น array ของตัวอักษรเพียงอย่างเดียว สิ่งที่เราต้องทำคือเราสามารถ *spread* ค่าต่างๆ ของ *arr1* เข้าไปสู่ *arr2*\r\n\r\nเมื่อใช้ spread operator\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n##### Rest parameter ของฟังก์ชั่น\r\n\r\nใน parameter ของฟังก์ชั่นเราสามารถใช้ rest operator สำหรับรวม parameters เป็น array ที่เราสามารถนำไปวนลูปได้ ถ้าเทียบก็เหมือนการห่อ **arguments** ที่รับมาเป็น object เอาไว้\r\n\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\n\r\nmyFunc(\"Nick\", \"Anderson\", 10, 12, 6);\r\n// \"Nick\"\r\n// \"Anderson\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\n\r\nแต่ถ้าเราต้องการให้ function นี้สร้าง student ใหม่พร้อมกับ grade ทั้งหมดของนักเรียนและค่าเฉลี่ยเกรด จะง่ายกว่าถ้าเราแยกให้สอง parameter แรกเป็นตัวแปรแยก และที่เหลือจากนั้นเป็น grade ที่เราสามารถนำไปวนรอบ (itelate) ได้มันน่าจะดีกว่ารึเปล่า?\r\n\r\nและ rest operator ทำให้เราสามารถทำแบบนั้นได้!\r\n\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  // firstName = \"Nick\"\r\n  // lastName = \"Anderson\"\r\n  // [10, 12, 6] -- \"...\" นำ paramters ที่รับเข้ามาที่เหลือสร้างเป็นตัวแปร array ชื่อ \"grades\"\r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // คำนวณค่าเฉลี่ยของ grades\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Nick\", \"Anderson\", 10, 12, 6);\r\nconsole.log(student);\r\n// {\r\n//   firstName: \"Nick\",\r\n//   lastName: \"Anderson\",\r\n//   grades: [10, 12, 6],\r\n//   avgGrade: 9,33\r\n// }\r\n```\r\n\r\n> **หมายเหตุ:** ฟังก์ชั่น createStudent ยังไม่ดีเท่าไหร่เพราะว่าเรายังไม่ได้เช็ก grades.length ในกรณีที่ไม่มีค่าอยู่จริงหรือไม่ใช่ 0 แต่มันง่ายกว่าถ้าเขียนแบบนี้เพื่อทำความเข้าใจ เพราะฉะนั้นในโค้ดตัวอย่างเลยจะไม่มีการจัดการกับกรณีนี้\r\n\r\n##### Object properties spreading\r\n\r\nก่อนจะเข้าเรื่องนี้ แนะนำให้อ่านคำอธิบายก่อนหน้าสำหรับ rest operator ที่ทำการห่อ parameter กลายเป็น object ที่สามารถทำการวนลูปได้ (itelable)\r\n\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // object destructuring ตรงนี้\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\n// z จะได้ค่าที่เหลือของ object ที่ถูก destructured แล้ว: myObj object เมื่อลบค่า x และ y properties ที่ถูก destructured ออกไปแล้ว\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// เมื่อนำ z object มา spread กลับเข้าไปให้กับตัวแปร n จะได้ค่าดังเดิม\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [TC39 - Object rest/spread](https://github.com/tc39/proposal-object-rest-spread)\r\n- [Spread operator introduction - WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md)\r\n- [JavaScript & the spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca)\r\n- [6 Great uses of the spread operator](https://davidwalsh.name/spread-operator)\r\n\r\n### Object property shorthand\r\n\r\nเมื่อ assign ค่าใช้ตัวแปรเป็น object property ถ้าชื่อตัวแปรมีค่าเท่ากับชื่อ property คุณสามารถทำแบบนี้ได้:\r\n\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // 10\r\n```\r\n\r\n#### อธิบาย\r\n\r\nปกติแล้ว (pre-ES2015) เมื่อคุณประกาศ *object literal* ใหม่ และต้องการใช้ค่าของตัวแปรไปเป็นค่าให้กับ object properties นั้นปกติแล้วต้องเขียนแบบนี้:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // assign ค่าของตัวแปร x ให้เป็นค่าของ myObj.x\r\n  y: y // assign ค่าของตัวแปร y ให้เป็นค่าของ myObj.y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\nจะเห็นว่ามันซ้ำซ้อนกันเพราะว่าชื่อ properties ของ myObj เป็นชื่อเดียวกับตัวแปรที่ต้องการ assign ให้กับ properties เหล่านั้น\r\n\r\nเมื่อเขียนด้วย ES2015 เมื่อชื่อตัวแปรเป็นชื่อเดียวกับชื่อ property สามารถเขียนให้สั้นลงเป็นแบบนี้ได้:\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [Property shorthand - ES6 Features](http://es6-features.org/#PropertyShorthand)\r\n\r\n### Promises\r\n\r\nPromise เป็น object ที่สามารถ return ค่าแบบ synchronous จากฟังก์ชั่นที่เป็น asynchronous ได้ ([ref](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0)).\r\n\r\nPromise สามารถใช้เพื่อแก้ปัญหาของ [callback hell](http://callbackhell.com/) และมันมักนำไปใช้ในโค้ด Javascript โปรเจ็คใหม่ๆ ที่ทันสมัย\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n    .done(posts => res(posts))\r\n    .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n#### อธิบาย\r\n\r\nเมื่อคุณสร้าง *Ajax request* จะได้รับ response ที่ไม่ synchronous เพราะว่ามันต้องใช้เวลาเพื่อจะได้ผลลัพธ์ที่กลับมา และมันอาจจะไม่ได้ค่าที่ต้องการกลับมาถ้า request ที่ส่งไปไม่สามารถใช้งานได้ด้วยเหตุบางประการ (404)\r\n\r\nเพื่อรับมือกับสถานการณ์แบบนั้น ES2015 ได้มี *promises* ซึ่ง promise มีทั้งหมด 3 states ด้วยกัน:\r\n\r\n- Pending\r\n- Fulfilled\r\n- Rejected\r\n\r\nหรือพูดอีกอย่างว่าเราต้องการใช้ promise ไปการจัดการกับพวก Ajax request เพื่อดึงข้อมูลจาก X\r\n\r\n##### การสร้าง promise\r\n\r\nก่อนที่เราจะใช้ promise เราจะใช้ jQuery สำหรับการทำ Ajax request ไปหา X\r\n\r\n```js\r\nconst xFetcherPromise = new Promise( // สร้าง promise โดยใช้คีย์เวิร์ด \"new\" และเก็บลงตัวแปร\r\n  function(resolve, reject) { // constructor ของ promise รับ parameter เป็นฟังก์ชั่นที่มี parameter ชื่อ resolve และ reject ด้วยตัวมันเอง\r\n    $.get(\"X\") // ส่ง Ajax request\r\n      .done(function(X) { // เมื่อ request เสร็จแล้ว ...\r\n        resolve(X); // ... resolve promise ด้วยค่า X กลับไปเป็น parameter\r\n      })\r\n      .fail(function(error) { // ถ้า request เกิดผิดพลาด...\r\n        reject(error); // ... reject promise แล้วส่ง error กลับไปเป็น parameter\r\n      });\r\n  }\r\n)\r\n```\r\n\r\nจากที่เห็นในตัวอย่างข้างบน Promise object จะรับ *executor* ฟังก์ชั่นที่รับ parameter สองตัวคือ **resolve** และ **reject** ซึ่งสองตัวนี้ถ้ามีการเรียกใช้จะเป็นการย้าย state ของ promise จาก *pending* ไปสู่ *fulfilled* หรือ *rejected*\r\n\r\npromise จะอยู่ใน pending state หลังสร้าง instance และฟังก์ชั่น *executor* ของมันจะทำงานทันที และเมื่อมีการเรียกใช้ฟังก์ชั่น *resolve* หรือ *reject* ภายใน *executor* ฟังก์ชั่นตัว promise จะมีสิ่งที่เรียกว่า handlers คอยจัดการกับสิ่งที่เกิดขึ้น\r\n\r\n##### การใช้งาน Promise handlers\r\n\r\nเพื่อที่จะรับผลลัพธ์ของ promise (หรือว่า error) เราจะสามารถควบคุมด้วย handlers โดยทำได้ดังนี้:\r\n\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err)\r\n  })\r\n```\r\n\r\nถ้า promise ทำงานสมบูรณ์และเรียกใช้ *resolve* โดยจะส่งค่าที่ได้ไปเป็น parameter ในฟังก์ชั่นใน ```.then```\r\n\r\nถ้าเกิดข้อผิดพลาด *reject* จะถูกเรียกแล้วส่งค่าไปเป็น parameter ในฟังก์ชั่นใน ```.catch```\r\n\r\n> **หมายเหตุ :** ถ้า promise เข้าไปสู่ state fulfilled หรือ rejected โดยที่มีการใช้ handler แล้ว handler จะถูกเรียกใช้ ทำให้ไม่เกิด race condition ระหว่างรอ asynchronous เสร็จสมบูรณ์กับ handlers [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Description)\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [JavaScript Promises for dummies - Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies)\r\n- [JavaScript Promise API - David Walsh](https://davidwalsh.name/promises)\r\n- [Using promises - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\r\n- [What is a promise - Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)\r\n- [JavaScript Promises: an Introduction - Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises)\r\n- [Promise documentation - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\r\n\r\n### Template literals\r\n\r\nTemplate literals เป็น [*expression interpolation*](https://en.wikipedia.org/wiki/String_interpolation) สำหรับ strings ที่สามารถทำได้ตั้งแต่บรรทัดเดียวถึงหลายบรรทัด\r\n\r\nหรือในอีกกรณีนึงก็คือ มันเป็น syntax ของ string ที่สามารถใช้ JavaScript expesssions ข้างในได้อย่างสะดวกมากขึ้น (ยกตัวอย่างเช่นแทรกตัวแปรภายใน string)\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n```js\r\nconst name = \"Nick\";\r\n`Hello ${name}, the following expression is equal to four : ${2+2}`;\r\n\r\n// Hello Nick, the following expression is equal to four: 4\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)\r\n- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)\r\n\r\n### Tagged template literals\r\n\r\nTemplate tags คือ *ฟังก์ชั่นที่สามารถกลายเป็นให้กับ [template literal](#template-literals) ได้*. ถ้าฟังก์ชั่นถูกเรียกใช้แบบนี้ parameter แรกจะเป็น array ของ *strings* ที่แสดงระหว่างตัวแปรของ template's interpolated และ parameter อื่นที่ตามมาคือค่า interpolated ดังนั้นถ้าใช้ spread operator `...` ก็จะสามารถรวบรวม parameter ที่เหลือทั้งหมดได้ [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals).\r\n\r\n> **หมายเหตุ :** Library ชื่อดังอย่าง [styled-components](https://www.styled-components.com/) ใช้ฟีเจอร์นี้อย่างเต็มรูปแบบ\r\n\r\nข้างล่างคือตัวอย่างของการนำไปใช้งาน\r\n```js\r\nfunction highlight(strings, ...values) {\r\n  const interpolation = strings.reduce((prev, current) => {\r\n    return prev + current + (values.length ? \"<mark>\" + values.shift() + \"</mark>\" : \"\");\r\n  }, \"\");\r\n\r\n  return interpolation;\r\n}\r\n\r\nconst condiment = \"jam\";\r\nconst meal = \"toast\";\r\n\r\nhighlight`I like ${condiment} on ${meal}.`;\r\n// \"I like <mark>jam</mark> on <mark>toast</mark>.\"\r\n```\r\n\r\nตัวอย่างที่น่าสนใจเพิ่มเติม:\r\n```js\r\nfunction comma(strings, ...values) {\r\n  return strings.reduce((prev, next) => {\r\n    let value = values.shift() || [];\r\n    value = value.join(\", \");\r\n    return prev + next + value;\r\n  }, \"\");\r\n}\r\n\r\nconst snacks = ['apples', 'bananas', 'cherries'];\r\ncomma`I like ${snacks} to snack on.`;\r\n// \"I like apples, bananas, cherries to snack on.\"\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)\r\n- [Library of common template tags](https://github.com/declandewet/common-tags)\r\n\r\n### Imports / Exports\r\n\r\nES6 modules สามารถเข้าถึงตัวแปรต่างๆ ของ modules ที่ทำการแยก export ค่าต่างๆ ได้ด้วยการ imports\r\n\r\nแนะนำให้ลองอ่านข้อมูลเพิ่มเติมใน MDN resources เกี่ยวกับเรื่อง import/export (ดูข้อมูลเพิ่มเติมภายนอกข้างล่าง) จะดีเป็นอย่างมาก เนื้อหาข้างในค่อนข้างอธิบายได้ตรงไปตรงมาและสมบูรณ์แบบ\r\n\r\n#### อธิบายตัวอย่างโค้ด\r\n\r\n##### Named exports\r\n\r\nNamed exports ใช้สำหรับการ export หลายๆ ค่าของ module\r\n\r\n> **หมายเหตุ :** สามารถ export แบบ name-export [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen) ได้เฉพาะกับของที่มีชื่อเท่านั้น.\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js'; // Named import -- คล้ายๆ กับ syntax destructuring\r\nconsole.log(pi) // 3.14\r\nconsole.log(exp) // 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js'; // ทำค่าทั้งหมดที่มีการ exports มาเป็นตัวแปร\r\nconsole.log(constants.pi) // 3.14\r\nconsole.log(constants.exp) // 2.7\r\n```\r\n\r\nnamed imports จะคล้ายกับ *destructuring* แต่ว่าจริงๆ แล้วมีความต่างและไม่เหมือนกัน มันไม่รองรับการใช้ default value หรือว่า *deep* destructuring\r\n\r\nนอกจากนี้คุณสามารถทำ alias ได้อยู่ เพียงแต่ว่า syntax จะแตกต่างกับ destructuring เป็นรูปแบบตามข้างล่าง\r\n\r\n```js\r\nimport { foo as bar } from 'myFile.js'; // foo ถูก import เข้ามาและเอาไปเป็นค่าตัวแปรใหม่ที่ชื่อว่า bar\r\n```\r\n\r\n##### Default import / export\r\n\r\nสำหรับ default export เราจะสามารถ export default ได้แค่ตัวเดียวต่อ module และค่า default ที่ export สามารถเป็นได้ทั้ง function, class, object หรืออะไรก็ตาม ค่านี้เป็นเหมือนค่า \"หลัก\" ในการ export และมันจะง่ายต่อการ import เวลานำไปใช้ [Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Description)\r\n\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n// Default export จะอิสระในการตั้งชื่อในหน้าที่ import เข้าไปใช้งาน อย่างข้างบนจะถูกเก็บลงตัวแปรชื่อ number ซึ่งเราสามารถตั้งเองได้\r\nconsole.log(number) // 42\r\n```\r\n\r\nExport ฟังก์ชั่น:\r\n\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // 3\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [ES6 Modules in bulletpoints](https://ponyfoo.com/articles/es6#modules)\r\n- [Export - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\r\n- [Import - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/)\r\n- [Destructuring special case - import statements](https://ponyfoo.com/articles/es6-destructuring-in-depth#special-case-import-statements)\r\n- [Misunderstanding ES6 Modules - Kent C. Dodds](https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0)\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript)\r\n\r\n### <a name=\"this_def\"></a> JavaScript *this*\r\n\r\n*this* operator จะแตกต่างกับาภาษาอื่นๆ และโดยกรณีส่วนมากเป็นกำหนดเองว่า this จะทำงานในบริบทไหนในฟังก์ชั่น ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)).\r\n\r\nเนื้อหานี้จะมีรายละเอียดที่ค่อนข้างอ่อนไหวและยากอยู่พอสมควร แนะนำให้ลองอ่านข้อมูลภายนอกเพิ่มเติมข้างล่าง ดังนั้นในที่นี้จะเขียนโดยอิงจากความเข้าใจส่วนตัวจาก[บทความที่เขียนโดย Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) อีกที\r\n\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// ข้างล่างจะแสดงให้เห็นค่าของ *this* ใน myFunc\r\n\r\nmyFunc.call(\"myString\", \"hello\") // \"myString\" -- ค่า parameter แรกใน .call จะถูกกำหนดเป็น *this*\r\n\r\n// ในโหมด non-strict-mode\r\nmyFunc(\"hello\") // window -- myFunc() เป็น syntax เหมือนกับเรียก myFunc.call(window, \"hello\")\r\n\r\n// ในโหมด strict-mode\r\nmyFunc(\"hello\") // undefined -- myFunc() เป็น syntax เหมือนกับเรียก myFunc.call(undefined, \"hello\")\r\n```\r\n\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\") // person Object -- ค่า parameter แรกใน .call จะถูกกำหนดเป็น *this*\r\nperson.myFunc(\"test\") // person Object -- person.myFunc() เป็น syntax เหมือนกับเรียก person.myFunc.call(person, \"test\")\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"hello\") // สร้างฟังก์ชั่นใหม่ที่ผูก \"hello\" เป็นค่าของ *this*\r\nperson.myFunc(\"test\") // person Object -- bind method ไม่มีผลใดๆ กับ method ดั้งเดิม\r\nmyBoundFunc(\"test\") // \"hello\" -- myBoundFunc เป็น person.myFunc ที่มี \"hello\" เป็น *this*\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [Understanding JavaScript Function Invocation and \"this\" - Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)\r\n- [JavaScript this - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\r\n\r\n### Class\r\n\r\nJavaScript เป็นภาษาที่เป็น [prototype-based](https://en.wikipedia.org/wiki/Prototype-based_programming) (เมื่อเปรียบเทียบกับ Java ที่เป็นภาษาที่เป็น [class-based](https://en.wikipedia.org/wiki/Class-based_programming)). ES6 ได้ทำให้ JavaScript เสมือนมี class ขึ้นมา แต่จริงๆแล้วเกิดจากการสืบทอดจาก prototype-based และ **ไม่ใช่** class-based ([ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)).\r\n\r\nคำว่า *class* จะไม่เหมือนกับ class ในภาษาอื่นๆ เป็นไปได้ควรทำความเข้าใจกับ class ใน JavaScript ก่อน assume ว่ามันจะเหมือนภาษาอื่น\r\n\r\nบทความนี้ไม่ได้สอนเรื่องภาษาตั้งแต่เริ่มต้น เราเชื่อคุณรู้อยู่แล้วว่า prototypes คืออะไรและทำหน้าที่อะไร แต่ถ้ายังไม่เข้าใจเรื่องพวกนี้เรามี link บางส่วนที่จะช่วยอธิบายเพื่อให้เรื่องเหล่านี้ได้ดีมากขึ้น\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\n#### ตัวอย่าง\r\n\r\nก่อนจะมี ES6 ต้องเขียนแบบ prototype syntax:\r\n\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n}\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n}\r\n```\r\n\r\nเมื่อใช้ Syntax แบบ ES6:\r\n\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Manu\", 23);\r\nconsole.log(myPerson.age) // 23\r\nconsole.log(myPerson.stringSentence()) // \"Hello, my name is Manu and I'm 23\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\nสำหรับทำความเข้าใจ prototype:\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\nสำหรับทำความเข้าใจ classes:\r\n\r\n- [ES6 Classes in Depth - Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features - Classes](http://es6-features.org/#ClassDefinition)\r\n- [JavaScript Classes - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\r\n\r\n### Async Await\r\n\r\nเพิ่มเติมจาก [Promises](#promises) จะมี syntax รูปแบบใหม่ให้สำหรับจัดการกับ asynchronous ชื่อว่า *async / await*\r\n\r\nจุดประสงค์ของ async/await function คือทำให้สามารถจัดการกับการใช้ promise synchronous ได้ง่ายขึ้น และทำพฤติกรรมคล้ายๆ กับ Promises ถ้าให้เปรียบเทียบคือถ้า Promises มีโครงสร้างคล้ายคลึงกับ callback สำหรับ async/await จะมีโครงสร้างคล้าย generators ผสมกับ promises นั่นเอง ซึ่ง async function จะ return เป็น Promise *เสมอ* ([Ref: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function))\r\n\r\n> **หมายเหตุ :** ต้องเข้าใจก่อนว่า promise คืออะไร และทำงานยังไง ก่อนที่จะพยายามทำความเข้าใจ async / await\r\n\r\n> **หมายเหตุ 2:** [*await* จะต้องใช้ใน *async* function](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0), นั่นหมายความว่าคุณไม่สามารถใช้ await ใน top level ของโค้ดได้ ถ้ามันไม่ได้อยู่ใน async function.\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n```js\r\nasync function getGithubUser(username) { // คีย์เวิร์ด async ทำให้สามารถใช้ await ภายในฟังก์ชั่นได้ นั่นหมายถึงฟังก์ชั่นนี้ return เป็น promise\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Execution จะหยุดที่ตรงนี้จนกว่า promise จะ return หลังจาก fetch แล้ว resolved\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user)) // log ข้อมูล response ของ user - ไม่สามารถใช้ syntax await ได้เพราะโค้ดไม่ได้เป็น async function\r\n  .catch(err => console.log(err)); // ถ้า error มีการ thrown ใน async function จะสามารถ catch ได้ที่นี่\r\n```\r\n\r\n#### อธิบายตัวอย่างโค้ด\r\n\r\n*Async / Await* สร้างมาจาก promise แต่ว่าออกแบบมาให้เขียนในรูปแบบที่ง่ายกว่า\r\n\r\n*async* operator จะเปลี่ยนฟังก์ชั่นเป็น asynchronous และจะ return เป็น *Promise* คุณสามารถใช้ *await* operator ใน *async* function เพื่อหยุดการ execution ที่บรรทัดนั้นๆ จนกว่า Promise จะ return ค่ากลับมาโดย resolves หรือ rejects\r\n\r\n```js\r\nasync function myFunc() {\r\n  // เราสามารถใช้ await operator เพราะฟังก์ชั่นนี้กำหนดเป็น async\r\n  return \"hello world\";\r\n}\r\n\r\nmyFunc().then(msg => console.log(msg)) // \"hello world\" -- ค่าที่คืนจากฟังก์ชั่น myFunc จะถูกเปลี่ยนไปเป็น promise เพราะว่ามีการใช้ async operator\r\n```\r\n\r\nเมื่อถึงบรรทัด *return* ของ async function ตัว Promise ที่ได้รับค่าแล้วจะ return กลับไป ถ้าเกิด error และมีการ thrown ข้างใน async function ตัว promise state จะถูกเปลี่ยนเป็น *rejected* และถ้ากรณีไม่มีค่า return จาก async function ตัว promise จะยังคง return และ resolve แบบไม่มีค่ากลับไปเมื่อ async function ทำงานเสร็จสมบูรณ์\r\n\r\n*await* operator จะใช้สำหรับรอ *Promise* จนกว่าจะได้รับค่า และสามารถใช้ได้เฉพาะในฟังก์ชั่นที่เป็น *async* เท่านั้น เมื่อโค้ด execution มาถึงจะหยุดจนกว่า promise จะได้รับการเติมเต็มข้อมูล (fulfilled)\r\n\r\n> **หมายเหตุ :** *fetch* เป็นฟังก์ชั่นที่ return เป็น Promise ที่สามารถทำ AJAX request ได้\r\n\r\nมาดูกันว่าเราสามารถใช้ fetch ข้อมูล github user ด้วย promises ยังไงได้บ้าง:\r\n\r\n```js\r\nfunction getGithubUser(username) {\r\n  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\nและอันนี้คือถ้ากรณีใช้ *async / await* จะเป็นยังไง:\r\n\r\n```js\r\nasync function getGithubUser(username) { // ใช้งาน promise + await ร่วมกัน\r\n  const response = await fetch(`https://api.github.com/users/${username}`); // Execution จะหยุดที่นี่จนกว่าข้อมูลใน Promise จะได้รับการเติมเต็ม (fulfilled)\r\n  return response.json();\r\n}\r\n\r\ngetGithubUser('mbeaudru')\r\n  .then(user => console.log(user))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n*async / await* syntax ทำให้เราสามารถเขียน promise แบบ chain ได้สะดวกสบายมากขึ้น\r\n\r\nยกตัวอย่างเช่น ถ้าเราต้องการเอาค่า token ก่อนเพื่อที่จะนำข้านี้ไป fetch ข้อมูล blog post ที่อยู่ใน database เพื่อเอาข้อมูลคนเขียน post เราจะสามารถให้มันทำงานตามลำดับได้:\r\n\r\n> **หมายเหตุ :** *await* ต้องครอบด้วยวงเล็บเพื่อรอให้เรียก resolve และได้รับค่าก่อน ถึงจะนำไปใช้ต่อได้ถ้าเขียนในบรรทัดเดียวกันหรือเขียนแบบ chain\r\n\r\n```js\r\nasync function fetchPostById(postId) {\r\n  const token = (await fetch('token_url')).json().token;\r\n  const post = (await fetch(`/posts/${postId}?token=${token}`)).json();\r\n  const author = (await fetch(`/users/${post.authorId}`)).json();\r\n\r\n  post.author = author;\r\n  return post;\r\n}\r\n\r\nfetchPostById('gzIrzeo64')\r\n  .then(post => console.log(post))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n##### การจัดการกับ Error\r\n\r\nนอกจากเพิ่ม *try / catch* blocks ครอบการใช้ *await* เพื่อดัก uncaught exceptions แล้ว -  ไม่ว่าอะไรก็ตามที่ thrown ภายใน *async* function หรือว่ามันโดนยกเลิกระหว่าง *await* – จะ reject ตัว promise กลับไปใน *async* function ดังนั้นถ้าใช้ `throw` ใน async function จะเหมือนกับ return ตัว Promise ที่ rejects นั่นเอง [(Ref: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).\r\n\r\n> **หมายเหตุ :** Promises เป็นแบบเดียวกัน!\r\n\r\nเมื่อใช้ Promises เราจะสามารถจัดการกับ error chain ได้แบบนี้:\r\n\r\n```js\r\nfunction getUser() { // Promise อันนี้จะโดน rejected!\r\n  return new Promise((res, rej) => rej(\"User not found !\"));\r\n}\r\n\r\nfunction getAvatarByUsername(userId) {\r\n  return getUser(userId).then(user => user.avatar);\r\n}\r\n\r\nfunction getUserAvatar(username) {\r\n  return getAvatarByUsername(username).then(avatar => ({ username, avatar }));\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\nกรณีถ้าใช้ *async / await*:\r\n\r\n```js\r\nasync function getUser() { // Promise ที่จะ return กลับไปจะ rejected!\r\n  throw \"User not found !\";\r\n}\r\n\r\nasync function getAvatarByUsername(userId) => {\r\n  const user = await getUser(userId);\r\n  return user.avatar;\r\n}\r\n\r\nasync function getUserAvatar(username) {\r\n  var avatar = await getAvatarByUsername(username);\r\n  return { username, avatar };\r\n}\r\n\r\ngetUserAvatar('mbeaudru')\r\n  .then(res => console.log(res))\r\n  .catch(err => console.log(err)); // \"User not found !\"\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n\r\n- [Async/Await - JavaScript.Info](https://javascript.info/async-await)\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/)\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9)\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits)\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n- [Async Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\r\n- [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\r\n- [Using async / await in express with node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n\r\n### Truthy / Falsy\r\n\r\nใน JavaScript ค่า truthy หรือ falsy เป็นค่าที่สามารถถูก casted ไปเป็น boolean เมื่ออยู่ในบริบทที่ต้องกระประเมินค่าเป็น boolean ยกตัวอย่างบริบทของ boolean เมื่อถูกนำไปใช้ใน ```if```:\r\n\r\nค่าทั้งหมดสามารถถูก casted ไปเป็น ```true``` ยกเว้นแต่ว่ามันจะเป็นค่าเหล่านี้:\r\n\r\n- false\r\n- 0\r\n- \"\" (empty string)\r\n- null\r\n- undefined\r\n- NaN\r\n\r\nนี่คือตัวอย่างของ *บริบทของ boolean*:\r\n\r\n- การประเมินค่าเมื่ออยู่ใน ```if``` condition\r\n\r\n```js\r\nif (myVar) {}\r\n```\r\n\r\n```myVar``` สามารถเป็นอะไรก็ได้ [first-class citizen](https://en.wikipedia.org/wiki/First-class_citizen) (ตัวแปร, ฟังก์ชั่น, boolean) แต่มันจะถูก casted ไปเป็น boolean เพราะว่ามันกำลังถูกประเมินอยู่ในบริบทของ boolean\r\n\r\n- การใช้ **NOT** ```!``` operator\r\n\r\noperator นี้จะ return false ถ้า operand สามารถถูก convert ไปเป็น true ได้\r\n\r\n```js\r\n!0 // true -- 0 เป็น falsy ดังนั้นมันจะ returns true\r\n!!0 // false -- 0 เป็น falsy ดังนั้น !0 จะ returns true และดังนั้น !(!0) จะ returns false\r\n!!\"\" // false -- string ว่างเป็น falsy ดังนั้น NOT (NOT false) จะเท่ากับ false\r\n```\r\n\r\n- เมื่อใช้ *Boolean* object constructor\r\n\r\n```js\r\nnew Boolean(0) // false\r\nnew Boolean(1) // true\r\n```\r\n\r\n- ในกรณีใช้ ternary evaluation\r\n\r\n```js\r\nmyVar ? \"truthy\" : \"falsy\"\r\n```\r\n\r\nmyVar ถูกประเมินให้อยู่ในบริบทของ boolean\r\n\r\n### Static Methods\r\n\r\n#### อธิบายสั้นๆ\r\n\r\nคีย์เวิร์ด `static` สามารถใช้ใน class เพื่อประกาศเป็น static method ได้ ตัว static method เป็นฟังก์ชั่นใน class ที่เป็นของ class object และจะไม่ใช่ของตัว instance ของ class นั้นๆ\r\n\r\n#### ตัวอย่างโค้ด\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n}\r\n\r\n//หมายเหตุ เราไม่ได้มีการสร้าง instance จาก Repo class\r\nconsole.log(Repo.getName()) //Repo name คือ modern-js-cheatsheet\r\n\r\nlet r = new Repo();\r\nconsole.log(r.getName()) //Uncaught TypeError: repo.getName is not a function\r\n```\r\n\r\n#### อธิบายรายละเอียด\r\n\r\nStatic method สามารถเรียก static method ตัวอื่นโดยใช้คีย์เวิร์ด `this` ได้ซึ่งจะไม่สามารถทำได้สำหรับ non-static methods และ non-static methods จะไม่สามารถเข้าถึง static method อื่นโดยใช้คีย์เวิร์ด `this` ได้\r\n\r\n##### เรียก static methods อื่นจาก static method\r\n\r\nเพื่อจะเรียก static method จาก static method อื่น ใช้คีย์เวิร์ด `this` แบบนี้ได้:\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  static modifyName(){\r\n    return this.getName() + '-added-this'\r\n  }\r\n}\r\n\r\nconsole.log(Repo.modifyName()) //Repo name คือ modern-js-cheatsheet-added-this\r\n```\r\n\r\n##### เรียก static methods อื่นจาก non-static method\r\n\r\nNon-static methods สามารถเรียก static methods ได้ใน 2 ทาง;\r\n1. ###### ใช้ชื่อ class.\r\n\r\nเพื่อที่จะใช้ static method จาก non-static method เราใช้ชื่อ class และเรียก static method เหมือนเป็น property ตัวอย่างเช่น `ClassName.StaticMethodName`\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    return Repo.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// เราต้องสร้าง instance จาก class ขึ้นมาก่อนเพื่อใช้เป็น non-static methods\r\nlet r = new Repo()\r\nconsole.log(r.useName()) //Repo name คือ modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n2. ###### ใช้ constructor\r\n\r\nStatic methods สามารถเรียกเหมือนเป็น properties ได้ใน constructor object\r\n\r\n```js\r\nclass Repo{\r\n  static getName() {\r\n    return \"Repo name is modern-js-cheatsheet\"\r\n  }\r\n\r\n  useName(){\r\n    //เรียก static method เหมือนเป็น property ของ constructor\r\n    return this.constructor.getName() + ' and it contains some really important stuff'\r\n  }\r\n}\r\n\r\n// เราต้องสร้าง instance จาก class ขึ้นมาก่อนเพื่อใช้เป็น non-static methods\r\nlet r = new Repo()\r\nconsole.log(r.useName()) //Repo name คือ modern-js-cheatsheet and it contains some really important stuff\r\n```\r\n\r\n#### ข้อมูลเพิ่มเติมจากภายนอก\r\n- [static keyword- MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)\r\n- [Static Methods- Javascript.info](https://javascript.info/class#static-methods)\r\n- [Static Members in ES6- OdeToCode](http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx)\r\n\r\n## คำศัพธ์\r\n\r\n### <a name=\"scope_def\"></a> Scope\r\n\r\nบริบทที่ค่าหรือ expression นั้น \"มีตัวตน\" หรือว่าสามารถอ้างอิงถึงได้ ถ้าตัวแปรหรือ expression ไม่ได้เป็น \"อยู่ใน scope นั้นๆ\" จะไม่สามารถใช้ได้\r\n\r\nแหล่งอ้างอิง: [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\r\n\r\n### <a name=\"mutation_def\"></a> Variable mutation\r\n\r\nหมายถึงตัวแปรที่ถูกการแปลงค่า (mutated) จากค่าตั้งต้นและถูกเปลี่ยนในภายหลัง\r\n\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // myArray กำลังถูกแปลงค่า (mutated)\r\n```\r\n\r\nตัวแปรจะถูกเรียกว่า *immutable* ถ้ามันไม่สามารถแปลงค่า (mutated) ได้\r\n\r\n[อ่านบทความ MDN Mutable](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) สำหรับข้อมูลเพิ่มเติม\r\n"
  },
  {
    "path": "JavaScript/translations/zh-CN.md",
    "content": "# Modern JavaScript Cheatsheet 简体中文版\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Image Credits: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n## 简介\r\n\r\n### 初心\r\n\r\n这份文档整理了在当前前端项目中经常需要查阅的内容，并给出了最新的代码示例。\r\n\r\n你或许会因为不熟悉当前一些新的代码库（例如 React）所用到的 JavaScript 概念，而很难上手这些新框架。所以本文档的目的并非从零教你 JavaScript，而是帮助已经有一定编程基础的你。\r\n\r\n除此之外，我（作者：[Manuel Beaudru](https://github.com/mbeaudru)）偶尔会写上一些我的小技巧，也会注意提示这只是我的个人提议。\r\n\r\n> **注：** 这篇文档里提到的大多数概念来自于目前最新的 JavaScript（ES2015，即 ES6），你可以在[这里](http://es6-features.org)查看新增的特性，网站做得很棒。\r\n\r\n### 参考材料\r\n\r\n当你觉得有的概念不容易理解时，你可以在下面的链接里面寻找答案。\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/zh-CN/search?q=)\r\n- [You don't know JS（书）](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 新特性和例子](http://es6-features.org)\r\n- [WesBos 博客中 ES6 类别](http://wesbos.com/category/es6/)\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) 可直接查找特定的博客和资源\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/javascript)\r\n\r\n## 目录\r\n\r\n- [Modern JavaScript Cheatsheet 简体中文版](#Modern-JavaScript-Cheatsheet-简体中文版)\r\n  * [简介](#简介)\r\n    + [初心](#初心)\r\n    + [参考材料](#参考材料)\r\n  * [目录](#目录)\r\n  * [正文](#正文)\r\n    + [变量声明: var, const, let](#变量声明-var-const-let)\r\n      - [简述](#简述)\r\n      - [代码示例](#代码示例)\r\n      - [详述](#详述)\r\n      - [延伸资料](#延伸资料)\r\n    + [箭头函数](#箭头函数)\r\n      - [简述](#简述-1)\r\n      - [详述](#详述-1)\r\n          * [简洁性](#简洁性)\r\n          * [*this* 关键字](#this-关键字)\r\n      - [相关资料](#相关资料)\r\n    + [方法默认参数值](#方法默认参数值)\r\n\r\n## 正文\r\n\r\n### 变量声明： var, const, let\r\n\r\n在 JavaScript 中，声明变量时可以用三个不同的关键词，分别是 `var`，`let` 以及 `const` ，它们各有异同。\r\n\r\n#### 简述\r\n\r\n用 `const` 声明的变量，不能被重新赋值，而另两个 `var` 和 `let` 是可以的。\r\n\r\n所以我建议默认情况下你都用 `const` 来声明变量，在你需要 *改变* 或是声明之后再重新指派它的时候，才用 `let` 来声明变量。\r\n\r\n\r\n| -     | 作用域  | 是否可重新赋值 | 是否可变                       | [暂存死区](#tdz_sample) |\r\n| ----- | ---- | ------- | -------------------------- | ------------------- |\r\n| const | 块级   | ×       | [√](#const_mutable_sample) | √                   |\r\n| let   | 块级   | √       | √                          | √                   |\r\n| var   | 函数   | √       | √                          | ×                   |\r\n\r\n#### 代码示例\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // 因为 person 不能被重新赋值，所以会报错\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\", 使用 let 声明的变量可以重新赋值\r\n```\r\n\r\n#### 详述\r\n\r\n简单来讲，变量的作用域（[*scope*](#scope_def)）是指“在这部分代码中可以访问到此变量”。\r\n\r\n##### var\r\n\r\n使用 `var` 定义的变量，其作用域是定义它的函数内部（*function scoped*），也就是说在函数内部创建一个 `var` 变量的时候，在此函数内部可以任意访问这个变量，但在函数之外，这样的局部变量是无法被访问的。\r\n\r\n我建议你这样理解，如果一个变量是 *X 作用域（scoped）* 类型的，那就是说这个变量是 X 的属性之一。（译注：X 有 function 和 block 两类，代表函数作用域和块级作用域。）\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - 在这个函数中 myVar 可被访问到\r\n}\r\nconsole.log(myVar); // 抛出错误 ReferenceError, 在函数之外 myVar 则无法访问\r\n```\r\n\r\n继续来看变量的作用域，下面有更多精妙的例子：\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // 实际上 myVar 是函数级作用域变量，重新声明的时候，相当于用 \"John\" 抹去了 myVar 之前的值 \"Nick\"\r\n  }\r\n  console.log(myVar); // \"John\" - 可见 if 块中的代码会如何影响变量\r\n}\r\nconsole.log(myVar); // 抛出错误 ReferenceError, 在函数之外 myVar 则无法访问\r\n```\r\n\r\n另外，*var* 声明的变量在执行的时候，就像会被移动到作用域的开始，这就是我们所说的[变量声明提升（var hoisting)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/**var)。\r\n\r\n所以看下面这段代码：\r\n\r\n```javascript\r\nconsole.log(myVar) // undefined -- 没有提示错误\r\nvar myVar = 2;\r\n```\r\n\r\n之所以没有发生错误，是因为它执行时会被解释为这样：\r\n\r\n```javascript\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- 没有提示错误\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n`var` 和 `let` 几乎是一样的，但是用 `let` 声明的变量有如下特性：\r\n\r\n- *块级作用域*（ block scoped )\r\n- 在被赋值之前，是**无法**访问使用的\r\n- 在同一个作用域之下，不能被重新声明\r\n\r\n我们来看看之前例子中提到的块级作用域（ block scoping ）的效果：\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // 实际上 myVar 是块级作用域的变量，在 if 块中，我们相当于是创建了一个新变量，\r\n    // 这个变量在此块之外是无法被访问的，而且它完全区别于我们创建的第一个 myVar 变量！\r\n  }\r\n  console.log(myVar); // \"Nick\", 可见 if 块中的代码，并没有影响到这个变量的值\r\n}\r\nconsole.log(myVar); // 抛出错误 ReferenceError，在函数外部无法访问到 myVar。\r\n```\r\n\r\n<a name=\"tdz_sample\"></a>现在，来看看 *let*（和 *const* ）声明的变量在赋值前无法访问是什么意思：\r\n\r\n```javascript\r\nconsole.log(myVar) // 提示错误 ReferenceError !\r\nlet myVar = 2;\r\n```\r\n\r\n这就是它们和 *var* 变量的区别，如果你在还未赋值给 *let* 或者 *const* 变量之前，就想读写它，是会提示错误的。这种情况常被称作暂存死区（[*Temporal dead zone*](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/let#let_的暂存死区与错误)）或者 *TDZ*。\r\n\r\n> **注意：** 从技术上讲，*let* 和 *const* 变量声明时也存在提升，但并不代表它们的赋值也会被提升。但由于它被设计成了赋值之前无法使用，所以我们直观感觉上它没有被提升，但其实是存在提升的。如果想了解更多细节，请看[这篇文章](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)。\r\n\r\n\r\n另外，在同一作用域内你不能重新声明一个 *let* 变量。\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // 提示语法错误 SyntaxError\r\n```\r\n\r\n##### const\r\n\r\n`const` 声明的变量很像 `let`，但它不能被重新赋值。\r\n\r\n总结一下 `const` 变量的特点如下：\r\n\r\n- *块级作用域*\r\n- 赋值之前无法使用\r\n- 在同一个作用域内部，你不能重新声明一个变量\r\n- 不能被重新指派\r\n\r\n```Javascript\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // 提示错误，不允许重新赋值 const 变量\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a>但这里有一个小细节：`const` 变量并非完全[不可变](#mutation_def)，如果这个变量是 `object` 和 `array` 类型的值，那它的值是**可以改变**的。assign\r\n\r\n对于对象类型来说：\r\n\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // 这会生效的！person 并非完全重新指派（ reassigned ），只是值变化了（ mutated ）\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // 提示错误，因为用 const 声明的变量不能被重新指派\r\n```\r\n\r\n对于数组类型来说：\r\n\r\n```js\r\nconst person = [];\r\nperson.push('John'); // 这也会生效！person 并非完全重新指派（ reassigned ），只是值变化了（ mutated ）\r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // 提示错误，因为用 const 声明的变量不能被重新指派\r\n```\r\n\r\n#### 延伸资料\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"arrow_func_concept\"></a> 箭头函数\r\n\r\nES6 JS 的最新版本已经介绍了*箭头函数*， 箭头函数是以另一种方式声明和使用函数。以下是箭头函数带来的一些好处：\r\n\r\n- 更加简洁\r\n- 从上下文获取*this*\r\n- 隐式的返回方式\r\n\r\n#### 简述\r\n\r\n- 简洁性和隐式的返回方式\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // 传统函数声明方式\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // 同样的函数，使用具有隐式返回方式的箭头函数来表示\r\nconsole.log(double(2)) // 4\r\n```\r\n- *this* 关键字\r\n\r\n在箭头函数中， *this*的值就等于函数所处的封闭的可执行上下文的*this*。简单来说，就是在箭头函数中，当你调用一个位于函数体内部的函数时，在内部函数中，你不需要使用\"that = this\" 这样的声明语句。\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n#### 详述\r\n\r\n##### 简洁性\r\n\r\n箭头函数从很多方面都比传统的函数简洁。案例如下：\r\n\r\n- 隐式返回 VS 显式返回\r\n\r\n**显式返回** 指的是函数的返回语句使用了return 关键字\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // 使用了*return*关键字，显式返回 x * 2\r\n  }\r\n```\r\n\r\n传统函数总是伴随着显式返回。使用箭头函数，你可以使用*隐式返回*，即不需要在函数体内使用return关键字就可以返回值。\r\n\r\n隐式返回需要将所需代码写在一条语句中。\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // 显式返回\r\n  }\r\n```\r\n\r\n鉴于只返回单值，我们可以使用隐式返回。\r\n\r\n```js\r\n  const double = (x) => x * 2;\r\n```\r\n\r\n为实现隐式返回，我们只需要 **移除花括号** 和 **return** 关键字。之所以被称为*隐式*返回，是因为*return*关键字不存在的情况下，函数仍可返回 ```x * 2```。\r\n\r\n> **注意:** 如果你的函数不是返回一个单值（伴有*连带值*），那么既不可以使用显式返回也不可以使用隐式返回。\r\n\r\n除此之外， 如果你想隐式返回一个*object* 则必须使用圆括号对其修饰， \r\n\r\n```js\r\nconst getPerson = () => ({ name: \"Nick\", age: 24 })\r\nconsole.log(getPerson()) // { name: \"Nick\", age: 24 } -- 箭头函数返回的对象\r\n```\r\n\r\n- 函数只有一个参数\r\n\r\n如果你的箭头函数只有一个参数，你可以省略修饰参数的圆括号，重新观察上面的代码：\r\n\r\n```js\r\n  const double = (x) => x * 2; // 箭头函数只有一个参数\r\n```\r\n\r\n参数外面的圆括号可以省略:\r\n\r\n```js\r\n  const double = x => x * 2; // 箭头函数只有一个参数\r\n```\r\n\r\n- 函数无参数\r\n\r\n当箭头函数无参数时，必须使用圆括号，否则会出现语法错误.\r\n\r\n```js\r\n  () => { // 必须提供圆括号\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // 无圆括号，错误!\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n##### *this* 关键字\r\n\r\n要理解箭头函数中this的微妙之处，你必须首先了解JavaScript中[this](#this_def) 的行为。\r\n\r\n在箭头函数中， *this*的值就等于函数所处的封闭可执行上下文的*this*。这句话的意思就是箭头函数不创建一个新的*this*， 而是从其所处的上下文环境中获取。\r\n\r\n没有箭头函数，如果你想要从*this*访问函数内部的函数中的一个变量，你必须使用*that = this*或者*self = this*这样的技巧。\r\n\r\n例如, 使用位于myFunc内部的函数setTimeout:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // that = this \r\n  setTimeout(\r\n    function() { // 在函数的内部创建一个新的\r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // 未定义 -- 请参照上面的函数this定义\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n但是一旦使用箭头函数, *this* 将从包含这个箭头函数的上下文中获取:\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // 从上下文中获取this, 在这里就是 myFunc\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n#### 相关资料\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n#### 方法默认参数值\r\n\r\n从 ES2015 以后开始，你可以使用下面的语法，给你的方法参数来设置默认值\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- 没有值传入，所以默认的值10传给了myFunc\r\nconsole.log(myFunc(5)) // 5 -- 一个值被传入，所以x等于5 \r\nconsole.log(myFunc(undefined)) // 10 -- undefined 值提供了，所以默认值关联了x\r\nconsole.log(myFunc(null)) // null -- 提供了 (null) , 见一下详细解释\r\n```\r\n默认参数有且只有在以下两种情况下才会生效：\r\n- 没有参数提供的时候\r\n- *undefined* 参数被提供的时候\r\n\r\n换句话说，如果你传入*NULL* 默认值**将不会生效**\r\n"
  },
  {
    "path": "JavaScript/translations/zh-TW.md",
    "content": "<a name=\"#modern-javascript-cheatsheet\"></a>\r\n# Modern JavaScript Cheatsheet 繁體中文版\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>圖片來源: [Ahmad Awais ⚡️](https://github.com/ahmadawais)</small>\r\n\r\n### 譯者的話\r\n> 原標題：[mbeaudru/modern-js-cheatsheet](https://github.com/mbeaudru/modern-js-cheatsheet)\r\n>\r\n> 原作者：[BEAUDRU Manuel](https://github.com/mbeaudru)\r\n> \r\n> 對於現代 JavaScript 開發而言，這篇文章整理了不少知識點，當作複習或是學習都很不錯。自己一直以來都是做為讀者的角色，很少主動為整個開源社群做些實際貢獻，這點一直感到蠻慚愧的，就像是 Sublime 是啟蒙你寫程式的第一個 editor，當你開始工作賺錢後卻遲遲不買 license 是類似的道理。趁著短暫的假日譯者盡可能的把翻譯做到盡善盡美，畢竟不是專業的，要做到信達雅的程度其實不太可能，但過程中確實查閱了不少相關資料，部分關鍵字因為怕超譯所以會在後頭括號保留原文。\r\n>\r\n> 另外也想藉著這回翻譯的經驗說點八股的，英文真的天殺的重要，能夠直接閱讀原文始終是最能理解原意的方式。整篇 cheatsheet 從意譯的角度出發，詞意有所疑問或是理解錯誤都煩請發個 Pull Request 謝謝。\r\n>\r\n> 2017/09/30 Update\r\n>\r\n> 昨天晚上收到簡體中文譯者的來信提醒，才發現原來 Issue 內早已有社群朋友 @BirkhoffLee 正在做繁體中文的翻譯 ([詳情可見此討論串](https://github.com/mbeaudru/modern-js-cheatsheet/issues/15))，真的很抱歉昨天才驚覺這件事，譯者在這裡推薦大家如果有空也可以多多瀏覽  @BirkhoffLee 翻譯過的 [機器學習動手玩](https://github.com/humphd/have-fun-with-machine-learning/blob/master/README_zh-tw.md) 以及相關專案，他也是位對於開源社群推廣非常積極的開發者。最後關於這份繁體中文文件，譯者會在這一兩天回顧下文件翻譯用詞有無需要調整的地方，確認過後便會 merge 回原作者的 repo，大概是醬。\r\n\r\n<a name=\"introduction\"></a>\r\n## 介紹\r\n\r\n<a name=\"motivation\"></a>\r\n### 動機\r\n\r\n本文檔整理了各種現代化 JavaScript 開發過程中經常使用到的腳本。\r\n\r\n該份指南的目標並不是放在幫助初學者從零基礎到入門，而是為了幫助那些因為 JavaScript 新式語法導致可能很難熟悉現代函數庫使用方式 (以 React 做為舉例) 的開發人員。\r\n\r\n此外我也會偶爾提供一些個人主觀的建議和技巧，而這些建議可能會造成部分的爭議性，但請務必留意，當我做出這些舉例時這僅僅是出自於個人的推薦作法。\r\n\r\n> **注意:** 此處介紹的大部分概念出自於 JavaScript 的語言更新 (ES2015，更多人稱其作 ES6)。你可以在[這個好地方](http://es6-features.org)找到更多添加的新功能。\r\n\r\n<a name=\"complementary-resources\"></a>\r\n### 配套資源\r\n\r\n當你在試圖理解一個新概念時，我建議你可以去瀏覽以下這些資源尋找解答：\r\n\r\n- [MDN (Mozilla Developer Network)](https://developer.mozilla.org/fr/search?q=)\r\n- [You don't know JS (book)](https://github.com/getify/You-Dont-Know-JS)\r\n- [ES6 Features with examples](http://es6-features.org)\r\n- [WesBos blog (ES6)](http://wesbos.com/category/es6/)\r\n- [Reddit (JavaScript)](https://www.reddit.com/r/javascript/)\r\n- [Google](https://www.google.com/) 搜尋特定相關主題的部落格文章和資源\r\n\r\n<a name=\"table-of-contents\"></a>\r\n## 目錄\r\n\r\n- [Modern JavaScript cheatsheet 繁體中文版](#modern-javascript-cheatsheet)\r\n  * [介紹](#introduction)\r\n    + [動機](#motivation)\r\n    + [配套資源](#complementary-resources)\r\n  * [目錄](#table-of-contents)\r\n  * [概念](#notions)\r\n    + [變數聲明： var, const, let](#variable-declaration-var-const-let)\r\n      - [簡短解釋](#short-explanation-1)\r\n      - [範例程式碼](#sample-code-2)\r\n      - [詳細說明](#detailed-explanation-3)\r\n      - [外部資源](#external-resource-4)\r\n    + [箭頭函數](#-arrow-function-4)\r\n      - [範例程式碼](#sample-code-5)\r\n      - [詳細說明](#detailed-explanation-6)\r\n        * [簡潔性](#concision-7)\r\n        * [*this* 關鍵字參照](#this-reference-8)\r\n      - [有用資源](#useful-resources-9)\r\n    + [函數預設值](#function-default-parameter-value-10)\r\n      - [外部資源](#external-resource-11)\r\n    + [objects 和 arrays 的解構](#destructuring-objects-and-arrays-12)\r\n      - [說明和範例程式碼](#explanation-with-sample-code-13)\r\n      - [有用資源](#useful-resources-14)\r\n    + [Array 的操作方法 - map / filter / reduce](#array-methods---map--filter--reduce-15)\r\n      - [範例程式碼](#sample-code-16)\r\n      - [說明](#explanation-17)\r\n        * [Array.prototype.map()](#arrayprototypemap-18)\r\n        * [Array.prototype.filter()](#arrayprototypefilter-19)\r\n        * [Array.prototype.reduce()](#arrayprototypereduce-20)\r\n      - [外部資源](#external-resource-21)\r\n    + [展開運算子 \"...\"](#spread-operator-22)\r\n      - [範例程式碼](#sample-code-23)\r\n      - [說明](#explanation-24)\r\n        * [迭代用法 (如同 array)](#in-iterables-like-array-25)\r\n        * [不定參數](#function-rest-parameter-26)\r\n        * [Object 屬性擴展](#object-properties-spreading-27)\r\n      - [外部資源](#external-resources-28)\r\n    + [Object 屬性簡寫](#object-property-shorthand-29)\r\n      - [說明](#explanation-30)\r\n      - [外部資源](#external-resources-31)\r\n    + [Promises](#promises-32)\r\n      - [範例程式碼](#sample-code-33)\r\n      - [說明](#explanation-34)\r\n        * [創造 promise](#create-the-promise-35)\r\n        * [使用 promise](#use-the-promise-36)\r\n      - [外部資源](#external-resources-37)\r\n    + [模板字符串](#template-literals-38)\r\n      - [範例程式碼](#sample-code-39)\r\n      - [外部資源](#external-resources-40)\r\n    + [Imports / Exports](#imports--exports-41)\r\n      - [說明與範例程式碼](#explanation-with-sample-code-42)\r\n      - [外部資源](#external-resources-43)\r\n    + [JavaScript *this*](#-javascript-this-44)\r\n      - [外部資源](#external-resources-45)\r\n    + [Class](#class-46)\r\n      - [範例](#samples-47)\r\n      - [外部資源](#external-resources-48)\r\n    + [Async Await](#async-await-49)\r\n      - [範例程式碼](#sample-code-50)\r\n      - [說明](#explanation-51)\r\n      - [外部資源](#external-resources-52)\r\n  * [術語詞彙](#glossary-53)\r\n    + [作用域範圍](#-scope-54)\r\n    + [變數變異](#-variable-variance-55)\r\n\r\n<a name=\"notions\"></a>\r\n## 概念\r\n\r\n<a name=\"variable-declaration-var-const-let\"></a>\r\n### 變數聲明： var, const, let\r\n\r\n在 JavaScript 中有三個不同關鍵字可用於宣告一個變數，分別是 ```var```， ```let``` 和 ```const```。\r\n\r\n<a name=\"short-explanation-1\"></a>\r\n#### 簡短解釋\r\n\r\n使用 ```const``` 關鍵字宣告的變數無法被重新指派, 而 ```let``` 和 ```var``` 是可以的。\r\n\r\n我會建議在默認情況下一律使用 ```const``` ，當你需要<i>改變</i>它或是稍後才重新指派時才使用 ```let``` 。\r\n\r\n<table>\r\n  <tr>\r\n    <th></th>\r\n    <th>作用域範圍</th>\r\n    <th>是否可重新指派</th>\r\n    <th>狀態變更</th>\r\n   <th><a href=\"#tdz_sample\">暫時性死區 (Temporal Dead Zone)</a></th>\r\n  </tr>\r\n  <tr>\r\n    <th>const</th>\r\n    <td>區塊</td>\r\n    <td>不是</td>\r\n    <td><a href=\"#const_mutable_sample\">是</a></td>\r\n    <td>是</td>\r\n  </tr>\r\n  <tr>\r\n    <th>let</th>\r\n    <td>區塊</td>\r\n    <td>是</td>\r\n    <td>是</td>\r\n    <td>是</td>\r\n  </tr>\r\n   <tr>\r\n    <th>var</th>\r\n    <td>函數</td>\r\n    <td>是</td>\r\n    <td>是</td>\r\n    <td>不是</td>\r\n  </tr>\r\n</table>\r\n\r\n<a name=\"sample-code-2\"></a>\r\n#### 範例程式碼\r\n\r\n```javascript\r\nconst person = \"Nick\";\r\nperson = \"John\" // 會有錯誤跳出，person 不能被重新指派\r\n```\r\n\r\n```javascript\r\nlet person = \"Nick\";\r\nperson = \"John\";\r\nconsole.log(person) // \"John\" 在 let 的使用下允許被重新指派\r\n```\r\n\r\n<a name=\"detailed-explanation-3\"></a>\r\n#### 詳細說明\r\n\r\n變數的 [*作用域範圍 (scope)*](#scope_def) 大致上意味著 \"這個變數的效力可被作用在哪段程式碼 (where is this variable available in the code)\"。\r\n\r\n##### var\r\n\r\n```var``` 宣告的變數是 *函數範圍 (function scoped)* 的，這表示當函數中創造變數的時候，該函數中的所有內容都可以訪問並使用該變數。相反的，在函數外創造的 *區塊範圍 (block scoped)* 變數則無法被使用。\r\n\r\n我會建議你把它看作是一個 *X scoped* 範圍的變數代表著這個變數是 X 的屬性之一。\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  console.log(myVar); // \"Nick\" - myVar 可以在函數範圍之內被使用\r\n}\r\nconsole.log(myVar); // Undefined, myVar 在函數範圍外部無法被使用\r\n```\r\n\r\n持續觀察變數的作用域範圍，這裡有個更細微的範例：\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  var myVar = \"Nick\";\r\n  if (true) {\r\n    var myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // actually, myVar 是函數範圍之內的，我們剛剛覆蓋了之前的 myVar 變數，值從 \"Nick\" 變成 \"John\"\r\n  }\r\n  console.log(myVar); // \"John\" - 印出來看看區塊如何影響 myVar 這個變數的值\r\n}\r\nconsole.log(myVar); // Undefined, myVar 在函數範圍外部無法被使用\r\n```\r\n\r\n此外， *var* 宣告出來的變數在程式執行之時就會被移到作用域的頂部。這個就是我們所說的[變數提升 (var hoisting)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting)。\r\n\r\n這段程式碼：\r\n\r\n```js\r\nconsole.log(myVar) // undefined -- 沒有錯誤發生\r\nvar myVar = 2;\r\n```\r\n\r\n在程式執行過程中被解讀為：\r\n\r\n```js\r\nvar myVar;\r\nconsole.log(myVar) // undefined -- 沒有錯誤發生\r\nmyVar = 2;\r\n```\r\n\r\n##### let\r\n\r\n```var``` 和 ```let ``` 大致上行為相同， ```let``` 在宣告變數時\r\n\r\n- 作用域是 *區塊範圍 (block scoped)*\r\n- 在被指派值以前 **無法** 被存取使用\r\n- 同一個作用域之下不能被重新宣告\r\n\r\n採用我們前面的例子來看看區塊範圍 (block scoped) 的影響：\r\n\r\n```javascript\r\nfunction myFunction() {\r\n  let myVar = \"Nick\";\r\n  if (true) {\r\n    let myVar = \"John\";\r\n    console.log(myVar); // \"John\"\r\n    // 事實上，myVar 是區塊範圍之內的，我們剛剛創造了一個全新的 myVar 變數\r\n    // 這個變數是無法從區塊範圍以外的地方存取，\r\n    // 而且它也是完全獨立於我們創造的第一個 myVar 變數！\r\n  }\r\n  console.log(myVar); // \"Nick\", 查看 if 區塊中的程式會不會影響到 myVar 這個值\r\n}\r\nconsole.log(myVar); // Undefined, myVar 在函數範圍外部無法被使用\r\n```\r\n\r\n<a name=\"tdz_sample\"></a> 現在我們來看看 *let* ( 和 *const* ) 變數在被賦值以前無法被使用是什麼意思：\r\n\r\n```js\r\nconsole.log(myVar) // 觸發 ReferenceError 錯誤!\r\nlet myVar = 2;\r\n```\r\n\r\n和 *var* 變數比較之下，如果在指派 *let* 或是 *const* 變數的值之前嘗試讀取或是寫入的動作是會引發錯誤的。這種現象通常被稱之為 [*Temporal dead zone*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) 或者是 *TDZ*。\r\n\r\n> **注意：** 技術上而言， *let* 和 *const* 變數在聲明時也是會被提升的，但並不是指它們的賦值。因為他們在被指派之前是不能使用的，所以直觀上就像是沒有提升一樣，但它們其實是有的。如果你想知道更多的話請查看 [更加詳細解釋的這篇文章](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)。\r\n\r\n此外，你不能重新宣告一個 *let* 變數：\r\n\r\n```js\r\nlet myVar = 2;\r\nlet myVar = 3; // 跳出 SyntaxError 錯誤\r\n```\r\n\r\n##### const\r\n\r\n```const``` 宣告出來的行為如同 *let* 變數，但它們同樣都不能被重新宣告。\r\n\r\n總結一下， *const* 變數：\r\n\r\n- 作用域是 *區塊範圍 (block scoped)*\r\n- 在被指派值以前 **無法** 被存取使用\r\n- 同一個作用域之下不能被重新宣告\r\n- 無法被重新指派新值\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nmyVar = \"John\" // 跳出錯誤，不允許重新指派新值\r\n```\r\n\r\n```js\r\nconst myVar = \"Nick\";\r\nconst myVar = \"John\" // 跳出錯誤， 重新宣告是不被允許的\r\n```\r\n\r\n<a name=\"const_mutable_sample\"></a> 但有個精妙之處 : ```const``` 變數不是[**不可變的**](#mutation_def) ! 更具體而言，這代表著 *object* 和 *array* 中由 ```const``` 宣告出來的變數是 **可以** 被改變的。\r\n\r\n對於 objects：\r\n\r\n```js\r\nconst person = {\r\n  name: 'Nick'\r\n};\r\nperson.name = 'John' // 這完全可行！ person 這個變數尚未完全被重新指派，但它確實改變了\r\nconsole.log(person.name) // \"John\"\r\nperson = \"Sandra\" // 跳出錯誤，因為重新指派時是不允許使用 const 宣告出來的變數的\r\n```\r\n\r\n對於 arrays：\r\n\r\n```js\r\nconst person = [];\r\nperson.push('John'); // 這完全可行！ person 這個變數尚未完全被重新指派，但它確實改變了 \r\nconsole.log(person[0]) // \"John\"\r\nperson = [\"Nick\"] // 跳出錯誤，因為重新指派時是不允許使用 const 宣告出來的變數的\r\n```\r\n\r\n<a name=\"external-resource-4\"></a>\r\n#### 外部資源\r\n\r\n- [How let and const are scoped in JavaScript - WesBos](http://wesbos.com/javascript-scoping/)\r\n- [Temporal Dead Zone (TDZ) Demystified](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified)\r\n\r\n### <a name=\"-arrow-function-4\"></a> 箭頭函數\r\n\r\nES6 的更新正式引入了 *箭頭函數 (arrow functions)*，這是另外一種宣告和使用函數的方法。以下是它們所帶來的好處：\r\n\r\n- 更為簡潔\r\n- *this* 的值繼承自外圍作用域 (*this* is picked up from surroundings)\r\n- 隱式回傳 (implicit return)\r\n\r\n<a name=\"sample-code-5\"></a>\r\n#### 範例程式碼\r\n\r\n- 簡潔性和隱式回傳 (implicit return)\r\n\r\n```js\r\nfunction double(x) { return x * 2; } // 傳統作法\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n```js\r\nconst double = x => x * 2; // 仍然是同樣的函數，寫成帶有隱式回傳的作法\r\nconsole.log(double(2)) // 4\r\n```\r\n\r\n- *this* 關鍵字參照\r\n\r\n在箭頭函數中， *this* 意味著封閉執行上下文的 *這個值*。基本上，透過使用箭頭函數，在函數中調用函數之前，你不需要去使用像是 \"that = this\" 這樣的用法。\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(() => {\r\n    this.myVar++;\r\n    console.log(this.myVar) // 1\r\n  }, 0);\r\n}\r\n```\r\n\r\n<a name=\"detailed-explanation-6\"></a>\r\n#### 詳細說明\r\n\r\n<a name=\"concision-7\"></a>\r\n##### 簡潔性\r\n\r\n箭頭函數在諸多方面都較傳統函數來的更為簡潔。讓我們來看看所有可能的情況：\r\n\r\n- 隱式回傳 VS 顯式回傳\r\n\r\n **顯式回傳 (explicit return)** 是指在函數中明確的使用 *return* 這個關鍵字。\r\n\r\n```js\r\n  function double(x) {\r\n    return x * 2; // 這個函數顯式回傳了 x * 2，並且使用了 return 這個關鍵字\r\n  }\r\n```\r\n\r\n以傳統的作法撰寫，return 永遠都會是顯式的。但是如果是使用箭頭函數，你可以執行隱式回傳，這同時代表著你不需要使用關鍵字 return 去取得回傳值。\r\n\r\n要做隱式回傳，程式碼必須用一行句子撰寫。\r\n\r\n```js\r\n  const double = (x) => {\r\n    return x * 2; // 此處顯示 return 值\r\n  }\r\n```\r\n\r\n由於這裡只有一個回傳值，我們可以做一個隱式回傳。\r\n\r\n```js\r\n const double = (x) => x * 2;\r\n```\r\n\r\n做到上述的轉換，我們只需要 **移除括號** 以及 **return** 這個關鍵字。這就是為什麼它會被稱為 *隱式* 回傳，*return* 關鍵字不在了，但是這個函數確實會回傳 ```x * 2```。\r\n\r\n> **注意：** 如果你的函數沒有回傳一個值 (這種作法有 *副作用*)，那麼它將不屬於顯式或是隱式返回中的任一種。\r\n\r\n- 只有一個參數\r\n\r\n如果你的函數只接受一個參數，你可以省略它周圍的括號。如果我們拿上述的 *double* 程式碼做為舉例：\r\n\r\n```js\r\n const double = (x) => x * 2; // 這個箭頭函數只接受一個參數\r\n```\r\n\r\n括號是可以被省略的：\r\n\r\n```js\r\n const double = x => x * 2; // 這個箭頭函數只接受一個參數\r\n```\r\n\r\n- 沒有參數\r\n\r\n當沒有為箭頭函數提供任何參數時，你就必須加上括號，否則語法將會出錯。\r\n\r\n```js\r\n  () => { // 有加上括號，一切都正常運作\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n```js\r\n  => { // 沒有括號，這樣的語法是行不通的！\r\n    const x = 2;\r\n    return x;\r\n  }\r\n```\r\n\r\n<a name=\"this-reference-8\"></a>\r\n##### *this* 關鍵字參照\r\n\r\n要理解箭頭函數的精妙之處，你一定要清楚 [this](#this_def) 在 JavaScript 中是如何運作的。\r\n\r\n在一個箭頭函數當中，*this* 等同於封閉執行上下文的 *這個值* 。意思就是說，一個箭頭函數並不會創造一個新的 *this*，而是從它的外圍作用域一併抓起。\r\n\r\n沒有箭頭函數的這項功能，如果你想要取得位於函數的函數內部由 *this* 參照的變數，你就只能使用 *that = this* 或者是 *self = this* 這樣的技巧。\r\n\r\n舉例來說，你在 myFunc 函數中使用 setTimeout 函數：\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  var that = this; // 使用 that = this 這個技巧\r\n  setTimeout(\r\n    function() { // 創造了一個新的 this \r\n      that.myVar++;\r\n      console.log(that.myVar) // 1\r\n\r\n      console.log(this.myVar) // undefined -- 詳見上述的函數宣告\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n但如果你使用了箭頭函數，*this* 的範圍將會是它的外圍作用域：\r\n\r\n```js\r\nfunction myFunc() {\r\n  this.myVar = 0;\r\n  setTimeout(\r\n    () => { // this 的值來自於它的外圍作用域，也就是 myFunc 函數\r\n      this.myVar++;\r\n      console.log(this.myVar) // 1\r\n    },\r\n    0\r\n  );\r\n}\r\n```\r\n\r\n<a name=\"useful-resources-9\"></a>\r\n#### 有用資源\r\n\r\n- [Arrow functions introduction - WesBos](http://wesbos.com/arrow-functions/)\r\n- [JavaScript arrow function - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\r\n- [Arrow function and lexical *this*](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)\r\n\r\n<a name=\"function-default-parameter-value-10\"></a>\r\n### 函數預設值\r\n\r\n從 ES2015 JavaScript 更新之後，你可以透過下列的語法為函數中的參數設定預設值：\r\n\r\n```js\r\nfunction myFunc(x = 10) {\r\n  return x;\r\n}\r\nconsole.log(myFunc()) // 10 -- 沒有提供任何值，所以 10 在 myFunc 中做為預設值指派給 x\r\nconsole.log(myFunc(5)) // 5 -- 有提供一個參數值，所以 x 在 myFunc 中等於 5   \r\n\r\nconsole.log(myFunc(undefined)) // 10 -- 未定義的值，所以預設值被指派給 x\r\nconsole.log(myFunc(null)) // null -- 提供一個值 (null)，詳細資料請見下文\r\n```\r\n\r\n預設值若且為若應用在兩種情況：\r\n\r\n- 沒有傳入任何參數\r\n- 傳入 *undefined* 這個參數\r\n\r\n換句話說，如果你傳入的是 *null* ，那麼預設值的機制是不會被觸發的。\r\n\r\n> **注意：** 預設值的指派可以搭配解構參數一同使用 (參照下一個概念的實際例子)\r\n\r\n<a name=\"external-resource-11\"></a>\r\n#### 外部資源\r\n\r\n- [Default parameter value - ES6 Features](http://es6-features.org/#DefaultParameterValues)\r\n- [Default parameters - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\r\n\r\n<a name=\"destructuring-objects-and-arrays-12\"></a>\r\n### objects 和 arrays 的解構\r\n\r\n*解構 (Destructuring)* 的概念是從 objects 或是 arrays 當中提取部分用值一種相當方便的方法。\r\n\r\n舉個簡單的實例，*destructuring* 可以被用來解構函數中的參數或者像是 React 專案中 *this.props* 這樣的用法。\r\n\r\n<a name=\"explanation-with-sample-code-13\"></a>\r\n#### 說明和範例程式碼\r\n\r\n- Object\r\n\r\n試著想想以下這個 object：\r\n\r\n```js\r\nconst person = {\r\n  firstName: \"Nick\",\r\n  lastName: \"Anderson\",\r\n  age: 35,\r\n  sex: \"M\"\r\n}\r\n```\r\n\r\n沒有解構的作法，你只能這樣做：\r\n\r\n```js\r\nconst first = person.firstName;\r\nconst age = person.age;\r\nconst city = person.city || \"Paris\";\r\n```\r\n\r\n使用解構，你只需要一行：\r\n\r\n```js\r\nconst { firstName: first, age, city = \"Paris\" } = person; // 這樣就搞定了！\r\n\r\nconsole.log(age) // 35 -- 一個名為 age 的新變數被創建出來了，其值等同於 person.age\r\nconsole.log(first) // \"Nick\" -- 一個名為 first 的新變數被創建出來了，其值等同於person.firstName\r\nconsole.log(firstName) // ReferenceError -- person.firstName 雖然存在，但其值是存在名叫 first 的新變數\r\nconsole.log(city) // \"Paris\" -- 一個名為 city 的新變數被創建出來了，同時因為 person.city 是未被定義的，所以 city 將等同於預設值也就是 \"Paris\"。\r\n```\r\n\r\n**注意：** 在 ```const { age } = person;```當中， *const* 後的括號並不是用來宣告 object 或者是區塊，僅僅是 *解構 (destructuring)* 的使用語法。\r\n\r\n- 帶有參數的函數用法\r\n\r\n*解構 (Destructuring)* 經常被用來解 objects 中的參數。\r\n\r\n沒有解構的作法，你只能這樣做：\r\n\r\n```js\r\nfunction joinFirstLastName(person) {\r\n  const firstName = person.firstName;\r\n  const lastName = person.lastName;\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n在解構 obejct 當中 *person* 這個參數時，我們可以得到一個更簡潔的函數：\r\n\r\n```js\r\nfunction joinFirstLastName({ firstName, lastName }) { \r\n  // 我們透過解構 person 分別創造了 firstName 和 lastName 這兩個變數\r\n  return firstName + '-' + lastName;\r\n}\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n解構搭配[箭頭函數](#arrow_func_concept)使得開發過程更加愉快：\r\n\r\n```js\r\nconst joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;\r\n\r\njoinFirstLastName(person); // \"Nick-Anderson\"\r\n```\r\n\r\n- Array\r\n\r\n讓我們來想想下列這個 array：\r\n\r\n```js\r\nconst myArray = [\"a\", \"b\", \"c\"];\r\n```\r\n\r\n沒有解構的作法，你只能這樣做：\r\n\r\n```js\r\nconst x = myArray[0];\r\nconst y = myArray[1];\r\n```\r\n\r\n使用解構的作法：\r\n\r\n```js\r\nconst [x, y] = myArray; // 就是這麼簡單！\r\n\r\nconsole.log(x) // \"a\"\r\nconsole.log(y) // \"b\"\r\n```\r\n\r\n<a name=\"useful-resources-14\"></a>\r\n#### 有用資源\r\n\r\n- [ES6 Features - Destructuring Assignment](http://es6-features.org/#ArrayMatching)\r\n- [Destructuring Objects - WesBos](http://wesbos.com/destructuring-objects/)\r\n- [ExploringJS - Destructuring](http://exploringjs.com/es6/ch_destructuring.html)\r\n\r\n<a name=\"array-methods---map--filter--reduce-1\"></a>\r\n### Array 的操作方法 - map / filter / reduce\r\n\r\n*Map*，*filter* 和 *reduce* 都是 array 提供的方法，它們源自於 [*functional programming*](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0) 開發範式。\r\n\r\n總結一下：\r\n\r\n- **Array.prototype.map()** 接受一組 array，針對其中的元素進行某些操作和轉換的動作。\r\n- **Array.prototype.filter()** 接受一組 array，依照元素本身決定是否保留，並且將會回傳一個僅含有保留元素的 array\r\n- **Array.prototype.reduce()** 接受一組 array，將這些元素合併成一個值並回傳\r\n\r\n我會建議在開發時盡可能的遵循函數式編程 (functional programming) 的原則，因為它們是可組合的，簡潔且優雅的。\r\n\r\n透過這三種方法，你將可以避免在大多數情況下使用 *for* 和 *forEach*。當你想做一個 *for* 迴圈時，試著用 *map*，*filter* 和 *reduce* 組合看看。起初你可能會覺得窒礙難行，因為它需要你學習一種新的思維方式，但一旦你掌握它了，事情也將變得更加容易。\r\n\r\n<a name=\"sample-code-16\"></a>\r\n#### 範例程式碼\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\nconst doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]\r\nconst evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]\r\nconst sum = numbers.reduce((prev, next) => prev + next, 0); // 21\r\n```\r\n\r\n透過 map，filter 和 reduce 這幾種組合技去計算出學生成績 >= 10 的總和：\r\n\r\n```js\r\nconst students = [\r\n  { name: \"Nick\", grade: 10 },\r\n  { name: \"John\", grade: 15 },\r\n  { name: \"Julia\", grade: 19 },\r\n  { name: \"Nathalie\", grade: 9 },\r\n];\r\n\r\nconst aboveTenSum = students\r\n  .map(student => student.grade) // map the students array to an array of their grades\r\n  .filter(grade => grade >= 10) // we filter the grades array to keep those 10 or above\r\n  .reduce((prev, next) => prev + next, 0); // we sum all the grades 10 or above one by one\r\n\r\nconsole.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie below 10 is ignored\r\n```\r\n\r\n<a name=\"explanation-17\"></a>\r\n#### 說明\r\n\r\n讓我們來思考下列這個 array：\r\n\r\n```js\r\nconst numbers = [0, 1, 2, 3, 4, 5, 6];\r\n```\r\n\r\n<a name=\"arrayprototypemap-18\"></a>\r\n##### Array.prototype.map()\r\n\r\n```js\r\nconst doubledNumbers = numbers.map(function(n) {\r\n  return n * 2;\r\n});\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n發生了什麼事？我們在 *numbers* 這個 array 中使用了 .map 方法，map 將會去迭代 array 中的每一個元素並且回傳給我們的函數。該函數的目標是生成並回傳一個新的值使得 map 可以替換掉原本的 array。\r\n\r\n讓我們提取這個函數以便讓解釋更清楚：\r\n\r\n```js\r\nconst doubleN = function(n) { return n * 2; };\r\nconst doubledNumbers = numbers.map(doubleN);\r\nconsole.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]\r\n```\r\n\r\n```numbers.map(doubleN)``` 將會產生 ```[doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)]``` ，而它們分別等同於 ```[0, 2, 4, 6, 8, 10, 12]```。\r\n\r\n> **注意：** 如果你不需要回傳一個新的 array 且只想實作一個帶有副作用的迴圈，使用 for / forEach 迴圈會更為符合你所需。\r\n\r\n<a name=\"arrayprototypefilter-19\"></a>\r\n##### Array.prototype.filter()\r\n\r\n```js\r\nconst evenNumbers = numbers.filter(function(n) {\r\n  return n % 2 === 0; // true if \"n\" is par, false if \"n\" isn't\r\n});\r\nconsole.log(evenNumbers); // [0, 2, 4, 6]\r\n```\r\n\r\n我們在這個充滿 *numbers* 的 array 上使用 .filter 方法，過濾器將會遍歷當中的每一個元素並回傳給我們的函數。函數的目標是回傳一個布林值，它將會確定當前值是否被保留。過濾之後回傳的是一個僅保留所需值的 array。\r\n\r\n<a name=\"arrayprototypereduce-20\"></a>\r\n##### Array.prototype.reduce()\r\n\r\nreduce 方法的目標是將進行迭代的 array 中的所有元素 *減少* 到只留下單一值。計算這些元素的方式將取決於你的需求。\r\n\r\n```js\r\nconst sum = numbers.reduce(\r\n  function(acc, n) {\r\n    return acc + n;\r\n  },\r\n  0 // 進行迭代計算的初始值\r\n);\r\n\r\nconsole.log(sum) //21\r\n```\r\n\r\n就像 .map 和 .filter 方法一樣， .reduce 方法被應用在 array 上並將函數做為第一個參數。\r\n\r\n\r\n這次有些變化了：\r\n\r\n- .reduce 接受兩個參數\r\n\r\n第一個參數是在每個迭代步驟中調用的函數。\r\n\r\n第二個參數是在第一個迭代步驟（讀取下一個之用）的累加器變數的值（此處是 *acc*）。\r\n\r\n- 帶有參數的函數用法\r\n\r\n做為 .reduce 的第一個參數所傳遞的函數需要兩個參數。第一個（此處是 *acc*）是累加器變數，而第二個參數（*n*）則是當前元素。\r\n\r\n累加器變數的值等於 **上一次** 迭代步驟中函數的回傳值。在迭代過程的第一步，*acc* 等於你做為 .reduce 時第二個參數所傳遞的值。\r\n\r\n###### 進行第一次迭代\r\n\r\n```acc = 0``` 因為我們把 0 做為 reduce 的第二個參數\r\n\r\n```n = 0```  *number* array 的第一個元素\r\n\r\n函數回傳 *acc* + *n* --> 0 + 0 --> 0\r\n\r\n###### 進行第二次迭代\r\n\r\n```acc = 0``` 因為它是上次迭代所回傳的值 \r\n\r\n```n = 1``` *number* array 的第二個元素\r\n\r\n函數回傳 *acc* + *n* --> 0 + 1 --> 1\r\n\r\n###### 進行第三次迭代\r\n\r\n```acc = 1``` 因為它是上次迭代所回傳的值 \r\n\r\n```n = 2``` *number* array 的第三個元素\r\n\r\n函數回傳 *acc* + *n* --> 1 + 2 --> 3\r\n\r\n###### 進行第四次迭代\r\n\r\n```acc = 3``` 因為它是上次迭代所回傳的值\r\n\r\n```n = 3``` *number* array 的第四個元素\r\n\r\n函數回傳 *acc* + *n* --> 3 + 3 --> 6\r\n\r\n###### [...] 進行最後一次迭代\r\n\r\n```acc = 15``` 因為它是上次迭代所回傳的值\r\n\r\n```n = 6``` *number* array 的最後一個元素\r\n\r\n函數回傳 *acc* + *n* --> 15 + 6 --> 21\r\n\r\n因為它是最後一個迭代步驟了， **.reduce** 將回傳 21。\r\n\r\n<a name=\"external-resource-21\"></a>\r\n#### 外部資源\r\n\r\n- [Understanding map / filter / reduce in JS](https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464)\r\n\r\n<a name=\"spread-operator-22\"></a>\r\n### 展開運算子 \"...\"\r\n\r\n展開運算子 ```...``` 的語法在 ES2015 之下已經支援了，而它將會被用於把可迭代的元素 (像是 array) 擴展到容納更多元素。\r\n\r\n<a name=\"sample-code-23\"></a>\r\n#### 範例程式碼\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nfunction myFunc(x, y, ...params) {\r\n  console.log(x);\r\n  console.log(y);\r\n  console.log(params)\r\n}\r\n\r\nmyFunc(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\r\n// \"a\"\r\n// \"b\"\r\n// [\"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n```js\r\nconst { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n```\r\n\r\n<a name=\"explanation-24\"></a>\r\n#### 說明\r\n\r\n<a name=\"in-iterables-like-array-25\"></a>\r\n##### 迭代用法 (如同 array)\r\n\r\n如果我們有以下兩個 arrays：\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [arr1, \"d\", \"e\", \"f\"]; // [[\"a\", \"b\", \"c\"], \"d\", \"e\", \"f\"]\r\n```\r\n\r\n*arr2* 中的第一個元素是 array ，因為 *arr1* 是被注入到 *arr2* 之中的。但我們真正想要得到的 *arr2* 是一個純字母的 array。為了做到這點，我們可以將 *arr1* *擴展 (spread)* 到 *arr2*。\r\n\r\n透過展開運算子\r\n\r\n```js\r\nconst arr1 = [\"a\", \"b\", \"c\"];\r\nconst arr2 = [...arr1, \"d\", \"e\", \"f\"]; // [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\r\n```\r\n\r\n<a name=\"function-rest-parameter-26\"></a>\r\n##### 不定參數\r\n\r\n在有著不定參數的函數當中，我們可以使用 rest 運算子將參數注入到我們可以進行迴圈操作的 array。這裡已經有一個名為 **arguments** 的 object 被綁定在函數上，等同於把 array 中的所有參數都傳遞給函數。\r\n\r\n```js\r\nfunction myFunc() {\r\n  for (var i = 0; i < arguments.length; i++) {\r\n    console.log(arguments[i]);\r\n  }\r\n}\r\n\r\nmyFunc(\"Nick\", \"Anderson\", 10, 12, 6);\r\n// \"Nick\"\r\n// \"Anderson\"\r\n// 10\r\n// 12\r\n// 6\r\n```\r\n\r\n但是如果說我們希望創造的是一個包含他的各科成績和平均成績的新學生，提取前兩個參數 (firstName 和 lastName)並把剩下的元素迭代生成一個 array 的作法是否會更有效率呢？\r\n\r\n這正是 rest 運算子允許我們做的事！\r\n\r\n```js\r\nfunction createStudent(firstName, lastName, ...grades) {\r\n  // firstName = \"Nick\"\r\n  // lastName = \"Anderson\"\r\n  // [10, 12, 6] -- \"...\" 運算子會把 firstName 和 lastName 以外的參數傳入，同時創造一個包含這些元素，叫做 \"grades\" 的 array\r\n\r\n  const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // 計算平均成績\r\n\r\n  return {\r\n    firstName: firstName,\r\n    lastName: lastName,\r\n    grades: grades,\r\n    avgGrade: avgGrade\r\n  }\r\n}\r\n\r\nconst student = createStudent(\"Nick\", \"Anderson\", 10, 12, 6);\r\nconsole.log(student);\r\n// {\r\n//   firstName: \"Nick\",\r\n//   lastName: \"Anderson\",\r\n//   grades: [10, 12, 6],\r\n//   avgGrade: 9,33\r\n// }\r\n```\r\n\r\n> **注意：** createStudent 這個函數的舉例其實並不太好，因為我們並沒有去檢查 grades.length 是否存在又或者它根本等於 0。但是這個例子的確能夠幫助我們更為容易理解其中運作，所以我並沒有花額外的時間處理這個情況，請見諒。\r\n\r\n<a name=\"object-properties-spreading-27\"></a>\r\n##### Object 屬性擴展\r\n\r\n關於這點，我建議你去閱讀先前有關 rest 運算子，迭代運作和帶有不定參數的函數等相關說明。\r\n\r\n```js\r\nconst myObj = { x: 1, y: 2, a: 3, b: 4 };\r\nconst { x, y, ...z } = myObj; // object 在此處被解構\r\nconsole.log(x); // 1\r\nconsole.log(y); // 2\r\nconsole.log(z); // { a: 3, b: 4 }\r\n\r\n// 解構後剩餘的部分都放在 z : 也就是 myObj 這個物件經過解構後鎖剩下的東西\r\n\r\nconst n = { x, y, ...z };\r\nconsole.log(n); // { x: 1, y: 2, a: 3, b: 4 }\r\n\r\n// 把 z 所包含的屬性擴展到 n 當中\r\n```\r\n\r\n<a name=\"external-resources-28\"></a>\r\n#### 外部資源\r\n\r\n- [TC39 - Object rest/spread](https://github.com/tc39/proposal-object-rest-spread)\r\n- [Spread operator introduction - WesBos](https://github.com/wesbos/es6-articles/blob/master/28%20-%20Spread%20Operator%20Introduction.md)\r\n- [JavaScript & the spread operator](https://codeburst.io/javascript-the-spread-operator-a867a71668ca)\r\n- [6 Great uses of the spread operator](https://davidwalsh.name/spread-operator)\r\n\r\n<a name=\"object-property-shorthand-29\"></a>\r\n### Object 屬性簡寫\r\n\r\n當我們想要把某個物件屬性指派給變數，如果變數名稱等同於屬性名稱，你可以試著執行以下操作：\r\n\r\n```js\r\nconst x = 10;\r\nconst myObj = { x };\r\nconsole.log(myObj.x) // 10\r\n```\r\n\r\n<a name=\"explanation-30\"></a>\r\n#### 說明\r\n\r\n通常 (pre-ES2015) 當你宣告一個新的 *物件實體語法 (object literal)* 並且想要使用變數做為物件屬性的值時，你可能會寫出以下類似的程式碼：\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x: x, // 將變數 x 賦值給 myObj.x\r\n  y: y // 將變數 y 賦值給 myObj.y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n你可以發現，這樣的作法其實相當繁瑣，因為 myObj 的屬性名和要指派給這些屬性的變數名稱都是相同的。\r\n\r\n透過使用 ES2015，當變數名稱和屬性名稱相同時，你可以把程式碼這樣簡寫：\r\n\r\n```js\r\nconst x = 10;\r\nconst y = 20;\r\n\r\nconst myObj = {\r\n  x,\r\n  y\r\n};\r\n\r\nconsole.log(myObj.x) // 10\r\nconsole.log(myObj.y) // 20\r\n```\r\n\r\n<a name=\"external-resources-31\"></a>\r\n#### 外部資源\r\n\r\n- [Property shorthand - ES6 Features](http://es6-features.org/#PropertyShorthand)\r\n\r\n<a name=\"promises-32\"></a>\r\n### Promises\r\n\r\npromise 是一個可以從異步函數 ([參考](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261#3cd0)) 同步回傳的函數。\r\n\r\nPromises 可以被用來避開 [回調地獄 (callback hell)](http://callbackhell.com/)，而且它們在現代 JavaScript 專案中也越來越常被使用到。\r\n\r\n<a name=\"sample-code-33\"></a>\r\n#### 範例程式碼\r\n\r\n```js\r\nconst fetchingPosts = new Promise((res, rej) => {\r\n  $.get(\"/posts\")\r\n    .done(posts => res(posts))\r\n    .fail(err => rej(err));\r\n});\r\n\r\nfetchingPosts\r\n  .then(posts => console.log(posts))\r\n  .catch(err => console.log(err));\r\n```\r\n\r\n<a name=\"explanation-34\"></a>\r\n#### 說明\r\n\r\n當你在進行 *Ajax 請求* 時，回傳絕對是非同步的，因為資源請求需要時間。如果你要的資源由於某些原因 (404) 而不能使用，請求的資源可能永遠都不會出現。\r\n\r\n為了處理這類情況，ES2015 為我們提供了 *promises*。Promises 可以有三種不同的狀態：\r\n\r\n- 等待中 (Pending)\r\n- 達成 (Fulfilled)\r\n- 拒絕 (Rejected)\r\n\r\n假設我們希望使用 promises 去進行 Ajax 請求以獲取 X 這項資源。\r\n\r\n<a name=\"create-the-promise-35\"></a>\r\n##### 創造 promise\r\n\r\n首先要創造一個 promise。我們將會使用 jQuery 的 get 方法去進行資源 X 的 Ajax 請求。\r\n\r\n```js\r\nconst xFetcherPromise = new Promise( // 使用 \"new\" 這個關鍵字並把它存至一個變數\r\n  function(resolve, reject) { // Promise 建構子需要一個有著 resolve 和 reject 這兩個參數的函數作為參數\r\n    $.get(\"X\") // 執行 Ajax 請求\r\n      .done(function(X) { // 一旦請求完成...\r\n        resolve(X); // ... 把 X 做為參數去 resolve promise\r\n      })\r\n      .fail(function(error) { // 如果請求失敗...\r\n        reject(error); // ... 把 error 做為參數去 reject promise\r\n      });\r\n  }\r\n)\r\n```\r\n\r\n如上所示，Promise 物件需要一個帶有兩個參數 ( **resolve** 以及 **reject** ) 的函數。這兩個參數會把 *pending* 狀態的 promise 分別進行 *fulfilled* 和 *rejected* 的處理。\r\n\r\n但在此時此刻，promise 尚未被使用，它僅僅是被宣告並且儲存到 *xFetcherPromise* 這個變數當中！所以它並不存在當前的狀態。\r\n\r\n<a name=\"use-the-promise-36\"></a>\r\n##### 使用 promise\r\n\r\n為了使用 promise，我們可以進行以下的實作：\r\n\r\n```js\r\nxFetcherPromise\r\n  .then(function(X) {\r\n    console.log(X);\r\n  })\r\n  .catch(function(err) {\r\n    console.log(err)\r\n  })\r\n```\r\n\r\n```.then``` 是一種方法，一旦被調用將會把 xFetcherPromise 調整至 **pending** 狀態。當被調用時，promise 本體會運行，在這個範例當中，Ajax 請求正在進行中。\r\n\r\n如果成功，將會調用 *resolve*，並且 ```.then``` 將會執行做為參數傳遞的函數。\r\n\r\n如果失敗，將會調用 *reject*，並且 ```.catch``` 將會執行做為參數傳遞的函數。\r\n\r\n<a name=\"external-resources-37\"></a>\r\n#### 外部資源\r\n\r\n- [JavaScript Promises for dummies - Jecelyn Yeen](https://scotch.io/tutorials/javascript-promises-for-dummies)\r\n- [JavaScript Promise API - David Walsh](https://davidwalsh.name/promises)\r\n- [Using promises - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\r\n- [What is a promise - Eric Elliott](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261)\r\n- [JavaScript Promises: an Introduction - Jake Archibald](https://developers.google.com/web/fundamentals/getting-started/primers/promises)\r\n- [Promise documentation - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\r\n\r\n<a name=\"template-literals-38\"></a>\r\n### 模板字符串\r\n\r\n模板字符串是一種單行和多行字符串的 [*表達式差值 (expression interpolation)*](https://en.wikipedia.org/wiki/String_interpolation)。\r\n\r\n換句話說，它是一種新的字符串語法，你可以更方便地在 JavaScript 表達式中使用 (例如變數)。\r\n\r\n<a name=\"sample-code-39\"></a>\r\n#### 範例程式碼\r\n\r\n```js\r\nconst name = \"Nick\";\r\n`Hello ${name}, the following expression is equal to four : ${2+2}`;\r\n\r\n// Hello Nick, the following expression is equal to four: 4\r\n```\r\n\r\n<a name=\"external-resources-40\"></a>\r\n#### 外部資源\r\n\r\n- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)\r\n- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)\r\n\r\n<a name=\"imports--exports-41\"></a>\r\n### Imports / Exports\r\n\r\nES6 模組被用來存取顯式輸出 (explicitly export)的變數或是函數。\r\n\r\n我強烈建議你去瀏覽 MDN 上有關 import/export (請參考下面的外部資源) 的文章，它們寫的既簡潔又完整。\r\n\r\n<a name=\"explanation-with-sample-code-42\"></a>\r\n#### 說明與範例程式碼\r\n\r\n- Named exports\r\n\r\nNamed exports 被用於從模組中輸出多個值的情況。你只能命名將要輸出的變數 (不能是函數或是類別)，所以當你想要輸出一個函數時，你必須先把它儲存在一個變數中。\r\n\r\n```js\r\n// mathConstants.js\r\nexport const pi = 3.14;\r\nexport const exp = 2.7;\r\nexport const alpha = 0.35;\r\n\r\n// -------------\r\n\r\n// myFile.js\r\nimport { pi, exp } from './mathConstants.js'; // 對 import 進行解構\r\nconsole.log(pi) // 3.14\r\nconsole.log(exp) // 2.7\r\n\r\n// -------------\r\n\r\n// mySecondFile.js\r\nimport * as constants from './mathConstants.js'; // 把所有的值輸出到 constants 這個變數\r\nconsole.log(constants.pi) // 3.14\r\nconsole.log(constants.exp) // 2.7\r\n```\r\n\r\n- 預設 import / export\r\n\r\n關於輸出，每個模組在預設下只能有一個輸出。一個預設的輸出可以是函數，類別，物件又或者是任何東西。這個值被認為是 \"主要的\" 輸出值，因為它將會是最簡單純粹的輸出。[參考： MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Description)\r\n\r\n```js\r\n// coolNumber.js\r\nconst ultimateNumber = 42;\r\nexport default ultimateNumber;\r\n\r\n// ------------\r\n\r\n// myFile.js\r\nimport number from './coolNumber.js';\r\n// 預設輸出將獨立於其名稱， 將被自動注入到 number 這個變數;\r\nconsole.log(number) // 42\r\n```\r\n\r\n函數輸出：\r\n\r\n```js\r\n// sum.js\r\nexport default function sum(x, y) {\r\n  return x + y;\r\n}\r\n// -------------\r\n\r\n// myFile.js\r\nimport sum from './sum.js';\r\nconst result = sum(1, 2);\r\nconsole.log(result) // 3\r\n```\r\n\r\n<a name=\"external-resources-43\"></a>\r\n#### 外部資源\r\n\r\n- [Export - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\r\n- [Import - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\r\n- [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/)\r\n- [Modules in JavaScript](http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript)\r\n\r\n### <a name=\"-javascript-this-44\"></a> JavaScript *this*\r\n\r\n*this* 這個運算子的行為和其他語言是不太一樣的，在大多數情況之下是由函數的調用方式決定。([參考： MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)).\r\n\r\n這個概念有很多精妙之處，並不是那麼容易理解，我強烈建議你好好研讀下面的外部資源。因此，我將會提供我個人對於 *this* 的一點理解和想法。我是從 [Yehuda Katz 寫的這篇文章](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) 學到了這個技巧。\r\n\r\n```js\r\nfunction myFunc() {\r\n  ...\r\n}\r\n\r\n// 在每個述句後頭，你都可以在 myFunc 中找到 this 的值\r\n\r\nmyFunc.call(\"myString\", \"hello\") // \"myString\" -- 首先， .call 參數的值被注入到 this\r\n\r\n// 非嚴格模式下\r\nmyFunc(\"hello\") // window -- myFunc() 是 myFunc.call(window, \"hello\") 的語法糖\r\n\r\n// 嚴格模式下\r\nmyFunc(\"hello\") // undefined -- myFunc() 是 myFunc.call(undefined, \"hello\") 的語法糖\r\n```\r\n\r\n```js\r\nvar person = {\r\n  myFunc: function() { ... }\r\n}\r\n\r\nperson.myFunc.call(person, \"test\") // person 物件 -- 調用參數注入 this\r\nperson.myFunc(\"test\") // person Object -- person.myFunc() 是 person.myFunc.call(person, \"test\") 的語法糖\r\n\r\nvar myBoundFunc = person.myFunc.bind(\"hello\") // 創造了一個函數，並且把 \"hello\" 注入到 this\r\nperson.myFunc(\"test\") // person Object -- 綁定方法對原有方法並無造成影響\r\nmyBoundFunc(\"test\") // \"hello\" -- myBoundFunc 是把帶有 \"hello\" 的 person.myFunc 綁定到 this\r\n```\r\n\r\n<a name=\"external-resources-45\"></a>\r\n#### 外部資源\r\n\r\n- [Understanding JavaScript Function Invocation and \"this\" - Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)\r\n- [JavaScript this - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\r\n\r\n<a name=\"class-46\"></a>\r\n### Class\r\n\r\nJavaScript 是一個 [基於原型](https://en.wikipedia.org/wiki/Prototype-based_programming) 的語言 (然而 Java 是 [基於類別](https://en.wikipedia.org/wiki/Class-based_programming) 的語言)。 ES6 引入了 JavaScript 類別，它們是基於原型繼承的語法糖，而 **不是** 真正意義上基於類別的繼承模型。([參考](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)).\r\n\r\n\r\n*類別 (class)* 一詞的確容易出錯，尤其是你同時也熟悉其他語言的情況下。如果真的有此困擾，請避免在這樣的認知下思考 JavaScript 的類別行為，並把它當作一個完全不同的新概念。\r\n\r\n由於此份文件的目標不在於從頭教會你 JavaScript，我相信你早已知道什麼是原型，以及它們的行為模式。不過這裡還是有一些參考連結，以方便你去理解這些概念：\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\n<a name=\"samples-47\"></a>\r\n#### 範例\r\n\r\nES6 之前的原型語法：\r\n\r\n```js\r\nvar Person = function(name, age) {\r\n  this.name = name;\r\n  this.age = age;\r\n}\r\nPerson.prototype.stringSentence = function() {\r\n  return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n}\r\n```\r\n\r\nES6 之後的類型語法：\r\n\r\n```js\r\nclass Person {\r\n  constructor(name, age) {\r\n    this.name = name;\r\n    this.age = age;\r\n  }\r\n\r\n  stringSentence() {\r\n    return \"Hello, my name is \" + this.name + \" and I'm \" + this.age;\r\n  }\r\n}\r\n\r\nconst myPerson = new Person(\"Manu\", 23);\r\nconsole.log(myPerson.age) // 23\r\nconsole.log(myPerson.stringSentence()) // \"Hello, my name is Manu and I'm 23\r\n```\r\n\r\n<a name=\"external-resources-48\"></a>\r\n#### 外部資源\r\n\r\n更好的理解原型：\r\n\r\n- [Understanding Prototypes in JS - Yehuda Katz](http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/)\r\n- [A plain English guide to JS prototypes - Sebastian Porto](http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/)\r\n- [Inheritance and the prototype chain - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\r\n\r\n更好的理解類別：\r\n\r\n- [ES6 Classes in Depth - Nicolas Bevacqua](https://ponyfoo.com/articles/es6-classes-in-depth)\r\n- [ES6 Features - Classes](http://es6-features.org/#ClassDefinition)\r\n- [JavaScript Classes - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\r\n\r\n<a name=\"async-await-49\"></a>\r\n### Async Await\r\n\r\n除了 [Promises](#promises) 以外，還有一種新語法你可能會遇到，那就是被稱作非同步的 *async / await*。\r\n\r\nasync/await 的目的在於簡化同步使用 promise 的行為，並對一組 promise 執行一些處理。正如同Promises 類似於結構化之後的回調 (callback)，async/await 同樣類似於組合生成器 (combining generators) 和 promises。 ([參考： MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function))\r\n\r\n> **注意：** 你必須先行了解到什麼是 promises 和它們是如何運作的，然後再去嘗試理解 async / await 的概念，因為後者是基於前者的進一步延伸。\r\n\r\n> **注意：** [*await* must be used in an *async* function](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0) 意味著你不能程式碼的頂部使用 await，因為它並不在異步函數之內。\r\n\r\n<a name=\"sample-code-50\"></a>\r\n#### 說明與範例程式碼\r\n\r\n*Async / Await* 是基於 promises 之上的新概念，但它們更允許你使用命令式風格 (imperative style)去撰寫程式。\r\n\r\n\r\n`await` 表達式使 `async` 函數暫停執行，直到 promise 被成功解析才會繼續執行。任何 `async` 函數堆將回傳 `Promise`，並將其解析為回傳值。\r\n\r\n```js\r\nasync function getGithubUser(handle) { // async 這個關鍵字允許在函數中使用 await，並且意味著函數將回傳一個 promise \r\n  try { // 這是 async / await 使用的方式\r\n    const url = `https://api.github.com/users/${handle}`;\r\n    const response = await fetch(url); // \"同步\" 等待 fetch 去解析 promise，然後才會跳轉到下一行\r\n    return response.json();\r\n  } catch (err) {\r\n    alert(err);\r\n  }\r\n}\r\n\r\ngetGithubUser('mbeaudru').then(user => console.log(user)); // 印出 user 的值 - 不能使用 await 語法，因為此段程式碼並不在 async 函數當中\r\n```\r\n\r\n<a name=\"external-resources-52\"></a>\r\n#### 外部資源\r\n\r\n- [Async/Await - JavaScript.Info](https://javascript.info/async-await)\r\n- [ES7 Async/Await](http://rossboucher.com/await/#/)\r\n- [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9)\r\n- [JavaScript awaits](https://dev.to/kayis/javascript-awaits)\r\n- [Using Async Await in Express with Node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016)\r\n- [Async Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\r\n- [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\r\n\r\n<a name=\"glossary-53\"></a>\r\n## 術語詞彙\r\n\r\n### <a name=\"-scope-54\"></a> 作用域範圍 (scope)\r\n\r\n在上下文之中有著 \"明顯可見的 (visible)\" 值和表達式，又或者是可以被參照的。如果變數或是表達式並不在 \"當前作用域和範圍\"，那麼它將會是不能用的。\r\n\r\n資料來源： [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\r\n\r\n### <a name=\"-variable-variance-55\"></a> 變數變異 (Variable mutation)\r\n\r\n一個變數在被宣告之後發生初始值變化的過程。\r\n\r\n```js\r\nvar myArray = [];\r\nmyArray.push(\"firstEl\") // myArray 正在變化\r\n```\r\n\r\n如果變數不能被改變的話，我們會說這個變數是 *不可變的 (immutable)* 。\r\n\r\n[查看 MDN Mutable 文章](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) 了解更多詳細資料。\r\n"
  },
  {
    "path": "Kotlin/README.md",
    "content": "# Introduction\r\n\r\nKotlin is a new programming language for the JVM. It produces Java bytecode, supports Android and generates JavaScript. The latest version of the language is [Kotlin M5.3](\"http://blog.jetbrains.com/kotlin/2013/06/kotlin-m5-3-idea-13-delegated-properties-and-more/\")\r\n\r\nKotlin project website is at [kotlin.jetbrains.org](http://kotlin.jetbrains.org).\r\n\r\nAll the codes here can be copied and run on [Kotlin online editor](http://kotlin-demo.jetbrains.com/).\r\n\r\nLet's get started.\r\n\r\n# Basics\r\n- You do not need `;` to break statements.\r\n- Comments are similar to Java or C#, `/* This is comment */` for multi line comments and `// for single line comment`.\r\n- Unlike Java, you do not need to match your file name to your class name.\r\n- Like JavaScript, you can create functions outside classes. So there is no need to stuff your functions as static members of classes like what you do in C# or Java.\r\n- Kotlin has string templates, which is awesome. e.g. `\"$firstName $lastName\"` for simple variable name or `\"${person.name} is ${1 * 2}\"` for any expressions. You can still do the string concatenation if you like e.g. `\"hello \" + \"world\"`, but that means being stupid.\r\n- It has no tuple although Kotlin's data classes is an option to use in place of tuple.\r\n\r\n\r\n## Variables\r\n- There are two keywords for variable declaration, **var** and **val**.\r\n- Use **var** when the variable value is to be modified and **val** where the variable value will not change after first assigned.\r\n- This **val** is similar to **readonly** keyword in C# or **final** keyword in Java.\r\n- **val** variable must be initialized at declaration.\r\n- Unlike Java or C#, you declare the type of a variable after the name, e.g. `var firstName : String`\r\n- Number primitive types are as follows: Double, Float, Long, Int, Short, Byte. There is no automatic conversion between types. You have to explicitly convert them.\r\n- More primitive types: Char, String, Boolean.\r\n- All variable declarations in Kotlin must be initialized.\r\n- The keyword `void` common in Java or C# is called `Unit` in Kotlin.\r\n\r\n### Null\r\n\r\nIn Kotlin you have to decide whether a variable can be assigned null or not. This applies to both primitives or class types. A nullable variable is marked by assigning ? after the type, e.g. `var firstName: String?`\r\n\r\nYou can assign a value from not-nullable to nullable type without any problem.\r\n\r\n```kotlin\r\nfun main(args : Array<String>) { \r\n    val firstName : String = \"Adam\"\r\n    val name : String? = firstName \r\n    print(\"$name\") \r\n}\r\n```\r\n\r\nThe other way around though requires that you declare that this nullable variable does not contain null at the point of assignment with !! operator (which pretty much declares : \"I am sure this nullable variable is not null at this point\")\r\n\r\n```kotlin\r\nfun main(args : Array<String>) { \r\n    val name : String? = \"Adam\" \r\n    val firstName : String = name!! \r\n    print(\"$firstName\") \r\n}\r\n```    \t\t\t\t\t\r\n\t\t\t\t\t\r\n### Type inference\r\n\r\nKotlin is pretty smart about inferring what type a variable is, whether it is primitives or class. This is similar to the var keyword in C#.\r\n\r\n```kotlin\r\nfun main(args : Array<String>) { \r\n    val firstName = \"Adam\" \r\n    val middle = 'c' \r\n    val lastName = \"Brown\" \r\n    val age = 15 \r\n    println(\"$firstName $middle $lastNameis $age\") \r\n}\r\n```\t\t\t\t\t\t\t\r\n                            \r\nYou will encounter in further examples of more capabilities of Kotlin's type inference.                            \r\n\r\n# Functions\r\nWe are going to spend a considerable time in discussing function because it has many different forms and subtleties. Here is a list of facilities that Kotlin provides for functions\r\n\r\n- Single expression function.\r\n- Optional parameter.\r\n- Positional argument and named argument.\r\n- Variable argument.\r\n- Single expression function.\r\n- Function type.\r\n- Function literals.\r\n- Callable references.\r\n- Extension functions.\r\n- Infix function call.\r\n- Local function.\r\n- Closure.\r\n- Generic function.\r\n- Operator overloading.\r\n\r\nBelow is an example of functions\r\n\r\n```kotlin\r\nfun main(args : Array<String>) { \r\n    greet(englishGreeting()) \r\n    greet(italianGreeting())\r\n} \r\n\r\nfun greet(msg : String){ \r\n    println(msg) \r\n} \r\n    \r\nfun englishGreeting() : String = \"Hello world\" \r\n    \r\nfun italianGreeting() : String{ \r\n    return \"bon giorno\" \r\n}\r\n```\t\t\t\t\t\r\n\r\n- Functions can exists on their own.\r\n- It is marked by **fun** keyword.\r\n- If a function returns value, you declare it after the function name.\r\n- `englishGreeting()` is a *single expression function*.\r\n- A void function such as `greet()` returns Unit type but you are not required to declare it.\r\n- All parameters in a Kotlin function are read only. You are actually not allowed to mark it with either `val` or `var` keyword.\r\n\r\n\r\n## Single expression function\r\n\r\nThis is a shorthand form in defining a function when you only have a single expression to be executed.\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n   val res = add(1,1)\r\n   show(\"$res\")\r\n}\r\n\r\n\r\nfun add(a : Int, b : Int) = a + b\r\nfun show(msg : String) = println(\"$msg\")\r\n```\r\n\r\nAs you can see above, in a single expression function, the function return type is inferred. You can declare the return type if you want to such as below. \r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n   val res = add(1,1)\r\n   show(\"$res\")\r\n}\r\n\r\n\r\nfun add(a : Int, b : Int) : Int = a + b\r\nfun show(msg : String) : Unit = println(\"$msg\")\r\n```\r\n\r\n\r\n## Optional parameters\r\n\r\nKotlin allows you to assign default values for your parameters, making them optional. \r\n\r\n```kotlin \r\nfun main(args : Array<String>) {\r\n  show()\r\n  show(\"Good morning\")\r\n}\r\n\r\n\r\nfun show (msg : String = \"Hello World\"){\r\n    println(\"$msg\") \r\n}\r\n```\r\n\r\nIf you are mixing mandatory parameter and optional parameter, the mandatory parameters must be listed first.\r\n\r\n## Arguments\r\n\r\n```kotlin\r\nfun main(args : Array<String>) { \r\n    greet(firstName = \"Frasensco\", lastName = \"Merini\") \r\n    greet(lastName = \"John\", firstName = \"Stamos\") \r\n    greet(\"Borat\", \"Ismail\") \r\n    greet(\"Crystal\", lastName = \"Stamos\") \r\n    call(\"Xavier\", age = 20, location = \"Portugal\") \r\n} \r\n    \r\nfun greet(firstName : String, lastName : String){\r\n    println(\"Good morning $firstName $lastName\") \r\n} \r\n    \r\nfun call(name : String, location : String, age : Int){ \r\n    println(\"Call $name who lives at $location and he is $age old\") \r\n}\r\n```\t\t\t\t\t\r\n\t\t\t\t\r\nKotlin allows positional argument, named argument and the mix between the two. When you mix named and positional argument, you must start with positional argument.\r\n\r\n### Variable arguments\r\n\r\nUse the keyword **vararg**.\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  names(\"John\", \"Adam\", \"Joy\")\r\n}\r\n\r\nfun names(vararg  names : String){\r\n  for(n in names){\r\n    println(\"$n\")\r\n  }\r\n}\r\n```\r\n\r\nIf **vararg** parameter is not the last parameter, named argument must be used to supply the function argument.\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  names(\"John\", \"Adam\", \"Joy\", age = 20)\r\n}\r\n\r\nfun names(vararg  names : String, age : Int){\r\n  for(n in names){\r\n    println(\"$n is $age old\")\r\n  }\r\n}\r\n```\r\n\r\n\r\n### vararg produces array of argument\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  names(\"John\", \"Adam\", \"Joy\")\r\n}\r\n\r\nfun names(vararg  names : String){\r\n  println(\"Argument length is ${names.size}\")\r\n  println(\"${names[0]}\")\r\n  val nns : Array<String> = names\r\n  println(\"${nns[1]}\")\r\n}\r\n```\r\n\r\n### Using array to supply variable arguments\r\nUse the * operator in front of the array variable\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  val n = array(\"John\", \"Adam\", \"Joy\")\r\n  names(*n)\r\n}\r\n\r\nfun names(vararg  names : String){\r\n  println(\"Argument length is ${names.size}\")\r\n  println(\"${names[0]}\")\r\n  val nns : Array<String> = names\r\n  println(\"${nns[1]}\")\r\n}\r\n``` \r\n\r\n### Passing one varargs argument to another\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  val n = array(\"John\", \"Adam\", \"Joy\")\r\n  fugitives(*n)\r\n}\r\n,  \r\nfun fugitives(vararg escapees: String){\r\n  names(*escapees) \r\n}\r\n\r\nfun names(vararg  names : String){\r\n  println(\"Argument length is ${names.size}\")\r\n  println(\"${names[0]}\")\r\n  val nns : Array<String> = names\r\n  println(\"${nns[1]}\")\r\n}\r\n```\r\nSince **vararg** creates an array, you simply use the * operator to pass one **vararg** to another.\r\n\r\n##Function Types and Function Literals\r\n\r\nA function type is a type consisted of a function signature and function return type that are separated by -> operator. In its simplest form, it looks as follows: \r\n\r\n`() -> Unit`\r\n\r\nAbove is a type for a function that takes no parameter and returns a Unit (void in other language parlance)\r\n\r\n`() -> String`\r\n\r\nAbove is a type for a function that takes no parameter and return a String\r\n\r\n`(String) -> Unit`\r\n\r\nAbove is a type for a function that takes a string and returns nothing.\r\n\r\n`(String, Float) -> Unit`\r\n\r\nAbove is a type for a function that takes two parameters (String and Float) and returns nothing.\r\n\r\nBecause a function type is just a type, it means that you can assign it to a variable, you can pass it as a function argument and you can return it from a function.\r\n\r\n### Different ways to write function literals\r\n\r\n```kotlin\r\nval m = { (x : String) -> println(\"$x\") } \r\nval n : (String) -> Unit = { x -> println(\"$x\") } \r\nval o : (String) -> Unit = { (x : String) -> println(\"$x\") } \r\n\r\nfun main(args : Array<String>) { \r\n    m(\"good morning\")\r\n    n(\"good morning\") \r\n    o(\"good morning\") \r\n}\r\n```\r\n\r\nAbove code is an example of function literals. All `m`, `n` and `o` represent the same function.\r\n            \t\t\r\nBelow is a function that returns a function type\r\n\r\n```kotlin\r\nfun main(args : Array<String>) { \r\n    val greet = greetingFrom(\"Cairo, Egypt\") \r\n    greet(\"Brown\") \r\n} \r\n\r\nfun greetingFrom(location : String) : (String) -> Unit{ \r\n    return { name -> println (\"Hello $name from $location\")}\r\n}\r\n```\t\t\t\t\r\n\t\r\nBelow shows that you can specify a function type as an argument and supply it with function literal with corresponding function signature and return type.\r\n\r\n```kotlin\r\nfun evening(): String = \"Good Evening\" \r\nfun main(args : Array<String>){ \r\n    say({ \"good morning\"}) \r\n    say { val msg = \"good afternoon\" msg } \r\n    say({evening()})\r\n} \r\n\r\nfun say(greet : () -> String){ \r\n    println(\"${greet()}\") \r\n}\r\n```\r\n\r\n## Callable references\r\n\r\nHow about if you already have a function that you want to pass as a parameter? You prefix the function name with '::'\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n calcAndShow(10,10, ::add) //20\r\n calcAndShow(10,10, ::multiply) /100\r\n calcAndShow(10,19, { x, y -> x - y }) //-9\r\n}\r\n\r\nfun calcAndShow(a : Int, b : Int,  func : (a : Int, b : Int) -> Int){\r\n val result = func (a, b)\r\n println(\"$result\")\r\n}\r\n\r\nfun add(a : Int, b : Int) : Int = a + b\r\nfun multiply (a : Int, b : Int) : Int = a * b\r\n```\r\n\r\n\r\n## Function expansion\r\n\r\nWhen you call a function which has a function type as the last argument, you can expand it by { }\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n    val a =  calculate(1) { x -> 10 + x } //11\r\n    val b = calculate(2) { x -> 20 * x } //40\r\n\r\n    println(\"a = $a, b = $b\")\r\n}\r\n\r\nfun calculate(a : Int,  calc : (Int) -> Int) : Int{\r\n    return calc(a)\r\n}\r\n```\r\n\r\n## Closure\r\n\r\nKotlin support Closure as highlighted by the example below\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n    val total = add(1)(2)\r\n    println(\"Total value is $total\")\r\n}\r\n\r\nfun add(a : Int) : (Int) -> Int{\r\n    return { x -> a + x }\r\n}\r\n```\r\n\r\n## Local function\r\n\r\nYou can declare a function inside a function. It will have access to the local variable at the parent function.\r\n```kotlin\r\nfun main(args : Array<String>){ \r\n    accumulate() \r\n} \r\n\r\nfun accumulate(){\r\n    var i = 0 \r\n\r\n    fun add(){ \r\n        i++ \r\n    } \r\n\r\n    for (i in 1..10){\r\n        add() \r\n    } \r\n\r\n    println(\"i is now $i\") \r\n}\r\n\r\n//It prints \"i is now 10\"\r\n```\r\n\r\n\r\n## Extension function\r\n\r\nExtension function enables a function to be accessed from the type function. It works in the form of __type.function__\r\nInside the function, the keyword `this` refers to the instance. \r\n\r\nFor example\r\n```kotlin   \r\nfun Int.show(){\r\n    println(\"This number is $this\")\r\n}\r\n    \r\nfun main(args : Array<String>){\r\n    3.show()\r\n}\r\n```\r\n\r\nAbove example shows how the `Int` built in type has been enriched by `show` extension function. Notice the use of `this` keyword that refers to the `3` number.\r\n\r\n\r\n**Notice** You can extend a function on a nullable type and it will be accessible for both nullable and non nullable type. The reverse though does not apply.\r\n\r\n```kotlin\r\nfun Int?.show(){\r\n    println(\"This number is $this\")\r\n}\r\n \r\nfun Int.show2(){\r\n    println(\"This number is $this\")\r\n}\r\n\r\nfun main(args : Array<String>){\r\n    var number : Int? = null\r\n    number.show()\r\n    5.show()\r\n    //number.show2() will not compile\r\n}\r\n```\r\n\r\n    \r\n### Extension function expressed in function literals\r\n\r\n```kotlin\r\nval show = { Int.() -> println(\"This is number $this\") }\r\nval add = { Int.(number : Int) : Int -> \r\n    val now = this + number\r\n    now\r\n}\r\n\r\nfun main(args : Array<String>){\r\n    5.add(10).show()\r\n}\r\n```\r\n\r\nBoth `show` and `add` extension functions are expressed in literal format. Please notice that `add` function returns an `Int`.\r\n\r\n    \r\n### Extension function in infix form\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n   val res = 1 add 2\r\n   println(\"$res\")\r\n}\r\n\r\nfun Int.add (one : Int) : Int = this + one\r\n```\r\n\r\nIf the extension function only takes one argument, you can call them in infix form (you drop the . between the type and the function). So instead of `1.add(2)`, you can call it in the form of `1 add 2`. This makes certain constructs looks natural (more like an operator than a function call) and especially useful in construction DSL in Kotlin.\r\n\r\n## Variable arguments and function type argument\r\n\r\n`vararg` parameter can also be naturally combined with a function type parameter.\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  names(\"John\", \"Adam\", \"Joy\"){ \r\n    name  -> println (\"$name\")\r\n  }\r\n}\r\n\r\nfun names(vararg  names : String, print : (String) -> Unit){\r\n  for(n in names){\r\n   print(n)\r\n  }\r\n}\r\n```\r\n\r\nabove code can also be expressed in this matter (using named argument)\r\n```kotlin\r\n\r\nfun main(args : Array<String>) {\r\n  names(\"John\", \"Adam\", \"Joy\", print = {name  -> println (\"$name\")})\r\n}\r\n\r\nfun names(vararg  names : String, print : (String) -> Unit){\r\n  for(n in names){\r\n   print(n)\r\n  }\r\n}\r\n\r\n```\r\n\r\n# Control Structures\r\n\r\n\r\n## If statement\r\n\r\nKotlin **if** statement should look familiar with other language\r\n\r\n```kotlin\r\nfun main(args : Array<String>) {\r\n  val total = 10\r\n  \r\n  if (total > 5){\r\n      println(\"$total is greater than 5\") \r\n  }else if (total > 10){\r\n      println(\"$total is greater than 10\")\r\n  }else{\r\n      println(\"$total is less than 6\")\r\n  }\r\n}\r\n\r\n```\r\n"
  },
  {
    "path": "MATLAB/README.md",
    "content": "# MATLAB Cheat Sheet\r\n\r\nBased off of [Learn X in Y Minutes](http://learnxinyminutes.com/docs/matlab/).\r\n\r\nMATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.\r\n\r\n## Quick Access Links\r\n1. [Basics](#basics)\r\n    1. [Comments and Code Sections](#comments)\r\n    2. [Helper Commands](#commands)\r\n    3. [Variables and Expressions](#vars)\r\n2. [Matrices and Vectors](#matrices)\r\n    1. [Declarations](#declarations)\r\n    2. [Splicing and Dicing](#splice)\r\n    3. [Arithmetic and Operations](#arith)\r\n3. [Plots](#plots)\r\n4. [Functions and Scripts](#functions)\r\n5. [Programming Logic](#logic)\r\n6. [Math/Engineering](#math)\r\n    1. [Common Math Functions](#common)\r\n    2. [Transfer Functions](#transfer)\r\n7. [Vectorization](#vectorization)\r\n8. [Optimization](#optimization)\r\n9. [Machine Learning](#ML)\r\n10. [Simulink](#simulink)\r\n\r\n<a name=\"basics\"></a>\r\n## 1. Basics\r\n<a name=\"comments\"></a>\r\n### i. Comments and Code Sections\r\n```matlab\r\n%% Code sections start with two percent signs. Section titles go on the same line.\r\n% Comments start with a percent sign.\r\n\r\n%{\r\nMulti line comments look\r\nsomething\r\nlike\r\nthis\r\n%}\r\n\r\n% Two percent signs denote the start of a new code section\r\n% Individual code sections can be run by moving the cursor to the section followed by\r\n% either clicking the \"Run Section\" button\r\n% or     using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X)\r\n\r\n%% This is the start of a code section\r\n%  One way of using sections is to separate expensive but unchanging start-up code like loading data\r\nload myFile.mat y\r\n\r\n%% This is another code section\r\n%  This section can be edited and run repeatedly on its own, and is helpful for exploratory programming and demos\r\nA = A * 2;\r\nplot(A);\r\n\r\n% commands can span multiple lines, using '...':\r\n a = 1 + 2 + ...\r\n + 4\r\n```\r\n\r\n<a name=\"commands\"></a>\r\n### ii. Helper Commands\r\n```matlab\r\n% commands can be passed to the operating system\r\n!ping google.com\r\n\r\nwho % Displays all variables in memory\r\nwhos % Displays all variables in memory, with their types\r\nclear % Erases all your variables from memory\r\nclear('A') % Erases a particular variable\r\nopenvar('A') % Open variable in variable editor\r\n\r\nclc % Erases the writing on your Command Window\r\ndiary % Toggle writing Command Window text to file\r\nctrl-c % Abort current computation\r\n\r\nclose all % Closes all figures\r\n\r\nedit('myfunction.m') % Open function/script in editor\r\ntype('myfunction.m') % Print the source of function/script to Command Window\r\n\r\nprofile on  % turns on the code profiler\r\nprofile off     % turns off the code profiler\r\nprofile viewer  % Open profiler\r\n\r\nhelp command    % Displays documentation for command in Command Window\r\ndoc command     % Displays documentation for command in Help Window\r\nlookfor command % Searches for command in the first commented line of all functions\r\nlookfor command -all % searches for command in all functions\r\n\r\n\r\n% Output formatting\r\nformat short    % 4 decimals in a floating number\r\nformat long     % 15 decimals\r\nformat bank     % only two digits after decimal point - for financial calculations\r\nfprintf('text') % print \"text\" to the screen\r\ndisp('text')    % print \"text\" to the screen\r\n\r\n% pressing the up key shows you a history of previous commands\r\n```\r\n\r\n<a name=\"vars\"></a>\r\n### iii. Variables and Expressions\r\n```matlab\r\n% Variables & Expressions\r\nmyVariable = 4  % Notice Workspace pane shows newly created variable\r\nmyVariable = 4; % Semi colon suppresses output to the Command Window\r\n4 + 6       % ans = 10\r\n8 * myVariable  % ans = 32\r\n2 ^ 3       % ans = 8\r\na = 2; b = 3;\r\nc = exp(a)*sin(pi/2) % c = 7.3891\r\n\r\n% Logicals\r\n1 > 5 % ans = 0\r\n10 >= 10 % ans = 1\r\n3 ~= 4 % Not equal to -> ans = 1\r\n3 == 3 % equal to -> ans = 1\r\n3 > 1 && 4 > 1 % AND -> ans = 1\r\n3 > 1 || 4 > 1 % OR -> ans = 1\r\n~1 % NOT -> ans = 0\r\n\r\n% Logicals can be applied to matrices:\r\nA > 5\r\n% for each element, if condition is true, that element is 1 in returned matrix\r\nA( A > 5 )\r\n% returns a vector containing the elements in A for which condition is true\r\n\r\n% Strings\r\na = 'MyString'\r\nlength(a) % ans = 8\r\na(2) % ans = y\r\n[a,a] % ans = MyStringMyString\r\n\r\n\r\n% Cells\r\na = {'one', 'two', 'three'}\r\na(1) % ans = 'one' - returns a cell\r\nchar(a(1)) % ans = one - returns a string\r\n\r\n% Structures\r\nA.b = {'one','two'};\r\nA.c = [1 2];\r\nA.d.e = false;\r\n\r\n% Variables can be saved to .mat files\r\nsave('myFileName.mat') % Save the variables in your Workspace\r\nload('myFileName.mat') % Load saved variables into Workspace\r\n```\r\n\r\n<a name=\"matrices\"></a>\r\n##2. Matrices and Vectors\r\n\r\n**IMPORTANT: Indices in Matlab start at 1, not 0**\r\n\r\n<a name=\"declarations\"></a>\r\n### i. Declarations\r\n```matlab\r\n% Vectors\r\nx = [4 32 53 7 1]\r\nx(2) % ans = 32\r\nx(2:3) % ans = 32 53\r\nx(2:end) % ans = 32 53 7 1\r\n\r\nx = [4; 32; 53; 7; 1] % Column vector\r\n\r\nx = [1:10] % x = 1 2 3 4 5 6 7 8 9 10\r\nx = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9\r\n\r\n% Matrices\r\nA = [1 2 3; 4 5 6; 7 8 9]\r\n% Rows are separated by a semicolon; elements are separated with space or comma\r\n% A =\r\n\r\n%     1     2     3\r\n%     4     5     6\r\n%     7     8     9\r\n\r\nA(2,3) % ans = 6, A(row, column)\r\nA(6) % ans = 8\r\n% (implicitly concatenates columns into vector, then indexes into that)\r\n\r\n\r\nA(2,3) = 42 % Update row 2 col 3 with 42\r\n% A =\r\n\r\n%     1     2     3\r\n%     4     5     42\r\n%     7     8     9\r\n```\r\n\r\n<a name=\"splice\"></a>\r\n### ii. Splicing and Dicing\r\n```matlab\r\nA(2:3,2:3) % Creates a new matrix from the old one\r\n%ans =\r\n\r\n%     5     42\r\n%     8     9\r\n\r\nA(:,1) % All rows in column 1\r\n%ans =\r\n\r\n%     1\r\n%     4\r\n%     7\r\n\r\nA(1,:) % All columns in row 1\r\n%ans =\r\n\r\n%     1     2     3\r\n\r\n[A ; A] % Concatenation of matrices (vertically)\r\n%ans =\r\n\r\n%     1     2     3\r\n%     4     5    42\r\n%     7     8     9\r\n%     1     2     3\r\n%     4     5    42\r\n%     7     8     9\r\n\r\n% this is the same as\r\nvertcat(A,A);\r\n\r\n\r\n[A , A] % Concatenation of matrices (horizontally)\r\n\r\n%ans =\r\n\r\n%     1     2     3     1     2     3\r\n%     4     5    42     4     5    42\r\n%     7     8     9     7     8     9\r\n\r\n% this is the same as\r\nhorzcat(A,A);\r\n\r\n\r\nA(:, [3 1 2]) % Rearrange the columns of original matrix\r\n%ans =\r\n\r\n%     3     1     2\r\n%    42     4     5\r\n%     9     7     8\r\n\r\nA(1, :) =[] % Delete the first row of the matrix\r\nA(:, 1) =[] % Delete the first column of the matrix\r\n\r\nsqueeze(A); % Removes singular dimensions ie. 2x1x3 -> 2x3\r\n```\r\n\r\n\r\n<a name=\"arith\"></a>\r\n### iii. Arithmetic and Operations\r\n```matlab\r\ntranspose(A) % Transpose the matrix, which is the same as:\r\nA one\r\n\r\nA' % Concise version of complex transpose\r\nA.' % Concise version of transpose (without taking complex conjugate)\r\n\r\nsize(A) % ans = 3 3\r\n\r\n% Element by Element Arithmetic vs. Matrix Arithmetic\r\n% On their own, the arithmetic operators act on whole matrices. When preceded\r\n% by a period, they act on each element instead. For example:\r\nA * B % Matrix multiplication\r\nA .* B % Multiple each element in A by its corresponding element in B\r\n\r\n% There are several pairs of functions, where one acts on each element, and\r\n% the other (whose name ends in m) acts on the whole matrix.\r\nexp(A) % exponentiate each element\r\nexpm(A) % calculate the matrix exponential\r\nsqrt(A) % take the square root of each element\r\nsqrtm(A) %  find the matrix whose square is A\r\n\r\n% Solving matrix equations (if no solution, returns a least squares solution)\r\n% The \\ and / operators are equivalent to the functions mldivide and mrdivide\r\nx=A\\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b.\r\nx=b/A % Solves xA=b\r\n\r\ninv(A) % calculate the inverse matrix\r\npinv(A) % calculate the pseudo-inverse\r\n\r\n% Common matrix functions\r\nzeros(m,n) % m x n matrix of 0's\r\nones(m,n) % m x n matrix of 1's\r\ndiag(A) % Extracts the diagonal elements of a matrix A\r\ndiag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere\r\neye(m,n) % Identity matrix\r\nlinspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2\r\ninv(A) % Inverse of matrix A\r\ndet(A) % Determinant of A\r\neig(A) % Eigenvalues and eigenvectors of A\r\ntrace(A) % Trace of matrix - equivalent to sum(diag(A))\r\nisempty(A) % Tests if array is empty\r\nall(A) % Tests if all elements are nonzero or true\r\nany(A) % Tests if any elements are nonzero or true\r\nisequal(A, B) % Tests equality of two arrays\r\nnumel(A) % Number of elements in matrix\r\ntriu(x) % Returns the upper triangular part of x\r\ntril(x) % Returns the lower triangular part of x\r\ncross(A,B) %  Returns the cross product of the vectors A and B\r\ndot(A,B) % Returns scalar product of two vectors (must have the same length)\r\ntranspose(A) % Returns the transpose of A\r\nfliplr(A) % Flip matrix left to right\r\nflipud(A) % Flip matrix up to down\r\n\r\n% Matrix Factorisations\r\n[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix\r\n[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues\r\n[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order\r\n[Q, R] = qr(A) % if A is mxn, Q is mxm and R is mxn upper triangular\r\n\r\n% Common vector functions\r\nmax     % largest component\r\nmin     % smallest component\r\nlength  % length of a vector\r\nsort    % sort in ascending order\r\nsum     % sum of elements\r\nprod    % product of elements\r\nmode    % modal value\r\nmedian  % median value\r\nmean    % mean value\r\nstd     % standard deviation\r\nperms(x) % list all permutations of elements of x\r\nfind(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, \r\n        % i.e. find( x == 3 ) returns indexes of elements that are equal to 3\r\n        % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3\r\n\r\n```\r\n\r\n\r\n<a name=\"plots\"></a>\r\n## 3. Plots\r\n```matlab\r\n% Plotting\r\nx = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1\r\ny = sin(x);\r\nplot(x,y)\r\nxlabel('x axis')\r\nylabel('y axis')\r\ntitle('Plot of y = sin(x)')\r\naxis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1\r\n\r\nplot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot\r\nlegend('Line 1 label', 'Line 2 label') % Label curves with a legend\r\n\r\n% Alternative method to plot multiple functions in one plot.\r\n% while 'hold' is on, commands add to existing graph rather than replacing it\r\nplot(x, y)\r\nhold on\r\nplot(x, z)\r\nhold off\r\n\r\nloglog(x, y) % A log-log plot\r\nsemilogx(x, y) % A plot with logarithmic x-axis\r\nsemilogy(x, y) % A plot with logarithmic y-axis\r\n\r\nfplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5\r\n\r\n% Creates a meshgrid (2D grid) to calculate a function for every point in the grid\r\n[X, Y] = meshgrid(x_min:step:x_max, y_min:step:y_max)\r\n\r\ngrid on % Show grid; turn off with 'grid off'\r\naxis square % Makes the current axes region square\r\naxis equal % Set aspect ratio so data units are the same in every direction\r\n\r\nscatter(x, y); % Scatter-plot\r\nhist(x); % Histogram\r\nstem(x); % Plot values as stems, useful for displaying discrete data\r\nbar(x); % Plot bar graph\r\n\r\nz = sin(x);\r\nplot3(x,y,z); % 3D line plot\r\n\r\npcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value\r\ncontour(A) % Contour plot of matrix\r\ncontourf(A) % Filled contour plot of matrix\r\nmesh(A) % Plot as a mesh surface\r\n\r\nh = figure % Create new figure object, with handle h\r\nfigure(h) % Makes the figure corresponding to handle h the current figure\r\nclose(h) % close figure with handle h\r\nclose all % close all open figure windows\r\nclose % close current figure window\r\n\r\nshg % bring an existing graphics window forward, or create new one if needed\r\nclf clear % clear current figure window, and reset most figure properties\r\n\r\n% Properties can be set and changed through a figure handle.\r\n% You can save a handle to a figure when you create it.\r\n% The function get returns a handle to the current figure\r\nh = plot(x, y); % you can save a handle to a figure when you create it\r\nset(h, 'Color', 'r')\r\n% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black\r\nset(h, 'LineStyle', '--')\r\n % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line\r\nget(h, 'LineStyle')\r\n\r\n\r\n% The function gca returns a handle to the axes for the current figure\r\nset(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis\r\n\r\n% To create a figure that contains several axes in tiled positions, use subplot\r\nsubplot(2,3,1); % select the first position in a 2-by-3 grid of subplots\r\nplot(x1); title('First Plot') % plot something in this position\r\nsubplot(2,3,2); % select second position in the grid\r\nplot(x2); title('Second Plot') % plot something there\r\n\r\n% Given\r\nx1 = [-3:0.5:3];\r\nx2 = x1;\r\ny = randi(500, length(x1), length(x1));\r\n\r\n% Show a 3-D plot\r\nfigure\r\nsubplot(2,1,1);\r\nsurf(x1,x2,y);\r\nxlabel(’x_1’);\r\nylabel(’x_2’);\r\n\r\n% Show contours\r\nsubplot(2,1,2);\r\ncontour(x1,x2,y);\r\nxlabel(’x_{1}’);\r\nylabel(’x_{2}’);\r\naxis equal\r\n\r\n% Show a colour map\r\nfigure\r\nimagesc(x1,x2,y)\r\nxlabel(’x_{1}’);\r\nylabel(’x_{2}’);\r\n```\r\n\r\n<a name=\"functions\"></a>\r\n## 4. Functions and Scripts\r\n```matlab\r\n% Calling Functions\r\n% Standard function syntax:\r\nload('myFile.mat', 'y')\r\n% Command syntax:\r\nload myFile.mat y   % no parentheses, and spaces instead of commas\r\n\r\n% Calling a function from a script\r\n% [arguments out] = function_name(arguments in)\r\n[V,D] = eig(A);\r\n[~,D] = eig(A);  % if you only want D and not V\r\n\r\n% To use functions or scripts, they must be on your path or current directory\r\npath % displays current path\r\naddpath /path/to/dir % add to path\r\nrmpath /path/to/dir % remove from path\r\ncd /path/to/move/into % change directory\r\n\r\n% M-file Scripts\r\n% A script file is an external file that contains a sequence of statements.\r\n% They let you avoid repeatedly typing the same code in the Command Window\r\n% Have .m extensions\r\n\r\n% M-file Functions\r\n% Like scripts, and have the same .m extension\r\n% But can accept input arguments and return an output\r\n% Also, they have their own workspace (ie. different variable scope).\r\n% Function name should match file name (so save this example as double_input.m).\r\n% 'help double_input.m' returns the comments under line beginning function\r\nfunction output = double_input(x)\r\n    %double_input(x) returns twice the value of x\r\n    output = 2*x;\r\nend\r\ndouble_input(6) % ans = 12\r\n\r\n% If you want to create a function without creating a new file you can use an\r\n% anonymous function.\r\n% Example that returns the square of it's input, assigned to the handle sqr:\r\nsqr = @(x) x.^2;\r\nsqr(10) % ans = 100\r\ndoc function_handle % find out more\r\n```\r\n\r\n<a name=\"logic\"></a>\r\n## 5. Programming Logic\r\n```matlab\r\n% User input\r\na = input('Enter the value: ')\r\n\r\n% Stops execution of file and gives control to the keyboard: user can examine\r\n% or change variables. Type 'return' to continue execution, or 'dbquit' to exit\r\nkeyboard\r\n\r\n% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)\r\nfopen(filename)\r\n\r\n% Output\r\ndisp(a) % Print out the value of variable a\r\ndisp('Hello World') % Print out a string\r\nfprintf % Print to Command Window with more control\r\n\r\n% Conditional statements (the parentheses are optional, but good style)\r\nif (a > 15)\r\n    disp('Greater than 15')\r\nelseif (a == 23)\r\n    disp('a is 23')\r\nelse\r\n    disp('neither condition met')\r\nend\r\n\r\n% Looping\r\n% NB. looping over elements of a vector/matrix is slow!\r\n% Where possible, use functions that act on whole vector/matrix at once\r\nfor k = 1:5\r\n    disp(k)\r\nend\r\n\r\nk = 0;\r\nwhile (k < 5)\r\n    k = k + 1;\r\nend\r\n\r\n% Timing code execution: 'toc' prints the time since 'tic' was called\r\ntic\r\nA = rand(1000);\r\nA*A*A*A*A*A*A;\r\ntoc\r\n```\r\n\r\n<a name=\"math\"></a>\r\n## 6. Math/Engineering\r\n<a name=\"common\"></a>\r\n### i. Common Math Functions\r\n```matlab\r\nsin(x)\r\ncos(x)\r\ntan(x)\r\nasin(x)\r\nacos(x)\r\natan(x)\r\nexp(x)\r\nsqrt(x)\r\nlog(x)\r\nlog10(x)\r\nabs(x) %If x is complex, returns magnitude\r\nmin(x)\r\nmax(x)\r\nceil(x)\r\nfloor(x)\r\nround(x)\r\nrem(x)\r\nrand % Uniformly distributed pseudorandom numbers\r\nrandi % Uniformly distributed pseudorandom integers\r\nrandn % Normally distributed pseudorandom numbers\r\n\r\n%Complex math operations\r\nabs(x)   % Magnitude of complex variable x\r\nphase(x) % Phase (or angle) of complex variable x\r\nreal(x)  % Returns the real part of x (i.e returns a if x = a +jb)\r\nimag(x)  % Returns the imaginary part of x (i.e returns b if x = a+jb)\r\nconj(x)  % Returns the complex conjugate \r\n\r\n\r\n% Common constants\r\npi\r\nNaN\r\ninf\r\n\r\n% Given a meshgrid X,Y and a function defined on the meshgrid like Gauss, interpolates the value of the function at the point u1,u2\r\ninterp2(X,Y,Gauss,u1,u2)\r\n\r\n\r\n```\r\n\r\n<a name=\"transfer\"></a>\r\n### ii. Transfer Functions\r\n```matlab\r\n% Transfer functions\r\ns = tf('s');\r\nG = s^2/(s^3 + 100*s^2 + 30*s + 50);\r\n\r\npole(G); % Returns the location(s) of the pole(s) in rad/s\r\nzero(G); % Returns the location(s) of the zero(s) in rad/s\r\npzmap(G); % Plots the locations of both the pole(s) and zero(s)\r\n\r\nbandwidth(closed_loop_system); % Returns bandwidth of a closed loop transfer function in rad/s\r\nbode(closed_loop_system) % Creates bode plot of system\r\nrlocus(closed_loop_system) % Plots a root locus of the specified system\r\n\r\nmargin(open_loop_system); % Creates a bode plot, displaying the gain and phase margins of an open loop transfer function\r\n\r\n```\r\n\r\n<a name=\"vectorization\"></a>\r\n## 7. Vectorization\r\n<a href=\"https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html\">Tips to vectorize your code to get rid of loops and make it run more efficiently.</a>\r\n```matlab\r\n```\r\n\r\n<a name=\"optimization\"></a>\r\n## 8. Optimization\r\n```matlab\r\n% fmincon\r\n```\r\n\r\n<a name=\"ML\"></a>\r\n## 9. Machine Learning\r\n```matlab\r\n\r\n\r\n```\r\n\r\n\r\n<a name=\"simulink\"></a>\r\n## 10. Simulink\r\n```matlab\r\nsimulink % starts Simulink\r\n\r\n```"
  },
  {
    "path": "Markdown/README.md",
    "content": "Markdown Cheatsheet\r\n===================\r\n\r\n- - - - \r\n\r\n# Heading 1 #\r\n\r\n    Markup :  # Heading 1 #\r\n\r\n    -OR-\r\n\r\n    Markup :  ============= (below H1 text)\r\n\r\n## Heading 2 ##\r\n\r\n    Markup :  ## Heading 2 ##\r\n\r\n    -OR-\r\n\r\n    Markup: --------------- (below H2 text)\r\n\r\n### Heading 3 ###\r\n\r\n    Markup :  ### Heading 3 ###\r\n\r\n#### Heading 4 ####\r\n\r\n    Markup :  #### Heading 4 ####\r\n\r\n\r\nCommon text\r\n\r\n    Markup :  Common text\r\n\r\n_Emphasized text_\r\n\r\n    Markup :  _Emphasized text_ or *Emphasized text*\r\n\r\n~~Strikethrough text~~\r\n\r\n    Markup :  ~~Strikethrough text~~\r\n\r\n__Strong text__\r\n\r\n    Markup :  __Strong text__ or **Strong text**\r\n\r\n___Strong emphasized text___\r\n\r\n    Markup :  ___Strong emphasized text___ or ***Strong emphasized text***\r\n\r\n[Named Link](http://www.google.fr/) and http://www.google.fr/ or <http://example.com/>\r\n\r\n    Markup :  [Named Link](http://www.google.fr/) and http://www.google.fr/ or <http://example.com/>\r\n\r\nTable, like this one :\r\n\r\nFirst Header  | Second Header\r\n------------- | -------------\r\nContent Cell  | Content Cell\r\nContent Cell  | Content Cell\r\n\r\n```\r\nFirst Header  | Second Header\r\n------------- | -------------\r\nContent Cell  | Content Cell\r\nContent Cell  | Content Cell\r\n```\r\n\r\n`code()`\r\n\r\n    Markup :  `code()`\r\n\r\n```javascript\r\n    var specificLanguage_code = \r\n    {\r\n        \"data\": {\r\n            \"lookedUpPlatform\": 1,\r\n            \"query\": \"Kasabian+Test+Transmission\",\r\n            \"lookedUpItem\": {\r\n                \"name\": \"Test Transmission\",\r\n                \"artist\": \"Kasabian\",\r\n                \"album\": \"Kasabian\",\r\n                \"picture\": null,\r\n                \"link\": \"http://open.spotify.com/track/5jhJur5n4fasblLSCOcrTp\"\r\n            }\r\n        }\r\n    }\r\n```\r\n\r\n    Markup : ```javascript\r\n             ```\r\n\r\n* Bullet list\r\n    * Nested bullet\r\n        * Sub-nested bullet etc\r\n* Bullet list item 2\r\n\r\n~~~\r\n Markup : * Bullet list\r\n              * Nested bullet\r\n                  * Sub-nested bullet etc\r\n          * Bullet list item 2\r\n~~~\r\n\r\n1. A numbered list\r\n    1. A nested numbered list\r\n    2. Which is numbered\r\n2. Which is numbered\r\n\r\n~~~\r\n Markup : 1. A numbered list\r\n              1. A nested numbered list\r\n              2. Which is numbered\r\n          2. Which is numbered\r\n~~~\r\n\r\n- [ ] An uncompleted task\r\n- [x] A completed task\r\n\r\n~~~\r\n Markup : - [ ] An uncompleted task\r\n          - [x] A completed task\r\n~~~\r\n\r\n> Blockquote\r\n>> Nested blockquote\r\n\r\n    Markup :  > Blockquote\r\n              >> Nested Blockquote\r\n\r\n_Horizontal line :_\r\n- - - -\r\n\r\n    Markup :  - - - -\r\n\r\n_Image with alt :_\r\n\r\n![picture alt](http://www.brightlightpictures.com/assets/images/portfolio/thethaw_header.jpg \"Title is optional\")\r\n\r\n    Markup : ![picture alt](http://www.brightlightpictures.com/assets/images/portfolio/thethaw_header.jpg \"Title is optional\")\r\n\r\nFoldable text:\r\n\r\n<details>\r\n  <summary>Title 1</summary>\r\n  <p>Content 1 Content 1 Content 1 Content 1 Content 1</p>\r\n</details>\r\n<details>\r\n  <summary>Title 2</summary>\r\n  <p>Content 2 Content 2 Content 2 Content 2 Content 2</p>\r\n</details>\r\n\r\n    Markup : <details>\r\n               <summary>Title 1</summary>\r\n               <p>Content 1 Content 1 Content 1 Content 1 Content 1</p>\r\n             </details>\r\n\r\n```html\r\n<h3>HTML</h3>\r\n<p> Some HTML code here </p>\r\n```\r\n\r\nHotkey:\r\n\r\n<kbd>⌘F</kbd>\r\n\r\n<kbd>⇧⌘F</kbd>\r\n\r\n    Markup : <kbd>⌘F</kbd>\r\n\r\nHotkey list:\r\n\r\n| Key | Symbol |\r\n| --- | --- |\r\n| Option | ⌥ |\r\n| Control | ⌃ |\r\n| Command | ⌘ |\r\n| Shift | ⇧ |\r\n| Caps Lock | ⇪ |\r\n| Tab | ⇥ |\r\n| Esc | ⎋ |\r\n| Power | ⌽ |\r\n| Return | ↩ |\r\n| Delete | ⌫ |\r\n| Up | ↑ |\r\n| Down | ↓ |\r\n| Left | ← |\r\n| Right | → |\r\n\r\nEmoji:\r\n\r\n:exclamation: Use emoji icons to enhance text. :+1:  Look up emoji codes at [emoji-cheat-sheet.com](http://emoji-cheat-sheet.com/)\r\n\r\n    Markup : Code appears between colons :EMOJICODE:\r\n"
  },
  {
    "path": "MongoDB/README.md",
    "content": "# MongoDB Cheat Sheet\n\n## Show All Databases\n\n```\nshow dbs\n```\n\n## Show Current Database\n\n```\ndb\n```\n\n## Create Or Switch Database\n\n```\nuse acme\n```\n\n## Drop\n\n```\ndb.dropDatabase()\n```\n\n## Create Collection\n\n```\ndb.createCollection('posts')\n```\n\n## Show Collections\n\n```\nshow collections\n```\n\n## Insert Row\n\n```\ndb.posts.insert({\n  title: 'Post One',\n  body: 'Body of post one',\n  category: 'News',\n  tags: ['news', 'events'],\n  user: {\n    name: 'John Doe',\n    status: 'author'\n  },\n  date: Date()\n})\n```\n\n## Insert Multiple Rows\n\n```\ndb.posts.insertMany([\n  {\n    title: 'Post Two',\n    body: 'Body of post two',\n    category: 'Technology',\n    date: Date()\n  },\n  {\n    title: 'Post Three',\n    body: 'Body of post three',\n    category: 'News',\n    date: Date()\n  },\n  {\n    title: 'Post Four',\n    body: 'Body of post three',\n    category: 'Entertainment',\n    date: Date()\n  }\n])\n```\n\n## Get All Rows\n\n```\ndb.posts.find()\n```\n\n## Get All Rows Formatted\n\n```\ndb.posts.find().pretty()\n```\n\n## Find Rows\n\n```\ndb.posts.find({ category: 'News' })\n```\n\n## Sort Rows\n\n```\n# asc\ndb.posts.find().sort({ title: 1 }).pretty()\n# desc\ndb.posts.find().sort({ title: -1 }).pretty()\n```\n\n## Count Rows\n\n```\ndb.posts.find().count()\ndb.posts.find({ category: 'news' }).count()\n```\n\n## Limit Rows\n\n```\ndb.posts.find().limit(2).pretty()\n```\n\n## Chaining\n\n```\ndb.posts.find().limit(2).sort({ title: 1 }).pretty()\n```\n\n## Foreach\n\n```\ndb.posts.find().forEach(function(doc) {\n  print(\"Blog Post: \" + doc.title)\n})\n```\n\n## Find One Row\n\n```\ndb.posts.findOne({ category: 'News' })\n```\n\n## Find Specific Fields\n\n```\ndb.posts.find({ title: 'Post One' }, {\n  title: 1,\n  author: 1\n})\n```\n\n## Update Row\n\n```\ndb.posts.update({ title: 'Post Two' },\n{\n  title: 'Post Two',\n  body: 'New body for post 2',\n  date: Date()\n},\n{\n  upsert: true\n})\n```\n\n## Update Specific Field\n\n```\ndb.posts.update({ title: 'Post Two' },\n{\n  $set: {\n    body: 'Body for post 2',\n    category: 'Technology'\n  }\n})\n```\n\n## Increment Field (\\$inc)\n\n```\ndb.posts.update({ title: 'Post Two' },\n{\n  $inc: {\n    likes: 5\n  }\n})\n```\n\n## Rename Field\n\n```\ndb.posts.update({ title: 'Post Two' },\n{\n  $rename: {\n    likes: 'views'\n  }\n})\n```\n\n## Delete Row\n\n```\ndb.posts.remove({ title: 'Post Four' })\n```\n\n## Sub-Documents\n\n```\ndb.posts.update({ title: 'Post One' },\n{\n  $set: {\n    comments: [\n      {\n        body: 'Comment One',\n        user: 'Mary Williams',\n        date: Date()\n      },\n      {\n        body: 'Comment Two',\n        user: 'Harry White',\n        date: Date()\n      }\n    ]\n  }\n})\n```\n\n## Find By Element in Array (\\$elemMatch)\n\n```\ndb.posts.find({\n  comments: {\n     $elemMatch: {\n       user: 'Mary Williams'\n       }\n    }\n  }\n)\n```\n\n## Add Index\n\n```\ndb.posts.createIndex({ title: 'text' })\n```\n\n## Text Search\n\n```\ndb.posts.find({\n  $text: {\n    $search: \"\\\"Post O\\\"\"\n    }\n})\n```\n\n## Greater & Less Than\n\n```\ndb.posts.find({ views: { $gt: 2 } })\ndb.posts.find({ views: { $gte: 7 } })\ndb.posts.find({ views: { $lt: 7 } })\ndb.posts.find({ views: { $lte: 7 } })\n```\n"
  },
  {
    "path": "MongoDB/sql_mongo_comparison.md",
    "content": "[SQL to MongoDB Mapping Chart](http://docs.mongodb.org/manual/reference/sql-comparison/#sql-to-mongodb-mapping-chart)\n<div class=\"section\" id=\"sql-to-mongodb-mapping-chart\">\n<h1>SQL to MongoDB Mapping Chart<a class=\"headerlink\" href=\"#sql-to-mongodb-mapping-chart\" title=\"Permalink to this headline\">¶</a></h1>\n<p>In addition to the charts that follow, you might want to consider the\n<a class=\"reference internal\" href=\"../../faq/\"><em>Frequently Asked Questions</em></a> section for a selection of common questions about MongoDB.</p>\n<div class=\"section\" id=\"executables\">\n<h2>Executables<a class=\"headerlink\" href=\"#executables\" title=\"Permalink to this headline\">¶</a></h2>\n<p>The following table presents the MySQL/Oracle executables and the\ncorresponding MongoDB executables.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"25%\">\n<col width=\"22%\">\n<col width=\"52%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">&nbsp;</th>\n<th class=\"head\">MySQL/Oracle</th>\n<th class=\"head\">MongoDB</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td>Database Server</td>\n<td>mysqld/oracle</td>\n<td><a class=\"reference internal\" href=\"../mongod/\"><em>mongod</em></a></td>\n</tr>\n<tr class=\"row-odd\"><td>Database Client</td>\n<td>mysql/sqlplus</td>\n<td><a class=\"reference internal\" href=\"../mongo/\"><em>mongo</em></a></td>\n</tr>\n</tbody>\n</table>\n</div>\n<div class=\"section\" id=\"terminology-and-concepts\">\n<h2>Terminology and Concepts<a class=\"headerlink\" href=\"#terminology-and-concepts\" title=\"Permalink to this headline\">¶</a></h2>\n<p>The following table presents the various SQL terminology and concepts\nand the corresponding MongoDB terminology and concepts.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"51%\">\n<col width=\"49%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">SQL Terms/Concepts</th>\n<th class=\"head\">MongoDB Terms/Concepts</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td>database</td>\n<td><a class=\"reference internal\" href=\"../glossary/#term-database\"><em class=\"xref std std-term\">database</em></a></td>\n</tr>\n<tr class=\"row-odd\"><td>table</td>\n<td><a class=\"reference internal\" href=\"../glossary/#term-collection\"><em class=\"xref std std-term\">collection</em></a></td>\n</tr>\n<tr class=\"row-even\"><td>row</td>\n<td><a class=\"reference internal\" href=\"../glossary/#term-document\"><em class=\"xref std std-term\">document</em></a> or <a class=\"reference internal\" href=\"../glossary/#term-bson\"><em class=\"xref std std-term\">BSON</em></a> document</td>\n</tr>\n<tr class=\"row-odd\"><td>column</td>\n<td><a class=\"reference internal\" href=\"../glossary/#term-field\"><em class=\"xref std std-term\">field</em></a></td>\n</tr>\n<tr class=\"row-even\"><td>index</td>\n<td><a class=\"reference internal\" href=\"../glossary/#term-index\"><em class=\"xref std std-term\">index</em></a></td>\n</tr>\n<tr class=\"row-odd\"><td>table joins</td>\n<td>embedded documents and linking</td>\n</tr>\n<tr class=\"row-even\"><td><p class=\"first\">primary key</p>\n<p class=\"last\">Specify any unique column or column combination as primary\nkey.</p>\n</td>\n<td><p class=\"first\"><a class=\"reference internal\" href=\"../glossary/#term-primary-key\"><em class=\"xref std std-term\">primary key</em></a></p>\n<p class=\"last\">In MongoDB, the primary key is automatically set to the\n<a class=\"reference internal\" href=\"../glossary/#term-id\"><em class=\"xref std std-term\">_id</em></a> field.</p>\n</td>\n</tr>\n<tr class=\"row-odd\"><td>aggregation (e.g. group by)</td>\n<td><p class=\"first\">aggregation framework</p>\n<p class=\"last\">See the <a class=\"reference internal\" href=\"../sql-aggregation-comparison/\"><em>SQL to Aggregation Framework Mapping Chart</em></a>.</p>\n</td>\n</tr>\n</tbody>\n</table>\n</div>\n<div class=\"section\" id=\"examples\">\n<h2>Examples<a class=\"headerlink\" href=\"#examples\" title=\"Permalink to this headline\">¶</a></h2>\n<p>The following table presents the various SQL statements and the\ncorresponding MongoDB statements. The examples in the table assume the\nfollowing conditions:</p>\n<ul>\n<li><p class=\"first\">The SQL examples assume a table named <tt class=\"docutils literal\"><span class=\"pre\">users</span></tt>.</p>\n</li>\n<li><p class=\"first\">The MongoDB examples assume a collection named <tt class=\"docutils literal\"><span class=\"pre\">users</span></tt> that contain\ndocuments of the following prototype:</p>\n<div class=\"highlight-javascript\"><div class=\"highlight\"><pre><span class=\"p\">{</span>\n  <span class=\"nx\">_id</span><span class=\"o\">:</span> <span class=\"nx\">ObjectID</span><span class=\"p\">(</span><span class=\"s2\">\"509a8fb2f3f4948bd2f983a0\"</span><span class=\"p\">),</span>\n  <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"s2\">\"abc123\"</span><span class=\"p\">,</span>\n  <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"mi\">55</span><span class=\"p\">,</span>\n  <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s1\">'A'</span>\n<span class=\"p\">}</span>\n</pre></div>\n</div>\n</li>\n</ul>\n<div class=\"section\" id=\"create-and-alter\">\n<h3>Create and Alter<a class=\"headerlink\" href=\"#create-and-alter\" title=\"Permalink to this headline\">¶</a></h3>\n<p>The following table presents the various SQL statements related to\ntable-level actions and the corresponding MongoDB statements.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"22%\">\n<col width=\"39%\">\n<col width=\"39%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">SQL Schema Statements</th>\n<th class=\"head\">MongoDB Schema Statements</th>\n<th class=\"head\">Reference</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">CREATE</span> <span class=\"k\">TABLE</span> <span class=\"n\">users</span> <span class=\"p\">(</span>\n    <span class=\"n\">id</span> <span class=\"n\">MEDIUMINT</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span>\n        <span class=\"n\">AUTO_INCREMENT</span><span class=\"p\">,</span>\n    <span class=\"n\">user_id</span> <span class=\"nb\">Varchar</span><span class=\"p\">(</span><span class=\"mi\">30</span><span class=\"p\">),</span>\n    <span class=\"n\">age</span> <span class=\"nb\">Number</span><span class=\"p\">,</span>\n    <span class=\"n\">status</span> <span class=\"nb\">char</span><span class=\"p\">(</span><span class=\"mi\">1</span><span class=\"p\">),</span>\n    <span class=\"k\">PRIMARY</span> <span class=\"k\">KEY</span> <span class=\"p\">(</span><span class=\"n\">id</span><span class=\"p\">)</span>\n<span class=\"p\">)</span>\n</pre></div>\n</div>\n</td>\n<td><p class=\"first\">Implicitly created on first <a class=\"reference internal\" href=\"../method/db.collection.insert/#db.collection.insert\" title=\"db.collection.insert\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">insert</span></tt></a> operation. The primary key <tt class=\"docutils literal\"><span class=\"pre\">_id</span></tt> is\nautomatically added if <tt class=\"docutils literal\"><span class=\"pre\">_id</span></tt> field is not specified.</p>\n<div class=\"highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">insert</span><span class=\"p\">(</span> <span class=\"p\">{</span>\n</span><span class=\"hll\">    <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"s2\">\"abc123\"</span><span class=\"p\">,</span>\n</span><span class=\"hll\">    <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"mi\">55</span><span class=\"p\">,</span>\n</span><span class=\"hll\">    <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span>\n</span><span class=\"hll\"> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n<p>However, you can also explicitly create a collection:</p>\n<div class=\"last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">createCollection</span><span class=\"p\">(</span><span class=\"s2\">\"users\"</span><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See\n<a class=\"reference internal\" href=\"../method/db.collection.insert/#db.collection.insert\" title=\"db.collection.insert\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">insert()</span></tt></a> and\n<a class=\"reference internal\" href=\"../method/db.createCollection/#db.createCollection\" title=\"db.createCollection\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">createCollection()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">ALTER</span> <span class=\"k\">TABLE</span> <span class=\"n\">users</span>\n<span class=\"k\">ADD</span> <span class=\"n\">join_date</span> <span class=\"n\">DATETIME</span>\n</pre></div>\n</div>\n</td>\n<td>Collections do not describe or enforce the structure of the\nconstituent documents. See the <a class=\"reference external\" href=\"http://www.mongodb.org/display/DOCS/Schema+Design\">Schema Design</a> wiki page for more information.</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.update/#db.collection.update\" title=\"db.collection.update\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">update()</span></tt></a> and\n<a class=\"reference internal\" href=\"../operators/#_S_set\" title=\"$set\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$set</span></tt></a> for more information on changing the structure\nof documents in a collection.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">ALTER</span> <span class=\"k\">TABLE</span> <span class=\"n\">users</span>\n<span class=\"k\">DROP</span> <span class=\"k\">COLUMN</span> <span class=\"n\">join_date</span>\n</pre></div>\n</div>\n</td>\n<td>Collections do not describe or enforce the structure of the\nconstituent documents. See the <a class=\"reference external\" href=\"http://www.mongodb.org/display/DOCS/Schema+Design\">Schema Design</a> wiki page for more information.</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.update/#db.collection.update\" title=\"db.collection.update\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">update()</span></tt></a> and\n<a class=\"reference internal\" href=\"../operators/#_S_set\" title=\"$set\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$set</span></tt></a> for more information on changing the structure\nof documents in a collection.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">CREATE</span> <span class=\"k\">INDEX</span> <span class=\"n\">idx_user_id_asc</span>\n<span class=\"k\">ON</span> <span class=\"n\">users</span><span class=\"p\">(</span><span class=\"n\">user_id</span><span class=\"p\">)</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">ensureIndex</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"mi\">1</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.ensureIndex/#db.collection.ensureIndex\" title=\"db.collection.ensureIndex\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">ensureIndex()</span></tt></a>\nand <a class=\"reference internal\" href=\"../../core/indexes/\"><em>indexes</em></a> for more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">CREATE</span> <span class=\"k\">INDEX</span>\n       <span class=\"n\">idx_user_id_asc_age_desc</span>\n<span class=\"k\">ON</span> <span class=\"n\">users</span><span class=\"p\">(</span><span class=\"n\">user_id</span><span class=\"p\">,</span> <span class=\"n\">age</span> <span class=\"k\">DESC</span><span class=\"p\">)</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">ensureIndex</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"o\">-</span><span class=\"mi\">1</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.ensureIndex/#db.collection.ensureIndex\" title=\"db.collection.ensureIndex\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">ensureIndex()</span></tt></a>\nand <a class=\"reference internal\" href=\"../../core/indexes/\"><em>indexes</em></a> for more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">DROP</span> <span class=\"k\">TABLE</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">drop</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.drop/#db.collection.drop\" title=\"db.collection.drop\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">drop()</span></tt></a> for\nmore information.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<div class=\"section\" id=\"insert\">\n<h3>Insert<a class=\"headerlink\" href=\"#insert\" title=\"Permalink to this headline\">¶</a></h3>\n<p>The following table presents the various SQL statements related to\ninserting records into tables and the corresponding MongoDB statements.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"30%\">\n<col width=\"31%\">\n<col width=\"39%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">SQL INSERT Statements</th>\n<th class=\"head\">MongoDB insert() Statements</th>\n<th class=\"head\">Reference</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">INSERT</span> <span class=\"k\">INTO</span> <span class=\"n\">users</span><span class=\"p\">(</span><span class=\"n\">user_id</span><span class=\"p\">,</span>\n                  <span class=\"n\">age</span><span class=\"p\">,</span>\n                  <span class=\"n\">status</span><span class=\"p\">)</span>\n<span class=\"k\">VALUES</span> <span class=\"p\">(</span><span class=\"ss\">\"bcd001\"</span><span class=\"p\">,</span>\n        <span class=\"mi\">45</span><span class=\"p\">,</span>\n        <span class=\"ss\">\"A\"</span><span class=\"p\">)</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">insert</span><span class=\"p\">(</span> <span class=\"p\">{</span>\n</span><span class=\"hll\">       <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"s2\">\"bcd001\"</span><span class=\"p\">,</span>\n</span><span class=\"hll\">       <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"mi\">45</span><span class=\"p\">,</span>\n</span><span class=\"hll\">       <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span>\n</span><span class=\"hll\"><span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.insert/#db.collection.insert\" title=\"db.collection.insert\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">insert()</span></tt></a>\nfor more information.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<div class=\"section\" id=\"select\">\n<h3>Select<a class=\"headerlink\" href=\"#select\" title=\"Permalink to this headline\">¶</a></h3>\n<p>The following table presents the various SQL statements related to\nreading records from tables and the corresponding MongoDB statements.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"21%\">\n<col width=\"42%\">\n<col width=\"37%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">SQL SELECT Statements</th>\n<th class=\"head\">MongoDB find() Statements</th>\n<th class=\"head\">Reference</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"n\">id</span><span class=\"p\">,</span> <span class=\"n\">user_id</span><span class=\"p\">,</span> <span class=\"n\">status</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"p\">},</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"mi\">1</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"n\">user_id</span><span class=\"p\">,</span> <span class=\"n\">status</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"p\">},</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"nx\">_id</span><span class=\"o\">:</span> <span class=\"mi\">0</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"n\">user_id</span><span class=\"p\">,</span> <span class=\"n\">status</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">},</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"nx\">_id</span><span class=\"o\">:</span> <span class=\"mi\">0</span> <span class=\"p\">}</span>\n</span><span class=\"p\">)</span>\n</pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">!=</span> <span class=\"ss\">\"A\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$ne</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_ne\" title=\"$ne\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$ne</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n<span class=\"k\">AND</span> <span class=\"n\">age</span> <span class=\"o\">=</span> <span class=\"mi\">50</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span><span class=\"p\">,</span>\n</span><span class=\"hll\">      <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"mi\">50</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_and\" title=\"$and\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$and</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n<span class=\"k\">OR</span> <span class=\"n\">age</span> <span class=\"o\">=</span> <span class=\"mi\">50</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">$or</span><span class=\"o\">:</span> <span class=\"p\">[</span> <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span> <span class=\"p\">,</span>\n</span><span class=\"hll\">             <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"mi\">50</span> <span class=\"p\">}</span> <span class=\"p\">]</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_or\" title=\"$or\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$or</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">age</span> <span class=\"o\">&gt;</span> <span class=\"mi\">25</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">    <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$gt</span><span class=\"o\">:</span> <span class=\"mi\">25</span> <span class=\"p\">}</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_gt\" title=\"$gt\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$gt</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">age</span> <span class=\"o\">&lt;</span> <span class=\"mi\">25</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$lt</span><span class=\"o\">:</span> <span class=\"mi\">25</span> <span class=\"p\">}</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_lt\" title=\"$lt\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$lt</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">age</span> <span class=\"o\">&gt;</span> <span class=\"mi\">25</span>\n<span class=\"k\">AND</span>   <span class=\"n\">age</span> <span class=\"o\">&lt;=</span> <span class=\"mi\">50</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$gt</span><span class=\"o\">:</span> <span class=\"mi\">25</span><span class=\"p\">,</span> <span class=\"nx\">$lte</span><span class=\"o\">:</span> <span class=\"mi\">50</span> <span class=\"p\">}</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>,\n<a class=\"reference internal\" href=\"../operators/#_S_gt\" title=\"$gt\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$gt</span></tt></a>, and <a class=\"reference internal\" href=\"../operators/#_S_lte\" title=\"$lte\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$lte</span></tt></a> for\nmore information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">user_id</span> <span class=\"k\">like</span> <span class=\"ss\">\"%bc%\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"sr\">/bc/</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_regex\" title=\"$regex\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$regex</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">user_id</span> <span class=\"k\">like</span> <span class=\"ss\">\"bc%\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"sr\">/^bc/</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../operators/#_S_regex\" title=\"$regex\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$regex</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n<span class=\"k\">ORDER</span> <span class=\"k\">BY</span> <span class=\"n\">user_id</span> <span class=\"k\">ASC</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span> <span class=\"p\">).</span><span class=\"nx\">sort</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"mi\">1</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../method/cursor.sort/#cursor.sort\" title=\"cursor.sort\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">sort()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n<span class=\"k\">ORDER</span> <span class=\"k\">BY</span> <span class=\"n\">user_id</span> <span class=\"k\">DESC</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span> <span class=\"p\">).</span><span class=\"nx\">sort</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"o\">-</span><span class=\"mi\">1</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../method/cursor.sort/#cursor.sort\" title=\"cursor.sort\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">sort()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"k\">COUNT</span><span class=\"p\">(</span><span class=\"o\">*</span><span class=\"p\">)</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">count</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n<p><em>or</em></p>\n<div class=\"last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">().</span><span class=\"nx\">count</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../method/cursor.count/#cursor.count\" title=\"cursor.count\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">count()</span></tt></a> for\nmore information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"k\">COUNT</span><span class=\"p\">(</span><span class=\"n\">user_id</span><span class=\"p\">)</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">count</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$exists</span><span class=\"o\">:</span> <span class=\"kc\">true</span> <span class=\"p\">}</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n<p><em>or</em></p>\n<div class=\"last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">user_id</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$exists</span><span class=\"o\">:</span> <span class=\"kc\">true</span> <span class=\"p\">}</span> <span class=\"p\">}</span> <span class=\"p\">).</span><span class=\"nx\">count</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>,\n<a class=\"reference internal\" href=\"../method/cursor.count/#cursor.count\" title=\"cursor.count\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">count()</span></tt></a>, and\n<a class=\"reference internal\" href=\"../operators/#_S_exists\" title=\"$exists\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$exists</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"k\">COUNT</span><span class=\"p\">(</span><span class=\"o\">*</span><span class=\"p\">)</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">age</span> <span class=\"o\">&gt;</span> <span class=\"mi\">30</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">count</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$gt</span><span class=\"o\">:</span> <span class=\"mi\">30</span> <span class=\"p\">}</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n<p><em>or</em></p>\n<div class=\"last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$gt</span><span class=\"o\">:</span> <span class=\"mi\">30</span> <span class=\"p\">}</span> <span class=\"p\">}</span> <span class=\"p\">).</span><span class=\"nx\">count</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>,\n<a class=\"reference internal\" href=\"../method/cursor.count/#cursor.count\" title=\"cursor.count\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">count()</span></tt></a>, and\n<a class=\"reference internal\" href=\"../operators/#_S_gt\" title=\"$gt\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$gt</span></tt></a> for more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"k\">DISTINCT</span><span class=\"p\">(</span><span class=\"n\">status</span><span class=\"p\">)</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">distinct</span><span class=\"p\">(</span> <span class=\"s2\">\"status\"</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../method/db.collection.distinct/#db.collection.distinct\" title=\"db.collection.distinct\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">distinct()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">LIMIT</span> <span class=\"mi\">1</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">findOne</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n<p><em>or</em></p>\n<div class=\"last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">().</span><span class=\"nx\">limit</span><span class=\"p\">(</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>,\n<a class=\"reference internal\" href=\"../method/db.collection.findOne/#db.collection.findOne\" title=\"db.collection.findOne\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">findOne()</span></tt></a>,\nand <a class=\"reference internal\" href=\"../method/cursor.limit/#cursor.limit\" title=\"cursor.limit\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">limit()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">LIMIT</span> <span class=\"mi\">5</span>\n<span class=\"n\">SKIP</span> <span class=\"mi\">10</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">().</span><span class=\"nx\">limit</span><span class=\"p\">(</span><span class=\"mi\">5</span><span class=\"p\">).</span><span class=\"nx\">skip</span><span class=\"p\">(</span><span class=\"mi\">10</span><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>,\n<a class=\"reference internal\" href=\"../method/cursor.limit/#cursor.limit\" title=\"cursor.limit\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">limit()</span></tt></a>, and\n<a class=\"reference internal\" href=\"../method/cursor.skip/#cursor.skip\" title=\"cursor.skip\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">skip()</span></tt></a> for\nmore information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">EXPLAIN</span> <span class=\"k\">SELECT</span> <span class=\"o\">*</span>\n<span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">find</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span> <span class=\"p\">).</span><span class=\"nx\">explain</span><span class=\"p\">()</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.find/#db.collection.find\" title=\"db.collection.find\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">find()</span></tt></a>\nand <a class=\"reference internal\" href=\"../method/cursor.explain/#cursor.explain\" title=\"cursor.explain\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">explain()</span></tt></a>\nfor more information.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<div class=\"section\" id=\"update-records\">\n<h3>Update Records<a class=\"headerlink\" href=\"#update-records\" title=\"Permalink to this headline\">¶</a></h3>\n<p>The following table presents the various SQL statements related to\nupdating existing records in tables and the corresponding MongoDB\nstatements.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"21%\">\n<col width=\"32%\">\n<col width=\"47%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">SQL Update Statements</th>\n<th class=\"head\">MongoDB update() Statements</th>\n<th class=\"head\">Reference</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">UPDATE</span> <span class=\"n\">users</span>\n<span class=\"k\">SET</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"C\"</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">age</span> <span class=\"o\">&gt;</span> <span class=\"mi\">25</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">update</span><span class=\"p\">(</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">$gt</span><span class=\"o\">:</span> <span class=\"mi\">25</span> <span class=\"p\">}</span> <span class=\"p\">},</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">$set</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"C\"</span> <span class=\"p\">}</span> <span class=\"p\">},</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">multi</span><span class=\"o\">:</span> <span class=\"kc\">true</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.update/#db.collection.update\" title=\"db.collection.update\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">update()</span></tt></a>,\n<a class=\"reference internal\" href=\"../operators/#_S_gt\" title=\"$gt\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$gt</span></tt></a>, and <a class=\"reference internal\" href=\"../operators/#_S_set\" title=\"$set\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$set</span></tt></a> for more\ninformation.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">UPDATE</span> <span class=\"n\">users</span>\n<span class=\"k\">SET</span> <span class=\"n\">age</span> <span class=\"o\">=</span> <span class=\"n\">age</span> <span class=\"o\">+</span> <span class=\"mi\">3</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"A\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">update</span><span class=\"p\">(</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"A\"</span> <span class=\"p\">}</span> <span class=\"p\">,</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">$inc</span><span class=\"o\">:</span> <span class=\"p\">{</span> <span class=\"nx\">age</span><span class=\"o\">:</span> <span class=\"mi\">3</span> <span class=\"p\">}</span> <span class=\"p\">},</span>\n</span><span class=\"hll\">   <span class=\"p\">{</span> <span class=\"nx\">multi</span><span class=\"o\">:</span> <span class=\"kc\">true</span> <span class=\"p\">}</span>\n</span><span class=\"hll\"><span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.update/#db.collection.update\" title=\"db.collection.update\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">update()</span></tt></a>,\n<a class=\"reference internal\" href=\"../operators/#_S_inc\" title=\"$inc\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$inc</span></tt></a>, and <a class=\"reference internal\" href=\"../operators/#_S_set\" title=\"$set\"><tt class=\"xref mongodb mongodb-operator docutils literal\"><span class=\"pre\">$set</span></tt></a> for more\ninformation.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<div class=\"section\" id=\"delete-records\">\n<h3>Delete Records<a class=\"headerlink\" href=\"#delete-records\" title=\"Permalink to this headline\">¶</a></h3>\n<p>The following table presents the various SQL statements related to\ndeleting records from tables and the corresponding MongoDB statements.</p>\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"21%\">\n<col width=\"35%\">\n<col width=\"44%\">\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">SQL Delete Statements</th>\n<th class=\"head\">MongoDB remove() Statements</th>\n<th class=\"head\">Reference</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">DELETE</span> <span class=\"k\">FROM</span> <span class=\"n\">users</span>\n<span class=\"k\">WHERE</span> <span class=\"n\">status</span> <span class=\"o\">=</span> <span class=\"ss\">\"D\"</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">remove</span><span class=\"p\">(</span> <span class=\"p\">{</span> <span class=\"nx\">status</span><span class=\"o\">:</span> <span class=\"s2\">\"D\"</span> <span class=\"p\">}</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.remove/#db.collection.remove\" title=\"db.collection.remove\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">remove()</span></tt></a>\nfor more information.</td>\n</tr>\n<tr class=\"row-odd\"><td><div class=\"first last highlight-sql\"><div class=\"highlight\"><pre><span class=\"k\">DELETE</span> <span class=\"k\">FROM</span> <span class=\"n\">users</span>\n</pre></div>\n</div>\n</td>\n<td><div class=\"first last highlight-javascript\"><div class=\"highlight\"><pre><span class=\"hll\"><span class=\"nx\">db</span><span class=\"p\">.</span><span class=\"nx\">users</span><span class=\"p\">.</span><span class=\"nx\">remove</span><span class=\"p\">(</span> <span class=\"p\">)</span>\n</span></pre></div>\n</div>\n</td>\n<td>See <a class=\"reference internal\" href=\"../method/db.collection.remove/#db.collection.remove\" title=\"db.collection.remove\"><tt class=\"xref mongodb mongodb-method docutils literal\"><span class=\"pre\">remove()</span></tt></a>\nfor more information.</td>\n</tr>\n</tbody>\n</table>\n</div>\n</div>\n</div>"
  },
  {
    "path": "Oracle SQL/README.md",
    "content": "# SQL cheatsheet\r\n\r\n#### This is note taken from the [SQL course on Codecademy](https://www.codecademy.com/learn/learn-sql).\r\n\r\n## Manipulation  \r\n\r\n```sql\r\nCREATE TABLE celebs (id INTEGER, name TEXT, age INTEGER);\r\n```\r\n\r\nThis `CREATE` statement creates a new table in the database named `celebs`. You can use the `CREATE` statement anytime you want to create a new table from scratch.\r\n\r\n1. `CREATE TABLE` is a clause that tells SQL you want to create a new table. \r\n\r\n\r\n2. `celebs` is the name of the table. \r\n\r\n\r\n3. `(id INTEGER, name TEXT, age INTEGER)`is a list of parameters defining each column in the table and its data type. \r\n\r\n- `id` is the first column in the table. It stores values of data type `INTEGER`\r\n- `name` is the second column in the table. It stores values of data type `TEXT`\r\n- `age` is the third column in the table. It stores values of data type `INTEGER`\r\n\r\n\r\n\r\nAdd a row to the table. In the code editor type\r\n\r\n```sql\r\nINSERT INTO celebs (id, name, age) VALUES (1, 'Justin Bieber', 21);\r\n```\r\n\r\nTo view the row you just created, under the `INSERT` statement type `SELECT * FROM celebs;`.\r\n\r\nThis `INSERT` statement inserts new rows into a table. You can use the `INSERT` statement when you want to add new records.\r\n\r\n1. `INSERT INTO` is a clause that adds the specified row or rows. \r\n2. `celebs` is the name of the table the row is added to. \r\n3. `(id, name, age)` is a parameter identifying the columns that data will be inserted into. \r\n4. `VALUES` is a clause that indicates the data being inserted. \r\n`(1, 'Justin Bieber', 21)` is a parameter identifying the values being inserted.\r\n\r\n- `1` is an integer that will be inserted into the `id` column\r\n- `'Justin Bieber'` is text that will be inserted into the `name` column\r\n- `21` is an integer that will be inserted into the `age` column\r\n\r\n\r\n\r\n```sql\r\nSELECT name FROM celebs;\r\n```\r\n\r\n`SELECT` statements are used to fetch data from a database. Here, `SELECT` returns all data in the `name` column of the `celebs` table.\r\n\r\n1. `SELECT` is a clause that indicates that the statement is a query. You will use `SELECT` every time you query data from a database. \r\n2. `name` specifies the column to query data from. \r\n3. `FROM celebs` specifies the name of the table to query data from. In this statement, data is queried from the `celebs` table. \r\n\r\nYou can also query data from all columns in a table with `SELECT`.\r\n\r\n```sql\r\nSELECT * FROM celebs;\r\n```\r\n\r\n`*` is a special wildcard character that we have been using. It allows you to select every column in a table without having to name each one individually. Here, the result set contains every column in the `celebs` table.\r\n\r\n`SELECT` statements always return a new table called the *result set*.\r\n\r\n\r\n\r\n```sql\r\nUPDATE celebs\r\nSET age = 22\r\nWHERE id = 1;\r\n```\r\n\r\nThe `UPDATE` statement edits a row in the table. You can use the `UPDATE` statement when you want to change existing records.\r\n\r\n1. `UPDATE` is a clause that edits a row in the table. \r\n2. `celebs` is the name of the table. \r\n3. `SET` is a clause that indicates the column to edit.\r\n\r\n- `age` is the name of the column that is going to be updated\r\n- `22` is the new value that is going to be inserted into the `age` column.\r\n\r\n4. `WHERE` is a clause that indicates which row(s) to update with the new column value. Here the row with a `1` in the `id` column is the row that will have the `age` updated to `22`.\r\n\r\n\r\n\r\n```sql\r\nALTER TABLE celebs ADD COLUMN twitter_handle TEXT;\r\n```\r\n\r\nThe `ALTER TABLE` statement added a new column to the table. You can use this command when you want to add columns to a table.\r\n\r\n1. `ALTER TABLE` is a clause that lets you make the specified changes. \r\n2. `celebs` is the name of the table that is being changed. \r\n3. `ADD COLUMN` is a clause that lets you add a new column to a table. \r\n\r\n- `twitter_handle` is the name of the new column being added\r\n- `TEXT` is the data type for the new column\r\n\r\n4. `NULL` is a special value in SQL that represents missing or unknown data. Here, the rows that existed before the column was added have `NULL`values for `twitter_handle`.\r\n\r\n\r\n\r\n```sql\r\nDELETE FROM celebs WHERE twitter_handle IS NULL;\r\n```\r\n\r\nThe `DELETE FROM` statement deletes one or more rows from a table. You can use the statement when you want to delete existing records.\r\n\r\n1. `DELETE FROM` is a clause that lets you delete rows from a table.\r\n2. `celebs` is the name of the table we want to delete rows from.\r\n3. `WHERE` is a clause that lets you select which rows you want to delete. Here we want to delete all of the rows where the twitter_handle column `IS NULL`.\r\n4. `IS NULL` is a condition in SQL that returns true when the value is `NULL` and false otherwise.\r\n\r\n\r\n\r\n## Queries  \r\n\r\n### Database Schema\r\n\r\n| movies220 rows |         |\r\n| -------------- | ------- |\r\n| id             | INTEGER |\r\n| name           | TEXT    |\r\n| genre          | TEXT    |\r\n| year           | INTEGER |\r\n| imdb_rating    | REAL    |\r\n\r\n\r\n\r\n```sql\r\nSELECT name, imdb_rating FROM movies;\r\n```\r\n\r\nIn Lesson 1 you learned that `SELECT` is used every time you want to query data from a database.\r\n\r\nMultiple columns can be queried at once by separating column names with a comma. By specifying `name, imdb_rating`, the result set contains a `name` and `imdb_rating` column.\r\n\r\n\r\n\r\n```sql\r\nSELECT DISTINCT genre FROM movies;\r\n```\r\n\r\n`SELECT DISTINCT` is used to return unique values in the result set. It filters out all duplicate values. Here, the result set lists each genre in the `movies` table exactly once.\r\n\r\n1. `SELECT DISTINCT` specifies that the statement is going to be a query that returns unique values in the specified column(s)\r\n\r\n2. `genre` is the name of the column to display in the result set.\r\n\r\n3. `FROM movies` indicates the table name to query from.\r\n\r\nFiltering the results of a query is an important skill in SQL. It is easier to see the different possible genres a movie can have after the data has been filtered, than to scan every row in the table.\r\n\r\nThe rest of this lesson will teach you different commands in SQL to filter the results of a query.\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM movies\r\n  WHERE imdb_rating > 8;\r\n```\r\n\r\nThis statement filters the result set to only include movies with IMDb ratings greater than 8. How does it work?\r\n\r\n1. `WHERE` is a clause that indicates you want to filter the result set to include only rows where the following *condition* is true.\r\n\r\n2. `imdb_rating > 8` is a condition that filters the result set. Here, only rows with a value greater than 8 in the `imdb_rating` column will be returned in the result set.\r\n\r\n3. `>` is an *operator*. Operators create a condition that can be evaluated as either true or false. Common operators used with the `WHERE` clause are:\r\n\r\n- `=` equals\r\n- `!=` not equals\r\n- `>` greater than\r\n- `<` less than\r\n- `>=` greater than or equal to\r\n- `<=` less than or equal to\r\n\r\nThere are also some special operators that we will learn more about in the upcoming exercises.\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM movies\r\nWHERE name LIKE 'Se_en';\r\n```\r\n\r\n`LIKE` can be a useful operator when you want to compare similar values. Here, we are comparing two movies with the same name but are spelled differently.\r\n\r\n1. `LIKE` is a special operator used with the `WHERE` clause to search for a specific pattern in a column.\r\n\r\n2. `name LIKE Se_en` is a condition evaluating the `name` column for a specific pattern.\r\n\r\n3. `Se_en` represents a pattern with a *wildcard* character. The `_` means you can substitute any individual character here without breaking the pattern. The names `Seven` and `Se7en` both match this pattern.\r\n\r\n`%` is another wildcard character that can be used with `LIKE`. We will learn more about `%` in the next exercise.\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM movies\r\nWHERE name LIKE 'A%';\r\n```\r\n\r\nThis statement filters the result set to only include movies with names that begin with the letter \"A\"\r\n\r\n`%` is a wildcard character that matches zero or more missing letters in the pattern.\r\n\r\n- `A%` matches all movies with names that begin with \"A\"\r\n- `%a` matches all movies that end with \"a\"\r\n\r\n```sql\r\nSELECT * FROM movies WHERE name LIKE '%man%';\r\n```\r\n\r\nYou can use `%` both before and after a pattern. Here, any movie that contains the word \"man\" in its name will be returned in the result set. Notice, that `LIKE` is not case sensitive. \"Batman\" and \"Man Of Steel\" both appear in the result set.\r\n\r\n\r\n\r\nThe `BETWEEN` operator is used to filter the result set within a certain range. The values can be numbers, text or dates.\r\n\r\n```sql\r\nSELECT * FROM movies\r\nWHERE name BETWEEN 'A' AND 'J';\r\n```\r\n\r\nThis statement filters the result set to only include movies with `name`s that begin with letters \"A\" up to but not including \"J\".\r\n\r\n```sql\r\nSELECT * FROM movies WHERE year BETWEEN 1990 AND 2000;\r\n```\r\n\r\nIn this statement, the `BETWEEN` operator is being used to filter the result set to only include movies with `year`s between 1990 up to and including 2000.\r\n\r\n\r\n\r\n```sql\r\n  SELECT * FROM movies\r\n  WHERE year BETWEEN 1990 and 2000\r\n  AND genre = 'comedy';\r\n```\r\n\r\nSometimes you want to combine multiple conditions in a `WHERE` clause to make the result set more specific and useful. One way of doing this is to use the `AND` operator.\r\n\r\n1. `year BETWEEN 1990 and 2000` is the first condition in the `WHERE` clause.\r\n\r\n\r\n2. `AND genre = 'comedy'` is the second condition in the `WHERE` clause.\r\n\r\n3. `AND` is an operator that combines two conditions. Both conditions must be true for the row to be included in the result set. Here, we use the `AND` operator to only return movies made between 1990 and 2000 that are also comedies.\r\n\r\n\r\n\r\n```sql\r\n  SELECT * FROM movies\r\n  WHERE genre = 'comedy'\r\n  OR year < 1980;\r\n```\r\n\r\nThe `OR` operator can also be used to combine more than one condition in a `WHERE` clause. The `OR` operator evaluates each condition separately and if any of the conditions are true then the row is added to the result set.\r\n\r\n1. `WHERE genre = 'comedy'` is the first condition in the `WHERE` clause.\r\n\r\n2. `OR year < 1980` is the second condition in the `WHERE` clause.\r\n\r\n3. `OR` is an operator that filters the result set to only include rows where either condition is true. Here, we return movies that either have a genre of comedy or were released before 1980.\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM movies\r\nORDER BY imdb_rating DESC;\r\n```\r\n\r\nYou can sort the results of your query using `ORDER BY`. Sorting the results often makes the data more useful and easier to analyze.\r\n\r\n1. `ORDER BY` is a clause that indicates you want to sort the result set by a particular column either alphabetically or numerically.\r\n\r\n2. `imdb_rating` is the name of the column that will be sorted.\r\n\r\n3. `DESC` is a keyword in SQL that is used with `ORDER BY` to sort the results in *descending order* (high to low or Z-A). Here, it sorts all of the movies from highest to lowest by their IMDb rating.\r\n\r\nIt is also possible to sort the results in *ascending order*. `ASC` is a keyword in SQL that is used with `ORDER BY` to sort the results in ascending order (low to high or A-Z).\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM movies\r\nORDER BY imdb_rating DESC\r\nLIMIT 3;\r\n```\r\n\r\nSometimes even filtered results can return thousands of rows in large databases. In these situations it becomes important to cap the number of rows in a result set.\r\n\r\n`LIMIT` is a clause that lets you specify the maximum number of rows the result set will have. Here, we specify that the result set can not have more than three rows.\r\n\r\n\r\n\r\n## Aggregrate Functions  \r\n\r\n### Database Schema\r\n\r\n| fake_apps200 rows |         |\r\n| ----------------- | ------- |\r\n| id                | INTEGER |\r\n| name              | TEXT    |\r\n| category          | TEXT    |\r\n| downloads         | INTEGER |\r\n| price             | REAL    |\r\n\r\n\r\n\r\n```sql\r\nSELECT COUNT(*) FROM fake_apps;\r\n```\r\n\r\nThe fastest way to calculate the number of rows in a table is to use the `COUNT()` function.\r\n\r\n`COUNT()` is a function that takes the name of a column as an argument and counts the number of rows where the column is not `NULL`. Here, we want to count every row so we pass `*` as an argument.\r\n\r\n\r\n\r\n```sql\r\nSELECT price, COUNT(*) FROM fake_apps\r\nGROUP BY price;\r\n```\r\n\r\nAggregate functions are more useful when they organize data into groups.\r\n\r\n`GROUP BY` is a clause in SQL that is only used with aggregate functions. It is used in collaboration with the `SELECT` statement to arrange identical data into groups.\r\n\r\nHere, our aggregate function is `COUNT()` and we are passing `price` as an argument to `GROUP BY`. SQL will count the total number of apps for each `price` in the table.\r\n\r\nIt is usually helpful to `SELECT` the column you pass as an argument to `GROUP BY`. Here we select `price` and `COUNT(*)`. You can see that the result set is organized into two columns making it easy to see the number of apps at each price.\r\n\r\nCount the total number of apps at each price that have been downloaded more than 20,000 times. \r\n\r\n```sql\r\nSELECT price, COUNT(*) FROM fake_apps WHERE downloads > 20000 GROUP BY price;\r\n```\r\n\r\n\r\n\r\n```sql\r\nSELECT SUM(downloads) FROM fake_apps;\r\n```\r\n\r\nSQL makes it easy to add all values in a particular column using `SUM()`.\r\n\r\n`SUM()` is a function that takes the name of a column as an argument and returns the sum of all the values in that column. Here, it adds all the values in the `downloads` column.\r\n\r\n\r\n\r\n```sql\r\nSELECT MAX(downloads) FROM fake_apps;\r\n```\r\n\r\nYou can find the largest value in a column by using `MAX()`.\r\n\r\n`MAX()` is a function that takes the name of a column as an argument and returns the largest value in that column. Here, we pass `downloads`as an argument so it will return the largest value in the `downloads` column.\r\n\r\n\r\n\r\nReturn the names of the most downloaded apps in each category.\r\n\r\n```sql\r\nSELECT name, category, MAX(downloads) FROM fake_apps GROUP BY category;\r\n```\r\n\r\n\r\n\r\n```sql\r\nSELECT MIN(downloads) FROM fake_apps;\r\n```\r\n\r\nSimilar to `MAX()`, SQL also makes it easy to return the smallest value in a column by using the `MIN()` function. `MIN()` is a function that takes the name of a column as an argument and returns the smallest value in that column. Here, we pass `downloads`as an argument so it will return the smallest value in the `downloads` column.\r\n\r\n\r\n\r\n```sql\r\nSELECT AVG(downloads) FROM fake_apps;\r\n```\r\n\r\nThis statement returns the average number of downloads for an app in our database. SQL uses the `AVG()` function to quickly calculate the average value of a particular column.\r\n\r\nThe `AVG()` function works by taking a column name as an argument and returns the average value for that column.\r\n\r\n\r\n\r\n```sql\r\nSELECT price, ROUND(AVG(downloads), 2) FROM fake_apps\r\nGROUP BY price;\r\n```\r\n\r\nBy default, SQL tries to be as precise as possible without rounding. We can make the result set easier to read using the `ROUND()` function.\r\n\r\n`ROUND()` is a function that takes a column name and an integer as an argument. It rounds the values in the column to the number of decimal places specified by the integer. Here, we pass the column `AVG(downloads)` and `2` as arguments. SQL first calculates the average for each price and then rounds the result to two decimal places in the result set.\r\n\r\n\r\n\r\nRound the average number of downloads to the nearest integer for each price. \r\n\r\n```sql\r\nSELECT price, ROUND(AVG(downloads)) FROM fake_apps\r\nGROUP BY price;\r\n```\r\n\r\n## Multiple Tables\r\n\r\nSo far we have learned how to build tables, write queries, and perform calculations using one table. In this lesson we will learn to query multiple tables that have relationships with each other.\r\n\r\nMost of the time, data is distributed across multiple tables in the database. Imagine a database with two tables, `artists` and `albums`. An artist can produce many different albums, and an album is produced by an artist.\r\n\r\nThe data in these tables are related to each other. Through SQL, we can write queries that combine data from multiple tables that are related to one another. This is one of the most powerful features of relational databases.\r\n\r\n### Database Schema\r\n\r\n| albums14 rows |         |\r\n| ------------- | ------- |\r\n| id            | INTEGER |\r\n| name          | TEXT    |\r\n| artist_id     | INTEGER |\r\n| year          | INTEGER |\r\n\r\n| artists0 rows |         |\r\n| ------------- | ------- |\r\n| id            | INTEGER |\r\n| name          | TEXT    |\r\n\r\n\r\n\r\nWe have created a table named `albums`for you. Create a second table named `artists`. \r\n\r\n```sql\r\nCREATE TABLE artists(id INTEGER PRIMARY KEY, name TEXT);\r\n```\r\n\r\n```sql\r\nCREATE TABLE artists(id INTEGER PRIMARY KEY, name TEXT)\r\n```\r\n\r\nUsing the `CREATE TABLE` statement we added a `PRIMARY KEY` to the `id` column.\r\n\r\nA **primary key** serves as a unique identifier for each row or record in a given table. The primary key is literally an `id` value for a record. We're going to use this value to connect `artists` to the `albums` they have produced.\r\n\r\nBy specifying that the `id` column is the `PRIMARY KEY`, SQL makes sure that:\r\n\r\n- None of the values in this column are `NULL`\r\n- Each value in this column is unique\r\n\r\nA table can not have more than one `PRIMARY KEY` column.\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM albums WHERE artist_id = 3;\r\nSELECT * FROM artists WHERE id = 3;\r\n```\r\n\r\nA *foreign key* is a column that contains the primary key of another table in the database. We use foreign keys and primary keys to connect rows in two different tables. One table's foreign key holds the value of another table's primary key. Unlike primary keys, foreign keys do not need to be unique and can be `NULL`.\r\n\r\nHere, `artist_id` is a foreign key in the `albums`table. We can see that Michael Jackson has an `id`of 3 in the `artists` table. All of the albums by Michael Jackson also have a 3 in the `artist_id`column in the `albums` table.\r\n\r\nThis is how SQL is linking data between the two tables. The *relationship* between the `artists`table and the `albums` table is the `id` value of the artists.\r\n\r\n\r\n\r\n```sql\r\nSELECT albums.name, albums.year, artists.name FROM albums, artists\r\n```\r\n\r\nOne way to query multiple tables is to write a `SELECT` statement with multiple table names separated by a comma. This is also known as a *cross join*. Here, `albums` and `artists` are the different tables we are querying.\r\n\r\nWhen querying more than one table, column names need to be specified by `table_name.column_name`. Here, the result set includes the `name` and `year` columns from the `albums` table and the `name` column from the `artists` table.\r\n\r\n**Unfortunately the result of this cross join is not very useful. It combines every row of the `artists` table with every row of the `albums`table. It would be more useful to only combine the rows where the album was created by the artist.**\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM albums JOIN artists ON albums.artist_id = artists.id;\r\n```\r\n\r\nIn SQL, joins are used to combine rows from two or more tables. The most common type of join in SQL is an *inner join*.\r\n\r\nAn inner join will combine rows from different tables if the *join condition* is true. Let's look at the syntax to see how it works.\r\n\r\n1. `SELECT *` specifies the columns our result set will have. Here, we want to include every column in both tables.\r\n2. `FROM albums` specifies the first table we are querying.\r\n3. `JOIN artists ON` specifies the type of join we are going to use as well as the name of the second table. Here, we want to do an inner join and the second table we want to query is `artists`.\r\n4. `albums.artist_id = artists.id` is the join condition that describes how the two tables are related to each other. Here, SQL uses the foreign key column `artist_id` in the `albums` table to match it with exactly one row in the `artists` table with the same value in the `id` column. We know it will only match one row in the `artists` table because `id` is the `PRIMARY KEY` of `artists`.\r\n\r\n\r\n\r\n```sql\r\nSELECT * FROM albums LEFT JOIN artists ON albums.artist_id = artists.id;\r\n```\r\n\r\nOuter joins also combine rows from two or more tables, but unlike inner joins, they do not require the join condition to be met. Instead, every row in the *left* table is returned in the result set, and if the join condition is not met, then `NULL` values are used to fill in the columns from the *right* table.\r\n\r\nThe left table is simply the first table that appears in the statement. Here, the left table is `albums`. Likewise, the right table is the second table that appears. Here, `artists` is the right table.\r\n\r\n\r\n\r\n```sql\r\nSELECT\r\n  albums.name AS 'Album',\r\n  albums.year,\r\n  artists.name AS 'Artist'\r\nFROM\r\n  albums\r\nJOIN artists ON\r\n  albums.artist_id = artists.id\r\nWHERE\r\n  albums.year > 1980;\r\n```\r\n\r\n`AS` is a keyword in SQL that allows you to rename a column or table using an *alias*. The new name can be anything you want as long as you put it inside of single quotes. Here we want to rename the `albums.name` column as `'Album'`, and the `artists.name` column as `'Artist'`.\r\n\r\nIt is important to note that the columns have not been renamed in either table. The aliases only appear in the result set.\r\n\r\n## Some other commands:\r\nThe `SUBSTR` functions return a portion of `char`, beginning at character `position`, `substring_length` characters long. `SUBSTR` calculates lengths using characters as defined by the input character set. `SUBSTRB` uses bytes instead of characters. `SUBSTRC` uses Unicode complete characters. `SUBSTR2` uses UCS2 code points. `SUBSTR4`uses UCS4 code points.\r\n\r\n- If `position` is 0, then it is treated as 1.\r\n- If `position` is positive, then Oracle Database counts from the beginning of `char` to find the first character.\r\n- If `position` is negative, then Oracle counts backward from the end of `char`.\r\n- If `substring_length` is omitted, then Oracle returns all characters to the end of `char`. If `substring_length` is less than 1, then Oracle returns null.\r\n\r\n- Examples\r\n\r\n  The following example returns several specified substrings of \"ABCDEFG\":\r\n\r\n  ```sql\r\n  SELECT SUBSTR('ABCDEFG',3,4) \"Substring\"\r\n       FROM DUAL;\r\n   \r\n  Substring\r\n  ---------\r\n  CDEF\r\n\r\n  SELECT SUBSTR('ABCDEFG',-5,4) \"Substring\"\r\n       FROM DUAL;\r\n\r\n  Substring\r\n  ---------\r\n  CDEF\r\n  ```\r\n"
  },
  {
    "path": "Oracle SQL/SQL_commands.md",
    "content": "## COMMANDS\r\n\r\n### ALTER TABLE\r\n\r\n```\r\nALTER TABLE table_name ADD column datatype;\r\n```\r\n\r\n`ALTER TABLE` lets you add columns to a table in a database.\r\n\r\n### AND\r\n\r\n```\r\nSELECT column_name(s)\r\nFROM table_name\r\nWHERE column_1 = value_1\r\nAND column_2 = value_2;\r\n```\r\n\r\n`AND` is an operator that combines two conditions. Both conditions must be true for the row to be included in the result set.\r\n\r\n### AS\r\n\r\n```\r\nSELECT column_name AS 'Alias'\r\nFROM table_name;\r\n```\r\n\r\n`AS` is a keyword in SQL that allows you to rename a column or table using an *alias*.\r\n\r\n### AVG\r\n\r\n```\r\nSELECT AVG(column_name)\r\nFROM table_name;\r\n\r\n```\r\n\r\n`AVG()` is an aggregate function that returns the average value for a numeric column.\r\n\r\n### BETWEEN\r\n\r\n```\r\nSELECT column_name(s)\r\nFROM table_name\r\nWHERE column_name BETWEEN value_1 AND value_2;\r\n```\r\n\r\nThe `BETWEEN` operator is used to filter the result set within a certain range. The values can be numbers, text or dates.\r\n\r\n### COUNT\r\n\r\n```\r\nSELECT COUNT(column_name)\r\nFROM table_name;\r\n```\r\n\r\n`COUNT()` is a function that takes the name of a column as an argument and counts the number of rows where the column is not `NULL`.\r\n\r\n### CREATE TABLE\r\n\r\n```\r\nCREATE TABLE table_name (column_1 datatype, column_2 datatype, column_3 datatype);\r\n```\r\n\r\n`CREATE TABLE` creates a new table in the database. It allows you to specify the name of the table and the name of each column in the table.\r\n\r\n### DELETE\r\n\r\n```\r\nDELETE FROM table_name WHERE some_column = some_value;\r\n```\r\n\r\n`DELETE` statements are used to remove rows from a table.\r\n\r\n### GROUP BY\r\n\r\n```\r\nSELECT COUNT(*)\r\nFROM table_name\r\nGROUP BY column_name;\r\n```\r\n\r\n`GROUP BY` is a clause in SQL that is only used with aggregate functions. It is used in collaboration with the `SELECT` statement to arrange identical data into groups.\r\n\r\n### INNER JOIN\r\n\r\n```\r\nSELECT column_name(s) FROM table_1\r\nJOIN table_2\r\nON table_1.column_name = table_2.column_name;\r\n```\r\n\r\nAn inner join will combine rows from different tables if the *join condition* is true.\r\n\r\n### INSERT\r\n\r\n```\r\nINSERT INTO table_name (column_1, column_2, column_3) VALUES (value_1, 'value_2', value_3);\r\n```\r\n\r\n`INSERT` statements are used to add a new row to a table.\r\n\r\n### LIKE\r\n\r\n```\r\nSELECT column_name(s)\r\nFROM table_name\r\nWHERE column_name LIKE pattern;\r\n```\r\n\r\n`LIKE` is a special operator used with the `WHERE` clause to search for a specific pattern in a column.\r\n\r\n### LIMIT\r\n\r\n```\r\nSELECT column_name(s)\r\nFROM table_name\r\nLIMIT number;\r\n```\r\n\r\n`LIMIT` is a clause that lets you specify the maximum number of rows the result set will have.\r\n\r\n### MAX\r\n\r\n```\r\nSELECT MAX(column_name)\r\nFROM table_name;\r\n```\r\n\r\n`MAX()` is a function that takes the name of a column as an argument and returns the largest value in that column.\r\n\r\n### MIN\r\n\r\n```\r\nSELECT MIN(column_name)\r\nFROM table_name;\r\n```\r\n\r\n`MIN()` is a function that takes the name of a column as an argument and returns the smallest value in that column.\r\n\r\n### OR\r\n\r\n```\r\nSELECT column_name\r\nFROM table_name\r\nWHERE column_name = value_1\r\nOR column_name = value_2;\r\n```\r\n\r\n`OR` is an operator that filters the result set to only include rows where either condition is true.\r\n\r\n### ORDER BY\r\n\r\n```\r\nSELECT column_name\r\nFROM table_name\r\nORDER BY column_name ASC|DESC;\r\n```\r\n\r\n`ORDER BY` is a clause that indicates you want to sort the result set by a particular column either alphabetically or numerically.\r\n\r\n### OUTER JOIN\r\n\r\n```\r\nSELECT column_name(s) FROM table_1\r\nLEFT JOIN table_2\r\nON table_1.column_name = table_2.column_name;\r\n```\r\n\r\nAn outer join will combine rows from different tables even if the the join condition is not met. Every row in the *left* table is returned in the result set, and if the join condition is not met, then `NULL` values are used to fill in the columns from the *right* table.\r\n\r\n### ROUND\r\n\r\n```\r\nSELECT ROUND(column_name, integer)\r\nFROM table_name;\r\n```\r\n\r\n`ROUND()` is a function that takes a column name and an integer as an argument. It rounds the values in the column to the number of decimal places specified by the integer.\r\n\r\n### SELECT\r\n\r\n```\r\nSELECT column_name FROM table_name;\r\n```\r\n\r\n`SELECT` statements are used to fetch data from a database. Every query will begin with SELECT.\r\n\r\n### SELECT DISTINCT\r\n\r\n```\r\nSELECT DISTINCT column_name FROM table_name;\r\n```\r\n\r\n`SELECT DISTINCT` specifies that the statement is going to be a query that returns unique values in the specified column(s).\r\n\r\n### SUM\r\n\r\n```\r\nSELECT SUM(column_name)\r\nFROM table_name;\r\n```\r\n\r\n`SUM()` is a function that takes the name of a column as an argument and returns the sum of all the values in that column.\r\n\r\n### UPDATE\r\n\r\n```\r\nUPDATE table_name\r\nSET some_column = some_value\r\nWHERE some_column = some_value;\r\n```\r\n\r\n`UPDATE` statments allow you to edit rows in a table.\r\n\r\n### WHERE\r\n\r\n```\r\nSELECT column_name(s)\r\nFROM table_name\r\nWHERE column_name operator value;\r\n```\r\n\r\n`WHERE` is a clause that indicates you want to filter the result set to include only rows where the following *condition* is true.\r\n"
  },
  {
    "path": "PHP/README.md",
    "content": "# PHP Help Sheet\r\n\r\n## Treehouse PHP Classes\r\n\r\n> PHP OOP\r\n    > classes\r\n        > recipe.php\r\n        > cookbook.php\r\n\r\n```php\r\n// recipe.php\r\n\r\n<?php\r\n\r\nclass Recipe\r\n{\r\n    private $title;\r\n    public $ingredients = array();\r\n    public $instruction = array();\r\n    public $yield;\r\n    public $tag = array();\r\n    public $source = 'Alena Holligan';\r\n\r\n    private $measurements = array(\r\n        \"tsp\",\r\n        \"tbsp\",\r\n        \"cup\",\r\n        \"oz\",\r\n        \"lb\",\r\n        \"fl oz\",\r\n        \"pint\",\r\n        \"quart\",\r\n        \"gallon\"\r\n    );\r\n\r\n    public function displayRecipe()\r\n    {\r\n        return $this->title . \"by\" . $this->source;\r\n    }\r\n\r\n    public function addIngredient($item, $amount = null, $measure=null)\r\n    {\r\n        if ($amount != null && !is_float($amount) && !is_int($amount)) {\r\n            exit(\"The amount must be a float: \") . gettype($amount) . \" $amount given\");\r\n        }\r\n\r\n        if ($measure != null && !in_array(strtolower($measure), $this->measurements)) {\r\n            exit(\"Please enter a valid measurement: \" . implode(\", \", $this->measurements));\r\n        }\r\n\r\n        $this->ingredients[] = array (\r\n            \"item\" => ucwords($item),\r\n            \"amount\" => $amount,\r\n            \"measure\" => strtolower($measure)\r\n        );\r\n    }\r\n\r\n    public function getIngredients()\r\n    {\r\n        return $this->ingredients;\r\n    }\r\n\r\n    public function setTitle($title)\r\n    {\r\n        $this->title = ucword($title);\r\n    }\r\n\r\n    public function getTitle()\r\n    {\r\n        return $this->title;\r\n    }\r\n\r\n}\r\n\r\n?>\r\n\r\n// cookbook.php\r\n\r\n<?php\r\n\r\ninclude \"classes/recipes.php\";\r\n\r\n$recipe1 = new Recipe();\r\necho $recipe1->source;\r\n$recipe1->source(\"Grandma Holligan\");\r\necho $recipe1->source;\r\n$recipe1->setTitle(\"My first recipe\");\r\n$recipe1->getTitle();\r\n\r\n$recipe1->addIngredient(\"egg\",1);\r\n$recipe1->addIngredient(\"flour\",2,\"cup\");\r\n\r\n$recipe2 = new Recipe();\r\n$recipe2->source = \"Betty Crocker\";\r\n$recipe1->setTitle = \"My second recipe\";\r\n\r\necho $recipe1->source;\r\necho $recipe2->source;\r\n\r\necho $recipe1->displayRecipe();\r\necho $recipe2->displayRecipe();\r\n\r\nforeach ($recipe1->getIngredients() as $ing) {\r\n    echo \"\\n\" . $ing[\"amount\"] . \" \" . $ing[\"measure\"] . \" \" . $ing[\"item\"];\r\n}\r\n\r\nvar_dump($recipe1);\r\n\r\n?>\r\n```\r\n\r\n## PHP Access Modifiers\r\n\r\n```php\r\n<?php\r\n\r\nclass Render {\r\n\r\n  public static function displayDimensions($size) {\r\n      return $size[0] . \" x \" . $size[1];\r\n  }\r\n\r\n  public static function detailsKitchen($room) {\r\n       return \"Kitchen Dimensions: \" . self::displayDimensions($room->getDimensions());\r\n  }\r\n\r\n}\r\n\r\n?>\r\n```\r\n\r\n## PHP Magic Methods and Constants\r\n\r\nSome magic constants:\r\n\r\n__CLASS__\r\n__FILE__\r\n\r\n```php\r\n<?php\r\nclass Example\r\n{\r\n\r\n    public function __construct($title = null)\r\n    {\r\n        $this->setTitle($title);\r\n    }\r\n\r\n    public function __toString()\r\n    {\r\n        $output = \"You are calling a \" . __CLASS__ . \" object with the title \\\"\";\r\n        $output .= $this->getTitle() . \"\\\"\";\r\n        $output .= \"\\nIt is stored in \" . basename(__FILE__) . \" at \" . __DIR__ . \".\";\r\n        $output .= \"\\nThis display is from line \" . __LINE__ . \" in method \" . __METHOD__;\r\n        $output .= \"\\nThe following methods are available for objects of this class: \\n\";\r\n        $output .= implode(\"\\n\", get_class_methods(__CLASS__));\r\n        return $output;\r\n    }\r\n}\r\n\r\nclass Render\r\n{\r\n\r\n    public function __toString()\r\n    {\r\n        $output = \"The following methods are available for \" . __CLASS__ . \" objects: \\n\";\r\n        $output .= implode(\"\\n\", get_class_methods(__CLASS__));\r\n        return $output;\r\n    }\r\n}\r\n\r\n$example = new Example(\"Name\");\r\necho $example;\r\n\r\n?>\r\n\r\n<?php\r\n\r\nclass Fish\r\n{\r\n    public $common_name;\r\n    public $flavor;\r\n    public $record_weight;\r\n\r\n    public function __construct($name, $flavor, $record) {\r\n      $this->common_name = $name;\r\n      $this->flavor = $flavor;\r\n      $this->record_weight = $record;\r\n    }\r\n\r\n    public function getInfo() {\r\n      return \"A {$this->common_name} is an {$this->flavor} flavored fish. The world record weight is {$this->record_weight}.\";\r\n    }\r\n}\r\n\r\n$bass = new Fish(\"Largemouth Bass\", \"Excellent\", \"22 pounds 5 ounces\");\r\n\r\n?>\r\n```\r\n\r\n## PHP Collections\r\n\r\nrecipecollection.php\r\n\r\n```php\r\n<?\r\n\r\nclass RecipeCollection\r\n{\r\n    private $title;\r\n    private $recipes = array();\r\n\r\n    // has constructor here and setter and getters\r\n\r\n    public function addRecipe($recipe) {\r\n        $this->recipes[] = $recipe;\r\n    }\r\n\r\n    public function getRecipe() {\r\n        return $this->recipes;\r\n    }\r\n}\r\n\r\n?>\r\n```\r\n\r\n## PHP Arrays\r\n\r\nCreate\r\n$myArray = array();\r\n\r\nPush into\r\n$myArray[] = \"­Som­eth­ing­\";\r\n\r\nPush to associ­ative\r\n$myArr­ay[­'key'] = \"­Val­ue\";\r\n\r\nCreate numeric\r\n$myArray = array(­'va­lue', 'value2');\r\n\r\nCreate associ­ative\r\n$a = array(­'ke­y'=­>'v­al');\r\n\r\nPrint from numeric\r\necho $myArr­ay[0];\r\n\r\nPrint from associ­ative\r\necho $myArr­ay[­'key'];\r\n\r\nAssoci­ative arrays\r\nKeys are strings\r\n\r\nNumeric arrays\r\nKeys are numbers: 0,1,2,3,4\r\n\r\n## PHP Array Functions\r\n\r\narray_diff (arr1, arr2 ...)\r\narray_filter (arr, function)\r\narray_flip (arr)\r\narray_intersect (arr1, arr2 ...)\r\narray_merge (arr1, arr2 ...)\r\narray_pop (arr)\r\narray_push (arr, var1, var2 ...)\r\narray_reverse (arr)\r\narray_keys(array $array [, mixed $search_value = null [, bool $strict = false ]] )\r\narray_search (needle, arr)\r\narray_walk (arr, function)\r\ncount (count)\r\nin_array (needle, haystack)\r\n\r\n// ARRAY EXAMPLES\r\n\r\n```php\r\n<?php\r\n    // add code below this comment\r\nclass Subdivision\r\n{\r\n  public $houses = array();\r\n\r\n  public function filterHouseColor($color)\r\n  {\r\n    $return = array();\r\n    foreach ($this->houses as $house) {\r\n      if ($house->roof_color == $color || $house->wall_color == $color) {\r\n        $return[] = $house;\r\n      }\r\n    }\r\n    return $return;\r\n  }\r\n}\r\n\r\n?>\r\n\r\n<? php\r\n\r\npublic function getCombinedIngredients()\r\n{\r\n    $ingredients = array();\r\n    foreach ($this->recipes as $recipe) {\r\n        foreach($recipe->getIngredients() as $ing) {\r\n            $item = $ing[\"item\"];\r\n\r\n            if (strpos($item, \",\")) {\r\n                $item = strstr($item, \",\", true);\r\n            }\r\n\r\n            if (in_array($item.\"s\", $ingredients)) {\r\n                $item.=\"s\";\r\n            } else if (in_array(substr($item, 0, -1), $ingredients)) {\r\n                $item = substr($item, 0, -1);\r\n            }\r\n\r\n            $ingredients[$item] = array (\r\n                $ing[\"amount\"],\r\n                $ing[\"measure\"]\r\n            );\r\n        }\r\n    }\r\n\r\n    return $ingredients;\r\n}\r\n\r\n?>\r\n```\r\n\r\n## PHP Control Flow Logic\r\n\r\nif (condi­tion) {\r\n... }\r\nelseif (condi­tion) {\r\n... }\r\nelse {\r\n... }\r\n\r\nFOR loop\r\nfor (initi­alize; condition; update) { ... }\r\n\r\nWHILE loop\r\nwhile (condi­tion) { ... }\r\n\r\nFOREACH loop\r\nforeach ($array as $value) { ... }\r\n\r\nDO WHILE\r\ndo { ... ;} while (condi­tion)\r\n\r\nSWITCH ($s) {\r\ncase 1:\r\n...\r\nbreak;\r\ncase 2:\r\n...\r\nbreak;\r\ndefault:\r\n...\r\n}\r\n\r\n## PHP if/elseif statements within a web document\r\n\r\n```php\r\n<?php\r\n\r\n$bool = false;\r\n\r\n?>\r\n\r\n<?php if ($bool) : ?>\r\n\r\n    <div>\r\n        <p><?php echo \"Bool is true\"?></p>\r\n    </div>\r\n\r\n<?php elseif (!$bool) : ?>\r\n\r\n    <div>\r\n        <p><?php echo \"Elseif works\"?></p>\r\n    </div>\r\n\r\n<?php else : ?>\r\n\r\n    <div>\r\n        <p><?php echo \"Bool is false\"?></p>\r\n    </div>\r\n\r\n<?php endif; ?>\r\n```\r\n\r\n## PHP General Functions\r\n\r\nisset()\r\ntest for variable exists\r\nempty()\r\ntest for empty variable\r\nmail($to, $subject, $msg, 'From: ' . $email)\r\nmail function\r\nmysqli­_fe­tch­_ar­ray­($r­esult)\r\nfetch each row of a query (in $result)\r\nheader()\r\nsend a header from the server\r\nis_num­eric()\r\ntest to see if a value is number\r\nexit()\r\ncauses script to stop immedi­ately\r\ntrim($­string)\r\ntrims leading and trailing spaces\r\nmysqli­_re­al_­esc­ape­_st­rin­g($­string)\r\nescapes special characters\r\nstr_re­pla­ce('a', 'b', $string)\r\nreplace a with b in a string\r\nexplode(', ' , $string)\r\nmake string into array\r\nimplode(', \" $string)\r\nmake array into string\r\nsubstr ($string, start, len)\r\ngrabs a substring\r\npreg_m­atc­h('­regex', $string)\r\nmatches regular expres­sions\r\npreg_r­epl­ace­('r­egex', $replace, $string)\r\nreplaces characters in a string by regex\r\n\r\n##  PHP Regex Functions\r\n\r\nereg (pattern, str)\r\nsplit (pattern, str)\r\nereg_replace (pattern, replace, str)\r\npreg_grep (pattern, arr)\r\npreg_match (pattern, str)\r\npreg_match_all (pattern, str, arr)\r\npreg_replace (pattern, replace, str)\r\npreg_split (pattern, str)\r\n\r\n## PHP String Functions\r\n\r\ncrypt (str, salt)\r\nexplode (sep, str)\r\nimplode (glue, arr)\r\nnl2br (str)\r\nsprintf (frmt, args)\r\nstrip_tags (str, allowed_tags)\r\nstr_replace (search, replace, str)\r\nstrpos (str, needle)\r\nstrrev (str)\r\nstrstr (str, needle)\r\nstrtolower (str)\r\nstrtoupper (str)\r\nsubstr (string, start, len)\r\n\r\n## PHP File System Functions\r\n\r\nclearstatcache ()\r\ncopy (source, dest)\r\nfclose (handle)\r\nfgets (handle, len)\r\nfile (file)\r\nfilemtime (file)\r\nfilesize (file)\r\nfile_exists (file)\r\nfopen (file, mode)\r\nfread (handle, len)\r\nfwrite (handle, str)\r\nreadfile (file)clearstatcache ()\r\ncopy (source, dest)\r\nfclose (handle)\r\nfgets (handle, len)\r\nfile (file)\r\nfilemtime (file)\r\nfilesize (file)\r\nfile_exists (file)\r\nfopen (file, mode)\r\nfread (handle, len)\r\nfwrite (handle, str)\r\nreadfile (file)\r\n\r\n## PHP Date/Time Functions\r\n\r\ncheckdate (month, day, year)\r\ndate (format, timestamp)\r\ngetdate (timestamp)\r\nmktime (hr, min, sec, month, day, yr)\r\nstrftime (formatstring, timestamp)\r\nstrtotime (str)\r\ntime ()\r\n\r\n## PHP Date Formatting\r\n\r\nY\r\n4 digit year (2008)\r\ny\r\n2 digit year (08)\r\nF\r\nLong month (January)\r\nM\r\nShort month (Jan)\r\nm\r\nMonth ⁴ (01 to 12)\r\nn\r\nMonth (1 to 12)\r\nD\r\nShort day name (Mon)\r\nl\r\nLong day name (Monday) (lowercase L)\r\nd\r\nDay ⁴ (01 to 31)\r\nj\r\nDay (1 to 31)\r\n\r\nh\r\n12 Hour ⁴ (01 to 12)\r\ng\r\n12 Hour (1 to 12)\r\nH\r\n24 Hour ⁴ (00 to 23)\r\nG\r\n24 Hour (0 to 23)\r\ni\r\nMinutes ⁴ (00 to 59)\r\ns\r\nSeconds ⁴ (00 to 59)\r\n\r\nw\r\nDay of week ¹ (0 to 6)\r\nz\r\nDay of year (0 to 365)\r\nW\r\nWeek of year ² (1 to 53)\r\nt\r\nDays in month (28 to 31)\r\n\r\na\r\nam or pm\r\nA\r\nAM or PM\r\nB\r\nSwatch Internet Time (000 to 999)\r\nS\r\nOrdinal Suffix (st, nd, rd, th)\r\n\r\nT\r\nTimezone of machine (GMT)\r\nZ\r\nTimezone offset (seconds)\r\nO\r\nGMT offset (hours) (+0200)\r\nI\r\nDaylight saving (1 or 0)\r\nL\r\nLeap year (1 or 0)\r\n\r\nU\r\nSeconds since Epoch ³\r\nc\r\nISO 8601 (PHP 5) (2008-­07-­31T­18:­30:­13+­01:00)\r\nr\r\nRFC 2822 (Thu, 31 Jul 2008 18:30:13 +0100)\r\n\r\n\r\n## Accessing deep arrays to find values\r\n\r\n```php\r\n$locations = Timber::get_terms('locations');\r\n\r\n        $data = [];\r\n        $exclusion = [];\r\n\r\n        foreach($locations as $location) {\r\n            $data[] = [\r\n                \"location\" => $location,\r\n                \"posts\" => Locations::getPostsForLocation($location,$count,$exclusion)\r\n            ];\r\n\r\n            // add posts with current ids to array to check against\r\n            foreach ($data as $key => $value) {\r\n                if ($value[\"posts\"]) {\r\n                    $posts = $value[\"posts\"];\r\n                    foreach($posts as $key => $value) {\r\n                        if (in_array($value->id, $exclusion)) {\r\n                            unset($posts[$key]);\r\n                        } else {\r\n                            array_push($exclusion, $value->id);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n```"
  },
  {
    "path": "Perl/README.md",
    "content": "# Perl 5 Cheatsheet\r\n\r\n## Table of Contents\r\n\r\n- [General](#general)\r\n- [Strings and Numbers 1](#strings-and-numbers-1)\r\n- [Strings and Numbers 2](#strings-and-numbers-2)\r\n- [Subroutines 1](#subroutines-1)\r\n\r\n## General\r\n\r\n```perl\r\n# Tell the compiler to generate errors if variables are not declared\r\nuse strict;\r\n\r\n# Tell the compiler to show warnings\r\nuse warnings;\r\n\r\n# my creates block scoped variables\r\nmy $value = 0;\r\n\r\n# Print the Perl version\r\n# It prints something like 5.018002, which means 5.18.2\r\nprint(\"$]\\n\");\r\n\r\n# Print the operating sysyem\r\n# It prints something like darwin, linux, MSWin32, etc.\r\nprint(\"$^O\\n\");\r\n```\r\n\r\nReferences:\r\n- http://www.perlmonks.org/?node_id=185675\r\n\r\n\r\n## Strings and Numbers 1\r\n\r\n```perl\r\nuse strict;\r\nuse warnings;\r\n\r\nmy $scalar1 = 8;\r\nmy $scalar2 = 42;\r\nmy $scalar3 = \"8\";\r\n\r\n# Numeric Comparison:\r\n# ==, !=, <, >, <=, >=, <=>\r\nmy $result1 = $scalar1 == $scalar2;   # undef\r\nmy $result2 = $scalar1 < $scalar2;    # 1\r\nmy $result3 = $scalar1 <=> $scalar2;  # -1\r\n\r\n# String Comparison:\r\n# eq, ne, lt, gt, le, ge, cmp\r\nmy $result4 = $scalar1 eq $scalar3;   # 1\r\nmy $result5 = $scalar1 lt $scalar2;   # undef\r\nmy $result6 = $scalar1 cmp $scalar2;  # 1\r\n\r\n# Arithmetic Operators\r\n# $scalar3 behaves like a number\r\nprint($scalar2 + $scalar3, \"\\n\");   #       Addition: 50\r\nprint($scalar2 - $scalar3, \"\\n\");   #    Subtraction: 34\r\nprint($scalar2 * $scalar3, \"\\n\");   # Multiplication: 336\r\nprint($scalar2 / $scalar3, \"\\n\");   #       Division: 5.25\r\nprint($scalar2 % $scalar3, \"\\n\");   #      Remainder: 2\r\nprint($scalar2 ** $scalar3, \"\\n\");  # Exponentiation: 9682651996416\r\nprint(\"\\n\");\r\nprint($scalar2++, \"\\n\");            # Post-Increment: 42\r\nprint($scalar2, \"\\n\");              #                 43\r\nprint(++$scalar2, \"\\n\");            #  Pre-Increment: 44\r\nprint(\"\\n\");\r\n\r\n# String Operators\r\n# $scalar1 behaves like a string\r\nprint($scalar1 . $scalar3, \"\\n\");  # Concatenation: 88\r\nprint($scalar1 x $scalar3, \"\\n\");  #    Repetition: 88888888\r\nprint(\"\\n\");\r\n\r\n# Single Quotes and Double Quotes\r\nprint('$scalar1, $scalar2', \"\\n\");  # $scalar1, $scalar2\r\nprint(\"$scalar1, $scalar2\\n\");      # 8, 44\r\n```\r\n\r\nReferences:\r\n- `man perlop`\r\n\r\n## Strings and Numbers 2\r\n\r\n```perl\r\nuse strict;\r\nuse warnings;\r\n\r\nmy $scalar1 = 8;\r\nmy $scalar4 = \"foo\";\r\nmy $scalar5 = \"bar\";\r\n\r\n# $scalar4 behaves like zero\r\nprint($scalar4 + $scalar1, \"\\n\");    # 8, Warning: Argument \"foo\" isn't numeric in addition (+)\r\nprint($scalar4 - $scalar1, \"\\n\");    # -8\r\nprint($scalar4 * $scalar1, \"\\n\");    # 0\r\nprint($scalar4 / $scalar1, \"\\n\");    # 0\r\nprint($scalar4 % $scalar1, \"\\n\");    # 0\r\nprint($scalar4 ** $scalar1, \"\\n\");   # 0\r\nprint(\"\\n\");\r\nprint($scalar1 + $scalar4, \"\\n\");    # 8\r\nprint($scalar1 - $scalar4, \"\\n\");    # 8\r\nprint($scalar1 * $scalar4, \"\\n\");    # 0\r\n# print($scalar1 / $scalar4, \"\\n\");  # Error: Illegal division by zero\r\n# print($scalar1 % $scalar4, \"\\n\");  # Error: Illegal modulus zero\r\nprint($scalar1 ** $scalar4, \"\\n\");   # 1\r\nprint(\"\\n\");\r\n\r\n# String Increment\r\nprint($scalar5++, \"\\n\");  # Post-Increment: bar\r\nprint($scalar5, \"\\n\");    #                 bas\r\nprint(++$scalar5, \"\\n\");  #  Pre-Increment: bat\r\nprint(\"\\n\");\r\n\r\n# String Increment (Weird Behaviour)\r\n# $scalar4 becomes a number after the warning above\r\n# Tested on:\r\n# - Perl v5.18.2 on darwin\r\n# - Perl v5.24.2 on linux\r\nprint($scalar4++, \"\\n\");  # Post-Increment: foo\r\nprint($scalar4, \"\\n\");    #                 1\r\nprint(++$scalar4, \"\\n\");  #  Pre-Increment: 2\r\nprint(\"\\n\");\r\n```\r\n\r\n## Subroutines 1\r\n\r\n```perl\r\nuse strict;\r\nuse warnings;\r\n\r\n# Subroutine Forward Declaration\r\nsub print_first_three_arguments;\r\n\r\n# This prints: Amy Bob Cody\r\nprint_first_three_arguments(\"Amy\", \"Bob\", \"Cody\", \"Dan\");\r\n\r\n# Parentheses are optional\r\nprint_first_three_arguments \"Amy\", \"Bob\", \"Cody\", \"Dan\";\r\n\r\nsub print_first_three_arguments {\r\n    my $first = shift;\r\n    my $second = shift;\r\n    my $third = shift;\r\n    print($first, \" \", $second, \" \", $third, \"\\n\");\r\n}\r\n\r\n# Subroutine Reference (Function Pointer)\r\nmy $p3ptr = \\&print_first_three_arguments;\r\n$p3ptr->(\"Amy\", \"Bob\", \"Cody\", \"Dan\");\r\n\r\n# Old syntax, same result\r\n&$p3ptr(\"Amy\", \"Bob\", \"Cody\", \"Dan\");\r\n\r\n# Anonymous Subroutine\r\nmy $p3anon = sub {\r\n    my $first = shift;\r\n    my $second = shift;\r\n    my $third = shift;\r\n    print($first, \" \", $second, \" \", $third, \"\\n\");\r\n};\r\n$p3anon->(\"Amy\", \"Bob\", \"Cody\", \"Dan\");\r\n\r\n# Old syntax, same result\r\n&$p3anon(\"Amy\", \"Bob\", \"Cody\", \"Dan\");\r\n```\r\n"
  },
  {
    "path": "Python/CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\r\n\r\n## Our Pledge\r\n\r\nIn the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.\r\n\r\n## Our Standards\r\n\r\nExamples of behavior that contributes to creating a positive environment include:\r\n\r\n* Using welcoming and inclusive language\r\n* Being respectful of differing viewpoints and experiences\r\n* Gracefully accepting constructive criticism\r\n* Focusing on what is best for the community\r\n* Showing empathy towards other community members\r\n\r\nExamples of unacceptable behavior by participants include:\r\n\r\n* The use of sexualized language or imagery and unwelcome sexual attention or advances\r\n* Trolling, insulting/derogatory comments, and personal or political attacks\r\n* Public or private harassment\r\n* Publishing others' private information, such as a physical or electronic address, without explicit permission\r\n* Other conduct which could reasonably be considered inappropriate in a professional setting\r\n\r\n## Our Responsibilities\r\n\r\nProject maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.\r\n\r\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.\r\n\r\n## Scope\r\n\r\nThis Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.\r\n\r\n## Enforcement\r\n\r\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at carlos.w.montecinos@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.\r\n\r\nProject maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.\r\n\r\n## Attribution\r\n\r\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]\r\n\r\n[homepage]: http://contributor-covenant.org\r\n[version]: http://contributor-covenant.org/version/1/4/\r\n"
  },
  {
    "path": "Python/CONTRIBUTING.md",
    "content": "## Contributing 🎉\r\n\r\nFirst off, thank you for taking the time to contribute!\r\n\r\nThe following is a set of guidelines for contributing to the 🐍 cheatsheet. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to [this document](https://github.com/wilfredinni/python-cheatsheet/blob/master/CONTRIBUTING.md) in a pull request.\r\n\r\n### Code of Conduct\r\n\r\nThis project and everyone who participates in it is governed by the [Contributor Covenant Code of Conduct](https://github.com/wilfredinni/python-cheatsheet/blob/master/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to services@github.com.\r\n\r\n### You Can\r\n\r\n* Propose changes to the cheatsheet.\r\n* Improve existing topics and examples.\r\n* Add new topics or resources.\r\n* Ask for new topics by creating an [Issue](https://github.com/wilfredinni/python-cheatsheet/issues).\r\n* Read the issues, Fork the project and do a [Pull Request](https://github.com/wilfredinni/python-cheatsheet/pulls).\r\n* Report any kind of error or typo by creating an [Issue](https://github.com/wilfredinni/python-cheatsheet/issues) or fix it with a [Pull Request](https://github.com/wilfredinni/python-cheatsheet/pulls).\r\n* **Write an article** that *could* be published in the [Blog](https://www.pythoncheatsheet.org/blog) and used in the [webpage](https://www.pythoncheatsheet.org) as reference.\r\n\r\n### Styling\r\n\r\n**Important!** Edit only the README.md and if you can, use [Notedown](https://github.com/aaren/notedown) to convert it to a Jupyter Notebook (no problem if you can't).\r\n\r\n* Use `##` headers for titles.\r\n* Use `###` for the sub categories.\r\n* Add a link to your section to the table of contents.\r\n* Make sure to include examples and keep explanations short.\r\n* At the end of your section or sub category, add a [*Return to the Top*](#python-cheatsheet) link.\r\n\r\n### What you need to Know\r\n\r\nIf you don't know were to start, please check this out:\r\n\r\n* [Mastering Markdown](https://guides.github.com/features/mastering-markdown/).\r\n* [Mastering Issues](https://guides.github.com/features/issues/).\r\n* [Forking Projects](https://guides.github.com/activities/forking/).\r\n* And read the rest of the [GitHub Guides](https://guides.github.com/).\r\n\r\nThat is all! thank you again for taking the time to check how to contribute."
  },
  {
    "path": "Python/README.md",
    "content": "# Python Cheat Sheet\r\n\r\nBasic cheatsheet for Python mostly based on the book written by Al Sweigart, [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) under the [Creative Commons license](https://creativecommons.org/licenses/by-nc-sa/3.0/) and many other sources.\r\n\r\n## Contribute\r\n\r\nAll contributions are welcome:\r\n\r\n- Read the issues, Fork the project and do a Pull Request.\r\n- Request a new topic creating a `New issue` with the  `enhancement` tag.\r\n- Find any kind of errors in the cheat sheet and create a `New issue` with the details or fork the project and do a Pull Request.\r\n- Suggest a better or more pythonic way for existing examples.\r\n\r\n## Read It\r\n\r\n- [Website](https://www.pythoncheatsheet.org)\r\n- [Github](https://github.com/wilfredinni/python-cheatsheet)\r\n- [PDF](https://github.com/wilfredinni/Python-cheatsheet/raw/master/python_cheat_sheet.pdf)\r\n- [Jupyter Notebook](https://mybinder.org/v2/gh/wilfredinni/python-cheatsheet/master?filepath=python_cheat_sheet.ipynb)\r\n\r\n## Python Cheatsheet\r\n\r\n- [The Zen of Python](#the-zen-of-python)\r\n- [Python Basics](#python-basics)\r\n    - [Math Operators](#math-operators)\r\n    - [Data Types](#data-types)\r\n    - [String Concatenation and Replication](#string-concatenation-and-replication)\r\n    - [Variables](#variables)\r\n    - [Comments](#comments)\r\n    - [The print() Function](#the-print-function)\r\n    - [The input() Function](#the-input-function)\r\n    - [The len() Function](#the-len-function)\r\n    - [The str(), int(), and float() Functions](#the-str-int-and-float-functions)\r\n- [Flow Control](#flow-control)\r\n    - [Comparison Operators](#comparison-operators)\r\n    - [Boolean evaluation](#boolean-evaluation)\r\n    - [Boolean Operators](#boolean-operators)\r\n    - [Mixing Boolean and Comparison Operators](#mixing-boolean-and-comparison-operators)\r\n    - [if Statements](#if-statements)\r\n    - [else Statements](#else-statements)\r\n    - [elif Statements](#elif-statements)\r\n    - [while Loop Statements](#while-loop-statements)\r\n    - [break Statements](#break-statements)\r\n    - [continue Statements](#continue-statements)\r\n    - [for Loops and the range() Function](#for-loops-and-the-range-function)\r\n    - [For else statement](#for-else-statement)\r\n    - [Importing Modules](#importing-modules)\r\n    - [Ending a Program Early with sys.exit()](#ending-a-program-early-with-sysexit)\r\n- [Functions](#functions)\r\n    - [Return Values and return Statements](#return-values-and-return-statements)\r\n    - [The None Value](#the-none-value)\r\n    - [Keyword Arguments and print()](#keyword-arguments-and-print)\r\n    - [Local and Global Scope](#local-and-global-scope)\r\n    - [The global Statement](#the-global-statement)\r\n- [Exception Handling](#exception-handling)\r\n    - [Basic exception handling](#basic-exception-handling)\r\n    - [Final code in exception handling](#final-code-in-exception-handling)\r\n- [Lists](#lists)\r\n    - [Getting Individual Values in a List with Indexes](#getting-individual-values-in-a-list-with-indexes)\r\n    - [Negative Indexes](#negative-indexes)\r\n    - [Getting Sublists with Slices](#getting-sublists-with-slices)\r\n    - [Getting a List’s Length with len()](#getting-a-list%E2%80%99s-length-with-len)\r\n    - [Changing Values in a List with Indexes](#changing-values-in-a-list-with-indexes)\r\n    - [List Concatenation and List Replication](#list-concatenation-and-list-replication)\r\n    - [Removing Values from Lists with del Statements](#removing-values-from-lists-with-del-statements)\r\n    - [Using for Loops with Lists](#using-for-loops-with-lists)\r\n    - [Looping Through Multiple Lists with zip()](#looping-through-multiple-lists-with-zip)\r\n    - [The in and not in Operators](#the-in-and-not-in-operators)\r\n    - [The Multiple Assignment Trick](#the-multiple-assignment-trick)\r\n    - [Augmented Assignment Operators](#augmented-assignment-operators)\r\n    - [Finding a Value in a List with the index() Method](#finding-a-value-in-a-list-with-the-index-method)\r\n    - [Adding Values to Lists with the append() and insert() Methods](#adding-values-to-lists-with-the-append-and-insert-methods)\r\n    - [Removing Values from Lists with remove()](#removing-values-from-lists-with-remove)\r\n    - [Sorting the Values in a List with the sort() Method](#sorting-the-values-in-a-list-with-the-sort-method)\r\n    - [Tuple Data Type](#tuple-data-type)\r\n    - [Converting Types with the list() and tuple() Functions](#converting-types-with-the-list-and-tuple-functions)\r\n- [Dictionaries and Structuring Data](#dictionaries-and-structuring-data)\r\n    - [The keys(), values(), and items() Methods](#the-keys-values-and-items-methods)\r\n    - [Checking Whether a Key or Value Exists in a Dictionary](#checking-whether-a-key-or-value-exists-in-a-dictionary)\r\n    - [The get() Method](#the-get-method)\r\n    - [The setdefault() Method](#the-setdefault-method)\r\n    - [Pretty Printing](#pretty-printing)\r\n    - [Merge two dictionaries](#merge-two-dictionaries)\r\n- [sets](#sets)\r\n    - [Initializing a set](#initializing-a-set)\r\n    - [sets: unordered collections of unique elements](#sets-unordered-collections-of-unique-elements)\r\n    - [set add() and update()](#set-add-and-update)\r\n    - [set remove() and discard()](#set-remove-and-discard)\r\n    - [set union()](#set-union)\r\n    - [set intersection](#set-intersection)\r\n    - [set difference](#set-difference)\r\n    - [set symetric_difference](#set-symetricdifference)\r\n- [itertools Module](#itertools-module)\r\n    - [accumulate()](#accumulate)\r\n    - [combinations()](#combinations)\r\n    - [combinations_with_replacement()](#combinationswithreplacement)\r\n    - [count()](#count)\r\n    - [cycle()](#cycle)\r\n    - [chain()](#chain)\r\n    - [compress()](#compress)\r\n    - [dropwhile()](#dropwhile)\r\n    - [filterfalse()](#filterfalse)\r\n    - [groupby()](#groupby)\r\n    - [islice()](#islice)\r\n    - [permutations()](#permutations)\r\n    - [product()](#product)\r\n    - [repeat()](#repeat)\r\n    - [starmap()](#starmap)\r\n    - [takewhile()](#takewhile)\r\n    - [tee()](#tee)\r\n    - [zip_longest()](#ziplongest)\r\n- [Comprehensions](#comprehensions)\r\n    - [List comprehension](#list-comprehension)\r\n    - [Set comprehension](#set-comprehension)\r\n    - [Dict comprehension](#dict-comprehension)\r\n- [Manipulating Strings](#manipulating-strings)\r\n    - [Escape Characters](#escape-characters)\r\n    - [Raw Strings](#raw-strings)\r\n    - [Multiline Strings with Triple Quotes](#multiline-strings-with-triple-quotes)\r\n    - [Indexing and Slicing Strings](#indexing-and-slicing-strings)\r\n    - [The in and not in Operators with Strings](#the-in-and-not-in-operators-with-strings)\r\n    - [The in and not in Operators with list](#the-in-and-not-in-operators-with-list)\r\n    - [The upper(), lower(), isupper(), and islower() String Methods](#the-upper-lower-isupper-and-islower-string-methods)\r\n    - [The isX String Methods](#the-isx-string-methods)\r\n    - [The startswith() and endswith() String Methods](#the-startswith-and-endswith-string-methods)\r\n    - [The join() and split() String Methods](#the-join-and-split-string-methods)\r\n    - [Justifying Text with rjust(), ljust(), and center()](#justifying-text-with-rjust-ljust-and-center)\r\n    - [Removing Whitespace with strip(), rstrip(), and lstrip()](#removing-whitespace-with-strip-rstrip-and-lstrip)\r\n    - [Copying and Pasting Strings with the pyperclip Module (need pip install)](#copying-and-pasting-strings-with-the-pyperclip-module-need-pip-install)\r\n- [String Formatting](#string-formatting)\r\n    - [% operator](#operator)\r\n    - [String Formatting (str.format)](#string-formatting-strformat)\r\n    - [Lazy string formatting](#lazy-string-formatting)\r\n    - [Formatted String Literals or f-strings (Python 3.6+)](#formatted-string-literals-or-f-strings-python-36)\r\n    - [Template Strings](#template-strings)\r\n- [Regular Expressions](#regular-expressions)\r\n    - [Matching Regex Objects](#matching-regex-objects)\r\n    - [Grouping with Parentheses](#grouping-with-parentheses)\r\n    - [Matching Multiple Groups with the Pipe](#matching-multiple-groups-with-the-pipe)\r\n    - [Optional Matching with the Question Mark](#optional-matching-with-the-question-mark)\r\n    - [Matching Zero or More with the Star](#matching-zero-or-more-with-the-star)\r\n    - [Matching One or More with the Plus](#matching-one-or-more-with-the-plus)\r\n    - [Matching Specific Repetitions with Curly Brackets](#matching-specific-repetitions-with-curly-brackets)\r\n    - [Greedy and Nongreedy Matching](#greedy-and-nongreedy-matching)\r\n    - [The findall() Method](#the-findall-method)\r\n    - [Making Your Own Character Classes](#making-your-own-character-classes)\r\n    - [The Caret and Dollar Sign Characters](#the-caret-and-dollar-sign-characters)\r\n    - [The Wildcard Character](#the-wildcard-character)\r\n    - [Matching Everything with Dot-Star](#matching-everything-with-dot-star)\r\n    - [Matching Newlines with the Dot Character](#matching-newlines-with-the-dot-character)\r\n    - [Review of Regex Symbols](#review-of-regex-symbols)\r\n    - [Case-Insensitive Matching](#case-insensitive-matching)\r\n    - [Substituting Strings with the sub() Method](#substituting-strings-with-the-sub-method)\r\n    - [Managing Complex Regexes](#managing-complex-regexes)\r\n- [Handling File and Directory Paths](#handling-file-and-directory-paths)\r\n    - [Backslash on Windows and Forward Slash on OS X and Linux](#backslash-on-windows-and-forward-slash-on-os-x-and-linux)\r\n    - [The Current Working Directory](#the-current-working-directory)\r\n    - [Creating New Folders](#creating-new-folders)\r\n    - [Absolute vs. Relative Paths](#absolute-vs-relative-paths)\r\n    - [Handling Absolute and Relative Paths](#handling-absolute-and-relative-paths)\r\n    - [Checking Path Validity](#checking-path-validity)\r\n    - [Finding File Sizes and Folder Contents](#finding-file-sizes-and-folder-contents)\r\n    - [Copying Files and Folders](#copying-files-and-folders)\r\n    - [Moving and Renaming Files and Folders](#moving-and-renaming-files-and-folders)\r\n    - [Permanently Deleting Files and Folders](#permanently-deleting-files-and-folders)\r\n    - [Safe Deletes with the send2trash Module](#safe-deletes-with-the-send2trash-module)\r\n    - [Walking a Directory Tree](#walking-a-directory-tree)\r\n- [Reading and Writing Files](#reading-and-writing-files)\r\n    - [The File Reading/Writing Process](#the-file-readingwriting-process)\r\n    - [Opening and reading files with the open() function](#opening-and-reading-files-with-the-open-function)\r\n    - [Writing to Files](#writing-to-files)\r\n    - [Saving Variables with the shelve Module](#saving-variables-with-the-shelve-module)\r\n    - [Saving Variables with the pprint.pformat() Function](#saving-variables-with-the-pprintpformat-function)\r\n    - [Reading ZIP Files](#reading-zip-files)\r\n    - [Extracting from ZIP Files](#extracting-from-zip-files)\r\n    - [Creating and Adding to ZIP Files](#creating-and-adding-to-zip-files)\r\n- [JSON, YAML and configuration files](#json-yaml-and-configuration-files)\r\n    - [JSON](#json)\r\n    - [YAML](#yaml)\r\n    - [Anyconfig](#anyconfig)\r\n- [Debugging](#debugging)\r\n    - [Raising Exceptions](#raising-exceptions)\r\n    - [Getting the Traceback as a String](#getting-the-traceback-as-a-string)\r\n    - [Assertions](#assertions)\r\n    - [Logging](#logging)\r\n    - [Logging Levels](#logging-levels)\r\n    - [Disabling Logging](#disabling-logging)\r\n    - [Logging to a File](#logging-to-a-file)\r\n- [Lambda Functions](#lambda-functions)\r\n- [Ternary Conditional Operator](#ternary-conditional-operator)\r\n- [args and kwargs](#args-and-kwargs)\r\n    - [Thinks to Remember(args)](#thinks-to-rememberargs)\r\n    - [Thinks to remember(kwargs)](#thinks-to-rememberkwargs)\r\n- [Context Manager](#context-manager)\r\n    - [with statement](#with-statement)\r\n    - [Writing your own contextmanager using generator syntax](#writing-your-own-contextmanager-using-generator-syntax)\r\n- [`__main__` Top-level script environment](#main-top-level-script-environment)\r\n    - [Advantages](#advantages)\r\n- [setup.py](#setuppy)\r\n- [Dataclasses](#dataclasses)\r\n    - [Features](#features)\r\n    - [Default values](#default-values)\r\n    - [Type hints](#type-hints)\r\n- [Virtual Environment](#virtual-environment)\r\n    - [virtualenv](#virtualenv)\r\n    - [pipenv](#pipenv)\r\n    - [anaconda](#anaconda)\r\n\r\n## The Zen of Python\r\n\r\nFrom the [PEP 20 -- The Zen of Python](https://www.python.org/dev/peps/pep-0020/):\r\n\r\n> Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.\r\n\r\n```python\r\n>>> import this\r\nThe Zen of Python, by Tim Peters\r\n\r\nBeautiful is better than ugly.\r\nExplicit is better than implicit.\r\nSimple is better than complex.\r\nComplex is better than complicated.\r\nFlat is better than nested.\r\nSparse is better than dense.\r\nReadability counts.\r\nSpecial cases aren't special enough to break the rules.\r\nAlthough practicality beats purity.\r\nErrors should never pass silently.\r\nUnless explicitly silenced.\r\nIn the face of ambiguity, refuse the temptation to guess.\r\nThere should be one-- and preferably only one --obvious way to do it.\r\nAlthough that way may not be obvious at first unless you're Dutch.\r\nNow is better than never.\r\nAlthough never is often better than *right* now.\r\nIf the implementation is hard to explain, it's a bad idea.\r\nIf the implementation is easy to explain, it may be a good idea.\r\nNamespaces are one honking great idea -- let's do more of those!\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Python Basics\r\n\r\n### Math Operators\r\n\r\nFrom **Highest** to **Lowest** precedence:\r\n\r\n| Operators | Operation        | Example         |\r\n| --------- | ---------------- | --------------- |\r\n| **        | Exponent         | `2 ** 3 = 8`    |\r\n| %         | Modulus/Remaider | `22 % 8 = 6`    |\r\n| //        | Integer division | `22 // 8 = 2`   |\r\n| /         | Division         | `22 / 8 = 2.75` |\r\n| *         | Multiplication   | `3 * 3 = 9`     |\r\n| -         | Subtraction      | `5 - 2 = 3`     |\r\n| +         | Addition         | `2 + 2 = 4`     |\r\n\r\nExamples of expressions in the interactive shell:\r\n\r\n```python\r\n>>> 2 + 3 * 6\r\n20\r\n```\r\n\r\n```python\r\n>>> (2 + 3) * 6\r\n30\r\n```\r\n\r\n```python\r\n>>> 2 ** 8\r\n256\r\n```\r\n\r\n```python\r\n>>> 23 // 7\r\n3\r\n```\r\n\r\n```python\r\n>>> 23 % 7\r\n2\r\n```\r\n\r\n```python\r\n>>> (5 - 1) * ((7 + 1) / (3 - 1))\r\n16.0\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Data Types\r\n\r\n| Data Type              | Examples                                  |\r\n| ---------------------- | ----------------------------------------- |\r\n| Integers               | `-2, -1, 0, 1, 2, 3, 4, 5`                |\r\n| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` |\r\n| Strings                | `'a', 'aa', 'aaa', 'Hello!', '11 cats'`   |\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### String Concatenation and Replication\r\n\r\nString concatenation:\r\n\r\n```python\r\n>>> 'Alice' 'Bob'\r\n'AliceBob'\r\n```\r\n\r\nNote: Avoid `+` operator for string concatenation. Prefer string formatting.\r\n\r\nString Replication:\r\n\r\n```python\r\n>>> 'Alice' * 5\r\n'AliceAliceAliceAliceAlice'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Variables\r\n\r\nYou can name a variable anything as long as it obeys the following three rules:\r\n\r\n1. It can be only one word.\r\n1. It can use only letters, numbers, and the underscore (`_`) character.\r\n1. It can’t begin with a number.\r\n1. Variable name starting with an underscore (`_`) are considered as \"unuseful`.\r\n\r\nExample:\r\n\r\n```python\r\n>>> spam = 'Hello'\r\n>>> spam\r\n'Hello'\r\n```\r\n\r\n```python\r\n>>> _spam = 'Hello'\r\n```\r\n\r\n`_spam` should not be used again in the code.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Comments\r\n\r\nInline comment:\r\n\r\n```python\r\n# This is a comment\r\n```\r\n\r\nMultiline comment:\r\n\r\n```Python\r\n# This is a\r\n# multiline comment\r\n```\r\n\r\nCode with a comment:\r\n\r\n```python\r\na = 1  # initialization\r\n```\r\n\r\nPlease note the two spaces in front of the comment.\r\n\r\nFunction docstring:\r\n\r\n```python\r\ndef foo():\r\n    \"\"\"\r\n    This is a function docstring\r\n    You can also use:\r\n    ''' Function Docstring '''\r\n    \"\"\"\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The print() Function\r\n\r\n```python\r\n>>> print('Hello world!')\r\nHello world!\r\n```\r\n\r\n```python\r\n>>> a = 1\r\n>>> print('Hello world!', a)\r\nHello world! 1\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The input() Function\r\n\r\nExample Code:\r\n\r\n```python\r\n>>> print('What is your name?')   # ask for their name\r\n>>> myName = input()\r\n>>> print('It is good to meet you, {}'.format(myName))\r\nWhat is your name?\r\nAl\r\nIt is good to meet you, Al\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The len() Function\r\n\r\nEvaluates to the integer value of the number of characters in a string:\r\n\r\n```python\r\n>>> len('hello')\r\n5\r\n```\r\n\r\nNote: test of emptiness of strings, lists, dictionary, etc, should **not** use len, but prefer direct\r\nboolean evaluation.\r\n\r\n```python\r\n>>> a = [1, 2, 3]\r\n>>> if a:\r\n>>>     print(\"the list is not empty!\")\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The str(), int(), and float() Functions\r\n\r\nInteger to String or Float:\r\n\r\n```python\r\n>>> str(29)\r\n'29'\r\n```\r\n\r\n```python\r\n>>> print('I am {} years old.'.format(str(29)))\r\nI am 29 years old.\r\n```\r\n\r\n```python\r\n>>> str(-3.14)\r\n'-3.14'\r\n```\r\n\r\nFloat to Integer:\r\n\r\n```python\r\n>>> int(7.7)\r\n7\r\n```\r\n\r\n```python\r\n>>> int(7.7) + 1\r\n8\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Flow Control\r\n\r\n### Comparison Operators\r\n\r\n| Operator | Meaning                  |\r\n| -------- | ------------------------ |\r\n| `==`     | Equal to                 |\r\n| `!=`     | Not equal to             |\r\n| `<`      | Less than                |\r\n| `>`      | Greater Than             |\r\n| `<=`     | Less than or Equal to    |\r\n| `>=`     | Greater than or Equal to |\r\n\r\nThese operators evaluate to True or False depending on the values you give them.\r\n\r\nExamples:\r\n\r\n```python\r\n>>> 42 == 42\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 40 == 42\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'hello' == 'hello'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'hello' == 'Hello'\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'dog' != 'cat'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 42 == 42.0\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 42 == '42'\r\nFalse\r\n```\r\n\r\n### Boolean evaluation\r\n\r\nNever use `==` or `!=` operator to evaluate boolean operation. Use the `is` or `is not` operators,\r\nor use implicit boolean evaluation.\r\n\r\nNO (even if they are valid Python):\r\n\r\n```python\r\n>>> True == True\r\nTrue\r\n```\r\n\r\n```python\r\n>>> True != False\r\nTrue\r\n```\r\n\r\nYES (even if they are valid Python):\r\n\r\n```python\r\n>>> True is True\r\nTrue\r\n```\r\n\r\n```python\r\n>>> True is not False\r\nTrue\r\n```\r\n\r\nThese statements are equivalent:\r\n\r\n```Python\r\n>>> if a is True:\r\n>>>    pass\r\n>>> if a is not False:\r\n>>>    pass\r\n>>> if a:\r\n>>>    pass\r\n```\r\n\r\nAnd these as well:\r\n\r\n```Python\r\n>>> if a is False:\r\n>>>    pass\r\n>>> if a is not True:\r\n>>>    pass\r\n>>> if not a:\r\n>>>    pass\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Boolean Operators\r\n\r\nThere are three Boolean operators: and, or, and not.\r\n\r\nThe *and* Operator’s *Truth* Table:\r\n\r\n| Expression        | Evaluates to |\r\n| ----------------- | ------------ |\r\n| `True and True`   | `True`       |\r\n| `True and False`  | `False`      |\r\n| `False and True`  | `False`      |\r\n| `False and False` | `False`      |\r\n\r\nThe *or* Operator’s *Truth* Table:\r\n\r\n| Expression       | Evaluates to |\r\n| ---------------- | ------------ |\r\n| `True or True`   | `True`       |\r\n| `True or False`  | `True`       |\r\n| `False or True`  | `True`       |\r\n| `False or False` | `False`      |\r\n\r\nThe *not* Operator’s *Truth* Table:\r\n\r\n| Expression  | Evaluates to |\r\n| ----------- | ------------ |\r\n| `not True`  | `False`      |\r\n| `not False` | `True`       |\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Mixing Boolean and Comparison Operators\r\n\r\n```python\r\n>>> (4 < 5) and (5 < 6)\r\nTrue\r\n```\r\n\r\n```python\r\n>>> (4 < 5) and (9 < 6)\r\nFalse\r\n```\r\n\r\n```python\r\n>>> (1 == 2) or (2 == 2)\r\nTrue\r\n```\r\n\r\nYou can also use multiple Boolean operators in an expression, along with the comparison operators:\r\n\r\n```python\r\n>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### if Statements\r\n\r\n```python\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### else Statements\r\n\r\n```python\r\nname = 'Bob'\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\nelse:\r\n    print('Hello, stranger.')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### elif Statements\r\n\r\n```python\r\nname = 'Bob'\r\nage = 5\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\nelif age < 12:\r\n    print('You are not Alice, kiddo.')\r\n```\r\n\r\n```python\r\nname = 'Bob'\r\nage = 30\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\nelif age < 12:\r\n    print('You are not Alice, kiddo.')\r\nelse:\r\n    print('You are neither Alice nor a little kid.')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### while Loop Statements\r\n\r\n```python\r\nspam = 0\r\nwhile spam < 5:\r\n    print('Hello, world.')\r\n    spam = spam + 1\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### break Statements\r\n\r\n If the execution reaches a break statement, it immediately exits the while loop’s clause:\r\n\r\n```python\r\nwhile True:\r\n    print('Please type your name.')\r\n    name = input()\r\n    if name == 'your name':\r\n        break\r\nprint('Thank you!')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### continue Statements\r\n\r\nWhen the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.\r\n\r\n```python\r\nwhile True:\r\n    print('Who are you?')\r\n    name = input()\r\n    if name != 'Joe':\r\n        continue\r\n    print('Hello, Joe. What is the password? (It is a fish.)')\r\n    password = input()\r\n    if password == 'swordfish':\r\n        break\r\nprint('Access granted.')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### for Loops and the range() Function\r\n\r\n```python\r\n>>> print('My name is')\r\n>>> for i in range(5):\r\n>>>     print('Jimmy Five Times ({})'.format(str(i)))\r\nMy name is\r\nJimmy Five Times (0)\r\nJimmy Five Times (1)\r\nJimmy Five Times (2)\r\nJimmy Five Times (3)\r\nJimmy Five Times (4)\r\n```\r\n\r\nThe *range()* function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.\r\n\r\n```python\r\n>>> for i in range(0, 10, 2):\r\n>>>    print(i)\r\n0\r\n2\r\n4\r\n6\r\n8\r\n```\r\n\r\nYou can even use a negative number for the step argument to make the for loop count down instead of up.\r\n\r\n```python\r\n>>> for i in range(5, -1, -1):\r\n>>>     print(i)\r\n5\r\n4\r\n3\r\n2\r\n1\r\n0\r\n```\r\n\r\n### For else statement\r\n\r\nThis allows to specify a statement to execute in case of the full loop has been executed. Only\r\nuseful when a `break` condition can occur in the loop:\r\n\r\n```python\r\n>>> for i in [1, 2, 3, 4, 5]:\r\n>>>    if i == 3:\r\n>>>        break\r\n>>> else:\r\n>>>    print(\"only executed when no item of the list is equal to 3\")\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Importing Modules\r\n\r\n```python\r\nimport random\r\nfor i in range(5):\r\n    print(random.randint(1, 10))\r\n```\r\n\r\n```python\r\nimport random, sys, os, math\r\n```\r\n\r\n```python\r\nfrom random import *.\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Ending a Program Early with sys.exit()\r\n\r\n```python\r\nimport sys\r\n\r\nwhile True:\r\n    print('Type exit to exit.')\r\n    response = input()\r\n    if response == 'exit':\r\n        sys.exit()\r\n    print('You typed {}.'.format(response))\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Functions\r\n\r\n```python\r\n>>> def hello(name):\r\n>>>     print('Hello {}'.format(name))\r\n>>>\r\n>>> hello('Alice')\r\n>>> hello('Bob')\r\nHello Alice\r\nHello Bob\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Return Values and return Statements\r\n\r\nWhen creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:\r\n\r\n- The return keyword.\r\n\r\n- The value or expression that the function should return.\r\n\r\n```python\r\nimport random\r\ndef getAnswer(answerNumber):\r\n    if answerNumber == 1:\r\n        return 'It is certain'\r\n    elif answerNumber == 2:\r\n        return 'It is decidedly so'\r\n    elif answerNumber == 3:\r\n        return 'Yes'\r\n    elif answerNumber == 4:\r\n        return 'Reply hazy try again'\r\n    elif answerNumber == 5:\r\n        return 'Ask again later'\r\n    elif answerNumber == 6:\r\n        return 'Concentrate and ask again'\r\n    elif answerNumber == 7:\r\n        return 'My reply is no'\r\n    elif answerNumber == 8:\r\n        return 'Outlook not so good'\r\n    elif answerNumber == 9:\r\n        return 'Very doubtful'\r\n\r\nr = random.randint(1, 9)\r\nfortune = getAnswer(r)\r\nprint(fortune)\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The None Value\r\n\r\n```python\r\n>>> spam = print('Hello!')\r\nHello!\r\n```\r\n\r\n```python\r\n>>> spam is None\r\nTrue\r\n```\r\n\r\nNote: never compare to `None` with the `==` operator. Always use `is`.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Keyword Arguments and print()\r\n\r\n```python\r\n>>> print('Hello', end='')\r\n>>> print('World')\r\nHelloWorld\r\n```\r\n\r\n```python\r\n>>> print('cats', 'dogs', 'mice')\r\ncats dogs mice\r\n```\r\n\r\n```python\r\n>>> print('cats', 'dogs', 'mice', sep=',')\r\ncats,dogs,mice\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Local and Global Scope\r\n\r\n- Code in the global scope cannot use any local variables.\r\n\r\n- However, a local scope can access global variables.\r\n\r\n- Code in a function’s local scope cannot use variables in any other local scope.\r\n\r\n- You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The global Statement\r\n\r\nIf you need to modify a global variable from within a function, use the global statement:\r\n\r\n```python\r\n>>> def spam():\r\n>>>     global eggs\r\n>>>     eggs = 'spam'\r\n>>>\r\n>>> eggs = 'global'\r\n>>> spam()\r\n>>> print(eggs)\r\nspam\r\n```\r\n\r\nThere are four rules to tell whether a variable is in a local scope or global scope:\r\n\r\n1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.\r\n\r\n1. If there is a global statement for that variable in a function, it is a global variable.\r\n\r\n1. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.\r\n\r\n1. But if the variable is not used in an assignment statement, it is a global variable.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Exception Handling\r\n\r\n### Basic exception handling\r\n\r\n```python\r\n>>> def spam(divideBy):\r\n>>>     try:\r\n>>>         return 42 / divideBy\r\n>>>     except ZeroDivisionError as e:\r\n>>>         print('Error: Invalid argument: {}'.format(e))\r\n>>>\r\n>>> print(spam(2))\r\n>>> print(spam(12))\r\n>>> print(spam(0))\r\n>>> print(spam(1))\r\n21.0\r\n3.5\r\nError: Invalid argument: division by zero\r\nNone\r\n42.0\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Final code in exception handling\r\n\r\nCode inside the `finally` section is always executed, no matter if an exception has been raised or\r\nnot, and even if an exception is not caught.\r\n\r\n```python\r\n>>> def spam(divideBy):\r\n>>>     try:\r\n>>>         return 42 / divideBy\r\n>>>     except ZeroDivisionError as e:\r\n>>>         print('Error: Invalid argument: {}'.format(e))\r\n>>>     finally:\r\n>>>         print(\"-- division finished --\")\r\n>>> print(spam(12))\r\n>>> print(spam(0))\r\n21.0\r\n-- division finished --\r\n3.5\r\n-- division finished --\r\nError: Invalid argument: division by zero\r\n-- division finished --\r\nNone\r\n-- division finished --\r\n42.0\r\n-- division finished --\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Lists\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n\r\n>>> spam\r\n['cat', 'bat', 'rat', 'elephant']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Getting Individual Values in a List with Indexes\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[0]\r\n'cat'\r\n```\r\n\r\n```python\r\n>>> spam[1]\r\n'bat'\r\n```\r\n\r\n```python\r\n>>> spam[2]\r\n'rat'\r\n```\r\n\r\n```python\r\n>>> spam[3]\r\n'elephant'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Negative Indexes\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[-1]\r\n'elephant'\r\n```\r\n\r\n```python\r\n>>> spam[-3]\r\n'bat'\r\n```\r\n\r\n```python\r\n>>> 'The {} is afraid of the {}.'.format(spam[-1], spam[-3])\r\n'The elephant is afraid of the bat.'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Getting Sublists with Slices\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[0:4]\r\n['cat', 'bat', 'rat', 'elephant']\r\n```\r\n\r\n```python\r\n>>> spam[1:3]\r\n['bat', 'rat']\r\n```\r\n\r\n```python\r\n>>> spam[0:-1]\r\n['cat', 'bat', 'rat']\r\n```\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[:2]\r\n['cat', 'bat']\r\n```\r\n\r\n```python\r\n>>> spam[1:]\r\n['bat', 'rat', 'elephant']\r\n```\r\n\r\nSlicing the complete list will perform a copy:\r\n\r\n```python\r\n>>> spam2 = spam[:]\r\n['cat', 'bat', 'rat', 'elephant']\r\n>>> spam.append('dog')\r\n>>> spam\r\n['cat', 'bat', 'rat', 'elephant', 'dog']\r\n>>> spam2\r\n['cat', 'bat', 'rat', 'elephant']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Getting a List’s Length with len()\r\n\r\n```python\r\n>>> spam = ['cat', 'dog', 'moose']\r\n>>> len(spam)\r\n3\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Changing Values in a List with Indexes\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[1] = 'aardvark'\r\n\r\n>>> spam\r\n['cat', 'aardvark', 'rat', 'elephant']\r\n\r\n>>> spam[2] = spam[1]\r\n\r\n>>> spam\r\n['cat', 'aardvark', 'aardvark', 'elephant']\r\n\r\n>>> spam[-1] = 12345\r\n\r\n>>> spam\r\n['cat', 'aardvark', 'aardvark', 12345]\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### List Concatenation and List Replication\r\n\r\n```python\r\n>>> [1, 2, 3] + ['A', 'B', 'C']\r\n[1, 2, 3, 'A', 'B', 'C']\r\n\r\n>>> ['X', 'Y', 'Z'] * 3\r\n['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']\r\n\r\n>>> spam = [1, 2, 3]\r\n\r\n>>> spam = spam + ['A', 'B', 'C']\r\n\r\n>>> spam\r\n[1, 2, 3, 'A', 'B', 'C']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Removing Values from Lists with del Statements\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> del spam[2]\r\n>>> spam\r\n['cat', 'bat', 'elephant']\r\n```\r\n\r\n```python\r\n>>> del spam[2]\r\n>>> spam\r\n['cat', 'bat']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Using for Loops with Lists\r\n\r\n```python\r\n>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']\r\n>>> for i, supply in enumerate(supplies):\r\n>>>     print('Index {} in supplies is: {}'.format(str(i), supply))\r\nIndex 0 in supplies is: pens\r\nIndex 1 in supplies is: staplers\r\nIndex 2 in supplies is: flame-throwers\r\nIndex 3 in supplies is: binders\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Looping Through Multiple Lists with zip()\r\n\r\n```python\r\n>>> name = ['Pete', 'John', 'Elizabeth']\r\n>>> age = [6, 23, 44]\r\n>>> for n, a in zip(name, age):\r\n>>>     print('{} is {} years old'.format(n, a))\r\nPete is 6 years old\r\nJohn is 23 years old\r\nElizabeth is 44 years old\r\n```\r\n\r\n### The in and not in Operators\r\n\r\n```python\r\n>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']\r\nTrue\r\n```\r\n\r\n```python\r\n>>> spam = ['hello', 'hi', 'howdy', 'heyas']\r\n>>> 'cat' in spam\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'howdy' not in spam\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'cat' not in spam\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The Multiple Assignment Trick\r\n\r\nThe multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:\r\n\r\n```python\r\n>>> cat = ['fat', 'orange', 'loud']\r\n\r\n>>> size = cat[0]\r\n\r\n>>> color = cat[1]\r\n\r\n>>> disposition = cat[2]\r\n```\r\n\r\nYou could type this line of code:\r\n\r\n```python\r\n>>> cat = ['fat', 'orange', 'loud']\r\n\r\n>>> size, color, disposition = cat\r\n```\r\n\r\nThe multiple assignment trick can also be used to swap the values in two variables:\r\n\r\n```python\r\n>>> a, b = 'Alice', 'Bob'\r\n>>> a, b = b, a\r\n>>> print(a)\r\n'Bob'\r\n```\r\n\r\n```python\r\n>>> print(b)\r\n'Alice'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Augmented Assignment Operators\r\n\r\n| Operator    | Equivalent        |\r\n| ----------- | ----------------- |\r\n| `spam += 1` | `spam = spam + 1` |\r\n| `spam -= 1` | `spam = spam - 1` |\r\n| `spam *= 1` | `spam = spam * 1` |\r\n| `spam /= 1` | `spam = spam / 1` |\r\n| `spam %= 1` | `spam = spam % 1` |\r\n\r\nExamples:\r\n\r\n```python\r\n>>> spam = 'Hello'\r\n>>> spam += ' world!'\r\n>>> spam\r\n'Hello world!'\r\n\r\n>>> bacon = ['Zophie']\r\n>>> bacon *= 3\r\n>>> bacon\r\n['Zophie', 'Zophie', 'Zophie']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Finding a Value in a List with the index() Method\r\n\r\n```python\r\n>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']\r\n\r\n>>> spam.index('Pooka')\r\n1\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Adding Values to Lists with the append() and insert() Methods\r\n\r\n**append()**:\r\n\r\n```python\r\n>>> spam = ['cat', 'dog', 'bat']\r\n\r\n>>> spam.append('moose')\r\n\r\n>>> spam\r\n['cat', 'dog', 'bat', 'moose']\r\n```\r\n\r\n**insert()**:\r\n\r\n```python\r\n>>> spam = ['cat', 'dog', 'bat']\r\n\r\n>>> spam.insert(1, 'chicken')\r\n\r\n>>> spam\r\n['cat', 'chicken', 'dog', 'bat']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Removing Values from Lists with remove()\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n\r\n>>> spam.remove('bat')\r\n\r\n>>> spam\r\n['cat', 'rat', 'elephant']\r\n```\r\n\r\nIf the value appears multiple times in the list, only the first instance of the value will be removed.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Sorting the Values in a List with the sort() Method\r\n\r\n```python\r\n>>> spam = [2, 5, 3.14, 1, -7]\r\n>>> spam.sort()\r\n>>> spam\r\n[-7, 1, 2, 3.14, 5]\r\n```\r\n\r\n```python\r\n>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']\r\n>>> spam.sort()\r\n>>> spam\r\n['ants', 'badgers', 'cats', 'dogs', 'elephants']\r\n```\r\n\r\nYou can also pass True for the reverse keyword argument to have sort() sort the values in reverse order:\r\n\r\n```python\r\n>>> spam.sort(reverse=True)\r\n>>> spam\r\n['elephants', 'dogs', 'cats', 'badgers', 'ants']\r\n```\r\n\r\nIf you need to sort the values in regular alphabetical order, pass str. lower for the key keyword argument in the sort() method call:\r\n\r\n```python\r\n>>> spam = ['a', 'z', 'A', 'Z']\r\n>>> spam.sort(key=str.lower)\r\n>>> spam\r\n['a', 'A', 'z', 'Z']\r\n```\r\n\r\nYou can use the built-in function `sorted` to return a new list:\r\n\r\n```python\r\n>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']\r\n>>> sorted(spam)\r\n['ants', 'badgers', 'cats', 'dogs', 'elephants']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Tuple Data Type\r\n\r\n```python\r\n>>> eggs = ('hello', 42, 0.5)\r\n>>> eggs[0]\r\n'hello'\r\n```\r\n\r\n```python\r\n>>> eggs[1:3]\r\n(42, 0.5)\r\n```\r\n\r\n```python\r\n>>> len(eggs)\r\n3\r\n```\r\n\r\nThe main way that tuples are different from lists is that tuples, like strings, are immutable.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Converting Types with the list() and tuple() Functions\r\n\r\n```python\r\n>>> tuple(['cat', 'dog', 5])\r\n('cat', 'dog', 5)\r\n```\r\n\r\n```python\r\n>>> list(('cat', 'dog', 5))\r\n['cat', 'dog', 5]\r\n```\r\n\r\n```python\r\n>>> list('hello')\r\n['h', 'e', 'l', 'l', 'o']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Dictionaries and Structuring Data\r\n\r\nExample Dictionary:\r\n\r\n```python\r\nmyCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The keys(), values(), and items() Methods\r\n\r\nvalues():\r\n\r\n```python\r\n>>> spam = {'color': 'red', 'age': 42}\r\n>>> for v in spam.values():\r\n>>>     print(v)\r\nred\r\n42\r\n```\r\n\r\nkeys():\r\n\r\n```python\r\n>>> for k in spam.keys():\r\n>>>     print(k)\r\ncolor\r\nage\r\n```\r\n\r\nitems():\r\n\r\n```python\r\n>>> for i in spam.items():\r\n>>>     print(i)\r\n('color', 'red')\r\n('age', 42)\r\n```\r\n\r\nUsing the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively.\r\n\r\n```python\r\n\r\n>>> spam = {'color': 'red', 'age': 42}\r\n>>>\r\n>>> for k, v in spam.items():\r\n>>>     print('Key: {} Value: {}'.format(k, str(v)))\r\nKey: age Value: 42\r\nKey: color Value: red\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Checking Whether a Key or Value Exists in a Dictionary\r\n\r\n```python\r\n>>> spam = {'name': 'Zophie', 'age': 7}\r\n```\r\n\r\n```python\r\n>>> 'name' in spam.keys()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Zophie' in spam.values()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> # You can omit the call to keys() when checking for a key\r\n>>> 'color' in spam\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'color' not in spam\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'color' in spam\r\nFalse\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The get() Method\r\n\r\n```python\r\n>>> picnic_items = {'apples': 5, 'cups': 2}\r\n\r\n>>> 'I am bringing {} cups.'.format(str(picnic_items.get('cups', 0)))\r\n'I am bringing 2 cups.'\r\n```\r\n\r\n```python\r\n>>> 'I am bringing {} eggs.'.format(str(picnic_items.get('eggs', 0)))\r\n'I am bringing 0 eggs.'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The setdefault() Method\r\n\r\nLet's consider this code:\r\n\r\n```python\r\nspam = {'name': 'Pooka', 'age': 5}\r\n\r\nif 'color' not in spam:\r\n    spam['color'] = 'black'\r\n```\r\n\r\nUsing `setdefault` we could make the same code more shortly:\r\n\r\n```python\r\n>>> spam = {'name': 'Pooka', 'age': 5}\r\n>>> spam.setdefault('color', 'black')\r\n'black'\r\n```\r\n\r\n```python\r\n>>> spam\r\n{'color': 'black', 'age': 5, 'name': 'Pooka'}\r\n```\r\n\r\n```python\r\n>>> spam.setdefault('color', 'white')\r\n'black'\r\n```\r\n\r\n```python\r\n>>> spam\r\n{'color': 'black', 'age': 5, 'name': 'Pooka'}\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Pretty Printing\r\n\r\n```python\r\n>>> import pprint\r\n>>>\r\n>>> message = 'It was a bright cold day in April, and the clocks were striking\r\n>>> thirteen.'\r\n>>> count = {}\r\n>>>\r\n>>> for character in message:\r\n>>>     count.setdefault(character, 0)\r\n>>>     count[character] = count[character] + 1\r\n>>>\r\n>>> pprint.pprint(count)\r\n{' ': 13,\r\n ',': 1,\r\n '.': 1,\r\n 'A': 1,\r\n 'I': 1,\r\n 'a': 4,\r\n 'b': 1,\r\n 'c': 3,\r\n 'd': 3,\r\n 'e': 5,\r\n 'g': 2,\r\n 'h': 3,\r\n 'i': 6,\r\n 'k': 2,\r\n 'l': 3,\r\n 'n': 4,\r\n 'o': 2,\r\n 'p': 1,\r\n 'r': 5,\r\n 's': 3,\r\n 't': 6,\r\n 'w': 2,\r\n 'y': 1}\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Merge two dictionaries\r\n\r\n```python\r\n# in Python 3.5+:\r\n>>> x = {'a': 1, 'b': 2}\r\n>>> y = {'b': 3, 'c': 4}\r\n>>> z = {**x, **y}\r\n>>> z\r\n{'c': 4, 'a': 1, 'b': 3}\r\n\r\n# in Python 2.7\r\n>>> z = dict(x, **y)\r\n>>> z\r\n{'c': 4, 'a': 1, 'b': 3}\r\n```\r\n\r\n## sets\r\n\r\nFrom the Python 3 [documentation](https://docs.python.org/3/tutorial/datastructures.html)\r\n\r\n> A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.\r\n\r\n### Initializing a set\r\n\r\nThere are two ways to create sets: using curly braces `{}` and the bult-in function `set()`\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s = set([1, 2, 3])\r\n```\r\n\r\nWhen creating an empty set, be sure to not use the curly braces `{}`  or you will get an empty dictionary instead.\r\n\r\n```python\r\n>>> s = {}\r\n>>> type(s)\r\n<class 'dict'>\r\n```\r\n\r\n### sets: unordered collections of unique elements\r\n\r\nA set automatically remove all the duplicate values.\r\n\r\n```python\r\n>>> s = {1, 2, 3, 2, 3, 4}\r\n>>> s\r\n{1, 2, 3, 4}\r\n```\r\n\r\nAnd as an unordered data type, they can't be indexed.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s[0]\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\nTypeError: 'set' object does not support indexing\r\n>>>\r\n```\r\n\r\n### set add() and update()\r\n\r\nUsing the `add()` method we can add a single element to the set.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.add(4)\r\n>>> s\r\n{1, 2, 3, 4}\r\n```\r\n\r\nAnd with `update()`, multiple ones .\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.update([2, 3, 4, 5, 6])\r\n>>> s\r\n{1, 2, 3, 4, 5, 6}  # remember, sets automatically remove duplicates\r\n```\r\n\r\n### set remove() and discard()\r\n\r\nBoth methods will remove an element from the set, but `remove()` will raise a `key error` if the value doesn't exist.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.remove(3)\r\n>>> s\r\n{1, 2}\r\n>>> s.remove(3)\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\nKeyError: 3\r\n```\r\n\r\n`discard()` won't raise any errors.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.discard(3)\r\n>>> s\r\n{1, 2}\r\n>>> s.discard(3)\r\n>>>\r\n```\r\n\r\n### set union()\r\n\r\n`union()` or `|` will create a new set that contains all the elements from the sets provided.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {3, 4, 5}\r\n>>> s1.union(s2)  # or 's1 | s2'\r\n{1, 2, 3, 4, 5}\r\n```\r\n\r\n### set  intersection\r\n\r\n`intersection`  or `&`  will return a set containing only the elements that are common to all of them.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {2, 3, 4}\r\n>>> s3 = {3, 4, 5}\r\n>>> s1.intersection(s2, s3)  # or 's1 & s2 & s3'\r\n{3}\r\n```\r\n\r\n### set  difference\r\n\r\n`difference` or `-` will return only the elements that are in one of the sets.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {2, 3, 4}\r\n>>> s1.difference(s2)  # or 's1 - s2'\r\n{1}\r\n```\r\n\r\n### set symetric_difference\r\n\r\n`symetric_difference` or `^` will return all the elements that are not common between them.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {2, 3, 4}\r\n>>> s1.symmetric_difference(s2)  # or 's1 ^ s2'\r\n{1, 4}\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## itertools Module\r\n\r\nThe *itertools* module is a colection of tools intented to be fast and use memory efficiently when handling iterators (like [lists](#lists) or [dictionaries](#dictionaries-and-structuring-data)).\r\n\r\nFrom the official [Python 3.x documentation](https://docs.python.org/3/library/itertools.html):\r\n\r\n> The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.\r\n\r\nThe *itertools* module comes in the standard library and must be imported.\r\n\r\nThe [operator](https://docs.python.org/3/library/operator.html) module will also be used. This module is not necessary when using itertools, but needed for some of the examples below.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### accumulate()\r\n\r\nMakes an iterator that returns the results of a function.\r\n\r\n```python\r\nitertools.accumulate(iterable[, func])\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5]\r\n>>> result = itertools.accumulate(data, operator.mul)\r\n>>> for each in result:\r\n>>>    print(each)\r\n1\r\n2\r\n6\r\n24\r\n120\r\n```\r\n\r\nThe operator.mul takes two numbers and multiplies them:\r\n\r\n```python\r\noperator.mul(1, 2)\r\n2\r\noperator.mul(2, 3)\r\n6\r\noperator.mul(6, 4)\r\n24\r\noperator.mul(24, 5)\r\n120\r\n```\r\n\r\nPassing a function is optional:\r\n\r\n```python\r\n>>> data = [5, 2, 6, 4, 5, 9, 1]\r\n>>> result = itertools.accumulate(data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n5\r\n7\r\n13\r\n17\r\n22\r\n31\r\n32\r\n```\r\n\r\nIf no function is designated the items will be summed:\r\n\r\n```python\r\n5\r\n5 + 2 = 7\r\n7 + 6 = 13\r\n13 + 4 = 17\r\n17 + 5 = 22\r\n22 + 9 = 31\r\n31 + 1 = 32\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### combinations()\r\n\r\nTakes an iterable and a integer. This will create all the unique combination that have r members.\r\n\r\n```python\r\nitertools.combinations(iterable, r)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> shapes = ['circle', 'triangle', 'square',]\r\n>>> result = itertools.combinations(shapes, 2)\r\n>>> for each in result:\r\n>>>    print(each)\r\n('circle', 'triangle')\r\n('circle', 'square')\r\n('triangle', 'square')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### combinations_with_replacement()\r\n\r\nJust like combinations(), but allows individual elements to be repeated more than once.\r\n\r\n```python\r\nitertools.combinations_with_replacement(iterable, r)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> shapes = ['circle', 'triangle', 'square']\r\n>>> result = itertools.combinations_with_replacement(shapes, 2)\r\n>>> for each in result:\r\n>>>    print(each)\r\n('circle', 'circle')\r\n('circle', 'triangle')\r\n('circle', 'square')\r\n('triangle', 'triangle')\r\n('triangle', 'square')\r\n('square', 'square')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### count()\r\n\r\nMakes an iterator that returns evenly spaced values starting with number start.\r\n\r\n```python\r\nitertools.count(start=0, step=1)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> for i in itertools.count(10,3):\r\n>>>    print(i)\r\n>>>    if i > 20:\r\n>>>        break\r\n10\r\n13\r\n16\r\n19\r\n22\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### cycle()\r\n\r\nThis function cycles through an iterator endlessly.\r\n\r\n```python\r\nitertools.cycle(iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']\r\n>>> for color in itertools.cycle(colors):\r\n>>>    print(color)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\nviolet\r\nred\r\norange\r\n```\r\n\r\nWhen reached the end of the iterable it start over again from the beginning.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### chain()\r\n\r\nTake a series of iterables and return them as one long iterable.\r\n\r\n```python\r\nitertools.chain(*iterables)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\r\n>>> shapes = ['circle', 'triangle', 'square', 'pentagon']\r\n>>> result = itertools.chain(colors, shapes)\r\n>>> for each in result:\r\n>>>    print(each)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\ncircle\r\ntriangle\r\nsquare\r\npentagon\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### compress()\r\n\r\nFilters one iterable with another.\r\n\r\n```python\r\nitertools.compress(data, selectors)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> shapes = ['circle', 'triangle', 'square', 'pentagon']\r\n>>> selections = [True, False, True, False]\r\n>>> result = itertools.compress(shapes, selections)\r\n>>> for each in result:\r\n>>>    print(each)\r\ncircle\r\nsquare\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### dropwhile()\r\n\r\nMake an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element.\r\n\r\n```python\r\nitertools.dropwhile(predicate, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\r\n>>> result = itertools.dropwhile(lambda x: x<5, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n1\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### filterfalse()\r\n\r\nMakes an iterator that filters elements from iterable returning only those for which the predicate is False.\r\n\r\n```python\r\nitertools.filterfalse(predicate, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\n>>> result = itertools.filterfalse(lambda x: x<5, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### groupby()\r\n\r\nSimply put, this function groups things together.\r\n\r\n```python\r\nitertools.groupby(iterable, key=None)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> robots = [{\r\n    'name': 'blaster',\r\n    'faction': 'autobot'\r\n}, {\r\n    'name': 'galvatron',\r\n    'faction': 'decepticon'\r\n}, {\r\n    'name': 'jazz',\r\n    'faction': 'autobot'\r\n}, {\r\n    'name': 'metroplex',\r\n    'faction': 'autobot'\r\n}, {\r\n    'name': 'megatron',\r\n    'faction': 'decepticon'\r\n}, {\r\n    'name': 'starcream',\r\n    'faction': 'decepticon'\r\n}]\r\n>>> for key, group in itertools.groupby(robots, key=lambda x: x['faction']):\r\n>>>    print(key)\r\n>>>    print(list(group))\r\nautobot\r\n[{'name': 'blaster', 'faction': 'autobot'}]\r\ndecepticon\r\n[{'name': 'galvatron', 'faction': 'decepticon'}]\r\nautobot\r\n[{'name': 'jazz', 'faction': 'autobot'}, {'name': 'metroplex', 'faction': 'autobot'}]\r\ndecepticon\r\n[{'name': 'megatron', 'faction': 'decepticon'}, {'name': 'starcream', 'faction': 'decepticon'}]\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### islice()\r\n\r\nThis function is very much like slices. This allows you to cut out a piece of an iterable.\r\n\r\n```python\r\nitertools.islice(iterable, start, stop[, step])\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue',]\r\n>>> few_colors = itertools.islice(colors, 2)\r\n>>> for each in few_colors:\r\n>>>    print(each)\r\nred\r\norange\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### permutations()\r\n\r\n```python\r\nitertools.permutations(iterable, r=None)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> alpha_data = ['a', 'b', 'c']\r\n>>> result = itertools.permutations(alpha_data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n('a', 'b', 'c')\r\n('a', 'c', 'b')\r\n('b', 'a', 'c')\r\n('b', 'c', 'a')\r\n('c', 'a', 'b')\r\n('c', 'b', 'a')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### product()\r\n\r\nCreates the cartesian products from a series of iterables.\r\n\r\n```python\r\n>>> num_data = [1, 2, 3]\r\n>>> alpha_data = ['a', 'b', 'c']\r\n>>> result = itertools.product(num_data, alpha_data)\r\n>>> for each in result:\r\n    print(each)\r\n(1, 'a')\r\n(1, 'b')\r\n(1, 'c')\r\n(2, 'a')\r\n(2, 'b')\r\n(2, 'c')\r\n(3, 'a')\r\n(3, 'b')\r\n(3, 'c')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### repeat()\r\n\r\nThis function will repeat an object over and over again. Unless, there is a times argument.\r\n\r\n```python\r\nitertools.repeat(object[, times])\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> for i in itertools.repeat(\"spam\", 3):\r\n    print(i)\r\nspam\r\nspam\r\nspam\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### starmap()\r\n\r\nMakes an iterator that computes the function using arguments obtained from the iterable.\r\n\r\n```python\r\nitertools.starmap(function, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [(2, 6), (8, 4), (7, 3)]\r\n>>> result = itertools.starmap(operator.mul, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n12\r\n32\r\n21\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### takewhile()\r\n\r\nThe opposite of dropwhile(). Makes an iterator and returns elements from the iterable as long as the predicate is true.\r\n\r\n```python\r\nitertools.takwwhile(predicate, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\r\n>>> result = itertools.takewhile(lambda x: x<5, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n1\r\n2\r\n3\r\n4\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### tee()\r\n\r\nReturn n independent iterators from a single iterable.\r\n\r\n```python\r\nitertools.tee(iterable, n=2)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\r\n>>> alpha_colors, beta_colors = itertools.tee(colors)\r\n>>> for each in alpha_colors:\r\n>>>    print(each)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\n```\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\r\n>>> alpha_colors, beta_colors = itertools.tee(colors)\r\n>>> for each in beta_colors:\r\n>>>    print(each)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### zip_longest()\r\n\r\nMakes an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.\r\n\r\n```python\r\nitertools.zip_longest(*iterables, fillvalue=None)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue',]\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,]\r\n>>> for each in itertools.zip_longest(colors, data, fillvalue=None):\r\n>>>    print(each)\r\n('red', 1)\r\n('orange', 2)\r\n('yellow', 3)\r\n('green', 4)\r\n('blue', 5)\r\n(None, 6)\r\n(None, 7)\r\n(None, 8)\r\n(None, 9)\r\n(None, 10)\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Comprehensions\r\n\r\n### List comprehension\r\n\r\n```python\r\n>>> a = [1, 3, 5, 7, 9, 11]\r\n\r\n>>> [i - 1 for i in a]\r\n[0, 2, 4, 6, 8, 10]\r\n```\r\n\r\n### Set comprehension\r\n\r\n```python\r\n>>> b = {\"abc\", \"def\"}\r\n>>> {s.upper() for s in b}\r\n{\"ABC\", \"DEF}\r\n```\r\n\r\n### Dict comprehension\r\n\r\n```python\r\n>>> c = {'name': 'Pooka', 'age': 5}\r\n>>> {v, k for k, v in c.items()}\r\n{'Pooka': 'name', 5: 'age'}\r\n```\r\n\r\nA List comprehension can be generated from a dictionary:\r\n\r\n```python\r\n>>> c = {'name': 'Pooka', 'first_name': 'Oooka'}\r\n>>> [\"{}:{}\".format(k.upper(), v.upper()) for k, v in c.items()]\r\n['NAME:POOKA', 'FIRST_NAME:OOOKA']\r\n```\r\n\r\n## Manipulating Strings\r\n\r\n### Escape Characters\r\n\r\n| Escape character | Prints as            |\r\n| ---------------- | -------------------- |\r\n| `\\'`             | Single quote         |\r\n| `\\\"`             | Double quote         |\r\n| `\\t`             | Tab                  |\r\n| `\\n`             | Newline (line break) |\r\n| `\\\\`             | Backslash            |\r\n\r\nExample:\r\n\r\n```python\r\n>>> print(\"Hello there!\\nHow are you?\\nI\\'m doing fine.\")\r\nHello there!\r\nHow are you?\r\nI'm doing fine.\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Raw Strings\r\n\r\nA raw string completely ignores all escape characters and prints any backslash that appears in the string.\r\n\r\n```python\r\n>>> print(r'That is Carol\\'s cat.')\r\nThat is Carol\\'s cat.\r\n```\r\n\r\nNote: mostly used for regular expression definition (see `re` package)\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Multiline Strings with Triple Quotes\r\n\r\n```python\r\n>>> print('''Dear Alice,\r\n>>>\r\n>>> Eve's cat has been arrested for catnapping, cat burglary, and extortion.\r\n>>>\r\n>>> Sincerely,\r\n>>> Bob''')\r\nDear Alice,\r\n\r\nEve's cat has been arrested for catnapping, cat burglary, and extortion.\r\n\r\nSincerely,\r\nBob\r\n```\r\n\r\nTo keep a nicer flow in your code, you can use the `dedent` function from the `textwrap` standard package.\r\n\r\n```python\r\n>>> from textwrap import dedent\r\n>>>\r\n>>> def my_function():\r\n>>>     print('''\r\n>>>         Dear Alice,\r\n>>>\r\n>>>         Eve's cat has been arrested for catnapping, cat burglary, and extortion.\r\n>>>\r\n>>>         Sincerely,\r\n>>>         Bob\r\n>>>         ''').strip()\r\n```\r\n\r\nThis generates the same string than before.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Indexing and Slicing Strings\r\n\r\n    H   e   l   l   o       w   o   r   l   d    !\r\n    0   1   2   3   4   5   6   7   8   9   10   11\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n\r\n>>> spam[0]\r\n'H'\r\n```\r\n\r\n```python\r\n>>> spam[4]\r\n'o'\r\n```\r\n\r\n```python\r\n>>> spam[-1]\r\n'!'\r\n```\r\n\r\nSlicing:\r\n\r\n```python\r\n\r\n>>> spam[0:5]\r\n'Hello'\r\n```\r\n\r\n```python\r\n>>> spam[:5]\r\n'Hello'\r\n```\r\n\r\n```python\r\n>>> spam[6:]\r\n'world!'\r\n```\r\n\r\n```python\r\n>>> spam[6:-1]\r\n'world'\r\n```\r\n\r\n```python\r\n>>> spam[:-1]\r\n'Hello world'\r\n```\r\n\r\n```python\r\n>>> spam[::-1]\r\n'!dlrow olleH'\r\n```\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n>>> fizz = spam[0:5]\r\n>>> fizz\r\n'Hello'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The in and not in Operators with Strings\r\n\r\n```python\r\n>>> 'Hello' in 'Hello World'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Hello' in 'Hello'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'HELLO' in 'Hello World'\r\nFalse\r\n```\r\n\r\n```python\r\n>>> '' in 'spam'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'cats' not in 'cats and dogs'\r\nFalse\r\n```\r\n\r\n### The in and not in Operators with list\r\n\r\n```python\r\n>>> a = [1, 2, 3, 4]\r\n>>> 5 in a\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 2 in a\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The upper(), lower(), isupper(), and islower() String Methods\r\n\r\n`upper()` and `lower()`:\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n>>> spam = spam.upper()\r\n>>> spam\r\n'HELLO WORLD!'\r\n```\r\n\r\n```python\r\n>>> spam = spam.lower()\r\n>>> spam\r\n'hello world!'\r\n```\r\n\r\nisupper() and islower():\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n>>> spam.islower()\r\nFalse\r\n```\r\n\r\n```python\r\n>>> spam.isupper()\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'HELLO'.isupper()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'abc12345'.islower()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> '12345'.islower()\r\nFalse\r\n```\r\n\r\n```python\r\n>>> '12345'.isupper()\r\nFalse\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The isX String Methods\r\n\r\n- **isalpha()** returns True if the string consists only of letters and is not blank.\r\n- **isalnum()** returns True if the string consists only of lettersand numbers and is not blank.\r\n- **isdecimal()** returns True if the string consists only ofnumeric characters and is not blank.\r\n- **isspace()** returns True if the string consists only of spaces,tabs, and new-lines and is not blank.\r\n- **istitle()** returns True if the string consists only of wordsthat begin with an uppercase letter followed by onlylowercase letters.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The startswith() and endswith() String Methods\r\n\r\n```python\r\n>>> 'Hello world!'.startswith('Hello')\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Hello world!'.endswith('world!')\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'abc123'.startswith('abcdef')\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'abc123'.endswith('12')\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'Hello world!'.startswith('Hello world!')\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Hello world!'.endswith('Hello world!')\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The join() and split() String Methods\r\n\r\njoin():\r\n\r\n```python\r\n>>> ', '.join(['cats', 'rats', 'bats'])\r\n'cats, rats, bats'\r\n```\r\n\r\n```python\r\n>>> ' '.join(['My', 'name', 'is', 'Simon'])\r\n'My name is Simon'\r\n```\r\n\r\n```python\r\n>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])\r\n'MyABCnameABCisABCSimon'\r\n```\r\n\r\nsplit():\r\n\r\n```python\r\n>>> 'My name is Simon'.split()\r\n['My', 'name', 'is', 'Simon']\r\n```\r\n\r\n```python\r\n>>> 'MyABCnameABCisABCSimon'.split('ABC')\r\n['My', 'name', 'is', 'Simon']\r\n```\r\n\r\n```python\r\n>>> 'My name is Simon'.split('m')\r\n['My na', 'e is Si', 'on']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Justifying Text with rjust(), ljust(), and center()\r\n\r\nrjust() and ljust():\r\n\r\n```python\r\n>>> 'Hello'.rjust(10)\r\n'     Hello'\r\n```\r\n\r\n```python\r\n>>> 'Hello'.rjust(20)\r\n'               Hello'\r\n```\r\n\r\n```python\r\n>>> 'Hello World'.rjust(20)\r\n'         Hello World'\r\n```\r\n\r\n```python\r\n>>> 'Hello'.ljust(10)\r\n'Hello     '\r\n```\r\n\r\nAn optional second argument to rjust() and ljust() will specify a fill character other than a space character. Enter the following into the interactive shell:\r\n\r\n```python\r\n>>> 'Hello'.rjust(20, '*')\r\n'***************Hello'\r\n```\r\n\r\n```python\r\n>>> 'Hello'.ljust(20, '-')\r\n'Hello---------------'\r\n```\r\n\r\ncenter():\r\n\r\n```python\r\n>>> 'Hello'.center(20)\r\n'       Hello       '\r\n```\r\n\r\n```python\r\n>>> 'Hello'.center(20, '=')\r\n'=======Hello========'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Removing Whitespace with strip(), rstrip(), and lstrip()\r\n\r\n```python\r\n>>> spam = '    Hello World     '\r\n>>> spam.strip()\r\n'Hello World'\r\n```\r\n\r\n```python\r\n>>> spam.lstrip()\r\n'Hello World '\r\n```\r\n\r\n```python\r\n>>> spam.rstrip()\r\n'    Hello World'\r\n```\r\n\r\n```python\r\n>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'\r\n>>> spam.strip('ampS')\r\n'BaconSpamEggs'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Copying and Pasting Strings with the pyperclip Module (need pip install)\r\n\r\n```python\r\n>>> import pyperclip\r\n\r\n>>> pyperclip.copy('Hello world!')\r\n\r\n>>> pyperclip.paste()\r\n'Hello world!'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## String Formatting\r\n\r\n### % operator\r\n\r\n```python\r\n>>> name = 'Pete'\r\n>>> 'Hello %s' % name\r\n\"Hello Pete\"\r\n```\r\n\r\nWe can use the `%x` format specifier to convert an int value to a string:\r\n\r\n```python\r\n>>> num = 5\r\n>>> 'I have %x apples' % num\r\n\"I have 5 apples\"\r\n```\r\n\r\nNote: For new code, using [str.format](#string-formatting-strformat) or [f-strings](#formatted-string-literals-or-f-strings-python-36) (Python 3.6+) is strongly recommended over the `%` operator.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### String Formatting (str.format)\r\n\r\nPython 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.\r\n\r\n```python\r\n>>> name = 'John'\r\n>>> age = 20'\r\n\r\n>>> \"Hello I'm {}, my age is {}\".format(name, age)\r\n\"Hello I'm John, my age is 20\"\r\n```\r\n\r\n```python\r\n>>> \"Hello I'm {0}, my age is {1}\".format(name, age)\r\n\"Hello I'm John, my age is 20\"\r\n```\r\n\r\nThe official [Python 3.x documentation](https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting) recommend `str.format` over the `%` operator:\r\n\r\n> The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Lazy string formatting\r\n\r\nYou would only use `%s` string formatting on functions that can do lazy parameters evaluation,\r\nthe most common being logging:\r\n\r\nPrefer:\r\n\r\n```python\r\n>>> name = \"alice\"\r\n>>> logging.debug(\"User name: %s\", name)\r\n```\r\n\r\nOver:\r\n\r\n```python\r\n>>> logging.debug(\"User name: {}\".format(name))\r\n```\r\n\r\nOr:\r\n\r\n```python\r\n>>> logging.debug(\"User name: \" + name)\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Formatted String Literals or f-strings (Python 3.6+)\r\n\r\n```python\r\n>>> name = 'Elizabeth'\r\n>>> f'Hello {name}!'\r\n'Hello Elizabeth!\r\n```\r\n\r\nIt is even possible to do inline arithmetic with it:\r\n\r\n```python\r\n>>> a = 5\r\n>>> b = 10\r\n>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'\r\n'Five plus ten is 15 and not 30.'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Template Strings\r\n\r\n A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.\r\n\r\n```python\r\n>>> from string import Template\r\n>>> name = 'Elizabeth'\r\n>>> t = Template('Hey $name!')\r\n>>> t.substitute(name=name)\r\n'Hey Elizabeth!'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Regular Expressions\r\n\r\n1. Import the regex module with `import re`.\r\n1. Create a Regex object with the `re.compile()` function. (Remember to use a raw string.)\r\n1. Pass the string you want to search into the Regex object’s `search()` method. This returns a `Match` object.\r\n1. Call the Match object’s `group()` method to return a string of the actual matched text.\r\n\r\nAll the regex functions in Python are in the re module:\r\n\r\n```python\r\n>>> import re\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching Regex Objects\r\n\r\n```python\r\n>>> phone_num_regex = re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\r\n\r\n>>> mo = phone_num_regex.search('My number is 415-555-4242.')\r\n\r\n>>> print('Phone number found: {}'.format(mo.group()))\r\nPhone number found: 415-555-4242\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Grouping with Parentheses\r\n\r\n```python\r\n>>> phone_num_regex = re.compile(r'(\\d\\d\\d)-(\\d\\d\\d-\\d\\d\\d\\d)')\r\n\r\n>>> mo = phone_num_regex.search('My number is 415-555-4242.')\r\n\r\n>>> mo.group(1)\r\n'415'\r\n\r\n>>> mo.group(2)\r\n'555-4242'\r\n\r\n>>> mo.group(0)\r\n'415-555-4242'\r\n\r\n>>> mo.group()\r\n'415-555-4242'\r\n```\r\n\r\nTo retrieve all the groups at once: use the groups() method—note the plural form for the name.\r\n\r\n```python\r\n>>> mo.groups()\r\n('415', '555-4242')\r\n\r\n>>> area_code, main_number = mo.groups()\r\n\r\n>>> print(area_code)\r\n415\r\n\r\n>>> print(main_number)\r\n555-4242\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching Multiple Groups with the Pipe\r\n\r\nThe | character is called a pipe. You can use it anywhere you want to match one of many expressions. For example, the regular expression r'Batman|Tina Fey' will match either 'Batman' or 'Tina Fey'.\r\n\r\n```python\r\n>>> hero_regex = re.compile (r'Batman|Tina Fey')\r\n\r\n>>> mo1 = hero_regex.search('Batman and Tina Fey.')\r\n\r\n>>> mo1.group()\r\n'Batman'\r\n\r\n>>> mo2 = hero_regex.search('Tina Fey and Batman.')\r\n\r\n>>> mo2.group()\r\n'Tina Fey'\r\n```\r\n\r\nYou can also use the pipe to match one of several patterns as part of your regex:\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(man|mobile|copter|bat)')\r\n\r\n>>> mo = bat_regex.search('Batmobile lost a wheel')\r\n\r\n>>> mo.group()\r\n'Batmobile'\r\n\r\n>>> mo.group(1)\r\n'mobile'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Optional Matching with the Question Mark\r\n\r\nThe ? character flags the group that precedes it as an optional part of the pattern.\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(wo)?man')\r\n>>> mo1 = bat_regex.search('The Adventures of Batman')\r\n>>> mo1.group()\r\n'Batman'\r\n\r\n>>> mo2 = bat_regex.search('The Adventures of Batwoman')\r\n>>> mo2.group()\r\n'Batwoman'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching Zero or More with the Star\r\n\r\nThe * (called the star or asterisk) means “match zero or more”—the group that precedes the star can occur any number of times in the text.\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(wo)*man')\r\n>>> mo1 = bat_regex.search('The Adventures of Batman')\r\n>>> mo1.group()\r\n'Batman'\r\n\r\n>>> mo2 = bat_regex.search('The Adventures of Batwoman')\r\n>>> mo2.group()\r\n'Batwoman'\r\n\r\n>>> mo3 = bat_regex.search('The Adventures of Batwowowowoman')\r\n>>> mo3.group()\r\n'Batwowowowoman'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching One or More with the Plus\r\n\r\nWhile * means “match zero or more,” the + (or plus) means “match one or more”. The group preceding a plus must appear at least once. It is not optional:\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(wo)+man')\r\n>>> mo1 = bat_regex.search('The Adventures of Batwoman')\r\n>>> mo1.group()\r\n'Batwoman'\r\n```\r\n\r\n```python\r\n>>> mo2 = bat_regex.search('The Adventures of Batwowowowoman')\r\n>>> mo2.group()\r\n'Batwowowowoman'\r\n```\r\n\r\n```python\r\n>>> mo3 = bat_regex.search('The Adventures of Batman')\r\n>>> mo3 is None\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching Specific Repetitions with Curly Brackets\r\n\r\nIf you have a group that you want to repeat a specific number of times, follow the group in your regex with a number in curly brackets. For example, the regex (Ha){3} will match the string 'HaHaHa', but it will not match 'HaHa', since the latter has only two repeats of the (Ha) group.\r\n\r\nInstead of one number, you can specify a range by writing a minimum, a comma, and a maximum in between the curly brackets. For example, the regex (Ha){3,5} will match 'HaHaHa', 'HaHaHaHa', and 'HaHaHaHaHa'.\r\n\r\n```python\r\n>>> ha_regex = re.compile(r'(Ha){3}')\r\n>>> mo1 = ha_regex.search('HaHaHa')\r\n>>> mo1.group()\r\n'HaHaHa'\r\n```\r\n\r\n```python\r\n>>> mo2 = ha_regex.search('Ha')\r\n>>> mo2 is None\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Greedy and Nongreedy Matching\r\n\r\nPython’s regular expressions are greedy by default, which means that in ambiguous situations they will match the longest string possible. The non-greedy version of the curly brackets, which matches the shortest string possible, has the closing curly bracket followed by a question mark.\r\n\r\n```python\r\n>>> greedy_ha_regex = re.compile(r'(Ha){3,5}')\r\n>>> mo1 = greedy_ha_regex.search('HaHaHaHaHa')\r\n>>> mo1.group()\r\n'HaHaHaHaHa'\r\n```\r\n\r\n```python\r\n>>> nongreedy_ha_regex = re.compile(r'(Ha){3,5}?')\r\n>>> mo2 = nongreedy_ha_regex.search('HaHaHaHaHa')\r\n>>> mo2.group()\r\n'HaHaHa'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The findall() Method\r\n\r\nIn addition to the search() method, Regex objects also have a findall() method. While search() will return a Match object of the first matched text in the searched string, the findall() method will return the strings of every match in the searched string.\r\n\r\n```python\r\n>>> phone_num_regex = re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d') # has no groups\r\n\r\n>>> phone_num_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')\r\n['415-555-9999', '212-555-0000']\r\n```\r\n\r\nTo summarize what the findall() method returns, remember the following:\r\n\r\n- When called on a regex with no groups, such as \\d-\\d\\d\\d-\\d\\d\\d\\d, the method findall() returns a list of ng matches, such as ['415-555-9999', '212-555-0000'].\r\n\r\n- When called on a regex that has groups, such as (\\d\\d\\d)-d\\d)-(\\d\\ d\\d\\d), the method findall() returns a list of es of strings (one string for each group), such as [('415', ', '9999'), ('212', '555', '0000')].\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Making Your Own Character Classes\r\n\r\nThere are times when you want to match a set of characters but the shorthand character classes (\\d, \\w, \\s, and so on) are too broad. You can define your own character class using square brackets. For example, the character class [aeiouAEIOU] will match any vowel, both lowercase and uppercase.\r\n\r\n```python\r\n>>> vowel_regex = re.compile(r'[aeiouAEIOU]')\r\n\r\n>>> vowel_regex.findall('Robocop eats baby food. BABY FOOD.')\r\n['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']\r\n```\r\n\r\nYou can also include ranges of letters or numbers by using a hyphen. For example, the character class [a-zA-Z0-9] will match all lowercase letters, uppercase letters, and numbers.\r\n\r\nBy placing a caret character (^) just after the character class’s opening bracket, you can make a negative character class. A negative character class will match all the characters that are not in the character class. For example, enter the following into the interactive shell:\r\n\r\n```python\r\n>>> consonant_regex = re.compile(r'[^aeiouAEIOU]')\r\n\r\n>>> consonant_regex.findall('Robocop eats baby food. BABY FOOD.')\r\n['R', 'b', 'c', 'p', ' ', 't', 's', ' ', 'b', 'b', 'y', ' ', 'f', 'd', '.', '\r\n', 'B', 'B', 'Y', ' ', 'F', 'D', '.']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The Caret and Dollar Sign Characters\r\n\r\n- You can also use the caret symbol (^) at the start of a regex to indicate that a match must occur at the beginning of the searched text.\r\n\r\n- Likewise, you can put a dollar sign ($) at the end of the regex to indicate the string must end with this regex pattern.\r\n\r\n- And you can use the ^ and $ together to indicate that the entire string must match the regex—that is, it’s not enough for a match to be made on some subset of the string.\r\n\r\nThe r'^Hello' regular expression string matches strings that begin with 'Hello':\r\n\r\n```python\r\n>>> begins_with_hello = re.compile(r'^Hello')\r\n\r\n>>> begins_with_hello.search('Hello world!')\r\n<_sre.SRE_Match object; span=(0, 5), match='Hello'>\r\n\r\n>>> begins_with_hello.search('He said hello.') is None\r\nTrue\r\n```\r\n\r\nThe r'\\d$' regular expression string matches strings that end with a numeric character from 0 to 9:\r\n\r\n```python\r\n>>> whole_string_is_num = re.compile(r'^\\d+$')\r\n\r\n>>> whole_string_is_num.search('1234567890')\r\n<_sre.SRE_Match object; span=(0, 10), match='1234567890'>\r\n\r\n>>> whole_string_is_num.search('12345xyz67890') is None\r\nTrue\r\n\r\n>>> whole_string_is_num.search('12 34567890') is None\r\nTrue\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The Wildcard Character\r\n\r\nThe . (or dot) character in a regular expression is called a wildcard and will match any character except for a newline:\r\n\r\n```python\r\n>>> at_regex = re.compile(r'.at')\r\n\r\n>>> at_regex.findall('The cat in the hat sat on the flat mat.')\r\n['cat', 'hat', 'sat', 'lat', 'mat']\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching Everything with Dot-Star\r\n\r\n```python\r\n>>> name_regex = re.compile(r'First Name: (.*) Last Name: (.*)')\r\n\r\n>>> mo = name_regex.search('First Name: Al Last Name: Sweigart')\r\n\r\n>>> mo.group(1)\r\n'Al'\r\n```\r\n\r\n```python\r\n>>> mo.group(2)\r\n'Sweigart'\r\n```\r\n\r\nThe dot-star uses greedy mode: It will always try to match as much text as possible. To match any and all text in a nongreedy fashion, use the dot, star, and question mark (.*?). The question mark tells Python to match in a nongreedy way:\r\n\r\n```python\r\n>>> nongreedy_regex = re.compile(r'<.*?>')\r\n>>> mo = nongreedy_regex.search('<To serve man> for dinner.>')\r\n>>> mo.group()\r\n'<To serve man>'\r\n```\r\n\r\n```python\r\n>>> greedy_regex = re.compile(r'<.*>')\r\n>>> mo = greedy_regex.search('<To serve man> for dinner.>')\r\n>>> mo.group()\r\n'<To serve man> for dinner.>'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Matching Newlines with the Dot Character\r\n\r\nThe dot-star will match everything except a newline. By passing re.DOTALL as the second argument to re.compile(), you can make the dot character match all characters, including the newline character:\r\n\r\n```python\r\n>>> no_newline_regex = re.compile('.*')\r\n>>> no_newline_regex.search('Serve the public trust.\\nProtect the innocent.\\nUphold the law.').group()\r\n'Serve the public trust.'\r\n```\r\n\r\n```python\r\n>>> newline_regex = re.compile('.*', re.DOTALL)\r\n>>> newline_regex.search('Serve the public trust.\\nProtect the innocent.\\nUphold the law.').group()\r\n'Serve the public trust.\\nProtect the innocent.\\nUphold the law.'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Review of Regex Symbols\r\n\r\n| Symbol                   | Matches                                                      |\r\n| ------------------------ | ------------------------------------------------------------ |\r\n| `?`                      | zero or one of the preceding group.                          |\r\n| `*`                      | zero or more of the preceding group.                         |\r\n| `+`                      | one or more of the preceding group.                          |\r\n| `{n}`                    | exactly n of the preceding group.                            |\r\n| `{n,}`                   | n or more of the preceding group.                            |\r\n| `{,m}`                   | 0 to m of the preceding group.                               |\r\n| `{n,m}`                  | at least n and at most m of the preceding p.                 |\r\n| `{n,m}?` or `*?` or `+?` | performs a nongreedy match of the preceding p.               |\r\n| `^spam`                  | means the string must begin with spam.                       |\r\n| `spam$`                  | means the string must end with spam.                         |\r\n| `.`                      | any character, except newline characters.                    |\r\n| `\\d`, `\\w`, and `\\s`     | a digit, word, or space character, ectively.                 |\r\n| `\\D`, `\\W`, and `\\S`     | anything except a digit, word, or space acter, respectively. |\r\n| `[abc]`                  | any character between the brackets (such as a, b, ).         |\r\n| `[^abc]`                 | any character that isn’t between the brackets.              |\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Case-Insensitive Matching\r\n\r\nTo make your regex case-insensitive, you can pass re.IGNORECASE or re.I as a second argument to re.compile():\r\n\r\n```python\r\n>>> robocop = re.compile(r'robocop', re.I)\r\n\r\n>>> robocop.search('Robocop is part man, part machine, all cop.').group()\r\n'Robocop'\r\n```\r\n\r\n```python\r\n>>> robocop.search('ROBOCOP protects the innocent.').group()\r\n'ROBOCOP'\r\n```\r\n\r\n```python\r\n>>> robocop.search('Al, why does your programming book talk about robocop so much?').group()\r\n'robocop'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Substituting Strings with the sub() Method\r\n\r\nThe sub() method for Regex objects is passed two arguments:\r\n\r\n1. The first argument is a string to replace any matches.\r\n1. The second is the string for the regular expression.\r\n\r\nThe sub() method returns a string with the substitutions applied:\r\n\r\n```python\r\n>>> names_regex = re.compile(r'Agent \\w+')\r\n\r\n>>> names_regex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')\r\n'CENSORED gave the secret documents to CENSORED.'\r\n```\r\n\r\nAnother example:\r\n\r\n```python\r\n>>> agent_names_regex = re.compile(r'Agent (\\w)\\w*')\r\n\r\n>>> agent_names_regex.sub(r'\\1****', 'Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')\r\nA**** told C**** that E**** knew B**** was a double agent.'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Managing Complex Regexes\r\n\r\nTo tell the re.compile() function to ignore whitespace and comments inside the regular expression string, “verbose mode” can be enabled by passing the variable re.VERBOSE as the second argument to re.compile().\r\n\r\nNow instead of a hard-to-read regular expression like this:\r\n\r\n```python\r\nphone_regex = re.compile(r'((\\d{3}|\\(\\d{3}\\))?(\\s|-|\\.)?\\d{3}(\\s|-|\\.)\\d{4}(\\s*(ext|x|ext.)\\s*\\d{2,5})?)')\r\n```\r\n\r\nyou can spread the regular expression over multiple lines with comments like this:\r\n\r\n```python\r\nphone_regex = re.compile(r'''(\r\n    (\\d{3}|\\(\\d{3}\\))?            # area code\r\n    (\\s|-|\\.)?                    # separator\r\n    \\d{3}                         # first 3 digits\r\n    (\\s|-|\\.)                     # separator\r\n    \\d{4}                         # last 4 digits\r\n    (\\s*(ext|x|ext.)\\s*\\d{2,5})?  # extension\r\n    )''', re.VERBOSE)\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Handling File and Directory Paths\r\n\r\nThere are two main modules in Python that deals with path manipulation.\r\nOne is the `os.path` module and the other is the `pathlib` module.\r\nThe `pathlib` module was added in Python 3.4, offering an object-oriented way\r\nto handle file system paths.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Backslash on Windows and Forward Slash on OS X and Linux\r\n\r\nOn Windows, paths are written using backslashes (\\) as the separator between\r\nfolder names. On Unix based operating system such as macOS, Linux, and BSDs,\r\nthe forward slash (/) is used as the path separator. Joining paths can be\r\na headache if your code needs to work on different platforms.\r\n\r\nFortunately, Python provides easy ways to handle this. We will showcase\r\nhow to deal with this with both `os.path.join` and `pathlib.Path.joinpath`\r\n\r\nUsing `os.path.join` on Windows:\r\n\r\n```python\r\n>>> import os\r\n\r\n>>> os.path.join('usr', 'bin', 'spam')\r\n'usr\\\\bin\\\\spam'\r\n```\r\n\r\nAnd using `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n\r\n>>> print(Path('usr').joinpath('bin').joinpath('spam'))\r\nusr/bin/spam\r\n```\r\n\r\n`pathlib` also provides a shortcut to joinpath using the `/` operator:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n\r\n>>> print(Path('usr') / 'bin' / 'spam')\r\nusr/bin/spam\r\n```\r\n\r\nNotice the path separator is different between Windows and Unix based operating\r\nsystem, that's why you want to use one of the above methods instead of\r\nadding strings together to join paths together.\r\n\r\nJoining paths is helpful if you need to create different file paths under\r\nthe same directory.\r\n\r\nUsing `os.path.join` on Windows:\r\n\r\n```python\r\n>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']\r\n\r\n>>> for filename in my_files:\r\n>>>     print(os.path.join('C:\\\\Users\\\\asweigart', filename))\r\nC:\\Users\\asweigart\\accounts.txt\r\nC:\\Users\\asweigart\\details.csv\r\nC:\\Users\\asweigart\\invite.docx\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']\r\n>>> home = Path.home()\r\n>>> for filename in my_files:\r\n>>>     print(home / filename)\r\n/home/asweigart/accounts.txt\r\n/home/asweigart/details.csv\r\n/home/asweigart/invite.docx\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### The Current Working Directory\r\n\r\nUsing `os` on Windows:\r\n\r\n```python\r\n>>> import os\r\n\r\n>>> os.getcwd()\r\n'C:\\\\Python34'\r\n>>> os.chdir('C:\\\\Windows\\\\System32')\r\n\r\n>>> os.getcwd()\r\n'C:\\\\Windows\\\\System32'\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> from os import chdir\r\n\r\n>>> print(Path.cwd())\r\n/home/asweigart\r\n\r\n>>> chdir('/usr/lib/python3.6')\r\n>>> print(Path.cwd())\r\n/usr/lib/python3.6\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Creating New Folders\r\n\r\nUsing `os` on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> os.makedirs('C:\\\\delicious\\\\walnut\\\\waffles')\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> cwd = Path.cwd()\r\n>>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir()\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\n  File \"/usr/lib/python3.6/pathlib.py\", line 1226, in mkdir\r\n    self._accessor.mkdir(self, mode)\r\n  File \"/usr/lib/python3.6/pathlib.py\", line 387, in wrapped\r\n    return strfunc(str(pathobj), *args)\r\nFileNotFoundError: [Errno 2] No such file or directory: '/home/asweigart/delicious/walnut/waffles'\r\n```\r\n\r\nOh no, we got a nasty error! The reason is that the 'delicious' directory does\r\nnot exist, so we cannot make the 'walnut' and the 'waffles' directories under\r\nit. To fix this, do:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> cwd = Path.cwd()\r\n>>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir(parents=True)\r\n```\r\n\r\nAnd all is good :)\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Absolute vs. Relative Paths\r\n\r\nThere are two ways to specify a file path.\r\n\r\n- An absolute path, which always begins with the root folder\r\n- A relative path, which is relative to the program’s current working directory\r\n\r\nThere are also the dot (.) and dot-dot (..) folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Handling Absolute and Relative Paths\r\n\r\nTo see if a path is an absolute path:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.isabs('/')\r\nTrue\r\n>>> os.path.isabs('..')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> Path('/').is_absolute()\r\nTrue\r\n>>> Path('..').is_absolute()\r\nFalse\r\n```\r\n\r\nYou can extract an absolute path with both `os.path` and `pathlib`\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.getcwd()\r\n'/home/asweigart'\r\n>>> os.path.abspath('..')\r\n'/home'\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\nfrom pathlib import Path\r\nprint(Path.cwd())\r\n/home/asweigart\r\nprint(Path('..').resolve())\r\n/home\r\n```\r\n\r\nYou can get a relative path from a starting path to another path.\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.relpath('/etc/passwd', '/')\r\n'etc/passwd'\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> print(Path('/etc/passwd').relative_to('/'))\r\netc/passwd\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Checking Path Validity\r\n\r\nChecking if a file/directory exists:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\nimport os\r\n>>> os.path.exists('.')\r\nTrue\r\n>>> os.path.exists('setup.py')\r\nTrue\r\n>>> os.path.exists('/etc')\r\nTrue\r\n>>> os.path.exists('nonexistentfile')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\nfrom pathlib import Path\r\n>>> Path('.').exists()\r\nTrue\r\n>>> Path('setup.py').exists()\r\nTrue\r\n>>> Path('/etc').exists()\r\nTrue\r\n>>> Path('nonexistentfile').exists()\r\nFalse\r\n```\r\n\r\nChecking if a path is a file:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.isfile('setup.py')\r\nTrue\r\n>>> os.path.isfile('/home')\r\nFalse\r\n>>> os.path.isfile('nonexistentfile')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> Path('setup.py').is_file()\r\nTrue\r\n>>> Path('/home').is_file()\r\nFalse\r\n>>> Path('nonexistentfile').is_file()\r\nFalse\r\n```\r\n\r\nChecking if a path is a directory:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.isdir('/')\r\nTrue\r\n>>> os.path.isdir('setup.py')\r\nFalse\r\n>>> os.path.isdir('/spam')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> Path('/').is_dir()\r\nTrue\r\n>>> Path('setup.py').is_dir()\r\nFalse\r\n>>> Path('/spam').is_dir()\r\nFalse\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Finding File Sizes and Folder Contents\r\n\r\nGetting a file's size in bytes:\r\n\r\nUsing `os.path` on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.getsize('C:\\\\Windows\\\\System32\\\\calc.exe')\r\n776192\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> stat = Path('/bin/python3.6').stat()\r\n>>> print(stat) # stat contains some other information about the file as well\r\nos.stat_result(st_mode=33261, st_ino=141087, st_dev=2051, st_nlink=2, st_uid=0,\r\n--snip--\r\nst_gid=0, st_size=10024, st_atime=1517725562, st_mtime=1515119809, st_ctime=1517261276)\r\n>>> print(stat.st_size) # size in bytes\r\n10024\r\n```\r\n\r\nListing directory contents using `os.listdir` on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> os.listdir('C:\\\\Windows\\\\System32')\r\n['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',\r\n--snip--\r\n'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']\r\n```\r\n\r\nListing directory contents using `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> for f in Path('/usr/bin').iterdir():\r\n>>>     print(f)\r\n...\r\n/usr/bin/tiff2rgba\r\n/usr/bin/iconv\r\n/usr/bin/ldd\r\n/usr/bin/cache_restore\r\n/usr/bin/udiskie\r\n/usr/bin/unix2dos\r\n/usr/bin/t1reencode\r\n/usr/bin/epstopdf\r\n/usr/bin/idle3\r\n...\r\n```\r\n\r\nTo find the total size of all the files in this directory:\r\n\r\n**WARNING**: Directories themselves also have a size! So you might want to\r\ncheck for whether a path is a file or directory using the methods in the methods discussed in the above section!\r\n\r\nUsing `os.path.getsize()` and `os.listdir()` together on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> total_size = 0\r\n\r\n>>> for filename in os.listdir('C:\\\\Windows\\\\System32'):\r\n      total_size = total_size + os.path.getsize(os.path.join('C:\\\\Windows\\\\System32', filename))\r\n\r\n>>> print(total_size)\r\n1117846456\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> total_size = 0\r\n\r\n>>> for sub_path in Path('/usr/bin').iterdir():\r\n...     total_size += sub_path.stat().st_size\r\n>>>\r\n>>> print(total_size)\r\n1903178911\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Copying Files and Folders\r\n\r\nThe shutil module provides functions for copying files, as well as entire folders.\r\n\r\n```python\r\n>>> import shutil, os\r\n\r\n>>> os.chdir('C:\\\\')\r\n\r\n>>> shutil.copy('C:\\\\spam.txt', 'C:\\\\delicious')\r\n   'C:\\\\delicious\\\\spam.txt'\r\n\r\n>>> shutil.copy('eggs.txt', 'C:\\\\delicious\\\\eggs2.txt')\r\n   'C:\\\\delicious\\\\eggs2.txt'\r\n```\r\n\r\nWhile shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and every folder and file contained in it:\r\n\r\n```python\r\n>>> import shutil, os\r\n\r\n>>> os.chdir('C:\\\\')\r\n\r\n>>> shutil.copytree('C:\\\\bacon', 'C:\\\\bacon_backup')\r\n'C:\\\\bacon_backup'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Moving and Renaming Files and Folders\r\n\r\n```python\r\n>>> import shutil\r\n>>> shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs')\r\n'C:\\\\eggs\\\\bacon.txt'\r\n```\r\n\r\nThe destination path can also specify a filename. In the following example, the source file is moved and renamed:\r\n\r\n```python\r\n>>> shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs\\\\new_bacon.txt')\r\n'C:\\\\eggs\\\\new_bacon.txt'\r\n```\r\n\r\n If there is no eggs folder, then move() will rename bacon.txt to a file named eggs.\r\n\r\n```python\r\n>>> shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs')\r\n'C:\\\\eggs'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Permanently Deleting Files and Folders\r\n\r\n- Calling os.unlink(path) or Path.unlink() will delete the file at path.\r\n\r\n- Calling os.rmdir(path) or Path.rmdir() will delete the folder at path. This folder must be empty of any files or folders.\r\n\r\n- Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be deleted.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Safe Deletes with the send2trash Module\r\n\r\n You can install this module by running pip install send2trash from a Terminal window.\r\n\r\n```python\r\n>>> import send2trash\r\n\r\n>>> with open('bacon.txt', 'a') as bacon_file: # creates the file\r\n...     bacon_file.write('Bacon is not a vegetable.')\r\n25\r\n\r\n>>> send2trash.send2trash('bacon.txt')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Walking a Directory Tree\r\n\r\n```python\r\n>>> import os\r\n>>>\r\n>>> for folder_name, subfolders, filenames in os.walk('C:\\\\delicious'):\r\n>>>     print('The current folder is {}'.format(folder_name))\r\n>>>\r\n>>>     for subfolder in subfolders:\r\n>>>         print('SUBFOLDER OF {}: {}'.format(folder_name, subfolder))\r\n>>>     for filename in filenames:\r\n>>>         print('FILE INSIDE {}: {}'.format(folder_name, filename))\r\n>>>\r\n>>>     print('')\r\nThe current folder is C:\\delicious\r\nSUBFOLDER OF C:\\delicious: cats\r\nSUBFOLDER OF C:\\delicious: walnut\r\nFILE INSIDE C:\\delicious: spam.txt\r\n\r\nThe current folder is C:\\delicious\\cats\r\nFILE INSIDE C:\\delicious\\cats: catnames.txt\r\nFILE INSIDE C:\\delicious\\cats: zophie.jpg\r\n\r\nThe current folder is C:\\delicious\\walnut\r\nSUBFOLDER OF C:\\delicious\\walnut: waffles\r\n\r\nThe current folder is C:\\delicious\\walnut\\waffles\r\nFILE INSIDE C:\\delicious\\walnut\\waffles: butter.txt\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n`pathlib` provides a lot more functionality than the ones listed above,\r\nlike getting file name, getting file extension, reading/writing a file without\r\nmanually opening it, etc. Check out the\r\n[official documentation](https://docs.python.org/3/library/pathlib.html)\r\nif you want to know more!\r\n\r\n## Reading and Writing Files\r\n\r\n### The File Reading/Writing Process\r\n\r\nTo read/write to a file in Python, you will want to use the `with`\r\nstatement, which will close the file for you after you are done.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Opening and reading files with the open() function\r\n\r\n```python\r\n>>> with open('C:\\\\Users\\\\your_home_folder\\\\hello.txt') as hello_file:\r\n...     hello_content = hello_file.read()\r\n>>> hello_content\r\n'Hello World!'\r\n\r\n>>> # Alternatively, you can use the *readlines()* method to get a list of string values from the file, one string for each line of text:\r\n\r\n>>> with open('sonnet29.txt') as sonnet_file:\r\n...     sonnet_file.readlines()\r\n[When, in disgrace with fortune and men's eyes,\\n', ' I all alone beweep my\r\noutcast state,\\n', And trouble deaf heaven with my bootless cries,\\n', And\r\nlook upon myself and curse my fate,']\r\n\r\n>>> # You can also iterate through the file line by line:\r\n>>> with open('sonnet29.txt') as sonnet_file:\r\n...     for line in sonnet_file: # note the new line character will be included in the line\r\n...         print(line, end='')\r\n\r\nWhen, in disgrace with fortune and men's eyes,\r\nI all alone beweep my outcast state,\r\nAnd trouble deaf heaven with my bootless cries,\r\nAnd look upon myself and curse my fate,\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Writing to Files\r\n\r\n```python\r\n>>> with open('bacon.txt', 'w') as bacon_file:\r\n...     bacon_file.write('Hello world!\\n')\r\n13\r\n\r\n>>> with open('bacon.txt', 'a') as bacon_file:\r\n...     bacon_file.write('Bacon is not a vegetable.')\r\n25\r\n\r\n>>> with open('bacon.txt') as bacon_file:\r\n...     content = bacon_file.read()\r\n\r\n>>> print(content)\r\nHello world!\r\nBacon is not a vegetable.\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Saving Variables with the shelve Module\r\n\r\nTo save variables:\r\n\r\n```python\r\n>>> import shelve\r\n\r\n>>> cats = ['Zophie', 'Pooka', 'Simon']\r\n>>> with shelve.open('mydata') as shelf_file:\r\n...     shelf_file['cats'] = cats\r\n```\r\n\r\nTo open and read variables:\r\n\r\n```python\r\n>>> with shelve.open('mydata') as shelf_file:\r\n...     print(type(shelf_file))\r\n...     print(shelf_file['cats'])\r\n<class 'shelve.DbfilenameShelf'>\r\n['Zophie', 'Pooka', 'Simon']\r\n```\r\n\r\nJust like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the list() function to get them in list form.\r\n\r\n```python\r\n>>> with shelve.open('mydata') as shelf_file:\r\n...     print(list(shelf_file.keys()))\r\n...     print(list(shelf_file.values()))\r\n['cats']\r\n[['Zophie', 'Pooka', 'Simon']]\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Saving Variables with the pprint.pformat() Function\r\n\r\n```python\r\n>>> import pprint\r\n\r\n>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]\r\n\r\n>>> pprint.pformat(cats)\r\n\"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]\"\r\n\r\n>>> with open('myCats.py', 'w') as file_obj:\r\n...     file_obj.write('cats = {}\\n'.format(pprint.pformat(cats)))\r\n83\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Reading ZIP Files\r\n\r\n```python\r\n>>> import zipfile, os\r\n\r\n>>> os.chdir('C:\\\\')    # move to the folder with example.zip\r\n>>> with zipfile.ZipFile('example.zip') as example_zip:\r\n...     print(example_zip.namelist())\r\n...     spam_info = example_zip.getinfo('spam.txt')\r\n...     print(spam_info.file_size)\r\n...     print(spam_info.compress_size)\r\n...     print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))\r\n\r\n['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']\r\n13908\r\n3828\r\n'Compressed file is 3.63x smaller!'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Extracting from ZIP Files\r\n\r\nThe extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current working directory.\r\n\r\n```python\r\n>>> import zipfile, os\r\n\r\n>>> os.chdir('C:\\\\')    # move to the folder with example.zip\r\n\r\n>>> with zipfile.ZipFile('example.zip') as example_zip:\r\n...     example_zip.extractall()\r\n```\r\n\r\nThe extract() method for ZipFile objects will extract a single file from the ZIP file. Continue the interactive shell example:\r\n\r\n```python\r\n>>> with zipfile.ZipFile('example.zip') as example_zip:\r\n...     print(example_zip.extract('spam.txt'))\r\n...     print(example_zip.extract('spam.txt', 'C:\\\\some\\\\new\\\\folders'))\r\n'C:\\\\spam.txt'\r\n'C:\\\\some\\\\new\\\\folders\\\\spam.txt'\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Creating and Adding to ZIP Files\r\n\r\n```python\r\n>>> import zipfile\r\n\r\n>>> with zipfile.ZipFile('new.zip', 'w') as new_zip:\r\n...     new_zip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)\r\n```\r\n\r\nThis code will create a new ZIP file named new.zip that has the compressed contents of spam.txt.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## JSON, YAML and configuration files\r\n\r\n### JSON\r\n\r\nOpen a JSON file with:\r\n\r\n```python\r\nimport json\r\nwith open(\"filename.json\", \"r\") as f:\r\n    content = json.loads(f.read())\r\n```\r\n\r\nWrite a JSON file with:\r\n\r\n```python\r\nimport json\r\n\r\ncontent = {\"name\": \"Joe\", \"age\": 20}\r\nwith open(\"filename.json\", \"w\") as f:\r\n    f.write(json.dumps(content, indent=2))\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### YAML\r\n\r\nCompared to JSON, YAML allows a much better humain maintainance and gives ability to add comments.\r\nIt is a convinient choice for configuration files where human will have to edit.\r\n\r\nThere are two main librairies allowing to access to YAML files:\r\n\r\n- [PyYaml](https://pypi.python.org/pypi/PyYAML)\r\n- [Ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml)\r\n\r\nInstall them using `pip install` in your virtual environment.\r\n\r\nThe first one it easier to use but the second one, Ruamel, implements much better the YAML\r\nspecification, and allow for example to modify a YAML content without altering comments.\r\n\r\nOpen a YAML file with:\r\n\r\n```python\r\nfrom ruamel.yaml import YAML\r\n\r\nwith open(\"filename.yaml\") as f:\r\n    yaml=YAML()\r\n    yaml.load(f)\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Anyconfig\r\n\r\n[Anyconfig](https://pypi.python.org/pypi/anyconfig) is a very handy package allowing to abstract completly the underlying configuration file format. It allows to load a Python dictionary from JSON, YAML, TOML, and so on.\r\n\r\nInstall it with:\r\n\r\n```bash\r\npip install anyconfig\r\n```\r\n\r\nUsage:\r\n\r\n```python\r\nimport anyconfig\r\n\r\nconf1 = anyconfig.load(\"/path/to/foo/conf.d/a.yml\")\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Debugging\r\n\r\n### Raising Exceptions\r\n\r\nExceptions are raised with a raise statement. In code, a raise statement consists of the following:\r\n\r\n- The raise keyword\r\n- A call to the Exception() function\r\n- A string with a helpful error message passed to the Exception() function\r\n\r\n```python\r\n>>> raise Exception('This is the error message.')\r\nTraceback (most recent call last):\r\n  File \"<pyshell#191>\", line 1, in <module>\r\n    raise Exception('This is the error message.')\r\nException: This is the error message.\r\n```\r\n\r\nOften it’s the code that calls the function, not the function itself, that knows how to handle an expection. So you will commonly see a raise statement inside a function and the try and except statements in the code calling the function.\r\n\r\n```python\r\ndef box_print(symbol, width, height):\r\n    if len(symbol) != 1:\r\n      raise Exception('Symbol must be a single character string.')\r\n    if width <= 2:\r\n      raise Exception('Width must be greater than 2.')\r\n    if height <= 2:\r\n      raise Exception('Height must be greater than 2.')\r\n    print(symbol * width)\r\n    for i in range(height - 2):\r\n        print(symbol + (' ' * (width - 2)) + symbol)\r\n    print(symbol * width)\r\nfor sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):\r\n    try:\r\n        box_print(sym, w, h)\r\n    except Exception as err:\r\n        print('An exception happened: ' + str(err))\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Getting the Traceback as a String\r\n\r\nThe traceback is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function.\r\n\r\n```python\r\n>>> import traceback\r\n\r\n>>> try:\r\n>>>      raise Exception('This is the error message.')\r\n>>> except:\r\n>>>      with open('errorInfo.txt', 'w') as error_file:\r\n>>>          error_file.write(traceback.format_exc())\r\n>>>      print('The traceback info was written to errorInfo.txt.')\r\n116\r\nThe traceback info was written to errorInfo.txt.\r\n```\r\n\r\nThe 116 is the return value from the write() method, since 116 characters were written to the file. The traceback text was written to errorInfo.txt.\r\n\r\n    Traceback (most recent call last):\r\n      File \"<pyshell#28>\", line 2, in <module>\r\n    Exception: This is the error message.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Assertions\r\n\r\nAn assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity checks are performed by assert statements. If the sanity check fails, then an AssertionError exception is raised. In code, an assert statement consists of the following:\r\n\r\n- The assert keyword\r\n- A condition (that is, an expression that evaluates to True or False)\r\n- A comma\r\n- A string to display when the condition is False\r\n\r\n```python\r\n>>> pod_bay_door_status = 'open'\r\n\r\n>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\r\n\r\n>>> pod_bay_door_status = 'I\\'m sorry, Dave. I\\'m afraid I can\\'t do that.'\r\n\r\n>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\r\n\r\nTraceback (most recent call last):\r\n  File \"<pyshell#10>\", line 1, in <module>\r\n    assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\r\nAssertionError: The pod bay doors need to be \"open\".\r\n```\r\n\r\nIn plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have to check before finding the code that’s causing the bug.\r\n\r\nDisabling Assertions\r\n\r\nAssertions can be disabled by passing the -O option when running Python.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Logging\r\n\r\nTo enable the logging module to display log messages on your screen as your program runs, copy the following to the top of your program (but under the #! python shebang line):\r\n\r\n```python\r\nimport logging\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\r\n```\r\n\r\nSay you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going wrong. Save the program as factorialLog.py.\r\n\r\n```python\r\n>>> import logging\r\n>>>\r\n>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\r\n>>>\r\n>>> logging.debug('Start of program')\r\n>>>\r\n>>> def factorial(n):\r\n>>>\r\n>>>     logging.debug('Start of factorial(%s)' % (n))\r\n>>>     total = 1\r\n>>>\r\n>>>     for i in range(1, n + 1):\r\n>>>         total *= i\r\n>>>         logging.debug('i is ' + str(i) + ', total is ' + str(total))\r\n>>>\r\n>>>     logging.debug('End of factorial(%s)' % (n))\r\n>>>\r\n>>>     return total\r\n>>>\r\n>>> print(factorial(5))\r\n>>> logging.debug('End of program')\r\n2015-05-23 16:20:12,664 - DEBUG - Start of program\r\n2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)\r\n2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0\r\n2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0\r\n2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0\r\n2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0\r\n2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0\r\n2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0\r\n2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)\r\n0\r\n2015-05-23 16:20:12,684 - DEBUG - End of program\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Logging Levels\r\n\r\nLogging levels provide a way to categorize your log messages by importance. There are five logging levels, described in Table 10-1 from least to most important. Messages can be logged at each level using a different logging function.\r\n\r\n| Level      | Logging Function     | Description                                                                                                                    |\r\n| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\r\n| `DEBUG`    | `logging.debug()`    | The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems.                 |\r\n| `INFO`     | `logging.info()`     | Used to record information on general events in your program or confirm that things are working at their point in the program. |\r\n| `WARNING`  | `logging.warning()`  | Used to indicate a potential problem that doesn’t prevent the program from working but might do so in the future.             |\r\n| `ERROR`    | `logging.error()`    | Used to record an error that caused the program to fail to do something.                                                       |\r\n| `CRITICAL` | `logging.critical()` | The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely.   |\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Disabling Logging\r\n\r\nAfter you’ve debugged your program, you probably don’t want all these log messages cluttering the screen. The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging calls by hand.\r\n\r\n```python\r\n>>> import logging\r\n\r\n>>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')\r\n\r\n>>> logging.critical('Critical error! Critical error!')\r\n2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!\r\n\r\n>>> logging.disable(logging.CRITICAL)\r\n\r\n>>> logging.critical('Critical error! Critical error!')\r\n\r\n>>> logging.error('Error! Error!')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Logging to a File\r\n\r\nInstead of displaying the log messages to the screen, you can write them to a text file. The logging.basicConfig() function takes a filename keyword argument, like so:\r\n\r\n```python\r\nimport logging\r\n\r\nlogging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Lambda Functions\r\n\r\nThis function:\r\n\r\n```python\r\n>>> def add(x, y):\r\n        return x + y\r\n\r\n>>> add(5, 3)\r\n8\r\n```\r\n\r\nIs equivalent to the *lambda* function:\r\n\r\n```python\r\n>>> add = lambda x, y: x + y\r\n>>> add(5, 3)\r\n8\r\n```\r\n\r\nIt's not even need to bind it to a name like add before:\r\n\r\n```python\r\n>>> (lambda x, y: x + y)(5, 3)\r\n8\r\n```\r\n\r\nLike regular nested functions, lambdas also work as lexical closures:\r\n\r\n```python\r\n>>> def make_adder(n):\r\n        return lambda x: x + n\r\n\r\n>>> plus_3 = make_adder(3)\r\n>>> plus_5 = make_adder(5)\r\n\r\n>>> plus_3(4)\r\n7\r\n>>> plus_5(4)\r\n9\r\n```\r\n\r\nNote: lambda can only evaluate an expression, like a single line of code.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Ternary Conditional Operator\r\n\r\nMany programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, otherwise it evaluates the second expression.\r\n\r\n    <expression1> if <condition> else <expression2>\r\n\r\nExample:\r\n\r\n```python\r\n>>> age = 15\r\n\r\n>>> print('kid' if age < 18 else 'adult')\r\nkid\r\n```\r\n\r\nTernary operators can be changed:\r\n\r\n```python\r\n>>> age = 15\r\n\r\n>>> print('kid' if age < 13 else 'teenager' if age < 18 else 'adult')\r\nteenager\r\n```\r\n\r\nThe code above is equivalent to:\r\n\r\n```python\r\nif age < 18:\r\n    if age < 12:\r\n        print('kid')\r\n    else:\r\n        print('teenager')\r\nelse:\r\n    print('adult')\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## args and kwargs\r\n\r\nThe names ```args and kwargs``` are arbitrary - the important thing are the ```*``` and ```**``` operators. They can mean:\r\n\r\n1. In a function declaration, ```*``` means “pack all remaining positional arguments into a tuple named `<name>`”, while ```**``` is the same for keyword arguments (except it uses a dictionary, not a tuple).\r\n\r\n2. In a function call, ```*``` means “unpack tuple or list named `<name>` to positional arguments at this position”, while ```**``` is the same for keyword arguments.\r\n\r\nFor example you can make a function that you can use to call any other function, no matter what parameters it has:\r\n\r\n```python\r\ndef forward(f, *args, **kwargs):\r\n    return f(*args, **kwargs)\r\n```\r\n\r\nInside forward, args is a tuple (of all positional arguments except the first one, because we specified it - the f), kwargs is a dict. Then we call f and unpack them so they become normal arguments to f.\r\n\r\nYou use ```*args``` when you have an indefinite amount of positional arguments.\r\n\r\n```python\r\n>>> def fruits(*args):\r\n>>>    for fruit in args:\r\n>>>       print(fruit)\r\n\r\n>>> fruits(\"apples\", \"bananas\", \"grapes\")\r\n\r\n\"apples\"\r\n\"bananas\"\r\n\"grapes\"\r\n```\r\n\r\nSimilarly, you use ```**kwargs``` when you have an indefinite number of keyword arguments.\r\n\r\n```python\r\n>>> def fruit(**kwargs):\r\n>>>    for key, value in kwargs.items():\r\n>>>        print(\"{0}: {1}\".format(key, value))\r\n\r\n>>> fruit(name = \"apple\", color = \"red\")\r\n\r\nname: apple\r\ncolor: red\r\n```\r\n\r\n```python\r\n>>> def show(arg1, arg2, *args, kwarg1=None, kwarg2=None, **kwargs):\r\n>>>   print(arg1)\r\n>>>   print(arg2)\r\n>>>   print(args)\r\n>>>   print(kwarg1)\r\n>>>   print(kwarg2)\r\n>>>   print(kwargs)\r\n\r\n>>> data1 = [1,2,3]\r\n>>> data2 = [4,5,6]\r\n>>> data3 = {'a':7,'b':8,'c':9}\r\n\r\n>>> show(*data1,*data2, kwarg1=\"python\",kwarg2=\"cheatsheet\",**data3)\r\n1\r\n2\r\n(3, 4, 5, 6)\r\npython\r\ncheatsheet\r\n{'a': 7, 'b': 8, 'c': 9}\r\n\r\n>>> show(*data1, *data2, **data3)\r\n1\r\n2\r\n(3, 4, 5, 6)\r\nNone\r\nNone\r\n{'a': 7, 'b': 8, 'c': 9}\r\n\r\n# If you do not specify ** for kwargs\r\n>>> show(*data1, *data2, *data3)\r\n1\r\n2\r\n(3, 4, 5, 6, \"a\", \"b\", \"c\")\r\nNone\r\nNone\r\n{}\r\n```\r\n\r\n### Thinks to Remember(args)\r\n\r\n1. Functions can accept a variable number of positional arguments by using ```*args``` in the def statement.\r\n2. You can use the items from a sequence as the positional arguments for a function with the ```*``` operator.\r\n3. Using the ```*``` operator with a generator may cause your program to run out of memory and crash.\r\n4. Adding new positional parameters to functions that accept ```*args``` can introduce hard-to-find bugs.\r\n\r\n### Thinks to remember(kwargs)\r\n\r\n1. Function arguments can be specified by position or by keyword.\r\n2. Keywords make it clear what the purpose of each argument is when it would be confusing with only positional arguments.\r\n3. Keyword arguments with default values make it easy to add new behaviors to a function, especially when the function has existing callers.\r\n4. Optional keyword arguments should always be passed by keyword instead of by position.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Context Manager\r\n\r\nWhile Python's context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes.\r\n\r\n### with statement\r\n\r\nA context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the with statement. It takes care of the notifying.\r\n\r\nFor example, file objects are context managers. When a context ends, the file object is closed automatically:\r\n\r\n```python\r\n>>> with open(filename) as f:\r\n>>>     file_contents = f.read()\r\n\r\n# the open_file object has automatically been closed.\r\n```\r\n\r\nAnything that ends execution of the block causes the context manager's exit method to be called. This includes exceptions, and can be useful when an error causes you to prematurely exit from an open file or connection. Exiting a script without properly closing files/connections is a bad idea, that may cause data loss or other problems. By using a context manager you can ensure that precautions are always taken to prevent damage or loss in this way.\r\n\r\n### Writing your own contextmanager using generator syntax\r\n\r\nIt is also possible to write a context manager using generator syntax thanks to the ```contextlib.contextmanager``` decorator:\r\n\r\n```python\r\n>>> import contextlib\r\n>>> @contextlib.contextmanager\r\n... def context_manager(num):\r\n...     print('Enter')\r\n...     yield num + 1\r\n...     print('Exit')\r\n>>> with context_manager(2) as cm:\r\n...     # the following instructions are run when the 'yield' point of the context\r\n...     # manager is reached.\r\n...     # 'cm' will have the value that was yielded\r\n...     print('Right in the middle with cm = {}'.format(cm))\r\nEnter\r\nRight in the middle with cm = 3\r\nExit\r\n\r\n>>>\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## `__main__` Top-level script environment\r\n\r\n`__main__` is the name of the scope in which top-level code executes.\r\nA module’s __name__ is set equal to `__main__` when read from standard input, a script, or from an interactive prompt.\r\n\r\nA module can discover whether or not it is running in the main scope by checking its own `__name__`, which allows a common idiom for conditionally executing code in a module when it is run as a script or with `python -m` but not when it is imported:\r\n\r\n```python\r\n>>> if __name__ == \"__main__\":\r\n...     # execute only if run as a script\r\n...     main()\r\n```\r\n\r\nFor a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m\r\n\r\nFor example we are developing script which is designed to be used as module, we should do:\r\n\r\n```python\r\n>>> # Python program to execute function directly\r\n>>> def add(a, b):\r\n...     return a+b\r\n...\r\n>>> add(10, 20) # we can test it by calling the function save it as calculate.py\r\n30\r\n>>> # Now if we want to use that module by importing we have to comment out our call,\r\n>>> # Instead we can write like this in calculate.py\r\n>>> if __name__ == \"__main__\":\r\n...     add(3, 5)\r\n...\r\n>>> import calculate\r\n>>> calculate.add(3, 5)\r\n8\r\n```\r\n\r\n### Advantages\r\n\r\n1. Every Python module has it’s `__name__` defined and if this is `__main__`, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.\r\n2. If you import this script as a module in another script, the __name__ is set to the name of the script/module.\r\n3. Python files can act as either reusable modules, or as standalone programs.\r\n4. if `__name__ == “main”:` is used to execute some code only if the file was run directly, and not imported.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## setup.py\r\n\r\nThe setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing.\r\n\r\nThe `setup.py` file is at the heart of a Python project. It describes all of the metadata about your project. There a quite a few fields you can add to a project to give it a rich set of metadata describing the project. However, there are only three required fields: name, version, and packages. The name field must be unique if you wish to publish your package on the Python Package Index (PyPI). The version field keeps track of different releases of the project. The packages field describes where you’ve put the Python source code within your project.\r\n\r\nThis allows you to easily install Python packages. Often it's enough to write:\r\n\r\n```bash\r\npython setup.py install\r\n```\r\n\r\nand module will install itself.\r\n\r\nOur initial setup.py will also include information about the license and will re-use the README.txt file for the long_description field. This will look like:\r\n\r\n```python\r\n>>> from distutils.core import setup\r\n>>> setup(\r\n...    name='pythonCheatsheet',\r\n...    version='0.1',\r\n...    packages=['pipenv',],\r\n...    license='MIT',\r\n...    long_description=open('README.txt').read(),\r\n... )\r\n```\r\n\r\nFind more information visit [http://docs.python.org/install/index.html](http://docs.python.org/install/index.html).\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Dataclasses\r\n\r\n`Dataclasses` are python classes but are suited for storing data objects.\r\nThis module provides a decorator and functions for automatically adding generated special methods such as `__init__()` and `__repr__()` to user-defined classes.\r\n\r\n### Features\r\n\r\n1. They store data and represent a certain data type. Ex: A number. For people familiar with ORMs, a model instance is a data object. It represents a specific kind of entity. It holds attributes that define or represent the entity.\r\n\r\n2. They can be compared to other objects of the same type. Ex: A number can be greater than, less than, or equal to another number.\r\n\r\nPython 3.7 provides a decorator dataclass that is used to convert a class into a dataclass.\r\n\r\npython 2.7\r\n\r\n```python\r\n>>> class Number:\r\n...     def __init__(self, val):\r\n...         self.val = val\r\n...\r\n>>> obj = Number(2)\r\n>>> obj.val\r\n2\r\n```\r\n\r\nwith dataclass\r\n\r\n```python\r\n>>> @dataclass\r\n... class Number:\r\n...     val: int\r\n...\r\n>>> obj = Number(2)\r\n>>> obj.val\r\n2\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### Default values\r\n\r\nIt is easy to add default values to the fields of your data class.\r\n\r\n```python\r\n>>> @dataclass\r\n... class Product:\r\n...     name: str\r\n...     count: int = 0\r\n...     price: float = 0.0\r\n...\r\n>>> obj = Product(\"Python\")\r\n>>> obj.name\r\nPython\r\n>>> obj.count\r\n0\r\n>>> obj.price\r\n0.0\r\n```\r\n\r\n### Type hints\r\n\r\nIt is mandatory to define the data type in dataclass. However, If you don't want specify the datatype then, use ```typing.Any```.\r\n\r\n```python\r\n>>> from dataclasses import dataclass\r\n>>> from typing import Any\r\n\r\n>>> @dataclass\r\n... class WithoutExplicitTypes:\r\n...    name: Any\r\n...    value: Any = 42\r\n...\r\n```\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n## Virtual Environment\r\n\r\nThe use of a Virtual Environment is to test python code in encapsulated environments and to also avoid filling the base Python installation with libraries we might use for only one project.\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### virtualenv\r\n\r\n1. Install virtualenv\r\n\r\n        pip install virtualenv\r\n\r\n1. Install virtualenvwrapper-win (Windows)\r\n\r\n        pip install virtualenvwrapper-win\r\n\r\nUsage:\r\n\r\n1. Make a Virtual Environment\r\n\r\n        mkvirtualenv HelloWold\r\n\r\n    Anything we install now will be specific to this project. And available to the projects we connect to this environment.\r\n\r\n1. Set Project Directory\r\n\r\n    To bind our virtualenv with our current working directory we simply enter:\r\n\r\n        setprojectdir .\r\n\r\n1. Deactivate\r\n\r\n    To move onto something else in the command line type ‘deactivate’ to deactivate your environment.\r\n\r\n        deactivate\r\n\r\n    Notice how the parenthesis disappear.\r\n\r\n1. Workon\r\n\r\n    Open up the command prompt and type ‘workon HelloWold’ to activate the environment and move into your root project folder\r\n\r\n        workon HelloWold\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### pipenv\r\n\r\n> [Pipenv](https://pipenv.readthedocs.io/en/latest/) is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.\r\n\r\n1. Install pipenv\r\n\r\n        pip install pipenv\r\n\r\n1. Enter your Project directory and install the Packages for your project\r\n\r\n        cd my_project\r\n        pipenv install <package>\r\n\r\n    Pipenv will install your package and create a Pipfile for you in your project’s directory. The Pipfile is used to track which dependencies your project needs in case you need to re-install them.\r\n\r\n1. Uninstall Packages\r\n\r\n        pipenv uninstall <package>\r\n\r\n1. Activate the Virtual Environment associated with your Python project\r\n\r\n        pipenv shell\r\n\r\n1. Exit the Virtual Environment\r\n\r\n        exit\r\n\r\nFind more information and a video in [docs.pipenv.org](https://docs.pipenv.org/).\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n\r\n### anaconda\r\n\r\n[Anaconda](https://anaconda.org/) is another popular tool to manage python packages.\r\n\r\n> Where packages, notebooks, projects and environments are shared. \r\nYour place for free public conda package hosting.\r\n\r\nUsage:\r\n\r\n1. Make a Virtual Environment\r\n\r\n        conda create -n HelloWorld\r\n\r\n2. To use the Virtual Environment, activate it by:\r\n\r\n        conda activate HelloWorld\r\n\r\n    Anything installed now will be specific to the project HelloWorld\r\n\r\n3. Exit the Virtual Environment\r\n\r\n        conda deactivate\r\n\r\n\r\n[*Return to the Top*](#python-cheatsheet)\r\n"
  },
  {
    "path": "Python/_config.yml",
    "content": "theme: jekyll-theme-cayman"
  },
  {
    "path": "Python/blog_files/about.md",
    "content": "## About Python Cheat Sheet\r\n\r\nThis is a basic [cheatsheet](https://www.pythoncheatsheet.org) for Python mostly based on the book written by Al Sweigart, [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) under the [Creative Commons license](https://creativecommons.org/licenses/by-nc-sa/3.0/) and many other sources.\r\n\r\n> Anyone can forget how to make [character classes for a regex](https://www.pythoncheatsheet.org/index#Making-Your-Own-Character-Classes), [slice a list](https://www.pythoncheatsheet.org/index#Getting-Sublists-with-Slices) or do a [for loop](https://www.pythoncheatsheet.org/index#Using-for-Loops-with-Lists). This cheatsheet tries to provide a basic reference for beginner and advanced developers, lower the entry barrier for newcomers and help veterans refresh the old tricks.\r\n\r\n## About the Website\r\n\r\nBuild with the [Flask](http://flask.pocoo.org/) microframework, this website provides a simple managment system with the following features:\r\n\r\n### Features\r\n\r\n- Blog system powered by SqlAlchemy\r\n- Articles and Static pages can render Markdown, HTML or both.\r\n- Uses a lightweight comments widget built on GitHub issues: [Utterances](https://github.com/utterance/utterances).\r\n- Tags.\r\n- Users roles.\r\n- Custom Profiles for users.\r\n- Quick search for static pages.\r\n- Elasticsearch integration.\r\n- Users Managment (create, edit, delete).\r\n- Articles Managment (create, edit, delete).\r\n- Licensed [MIT](https://github.com/wilfredinni/pysheetBlog/blob/master/LICENSE).\r\n\r\nIn the frontend is [Bulma](https://github.com/jgthms/bulma), a great and easy to use CSS framework along with some vanilla Javascript.\r\n\r\n![flask](https://raw.githubusercontent.com/wilfredinni/pysheetBlog/master/img/new_post.png)\r\n\r\nFor more information visit the [Project Page](https://github.com/wilfredinni/pysheetBlog).\r\n"
  },
  {
    "path": "Python/blog_files/pysheet.md",
    "content": "## The Zen of Python\r\n\r\nFrom the [PEP 20 -- The Zen of Python](https://www.python.org/dev/peps/pep-0020/):\r\n\r\n> Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.\r\n\r\n```python\r\n>>> import this\r\nThe Zen of Python, by Tim Peters\r\n\r\nBeautiful is better than ugly.\r\nExplicit is better than implicit.\r\nSimple is better than complex.\r\nComplex is better than complicated.\r\nFlat is better than nested.\r\nSparse is better than dense.\r\nReadability counts.\r\nSpecial cases aren't special enough to break the rules.\r\nAlthough practicality beats purity.\r\nErrors should never pass silently.\r\nUnless explicitly silenced.\r\nIn the face of ambiguity, refuse the temptation to guess.\r\nThere should be one-- and preferably only one --obvious way to do it.\r\nAlthough that way may not be obvious at first unless you're Dutch.\r\nNow is better than never.\r\nAlthough never is often better than *right* now.\r\nIf the implementation is hard to explain, it's a bad idea.\r\nIf the implementation is easy to explain, it may be a good idea.\r\nNamespaces are one honking great idea -- let's do more of those!\r\n```\r\n\r\n## Python Basics\r\n\r\n### Math Operators\r\n\r\nFrom **Highest** to **Lowest** precedence:\r\n\r\n| Operators | Operation        | Example         |\r\n| --------- | ---------------- | --------------- |\r\n| **        | Exponent         | `2 ** 3 = 8`    |\r\n| %         | Modulus/Remaider | `22 % 8 = 6`    |\r\n| //        | Integer division | `22 // 8 = 2`   |\r\n| /         | Division         | `22 / 8 = 2.75` |\r\n| *         | Multiplication   | `3 * 3 = 9`     |\r\n| -         | Subtraction      | `5 - 2 = 3`     |\r\n| +         | Addition         | `2 + 2 = 4`     |\r\n\r\nExamples of expressions in the interactive shell:\r\n\r\n```python\r\n>>> 2 + 3 * 6\r\n20\r\n```\r\n\r\n```python\r\n>>> (2 + 3) * 6\r\n30\r\n```\r\n\r\n```python\r\n>>> 2 ** 8\r\n256\r\n```\r\n\r\n```python\r\n>>> 23 // 7\r\n3\r\n```\r\n\r\n```python\r\n>>> 23 % 7\r\n2\r\n```\r\n\r\n```python\r\n>>> (5 - 1) * ((7 + 1) / (3 - 1))\r\n16.0\r\n```\r\n\r\n### Data Types\r\n\r\n| Data Type              | Examples                                  |\r\n| ---------------------- | ----------------------------------------- |\r\n| Integers               | `-2, -1, 0, 1, 2, 3, 4, 5`                |\r\n| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` |\r\n| Strings                | `'a', 'aa', 'aaa', 'Hello!', '11 cats'`   |\r\n\r\n### String Concatenation and Replication\r\n\r\nString concatenation:\r\n\r\n```python\r\n>>> 'Alice' 'Bob'\r\n'AliceBob'\r\n```\r\n\r\nNote: Avoid `+` operator for string concatenation. Prefer string formatting.\r\n\r\nString Replication:\r\n\r\n```python\r\n>>> 'Alice' * 5\r\n'AliceAliceAliceAliceAlice'\r\n```\r\n\r\n### Variables\r\n\r\nYou can name a variable anything as long as it obeys the following three rules:\r\n\r\n1. It can be only one word.\r\n1. It can use only letters, numbers, and the underscore (`_`) character.\r\n1. It can’t begin with a number.\r\n1. Variable name starting with an underscore (`_`) are considered as \"unuseful`.\r\n\r\nExample:\r\n\r\n```python\r\n>>> spam = 'Hello'\r\n>>> spam\r\n'Hello'\r\n```\r\n\r\n```python\r\n>>> _spam = 'Hello'\r\n```\r\n\r\n`_spam` should not be used again in the code.\r\n\r\n### Comments\r\n\r\nInline comment:\r\n\r\n```python\r\n# This is a comment\r\n```\r\n\r\nMultiline comment:\r\n\r\n```Python\r\n# This is a\r\n# multiline comment\r\n```\r\n\r\nCode with a comment:\r\n\r\n```python\r\na = 1  # initialization\r\n```\r\n\r\nPlease note the two spaces in front of the comment.\r\n\r\nFunction docstring:\r\n\r\n```python\r\ndef foo():\r\n    \"\"\"\r\n    This is a function docstring\r\n    You can also use:\r\n    ''' Function Docstring '''\r\n    \"\"\"\r\n```\r\n\r\n### The print Function\r\n\r\n```python\r\n>>> print('Hello world!')\r\nHello world!\r\n```\r\n\r\n```python\r\n>>> a = 1\r\n>>> print('Hello world!', a)\r\nHello world! 1\r\n```\r\n\r\n### The input Function\r\n\r\nExample Code:\r\n\r\n```python\r\n>>> print('What is your name?')   # ask for their name\r\n>>> myName = input()\r\n>>> print('It is good to meet you, {}'.format(myName))\r\nWhat is your name?\r\nAl\r\nIt is good to meet you, Al\r\n```\r\n\r\n### The len Function\r\n\r\nEvaluates to the integer value of the number of characters in a string:\r\n\r\n```python\r\n>>> len('hello')\r\n5\r\n```\r\n\r\nNote: test of emptiness of strings, lists, dictionary, etc, should **not** use len, but prefer direct\r\nboolean evaluation.\r\n\r\n```python\r\n>>> a = [1, 2, 3]\r\n>>> if a:\r\n>>>     print(\"the list is not empty!\")\r\n```\r\n\r\n### The str, int, and float Functions\r\n\r\nInteger to String or Float:\r\n\r\n```python\r\n>>> str(29)\r\n'29'\r\n```\r\n\r\n```python\r\n>>> print('I am {} years old.'.format(str(29)))\r\nI am 29 years old.\r\n```\r\n\r\n```python\r\n>>> str(-3.14)\r\n'-3.14'\r\n```\r\n\r\nFloat to Integer:\r\n\r\n```python\r\n>>> int(7.7)\r\n7\r\n```\r\n\r\n```python\r\n>>> int(7.7) + 1\r\n8\r\n```\r\n\r\n## Flow Control\r\n\r\n### Comparison Operators\r\n\r\n| Operator | Meaning                  |\r\n| -------- | ------------------------ |\r\n| `==`     | Equal to                 |\r\n| `!=`     | Not equal to             |\r\n| `<`      | Less than                |\r\n| `>`      | Greater Than             |\r\n| `<=`     | Less than or Equal to    |\r\n| `>=`     | Greater than or Equal to |\r\n\r\nThese operators evaluate to True or False depending on the values you give them.\r\n\r\nExamples:\r\n\r\n```python\r\n>>> 42 == 42\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 40 == 42\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'hello' == 'hello'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'hello' == 'Hello'\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'dog' != 'cat'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 42 == 42.0\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 42 == '42'\r\nFalse\r\n```\r\n\r\n### Boolean evaluation\r\n\r\nNever use `==` or `!=` operator to evaluate boolean operation. Use the `is` or `is not` operators,\r\nor use implicit boolean evaluation.\r\n\r\nNO (even if they are valid Python):\r\n\r\n```python\r\n>>> True == True\r\nTrue\r\n```\r\n\r\n```python\r\n>>> True != False\r\nTrue\r\n```\r\n\r\nYES (even if they are valid Python):\r\n\r\n```python\r\n>>> True is True\r\nTrue\r\n```\r\n\r\n```python\r\n>>> True is not False\r\nTrue\r\n```\r\n\r\nThese statements are equivalent:\r\n\r\n```Python\r\n>>> if a is True:\r\n>>>    pass\r\n>>> if a is not False:\r\n>>>    pass\r\n>>> if a:\r\n>>>    pass\r\n```\r\n\r\nAnd these as well:\r\n\r\n```Python\r\n>>> if a is False:\r\n>>>    pass\r\n>>> if a is not True:\r\n>>>    pass\r\n>>> if not a:\r\n>>>    pass\r\n```\r\n\r\n### Boolean Operators\r\n\r\nThere are three Boolean operators: and, or, and not.\r\n\r\nThe *and* Operator’s *Truth* Table:\r\n\r\n| Expression      | Evaluates to |\r\n| --------------- | ------------ |\r\n| True and True   | True         |\r\n| True and False  | False        |\r\n| False and True  | False        |\r\n| False and False | False        |\r\n\r\nThe *or* Operator’s *Truth* Table:\r\n\r\n| Expression     | Evaluates to |\r\n| -------------- | ------------ |\r\n| True or True   | True         |\r\n| True or False  | True         |\r\n| False or True  | True         |\r\n| False or False | False        |\r\n\r\nThe *not* Operator’s *Truth* Table:\r\n\r\n| Expression | Evaluates to |\r\n| ---------- | ------------ |\r\n| not True   | False        |\r\n| not False  | True         |\r\n\r\n### Mixing Boolean and Comparison Operators\r\n\r\n```python\r\n>>> (4 < 5) and (5 < 6)\r\nTrue\r\n```\r\n\r\n```python\r\n>>> (4 < 5) and (9 < 6)\r\nFalse\r\n```\r\n\r\n```python\r\n>>> (1 == 2) or (2 == 2)\r\nTrue\r\n```\r\n\r\nYou can also use multiple Boolean operators in an expression, along with the comparison operators:\r\n\r\n```python\r\n>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2\r\nTrue\r\n```\r\n\r\n### if Statements\r\n\r\n```python\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\n```\r\n\r\n### else Statements\r\n\r\n```python\r\nname = 'Bob'\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\nelse:\r\n    print('Hello, stranger.')\r\n```\r\n\r\n### elif Statements\r\n\r\n```python\r\nname = 'Bob'\r\nage = 5\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\nelif age < 12:\r\n    print('You are not Alice, kiddo.')\r\n```\r\n\r\n```python\r\nname = 'Bob'\r\nage = 30\r\nif name == 'Alice':\r\n    print('Hi, Alice.')\r\nelif age < 12:\r\n    print('You are not Alice, kiddo.')\r\nelse:\r\n    print('You are neither Alice nor a little kid.')\r\n```\r\n\r\n### while Loop Statements\r\n\r\n```python\r\nspam = 0\r\nwhile spam < 5:\r\n    print('Hello, world.')\r\n    spam = spam + 1\r\n```\r\n\r\n### break Statements\r\n\r\n If the execution reaches a break statement, it immediately exits the while loop’s clause:\r\n\r\n```python\r\nwhile True:\r\n    print('Please type your name.')\r\n    name = input()\r\n    if name == 'your name':\r\n        break\r\nprint('Thank you!')\r\n```\r\n\r\n### continue Statements\r\n\r\nWhen the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.\r\n\r\n```python\r\nwhile True:\r\n    print('Who are you?')\r\n    name = input()\r\n    if name != 'Joe':\r\n        continue\r\n    print('Hello, Joe. What is the password? (It is a fish.)')\r\n    password = input()\r\n    if password == 'swordfish':\r\n        break\r\nprint('Access granted.')\r\n```\r\n\r\n### for Loops and the range() Function\r\n\r\n```python\r\n>>> print('My name is')\r\n>>> for i in range(5):\r\n>>>     print('Jimmy Five Times ({})'.format(str(i)))\r\nMy name is\r\nJimmy Five Times (0)\r\nJimmy Five Times (1)\r\nJimmy Five Times (2)\r\nJimmy Five Times (3)\r\nJimmy Five Times (4)\r\n```\r\n\r\nThe *range()* function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.\r\n\r\n```python\r\n>>> for i in range(0, 10, 2):\r\n>>>    print(i)\r\n0\r\n2\r\n4\r\n6\r\n8\r\n```\r\n\r\nYou can even use a negative number for the step argument to make the for loop count down instead of up.\r\n\r\n```python\r\n>>> for i in range(5, -1, -1):\r\n>>>     print(i)\r\n5\r\n4\r\n3\r\n2\r\n1\r\n0\r\n```\r\n\r\n### For else statement\r\n\r\nThis allows to specify a statement to execute in case of the full loop has been executed. Only\r\nuseful when a `break` condition can occur in the loop:\r\n\r\n```python\r\n>>> for i in [1, 2, 3, 4, 5]:\r\n>>>    if i == 3:\r\n>>>        break\r\n>>> else:\r\n>>>    print(\"only executed when no item of the list is equal to 3\")\r\n```\r\n\r\n### Importing Modules\r\n\r\n```python\r\nimport random\r\nfor i in range(5):\r\n    print(random.randint(1, 10))\r\n```\r\n\r\n```python\r\nimport random, sys, os, math\r\n```\r\n\r\n```python\r\nfrom random import *.\r\n```\r\n\r\n### Ending a Program with sys.exit\r\n\r\n```python\r\nimport sys\r\n\r\nwhile True:\r\n    print('Type exit to exit.')\r\n    response = input()\r\n    if response == 'exit':\r\n        sys.exit()\r\n    print('You typed {}.'.format(response))\r\n```\r\n\r\n## Functions\r\n\r\n```python\r\n>>> def hello(name):\r\n>>>     print('Hello {}'.format(name))\r\n>>>\r\n>>> hello('Alice')\r\n>>> hello('Bob')\r\nHello Alice\r\nHello Bob\r\n```\r\n\r\n### Return Values and return Statements\r\n\r\nWhen creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:\r\n\r\n- The return keyword.\r\n\r\n- The value or expression that the function should return.\r\n\r\n```python\r\nimport random\r\ndef getAnswer(answerNumber):\r\n    if answerNumber == 1:\r\n        return 'It is certain'\r\n    elif answerNumber == 2:\r\n        return 'It is decidedly so'\r\n    elif answerNumber == 3:\r\n        return 'Yes'\r\n    elif answerNumber == 4:\r\n        return 'Reply hazy try again'\r\n    elif answerNumber == 5:\r\n        return 'Ask again later'\r\n    elif answerNumber == 6:\r\n        return 'Concentrate and ask again'\r\n    elif answerNumber == 7:\r\n        return 'My reply is no'\r\n    elif answerNumber == 8:\r\n        return 'Outlook not so good'\r\n    elif answerNumber == 9:\r\n        return 'Very doubtful'\r\n\r\nr = random.randint(1, 9)\r\nfortune = getAnswer(r)\r\nprint(fortune)\r\n```\r\n\r\n### The None Value\r\n\r\n```python\r\n>>> spam = print('Hello!')\r\nHello!\r\n```\r\n\r\n```python\r\n>>> spam is None\r\nTrue\r\n```\r\n\r\nNote: never compare to `None` with the `==` operator. Always use `is`.\r\n\r\n### print Keyword Arguments\r\n\r\n```python\r\n>>> print('Hello', end='')\r\n>>> print('World')\r\nHelloWorld\r\n```\r\n\r\n```python\r\n>>> print('cats', 'dogs', 'mice')\r\ncats dogs mice\r\n```\r\n\r\n```python\r\n>>> print('cats', 'dogs', 'mice', sep=',')\r\ncats,dogs,mice\r\n```\r\n\r\n### Local and Global Scope\r\n\r\n- Code in the global scope cannot use any local variables.\r\n\r\n- However, a local scope can access global variables.\r\n\r\n- Code in a function’s local scope cannot use variables in any other local scope.\r\n\r\n- You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.\r\n\r\n### The global Statement\r\n\r\nIf you need to modify a global variable from within a function, use the global statement:\r\n\r\n```python\r\n>>> def spam():\r\n>>>     global eggs\r\n>>>     eggs = 'spam'\r\n>>>\r\n>>> eggs = 'global'\r\n>>> spam()\r\n>>> print(eggs)\r\nspam\r\n```\r\n\r\nThere are four rules to tell whether a variable is in a local scope or global scope:\r\n\r\n1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.\r\n\r\n1. If there is a global statement for that variable in a function, it is a global variable.\r\n\r\n1. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.\r\n\r\n1. But if the variable is not used in an assignment statement, it is a global variable.\r\n\r\n## Exception Handling\r\n\r\n### Basic exception handling\r\n\r\n```python\r\n>>> def spam(divideBy):\r\n>>>     try:\r\n>>>         return 42 / divideBy\r\n>>>     except ZeroDivisionError as e:\r\n>>>         print('Error: Invalid argument: {}'.format(e))\r\n>>>\r\n>>> print(spam(2))\r\n>>> print(spam(12))\r\n>>> print(spam(0))\r\n>>> print(spam(1))\r\n21.0\r\n3.5\r\nError: Invalid argument: division by zero\r\nNone\r\n42.0\r\n```\r\n\r\n### Final code in exception handling\r\n\r\nCode inside the `finally` section is always executed, no matter if an exception has been raised or\r\nnot, and even if an exception is not caught.\r\n\r\n```python\r\n>>> def spam(divideBy):\r\n>>>     try:\r\n>>>         return 42 / divideBy\r\n>>>     except ZeroDivisionError as e:\r\n>>>         print('Error: Invalid argument: {}'.format(e))\r\n>>>     finally:\r\n>>>         print(\"-- division finished --\")\r\n>>> print(spam(12))\r\n>>> print(spam(0))\r\n21.0\r\n-- division finished --\r\n3.5\r\n-- division finished --\r\nError: Invalid argument: division by zero\r\n-- division finished --\r\nNone\r\n-- division finished --\r\n42.0\r\n-- division finished --\r\n```\r\n\r\n## Lists\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n\r\n>>> spam\r\n['cat', 'bat', 'rat', 'elephant']\r\n```\r\n\r\n### Getting Individual Values in a List with Indexes\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[0]\r\n'cat'\r\n```\r\n\r\n```python\r\n>>> spam[1]\r\n'bat'\r\n```\r\n\r\n```python\r\n>>> spam[2]\r\n'rat'\r\n```\r\n\r\n```python\r\n>>> spam[3]\r\n'elephant'\r\n```\r\n\r\n### Negative Indexes\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[-1]\r\n'elephant'\r\n```\r\n\r\n```python\r\n>>> spam[-3]\r\n'bat'\r\n```\r\n\r\n```python\r\n>>> 'The {} is afraid of the {}.'.format(spam[-1], spam[-3])\r\n'The elephant is afraid of the bat.'\r\n```\r\n\r\n### Getting Sublists with Slices\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[0:4]\r\n['cat', 'bat', 'rat', 'elephant']\r\n```\r\n\r\n```python\r\n>>> spam[1:3]\r\n['bat', 'rat']\r\n```\r\n\r\n```python\r\n>>> spam[0:-1]\r\n['cat', 'bat', 'rat']\r\n```\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[:2]\r\n['cat', 'bat']\r\n```\r\n\r\n```python\r\n>>> spam[1:]\r\n['bat', 'rat', 'elephant']\r\n```\r\n\r\n```python\r\n>>> spam[:]\r\n['cat', 'bat', 'rat', 'elephant']\r\n```\r\n\r\n### Getting a list Length with len\r\n\r\n```python\r\n>>> spam = ['cat', 'dog', 'moose']\r\n>>> len(spam)\r\n3\r\n```\r\n\r\n### Changing Values in a List with Indexes\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> spam[1] = 'aardvark'\r\n\r\n>>> spam\r\n['cat', 'aardvark', 'rat', 'elephant']\r\n\r\n>>> spam[2] = spam[1]\r\n\r\n>>> spam\r\n['cat', 'aardvark', 'aardvark', 'elephant']\r\n\r\n>>> spam[-1] = 12345\r\n\r\n>>> spam\r\n['cat', 'aardvark', 'aardvark', 12345]\r\n```\r\n\r\n### List Concatenation and List Replication\r\n\r\n```python\r\n>>> [1, 2, 3] + ['A', 'B', 'C']\r\n[1, 2, 3, 'A', 'B', 'C']\r\n\r\n>>> ['X', 'Y', 'Z'] * 3\r\n['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']\r\n\r\n>>> spam = [1, 2, 3]\r\n\r\n>>> spam = spam + ['A', 'B', 'C']\r\n\r\n>>> spam\r\n[1, 2, 3, 'A', 'B', 'C']\r\n```\r\n\r\n### Removing Values from Lists with del Statements\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n>>> del spam[2]\r\n>>> spam\r\n['cat', 'bat', 'elephant']\r\n```\r\n\r\n```python\r\n>>> del spam[2]\r\n>>> spam\r\n['cat', 'bat']\r\n```\r\n\r\n### Using for Loops with Lists\r\n\r\n```python\r\n>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']\r\n>>> for i, supply in enumerate(supplies):\r\n>>>     print('Index {} in supplies is: {}'.format(str(i), supply))\r\nIndex 0 in supplies is: pens\r\nIndex 1 in supplies is: staplers\r\nIndex 2 in supplies is: flame-throwers\r\nIndex 3 in supplies is: binders\r\n```\r\n\r\n### Looping Through Multiple Lists with zip\r\n\r\n```python\r\n>>> name = ['Pete', 'John', 'Elizabeth']\r\n>>> age = [6, 23, 44]\r\n>>> for n, a in zip(name, age):\r\n>>>     print('{} is {} years old'.format(n, a))\r\nPete is 6 years old\r\nJohn is 23 years old\r\nElizabeth is 44 years old\r\n```\r\n\r\n### The in and not in Operators\r\n\r\n```python\r\n>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']\r\nTrue\r\n```\r\n\r\n```python\r\n>>> spam = ['hello', 'hi', 'howdy', 'heyas']\r\n>>> 'cat' in spam\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'howdy' not in spam\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'cat' not in spam\r\nTrue\r\n```\r\n\r\n### The Multiple Assignment Trick\r\n\r\nThe multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:\r\n\r\n```python\r\n>>> cat = ['fat', 'orange', 'loud']\r\n\r\n>>> size = cat[0]\r\n\r\n>>> color = cat[1]\r\n\r\n>>> disposition = cat[2]\r\n```\r\n\r\nYou could type this line of code:\r\n\r\n```python\r\n>>> cat = ['fat', 'orange', 'loud']\r\n\r\n>>> size, color, disposition = cat\r\n```\r\n\r\nThe multiple assignment trick can also be used to swap the values in two variables:\r\n\r\n```python\r\n>>> a, b = 'Alice', 'Bob'\r\n>>> a, b = b, a\r\n>>> print(a)\r\n'Bob'\r\n```\r\n\r\n```python\r\n>>> print(b)\r\n'Alice'\r\n```\r\n\r\n### Augmented Assignment Operators\r\n\r\n| Operator    | Equivalent        |\r\n| ----------- | ----------------- |\r\n| `spam += 1` | `spam = spam + 1` |\r\n| `spam -= 1` | `spam = spam - 1` |\r\n| `spam *= 1` | `spam = spam * 1` |\r\n| `spam /= 1` | `spam = spam / 1` |\r\n| `spam %= 1` | `spam = spam % 1` |\r\n\r\nExamples:\r\n\r\n```python\r\n>>> spam = 'Hello'\r\n>>> spam += ' world!'\r\n>>> spam\r\n'Hello world!'\r\n\r\n>>> bacon = ['Zophie']\r\n>>> bacon *= 3\r\n>>> bacon\r\n['Zophie', 'Zophie', 'Zophie']\r\n```\r\n\r\n### Finding a Value in a List with the index Method\r\n\r\n```python\r\n>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']\r\n\r\n>>> spam.index('Pooka')\r\n1\r\n```\r\n\r\n### Adding Values to Lists with append and insert\r\n\r\n**append()**:\r\n\r\n```python\r\n>>> spam = ['cat', 'dog', 'bat']\r\n\r\n>>> spam.append('moose')\r\n\r\n>>> spam\r\n['cat', 'dog', 'bat', 'moose']\r\n```\r\n\r\n**insert()**:\r\n\r\n```python\r\n>>> spam = ['cat', 'dog', 'bat']\r\n\r\n>>> spam.insert(1, 'chicken')\r\n\r\n>>> spam\r\n['cat', 'chicken', 'dog', 'bat']\r\n```\r\n\r\n### Removing Values from Lists with remove\r\n\r\n```python\r\n>>> spam = ['cat', 'bat', 'rat', 'elephant']\r\n\r\n>>> spam.remove('bat')\r\n\r\n>>> spam\r\n['cat', 'rat', 'elephant']\r\n```\r\n\r\nIf the value appears multiple times in the list, only the first instance of the value will be removed.\r\n\r\n### Sorting the Values in a List with sort\r\n\r\n```python\r\n>>> spam = [2, 5, 3.14, 1, -7]\r\n>>> spam.sort()\r\n>>> spam\r\n[-7, 1, 2, 3.14, 5]\r\n```\r\n\r\n```python\r\n>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']\r\n>>> spam.sort()\r\n>>> spam\r\n['ants', 'badgers', 'cats', 'dogs', 'elephants']\r\n```\r\n\r\nYou can also pass True for the reverse keyword argument to have sort() sort the values in reverse order:\r\n\r\n```python\r\n>>> spam.sort(reverse=True)\r\n>>> spam\r\n['elephants', 'dogs', 'cats', 'badgers', 'ants']\r\n```\r\n\r\nIf you need to sort the values in regular alphabetical order, pass str. lower for the key keyword argument in the sort() method call:\r\n\r\n```python\r\n>>> spam = ['a', 'z', 'A', 'Z']\r\n>>> spam.sort(key=str.lower)\r\n>>> spam\r\n['a', 'A', 'z', 'Z']\r\n```\r\n\r\nYou can use the built-in function `sorted` to return a new list:\r\n\r\n```python\r\n>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']\r\n>>> sorted(spam)\r\n['ants', 'badgers', 'cats', 'dogs', 'elephants']\r\n```\r\n\r\n### Tuple Data Type\r\n\r\n```python\r\n>>> eggs = ('hello', 42, 0.5)\r\n>>> eggs[0]\r\n'hello'\r\n```\r\n\r\n```python\r\n>>> eggs[1:3]\r\n(42, 0.5)\r\n```\r\n\r\n```python\r\n>>> len(eggs)\r\n3\r\n```\r\n\r\nThe main way that tuples are different from lists is that tuples, like strings, are immutable.\r\n\r\n### Converting Types with the list and tuple Functions\r\n\r\n```python\r\n>>> tuple(['cat', 'dog', 5])\r\n('cat', 'dog', 5)\r\n```\r\n\r\n```python\r\n>>> list(('cat', 'dog', 5))\r\n['cat', 'dog', 5]\r\n```\r\n\r\n```python\r\n>>> list('hello')\r\n['h', 'e', 'l', 'l', 'o']\r\n```\r\n\r\n## Dictionaries and Structuring Data\r\n\r\nExample Dictionary:\r\n\r\n```python\r\nmyCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}\r\n```\r\n\r\n### The keys, values, and items Methods\r\n\r\nvalues():\r\n\r\n```python\r\n>>> spam = {'color': 'red', 'age': 42}\r\n>>> for v in spam.values():\r\n>>>     print(v)\r\nred\r\n42\r\n```\r\n\r\nkeys():\r\n\r\n```python\r\n>>> for k in spam.keys():\r\n>>>     print(k)\r\ncolor\r\nage\r\n```\r\n\r\nitems():\r\n\r\n```python\r\n>>> for i in spam.items():\r\n>>>     print(i)\r\n('color', 'red')\r\n('age', 42)\r\n```\r\n\r\nUsing the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively.\r\n\r\n```python\r\n\r\n>>> spam = {'color': 'red', 'age': 42}\r\n>>>\r\n>>> for k, v in spam.items():\r\n>>>     print('Key: {} Value: {}'.format(k, str(v)))\r\nKey: age Value: 42\r\nKey: color Value: red\r\n```\r\n\r\n### Checking if a Key or Value Exists in a Dictionary\r\n\r\n```python\r\n>>> spam = {'name': 'Zophie', 'age': 7}\r\n```\r\n\r\n```python\r\n>>> 'name' in spam.keys()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Zophie' in spam.values()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> # You can omit the call to keys() when checking for a key\r\n>>> 'color' in spam\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'color' not in spam\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'color' in spam\r\nFalse\r\n```\r\n\r\n### The get Method\r\n\r\n```python\r\n>>> picnic_items = {'apples': 5, 'cups': 2}\r\n\r\n>>> 'I am bringing {} cups.'.format(str(picnic_items.get('cups', 0)))\r\n'I am bringing 2 cups.'\r\n```\r\n\r\n```python\r\n>>> 'I am bringing {} eggs.'.format(str(picnic_items.get('eggs', 0)))\r\n'I am bringing 0 eggs.'\r\n```\r\n\r\n### The setdefault Method\r\n\r\nLet's consider this code:\r\n\r\n```python\r\nspam = {'name': 'Pooka', 'age': 5}\r\n\r\nif 'color' not in spam:\r\n    spam['color'] = 'black'\r\n```\r\n\r\nUsing `setdefault` we could make the same code more shortly:\r\n\r\n```python\r\n>>> spam = {'name': 'Pooka', 'age': 5}\r\n>>> spam.setdefault('color', 'black')\r\n'black'\r\n```\r\n\r\n```python\r\n>>> spam\r\n{'color': 'black', 'age': 5, 'name': 'Pooka'}\r\n```\r\n\r\n```python\r\n>>> spam.setdefault('color', 'white')\r\n'black'\r\n```\r\n\r\n```python\r\n>>> spam\r\n{'color': 'black', 'age': 5, 'name': 'Pooka'}\r\n```\r\n\r\n### Pretty Printing\r\n\r\n```python\r\n>>> import pprint\r\n>>>\r\n>>> message = 'It was a bright cold day in April, and the clocks were striking\r\n>>> thirteen.'\r\n>>> count = {}\r\n>>>\r\n>>> for character in message:\r\n>>>     count.setdefault(character, 0)\r\n>>>     count[character] = count[character] + 1\r\n>>>\r\n>>> pprint.pprint(count)\r\n{' ': 13,\r\n ',': 1,\r\n '.': 1,\r\n 'A': 1,\r\n 'I': 1,\r\n 'a': 4,\r\n 'b': 1,\r\n 'c': 3,\r\n 'd': 3,\r\n 'e': 5,\r\n 'g': 2,\r\n 'h': 3,\r\n 'i': 6,\r\n 'k': 2,\r\n 'l': 3,\r\n 'n': 4,\r\n 'o': 2,\r\n 'p': 1,\r\n 'r': 5,\r\n 's': 3,\r\n 't': 6,\r\n 'w': 2,\r\n 'y': 1}\r\n```\r\n\r\n### Merge two dictionaries\r\n\r\n```python\r\n# in Python 3.5+:\r\n>>> x = {'a': 1, 'b': 2}\r\n>>> y = {'b': 3, 'c': 4}\r\n>>> z = {**x, **y}\r\n>>> z\r\n{'c': 4, 'a': 1, 'b': 3}\r\n\r\n# in Python 2.7\r\n>>> z = dict(x, **y)\r\n>>> z\r\n{'c': 4, 'a': 1, 'b': 3}\r\n```\r\n\r\n## sets\r\n\r\nFrom the Python 3 [documentation](https://docs.python.org/3/tutorial/datastructures.html)\r\n\r\n> A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.\r\n\r\n### Initializing a set\r\n\r\nThere are two ways to create sets: using curly braces `{}` and the bult-in function `set()`\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s = set([1, 2, 3])\r\n```\r\n\r\nWhen creating an empty set, be sure to not use the curly braces `{}`  or you will get an empty dictionary instead.\r\n\r\n```python\r\n>>> s = {}\r\n>>> type(s)\r\n<class 'dict'>\r\n```\r\n\r\n### sets: unordered collections of unique elements\r\n\r\nA set automatically remove all the duplicate values.\r\n\r\n```python\r\n>>> s = {1, 2, 3, 2, 3, 4}\r\n>>> s\r\n{1, 2, 3, 4}\r\n```\r\n\r\nAnd as an unordered data type, they can't be indexed.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s(0)\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\nTypeError: 'set' object does not support indexing\r\n>>>\r\n```\r\n\r\n### set add and update\r\n\r\nUsing the `add()` method we can add a single element to the set.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.add(4)\r\n>>> s\r\n{1, 2, 3, 4}\r\n```\r\n\r\nAnd with `update()`, multiple ones .\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.update([2, 3, 4, 5, 6])\r\n>>> s\r\n{1, 2, 3, 4, 5, 6}  # remember, sets automatically remove duplicates\r\n```\r\n\r\n### set remove and discard\r\n\r\nBoth methods will remove an element from the set, but `remove()` will raise a `key error` if the value doesn't exist.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.remove(3)\r\n>>> s\r\n{1, 2}\r\n>>> s.remove(3)\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\nKeyError: 3\r\n```\r\n\r\n`discard()` won't raise any errors.\r\n\r\n```python\r\n>>> s = {1, 2, 3}\r\n>>> s.discard(3)\r\n>>> s\r\n{1, 2}\r\n>>> s.discard(3)\r\n>>>\r\n```\r\n\r\n### set union\r\n\r\n`union()` or `|` will create a new set that contains all the elements from the sets provided.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {3, 4, 5}\r\n>>> s1.union(s2)  # or 's1 | s2'\r\n{1, 2, 3, 4, 5}\r\n```\r\n\r\n### set intersection\r\n\r\n`intersection`  or `&`  will return a set containing only the elements that are common to all of them.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {2, 3, 4}\r\n>>> s3 = {3, 4, 5}\r\n>>> s1.intersection(s2, s3)  # or 's1 & s2 & s3'\r\n{3}\r\n```\r\n\r\n### set difference\r\n\r\n`difference` or `-` will return only the elements that are in one of the sets.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {2, 3, 4}\r\n>>> s1.difference(s2)  # or 's1 - s2'\r\n{1}\r\n```\r\n\r\n### set symetric_difference\r\n\r\n`symetric_difference` or `^` will return all the elements that are not common between them.\r\n\r\n```python\r\n>>> s1 = {1, 2, 3}\r\n>>> s2 = {2, 3, 4}\r\n>>> s1.symmetric_difference(s2)  # or 's1 ^ s2'\r\n{1, 4}\r\n```\r\n\r\n## itertools Module\r\n\r\nThe *itertools* module is a collection of tools intented to be fast and use memory efficiently when handling iterators (like [lists](#lists) or [dictionaries](#dictionaries-and-structuring-data)).\r\n\r\nFrom the official [Python 3.x documentation](https://docs.python.org/3/library/itertools.html):\r\n\r\n> The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.\r\n\r\nThe *itertools* module comes in the standard library and must be imported.\r\n\r\nThe [operator](https://docs.python.org/3/library/operator.html) module will also be used. This module is not necessary when using itertools, but needed for some of the examples below.\r\n\r\n### accumulate\r\n\r\nMakes an iterator that returns the results of a function.\r\n\r\n```python\r\nitertools.accumulate(iterable[, func])\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5]\r\n>>> result = itertools.accumulate(data, operator.mul)\r\n>>> for each in result:\r\n>>>    print(each)\r\n1\r\n2\r\n6\r\n24\r\n120\r\n```\r\n\r\nThe operator.mul takes two numbers and multiplies them:\r\n\r\n```python\r\noperator.mul(1, 2)\r\n2\r\noperator.mul(2, 3)\r\n6\r\noperator.mul(6, 4)\r\n24\r\noperator.mul(24, 5)\r\n120\r\n```\r\n\r\nPassing a function is optional:\r\n\r\n```python\r\n>>> data = [5, 2, 6, 4, 5, 9, 1]\r\n>>> result = itertools.accumulate(data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n5\r\n7\r\n13\r\n17\r\n22\r\n31\r\n32\r\n```\r\n\r\nIf no function is designated the items will be summed:\r\n\r\n```python\r\n5\r\n5 + 2 = 7\r\n7 + 6 = 13\r\n13 + 4 = 17\r\n17 + 5 = 22\r\n22 + 9 = 31\r\n31 + 1 = 32\r\n```\r\n\r\n### combinations\r\n\r\nTakes an iterable and a integer. This will create all the unique combination that have r members.\r\n\r\n```python\r\nitertools.combinations(iterable, r)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> shapes = ['circle', 'triangle', 'square',]\r\n>>> result = itertools.combinations(shapes, 2)\r\n>>> for each in result:\r\n>>>    print(each)\r\n('circle', 'triangle')\r\n('circle', 'square')\r\n('triangle', 'square')\r\n```\r\n\r\n### combinations_with_replacement\r\n\r\nJust like combinations(), but allows individual elements to be repeated more than once.\r\n\r\n```python\r\nitertools.combinations_with_replacement(iterable, r)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> shapes = ['circle', 'triangle', 'square']\r\n>>> result = itertools.combinations_with_replacement(shapes, 2)\r\n>>> for each in result:\r\n>>>    print(each)\r\n('circle', 'circle')\r\n('circle', 'triangle')\r\n('circle', 'square')\r\n('triangle', 'triangle')\r\n('triangle', 'square')\r\n('square', 'square')\r\n```\r\n\r\n### count\r\n\r\nMakes an iterator that returns evenly spaced values starting with number start.\r\n\r\n```python\r\nitertools.count(start=0, step=1)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> for i in itertools.count(10,3):\r\n>>>    print(i)\r\n>>>    if i > 20:\r\n>>>        break\r\n10\r\n13\r\n16\r\n19\r\n22\r\n```\r\n\r\n### cycle\r\n\r\nThis function cycles through an iterator endlessly.\r\n\r\n```python\r\nitertools.cycle(iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']\r\n>>> for color in itertools.cycle(colors):\r\n>>>    print(color)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\nviolet\r\nred\r\norange\r\n```\r\n\r\nWhen reached the end of the iterable it start over again from the beginning.\r\n\r\n### chain\r\n\r\nTake a series of iterables and return them as one long iterable.\r\n\r\n```python\r\nitertools.chain(*iterables)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\r\n>>> shapes = ['circle', 'triangle', 'square', 'pentagon']\r\n>>> result = itertools.chain(colors, shapes)\r\n>>> for each in result:\r\n>>>    print(each)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\ncircle\r\ntriangle\r\nsquare\r\npentagon\r\n```\r\n\r\n### compress\r\n\r\nFilters one iterable with another.\r\n\r\n```python\r\nitertools.compress(data, selectors)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> shapes = ['circle', 'triangle', 'square', 'pentagon']\r\n>>> selections = [True, False, True, False]\r\n>>> result = itertools.compress(shapes, selections)\r\n>>> for each in result:\r\n>>>    print(each)\r\ncircle\r\nsquare\r\n```\r\n\r\n### dropwhile\r\n\r\nMake an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element.\r\n\r\n```python\r\nitertools.dropwhile(predicate, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\r\n>>> result = itertools.dropwhile(lambda x: x<5, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n1\r\n```\r\n\r\n### filterfalse\r\n\r\nMakes an iterator that filters elements from iterable returning only those for which the predicate is False.\r\n\r\n```python\r\nitertools.filterfalse(predicate, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\n>>> result = itertools.filterfalse(lambda x: x<5, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n```\r\n\r\n### groupby\r\n\r\nSimply put, this function groups things together.\r\n\r\n```python\r\nitertools.groupby(iterable, key=None)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> robots = [{\r\n    'name': 'blaster',\r\n    'faction': 'autobot'\r\n}, {\r\n    'name': 'galvatron',\r\n    'faction': 'decepticon'\r\n}, {\r\n    'name': 'jazz',\r\n    'faction': 'autobot'\r\n}, {\r\n    'name': 'metroplex',\r\n    'faction': 'autobot'\r\n}, {\r\n    'name': 'megatron',\r\n    'faction': 'decepticon'\r\n}, {\r\n    'name': 'starcream',\r\n    'faction': 'decepticon'\r\n}]\r\n>>> for key, group in itertools.groupby(robots, key=lambda x: x['faction']):\r\n>>>    print(key)\r\n>>>    print(list(group))\r\nautobot\r\n[{'name': 'blaster', 'faction': 'autobot'}]\r\ndecepticon\r\n[{'name': 'galvatron', 'faction': 'decepticon'}]\r\nautobot\r\n[{'name': 'jazz', 'faction': 'autobot'}, {'name': 'metroplex', 'faction': 'autobot'}]\r\ndecepticon\r\n[{'name': 'megatron', 'faction': 'decepticon'}, {'name': 'starcream', 'faction': 'decepticon'}]\r\n```\r\n\r\n### islice\r\n\r\nThis function is very much like slices. This allows you to cut out a piece of an iterable.\r\n\r\n```python\r\nitertools.islice(iterable, start, stop[, step])\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue',]\r\n>>> few_colors = itertools.islice(colors, 2)\r\n>>> for each in few_colors:\r\n>>>    print(each)\r\nred\r\norange\r\n```\r\n\r\n### permutations\r\n\r\n```python\r\nitertools.permutations(iterable, r=None)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> alpha_data = ['a', 'b', 'c']\r\n>>> result = itertools.permutations(alpha_data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n('a', 'b', 'c')\r\n('a', 'c', 'b')\r\n('b', 'a', 'c')\r\n('b', 'c', 'a')\r\n('c', 'a', 'b')\r\n('c', 'b', 'a')\r\n```\r\n\r\n### product\r\n\r\nCreates the cartesian products from a series of iterables.\r\n\r\n```python\r\n>>> num_data = [1, 2, 3]\r\n>>> alpha_data = ['a', 'b', 'c']\r\n>>> result = itertools.product(num_data, alpha_data)\r\n>>> for each in result:\r\n    print(each)\r\n(1, 'a')\r\n(1, 'b')\r\n(1, 'c')\r\n(2, 'a')\r\n(2, 'b')\r\n(2, 'c')\r\n(3, 'a')\r\n(3, 'b')\r\n(3, 'c')\r\n```\r\n\r\n### repeat\r\n\r\nThis function will repeat an object over and over again. Unless, there is a times argument.\r\n\r\n```python\r\nitertools.repeat(object[, times])\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> for i in itertools.repeat(\"spam\", 3):\r\n    print(i)\r\nspam\r\nspam\r\nspam\r\n```\r\n\r\n### starmap\r\n\r\nMakes an iterator that computes the function using arguments obtained from the iterable.\r\n\r\n```python\r\nitertools.starmap(function, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [(2, 6), (8, 4), (7, 3)]\r\n>>> result = itertools.starmap(operator.mul, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n12\r\n32\r\n21\r\n```\r\n\r\n### takewhile\r\n\r\nThe opposite of dropwhile(). Makes an iterator and returns elements from the iterable as long as the predicate is true.\r\n\r\n```python\r\nitertools.takewhile(predicate, iterable)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\r\n>>> result = itertools.takewhile(lambda x: x<5, data)\r\n>>> for each in result:\r\n>>>    print(each)\r\n1\r\n2\r\n3\r\n4\r\n```\r\n\r\n### tee\r\n\r\nReturn n independent iterators from a single iterable.\r\n\r\n```python\r\nitertools.tee(iterable, n=2)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\r\n>>> alpha_colors, beta_colors = itertools.tee(colors)\r\n>>> for each in alpha_colors:\r\n>>>    print(each)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\n```\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\r\n>>> alpha_colors, beta_colors = itertools.tee(colors)\r\n>>> for each in beta_colors:\r\n>>>    print(each)\r\nred\r\norange\r\nyellow\r\ngreen\r\nblue\r\n```\r\n\r\n### zip_longest\r\n\r\nMakes an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.\r\n\r\n```python\r\nitertools.zip_longest(*iterables, fillvalue=None)\r\n```\r\n\r\nExample:\r\n\r\n```python\r\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue',]\r\n>>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,]\r\n>>> for each in itertools.zip_longest(colors, data, fillvalue=None):\r\n>>>    print(each)\r\n('red', 1)\r\n('orange', 2)\r\n('yellow', 3)\r\n('green', 4)\r\n('blue', 5)\r\n(None, 6)\r\n(None, 7)\r\n(None, 8)\r\n(None, 9)\r\n(None, 10)\r\n```\r\n\r\n## Comprehensions\r\n\r\n### List comprehension\r\n\r\n```python\r\n>>> a = [1, 3, 5, 7, 9, 11]\r\n\r\n>>> [i - 1 for i in a]\r\n[0, 2, 4, 6, 8, 10]\r\n```\r\n\r\n### Set comprehension\r\n\r\n```python\r\n>>> b = {\"abc\", \"def\"}\r\n>>> {s.upper() for s in b}\r\n{\"ABC\", \"DEF}\r\n```\r\n\r\n### Dict comprehension\r\n\r\n```python\r\n>>> c = {'name': 'Pooka', 'age': 5}\r\n>>> {v, k for k, v in c.items()}\r\n{'Pooka': 'name', 5: 'age'}\r\n```\r\n\r\nA List comprehension can be generated from a dictionary:\r\n\r\n```python\r\n>>> c = {'name': 'Pooka', 'first_name': 'Oooka'}\r\n>>> [\"{}:{}\".format(k.upper(), v.upper()) for k, v in c.items()]\r\n['NAME:POOKA', 'FIRST_NAME:OOOKA']\r\n```\r\n\r\n## Manipulating Strings\r\n\r\n### Escape Characters\r\n\r\n| Escape character | Prints as            |\r\n| ---------------- | -------------------- |\r\n| `\\'`             | Single quote         |\r\n| `\\\"`             | Double quote         |\r\n| `\\t`             | Tab                  |\r\n| `\\n`             | Newline (line break) |\r\n| `\\\\`             | Backslash            |\r\n\r\nExample:\r\n\r\n```python\r\n>>> print(\"Hello there!\\nHow are you?\\nI\\'m doing fine.\")\r\nHello there!\r\nHow are you?\r\nI'm doing fine.\r\n```\r\n\r\n### Raw Strings\r\n\r\nA raw string completely ignores all escape characters and prints any backslash that appears in the string.\r\n\r\n```python\r\n>>> print(r'That is Carol\\'s cat.')\r\nThat is Carol\\'s cat.\r\n```\r\n\r\nNote: mostly used for regular expression definition (see `re` package)\r\n\r\n### Multiline Strings with Triple Quotes\r\n\r\n```python\r\n>>> print('''Dear Alice,\r\n>>>\r\n>>> Eve's cat has been arrested for catnapping, cat burglary, and extortion.\r\n>>>\r\n>>> Sincerely,\r\n>>> Bob''')\r\nDear Alice,\r\n\r\nEve's cat has been arrested for catnapping, cat burglary, and extortion.\r\n\r\nSincerely,\r\nBob\r\n```\r\n\r\nTo keep a nicer flow in your code, you can use the `dedent` function from the `textwrap` standard package.\r\n\r\n```python\r\n>>> from textwrap import dedent\r\n>>>\r\n>>> def my_function():\r\n>>>     print('''\r\n>>>         Dear Alice,\r\n>>>\r\n>>>         Eve's cat has been arrested for catnapping, cat burglary, and extortion.\r\n>>>\r\n>>>         Sincerely,\r\n>>>         Bob\r\n>>>         ''').strip()\r\n```\r\n\r\nThis generates the same string than before.\r\n\r\n### Indexing and Slicing Strings\r\n\r\n    H   e   l   l   o       w   o   r   l   d    !\r\n    0   1   2   3   4   5   6   7   8   9   10   11\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n\r\n>>> spam[0]\r\n'H'\r\n```\r\n\r\n```python\r\n>>> spam[4]\r\n'o'\r\n```\r\n\r\n```python\r\n>>> spam[-1]\r\n'!'\r\n```\r\n\r\nSlicing:\r\n\r\n```python\r\n\r\n>>> spam[0:5]\r\n'Hello'\r\n```\r\n\r\n```python\r\n>>> spam[:5]\r\n'Hello'\r\n```\r\n\r\n```python\r\n>>> spam[6:]\r\n'world!'\r\n```\r\n\r\n```python\r\n>>> spam[6:-1]\r\n'world'\r\n```\r\n\r\n```python\r\n>>> spam[:-1]\r\n'Hello world'\r\n```\r\n\r\n```python\r\n>>> spam[::-1]\r\n'!dlrow olleH'\r\n```\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n>>> fizz = spam[0:5]\r\n>>> fizz\r\n'Hello'\r\n```\r\n\r\n### The in and not in Operators with Strings\r\n\r\n```python\r\n>>> 'Hello' in 'Hello World'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Hello' in 'Hello'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'HELLO' in 'Hello World'\r\nFalse\r\n```\r\n\r\n```python\r\n>>> '' in 'spam'\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'cats' not in 'cats and dogs'\r\nFalse\r\n```\r\n\r\n### The in and not in Operators with list\r\n\r\n```python\r\n>>> a = [1, 2, 3, 4]\r\n>>> 5 in a\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 2 in a\r\nTrue\r\n```\r\n\r\n### The upper, lower, isupper, and islower String Methods\r\n\r\n`upper()` and `lower()`:\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n>>> spam = spam.upper()\r\n>>> spam\r\n'HELLO WORLD!'\r\n```\r\n\r\n```python\r\n>>> spam = spam.lower()\r\n>>> spam\r\n'hello world!'\r\n```\r\n\r\nisupper() and islower():\r\n\r\n```python\r\n>>> spam = 'Hello world!'\r\n>>> spam.islower()\r\nFalse\r\n```\r\n\r\n```python\r\n>>> spam.isupper()\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'HELLO'.isupper()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'abc12345'.islower()\r\nTrue\r\n```\r\n\r\n```python\r\n>>> '12345'.islower()\r\nFalse\r\n```\r\n\r\n```python\r\n>>> '12345'.isupper()\r\nFalse\r\n```\r\n\r\n### The isX String Methods\r\n\r\n- **isalpha()** returns True if the string consists only of letters and is not blank.\r\n- **isalnum()** returns True if the string consists only of lettersand numbers and is not blank.\r\n- **isdecimal()** returns True if the string consists only ofnumeric characters and is not blank.\r\n- **isspace()** returns True if the string consists only of spaces,tabs, and new-lines and is not blank.\r\n- **istitle()** returns True if the string consists only of wordsthat begin with an uppercase letter followed by onlylowercase letters.\r\n\r\n### The startswith and endswith String Methods\r\n\r\n```python\r\n>>> 'Hello world!'.startswith('Hello')\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Hello world!'.endswith('world!')\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'abc123'.startswith('abcdef')\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'abc123'.endswith('12')\r\nFalse\r\n```\r\n\r\n```python\r\n>>> 'Hello world!'.startswith('Hello world!')\r\nTrue\r\n```\r\n\r\n```python\r\n>>> 'Hello world!'.endswith('Hello world!')\r\nTrue\r\n```\r\n\r\n### The join and split String Methods\r\n\r\njoin():\r\n\r\n```python\r\n>>> ', '.join(['cats', 'rats', 'bats'])\r\n'cats, rats, bats'\r\n```\r\n\r\n```python\r\n>>> ' '.join(['My', 'name', 'is', 'Simon'])\r\n'My name is Simon'\r\n```\r\n\r\n```python\r\n>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])\r\n'MyABCnameABCisABCSimon'\r\n```\r\n\r\nsplit():\r\n\r\n```python\r\n>>> 'My name is Simon'.split()\r\n['My', 'name', 'is', 'Simon']\r\n```\r\n\r\n```python\r\n>>> 'MyABCnameABCisABCSimon'.split('ABC')\r\n['My', 'name', 'is', 'Simon']\r\n```\r\n\r\n```python\r\n>>> 'My name is Simon'.split('m')\r\n['My na', 'e is Si', 'on']\r\n```\r\n\r\n### Justifying Text with rjust, ljust, and center\r\n\r\nrjust() and ljust():\r\n\r\n```python\r\n>>> 'Hello'.rjust(10)\r\n'     Hello'\r\n```\r\n\r\n```python\r\n>>> 'Hello'.rjust(20)\r\n'               Hello'\r\n```\r\n\r\n```python\r\n>>> 'Hello World'.rjust(20)\r\n'         Hello World'\r\n```\r\n\r\n```python\r\n>>> 'Hello'.ljust(10)\r\n'Hello     '\r\n```\r\n\r\nAn optional second argument to rjust() and ljust() will specify a fill character other than a space character. Enter the following into the interactive shell:\r\n\r\n```python\r\n>>> 'Hello'.rjust(20, '*')\r\n'***************Hello'\r\n```\r\n\r\n```python\r\n>>> 'Hello'.ljust(20, '-')\r\n'Hello---------------'\r\n```\r\n\r\ncenter():\r\n\r\n```python\r\n>>> 'Hello'.center(20)\r\n'       Hello       '\r\n```\r\n\r\n```python\r\n>>> 'Hello'.center(20, '=')\r\n'=======Hello========'\r\n```\r\n\r\n### Removing Whitespace with strip, rstrip, and lstrip\r\n\r\n```python\r\n>>> spam = '    Hello World     '\r\n>>> spam.strip()\r\n'Hello World'\r\n```\r\n\r\n```python\r\n>>> spam.lstrip()\r\n'Hello World '\r\n```\r\n\r\n```python\r\n>>> spam.rstrip()\r\n'    Hello World'\r\n```\r\n\r\n```python\r\n>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'\r\n>>> spam.strip('ampS')\r\n'BaconSpamEggs'\r\n```\r\n\r\n### Copying and Pasting Strings with the pyperclip Module\r\n\r\nFirst, install `pypeerclip` with pip:\r\n\r\n```shell\r\npip install pyperclip\r\n```\r\n\r\n```python\r\n>>> import pyperclip\r\n\r\n>>> pyperclip.copy('Hello world!')\r\n\r\n>>> pyperclip.paste()\r\n'Hello world!'\r\n```\r\n\r\n## String Formatting\r\n\r\n### % operator\r\n\r\n```python\r\n>>> name = 'Pete'\r\n>>> 'Hello %s' % name\r\n\"Hello Pete\"\r\n```\r\n\r\nWe can use the `%x` format specifier to convert an int value to a string:\r\n\r\n```python\r\n>>> num = 5\r\n>>> 'I have %x apples' % num\r\n\"I have 5 apples\"\r\n```\r\n\r\nNote: For new code, using str.format or f-strings is strongly recommended over the `%` operator.\r\n\r\n### str.format\r\n\r\nPython 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.\r\n\r\n```python\r\n>>> name = 'John'\r\n>>> age = 20'\r\n\r\n>>> \"Hello I'm {}, my age is {}\".format(name, age)\r\n\"Hello I'm John, my age is 20\"\r\n```\r\n\r\n```python\r\n>>> \"Hello I'm {0}, my age is {1}\".format(name, age)\r\n\"Hello I'm John, my age is 20\"\r\n```\r\n\r\nThe official [Python 3.x documentation](https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting) recommend `str.format` over the `%` operator:\r\n\r\n> The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.\r\n\r\n### Lazy string formatting\r\n\r\nYou would only use `%s` string formatting on functions that can do lazy parameters evaluation,\r\nthe most common being logging:\r\n\r\nPrefer:\r\n\r\n```python\r\n>>> name = \"alice\"\r\n>>> logging.debug(\"User name: %s\", name)\r\n```\r\n\r\nOver:\r\n\r\n```python\r\n>>> logging.debug(\"User name: {}\".format(name))\r\n```\r\n\r\nOr:\r\n\r\n```python\r\n>>> logging.debug(\"User name: \" + name)\r\n```\r\n\r\n### Formatted String Literals or f-strings\r\n\r\nPython 3.6+\r\n\r\n```python\r\n>>> name = 'Elizabeth'\r\n>>> f'Hello {name}!'\r\n'Hello Elizabeth!\r\n```\r\n\r\nIt is even possible to do inline arithmetic with it:\r\n\r\n```python\r\n>>> a = 5\r\n>>> b = 10\r\n>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'\r\n'Five plus ten is 15 and not 30.'\r\n```\r\n\r\n### Template Strings\r\n\r\n A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.\r\n\r\n```python\r\n>>> from string import Template\r\n>>> name = 'Elizabeth'\r\n>>> t = Template('Hey $name!')\r\n>>> t.substitute(name=name)\r\n'Hey Elizabeth!'\r\n```\r\n\r\n## Regular Expressions\r\n\r\n1. Import the regex module with `import re`.\r\n2. Create a Regex object with the `re.compile()` function. (Remember to use a raw string.)\r\n3. Pass the string you want to search into the Regex object’s `search()` method. This returns a `Match` object.\r\n4. Call the Match object’s `group()` method to return a string of the actual matched text.\r\n\r\nAll the regex functions in Python are in the re module:\r\n\r\n```python\r\n>>> import re\r\n```\r\n\r\n### Matching Regex Objects\r\n\r\n```python\r\n>>> phone_num_regex = re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\r\n\r\n>>> mo = phone_num_regex.search('My number is 415-555-4242.')\r\n\r\n>>> print('Phone number found: {}'.format(mo.group()))\r\nPhone number found: 415-555-4242\r\n```\r\n\r\n### Grouping with Parentheses\r\n\r\n```python\r\n>>> phone_num_regex = re.compile(r'(\\d\\d\\d)-(\\d\\d\\d-\\d\\d\\d\\d)')\r\n\r\n>>> mo = phone_num_regex.search('My number is 415-555-4242.')\r\n\r\n>>> mo.group(1)\r\n'415'\r\n\r\n>>> mo.group(2)\r\n'555-4242'\r\n\r\n>>> mo.group(0)\r\n'415-555-4242'\r\n\r\n>>> mo.group()\r\n'415-555-4242'\r\n```\r\n\r\nTo retrieve all the groups at once: use the groups() method—note the plural form for the name.\r\n\r\n```python\r\n>>> mo.groups()\r\n('415', '555-4242')\r\n\r\n>>> area_code, main_number = mo.groups()\r\n\r\n>>> print(area_code)\r\n415\r\n\r\n>>> print(main_number)\r\n555-4242\r\n```\r\n\r\n### Matching Multiple Groups with the Pipe\r\n\r\nThe | character is called a pipe. You can use it anywhere you want to match one of many expressions. For example, the regular expression r'Batman|Tina Fey' will match either 'Batman' or 'Tina Fey'.\r\n\r\n```python\r\n>>> hero_regex = re.compile (r'Batman|Tina Fey')\r\n\r\n>>> mo1 = hero_regex.search('Batman and Tina Fey.')\r\n\r\n>>> mo1.group()\r\n'Batman'\r\n\r\n>>> mo2 = hero_regex.search('Tina Fey and Batman.')\r\n\r\n>>> mo2.group()\r\n'Tina Fey'\r\n```\r\n\r\nYou can also use the pipe to match one of several patterns as part of your regex:\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(man|mobile|copter|bat)')\r\n\r\n>>> mo = bat_regex.search('Batmobile lost a wheel')\r\n\r\n>>> mo.group()\r\n'Batmobile'\r\n\r\n>>> mo.group(1)\r\n'mobile'\r\n```\r\n\r\n### Optional Matching with the Question Mark\r\n\r\nThe ? character flags the group that precedes it as an optional part of the pattern.\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(wo)?man')\r\n>>> mo1 = bat_regex.search('The Adventures of Batman')\r\n>>> mo1.group()\r\n'Batman'\r\n\r\n>>> mo2 = bat_regex.search('The Adventures of Batwoman')\r\n>>> mo2.group()\r\n'Batwoman'\r\n```\r\n\r\n### Matching Zero or More with the Star\r\n\r\nThe * (called the star or asterisk) means “match zero or more”—the group that precedes the star can occur any number of times in the text.\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(wo)*man')\r\n>>> mo1 = bat_regex.search('The Adventures of Batman')\r\n>>> mo1.group()\r\n'Batman'\r\n\r\n>>> mo2 = bat_regex.search('The Adventures of Batwoman')\r\n>>> mo2.group()\r\n'Batwoman'\r\n\r\n>>> mo3 = bat_regex.search('The Adventures of Batwowowowoman')\r\n>>> mo3.group()\r\n'Batwowowowoman'\r\n```\r\n\r\n### Matching One or More with the Plus\r\n\r\nWhile * means “match zero or more,” the + (or plus) means “match one or more”. The group preceding a plus must appear at least once. It is not optional:\r\n\r\n```python\r\n>>> bat_regex = re.compile(r'Bat(wo)+man')\r\n>>> mo1 = bat_regex.search('The Adventures of Batwoman')\r\n>>> mo1.group()\r\n'Batwoman'\r\n```\r\n\r\n```python\r\n>>> mo2 = bat_regex.search('The Adventures of Batwowowowoman')\r\n>>> mo2.group()\r\n'Batwowowowoman'\r\n```\r\n\r\n```python\r\n>>> mo3 = bat_regex.search('The Adventures of Batman')\r\n>>> mo3 is None\r\nTrue\r\n```\r\n\r\n### Matching Specific Repetitions with Curly Brackets\r\n\r\nIf you have a group that you want to repeat a specific number of times, follow the group in your regex with a number in curly brackets. For example, the regex (Ha){3} will match the string 'HaHaHa', but it will not match 'HaHa', since the latter has only two repeats of the (Ha) group.\r\n\r\nInstead of one number, you can specify a range by writing a minimum, a comma, and a maximum in between the curly brackets. For example, the regex (Ha){3,5} will match 'HaHaHa', 'HaHaHaHa', and 'HaHaHaHaHa'.\r\n\r\n```python\r\n>>> ha_regex = re.compile(r'(Ha){3}')\r\n>>> mo1 = ha_regex.search('HaHaHa')\r\n>>> mo1.group()\r\n'HaHaHa'\r\n```\r\n\r\n```python\r\n>>> mo2 = ha_regex.search('Ha')\r\n>>> mo2 is None\r\nTrue\r\n```\r\n\r\n### Greedy and Nongreedy Matching\r\n\r\nPython’s regular expressions are greedy by default, which means that in ambiguous situations they will match the longest string possible. The non-greedy version of the curly brackets, which matches the shortest string possible, has the closing curly bracket followed by a question mark.\r\n\r\n```python\r\n>>> greedy_ha_regex = re.compile(r'(Ha){3,5}')\r\n>>> mo1 = greedy_ha_regex.search('HaHaHaHaHa')\r\n>>> mo1.group()\r\n'HaHaHaHaHa'\r\n```\r\n\r\n```python\r\n>>> nongreedy_ha_regex = re.compile(r'(Ha){3,5}?')\r\n>>> mo2 = nongreedy_ha_regex.search('HaHaHaHaHa')\r\n>>> mo2.group()\r\n'HaHaHa'\r\n```\r\n\r\n### The findall Method\r\n\r\nIn addition to the search() method, Regex objects also have a findall() method. While search() will return a Match object of the first matched text in the searched string, the findall() method will return the strings of every match in the searched string.\r\n\r\n```python\r\n>>> phone_num_regex = re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d') # has no groups\r\n\r\n>>> phone_num_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')\r\n['415-555-9999', '212-555-0000']\r\n```\r\n\r\nTo summarize what the findall() method returns, remember the following:\r\n\r\n- When called on a regex with no groups, such as \\d-\\d\\d\\d-\\d\\d\\d\\d, the method findall() returns a list of ng matches, such as ['415-555-9999', '212-555-0000'].\r\n\r\n- When called on a regex that has groups, such as (\\d\\d\\d)-d\\d)-(\\d\\ d\\d\\d), the method findall() returns a list of es of strings (one string for each group), such as [('415', ', '9999'), ('212', '555', '0000')].\r\n\r\n### Making Your Own Character Classes\r\n\r\nThere are times when you want to match a set of characters but the shorthand character classes (\\d, \\w, \\s, and so on) are too broad. You can define your own character class using square brackets. For example, the character class [aeiouAEIOU] will match any vowel, both lowercase and uppercase.\r\n\r\n```python\r\n>>> vowel_regex = re.compile(r'[aeiouAEIOU]')\r\n\r\n>>> vowel_regex.findall('Robocop eats baby food. BABY FOOD.')\r\n['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']\r\n```\r\n\r\nYou can also include ranges of letters or numbers by using a hyphen. For example, the character class [a-zA-Z0-9] will match all lowercase letters, uppercase letters, and numbers.\r\n\r\nBy placing a caret character (^) just after the character class’s opening bracket, you can make a negative character class. A negative character class will match all the characters that are not in the character class. For example, enter the following into the interactive shell:\r\n\r\n```python\r\n>>> consonant_regex = re.compile(r'[^aeiouAEIOU]')\r\n\r\n>>> consonant_regex.findall('Robocop eats baby food. BABY FOOD.')\r\n['R', 'b', 'c', 'p', ' ', 't', 's', ' ', 'b', 'b', 'y', ' ', 'f', 'd', '.', '\r\n', 'B', 'B', 'Y', ' ', 'F', 'D', '.']\r\n```\r\n\r\n### The Caret and Dollar Sign Characters\r\n\r\n- You can also use the caret symbol (^) at the start of a regex to indicate that a match must occur at the beginning of the searched text.\r\n\r\n- Likewise, you can put a dollar sign ($) at the end of the regex to indicate the string must end with this regex pattern.\r\n\r\n- And you can use the ^ and $ together to indicate that the entire string must match the regex—that is, it’s not enough for a match to be made on some subset of the string.\r\n\r\nThe r'^Hello' regular expression string matches strings that begin with 'Hello':\r\n\r\n```python\r\n>>> begins_with_hello = re.compile(r'^Hello')\r\n\r\n>>> begins_with_hello.search('Hello world!')\r\n<_sre.SRE_Match object; span=(0, 5), match='Hello'>\r\n\r\n>>> begins_with_hello.search('He said hello.') is None\r\nTrue\r\n```\r\n\r\nThe r'\\d$' regular expression string matches strings that end with a numeric character from 0 to 9:\r\n\r\n```python\r\n>>> whole_string_is_num = re.compile(r'^\\d+$')\r\n\r\n>>> whole_string_is_num.search('1234567890')\r\n<_sre.SRE_Match object; span=(0, 10), match='1234567890'>\r\n\r\n>>> whole_string_is_num.search('12345xyz67890') is None\r\nTrue\r\n\r\n>>> whole_string_is_num.search('12 34567890') is None\r\nTrue\r\n```\r\n\r\n### The Wildcard Character\r\n\r\nThe . (or dot) character in a regular expression is called a wildcard and will match any character except for a newline:\r\n\r\n```python\r\n>>> at_regex = re.compile(r'.at')\r\n\r\n>>> at_regex.findall('The cat in the hat sat on the flat mat.')\r\n['cat', 'hat', 'sat', 'lat', 'mat']\r\n```\r\n\r\n### Matching Everything with Dot-Star\r\n\r\n```python\r\n>>> name_regex = re.compile(r'First Name: (.*) Last Name: (.*)')\r\n\r\n>>> mo = name_regex.search('First Name: Al Last Name: Sweigart')\r\n\r\n>>> mo.group(1)\r\n'Al'\r\n```\r\n\r\n```python\r\n>>> mo.group(2)\r\n'Sweigart'\r\n```\r\n\r\nThe dot-star uses greedy mode: It will always try to match as much text as possible. To match any and all text in a nongreedy fashion, use the dot, star, and question mark (.*?). The question mark tells Python to match in a nongreedy way:\r\n\r\n```python\r\n>>> nongreedy_regex = re.compile(r'<.*?>')\r\n>>> mo = nongreedy_regex.search('<To serve man> for dinner.>')\r\n>>> mo.group()\r\n'<To serve man>'\r\n```\r\n\r\n```python\r\n>>> greedy_regex = re.compile(r'<.*>')\r\n>>> mo = greedy_regex.search('<To serve man> for dinner.>')\r\n>>> mo.group()\r\n'<To serve man> for dinner.>'\r\n```\r\n\r\n### Matching Newlines with the Dot Character\r\n\r\nThe dot-star will match everything except a newline. By passing re.DOTALL as the second argument to re.compile(), you can make the dot character match all characters, including the newline character:\r\n\r\n```python\r\n>>> no_newline_regex = re.compile('.*')\r\n>>> no_newline_regex.search('Serve the public trust.\\nProtect the innocent.\\nUphold the law.').group()\r\n'Serve the public trust.'\r\n```\r\n\r\n```python\r\n>>> newline_regex = re.compile('.*', re.DOTALL)\r\n>>> newline_regex.search('Serve the public trust.\\nProtect the innocent.\\nUphold the law.').group()\r\n'Serve the public trust.\\nProtect the innocent.\\nUphold the law.'\r\n```\r\n\r\n### Review of Regex Symbols\r\n\r\n| Symbol                   | Matches                                                      |\r\n| ------------------------ | ------------------------------------------------------------ |\r\n| `?`                      | zero or one of the preceding group.                          |\r\n| `*`                      | zero or more of the preceding group.                         |\r\n| `+`                      | one or more of the preceding group.                          |\r\n| `{n}`                    | exactly n of the preceding group.                            |\r\n| `{n,}`                   | n or more of the preceding group.                            |\r\n| `{,m}`                   | 0 to m of the preceding group.                               |\r\n| `{n,m}`                  | at least n and at most m of the preceding p.                 |\r\n| `{n,m}?` or `*?` or `+?` | performs a nongreedy match of the preceding p.               |\r\n| `^spam`                  | means the string must begin with spam.                       |\r\n| `spam$`                  | means the string must end with spam.                         |\r\n| `.`                      | any character, except newline characters.                    |\r\n| `\\d`, `\\w`, and `\\s`     | a digit, word, or space character, resectively.              |\r\n| `\\D`, `\\W`, and `\\S`     | anything except a digit, word, or space acter, respectively. |\r\n| `[abc]`                  | any character between the brackets (such as a, b, ).         |\r\n| `[^abc]`                 | any character that isn’t between the brackets.              |\r\n\r\n### Case-Insensitive Matching\r\n\r\nTo make your regex case-insensitive, you can pass re.IGNORECASE or re.I as a second argument to re.compile():\r\n\r\n```python\r\n>>> robocop = re.compile(r'robocop', re.I)\r\n\r\n>>> robocop.search('Robocop is part man, part machine, all cop.').group()\r\n'Robocop'\r\n```\r\n\r\n```python\r\n>>> robocop.search('ROBOCOP protects the innocent.').group()\r\n'ROBOCOP'\r\n```\r\n\r\n```python\r\n>>> robocop.search('Al, why does your programming book talk about robocop so much?').group()\r\n'robocop'\r\n```\r\n\r\n### Substituting Strings with the sub() Method\r\n\r\nThe sub() method for Regex objects is passed two arguments:\r\n\r\n1. The first argument is a string to replace any matches.\r\n1. The second is the string for the regular expression.\r\n\r\nThe sub() method returns a string with the substitutions applied:\r\n\r\n```python\r\n>>> names_regex = re.compile(r'Agent \\w+')\r\n\r\n>>> names_regex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')\r\n'CENSORED gave the secret documents to CENSORED.'\r\n```\r\n\r\nAnother example:\r\n\r\n```python\r\n>>> agent_names_regex = re.compile(r'Agent (\\w)\\w*')\r\n\r\n>>> agent_names_regex.sub(r'\\1****', 'Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')\r\nA**** told C**** that E**** knew B**** was a double agent.'\r\n```\r\n\r\n### Managing Complex Regexes\r\n\r\nTo tell the re.compile() function to ignore whitespace and comments inside the regular expression string, “verbose mode” can be enabled by passing the variable re.VERBOSE as the second argument to re.compile().\r\n\r\nNow instead of a hard-to-read regular expression like this:\r\n\r\n```python\r\nphone_regex = re.compile(r'((\\d{3}|\\(\\d{3}\\))?(\\s|-|\\.)?\\d{3}(\\s|-|\\.)\\d{4}(\\s*(ext|x|ext.)\\s*\\d{2,5})?)')\r\n```\r\n\r\nyou can spread the regular expression over multiple lines with comments like this:\r\n\r\n```python\r\nphone_regex = re.compile(r'''(\r\n    (\\d{3}|\\(\\d{3}\\))?            # area code\r\n    (\\s|-|\\.)?                    # separator\r\n    \\d{3}                         # first 3 digits\r\n    (\\s|-|\\.)                     # separator\r\n    \\d{4}                         # last 4 digits\r\n    (\\s*(ext|x|ext.)\\s*\\d{2,5})?  # extension\r\n    )''', re.VERBOSE)\r\n```\r\n\r\n## Handling File and Directory Paths\r\n\r\nThere are two main modules in Python that deals with path manipulation.\r\nOne is the `os.path` module and the other is the `pathlib` module.\r\nThe `pathlib` module was added in Python 3.4, offering an object-oriented way\r\nto handle file system paths.\r\n\r\n### Backslash on Windows and Forward Slash on OS X and Linux\r\n\r\nOn Windows, paths are written using backslashes (\\) as the separator between\r\nfolder names. On Unix based operating system such as macOS, Linux, and BSDs,\r\nthe forward slash (/) is used as the path separator. Joining paths can be\r\na headache if your code needs to work on different platforms.\r\n\r\nFortunately, Python provides easy ways to handle this. We will showcase\r\nhow to deal with this with both `os.path.join` and `pathlib.Path.joinpath`\r\n\r\nUsing `os.path.join` on Windows:\r\n\r\n```python\r\n>>> import os\r\n\r\n>>> os.path.join('usr', 'bin', 'spam')\r\n'usr\\\\bin\\\\spam'\r\n```\r\n\r\nAnd using `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n\r\n>>> print(Path('usr').joinpath('bin').joinpath('spam'))\r\nusr/bin/spam\r\n```\r\n\r\n`pathlib` also provides a shortcut to joinpath using the `/` operator:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n\r\n>>> print(Path('usr') / 'bin' / 'spam')\r\nusr/bin/spam\r\n```\r\n\r\nNotice the path separator is different between Windows and Unix based operating\r\nsystem, that's why you want to use one of the above methods instead of\r\nadding strings together to join paths together.\r\n\r\nJoining paths is helpful if you need to create different file paths under\r\nthe same directory.\r\n\r\nUsing `os.path.join` on Windows:\r\n\r\n```python\r\n>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']\r\n\r\n>>> for filename in my_files:\r\n>>>     print(os.path.join('C:\\\\Users\\\\asweigart', filename))\r\nC:\\Users\\asweigart\\accounts.txt\r\nC:\\Users\\asweigart\\details.csv\r\nC:\\Users\\asweigart\\invite.docx\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']\r\n>>> home = Path.home()\r\n>>> for filename in my_files:\r\n>>>     print(home / filename)\r\n/home/asweigart/accounts.txt\r\n/home/asweigart/details.csv\r\n/home/asweigart/invite.docx\r\n```\r\n\r\n### The Current Working Directory\r\n\r\nUsing `os` on Windows:\r\n\r\n```python\r\n>>> import os\r\n\r\n>>> os.getcwd()\r\n'C:\\\\Python34'\r\n>>> os.chdir('C:\\\\Windows\\\\System32')\r\n\r\n>>> os.getcwd()\r\n'C:\\\\Windows\\\\System32'\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> from os import chdir\r\n\r\n>>> print(Path.cwd())\r\n/home/asweigart\r\n\r\n>>> chdir('/usr/lib/python3.6')\r\n>>> print(Path.cwd())\r\n/usr/lib/python3.6\r\n```\r\n\r\n### Creating New Folders\r\n\r\nUsing `os` on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> os.makedirs('C:\\\\delicious\\\\walnut\\\\waffles')\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> cwd = Path.cwd()\r\n>>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir()\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\n  File \"/usr/lib/python3.6/pathlib.py\", line 1226, in mkdir\r\n    self._accessor.mkdir(self, mode)\r\n  File \"/usr/lib/python3.6/pathlib.py\", line 387, in wrapped\r\n    return strfunc(str(pathobj), *args)\r\nFileNotFoundError: [Errno 2] No such file or directory: '/home/asweigart/delicious/walnut/waffles'\r\n```\r\n\r\nOh no, we got a nasty error! The reason is that the 'delicious' directory does\r\nnot exist, so we cannot make the 'walnut' and the 'waffles' directories under\r\nit. To fix this, do:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> cwd = Path.cwd()\r\n>>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir(parents=True)\r\n```\r\n\r\nAnd all is good :)\r\n\r\n### Absolute vs. Relative Paths\r\n\r\nThere are two ways to specify a file path.\r\n\r\n- An absolute path, which always begins with the root folder\r\n- A relative path, which is relative to the program’s current working directory\r\n\r\nThere are also the dot (.) and dot-dot (..) folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”\r\n\r\n### Handling Absolute and Relative Paths\r\n\r\nTo see if a path is an absolute path:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.isabs('/')\r\nTrue\r\n>>> os.path.isabs('..')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> Path('/').is_absolute()\r\nTrue\r\n>>> Path('..').is_absolute()\r\nFalse\r\n```\r\n\r\nYou can extract an absolute path with both `os.path` and `pathlib`\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.getcwd()\r\n'/home/asweigart'\r\n>>> os.path.abspath('..')\r\n'/home'\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\nfrom pathlib import Path\r\nprint(Path.cwd())\r\n/home/asweigart\r\nprint(Path('..').resolve())\r\n/home\r\n```\r\n\r\nYou can get a relative path from a starting path to another path.\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.relpath('/etc/passwd', '/')\r\n'etc/passwd'\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> print(Path('/etc/passwd').relative_to('/'))\r\netc/passwd\r\n```\r\n\r\n### Checking Path Validity\r\n\r\nChecking if a file/directory exists:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\nimport os\r\n>>> os.path.exists('.')\r\nTrue\r\n>>> os.path.exists('setup.py')\r\nTrue\r\n>>> os.path.exists('/etc')\r\nTrue\r\n>>> os.path.exists('nonexistentfile')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\nfrom pathlib import Path\r\n>>> Path('.').exists()\r\nTrue\r\n>>> Path('setup.py').exists()\r\nTrue\r\n>>> Path('/etc').exists()\r\nTrue\r\n>>> Path('nonexistentfile').exists()\r\nFalse\r\n```\r\n\r\nChecking if a path is a file:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.isfile('setup.py')\r\nTrue\r\n>>> os.path.isfile('/home')\r\nFalse\r\n>>> os.path.isfile('nonexistentfile')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> Path('setup.py').is_file()\r\nTrue\r\n>>> Path('/home').is_file()\r\nFalse\r\n>>> Path('nonexistentfile').is_file()\r\nFalse\r\n```\r\n\r\nChecking if a path is a directory:\r\n\r\nUsing `os.path` on \\*nix:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.isdir('/')\r\nTrue\r\n>>> os.path.isdir('setup.py')\r\nFalse\r\n>>> os.path.isdir('/spam')\r\nFalse\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> Path('/').is_dir()\r\nTrue\r\n>>> Path('setup.py').is_dir()\r\nFalse\r\n>>> Path('/spam').is_dir()\r\nFalse\r\n```\r\n\r\n### Finding File Sizes and Folder Contents\r\n\r\nGetting a file's size in bytes:\r\n\r\nUsing `os.path` on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> os.path.getsize('C:\\\\Windows\\\\System32\\\\calc.exe')\r\n776192\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> stat = Path('/bin/python3.6').stat()\r\n>>> print(stat) # stat contains some other information about the file as well\r\nos.stat_result(st_mode=33261, st_ino=141087, st_dev=2051, st_nlink=2, st_uid=0,\r\n--snip--\r\nst_gid=0, st_size=10024, st_atime=1517725562, st_mtime=1515119809, st_ctime=1517261276)\r\n>>> print(stat.st_size) # size in bytes\r\n10024\r\n```\r\n\r\nListing directory contents using `os.listdir` on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> os.listdir('C:\\\\Windows\\\\System32')\r\n['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',\r\n--snip--\r\n'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']\r\n```\r\n\r\nListing directory contents using `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> for f in Path('/usr/bin').iterdir():\r\n>>>     print(f)\r\n...\r\n/usr/bin/tiff2rgba\r\n/usr/bin/iconv\r\n/usr/bin/ldd\r\n/usr/bin/cache_restore\r\n/usr/bin/udiskie\r\n/usr/bin/unix2dos\r\n/usr/bin/t1reencode\r\n/usr/bin/epstopdf\r\n/usr/bin/idle3\r\n...\r\n```\r\n\r\nTo find the total size of all the files in this directory:\r\n\r\n**WARNING**: Directories themselves also have a size! So you might want to\r\ncheck for whether a path is a file or directory using the methods in the methods discussed in the above section!\r\n\r\nUsing `os.path.getsize()` and `os.listdir()` together on Windows:\r\n\r\n```python\r\n>>> import os\r\n>>> total_size = 0\r\n\r\n>>> for filename in os.listdir('C:\\\\Windows\\\\System32'):\r\n      total_size = total_size + os.path.getsize(os.path.join('C:\\\\Windows\\\\System32', filename))\r\n\r\n>>> print(total_size)\r\n1117846456\r\n```\r\n\r\nUsing `pathlib` on \\*nix:\r\n\r\n```python\r\n>>> from pathlib import Path\r\n>>> total_size = 0\r\n\r\n>>> for sub_path in Path('/usr/bin').iterdir():\r\n...     total_size += sub_path.stat().st_size\r\n>>>\r\n>>> print(total_size)\r\n1903178911\r\n```\r\n\r\n### Copying Files and Folders\r\n\r\nThe shutil module provides functions for copying files, as well as entire folders.\r\n\r\n```python\r\n>>> import shutil, os\r\n\r\n>>> os.chdir('C:\\\\')\r\n\r\n>>> shutil.copy('C:\\\\spam.txt', 'C:\\\\delicious')\r\n   'C:\\\\delicious\\\\spam.txt'\r\n\r\n>>> shutil.copy('eggs.txt', 'C:\\\\delicious\\\\eggs2.txt')\r\n   'C:\\\\delicious\\\\eggs2.txt'\r\n```\r\n\r\nWhile shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and every folder and file contained in it:\r\n\r\n```python\r\n>>> import shutil, os\r\n\r\n>>> os.chdir('C:\\\\')\r\n\r\n>>> shutil.copytree('C:\\\\bacon', 'C:\\\\bacon_backup')\r\n'C:\\\\bacon_backup'\r\n```\r\n\r\n### Moving and Renaming Files and Folders\r\n\r\n```python\r\n>>> import shutil\r\n>>> shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs')\r\n'C:\\\\eggs\\\\bacon.txt'\r\n```\r\n\r\nThe destination path can also specify a filename. In the following example, the source file is moved and renamed:\r\n\r\n```python\r\n>>> shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs\\\\new_bacon.txt')\r\n'C:\\\\eggs\\\\new_bacon.txt'\r\n```\r\n\r\n If there is no eggs folder, then move() will rename bacon.txt to a file named eggs.\r\n\r\n```python\r\n>>> shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs')\r\n'C:\\\\eggs'\r\n```\r\n\r\n### Permanently Deleting Files and Folders\r\n\r\n- Calling os.unlink(path) or Path.unlink() will delete the file at path.\r\n\r\n- Calling os.rmdir(path) or Path.rmdir() will delete the folder at path. This folder must be empty of any files or folders.\r\n\r\n- Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be deleted.\r\n\r\n### Safe Deletes with the send2trash Module\r\n\r\n You can install this module by running pip install send2trash from a Terminal window.\r\n\r\n```python\r\n>>> import send2trash\r\n\r\n>>> with open('bacon.txt', 'a') as bacon_file: # creates the file\r\n...     bacon_file.write('Bacon is not a vegetable.')\r\n25\r\n\r\n>>> send2trash.send2trash('bacon.txt')\r\n```\r\n\r\n### Walking a Directory Tree\r\n\r\n```python\r\n>>> import os\r\n>>>\r\n>>> for folder_name, subfolders, filenames in os.walk('C:\\\\delicious'):\r\n>>>     print('The current folder is {}'.format(folder_name))\r\n>>>\r\n>>>     for subfolder in subfolders:\r\n>>>         print('SUBFOLDER OF {}: {}'.format(folder_name, subfolder))\r\n>>>     for filename in filenames:\r\n>>>         print('FILE INSIDE {}: {}'.format(folder_name, filename))\r\n>>>\r\n>>>     print('')\r\nThe current folder is C:\\delicious\r\nSUBFOLDER OF C:\\delicious: cats\r\nSUBFOLDER OF C:\\delicious: walnut\r\nFILE INSIDE C:\\delicious: spam.txt\r\n\r\nThe current folder is C:\\delicious\\cats\r\nFILE INSIDE C:\\delicious\\cats: catnames.txt\r\nFILE INSIDE C:\\delicious\\cats: zophie.jpg\r\n\r\nThe current folder is C:\\delicious\\walnut\r\nSUBFOLDER OF C:\\delicious\\walnut: waffles\r\n\r\nThe current folder is C:\\delicious\\walnut\\waffles\r\nFILE INSIDE C:\\delicious\\walnut\\waffles: butter.txt\r\n```\r\n\r\n`pathlib` provides a lot more functionality than the ones listed above,\r\nlike getting file name, getting file extension, reading/writing a file without\r\nmanually opening it, etc. Check out the\r\n[official documentation](https://docs.python.org/3/library/pathlib.html)\r\nif you want to know more!\r\n\r\n## Reading and Writing Files\r\n\r\n### The File Reading/Writing Process\r\n\r\nTo read/write to a file in Python, you will want to use the `with`\r\nstatement, which will close the file for you after you are done.\r\n\r\n### Opening and reading files with the open function\r\n\r\n```python\r\n>>> with open('C:\\\\Users\\\\your_home_folder\\\\hello.txt') as hello_file:\r\n...     hello_content = hello_file.read()\r\n>>> hello_content\r\n'Hello World!'\r\n\r\n>>> # Alternatively, you can use the *readlines()* method to get a list of string values from the file, one string for each line of text:\r\n\r\n>>> with open('sonnet29.txt') as sonnet_file:\r\n...     sonnet_file.readlines()\r\n[When, in disgrace with fortune and men's eyes,\\n', ' I all alone beweep my\r\noutcast state,\\n', And trouble deaf heaven with my bootless cries,\\n', And\r\nlook upon myself and curse my fate,']\r\n\r\n>>> # You can also iterate through the file line by line:\r\n>>> with open('sonnet29.txt') as sonnet_file:\r\n...     for line in sonnet_file: # note the new line character will be included in the line\r\n...         print(line, end='')\r\n\r\nWhen, in disgrace with fortune and men's eyes,\r\nI all alone beweep my outcast state,\r\nAnd trouble deaf heaven with my bootless cries,\r\nAnd look upon myself and curse my fate,\r\n```\r\n\r\n### Writing to Files\r\n\r\n```python\r\n>>> with open('bacon.txt', 'w') as bacon_file:\r\n...     bacon_file.write('Hello world!\\n')\r\n13\r\n\r\n>>> with open('bacon.txt', 'a') as bacon_file:\r\n...     bacon_file.write('Bacon is not a vegetable.')\r\n25\r\n\r\n>>> with open('bacon.txt') as bacon_file:\r\n...     content = bacon_file.read()\r\n\r\n>>> print(content)\r\nHello world!\r\nBacon is not a vegetable.\r\n```\r\n\r\n### Saving Variables with the shelve Module\r\n\r\nTo save variables:\r\n\r\n```python\r\n>>> import shelve\r\n\r\n>>> cats = ['Zophie', 'Pooka', 'Simon']\r\n>>> with shelve.open('mydata') as shelf_file:\r\n...     shelf_file['cats'] = cats\r\n```\r\n\r\nTo open and read variables:\r\n\r\n```python\r\n>>> with shelve.open('mydata') as shelf_file:\r\n...     print(type(shelf_file))\r\n...     print(shelf_file['cats'])\r\n<class 'shelve.DbfilenameShelf'>\r\n['Zophie', 'Pooka', 'Simon']\r\n```\r\n\r\nJust like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the list() function to get them in list form.\r\n\r\n```python\r\n>>> with shelve.open('mydata') as shelf_file:\r\n...     print(list(shelf_file.keys()))\r\n...     print(list(shelf_file.values()))\r\n['cats']\r\n[['Zophie', 'Pooka', 'Simon']]\r\n```\r\n\r\n### Saving Variables with pprint.pformat\r\n\r\n```python\r\n>>> import pprint\r\n\r\n>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]\r\n\r\n>>> pprint.pformat(cats)\r\n\"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]\"\r\n\r\n>>> with open('myCats.py', 'w') as file_obj:\r\n...     file_obj.write('cats = {}\\n'.format(pprint.pformat(cats)))\r\n83\r\n```\r\n\r\n### Reading ZIP Files\r\n\r\n```python\r\n>>> import zipfile, os\r\n\r\n>>> os.chdir('C:\\\\')    # move to the folder with example.zip\r\n>>> with zipfile.ZipFile('example.zip') as example_zip:\r\n...     print(example_zip.namelist())\r\n...     spam_info = example_zip.getinfo('spam.txt')\r\n...     print(spam_info.file_size)\r\n...     print(spam_info.compress_size)\r\n...     print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))\r\n\r\n['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']\r\n13908\r\n3828\r\n'Compressed file is 3.63x smaller!'\r\n```\r\n\r\n### Extracting from ZIP Files\r\n\r\nThe extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current working directory.\r\n\r\n```python\r\n>>> import zipfile, os\r\n\r\n>>> os.chdir('C:\\\\')    # move to the folder with example.zip\r\n\r\n>>> with zipfile.ZipFile('example.zip') as example_zip:\r\n...     example_zip.extractall()\r\n```\r\n\r\nThe extract() method for ZipFile objects will extract a single file from the ZIP file. Continue the interactive shell example:\r\n\r\n```python\r\n>>> with zipfile.ZipFile('example.zip') as example_zip:\r\n...     print(example_zip.extract('spam.txt'))\r\n...     print(example_zip.extract('spam.txt', 'C:\\\\some\\\\new\\\\folders'))\r\n'C:\\\\spam.txt'\r\n'C:\\\\some\\\\new\\\\folders\\\\spam.txt'\r\n```\r\n\r\n### Creating and Adding to ZIP Files\r\n\r\n```python\r\n>>> import zipfile\r\n\r\n>>> with zipfile.ZipFile('new.zip', 'w') as new_zip:\r\n...     new_zip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)\r\n```\r\n\r\nThis code will create a new ZIP file named new.zip that has the compressed contents of spam.txt.\r\n\r\n## JSON, YAML and configuration files\r\n\r\n### JSON\r\n\r\nOpen a JSON file with:\r\n\r\n```python\r\nimport json\r\nwith open(\"filename.json\", \"r\") as f:\r\n    content = json.loads(f.read())\r\n```\r\n\r\nWrite a JSON file with:\r\n\r\n```python\r\nimport json\r\n\r\ncontent = {\"name\": \"Joe\", \"age\": 20}\r\nwith open(\"filename.json\", \"w\") as f:\r\n    f.write(json.dumps(content, indent=2))\r\n```\r\n\r\n### YAML\r\n\r\nCompared to JSON, YAML allows a much better humain maintainance and gives ability to add comments.\r\nIt is a convinient choice for configuration files where human will have to edit.\r\n\r\nThere are two main librairies allowing to access to YAML files:\r\n\r\n- [PyYaml](https://pypi.python.org/pypi/PyYAML)\r\n- [Ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml)\r\n\r\nInstall them using `pip install` in your virtual environment.\r\n\r\nThe first one it easier to use but the second one, Ruamel, implements much better the YAML\r\nspecification, and allow for example to modify a YAML content without altering comments.\r\n\r\nOpen a YAML file with:\r\n\r\n```python\r\nfrom ruamel.yaml import YAML\r\n\r\nwith open(\"filename.yaml\") as f:\r\n    yaml=YAML()\r\n    yaml.load(f)\r\n```\r\n\r\n### Anyconfig\r\n\r\n[Anyconfig](https://pypi.python.org/pypi/anyconfig) is a very handy package allowing to abstract completly the underlying configuration file format. It allows to load a Python dictionary from JSON, YAML, TOML, and so on.\r\n\r\nInstall it with:\r\n\r\n```bash\r\npip install anyconfig\r\n```\r\n\r\nUsage:\r\n\r\n```python\r\nimport anyconfig\r\n\r\nconf1 = anyconfig.load(\"/path/to/foo/conf.d/a.yml\")\r\n```\r\n\r\n## Debugging\r\n\r\n### Raising Exceptions\r\n\r\nExceptions are raised with a raise statement. In code, a raise statement consists of the following:\r\n\r\n- The raise keyword\r\n- A call to the Exception() function\r\n- A string with a helpful error message passed to the Exception() function\r\n\r\n```python\r\n>>> raise Exception('This is the error message.')\r\nTraceback (most recent call last):\r\n  File \"<pyshell#191>\", line 1, in <module>\r\n    raise Exception('This is the error message.')\r\nException: This is the error message.\r\n```\r\n\r\nOften it’s the code that calls the function, not the function itself, that knows how to handle an expection. So you will commonly see a raise statement inside a function and the try and except statements in the code calling the function.\r\n\r\n```python\r\ndef box_print(symbol, width, height):\r\n    if len(symbol) != 1:\r\n      raise Exception('Symbol must be a single character string.')\r\n    if width <= 2:\r\n      raise Exception('Width must be greater than 2.')\r\n    if height <= 2:\r\n      raise Exception('Height must be greater than 2.')\r\n    print(symbol * width)\r\n    for i in range(height - 2):\r\n        print(symbol + (' ' * (width - 2)) + symbol)\r\n    print(symbol * width)\r\nfor sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):\r\n    try:\r\n        box_print(sym, w, h)\r\n    except Exception as err:\r\n        print('An exception happened: ' + str(err))\r\n```\r\n\r\n### Getting the Traceback as a String\r\n\r\nThe traceback is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function.\r\n\r\n```python\r\n>>> import traceback\r\n\r\n>>> try:\r\n>>>      raise Exception('This is the error message.')\r\n>>> except:\r\n>>>      with open('errorInfo.txt', 'w') as error_file:\r\n>>>          error_file.write(traceback.format_exc())\r\n>>>      print('The traceback info was written to errorInfo.txt.')\r\n116\r\nThe traceback info was written to errorInfo.txt.\r\n```\r\n\r\nThe 116 is the return value from the write() method, since 116 characters were written to the file. The traceback text was written to errorInfo.txt.\r\n\r\n    Traceback (most recent call last):\r\n      File \"<pyshell#28>\", line 2, in <module>\r\n    Exception: This is the error message.\r\n\r\n### Assertions\r\n\r\nAn assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity checks are performed by assert statements. If the sanity check fails, then an AssertionError exception is raised. In code, an assert statement consists of the following:\r\n\r\n- The assert keyword\r\n- A condition (that is, an expression that evaluates to True or False)\r\n- A comma\r\n- A string to display when the condition is False\r\n\r\n```python\r\n>>> pod_bay_door_status = 'open'\r\n\r\n>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\r\n\r\n>>> pod_bay_door_status = 'I\\'m sorry, Dave. I\\'m afraid I can\\'t do that.'\r\n\r\n>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\r\n\r\nTraceback (most recent call last):\r\n  File \"<pyshell#10>\", line 1, in <module>\r\n    assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\r\nAssertionError: The pod bay doors need to be \"open\".\r\n```\r\n\r\nIn plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have to check before finding the code that’s causing the bug.\r\n\r\nDisabling Assertions\r\n\r\nAssertions can be disabled by passing the -O option when running Python.\r\n\r\n### Logging\r\n\r\nTo enable the logging module to display log messages on your screen as your program runs, copy the following to the top of your program (but under the #! python shebang line):\r\n\r\n```python\r\nimport logging\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\r\n```\r\n\r\nSay you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going wrong. Save the program as factorialLog.py.\r\n\r\n```python\r\n>>> import logging\r\n>>>\r\n>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\r\n>>>\r\n>>> logging.debug('Start of program')\r\n>>>\r\n>>> def factorial(n):\r\n>>>\r\n>>>     logging.debug('Start of factorial(%s)' % (n))\r\n>>>     total = 1\r\n>>>\r\n>>>     for i in range(1, n + 1):\r\n>>>         total *= i\r\n>>>         logging.debug('i is ' + str(i) + ', total is ' + str(total))\r\n>>>\r\n>>>     logging.debug('End of factorial(%s)' % (n))\r\n>>>\r\n>>>     return total\r\n>>>\r\n>>> print(factorial(5))\r\n>>> logging.debug('End of program')\r\n2015-05-23 16:20:12,664 - DEBUG - Start of program\r\n2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)\r\n2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0\r\n2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0\r\n2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0\r\n2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0\r\n2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0\r\n2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0\r\n2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)\r\n0\r\n2015-05-23 16:20:12,684 - DEBUG - End of program\r\n```\r\n\r\n### Logging Levels\r\n\r\nLogging levels provide a way to categorize your log messages by importance. There are five logging levels, described in Table 10-1 from least to most important. Messages can be logged at each level using a different logging function.\r\n\r\n| Level      | Logging Function     | Description                                                                                                                    |\r\n| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\r\n| `DEBUG`    | `logging.debug()`    | The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems.                 |\r\n| `INFO`     | `logging.info()`     | Used to record information on general events in your program or confirm that things are working at their point in the program. |\r\n| `WARNING`  | `logging.warning()`  | Used to indicate a potential problem that doesn’t prevent the program from working but might do so in the future.             |\r\n| `ERROR`    | `logging.error()`    | Used to record an error that caused the program to fail to do something.                                                       |\r\n| `CRITICAL` | `logging.critical()` | The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely.   |\r\n\r\n### Disabling Logging\r\n\r\nAfter you’ve debugged your program, you probably don’t want all these log messages cluttering the screen. The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging calls by hand.\r\n\r\n```python\r\n>>> import logging\r\n\r\n>>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')\r\n\r\n>>> logging.critical('Critical error! Critical error!')\r\n2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!\r\n\r\n>>> logging.disable(logging.CRITICAL)\r\n\r\n>>> logging.critical('Critical error! Critical error!')\r\n\r\n>>> logging.error('Error! Error!')\r\n```\r\n\r\n### Logging to a File\r\n\r\nInstead of displaying the log messages to the screen, you can write them to a text file. The logging.basicConfig() function takes a filename keyword argument, like so:\r\n\r\n```python\r\nimport logging\r\n\r\nlogging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\r\n```\r\n\r\n## Lambda Functions\r\n\r\nThis function:\r\n\r\n```python\r\n>>> def add(x, y):\r\n        return x + y\r\n\r\n>>> add(5, 3)\r\n8\r\n```\r\n\r\nIs equivalent to the *lambda* function:\r\n\r\n```python\r\n>>> add = lambda x, y: x + y\r\n>>> add(5, 3)\r\n8\r\n```\r\n\r\nIt's not even need to bind it to a name like add before:\r\n\r\n```python\r\n>>> (lambda x, y: x + y)(5, 3)\r\n8\r\n```\r\n\r\nLike regular nested functions, lambdas also work as lexical closures:\r\n\r\n```python\r\n>>> def make_adder(n):\r\n        return lambda x: x + n\r\n\r\n>>> plus_3 = make_adder(3)\r\n>>> plus_5 = make_adder(5)\r\n\r\n>>> plus_3(4)\r\n7\r\n>>> plus_5(4)\r\n9\r\n```\r\n\r\nNote: lambda can only evaluate an expression, like a single line of code.\r\n\r\n## Ternary Conditional Operator\r\n\r\nMany programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, otherwise it evaluates the second expression.\r\n\r\n    <expression1> if <condition> else <expression2>\r\n\r\nExample:\r\n\r\n```python\r\n>>> age = 15\r\n\r\n>>> print('kid' if age < 18 else 'adult')\r\nkid\r\n```\r\n\r\nTernary operators can be changed:\r\n\r\n```python\r\n>>> age = 15\r\n\r\n>>> print('kid' if age < 13 else 'teenager' if age < 18 else 'adult')\r\nteenager\r\n```\r\n\r\nThe code above is equivalent to:\r\n\r\n```python\r\nif age < 18:\r\n    if age < 12:\r\n        print('kid')\r\n    else:\r\n        print('teenager')\r\nelse:\r\n    print('adult')\r\n```\r\n\r\n## args and kwargs\r\n\r\nThe names ```args and kwargs``` are arbitrary - the important thing are the ```*``` and ```**``` operators. They can mean:\r\n\r\n1. In a function declaration, ```*``` means “pack all remaining positional arguments into a tuple named `<name>`”, while ```**``` is the same for keyword arguments (except it uses a dictionary, not a tuple).\r\n\r\n2. In a function call, ```*``` means “unpack tuple or list named `<name>` to positional arguments at this position”, while ```**``` is the same for keyword arguments.\r\n\r\nFor example you can make a function that you can use to call any other function, no matter what parameters it has:\r\n\r\n```python\r\ndef forward(f, *args, **kwargs):\r\n    return f(*args, **kwargs)\r\n```\r\n\r\nInside forward, args is a tuple (of all positional arguments except the first one, because we specified it - the f), kwargs is a dict. Then we call f and unpack them so they become normal arguments to f.\r\n\r\nYou use ```*args``` when you have an indefinite amount of positional arguments.\r\n\r\n```python\r\n>>> def fruits(*args):\r\n>>>    for fruit in args:\r\n>>>       print(fruit)\r\n\r\n>>> fruits(\"apples\", \"bananas\", \"grapes\")\r\n\r\n\"apples\"\r\n\"bananas\"\r\n\"grapes\"\r\n```\r\n\r\nSimilarly, you use ```**kwargs``` when you have an indefinite number of keyword arguments.\r\n\r\n```python\r\n>>> def fruit(**kwargs):\r\n>>>    for key, value in kwargs.items():\r\n>>>        print(\"{0}: {1}\".format(key, value))\r\n\r\n>>> fruit(name = \"apple\", color = \"red\")\r\n\r\nname: apple\r\ncolor: red\r\n```\r\n\r\n```python\r\n>>> def show(arg1, arg2, *args, kwarg1=None, kwarg2=None, **kwargs):\r\n>>>   print(arg1)\r\n>>>   print(arg2)\r\n>>>   print(args)\r\n>>>   print(kwarg1)\r\n>>>   print(kwarg2)\r\n>>>   print(kwargs)\r\n\r\n>>> data1 = [1,2,3]\r\n>>> data2 = [4,5,6]\r\n>>> data3 = {'a':7,'b':8,'c':9}\r\n\r\n>>> show(*data1,*data2, kwarg1=\"python\",kwarg2=\"cheatsheet\",**data3)\r\n1\r\n2\r\n(3, 4, 5, 6)\r\npython\r\ncheatsheet\r\n{'a': 7, 'b': 8, 'c': 9}\r\n\r\n>>> show(*data1, *data2, **data3)\r\n1\r\n2\r\n(3, 4, 5, 6)\r\nNone\r\nNone\r\n{'a': 7, 'b': 8, 'c': 9}\r\n\r\n# If you do not specify ** for kwargs\r\n>>> show(*data1, *data2, *data3)\r\n1\r\n2\r\n(3, 4, 5, 6, \"a\", \"b\", \"c\")\r\nNone\r\nNone\r\n{}\r\n```\r\n\r\n### Thinks to Remember(args)\r\n\r\n1. Functions can accept a variable number of positional arguments by using ```*args``` in the def statement.\r\n2. You can use the items from a sequence as the positional arguments for a function with the ```*``` operator.\r\n3. Using the ```*``` operator with a generator may cause your program to run out of memory and crash.\r\n4. Adding new positional parameters to functions that accept ```*args``` can introduce hard-to-find bugs.\r\n\r\n### Thinks to remember(kwargs)\r\n\r\n1. Function arguments can be specified by position or by keyword.\r\n2. Keywords make it clear what the purpose of each argument is when it would be confusing with only positional arguments.\r\n3. Keyword arguments with default values make it easy to add new behaviors to a function, especially when the function has existing callers.\r\n4. Optional keyword arguments should always be passed by keyword instead of by position.\r\n\r\n## Context Manager\r\n\r\nWhile Python's context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes.\r\n\r\n### with statement\r\n\r\nA context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the with statement. It takes care of the notifying.\r\n\r\nFor example, file objects are context managers. When a context ends, the file object is closed automatically:\r\n\r\n```python\r\n>>> with open(filename) as f:\r\n>>>     file_contents = f.read()\r\n\r\n# the open_file object has automatically been closed.\r\n```\r\n\r\nAnything that ends execution of the block causes the context manager's exit method to be called. This includes exceptions, and can be useful when an error causes you to prematurely exit from an open file or connection. Exiting a script without properly closing files/connections is a bad idea, that may cause data loss or other problems. By using a context manager you can ensure that precautions are always taken to prevent damage or loss in this way.\r\n\r\n### Writing your own contextmanager using generator syntax\r\n\r\nIt is also possible to write a context manager using generator syntax thanks to the ```contextlib.contextmanager``` decorator:\r\n\r\n```python\r\n>>> import contextlib\r\n>>> @contextlib.contextmanager\r\n... def context_manager(num):\r\n...     print('Enter')\r\n...     yield num + 1\r\n...     print('Exit')\r\n>>> with context_manager(2) as cm:\r\n...     # the following instructions are run when the 'yield' point of the context\r\n...     # manager is reached.\r\n...     # 'cm' will have the value that was yielded\r\n...     print('Right in the middle with cm = {}'.format(cm))\r\n\r\nEnter\r\nRight in the middle with cm = 3\r\nExit\r\n>>>\r\n```\r\n\r\n## `__main__` Top-level script environment\r\n\r\n`__main__` is the name of the scope in which top-level code executes.\r\nA module’s __name__ is set equal to `__main__` when read from standard input, a script, or from an interactive prompt.\r\n\r\nA module can discover whether or not it is running in the main scope by checking its own `__name__`, which allows a common idiom for conditionally executing code in a module when it is run as a script or with `python -m` but not when it is imported:\r\n\r\n```python\r\n>>> if __name__ == \"__main__\":\r\n...     # execute only if run as a script\r\n...     main()\r\n```\r\n\r\nFor a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.\r\n\r\nFor example we are developing script which is designed to be used as module, we should do:\r\n\r\n```python\r\n>>> # Python program to execute function directly\r\n>>> def add(a, b):\r\n...     return a+b\r\n...\r\n>>> add(10, 20) # we can test it by calling the function save it as calculate.py\r\n30\r\n>>> # Now if we want to use that module by importing we have to comment out our call,\r\n>>> # Instead we can write like this in calculate.py\r\n>>> if __name__ == \"__main__\":\r\n...     add(3, 5)\r\n...\r\n>>> import calculate\r\n>>> calculate.add(3, 5)\r\n8\r\n```\r\n\r\n### Advantages\r\n\r\n1. Every Python module has it’s `__name__` defined and if this is `__main__`, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.\r\n2. If you import this script as a module in another script, the __name__ is set to the name of the script/module.\r\n3. Python files can act as either reusable modules, or as standalone programs.\r\n4. if `__name__ == “main”:` is used to execute some code only if the file was run directly, and not imported.\r\n\r\n## setup.py\r\n\r\nThe setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing.\r\n\r\nThe `setup.py` file is at the heart of a Python project. It describes all of the metadata about your project. There a quite a few fields you can add to a project to give it a rich set of metadata describing the project. However, there are only three required fields: name, version, and packages. The name field must be unique if you wish to publish your package on the Python Package Index (PyPI). The version field keeps track of different releases of the project. The packages field describes where you’ve put the Python source code within your project.\r\n\r\nThis allows you to easily install Python packages. Often it's enough to write:\r\n\r\n```bash\r\npython setup.py install\r\n```\r\n\r\nand module will install itself.\r\n\r\nOur initial setup.py will also include information about the license and will re-use the README.txt file for the long_description field. This will look like:\r\n\r\n```python\r\n>>> from distutils.core import setup\r\n>>> setup(\r\n...    name='pythonCheatsheet',\r\n...    version='0.1',\r\n...    packages=['pipenv',],\r\n...    license='MIT',\r\n...    long_description=open('README.txt').read(),\r\n... )\r\n```\r\n\r\nFind more information visit [http://docs.python.org/install/index.html](http://docs.python.org/install/index.html).\r\n\r\n## Dataclasses\r\n\r\n`Dataclasses` are python classes but are suited for storing data objects.\r\nThis module provides a decorator and functions for automatically adding generated special methods such as `__init__()` and `__repr__()` to user-defined classes.\r\n\r\n### Features\r\n\r\n1. They store data and represent a certain data type. Ex: A number. For people familiar with ORMs, a model instance is a data object. It represents a specific kind of entity. It holds attributes that define or represent the entity.\r\n\r\n2. They can be compared to other objects of the same type. Ex: A number can be greater than, less than, or equal to another number.\r\n\r\nPython 3.7 provides a decorator dataclass that is used to convert a class into a dataclass.\r\n\r\npython 2.7\r\n\r\n```python\r\n>>> class Number:\r\n...     def __init__(self, val):\r\n...         self.val = val\r\n...\r\n>>> obj = Number(2)\r\n>>> obj.val\r\n2\r\n```\r\n\r\nwith dataclass\r\n\r\n```python\r\n>>> @dataclass\r\n... class Number:\r\n...     val: int\r\n...\r\n>>> obj = Number(2)\r\n>>> obj.val\r\n2\r\n```\r\n\r\n### Default values\r\n\r\nIt is easy to add default values to the fields of your data class.\r\n\r\n```python\r\n>>> @dataclass\r\n... class Product:\r\n...     name: str\r\n...     count: int = 0\r\n...     price: float = 0.0\r\n...\r\n>>> obj = Product(\"Python\")\r\n>>> obj.name\r\nPython\r\n>>> obj.count\r\n0\r\n>>> obj.price\r\n0.0\r\n```\r\n\r\n### Type hints\r\n\r\nIt is mandatory to define the data type in dataclass. However, If you don't want specify the datatype then, use ```typing.Any```.\r\n\r\n```python\r\n>>> from dataclasses import dataclass\r\n>>> from typing import Any\r\n\r\n>>> @dataclass\r\n... class WithoutExplicitTypes:\r\n...    name: Any\r\n...    value: Any = 42\r\n...\r\n```\r\n\r\n## Virtual Environment\r\n\r\nThe use of a Virtual Environment is to test python code in encapsulated environments and to also avoid filling the base Python installation with libraries we might use for only one project.\r\n\r\n### virtualenv\r\n\r\n1. Install virtualenv\r\n\r\n        pip install virtualenv\r\n\r\n1. Install virtualenvwrapper-win (Windows)\r\n\r\n        pip install virtualenvwrapper-win\r\n\r\nUsage:\r\n\r\n1. Make a Virtual Environment\r\n\r\n        mkvirtualenv HelloWold\r\n\r\n    Anything we install now will be specific to this project. And available to the projects we connect to this environment.\r\n\r\n1. Set Project Directory\r\n\r\n    To bind our virtualenv with our current working directory we simply enter:\r\n\r\n        setprojectdir .\r\n\r\n1. Deactivate\r\n\r\n    To move onto something else in the command line type ‘deactivate’ to deactivate your environment.\r\n\r\n        deactivate\r\n\r\n    Notice how the parenthesis disappear.\r\n\r\n1. Workon\r\n\r\n    Open up the command prompt and type ‘workon HelloWold’ to activate the environment and move into your root project folder\r\n\r\n        workon HelloWold\r\n\r\n### pipenv\r\n\r\n> [Pipenv](https://pipenv.readthedocs.io/en/latest/) is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.\r\n\r\n1. Install pipenv\r\n\r\n        pip install pipenv\r\n\r\n1. Enter your Project directory and install the Packages for your project\r\n\r\n        cd my_project\r\n        pipenv install <package>\r\n\r\n    Pipenv will install your package and create a Pipfile for you in your project’s directory. The Pipfile is used to track which dependencies your project needs in case you need to re-install them.\r\n\r\n1. Uninstall Packages\r\n\r\n        pipenv uninstall <package>\r\n\r\n1. Activate the Virtual Environment associated with your Python project\r\n\r\n        pipenv shell\r\n\r\n1. Exit the Virtual Environment\r\n\r\n        exit\r\n\r\nFind more information and a video in [docs.pipenv.org](https://docs.pipenv.org/).\r\n\r\n### anaconda\r\n\r\n[Anaconda](https://anaconda.org/) is another popular tool to manage python packages.\r\n\r\n> Where packages, notebooks, projects and environments are shared. \r\nYour place for free public conda package hosting.\r\n\r\nUsage:\r\n\r\n1. Make a Virtual Environment\r\n\r\n        conda create -n HelloWorld\r\n\r\n2. To use the Virtual Environment, activate it by:\r\n\r\n        conda activate HelloWorld\r\n\r\n    Anything installed now will be specific to the project HelloWorld\r\n\r\n3. Exit the Virtual Environment\r\n\r\n        conda deactivate\r\n"
  },
  {
    "path": "Python/pyproject.toml",
    "content": "[tool.poetry]\r\nname = \"python-cheatsheet\"\r\nversion = \"0.1.0\"\r\ndescription = \"\"\r\nauthors = [\"'Carlos <'carlos.w.montecinos@gmail.com'>\"]\r\n\r\n[tool.poetry.dependencies]\r\npython = \"*\"\r\nnotedown = \"^1.5\"\r\n\r\n[tool.poetry.dev-dependencies]\r\n"
  },
  {
    "path": "Python/python_cheat_sheet.ipynb",
    "content": "{\r\n \"cells\": [\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"# About [![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/wilfredinni/python-cheatsheet/master)\\n\",\r\n    \"\\n\",\r\n    \"Basic cheatsheet for Python mostly based on the book written by Al Sweigart, [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) under the [Creative Commons license](https://creativecommons.org/licenses/by-nc-sa/3.0/) and many other sources.\\n\",\r\n    \"\\n\",\r\n    \"## Contribute\\n\",\r\n    \"\\n\",\r\n    \"All contributions are welcome:\\n\",\r\n    \"\\n\",\r\n    \"- Read the issues, Fork the project and do a Pull Request.\\n\",\r\n    \"- Request a new topic creating a `New issue` with the  `enhancement` tag.\\n\",\r\n    \"- Find any kind of errors in the cheat sheet and create a `New issue` with the details or fork the project and do a Pull Request.\\n\",\r\n    \"- Suggest a better or more pythonic way for existing examples.\\n\",\r\n    \"\\n\",\r\n    \"## Read It\\n\",\r\n    \"\\n\",\r\n    \"- [Website](https://www.pythoncheatsheet.org)\\n\",\r\n    \"- [Github](https://github.com/wilfredinni/python-cheatsheet)\\n\",\r\n    \"- [PDF](https://github.com/wilfredinni/Python-cheatsheet/raw/master/python_cheat_sheet.pdf)\\n\",\r\n    \"- [Jupyter Notebook](https://mybinder.org/v2/gh/wilfredinni/python-cheatsheet/master?filepath=python_cheat_sheet.ipynb)\\n\",\r\n    \"\\n\",\r\n    \"## Python Cheatsheet\\n\",\r\n    \"\\n\",\r\n    \"- [The Zen of Python](#the-zen-of-python)\\n\",\r\n    \"- [Python Basics](#python-basics)\\n\",\r\n    \"    - [Math Operators](#math-operators)\\n\",\r\n    \"    - [Data Types](#data-types)\\n\",\r\n    \"    - [String Concatenation and Replication](#string-concatenation-and-replication)\\n\",\r\n    \"    - [Variables](#variables)\\n\",\r\n    \"    - [Comments](#comments)\\n\",\r\n    \"    - [The print() Function](#the-print-function)\\n\",\r\n    \"    - [The input() Function](#the-input-function)\\n\",\r\n    \"    - [The len() Function](#the-len-function)\\n\",\r\n    \"    - [The str(), int(), and float() Functions](#the-str-int-and-float-functions)\\n\",\r\n    \"- [Flow Control](#flow-control)\\n\",\r\n    \"    - [Comparison Operators](#comparison-operators)\\n\",\r\n    \"    - [Boolean evaluation](#boolean-evaluation)\\n\",\r\n    \"    - [Boolean Operators](#boolean-operators)\\n\",\r\n    \"    - [Mixing Boolean and Comparison Operators](#mixing-boolean-and-comparison-operators)\\n\",\r\n    \"    - [if Statements](#if-statements)\\n\",\r\n    \"    - [else Statements](#else-statements)\\n\",\r\n    \"    - [elif Statements](#elif-statements)\\n\",\r\n    \"    - [while Loop Statements](#while-loop-statements)\\n\",\r\n    \"    - [break Statements](#break-statements)\\n\",\r\n    \"    - [continue Statements](#continue-statements)\\n\",\r\n    \"    - [for Loops and the range() Function](#for-loops-and-the-range-function)\\n\",\r\n    \"    - [For else statement](#for-else-statement)\\n\",\r\n    \"    - [Importing Modules](#importing-modules)\\n\",\r\n    \"    - [Ending a Program Early with sys.exit()](#ending-a-program-early-with-sysexit)\\n\",\r\n    \"- [Functions](#functions)\\n\",\r\n    \"    - [Return Values and return Statements](#return-values-and-return-statements)\\n\",\r\n    \"    - [The None Value](#the-none-value)\\n\",\r\n    \"    - [Keyword Arguments and print()](#keyword-arguments-and-print)\\n\",\r\n    \"    - [Local and Global Scope](#local-and-global-scope)\\n\",\r\n    \"    - [The global Statement](#the-global-statement)\\n\",\r\n    \"- [Exception Handling](#exception-handling)\\n\",\r\n    \"    - [Basic exception handling](#basic-exception-handling)\\n\",\r\n    \"    - [Final code in exception handling](#final-code-in-exception-handling)\\n\",\r\n    \"- [Lists](#lists)\\n\",\r\n    \"    - [Getting Individual Values in a List with Indexes](#getting-individual-values-in-a-list-with-indexes)\\n\",\r\n    \"    - [Negative Indexes](#negative-indexes)\\n\",\r\n    \"    - [Getting Sublists with Slices](#getting-sublists-with-slices)\\n\",\r\n    \"    - [Getting a List’s Length with len()](#getting-a-list%E2%80%99s-length-with-len)\\n\",\r\n    \"    - [Changing Values in a List with Indexes](#changing-values-in-a-list-with-indexes)\\n\",\r\n    \"    - [List Concatenation and List Replication](#list-concatenation-and-list-replication)\\n\",\r\n    \"    - [Removing Values from Lists with del Statements](#removing-values-from-lists-with-del-statements)\\n\",\r\n    \"    - [Using for Loops with Lists](#using-for-loops-with-lists)\\n\",\r\n    \"    - [Looping Through Multiple Lists with zip()](#looping-through-multiple-lists-with-zip)\\n\",\r\n    \"    - [The in and not in Operators](#the-in-and-not-in-operators)\\n\",\r\n    \"    - [The Multiple Assignment Trick](#the-multiple-assignment-trick)\\n\",\r\n    \"    - [Augmented Assignment Operators](#augmented-assignment-operators)\\n\",\r\n    \"    - [Finding a Value in a List with the index() Method](#finding-a-value-in-a-list-with-the-index-method)\\n\",\r\n    \"    - [Adding Values to Lists with the append() and insert() Methods](#adding-values-to-lists-with-the-append-and-insert-methods)\\n\",\r\n    \"    - [Removing Values from Lists with remove()](#removing-values-from-lists-with-remove)\\n\",\r\n    \"    - [Sorting the Values in a List with the sort() Method](#sorting-the-values-in-a-list-with-the-sort-method)\\n\",\r\n    \"    - [Tuple Data Type](#tuple-data-type)\\n\",\r\n    \"    - [Converting Types with the list() and tuple() Functions](#converting-types-with-the-list-and-tuple-functions)\\n\",\r\n    \"- [Dictionaries and Structuring Data](#dictionaries-and-structuring-data)\\n\",\r\n    \"    - [The keys(), values(), and items() Methods](#the-keys-values-and-items-methods)\\n\",\r\n    \"    - [Checking Whether a Key or Value Exists in a Dictionary](#checking-whether-a-key-or-value-exists-in-a-dictionary)\\n\",\r\n    \"    - [The get() Method](#the-get-method)\\n\",\r\n    \"    - [The setdefault() Method](#the-setdefault-method)\\n\",\r\n    \"    - [Pretty Printing](#pretty-printing)\\n\",\r\n    \"    - [Merge two dictionaries](#merge-two-dictionaries)\\n\",\r\n    \"- [sets](#sets)\\n\",\r\n    \"    - [Initializing a set](#initializing-a-set)\\n\",\r\n    \"    - [sets: unordered collections of unique elements](#sets-unordered-collections-of-unique-elements)\\n\",\r\n    \"    - [set add() and update()](#set-add-and-update)\\n\",\r\n    \"    - [set remove() and discard()](#set-remove-and-discard)\\n\",\r\n    \"    - [set union()](#set-union)\\n\",\r\n    \"    - [set intersection](#set-intersection)\\n\",\r\n    \"    - [set difference](#set-difference)\\n\",\r\n    \"    - [set symetric_difference](#set-symetricdifference)\\n\",\r\n    \"- [itertools Module](#itertools-module)\\n\",\r\n    \"    - [accumulate()](#accumulate)\\n\",\r\n    \"    - [combinations()](#combinations)\\n\",\r\n    \"    - [combinations_with_replacement()](#combinationswithreplacement)\\n\",\r\n    \"    - [count()](#count)\\n\",\r\n    \"    - [cycle()](#cycle)\\n\",\r\n    \"    - [chain()](#chain)\\n\",\r\n    \"    - [compress()](#compress)\\n\",\r\n    \"    - [dropwhile()](#dropwhile)\\n\",\r\n    \"    - [filterfalse()](#filterfalse)\\n\",\r\n    \"    - [groupby()](#groupby)\\n\",\r\n    \"    - [islice()](#islice)\\n\",\r\n    \"    - [permutations()](#permutations)\\n\",\r\n    \"    - [product()](#product)\\n\",\r\n    \"    - [repeat()](#repeat)\\n\",\r\n    \"    - [starmap()](#starmap)\\n\",\r\n    \"    - [takewhile()](#takewhile)\\n\",\r\n    \"    - [tee()](#tee)\\n\",\r\n    \"    - [zip_longest()](#ziplongest)\\n\",\r\n    \"- [Comprehensions](#comprehensions)\\n\",\r\n    \"    - [List comprehension](#list-comprehension)\\n\",\r\n    \"    - [Set comprehension](#set-comprehension)\\n\",\r\n    \"    - [Dict comprehension](#dict-comprehension)\\n\",\r\n    \"- [Manipulating Strings](#manipulating-strings)\\n\",\r\n    \"    - [Escape Characters](#escape-characters)\\n\",\r\n    \"    - [Raw Strings](#raw-strings)\\n\",\r\n    \"    - [Multiline Strings with Triple Quotes](#multiline-strings-with-triple-quotes)\\n\",\r\n    \"    - [Indexing and Slicing Strings](#indexing-and-slicing-strings)\\n\",\r\n    \"    - [The in and not in Operators with Strings](#the-in-and-not-in-operators-with-strings)\\n\",\r\n    \"    - [The in and not in Operators with list](#the-in-and-not-in-operators-with-list)\\n\",\r\n    \"    - [The upper(), lower(), isupper(), and islower() String Methods](#the-upper-lower-isupper-and-islower-string-methods)\\n\",\r\n    \"    - [The isX String Methods](#the-isx-string-methods)\\n\",\r\n    \"    - [The startswith() and endswith() String Methods](#the-startswith-and-endswith-string-methods)\\n\",\r\n    \"    - [The join() and split() String Methods](#the-join-and-split-string-methods)\\n\",\r\n    \"    - [Justifying Text with rjust(), ljust(), and center()](#justifying-text-with-rjust-ljust-and-center)\\n\",\r\n    \"    - [Removing Whitespace with strip(), rstrip(), and lstrip()](#removing-whitespace-with-strip-rstrip-and-lstrip)\\n\",\r\n    \"    - [Copying and Pasting Strings with the pyperclip Module (need pip install)](#copying-and-pasting-strings-with-the-pyperclip-module-need-pip-install)\\n\",\r\n    \"- [String Formatting](#string-formatting)\\n\",\r\n    \"    - [% operator](#operator)\\n\",\r\n    \"    - [String Formatting (str.format)](#string-formatting-strformat)\\n\",\r\n    \"    - [Lazy string formatting](#lazy-string-formatting)\\n\",\r\n    \"    - [Formatted String Literals or f-strings (Python 3.6+)](#formatted-string-literals-or-f-strings-python-36)\\n\",\r\n    \"    - [Template Strings](#template-strings)\\n\",\r\n    \"- [Regular Expressions](#regular-expressions)\\n\",\r\n    \"    - [Matching Regex Objects](#matching-regex-objects)\\n\",\r\n    \"    - [Grouping with Parentheses](#grouping-with-parentheses)\\n\",\r\n    \"    - [Matching Multiple Groups with the Pipe](#matching-multiple-groups-with-the-pipe)\\n\",\r\n    \"    - [Optional Matching with the Question Mark](#optional-matching-with-the-question-mark)\\n\",\r\n    \"    - [Matching Zero or More with the Star](#matching-zero-or-more-with-the-star)\\n\",\r\n    \"    - [Matching One or More with the Plus](#matching-one-or-more-with-the-plus)\\n\",\r\n    \"    - [Matching Specific Repetitions with Curly Brackets](#matching-specific-repetitions-with-curly-brackets)\\n\",\r\n    \"    - [Greedy and Nongreedy Matching](#greedy-and-nongreedy-matching)\\n\",\r\n    \"    - [The findall() Method](#the-findall-method)\\n\",\r\n    \"    - [Making Your Own Character Classes](#making-your-own-character-classes)\\n\",\r\n    \"    - [The Caret and Dollar Sign Characters](#the-caret-and-dollar-sign-characters)\\n\",\r\n    \"    - [The Wildcard Character](#the-wildcard-character)\\n\",\r\n    \"    - [Matching Everything with Dot-Star](#matching-everything-with-dot-star)\\n\",\r\n    \"    - [Matching Newlines with the Dot Character](#matching-newlines-with-the-dot-character)\\n\",\r\n    \"    - [Review of Regex Symbols](#review-of-regex-symbols)\\n\",\r\n    \"    - [Case-Insensitive Matching](#case-insensitive-matching)\\n\",\r\n    \"    - [Substituting Strings with the sub() Method](#substituting-strings-with-the-sub-method)\\n\",\r\n    \"    - [Managing Complex Regexes](#managing-complex-regexes)\\n\",\r\n    \"- [Handling File and Directory Paths](#handling-file-and-directory-paths)\\n\",\r\n    \"    - [Backslash on Windows and Forward Slash on OS X and Linux](#backslash-on-windows-and-forward-slash-on-os-x-and-linux)\\n\",\r\n    \"    - [The Current Working Directory](#the-current-working-directory)\\n\",\r\n    \"    - [Creating New Folders](#creating-new-folders)\\n\",\r\n    \"    - [Absolute vs. Relative Paths](#absolute-vs-relative-paths)\\n\",\r\n    \"    - [Handling Absolute and Relative Paths](#handling-absolute-and-relative-paths)\\n\",\r\n    \"    - [Checking Path Validity](#checking-path-validity)\\n\",\r\n    \"    - [Finding File Sizes and Folder Contents](#finding-file-sizes-and-folder-contents)\\n\",\r\n    \"    - [Copying Files and Folders](#copying-files-and-folders)\\n\",\r\n    \"    - [Moving and Renaming Files and Folders](#moving-and-renaming-files-and-folders)\\n\",\r\n    \"    - [Permanently Deleting Files and Folders](#permanently-deleting-files-and-folders)\\n\",\r\n    \"    - [Safe Deletes with the send2trash Module](#safe-deletes-with-the-send2trash-module)\\n\",\r\n    \"    - [Walking a Directory Tree](#walking-a-directory-tree)\\n\",\r\n    \"- [Reading and Writing Files](#reading-and-writing-files)\\n\",\r\n    \"    - [The File Reading/Writing Process](#the-file-readingwriting-process)\\n\",\r\n    \"    - [Opening and reading files with the open() function](#opening-and-reading-files-with-the-open-function)\\n\",\r\n    \"    - [Writing to Files](#writing-to-files)\\n\",\r\n    \"    - [Saving Variables with the shelve Module](#saving-variables-with-the-shelve-module)\\n\",\r\n    \"    - [Saving Variables with the pprint.pformat() Function](#saving-variables-with-the-pprintpformat-function)\\n\",\r\n    \"    - [Reading ZIP Files](#reading-zip-files)\\n\",\r\n    \"    - [Extracting from ZIP Files](#extracting-from-zip-files)\\n\",\r\n    \"    - [Creating and Adding to ZIP Files](#creating-and-adding-to-zip-files)\\n\",\r\n    \"- [JSON, YAML and configuration files](#json-yaml-and-configuration-files)\\n\",\r\n    \"    - [JSON](#json)\\n\",\r\n    \"    - [YAML](#yaml)\\n\",\r\n    \"    - [Anyconfig](#anyconfig)\\n\",\r\n    \"- [Debugging](#debugging)\\n\",\r\n    \"    - [Raising Exceptions](#raising-exceptions)\\n\",\r\n    \"    - [Getting the Traceback as a String](#getting-the-traceback-as-a-string)\\n\",\r\n    \"    - [Assertions](#assertions)\\n\",\r\n    \"    - [Logging](#logging)\\n\",\r\n    \"    - [Logging Levels](#logging-levels)\\n\",\r\n    \"    - [Disabling Logging](#disabling-logging)\\n\",\r\n    \"    - [Logging to a File](#logging-to-a-file)\\n\",\r\n    \"- [Lambda Functions](#lambda-functions)\\n\",\r\n    \"- [Ternary Conditional Operator](#ternary-conditional-operator)\\n\",\r\n    \"- [args and kwargs](#args-and-kwargs)\\n\",\r\n    \"    - [Thinks to Remember(args)](#thinks-to-rememberargs)\\n\",\r\n    \"    - [Thinks to remember(kwargs)](#thinks-to-rememberkwargs)\\n\",\r\n    \"- [Context Manager](#context-manager)\\n\",\r\n    \"    - [with statement](#with-statement)\\n\",\r\n    \"    - [Writing your own contextmanager using generator syntax](#writing-your-own-contextmanager-using-generator-syntax)\\n\",\r\n    \"- [`__main__` Top-level script environment](#main-top-level-script-environment)\\n\",\r\n    \"    - [Advantages](#advantages)\\n\",\r\n    \"- [setup.py](#setuppy)\\n\",\r\n    \"- [Dataclasses](#dataclasses)\\n\",\r\n    \"    - [Features](#features)\\n\",\r\n    \"    - [Default values](#default-values)\\n\",\r\n    \"    - [Type hints](#type-hints)\\n\",\r\n    \"- [Virtual Environment](#virtual-environment)\\n\",\r\n    \"    - [virtualenv](#virtualenv)\\n\",\r\n    \"    - [pipenv](#pipenv)\\n\",\r\n    \"    - [anaconda](#anaconda)\\n\",\r\n    \"\\n\",\r\n    \"## The Zen of Python\\n\",\r\n    \"\\n\",\r\n    \"From the [PEP 20 -- The Zen of Python](https://www.python.org/dev/peps/pep-0020/):\\n\",\r\n    \"\\n\",\r\n    \"> Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import this\\n\",\r\n    \"The Zen of Python, by Tim Peters\\n\",\r\n    \"\\n\",\r\n    \"Beautiful is better than ugly.\\n\",\r\n    \"Explicit is better than implicit.\\n\",\r\n    \"Simple is better than complex.\\n\",\r\n    \"Complex is better than complicated.\\n\",\r\n    \"Flat is better than nested.\\n\",\r\n    \"Sparse is better than dense.\\n\",\r\n    \"Readability counts.\\n\",\r\n    \"Special cases aren't special enough to break the rules.\\n\",\r\n    \"Although practicality beats purity.\\n\",\r\n    \"Errors should never pass silently.\\n\",\r\n    \"Unless explicitly silenced.\\n\",\r\n    \"In the face of ambiguity, refuse the temptation to guess.\\n\",\r\n    \"There should be one-- and preferably only one --obvious way to do it.\\n\",\r\n    \"Although that way may not be obvious at first unless you're Dutch.\\n\",\r\n    \"Now is better than never.\\n\",\r\n    \"Although never is often better than *right* now.\\n\",\r\n    \"If the implementation is hard to explain, it's a bad idea.\\n\",\r\n    \"If the implementation is easy to explain, it may be a good idea.\\n\",\r\n    \"Namespaces are one honking great idea -- let's do more of those!\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Python Basics\\n\",\r\n    \"\\n\",\r\n    \"### Math Operators\\n\",\r\n    \"\\n\",\r\n    \"From **Highest** to **Lowest** precedence:\\n\",\r\n    \"\\n\",\r\n    \"| Operators | Operation        | Example         |\\n\",\r\n    \"| --------- | ---------------- | --------------- |\\n\",\r\n    \"| **        | Exponent         | `2 ** 3 = 8`    |\\n\",\r\n    \"| %         | Modulus/Remaider | `22 % 8 = 6`    |\\n\",\r\n    \"| //        | Integer division | `22 // 8 = 2`   |\\n\",\r\n    \"| /         | Division         | `22 / 8 = 2.75` |\\n\",\r\n    \"| *         | Multiplication   | `3 * 3 = 9`     |\\n\",\r\n    \"| -         | Subtraction      | `5 - 2 = 3`     |\\n\",\r\n    \"| +         | Addition         | `2 + 2 = 4`     |\\n\",\r\n    \"\\n\",\r\n    \"Examples of expressions in the interactive shell:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 2 + 3 * 6\\n\",\r\n    \"20\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> (2 + 3) * 6\\n\",\r\n    \"30\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 2 ** 8\\n\",\r\n    \"256\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 23 // 7\\n\",\r\n    \"3\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 23 % 7\\n\",\r\n    \"2\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> (5 - 1) * ((7 + 1) / (3 - 1))\\n\",\r\n    \"16.0\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Data Types\\n\",\r\n    \"\\n\",\r\n    \"| Data Type              | Examples                                  |\\n\",\r\n    \"| ---------------------- | ----------------------------------------- |\\n\",\r\n    \"| Integers               | `-2, -1, 0, 1, 2, 3, 4, 5`                |\\n\",\r\n    \"| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` |\\n\",\r\n    \"| Strings                | `'a', 'aa', 'aaa', 'Hello!', '11 cats'`   |\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### String Concatenation and Replication\\n\",\r\n    \"\\n\",\r\n    \"String concatenation:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Alice' 'Bob'\\n\",\r\n    \"'AliceBob'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Note: Avoid `+` operator for string concatenation. Prefer string formatting.\\n\",\r\n    \"\\n\",\r\n    \"String Replication:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Alice' * 5\\n\",\r\n    \"'AliceAliceAliceAliceAlice'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Variables\\n\",\r\n    \"\\n\",\r\n    \"You can name a variable anything as long as it obeys the following three rules:\\n\",\r\n    \"\\n\",\r\n    \"1. It can be only one word.\\n\",\r\n    \"1. It can use only letters, numbers, and the underscore (`_`) character.\\n\",\r\n    \"1. It can’t begin with a number.\\n\",\r\n    \"1. Variable name starting with an underscore (`_`) are considered as \\\"unuseful`.\\n\",\r\n    \"\\n\",\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'Hello'\\n\",\r\n    \">>> spam\\n\",\r\n    \"'Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> _spam = 'Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"`_spam` should not be used again in the code.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Comments\\n\",\r\n    \"\\n\",\r\n    \"Inline comment:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"# This is a comment\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Multiline comment:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {\r\n    \"attributes\": {\r\n     \"classes\": [\r\n      \"Python\"\r\n     ],\r\n     \"id\": \"\"\r\n    }\r\n   },\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"# This is a\\n\",\r\n    \"# multiline comment\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Code with a comment:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"a = 1  # initialization\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Please note the two spaces in front of the comment.\\n\",\r\n    \"\\n\",\r\n    \"Function docstring:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"def foo():\\n\",\r\n    \"    \\\"\\\"\\\"\\n\",\r\n    \"    This is a function docstring\\n\",\r\n    \"    You can also use:\\n\",\r\n    \"    ''' Function Docstring '''\\n\",\r\n    \"    \\\"\\\"\\\"\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The print() Function\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('Hello world!')\\n\",\r\n    \"Hello world!\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> a = 1\\n\",\r\n    \">>> print('Hello world!', a)\\n\",\r\n    \"Hello world! 1\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The input() Function\\n\",\r\n    \"\\n\",\r\n    \"Example Code:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('What is your name?')   # ask for their name\\n\",\r\n    \">>> myName = input()\\n\",\r\n    \">>> print('It is good to meet you, {}'.format(myName))\\n\",\r\n    \"What is your name?\\n\",\r\n    \"Al\\n\",\r\n    \"It is good to meet you, Al\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The len() Function\\n\",\r\n    \"\\n\",\r\n    \"Evaluates to the integer value of the number of characters in a string:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> len('hello')\\n\",\r\n    \"5\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Note: test of emptiness of strings, lists, dictionary, etc, should **not** use len, but prefer direct\\n\",\r\n    \"boolean evaluation.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> a = [1, 2, 3]\\n\",\r\n    \">>> if a:\\n\",\r\n    \">>>     print(\\\"the list is not empty!\\\")\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The str(), int(), and float() Functions\\n\",\r\n    \"\\n\",\r\n    \"Integer to String or Float:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> str(29)\\n\",\r\n    \"'29'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('I am {} years old.'.format(str(29)))\\n\",\r\n    \"I am 29 years old.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> str(-3.14)\\n\",\r\n    \"'-3.14'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Float to Integer:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> int(7.7)\\n\",\r\n    \"7\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> int(7.7) + 1\\n\",\r\n    \"8\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Flow Control\\n\",\r\n    \"\\n\",\r\n    \"### Comparison Operators\\n\",\r\n    \"\\n\",\r\n    \"| Operator | Meaning                  |\\n\",\r\n    \"| -------- | ------------------------ |\\n\",\r\n    \"| `==`     | Equal to                 |\\n\",\r\n    \"| `!=`     | Not equal to             |\\n\",\r\n    \"| `<`      | Less than                |\\n\",\r\n    \"| `>`      | Greater Than             |\\n\",\r\n    \"| `<=`     | Less than or Equal to    |\\n\",\r\n    \"| `>=`     | Greater than or Equal to |\\n\",\r\n    \"\\n\",\r\n    \"These operators evaluate to True or False depending on the values you give them.\\n\",\r\n    \"\\n\",\r\n    \"Examples:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 42 == 42\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 40 == 42\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'hello' == 'hello'\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'hello' == 'Hello'\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'dog' != 'cat'\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 42 == 42.0\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 42 == '42'\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### Boolean evaluation\\n\",\r\n    \"\\n\",\r\n    \"Never use `==` or `!=` operator to evaluate boolean operation. Use the `is` or `is not` operators,\\n\",\r\n    \"or use implicit boolean evaluation.\\n\",\r\n    \"\\n\",\r\n    \"NO (even if they are valid Python):\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> True == True\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> True != False\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"YES (even if they are valid Python):\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> True is True\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> True is not False\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"These statements are equivalent:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {\r\n    \"attributes\": {\r\n     \"classes\": [\r\n      \"Python\"\r\n     ],\r\n     \"id\": \"\"\r\n    }\r\n   },\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> if a is True:\\n\",\r\n    \">>>    pass\\n\",\r\n    \">>> if a is not False:\\n\",\r\n    \">>>    pass\\n\",\r\n    \">>> if a:\\n\",\r\n    \">>>    pass\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"And these as well:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {\r\n    \"attributes\": {\r\n     \"classes\": [\r\n      \"Python\"\r\n     ],\r\n     \"id\": \"\"\r\n    }\r\n   },\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> if a is False:\\n\",\r\n    \">>>    pass\\n\",\r\n    \">>> if a is not True:\\n\",\r\n    \">>>    pass\\n\",\r\n    \">>> if not a:\\n\",\r\n    \">>>    pass\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Boolean Operators\\n\",\r\n    \"\\n\",\r\n    \"There are three Boolean operators: and, or, and not.\\n\",\r\n    \"\\n\",\r\n    \"The *and* Operator’s *Truth* Table:\\n\",\r\n    \"\\n\",\r\n    \"| Expression        | Evaluates to |\\n\",\r\n    \"| ----------------- | ------------ |\\n\",\r\n    \"| `True and True`   | `True`       |\\n\",\r\n    \"| `True and False`  | `False`      |\\n\",\r\n    \"| `False and True`  | `False`      |\\n\",\r\n    \"| `False and False` | `False`      |\\n\",\r\n    \"\\n\",\r\n    \"The *or* Operator’s *Truth* Table:\\n\",\r\n    \"\\n\",\r\n    \"| Expression       | Evaluates to |\\n\",\r\n    \"| ---------------- | ------------ |\\n\",\r\n    \"| `True or True`   | `True`       |\\n\",\r\n    \"| `True or False`  | `True`       |\\n\",\r\n    \"| `False or True`  | `True`       |\\n\",\r\n    \"| `False or False` | `False`      |\\n\",\r\n    \"\\n\",\r\n    \"The *not* Operator’s *Truth* Table:\\n\",\r\n    \"\\n\",\r\n    \"| Expression  | Evaluates to |\\n\",\r\n    \"| ----------- | ------------ |\\n\",\r\n    \"| `not True`  | `False`      |\\n\",\r\n    \"| `not False` | `True`       |\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Mixing Boolean and Comparison Operators\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> (4 < 5) and (5 < 6)\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> (4 < 5) and (9 < 6)\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> (1 == 2) or (2 == 2)\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can also use multiple Boolean operators in an expression, along with the comparison operators:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### if Statements\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"if name == 'Alice':\\n\",\r\n    \"    print('Hi, Alice.')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### else Statements\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"name = 'Bob'\\n\",\r\n    \"if name == 'Alice':\\n\",\r\n    \"    print('Hi, Alice.')\\n\",\r\n    \"else:\\n\",\r\n    \"    print('Hello, stranger.')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### elif Statements\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"name = 'Bob'\\n\",\r\n    \"age = 5\\n\",\r\n    \"if name == 'Alice':\\n\",\r\n    \"    print('Hi, Alice.')\\n\",\r\n    \"elif age < 12:\\n\",\r\n    \"    print('You are not Alice, kiddo.')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"name = 'Bob'\\n\",\r\n    \"age = 30\\n\",\r\n    \"if name == 'Alice':\\n\",\r\n    \"    print('Hi, Alice.')\\n\",\r\n    \"elif age < 12:\\n\",\r\n    \"    print('You are not Alice, kiddo.')\\n\",\r\n    \"else:\\n\",\r\n    \"    print('You are neither Alice nor a little kid.')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### while Loop Statements\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"spam = 0\\n\",\r\n    \"while spam < 5:\\n\",\r\n    \"    print('Hello, world.')\\n\",\r\n    \"    spam = spam + 1\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### break Statements\\n\",\r\n    \"\\n\",\r\n    \" If the execution reaches a break statement, it immediately exits the while loop’s clause:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"while True:\\n\",\r\n    \"    print('Please type your name.')\\n\",\r\n    \"    name = input()\\n\",\r\n    \"    if name == 'your name':\\n\",\r\n    \"        break\\n\",\r\n    \"print('Thank you!')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### continue Statements\\n\",\r\n    \"\\n\",\r\n    \"When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"while True:\\n\",\r\n    \"    print('Who are you?')\\n\",\r\n    \"    name = input()\\n\",\r\n    \"    if name != 'Joe':\\n\",\r\n    \"        continue\\n\",\r\n    \"    print('Hello, Joe. What is the password? (It is a fish.)')\\n\",\r\n    \"    password = input()\\n\",\r\n    \"    if password == 'swordfish':\\n\",\r\n    \"        break\\n\",\r\n    \"print('Access granted.')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### for Loops and the range() Function\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('My name is')\\n\",\r\n    \">>> for i in range(5):\\n\",\r\n    \">>>     print('Jimmy Five Times ({})'.format(str(i)))\\n\",\r\n    \"My name is\\n\",\r\n    \"Jimmy Five Times (0)\\n\",\r\n    \"Jimmy Five Times (1)\\n\",\r\n    \"Jimmy Five Times (2)\\n\",\r\n    \"Jimmy Five Times (3)\\n\",\r\n    \"Jimmy Five Times (4)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The *range()* function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for i in range(0, 10, 2):\\n\",\r\n    \">>>    print(i)\\n\",\r\n    \"0\\n\",\r\n    \"2\\n\",\r\n    \"4\\n\",\r\n    \"6\\n\",\r\n    \"8\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can even use a negative number for the step argument to make the for loop count down instead of up.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for i in range(5, -1, -1):\\n\",\r\n    \">>>     print(i)\\n\",\r\n    \"5\\n\",\r\n    \"4\\n\",\r\n    \"3\\n\",\r\n    \"2\\n\",\r\n    \"1\\n\",\r\n    \"0\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### For else statement\\n\",\r\n    \"\\n\",\r\n    \"This allows to specify a statement to execute in case of the full loop has been executed. Only\\n\",\r\n    \"useful when a `break` condition can occur in the loop:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for i in [1, 2, 3, 4, 5]:\\n\",\r\n    \">>>    if i == 3:\\n\",\r\n    \">>>        break\\n\",\r\n    \">>> else:\\n\",\r\n    \">>>    print(\\\"only executed when no item of the list is equal to 3\\\")\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Importing Modules\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import random\\n\",\r\n    \"for i in range(5):\\n\",\r\n    \"    print(random.randint(1, 10))\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import random, sys, os, math\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"from random import *.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Ending a Program Early with sys.exit()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import sys\\n\",\r\n    \"\\n\",\r\n    \"while True:\\n\",\r\n    \"    print('Type exit to exit.')\\n\",\r\n    \"    response = input()\\n\",\r\n    \"    if response == 'exit':\\n\",\r\n    \"        sys.exit()\\n\",\r\n    \"    print('You typed {}.'.format(response))\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Functions\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def hello(name):\\n\",\r\n    \">>>     print('Hello {}'.format(name))\\n\",\r\n    \">>>\\n\",\r\n    \">>> hello('Alice')\\n\",\r\n    \">>> hello('Bob')\\n\",\r\n    \"Hello Alice\\n\",\r\n    \"Hello Bob\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Return Values and return Statements\\n\",\r\n    \"\\n\",\r\n    \"When creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:\\n\",\r\n    \"\\n\",\r\n    \"- The return keyword.\\n\",\r\n    \"\\n\",\r\n    \"- The value or expression that the function should return.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import random\\n\",\r\n    \"def getAnswer(answerNumber):\\n\",\r\n    \"    if answerNumber == 1:\\n\",\r\n    \"        return 'It is certain'\\n\",\r\n    \"    elif answerNumber == 2:\\n\",\r\n    \"        return 'It is decidedly so'\\n\",\r\n    \"    elif answerNumber == 3:\\n\",\r\n    \"        return 'Yes'\\n\",\r\n    \"    elif answerNumber == 4:\\n\",\r\n    \"        return 'Reply hazy try again'\\n\",\r\n    \"    elif answerNumber == 5:\\n\",\r\n    \"        return 'Ask again later'\\n\",\r\n    \"    elif answerNumber == 6:\\n\",\r\n    \"        return 'Concentrate and ask again'\\n\",\r\n    \"    elif answerNumber == 7:\\n\",\r\n    \"        return 'My reply is no'\\n\",\r\n    \"    elif answerNumber == 8:\\n\",\r\n    \"        return 'Outlook not so good'\\n\",\r\n    \"    elif answerNumber == 9:\\n\",\r\n    \"        return 'Very doubtful'\\n\",\r\n    \"\\n\",\r\n    \"r = random.randint(1, 9)\\n\",\r\n    \"fortune = getAnswer(r)\\n\",\r\n    \"print(fortune)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The None Value\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = print('Hello!')\\n\",\r\n    \"Hello!\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam is None\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Note: never compare to `None` with the `==` operator. Always use `is`.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Keyword Arguments and print()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('Hello', end='')\\n\",\r\n    \">>> print('World')\\n\",\r\n    \"HelloWorld\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('cats', 'dogs', 'mice')\\n\",\r\n    \"cats dogs mice\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('cats', 'dogs', 'mice', sep=',')\\n\",\r\n    \"cats,dogs,mice\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Local and Global Scope\\n\",\r\n    \"\\n\",\r\n    \"- Code in the global scope cannot use any local variables.\\n\",\r\n    \"\\n\",\r\n    \"- However, a local scope can access global variables.\\n\",\r\n    \"\\n\",\r\n    \"- Code in a function’s local scope cannot use variables in any other local scope.\\n\",\r\n    \"\\n\",\r\n    \"- You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The global Statement\\n\",\r\n    \"\\n\",\r\n    \"If you need to modify a global variable from within a function, use the global statement:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def spam():\\n\",\r\n    \">>>     global eggs\\n\",\r\n    \">>>     eggs = 'spam'\\n\",\r\n    \">>>\\n\",\r\n    \">>> eggs = 'global'\\n\",\r\n    \">>> spam()\\n\",\r\n    \">>> print(eggs)\\n\",\r\n    \"spam\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"There are four rules to tell whether a variable is in a local scope or global scope:\\n\",\r\n    \"\\n\",\r\n    \"1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.\\n\",\r\n    \"\\n\",\r\n    \"1. If there is a global statement for that variable in a function, it is a global variable.\\n\",\r\n    \"\\n\",\r\n    \"1. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.\\n\",\r\n    \"\\n\",\r\n    \"1. But if the variable is not used in an assignment statement, it is a global variable.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Exception Handling\\n\",\r\n    \"\\n\",\r\n    \"### Basic exception handling\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def spam(divideBy):\\n\",\r\n    \">>>     try:\\n\",\r\n    \">>>         return 42 / divideBy\\n\",\r\n    \">>>     except ZeroDivisionError as e:\\n\",\r\n    \">>>         print('Error: Invalid argument: {}'.format(e))\\n\",\r\n    \">>>\\n\",\r\n    \">>> print(spam(2))\\n\",\r\n    \">>> print(spam(12))\\n\",\r\n    \">>> print(spam(0))\\n\",\r\n    \">>> print(spam(1))\\n\",\r\n    \"21.0\\n\",\r\n    \"3.5\\n\",\r\n    \"Error: Invalid argument: division by zero\\n\",\r\n    \"None\\n\",\r\n    \"42.0\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Final code in exception handling\\n\",\r\n    \"\\n\",\r\n    \"Code inside the `finally` section is always executed, no matter if an exception has been raised or\\n\",\r\n    \"not, and even if an exception is not caught.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def spam(divideBy):\\n\",\r\n    \">>>     try:\\n\",\r\n    \">>>         return 42 / divideBy\\n\",\r\n    \">>>     except ZeroDivisionError as e:\\n\",\r\n    \">>>         print('Error: Invalid argument: {}'.format(e))\\n\",\r\n    \">>>     finally:\\n\",\r\n    \">>>         print(\\\"-- division finished --\\\")\\n\",\r\n    \">>> print(spam(12))\\n\",\r\n    \">>> print(spam(0))\\n\",\r\n    \"21.0\\n\",\r\n    \"-- division finished --\\n\",\r\n    \"3.5\\n\",\r\n    \"-- division finished --\\n\",\r\n    \"Error: Invalid argument: division by zero\\n\",\r\n    \"-- division finished --\\n\",\r\n    \"None\\n\",\r\n    \"-- division finished --\\n\",\r\n    \"42.0\\n\",\r\n    \"-- division finished --\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Lists\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'bat', 'rat', 'elephant']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Getting Individual Values in a List with Indexes\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> spam[0]\\n\",\r\n    \"'cat'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[1]\\n\",\r\n    \"'bat'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[2]\\n\",\r\n    \"'rat'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[3]\\n\",\r\n    \"'elephant'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Negative Indexes\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> spam[-1]\\n\",\r\n    \"'elephant'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[-3]\\n\",\r\n    \"'bat'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'The {} is afraid of the {}.'.format(spam[-1], spam[-3])\\n\",\r\n    \"'The elephant is afraid of the bat.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Getting Sublists with Slices\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> spam[0:4]\\n\",\r\n    \"['cat', 'bat', 'rat', 'elephant']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[1:3]\\n\",\r\n    \"['bat', 'rat']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[0:-1]\\n\",\r\n    \"['cat', 'bat', 'rat']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> spam[:2]\\n\",\r\n    \"['cat', 'bat']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[1:]\\n\",\r\n    \"['bat', 'rat', 'elephant']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Slicing the complete list will perform a copy:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam2 = spam[:]\\n\",\r\n    \"['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> spam.append('dog')\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'bat', 'rat', 'elephant', 'dog']\\n\",\r\n    \">>> spam2\\n\",\r\n    \"['cat', 'bat', 'rat', 'elephant']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Getting a List’s Length with len()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'dog', 'moose']\\n\",\r\n    \">>> len(spam)\\n\",\r\n    \"3\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Changing Values in a List with Indexes\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> spam[1] = 'aardvark'\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'aardvark', 'rat', 'elephant']\\n\",\r\n    \"\\n\",\r\n    \">>> spam[2] = spam[1]\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'aardvark', 'aardvark', 'elephant']\\n\",\r\n    \"\\n\",\r\n    \">>> spam[-1] = 12345\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'aardvark', 'aardvark', 12345]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### List Concatenation and List Replication\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> [1, 2, 3] + ['A', 'B', 'C']\\n\",\r\n    \"[1, 2, 3, 'A', 'B', 'C']\\n\",\r\n    \"\\n\",\r\n    \">>> ['X', 'Y', 'Z'] * 3\\n\",\r\n    \"['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']\\n\",\r\n    \"\\n\",\r\n    \">>> spam = [1, 2, 3]\\n\",\r\n    \"\\n\",\r\n    \">>> spam = spam + ['A', 'B', 'C']\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"[1, 2, 3, 'A', 'B', 'C']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Removing Values from Lists with del Statements\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \">>> del spam[2]\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'bat', 'elephant']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> del spam[2]\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'bat']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Using for Loops with Lists\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']\\n\",\r\n    \">>> for i, supply in enumerate(supplies):\\n\",\r\n    \">>>     print('Index {} in supplies is: {}'.format(str(i), supply))\\n\",\r\n    \"Index 0 in supplies is: pens\\n\",\r\n    \"Index 1 in supplies is: staplers\\n\",\r\n    \"Index 2 in supplies is: flame-throwers\\n\",\r\n    \"Index 3 in supplies is: binders\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Looping Through Multiple Lists with zip()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> name = ['Pete', 'John', 'Elizabeth']\\n\",\r\n    \">>> age = [6, 23, 44]\\n\",\r\n    \">>> for n, a in zip(name, age):\\n\",\r\n    \">>>     print('{} is {} years old'.format(n, a))\\n\",\r\n    \"Pete is 6 years old\\n\",\r\n    \"John is 23 years old\\n\",\r\n    \"Elizabeth is 44 years old\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### The in and not in Operators\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['hello', 'hi', 'howdy', 'heyas']\\n\",\r\n    \">>> 'cat' in spam\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'howdy' not in spam\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'cat' not in spam\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The Multiple Assignment Trick\\n\",\r\n    \"\\n\",\r\n    \"The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> cat = ['fat', 'orange', 'loud']\\n\",\r\n    \"\\n\",\r\n    \">>> size = cat[0]\\n\",\r\n    \"\\n\",\r\n    \">>> color = cat[1]\\n\",\r\n    \"\\n\",\r\n    \">>> disposition = cat[2]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You could type this line of code:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> cat = ['fat', 'orange', 'loud']\\n\",\r\n    \"\\n\",\r\n    \">>> size, color, disposition = cat\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The multiple assignment trick can also be used to swap the values in two variables:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> a, b = 'Alice', 'Bob'\\n\",\r\n    \">>> a, b = b, a\\n\",\r\n    \">>> print(a)\\n\",\r\n    \"'Bob'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print(b)\\n\",\r\n    \"'Alice'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Augmented Assignment Operators\\n\",\r\n    \"\\n\",\r\n    \"| Operator    | Equivalent        |\\n\",\r\n    \"| ----------- | ----------------- |\\n\",\r\n    \"| `spam += 1` | `spam = spam + 1` |\\n\",\r\n    \"| `spam -= 1` | `spam = spam - 1` |\\n\",\r\n    \"| `spam *= 1` | `spam = spam * 1` |\\n\",\r\n    \"| `spam /= 1` | `spam = spam / 1` |\\n\",\r\n    \"| `spam %= 1` | `spam = spam % 1` |\\n\",\r\n    \"\\n\",\r\n    \"Examples:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'Hello'\\n\",\r\n    \">>> spam += ' world!'\\n\",\r\n    \">>> spam\\n\",\r\n    \"'Hello world!'\\n\",\r\n    \"\\n\",\r\n    \">>> bacon = ['Zophie']\\n\",\r\n    \">>> bacon *= 3\\n\",\r\n    \">>> bacon\\n\",\r\n    \"['Zophie', 'Zophie', 'Zophie']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Finding a Value in a List with the index() Method\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']\\n\",\r\n    \"\\n\",\r\n    \">>> spam.index('Pooka')\\n\",\r\n    \"1\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Adding Values to Lists with the append() and insert() Methods\\n\",\r\n    \"\\n\",\r\n    \"**append()**:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'dog', 'bat']\\n\",\r\n    \"\\n\",\r\n    \">>> spam.append('moose')\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'dog', 'bat', 'moose']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"**insert()**:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'dog', 'bat']\\n\",\r\n    \"\\n\",\r\n    \">>> spam.insert(1, 'chicken')\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'chicken', 'dog', 'bat']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Removing Values from Lists with remove()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['cat', 'bat', 'rat', 'elephant']\\n\",\r\n    \"\\n\",\r\n    \">>> spam.remove('bat')\\n\",\r\n    \"\\n\",\r\n    \">>> spam\\n\",\r\n    \"['cat', 'rat', 'elephant']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"If the value appears multiple times in the list, only the first instance of the value will be removed.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Sorting the Values in a List with the sort() Method\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = [2, 5, 3.14, 1, -7]\\n\",\r\n    \">>> spam.sort()\\n\",\r\n    \">>> spam\\n\",\r\n    \"[-7, 1, 2, 3.14, 5]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']\\n\",\r\n    \">>> spam.sort()\\n\",\r\n    \">>> spam\\n\",\r\n    \"['ants', 'badgers', 'cats', 'dogs', 'elephants']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam.sort(reverse=True)\\n\",\r\n    \">>> spam\\n\",\r\n    \"['elephants', 'dogs', 'cats', 'badgers', 'ants']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"If you need to sort the values in regular alphabetical order, pass str. lower for the key keyword argument in the sort() method call:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['a', 'z', 'A', 'Z']\\n\",\r\n    \">>> spam.sort(key=str.lower)\\n\",\r\n    \">>> spam\\n\",\r\n    \"['a', 'A', 'z', 'Z']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can use the built-in function `sorted` to return a new list:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']\\n\",\r\n    \">>> sorted(spam)\\n\",\r\n    \"['ants', 'badgers', 'cats', 'dogs', 'elephants']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Tuple Data Type\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> eggs = ('hello', 42, 0.5)\\n\",\r\n    \">>> eggs[0]\\n\",\r\n    \"'hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> eggs[1:3]\\n\",\r\n    \"(42, 0.5)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> len(eggs)\\n\",\r\n    \"3\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The main way that tuples are different from lists is that tuples, like strings, are immutable.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Converting Types with the list() and tuple() Functions\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> tuple(['cat', 'dog', 5])\\n\",\r\n    \"('cat', 'dog', 5)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> list(('cat', 'dog', 5))\\n\",\r\n    \"['cat', 'dog', 5]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> list('hello')\\n\",\r\n    \"['h', 'e', 'l', 'l', 'o']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Dictionaries and Structuring Data\\n\",\r\n    \"\\n\",\r\n    \"Example Dictionary:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The keys(), values(), and items() Methods\\n\",\r\n    \"\\n\",\r\n    \"values():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = {'color': 'red', 'age': 42}\\n\",\r\n    \">>> for v in spam.values():\\n\",\r\n    \">>>     print(v)\\n\",\r\n    \"red\\n\",\r\n    \"42\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"keys():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for k in spam.keys():\\n\",\r\n    \">>>     print(k)\\n\",\r\n    \"color\\n\",\r\n    \"age\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"items():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for i in spam.items():\\n\",\r\n    \">>>     print(i)\\n\",\r\n    \"('color', 'red')\\n\",\r\n    \"('age', 42)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"\\n\",\r\n    \">>> spam = {'color': 'red', 'age': 42}\\n\",\r\n    \">>>\\n\",\r\n    \">>> for k, v in spam.items():\\n\",\r\n    \">>>     print('Key: {} Value: {}'.format(k, str(v)))\\n\",\r\n    \"Key: age Value: 42\\n\",\r\n    \"Key: color Value: red\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Checking Whether a Key or Value Exists in a Dictionary\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = {'name': 'Zophie', 'age': 7}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'name' in spam.keys()\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Zophie' in spam.values()\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> # You can omit the call to keys() when checking for a key\\n\",\r\n    \">>> 'color' in spam\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'color' not in spam\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'color' in spam\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The get() Method\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> picnic_items = {'apples': 5, 'cups': 2}\\n\",\r\n    \"\\n\",\r\n    \">>> 'I am bringing {} cups.'.format(str(picnic_items.get('cups', 0)))\\n\",\r\n    \"'I am bringing 2 cups.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'I am bringing {} eggs.'.format(str(picnic_items.get('eggs', 0)))\\n\",\r\n    \"'I am bringing 0 eggs.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The setdefault() Method\\n\",\r\n    \"\\n\",\r\n    \"Let's consider this code:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"spam = {'name': 'Pooka', 'age': 5}\\n\",\r\n    \"\\n\",\r\n    \"if 'color' not in spam:\\n\",\r\n    \"    spam['color'] = 'black'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `setdefault` we could make the same code more shortly:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = {'name': 'Pooka', 'age': 5}\\n\",\r\n    \">>> spam.setdefault('color', 'black')\\n\",\r\n    \"'black'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam\\n\",\r\n    \"{'color': 'black', 'age': 5, 'name': 'Pooka'}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam.setdefault('color', 'white')\\n\",\r\n    \"'black'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam\\n\",\r\n    \"{'color': 'black', 'age': 5, 'name': 'Pooka'}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Pretty Printing\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import pprint\\n\",\r\n    \">>>\\n\",\r\n    \">>> message = 'It was a bright cold day in April, and the clocks were striking\\n\",\r\n    \">>> thirteen.'\\n\",\r\n    \">>> count = {}\\n\",\r\n    \">>>\\n\",\r\n    \">>> for character in message:\\n\",\r\n    \">>>     count.setdefault(character, 0)\\n\",\r\n    \">>>     count[character] = count[character] + 1\\n\",\r\n    \">>>\\n\",\r\n    \">>> pprint.pprint(count)\\n\",\r\n    \"{' ': 13,\\n\",\r\n    \" ',': 1,\\n\",\r\n    \" '.': 1,\\n\",\r\n    \" 'A': 1,\\n\",\r\n    \" 'I': 1,\\n\",\r\n    \" 'a': 4,\\n\",\r\n    \" 'b': 1,\\n\",\r\n    \" 'c': 3,\\n\",\r\n    \" 'd': 3,\\n\",\r\n    \" 'e': 5,\\n\",\r\n    \" 'g': 2,\\n\",\r\n    \" 'h': 3,\\n\",\r\n    \" 'i': 6,\\n\",\r\n    \" 'k': 2,\\n\",\r\n    \" 'l': 3,\\n\",\r\n    \" 'n': 4,\\n\",\r\n    \" 'o': 2,\\n\",\r\n    \" 'p': 1,\\n\",\r\n    \" 'r': 5,\\n\",\r\n    \" 's': 3,\\n\",\r\n    \" 't': 6,\\n\",\r\n    \" 'w': 2,\\n\",\r\n    \" 'y': 1}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Merge two dictionaries\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"# in Python 3.5+:\\n\",\r\n    \">>> x = {'a': 1, 'b': 2}\\n\",\r\n    \">>> y = {'b': 3, 'c': 4}\\n\",\r\n    \">>> z = {**x, **y}\\n\",\r\n    \">>> z\\n\",\r\n    \"{'c': 4, 'a': 1, 'b': 3}\\n\",\r\n    \"\\n\",\r\n    \"# in Python 2.7\\n\",\r\n    \">>> z = dict(x, **y)\\n\",\r\n    \">>> z\\n\",\r\n    \"{'c': 4, 'a': 1, 'b': 3}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"## sets\\n\",\r\n    \"\\n\",\r\n    \"From the Python 3 [documentation](https://docs.python.org/3/tutorial/datastructures.html)\\n\",\r\n    \"\\n\",\r\n    \"> A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.\\n\",\r\n    \"\\n\",\r\n    \"### Initializing a set\\n\",\r\n    \"\\n\",\r\n    \"There are two ways to create sets: using curly braces `{}` and the bult-in function `set()`\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3}\\n\",\r\n    \">>> s = set([1, 2, 3])\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"When creating an empty set, be sure to not use the curly braces `{}`  or you will get an empty dictionary instead.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {}\\n\",\r\n    \">>> type(s)\\n\",\r\n    \"<class 'dict'>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### sets: unordered collections of unique elements\\n\",\r\n    \"\\n\",\r\n    \"A set automatically remove all the duplicate values.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3, 2, 3, 4}\\n\",\r\n    \">>> s\\n\",\r\n    \"{1, 2, 3, 4}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"And as an unordered data type, they can't be indexed.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3}\\n\",\r\n    \">>> s[0]\\n\",\r\n    \"Traceback (most recent call last):\\n\",\r\n    \"  File \\\"<stdin>\\\", line 1, in <module>\\n\",\r\n    \"TypeError: 'set' object does not support indexing\\n\",\r\n    \">>>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### set add() and update()\\n\",\r\n    \"\\n\",\r\n    \"Using the `add()` method we can add a single element to the set.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3}\\n\",\r\n    \">>> s.add(4)\\n\",\r\n    \">>> s\\n\",\r\n    \"{1, 2, 3, 4}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"And with `update()`, multiple ones .\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3}\\n\",\r\n    \">>> s.update([2, 3, 4, 5, 6])\\n\",\r\n    \">>> s\\n\",\r\n    \"{1, 2, 3, 4, 5, 6}  # remember, sets automatically remove duplicates\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### set remove() and discard()\\n\",\r\n    \"\\n\",\r\n    \"Both methods will remove an element from the set, but `remove()` will raise a `key error` if the value doesn't exist.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3}\\n\",\r\n    \">>> s.remove(3)\\n\",\r\n    \">>> s\\n\",\r\n    \"{1, 2}\\n\",\r\n    \">>> s.remove(3)\\n\",\r\n    \"Traceback (most recent call last):\\n\",\r\n    \"  File \\\"<stdin>\\\", line 1, in <module>\\n\",\r\n    \"KeyError: 3\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"`discard()` won't raise any errors.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s = {1, 2, 3}\\n\",\r\n    \">>> s.discard(3)\\n\",\r\n    \">>> s\\n\",\r\n    \"{1, 2}\\n\",\r\n    \">>> s.discard(3)\\n\",\r\n    \">>>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### set union()\\n\",\r\n    \"\\n\",\r\n    \"`union()` or `|` will create a new set that contains all the elements from the sets provided.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s1 = {1, 2, 3}\\n\",\r\n    \">>> s2 = {3, 4, 5}\\n\",\r\n    \">>> s1.union(s2)  # or 's1 | s2'\\n\",\r\n    \"{1, 2, 3, 4, 5}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### set  intersection\\n\",\r\n    \"\\n\",\r\n    \"`intersection`  or `&`  will return a set containing only the elements that are common to all of them.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s1 = {1, 2, 3}\\n\",\r\n    \">>> s2 = {2, 3, 4}\\n\",\r\n    \">>> s3 = {3, 4, 5}\\n\",\r\n    \">>> s1.intersection(s2, s3)  # or 's1 & s2 & s3'\\n\",\r\n    \"{3}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### set  difference\\n\",\r\n    \"\\n\",\r\n    \"`difference` or `-` will return only the elements that are in one of the sets.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s1 = {1, 2, 3}\\n\",\r\n    \">>> s2 = {2, 3, 4}\\n\",\r\n    \">>> s1.difference(s2)  # or 's1 - s2'\\n\",\r\n    \"{1}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### set symetric_difference\\n\",\r\n    \"\\n\",\r\n    \"`symetric_difference` or `^` will return all the elements that are not common between them.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> s1 = {1, 2, 3}\\n\",\r\n    \">>> s2 = {2, 3, 4}\\n\",\r\n    \">>> s1.symmetric_difference(s2)  # or 's1 ^ s2'\\n\",\r\n    \"{1, 4}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## itertools Module\\n\",\r\n    \"\\n\",\r\n    \"The *itertools* module is a colection of tools intented to be fast and use memory efficiently when handling iterators (like [lists](#lists) or [dictionaries](#dictionaries-and-structuring-data)).\\n\",\r\n    \"\\n\",\r\n    \"From the official [Python 3.x documentation](https://docs.python.org/3/library/itertools.html):\\n\",\r\n    \"\\n\",\r\n    \"> The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.\\n\",\r\n    \"\\n\",\r\n    \"The *itertools* module comes in the standard library and must be imported.\\n\",\r\n    \"\\n\",\r\n    \"The [operator](https://docs.python.org/3/library/operator.html) module will also be used. This module is not necessary when using itertools, but needed for some of the examples below.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### accumulate()\\n\",\r\n    \"\\n\",\r\n    \"Makes an iterator that returns the results of a function.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.accumulate(iterable[, func])\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> data = [1, 2, 3, 4, 5]\\n\",\r\n    \">>> result = itertools.accumulate(data, operator.mul)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"1\\n\",\r\n    \"2\\n\",\r\n    \"6\\n\",\r\n    \"24\\n\",\r\n    \"120\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The operator.mul takes two numbers and multiplies them:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"operator.mul(1, 2)\\n\",\r\n    \"2\\n\",\r\n    \"operator.mul(2, 3)\\n\",\r\n    \"6\\n\",\r\n    \"operator.mul(6, 4)\\n\",\r\n    \"24\\n\",\r\n    \"operator.mul(24, 5)\\n\",\r\n    \"120\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Passing a function is optional:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> data = [5, 2, 6, 4, 5, 9, 1]\\n\",\r\n    \">>> result = itertools.accumulate(data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"5\\n\",\r\n    \"7\\n\",\r\n    \"13\\n\",\r\n    \"17\\n\",\r\n    \"22\\n\",\r\n    \"31\\n\",\r\n    \"32\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"If no function is designated the items will be summed:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"5\\n\",\r\n    \"5 + 2 = 7\\n\",\r\n    \"7 + 6 = 13\\n\",\r\n    \"13 + 4 = 17\\n\",\r\n    \"17 + 5 = 22\\n\",\r\n    \"22 + 9 = 31\\n\",\r\n    \"31 + 1 = 32\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### combinations()\\n\",\r\n    \"\\n\",\r\n    \"Takes an iterable and a integer. This will create all the unique combination that have r members.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.combinations(iterable, r)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> shapes = ['circle', 'triangle', 'square',]\\n\",\r\n    \">>> result = itertools.combinations(shapes, 2)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"('circle', 'triangle')\\n\",\r\n    \"('circle', 'square')\\n\",\r\n    \"('triangle', 'square')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### combinations_with_replacement()\\n\",\r\n    \"\\n\",\r\n    \"Just like combinations(), but allows individual elements to be repeated more than once.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.combinations_with_replacement(iterable, r)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> shapes = ['circle', 'triangle', 'square']\\n\",\r\n    \">>> result = itertools.combinations_with_replacement(shapes, 2)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"('circle', 'circle')\\n\",\r\n    \"('circle', 'triangle')\\n\",\r\n    \"('circle', 'square')\\n\",\r\n    \"('triangle', 'triangle')\\n\",\r\n    \"('triangle', 'square')\\n\",\r\n    \"('square', 'square')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### count()\\n\",\r\n    \"\\n\",\r\n    \"Makes an iterator that returns evenly spaced values starting with number start.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.count(start=0, step=1)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for i in itertools.count(10,3):\\n\",\r\n    \">>>    print(i)\\n\",\r\n    \">>>    if i > 20:\\n\",\r\n    \">>>        break\\n\",\r\n    \"10\\n\",\r\n    \"13\\n\",\r\n    \"16\\n\",\r\n    \"19\\n\",\r\n    \"22\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### cycle()\\n\",\r\n    \"\\n\",\r\n    \"This function cycles through an iterator endlessly.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.cycle(iterable)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']\\n\",\r\n    \">>> for color in itertools.cycle(colors):\\n\",\r\n    \">>>    print(color)\\n\",\r\n    \"red\\n\",\r\n    \"orange\\n\",\r\n    \"yellow\\n\",\r\n    \"green\\n\",\r\n    \"blue\\n\",\r\n    \"violet\\n\",\r\n    \"red\\n\",\r\n    \"orange\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"When reached the end of the iterable it start over again from the beginning.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### chain()\\n\",\r\n    \"\\n\",\r\n    \"Take a series of iterables and return them as one long iterable.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.chain(*iterables)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\\n\",\r\n    \">>> shapes = ['circle', 'triangle', 'square', 'pentagon']\\n\",\r\n    \">>> result = itertools.chain(colors, shapes)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"red\\n\",\r\n    \"orange\\n\",\r\n    \"yellow\\n\",\r\n    \"green\\n\",\r\n    \"blue\\n\",\r\n    \"circle\\n\",\r\n    \"triangle\\n\",\r\n    \"square\\n\",\r\n    \"pentagon\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### compress()\\n\",\r\n    \"\\n\",\r\n    \"Filters one iterable with another.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.compress(data, selectors)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> shapes = ['circle', 'triangle', 'square', 'pentagon']\\n\",\r\n    \">>> selections = [True, False, True, False]\\n\",\r\n    \">>> result = itertools.compress(shapes, selections)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"circle\\n\",\r\n    \"square\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### dropwhile()\\n\",\r\n    \"\\n\",\r\n    \"Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.dropwhile(predicate, iterable)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\\n\",\r\n    \">>> result = itertools.dropwhile(lambda x: x<5, data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"5\\n\",\r\n    \"6\\n\",\r\n    \"7\\n\",\r\n    \"8\\n\",\r\n    \"9\\n\",\r\n    \"10\\n\",\r\n    \"1\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### filterfalse()\\n\",\r\n    \"\\n\",\r\n    \"Makes an iterator that filters elements from iterable returning only those for which the predicate is False.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.filterfalse(predicate, iterable)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\\n\",\r\n    \">>> result = itertools.filterfalse(lambda x: x<5, data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"5\\n\",\r\n    \"6\\n\",\r\n    \"7\\n\",\r\n    \"8\\n\",\r\n    \"9\\n\",\r\n    \"10\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### groupby()\\n\",\r\n    \"\\n\",\r\n    \"Simply put, this function groups things together.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.groupby(iterable, key=None)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> robots = [{\\n\",\r\n    \"    'name': 'blaster',\\n\",\r\n    \"    'faction': 'autobot'\\n\",\r\n    \"}, {\\n\",\r\n    \"    'name': 'galvatron',\\n\",\r\n    \"    'faction': 'decepticon'\\n\",\r\n    \"}, {\\n\",\r\n    \"    'name': 'jazz',\\n\",\r\n    \"    'faction': 'autobot'\\n\",\r\n    \"}, {\\n\",\r\n    \"    'name': 'metroplex',\\n\",\r\n    \"    'faction': 'autobot'\\n\",\r\n    \"}, {\\n\",\r\n    \"    'name': 'megatron',\\n\",\r\n    \"    'faction': 'decepticon'\\n\",\r\n    \"}, {\\n\",\r\n    \"    'name': 'starcream',\\n\",\r\n    \"    'faction': 'decepticon'\\n\",\r\n    \"}]\\n\",\r\n    \">>> for key, group in itertools.groupby(robots, key=lambda x: x['faction']):\\n\",\r\n    \">>>    print(key)\\n\",\r\n    \">>>    print(list(group))\\n\",\r\n    \"autobot\\n\",\r\n    \"[{'name': 'blaster', 'faction': 'autobot'}]\\n\",\r\n    \"decepticon\\n\",\r\n    \"[{'name': 'galvatron', 'faction': 'decepticon'}]\\n\",\r\n    \"autobot\\n\",\r\n    \"[{'name': 'jazz', 'faction': 'autobot'}, {'name': 'metroplex', 'faction': 'autobot'}]\\n\",\r\n    \"decepticon\\n\",\r\n    \"[{'name': 'megatron', 'faction': 'decepticon'}, {'name': 'starcream', 'faction': 'decepticon'}]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### islice()\\n\",\r\n    \"\\n\",\r\n    \"This function is very much like slices. This allows you to cut out a piece of an iterable.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.islice(iterable, start, stop[, step])\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> colors = ['red', 'orange', 'yellow', 'green', 'blue',]\\n\",\r\n    \">>> few_colors = itertools.islice(colors, 2)\\n\",\r\n    \">>> for each in few_colors:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"red\\n\",\r\n    \"orange\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### permutations()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.permutations(iterable, r=None)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> alpha_data = ['a', 'b', 'c']\\n\",\r\n    \">>> result = itertools.permutations(alpha_data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"('a', 'b', 'c')\\n\",\r\n    \"('a', 'c', 'b')\\n\",\r\n    \"('b', 'a', 'c')\\n\",\r\n    \"('b', 'c', 'a')\\n\",\r\n    \"('c', 'a', 'b')\\n\",\r\n    \"('c', 'b', 'a')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### product()\\n\",\r\n    \"\\n\",\r\n    \"Creates the cartesian products from a series of iterables.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> num_data = [1, 2, 3]\\n\",\r\n    \">>> alpha_data = ['a', 'b', 'c']\\n\",\r\n    \">>> result = itertools.product(num_data, alpha_data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \"    print(each)\\n\",\r\n    \"(1, 'a')\\n\",\r\n    \"(1, 'b')\\n\",\r\n    \"(1, 'c')\\n\",\r\n    \"(2, 'a')\\n\",\r\n    \"(2, 'b')\\n\",\r\n    \"(2, 'c')\\n\",\r\n    \"(3, 'a')\\n\",\r\n    \"(3, 'b')\\n\",\r\n    \"(3, 'c')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### repeat()\\n\",\r\n    \"\\n\",\r\n    \"This function will repeat an object over and over again. Unless, there is a times argument.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.repeat(object[, times])\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> for i in itertools.repeat(\\\"spam\\\", 3):\\n\",\r\n    \"    print(i)\\n\",\r\n    \"spam\\n\",\r\n    \"spam\\n\",\r\n    \"spam\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### starmap()\\n\",\r\n    \"\\n\",\r\n    \"Makes an iterator that computes the function using arguments obtained from the iterable.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.starmap(function, iterable)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> data = [(2, 6), (8, 4), (7, 3)]\\n\",\r\n    \">>> result = itertools.starmap(operator.mul, data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"12\\n\",\r\n    \"32\\n\",\r\n    \"21\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### takewhile()\\n\",\r\n    \"\\n\",\r\n    \"The opposite of dropwhile(). Makes an iterator and returns elements from the iterable as long as the predicate is true.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.takwwhile(predicate, iterable)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\\n\",\r\n    \">>> result = itertools.takewhile(lambda x: x<5, data)\\n\",\r\n    \">>> for each in result:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"1\\n\",\r\n    \"2\\n\",\r\n    \"3\\n\",\r\n    \"4\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### tee()\\n\",\r\n    \"\\n\",\r\n    \"Return n independent iterators from a single iterable.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.tee(iterable, n=2)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\\n\",\r\n    \">>> alpha_colors, beta_colors = itertools.tee(colors)\\n\",\r\n    \">>> for each in alpha_colors:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"red\\n\",\r\n    \"orange\\n\",\r\n    \"yellow\\n\",\r\n    \"green\\n\",\r\n    \"blue\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> colors = ['red', 'orange', 'yellow', 'green', 'blue']\\n\",\r\n    \">>> alpha_colors, beta_colors = itertools.tee(colors)\\n\",\r\n    \">>> for each in beta_colors:\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"red\\n\",\r\n    \"orange\\n\",\r\n    \"yellow\\n\",\r\n    \"green\\n\",\r\n    \"blue\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### zip_longest()\\n\",\r\n    \"\\n\",\r\n    \"Makes an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"itertools.zip_longest(*iterables, fillvalue=None)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> colors = ['red', 'orange', 'yellow', 'green', 'blue',]\\n\",\r\n    \">>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,]\\n\",\r\n    \">>> for each in itertools.zip_longest(colors, data, fillvalue=None):\\n\",\r\n    \">>>    print(each)\\n\",\r\n    \"('red', 1)\\n\",\r\n    \"('orange', 2)\\n\",\r\n    \"('yellow', 3)\\n\",\r\n    \"('green', 4)\\n\",\r\n    \"('blue', 5)\\n\",\r\n    \"(None, 6)\\n\",\r\n    \"(None, 7)\\n\",\r\n    \"(None, 8)\\n\",\r\n    \"(None, 9)\\n\",\r\n    \"(None, 10)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Comprehensions\\n\",\r\n    \"\\n\",\r\n    \"### List comprehension\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> a = [1, 3, 5, 7, 9, 11]\\n\",\r\n    \"\\n\",\r\n    \">>> [i - 1 for i in a]\\n\",\r\n    \"[0, 2, 4, 6, 8, 10]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### Set comprehension\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> b = {\\\"abc\\\", \\\"def\\\"}\\n\",\r\n    \">>> {s.upper() for s in b}\\n\",\r\n    \"{\\\"ABC\\\", \\\"DEF}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### Dict comprehension\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> c = {'name': 'Pooka', 'age': 5}\\n\",\r\n    \">>> {v, k for k, v in c.items()}\\n\",\r\n    \"{'Pooka': 'name', 5: 'age'}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"A List comprehension can be generated from a dictionary:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> c = {'name': 'Pooka', 'first_name': 'Oooka'}\\n\",\r\n    \">>> [\\\"{}:{}\\\".format(k.upper(), v.upper()) for k, v in c.items()]\\n\",\r\n    \"['NAME:POOKA', 'FIRST_NAME:OOOKA']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"## Manipulating Strings\\n\",\r\n    \"\\n\",\r\n    \"### Escape Characters\\n\",\r\n    \"\\n\",\r\n    \"| Escape character | Prints as            |\\n\",\r\n    \"| ---------------- | -------------------- |\\n\",\r\n    \"| `\\\\'`             | Single quote         |\\n\",\r\n    \"| `\\\\\\\"`             | Double quote         |\\n\",\r\n    \"| `\\\\t`             | Tab                  |\\n\",\r\n    \"| `\\\\n`             | Newline (line break) |\\n\",\r\n    \"| `\\\\\\\\`             | Backslash            |\\n\",\r\n    \"\\n\",\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print(\\\"Hello there!\\\\nHow are you?\\\\nI\\\\'m doing fine.\\\")\\n\",\r\n    \"Hello there!\\n\",\r\n    \"How are you?\\n\",\r\n    \"I'm doing fine.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Raw Strings\\n\",\r\n    \"\\n\",\r\n    \"A raw string completely ignores all escape characters and prints any backslash that appears in the string.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print(r'That is Carol\\\\'s cat.')\\n\",\r\n    \"That is Carol\\\\'s cat.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Note: mostly used for regular expression definition (see `re` package)\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Multiline Strings with Triple Quotes\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> print('''Dear Alice,\\n\",\r\n    \">>>\\n\",\r\n    \">>> Eve's cat has been arrested for catnapping, cat burglary, and extortion.\\n\",\r\n    \">>>\\n\",\r\n    \">>> Sincerely,\\n\",\r\n    \">>> Bob''')\\n\",\r\n    \"Dear Alice,\\n\",\r\n    \"\\n\",\r\n    \"Eve's cat has been arrested for catnapping, cat burglary, and extortion.\\n\",\r\n    \"\\n\",\r\n    \"Sincerely,\\n\",\r\n    \"Bob\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"To keep a nicer flow in your code, you can use the `dedent` function from the `textwrap` standard package.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from textwrap import dedent\\n\",\r\n    \">>>\\n\",\r\n    \">>> def my_function():\\n\",\r\n    \">>>     print('''\\n\",\r\n    \">>>         Dear Alice,\\n\",\r\n    \">>>\\n\",\r\n    \">>>         Eve's cat has been arrested for catnapping, cat burglary, and extortion.\\n\",\r\n    \">>>\\n\",\r\n    \">>>         Sincerely,\\n\",\r\n    \">>>         Bob\\n\",\r\n    \">>>         ''').strip()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"This generates the same string than before.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Indexing and Slicing Strings\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"H   e   l   l   o       w   o   r   l   d    !\\n\",\r\n    \"0   1   2   3   4   5   6   7   8   9   10   11\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'Hello world!'\\n\",\r\n    \"\\n\",\r\n    \">>> spam[0]\\n\",\r\n    \"'H'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[4]\\n\",\r\n    \"'o'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[-1]\\n\",\r\n    \"'!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Slicing:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"\\n\",\r\n    \">>> spam[0:5]\\n\",\r\n    \"'Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[:5]\\n\",\r\n    \"'Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[6:]\\n\",\r\n    \"'world!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[6:-1]\\n\",\r\n    \"'world'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[:-1]\\n\",\r\n    \"'Hello world'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam[::-1]\\n\",\r\n    \"'!dlrow olleH'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'Hello world!'\\n\",\r\n    \">>> fizz = spam[0:5]\\n\",\r\n    \">>> fizz\\n\",\r\n    \"'Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The in and not in Operators with Strings\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello' in 'Hello World'\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello' in 'Hello'\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'HELLO' in 'Hello World'\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> '' in 'spam'\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'cats' not in 'cats and dogs'\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### The in and not in Operators with list\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> a = [1, 2, 3, 4]\\n\",\r\n    \">>> 5 in a\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 2 in a\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The upper(), lower(), isupper(), and islower() String Methods\\n\",\r\n    \"\\n\",\r\n    \"`upper()` and `lower()`:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'Hello world!'\\n\",\r\n    \">>> spam = spam.upper()\\n\",\r\n    \">>> spam\\n\",\r\n    \"'HELLO WORLD!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = spam.lower()\\n\",\r\n    \">>> spam\\n\",\r\n    \"'hello world!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"isupper() and islower():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'Hello world!'\\n\",\r\n    \">>> spam.islower()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam.isupper()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'HELLO'.isupper()\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'abc12345'.islower()\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> '12345'.islower()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> '12345'.isupper()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The isX String Methods\\n\",\r\n    \"\\n\",\r\n    \"- **isalpha()** returns True if the string consists only of letters and is not blank.\\n\",\r\n    \"- **isalnum()** returns True if the string consists only of lettersand numbers and is not blank.\\n\",\r\n    \"- **isdecimal()** returns True if the string consists only ofnumeric characters and is not blank.\\n\",\r\n    \"- **isspace()** returns True if the string consists only of spaces,tabs, and new-lines and is not blank.\\n\",\r\n    \"- **istitle()** returns True if the string consists only of wordsthat begin with an uppercase letter followed by onlylowercase letters.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The startswith() and endswith() String Methods\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello world!'.startswith('Hello')\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello world!'.endswith('world!')\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'abc123'.startswith('abcdef')\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'abc123'.endswith('12')\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello world!'.startswith('Hello world!')\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello world!'.endswith('Hello world!')\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The join() and split() String Methods\\n\",\r\n    \"\\n\",\r\n    \"join():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> ', '.join(['cats', 'rats', 'bats'])\\n\",\r\n    \"'cats, rats, bats'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> ' '.join(['My', 'name', 'is', 'Simon'])\\n\",\r\n    \"'My name is Simon'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'ABC'.join(['My', 'name', 'is', 'Simon'])\\n\",\r\n    \"'MyABCnameABCisABCSimon'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"split():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'My name is Simon'.split()\\n\",\r\n    \"['My', 'name', 'is', 'Simon']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'MyABCnameABCisABCSimon'.split('ABC')\\n\",\r\n    \"['My', 'name', 'is', 'Simon']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'My name is Simon'.split('m')\\n\",\r\n    \"['My na', 'e is Si', 'on']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Justifying Text with rjust(), ljust(), and center()\\n\",\r\n    \"\\n\",\r\n    \"rjust() and ljust():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.rjust(10)\\n\",\r\n    \"'     Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.rjust(20)\\n\",\r\n    \"'               Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello World'.rjust(20)\\n\",\r\n    \"'         Hello World'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.ljust(10)\\n\",\r\n    \"'Hello     '\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"An optional second argument to rjust() and ljust() will specify a fill character other than a space character. Enter the following into the interactive shell:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.rjust(20, '*')\\n\",\r\n    \"'***************Hello'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.ljust(20, '-')\\n\",\r\n    \"'Hello---------------'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"center():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.center(20)\\n\",\r\n    \"'       Hello       '\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> 'Hello'.center(20, '=')\\n\",\r\n    \"'=======Hello========'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Removing Whitespace with strip(), rstrip(), and lstrip()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = '    Hello World     '\\n\",\r\n    \">>> spam.strip()\\n\",\r\n    \"'Hello World'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam.lstrip()\\n\",\r\n    \"'Hello World '\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam.rstrip()\\n\",\r\n    \"'    Hello World'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> spam = 'SpamSpamBaconSpamEggsSpamSpam'\\n\",\r\n    \">>> spam.strip('ampS')\\n\",\r\n    \"'BaconSpamEggs'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Copying and Pasting Strings with the pyperclip Module (need pip install)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import pyperclip\\n\",\r\n    \"\\n\",\r\n    \">>> pyperclip.copy('Hello world!')\\n\",\r\n    \"\\n\",\r\n    \">>> pyperclip.paste()\\n\",\r\n    \"'Hello world!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## String Formatting\\n\",\r\n    \"\\n\",\r\n    \"### % operator\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> name = 'Pete'\\n\",\r\n    \">>> 'Hello %s' % name\\n\",\r\n    \"\\\"Hello Pete\\\"\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"We can use the `%x` format specifier to convert an int value to a string:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> num = 5\\n\",\r\n    \">>> 'I have %x apples' % num\\n\",\r\n    \"\\\"I have 5 apples\\\"\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Note: For new code, using [str.format](#string-formatting-strformat) or [f-strings](#formatted-string-literals-or-f-strings-python-36) (Python 3.6+) is strongly recommended over the `%` operator.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### String Formatting (str.format)\\n\",\r\n    \"\\n\",\r\n    \"Python 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> name = 'John'\\n\",\r\n    \">>> age = 20'\\n\",\r\n    \"\\n\",\r\n    \">>> \\\"Hello I'm {}, my age is {}\\\".format(name, age)\\n\",\r\n    \"\\\"Hello I'm John, my age is 20\\\"\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> \\\"Hello I'm {0}, my age is {1}\\\".format(name, age)\\n\",\r\n    \"\\\"Hello I'm John, my age is 20\\\"\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The official [Python 3.x documentation](https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting) recommend `str.format` over the `%` operator:\\n\",\r\n    \"\\n\",\r\n    \"> The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Lazy string formatting\\n\",\r\n    \"\\n\",\r\n    \"You would only use `%s` string formatting on functions that can do lazy parameters evaluation,\\n\",\r\n    \"the most common being logging:\\n\",\r\n    \"\\n\",\r\n    \"Prefer:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> name = \\\"alice\\\"\\n\",\r\n    \">>> logging.debug(\\\"User name: %s\\\", name)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Over:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> logging.debug(\\\"User name: {}\\\".format(name))\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Or:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> logging.debug(\\\"User name: \\\" + name)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Formatted String Literals or f-strings (Python 3.6+)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> name = 'Elizabeth'\\n\",\r\n    \">>> f'Hello {name}!'\\n\",\r\n    \"'Hello Elizabeth!\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"It is even possible to do inline arithmetic with it:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> a = 5\\n\",\r\n    \">>> b = 10\\n\",\r\n    \">>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'\\n\",\r\n    \"'Five plus ten is 15 and not 30.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Template Strings\\n\",\r\n    \"\\n\",\r\n    \" A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from string import Template\\n\",\r\n    \">>> name = 'Elizabeth'\\n\",\r\n    \">>> t = Template('Hey $name!')\\n\",\r\n    \">>> t.substitute(name=name)\\n\",\r\n    \"'Hey Elizabeth!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Regular Expressions\\n\",\r\n    \"\\n\",\r\n    \"1. Import the regex module with `import re`.\\n\",\r\n    \"1. Create a Regex object with the `re.compile()` function. (Remember to use a raw string.)\\n\",\r\n    \"1. Pass the string you want to search into the Regex object’s `search()` method. This returns a `Match` object.\\n\",\r\n    \"1. Call the Match object’s `group()` method to return a string of the actual matched text.\\n\",\r\n    \"\\n\",\r\n    \"All the regex functions in Python are in the re module:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import re\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching Regex Objects\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> phone_num_regex = re.compile(r'\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d')\\n\",\r\n    \"\\n\",\r\n    \">>> mo = phone_num_regex.search('My number is 415-555-4242.')\\n\",\r\n    \"\\n\",\r\n    \">>> print('Phone number found: {}'.format(mo.group()))\\n\",\r\n    \"Phone number found: 415-555-4242\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Grouping with Parentheses\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> phone_num_regex = re.compile(r'(\\\\d\\\\d\\\\d)-(\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d)')\\n\",\r\n    \"\\n\",\r\n    \">>> mo = phone_num_regex.search('My number is 415-555-4242.')\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group(1)\\n\",\r\n    \"'415'\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group(2)\\n\",\r\n    \"'555-4242'\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group(0)\\n\",\r\n    \"'415-555-4242'\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group()\\n\",\r\n    \"'415-555-4242'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"To retrieve all the groups at once: use the groups() method—note the plural form for the name.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> mo.groups()\\n\",\r\n    \"('415', '555-4242')\\n\",\r\n    \"\\n\",\r\n    \">>> area_code, main_number = mo.groups()\\n\",\r\n    \"\\n\",\r\n    \">>> print(area_code)\\n\",\r\n    \"415\\n\",\r\n    \"\\n\",\r\n    \">>> print(main_number)\\n\",\r\n    \"555-4242\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching Multiple Groups with the Pipe\\n\",\r\n    \"\\n\",\r\n    \"The | character is called a pipe. You can use it anywhere you want to match one of many expressions. For example, the regular expression r'Batman|Tina Fey' will match either 'Batman' or 'Tina Fey'.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> hero_regex = re.compile (r'Batman|Tina Fey')\\n\",\r\n    \"\\n\",\r\n    \">>> mo1 = hero_regex.search('Batman and Tina Fey.')\\n\",\r\n    \"\\n\",\r\n    \">>> mo1.group()\\n\",\r\n    \"'Batman'\\n\",\r\n    \"\\n\",\r\n    \">>> mo2 = hero_regex.search('Tina Fey and Batman.')\\n\",\r\n    \"\\n\",\r\n    \">>> mo2.group()\\n\",\r\n    \"'Tina Fey'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can also use the pipe to match one of several patterns as part of your regex:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> bat_regex = re.compile(r'Bat(man|mobile|copter|bat)')\\n\",\r\n    \"\\n\",\r\n    \">>> mo = bat_regex.search('Batmobile lost a wheel')\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group()\\n\",\r\n    \"'Batmobile'\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group(1)\\n\",\r\n    \"'mobile'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Optional Matching with the Question Mark\\n\",\r\n    \"\\n\",\r\n    \"The ? character flags the group that precedes it as an optional part of the pattern.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> bat_regex = re.compile(r'Bat(wo)?man')\\n\",\r\n    \">>> mo1 = bat_regex.search('The Adventures of Batman')\\n\",\r\n    \">>> mo1.group()\\n\",\r\n    \"'Batman'\\n\",\r\n    \"\\n\",\r\n    \">>> mo2 = bat_regex.search('The Adventures of Batwoman')\\n\",\r\n    \">>> mo2.group()\\n\",\r\n    \"'Batwoman'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching Zero or More with the Star\\n\",\r\n    \"\\n\",\r\n    \"The * (called the star or asterisk) means “match zero or more”—the group that precedes the star can occur any number of times in the text.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> bat_regex = re.compile(r'Bat(wo)*man')\\n\",\r\n    \">>> mo1 = bat_regex.search('The Adventures of Batman')\\n\",\r\n    \">>> mo1.group()\\n\",\r\n    \"'Batman'\\n\",\r\n    \"\\n\",\r\n    \">>> mo2 = bat_regex.search('The Adventures of Batwoman')\\n\",\r\n    \">>> mo2.group()\\n\",\r\n    \"'Batwoman'\\n\",\r\n    \"\\n\",\r\n    \">>> mo3 = bat_regex.search('The Adventures of Batwowowowoman')\\n\",\r\n    \">>> mo3.group()\\n\",\r\n    \"'Batwowowowoman'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching One or More with the Plus\\n\",\r\n    \"\\n\",\r\n    \"While * means “match zero or more,” the + (or plus) means “match one or more”. The group preceding a plus must appear at least once. It is not optional:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> bat_regex = re.compile(r'Bat(wo)+man')\\n\",\r\n    \">>> mo1 = bat_regex.search('The Adventures of Batwoman')\\n\",\r\n    \">>> mo1.group()\\n\",\r\n    \"'Batwoman'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> mo2 = bat_regex.search('The Adventures of Batwowowowoman')\\n\",\r\n    \">>> mo2.group()\\n\",\r\n    \"'Batwowowowoman'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> mo3 = bat_regex.search('The Adventures of Batman')\\n\",\r\n    \">>> mo3 is None\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching Specific Repetitions with Curly Brackets\\n\",\r\n    \"\\n\",\r\n    \"If you have a group that you want to repeat a specific number of times, follow the group in your regex with a number in curly brackets. For example, the regex (Ha){3} will match the string 'HaHaHa', but it will not match 'HaHa', since the latter has only two repeats of the (Ha) group.\\n\",\r\n    \"\\n\",\r\n    \"Instead of one number, you can specify a range by writing a minimum, a comma, and a maximum in between the curly brackets. For example, the regex (Ha){3,5} will match 'HaHaHa', 'HaHaHaHa', and 'HaHaHaHaHa'.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> ha_regex = re.compile(r'(Ha){3}')\\n\",\r\n    \">>> mo1 = ha_regex.search('HaHaHa')\\n\",\r\n    \">>> mo1.group()\\n\",\r\n    \"'HaHaHa'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> mo2 = ha_regex.search('Ha')\\n\",\r\n    \">>> mo2 is None\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Greedy and Nongreedy Matching\\n\",\r\n    \"\\n\",\r\n    \"Python’s regular expressions are greedy by default, which means that in ambiguous situations they will match the longest string possible. The non-greedy version of the curly brackets, which matches the shortest string possible, has the closing curly bracket followed by a question mark.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> greedy_ha_regex = re.compile(r'(Ha){3,5}')\\n\",\r\n    \">>> mo1 = greedy_ha_regex.search('HaHaHaHaHa')\\n\",\r\n    \">>> mo1.group()\\n\",\r\n    \"'HaHaHaHaHa'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> nongreedy_ha_regex = re.compile(r'(Ha){3,5}?')\\n\",\r\n    \">>> mo2 = nongreedy_ha_regex.search('HaHaHaHaHa')\\n\",\r\n    \">>> mo2.group()\\n\",\r\n    \"'HaHaHa'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The findall() Method\\n\",\r\n    \"\\n\",\r\n    \"In addition to the search() method, Regex objects also have a findall() method. While search() will return a Match object of the first matched text in the searched string, the findall() method will return the strings of every match in the searched string.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> phone_num_regex = re.compile(r'\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d') # has no groups\\n\",\r\n    \"\\n\",\r\n    \">>> phone_num_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')\\n\",\r\n    \"['415-555-9999', '212-555-0000']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"To summarize what the findall() method returns, remember the following:\\n\",\r\n    \"\\n\",\r\n    \"- When called on a regex with no groups, such as \\\\d-\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d, the method findall() returns a list of ng matches, such as ['415-555-9999', '212-555-0000'].\\n\",\r\n    \"\\n\",\r\n    \"- When called on a regex that has groups, such as (\\\\d\\\\d\\\\d)-d\\\\d)-(\\\\d\\\\ d\\\\d\\\\d), the method findall() returns a list of es of strings (one string for each group), such as [('415', ', '9999'), ('212', '555', '0000')].\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Making Your Own Character Classes\\n\",\r\n    \"\\n\",\r\n    \"There are times when you want to match a set of characters but the shorthand character classes (\\\\d, \\\\w, \\\\s, and so on) are too broad. You can define your own character class using square brackets. For example, the character class [aeiouAEIOU] will match any vowel, both lowercase and uppercase.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> vowel_regex = re.compile(r'[aeiouAEIOU]')\\n\",\r\n    \"\\n\",\r\n    \">>> vowel_regex.findall('Robocop eats baby food. BABY FOOD.')\\n\",\r\n    \"['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can also include ranges of letters or numbers by using a hyphen. For example, the character class [a-zA-Z0-9] will match all lowercase letters, uppercase letters, and numbers.\\n\",\r\n    \"\\n\",\r\n    \"By placing a caret character (^) just after the character class’s opening bracket, you can make a negative character class. A negative character class will match all the characters that are not in the character class. For example, enter the following into the interactive shell:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> consonant_regex = re.compile(r'[^aeiouAEIOU]')\\n\",\r\n    \"\\n\",\r\n    \">>> consonant_regex.findall('Robocop eats baby food. BABY FOOD.')\\n\",\r\n    \"['R', 'b', 'c', 'p', ' ', 't', 's', ' ', 'b', 'b', 'y', ' ', 'f', 'd', '.', '\\n\",\r\n    \"', 'B', 'B', 'Y', ' ', 'F', 'D', '.']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The Caret and Dollar Sign Characters\\n\",\r\n    \"\\n\",\r\n    \"- You can also use the caret symbol (^) at the start of a regex to indicate that a match must occur at the beginning of the searched text.\\n\",\r\n    \"\\n\",\r\n    \"- Likewise, you can put a dollar sign ($) at the end of the regex to indicate the string must end with this regex pattern.\\n\",\r\n    \"\\n\",\r\n    \"- And you can use the ^ and $ together to indicate that the entire string must match the regex—that is, it’s not enough for a match to be made on some subset of the string.\\n\",\r\n    \"\\n\",\r\n    \"The r'^Hello' regular expression string matches strings that begin with 'Hello':\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> begins_with_hello = re.compile(r'^Hello')\\n\",\r\n    \"\\n\",\r\n    \">>> begins_with_hello.search('Hello world!')\\n\",\r\n    \"<_sre.SRE_Match object; span=(0, 5), match='Hello'>\\n\",\r\n    \"\\n\",\r\n    \">>> begins_with_hello.search('He said hello.') is None\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The r'\\\\d$' regular expression string matches strings that end with a numeric character from 0 to 9:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> whole_string_is_num = re.compile(r'^\\\\d+$')\\n\",\r\n    \"\\n\",\r\n    \">>> whole_string_is_num.search('1234567890')\\n\",\r\n    \"<_sre.SRE_Match object; span=(0, 10), match='1234567890'>\\n\",\r\n    \"\\n\",\r\n    \">>> whole_string_is_num.search('12345xyz67890') is None\\n\",\r\n    \"True\\n\",\r\n    \"\\n\",\r\n    \">>> whole_string_is_num.search('12 34567890') is None\\n\",\r\n    \"True\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The Wildcard Character\\n\",\r\n    \"\\n\",\r\n    \"The . (or dot) character in a regular expression is called a wildcard and will match any character except for a newline:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> at_regex = re.compile(r'.at')\\n\",\r\n    \"\\n\",\r\n    \">>> at_regex.findall('The cat in the hat sat on the flat mat.')\\n\",\r\n    \"['cat', 'hat', 'sat', 'lat', 'mat']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching Everything with Dot-Star\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> name_regex = re.compile(r'First Name: (.*) Last Name: (.*)')\\n\",\r\n    \"\\n\",\r\n    \">>> mo = name_regex.search('First Name: Al Last Name: Sweigart')\\n\",\r\n    \"\\n\",\r\n    \">>> mo.group(1)\\n\",\r\n    \"'Al'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> mo.group(2)\\n\",\r\n    \"'Sweigart'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The dot-star uses greedy mode: It will always try to match as much text as possible. To match any and all text in a nongreedy fashion, use the dot, star, and question mark (.*?). The question mark tells Python to match in a nongreedy way:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> nongreedy_regex = re.compile(r'<.*?>')\\n\",\r\n    \">>> mo = nongreedy_regex.search('<To serve man> for dinner.>')\\n\",\r\n    \">>> mo.group()\\n\",\r\n    \"'<To serve man>'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> greedy_regex = re.compile(r'<.*>')\\n\",\r\n    \">>> mo = greedy_regex.search('<To serve man> for dinner.>')\\n\",\r\n    \">>> mo.group()\\n\",\r\n    \"'<To serve man> for dinner.>'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Matching Newlines with the Dot Character\\n\",\r\n    \"\\n\",\r\n    \"The dot-star will match everything except a newline. By passing re.DOTALL as the second argument to re.compile(), you can make the dot character match all characters, including the newline character:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> no_newline_regex = re.compile('.*')\\n\",\r\n    \">>> no_newline_regex.search('Serve the public trust.\\\\nProtect the innocent.\\\\nUphold the law.').group()\\n\",\r\n    \"'Serve the public trust.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> newline_regex = re.compile('.*', re.DOTALL)\\n\",\r\n    \">>> newline_regex.search('Serve the public trust.\\\\nProtect the innocent.\\\\nUphold the law.').group()\\n\",\r\n    \"'Serve the public trust.\\\\nProtect the innocent.\\\\nUphold the law.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Review of Regex Symbols\\n\",\r\n    \"\\n\",\r\n    \"| Symbol                   | Matches                                                      |\\n\",\r\n    \"| ------------------------ | ------------------------------------------------------------ |\\n\",\r\n    \"| `?`                      | zero or one of the preceding group.                          |\\n\",\r\n    \"| `*`                      | zero or more of the preceding group.                         |\\n\",\r\n    \"| `+`                      | one or more of the preceding group.                          |\\n\",\r\n    \"| `{n}`                    | exactly n of the preceding group.                            |\\n\",\r\n    \"| `{n,}`                   | n or more of the preceding group.                            |\\n\",\r\n    \"| `{,m}`                   | 0 to m of the preceding group.                               |\\n\",\r\n    \"| `{n,m}`                  | at least n and at most m of the preceding p.                 |\\n\",\r\n    \"| `{n,m}?` or `*?` or `+?` | performs a nongreedy match of the preceding p.               |\\n\",\r\n    \"| `^spam`                  | means the string must begin with spam.                       |\\n\",\r\n    \"| `spam$`                  | means the string must end with spam.                         |\\n\",\r\n    \"| `.`                      | any character, except newline characters.                    |\\n\",\r\n    \"| `\\\\d`, `\\\\w`, and `\\\\s`     | a digit, word, or space character, ectively.                 |\\n\",\r\n    \"| `\\\\D`, `\\\\W`, and `\\\\S`     | anything except a digit, word, or space acter, respectively. |\\n\",\r\n    \"| `[abc]`                  | any character between the brackets (such as a, b, ).         |\\n\",\r\n    \"| `[^abc]`                 | any character that isn’t between the brackets.              |\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Case-Insensitive Matching\\n\",\r\n    \"\\n\",\r\n    \"To make your regex case-insensitive, you can pass re.IGNORECASE or re.I as a second argument to re.compile():\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> robocop = re.compile(r'robocop', re.I)\\n\",\r\n    \"\\n\",\r\n    \">>> robocop.search('Robocop is part man, part machine, all cop.').group()\\n\",\r\n    \"'Robocop'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> robocop.search('ROBOCOP protects the innocent.').group()\\n\",\r\n    \"'ROBOCOP'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> robocop.search('Al, why does your programming book talk about robocop so much?').group()\\n\",\r\n    \"'robocop'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Substituting Strings with the sub() Method\\n\",\r\n    \"\\n\",\r\n    \"The sub() method for Regex objects is passed two arguments:\\n\",\r\n    \"\\n\",\r\n    \"1. The first argument is a string to replace any matches.\\n\",\r\n    \"1. The second is the string for the regular expression.\\n\",\r\n    \"\\n\",\r\n    \"The sub() method returns a string with the substitutions applied:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> names_regex = re.compile(r'Agent \\\\w+')\\n\",\r\n    \"\\n\",\r\n    \">>> names_regex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')\\n\",\r\n    \"'CENSORED gave the secret documents to CENSORED.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Another example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> agent_names_regex = re.compile(r'Agent (\\\\w)\\\\w*')\\n\",\r\n    \"\\n\",\r\n    \">>> agent_names_regex.sub(r'\\\\1****', 'Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')\\n\",\r\n    \"A**** told C**** that E**** knew B**** was a double agent.'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Managing Complex Regexes\\n\",\r\n    \"\\n\",\r\n    \"To tell the re.compile() function to ignore whitespace and comments inside the regular expression string, “verbose mode” can be enabled by passing the variable re.VERBOSE as the second argument to re.compile().\\n\",\r\n    \"\\n\",\r\n    \"Now instead of a hard-to-read regular expression like this:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"phone_regex = re.compile(r'((\\\\d{3}|\\\\(\\\\d{3}\\\\))?(\\\\s|-|\\\\.)?\\\\d{3}(\\\\s|-|\\\\.)\\\\d{4}(\\\\s*(ext|x|ext.)\\\\s*\\\\d{2,5})?)')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"you can spread the regular expression over multiple lines with comments like this:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"phone_regex = re.compile(r'''(\\n\",\r\n    \"    (\\\\d{3}|\\\\(\\\\d{3}\\\\))?            # area code\\n\",\r\n    \"    (\\\\s|-|\\\\.)?                    # separator\\n\",\r\n    \"    \\\\d{3}                         # first 3 digits\\n\",\r\n    \"    (\\\\s|-|\\\\.)                     # separator\\n\",\r\n    \"    \\\\d{4}                         # last 4 digits\\n\",\r\n    \"    (\\\\s*(ext|x|ext.)\\\\s*\\\\d{2,5})?  # extension\\n\",\r\n    \"    )''', re.VERBOSE)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Handling File and Directory Paths\\n\",\r\n    \"\\n\",\r\n    \"There are two main modules in Python that deals with path manipulation.\\n\",\r\n    \"One is the `os.path` module and the other is the `pathlib` module.\\n\",\r\n    \"The `pathlib` module was added in Python 3.4, offering an object-oriented way\\n\",\r\n    \"to handle file system paths.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Backslash on Windows and Forward Slash on OS X and Linux\\n\",\r\n    \"\\n\",\r\n    \"On Windows, paths are written using backslashes (\\\\) as the separator between\\n\",\r\n    \"folder names. On Unix based operating system such as macOS, Linux, and BSDs,\\n\",\r\n    \"the forward slash (/) is used as the path separator. Joining paths can be\\n\",\r\n    \"a headache if your code needs to work on different platforms.\\n\",\r\n    \"\\n\",\r\n    \"Fortunately, Python provides easy ways to handle this. We will showcase\\n\",\r\n    \"how to deal with this with both `os.path.join` and `pathlib.Path.joinpath`\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path.join` on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \"\\n\",\r\n    \">>> os.path.join('usr', 'bin', 'spam')\\n\",\r\n    \"'usr\\\\\\\\bin\\\\\\\\spam'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"And using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \"\\n\",\r\n    \">>> print(Path('usr').joinpath('bin').joinpath('spam'))\\n\",\r\n    \"usr/bin/spam\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"`pathlib` also provides a shortcut to joinpath using the `/` operator:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \"\\n\",\r\n    \">>> print(Path('usr') / 'bin' / 'spam')\\n\",\r\n    \"usr/bin/spam\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Notice the path separator is different between Windows and Unix based operating\\n\",\r\n    \"system, that's why you want to use one of the above methods instead of\\n\",\r\n    \"adding strings together to join paths together.\\n\",\r\n    \"\\n\",\r\n    \"Joining paths is helpful if you need to create different file paths under\\n\",\r\n    \"the same directory.\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path.join` on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']\\n\",\r\n    \"\\n\",\r\n    \">>> for filename in my_files:\\n\",\r\n    \">>>     print(os.path.join('C:\\\\\\\\Users\\\\\\\\asweigart', filename))\\n\",\r\n    \"C:\\\\Users\\\\asweigart\\\\accounts.txt\\n\",\r\n    \"C:\\\\Users\\\\asweigart\\\\details.csv\\n\",\r\n    \"C:\\\\Users\\\\asweigart\\\\invite.docx\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']\\n\",\r\n    \">>> home = Path.home()\\n\",\r\n    \">>> for filename in my_files:\\n\",\r\n    \">>>     print(home / filename)\\n\",\r\n    \"/home/asweigart/accounts.txt\\n\",\r\n    \"/home/asweigart/details.csv\\n\",\r\n    \"/home/asweigart/invite.docx\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### The Current Working Directory\\n\",\r\n    \"\\n\",\r\n    \"Using `os` on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \"\\n\",\r\n    \">>> os.getcwd()\\n\",\r\n    \"'C:\\\\\\\\Python34'\\n\",\r\n    \">>> os.chdir('C:\\\\\\\\Windows\\\\\\\\System32')\\n\",\r\n    \"\\n\",\r\n    \">>> os.getcwd()\\n\",\r\n    \"'C:\\\\\\\\Windows\\\\\\\\System32'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> from os import chdir\\n\",\r\n    \"\\n\",\r\n    \">>> print(Path.cwd())\\n\",\r\n    \"/home/asweigart\\n\",\r\n    \"\\n\",\r\n    \">>> chdir('/usr/lib/python3.6')\\n\",\r\n    \">>> print(Path.cwd())\\n\",\r\n    \"/usr/lib/python3.6\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Creating New Folders\\n\",\r\n    \"\\n\",\r\n    \"Using `os` on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.makedirs('C:\\\\\\\\delicious\\\\\\\\walnut\\\\\\\\waffles')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> cwd = Path.cwd()\\n\",\r\n    \">>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir()\\n\",\r\n    \"Traceback (most recent call last):\\n\",\r\n    \"  File \\\"<stdin>\\\", line 1, in <module>\\n\",\r\n    \"  File \\\"/usr/lib/python3.6/pathlib.py\\\", line 1226, in mkdir\\n\",\r\n    \"    self._accessor.mkdir(self, mode)\\n\",\r\n    \"  File \\\"/usr/lib/python3.6/pathlib.py\\\", line 387, in wrapped\\n\",\r\n    \"    return strfunc(str(pathobj), *args)\\n\",\r\n    \"FileNotFoundError: [Errno 2] No such file or directory: '/home/asweigart/delicious/walnut/waffles'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Oh no, we got a nasty error! The reason is that the 'delicious' directory does\\n\",\r\n    \"not exist, so we cannot make the 'walnut' and the 'waffles' directories under\\n\",\r\n    \"it. To fix this, do:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> cwd = Path.cwd()\\n\",\r\n    \">>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir(parents=True)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"And all is good :)\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Absolute vs. Relative Paths\\n\",\r\n    \"\\n\",\r\n    \"There are two ways to specify a file path.\\n\",\r\n    \"\\n\",\r\n    \"- An absolute path, which always begins with the root folder\\n\",\r\n    \"- A relative path, which is relative to the program’s current working directory\\n\",\r\n    \"\\n\",\r\n    \"There are also the dot (.) and dot-dot (..) folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Handling Absolute and Relative Paths\\n\",\r\n    \"\\n\",\r\n    \"To see if a path is an absolute path:\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.path.isabs('/')\\n\",\r\n    \"True\\n\",\r\n    \">>> os.path.isabs('..')\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> Path('/').is_absolute()\\n\",\r\n    \"True\\n\",\r\n    \">>> Path('..').is_absolute()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can extract an absolute path with both `os.path` and `pathlib`\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.getcwd()\\n\",\r\n    \"'/home/asweigart'\\n\",\r\n    \">>> os.path.abspath('..')\\n\",\r\n    \"'/home'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"from pathlib import Path\\n\",\r\n    \"print(Path.cwd())\\n\",\r\n    \"/home/asweigart\\n\",\r\n    \"print(Path('..').resolve())\\n\",\r\n    \"/home\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"You can get a relative path from a starting path to another path.\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.path.relpath('/etc/passwd', '/')\\n\",\r\n    \"'etc/passwd'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> print(Path('/etc/passwd').relative_to('/'))\\n\",\r\n    \"etc/passwd\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Checking Path Validity\\n\",\r\n    \"\\n\",\r\n    \"Checking if a file/directory exists:\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import os\\n\",\r\n    \">>> os.path.exists('.')\\n\",\r\n    \"True\\n\",\r\n    \">>> os.path.exists('setup.py')\\n\",\r\n    \"True\\n\",\r\n    \">>> os.path.exists('/etc')\\n\",\r\n    \"True\\n\",\r\n    \">>> os.path.exists('nonexistentfile')\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"from pathlib import Path\\n\",\r\n    \">>> Path('.').exists()\\n\",\r\n    \"True\\n\",\r\n    \">>> Path('setup.py').exists()\\n\",\r\n    \"True\\n\",\r\n    \">>> Path('/etc').exists()\\n\",\r\n    \"True\\n\",\r\n    \">>> Path('nonexistentfile').exists()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Checking if a path is a file:\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.path.isfile('setup.py')\\n\",\r\n    \"True\\n\",\r\n    \">>> os.path.isfile('/home')\\n\",\r\n    \"False\\n\",\r\n    \">>> os.path.isfile('nonexistentfile')\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> Path('setup.py').is_file()\\n\",\r\n    \"True\\n\",\r\n    \">>> Path('/home').is_file()\\n\",\r\n    \"False\\n\",\r\n    \">>> Path('nonexistentfile').is_file()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Checking if a path is a directory:\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.path.isdir('/')\\n\",\r\n    \"True\\n\",\r\n    \">>> os.path.isdir('setup.py')\\n\",\r\n    \"False\\n\",\r\n    \">>> os.path.isdir('/spam')\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> Path('/').is_dir()\\n\",\r\n    \"True\\n\",\r\n    \">>> Path('setup.py').is_dir()\\n\",\r\n    \"False\\n\",\r\n    \">>> Path('/spam').is_dir()\\n\",\r\n    \"False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Finding File Sizes and Folder Contents\\n\",\r\n    \"\\n\",\r\n    \"Getting a file's size in bytes:\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path` on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.path.getsize('C:\\\\\\\\Windows\\\\\\\\System32\\\\\\\\calc.exe')\\n\",\r\n    \"776192\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> stat = Path('/bin/python3.6').stat()\\n\",\r\n    \">>> print(stat) # stat contains some other information about the file as well\\n\",\r\n    \"os.stat_result(st_mode=33261, st_ino=141087, st_dev=2051, st_nlink=2, st_uid=0,\\n\",\r\n    \"--snip--\\n\",\r\n    \"st_gid=0, st_size=10024, st_atime=1517725562, st_mtime=1515119809, st_ctime=1517261276)\\n\",\r\n    \">>> print(stat.st_size) # size in bytes\\n\",\r\n    \"10024\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Listing directory contents using `os.listdir` on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> os.listdir('C:\\\\\\\\Windows\\\\\\\\System32')\\n\",\r\n    \"['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',\\n\",\r\n    \"--snip--\\n\",\r\n    \"'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Listing directory contents using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> for f in Path('/usr/bin').iterdir():\\n\",\r\n    \">>>     print(f)\\n\",\r\n    \"...\\n\",\r\n    \"/usr/bin/tiff2rgba\\n\",\r\n    \"/usr/bin/iconv\\n\",\r\n    \"/usr/bin/ldd\\n\",\r\n    \"/usr/bin/cache_restore\\n\",\r\n    \"/usr/bin/udiskie\\n\",\r\n    \"/usr/bin/unix2dos\\n\",\r\n    \"/usr/bin/t1reencode\\n\",\r\n    \"/usr/bin/epstopdf\\n\",\r\n    \"/usr/bin/idle3\\n\",\r\n    \"...\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"To find the total size of all the files in this directory:\\n\",\r\n    \"\\n\",\r\n    \"**WARNING**: Directories themselves also have a size! So you might want to\\n\",\r\n    \"check for whether a path is a file or directory using the methods in the methods discussed in the above section!\\n\",\r\n    \"\\n\",\r\n    \"Using `os.path.getsize()` and `os.listdir()` together on Windows:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>> total_size = 0\\n\",\r\n    \"\\n\",\r\n    \">>> for filename in os.listdir('C:\\\\\\\\Windows\\\\\\\\System32'):\\n\",\r\n    \"      total_size = total_size + os.path.getsize(os.path.join('C:\\\\\\\\Windows\\\\\\\\System32', filename))\\n\",\r\n    \"\\n\",\r\n    \">>> print(total_size)\\n\",\r\n    \"1117846456\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Using `pathlib` on \\\\*nix:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from pathlib import Path\\n\",\r\n    \">>> total_size = 0\\n\",\r\n    \"\\n\",\r\n    \">>> for sub_path in Path('/usr/bin').iterdir():\\n\",\r\n    \"...     total_size += sub_path.stat().st_size\\n\",\r\n    \">>>\\n\",\r\n    \">>> print(total_size)\\n\",\r\n    \"1903178911\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Copying Files and Folders\\n\",\r\n    \"\\n\",\r\n    \"The shutil module provides functions for copying files, as well as entire folders.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import shutil, os\\n\",\r\n    \"\\n\",\r\n    \">>> os.chdir('C:\\\\\\\\')\\n\",\r\n    \"\\n\",\r\n    \">>> shutil.copy('C:\\\\\\\\spam.txt', 'C:\\\\\\\\delicious')\\n\",\r\n    \"   'C:\\\\\\\\delicious\\\\\\\\spam.txt'\\n\",\r\n    \"\\n\",\r\n    \">>> shutil.copy('eggs.txt', 'C:\\\\\\\\delicious\\\\\\\\eggs2.txt')\\n\",\r\n    \"   'C:\\\\\\\\delicious\\\\\\\\eggs2.txt'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"While shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and every folder and file contained in it:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import shutil, os\\n\",\r\n    \"\\n\",\r\n    \">>> os.chdir('C:\\\\\\\\')\\n\",\r\n    \"\\n\",\r\n    \">>> shutil.copytree('C:\\\\\\\\bacon', 'C:\\\\\\\\bacon_backup')\\n\",\r\n    \"'C:\\\\\\\\bacon_backup'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Moving and Renaming Files and Folders\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import shutil\\n\",\r\n    \">>> shutil.move('C:\\\\\\\\bacon.txt', 'C:\\\\\\\\eggs')\\n\",\r\n    \"'C:\\\\\\\\eggs\\\\\\\\bacon.txt'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The destination path can also specify a filename. In the following example, the source file is moved and renamed:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> shutil.move('C:\\\\\\\\bacon.txt', 'C:\\\\\\\\eggs\\\\\\\\new_bacon.txt')\\n\",\r\n    \"'C:\\\\\\\\eggs\\\\\\\\new_bacon.txt'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"If there is no eggs folder, then move() will rename bacon.txt to a file named eggs.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> shutil.move('C:\\\\\\\\bacon.txt', 'C:\\\\\\\\eggs')\\n\",\r\n    \"'C:\\\\\\\\eggs'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Permanently Deleting Files and Folders\\n\",\r\n    \"\\n\",\r\n    \"- Calling os.unlink(path) or Path.unlink() will delete the file at path.\\n\",\r\n    \"\\n\",\r\n    \"- Calling os.rmdir(path) or Path.rmdir() will delete the folder at path. This folder must be empty of any files or folders.\\n\",\r\n    \"\\n\",\r\n    \"- Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be deleted.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Safe Deletes with the send2trash Module\\n\",\r\n    \"\\n\",\r\n    \" You can install this module by running pip install send2trash from a Terminal window.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import send2trash\\n\",\r\n    \"\\n\",\r\n    \">>> with open('bacon.txt', 'a') as bacon_file: # creates the file\\n\",\r\n    \"...     bacon_file.write('Bacon is not a vegetable.')\\n\",\r\n    \"25\\n\",\r\n    \"\\n\",\r\n    \">>> send2trash.send2trash('bacon.txt')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Walking a Directory Tree\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import os\\n\",\r\n    \">>>\\n\",\r\n    \">>> for folder_name, subfolders, filenames in os.walk('C:\\\\\\\\delicious'):\\n\",\r\n    \">>>     print('The current folder is {}'.format(folder_name))\\n\",\r\n    \">>>\\n\",\r\n    \">>>     for subfolder in subfolders:\\n\",\r\n    \">>>         print('SUBFOLDER OF {}: {}'.format(folder_name, subfolder))\\n\",\r\n    \">>>     for filename in filenames:\\n\",\r\n    \">>>         print('FILE INSIDE {}: {}'.format(folder_name, filename))\\n\",\r\n    \">>>\\n\",\r\n    \">>>     print('')\\n\",\r\n    \"The current folder is C:\\\\delicious\\n\",\r\n    \"SUBFOLDER OF C:\\\\delicious: cats\\n\",\r\n    \"SUBFOLDER OF C:\\\\delicious: walnut\\n\",\r\n    \"FILE INSIDE C:\\\\delicious: spam.txt\\n\",\r\n    \"\\n\",\r\n    \"The current folder is C:\\\\delicious\\\\cats\\n\",\r\n    \"FILE INSIDE C:\\\\delicious\\\\cats: catnames.txt\\n\",\r\n    \"FILE INSIDE C:\\\\delicious\\\\cats: zophie.jpg\\n\",\r\n    \"\\n\",\r\n    \"The current folder is C:\\\\delicious\\\\walnut\\n\",\r\n    \"SUBFOLDER OF C:\\\\delicious\\\\walnut: waffles\\n\",\r\n    \"\\n\",\r\n    \"The current folder is C:\\\\delicious\\\\walnut\\\\waffles\\n\",\r\n    \"FILE INSIDE C:\\\\delicious\\\\walnut\\\\waffles: butter.txt\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"`pathlib` provides a lot more functionality than the ones listed above,\\n\",\r\n    \"like getting file name, getting file extension, reading/writing a file without\\n\",\r\n    \"manually opening it, etc. Check out the\\n\",\r\n    \"[official documentation](https://docs.python.org/3/library/pathlib.html)\\n\",\r\n    \"if you want to know more!\\n\",\r\n    \"\\n\",\r\n    \"## Reading and Writing Files\\n\",\r\n    \"\\n\",\r\n    \"### The File Reading/Writing Process\\n\",\r\n    \"\\n\",\r\n    \"To read/write to a file in Python, you will want to use the `with`\\n\",\r\n    \"statement, which will close the file for you after you are done.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Opening and reading files with the open() function\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> with open('C:\\\\\\\\Users\\\\\\\\your_home_folder\\\\\\\\hello.txt') as hello_file:\\n\",\r\n    \"...     hello_content = hello_file.read()\\n\",\r\n    \">>> hello_content\\n\",\r\n    \"'Hello World!'\\n\",\r\n    \"\\n\",\r\n    \">>> # Alternatively, you can use the *readlines()* method to get a list of string values from the file, one string for each line of text:\\n\",\r\n    \"\\n\",\r\n    \">>> with open('sonnet29.txt') as sonnet_file:\\n\",\r\n    \"...     sonnet_file.readlines()\\n\",\r\n    \"[When, in disgrace with fortune and men's eyes,\\\\n', ' I all alone beweep my\\n\",\r\n    \"outcast state,\\\\n', And trouble deaf heaven with my bootless cries,\\\\n', And\\n\",\r\n    \"look upon myself and curse my fate,']\\n\",\r\n    \"\\n\",\r\n    \">>> # You can also iterate through the file line by line:\\n\",\r\n    \">>> with open('sonnet29.txt') as sonnet_file:\\n\",\r\n    \"...     for line in sonnet_file: # note the new line character will be included in the line\\n\",\r\n    \"...         print(line, end='')\\n\",\r\n    \"\\n\",\r\n    \"When, in disgrace with fortune and men's eyes,\\n\",\r\n    \"I all alone beweep my outcast state,\\n\",\r\n    \"And trouble deaf heaven with my bootless cries,\\n\",\r\n    \"And look upon myself and curse my fate,\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Writing to Files\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> with open('bacon.txt', 'w') as bacon_file:\\n\",\r\n    \"...     bacon_file.write('Hello world!\\\\n')\\n\",\r\n    \"13\\n\",\r\n    \"\\n\",\r\n    \">>> with open('bacon.txt', 'a') as bacon_file:\\n\",\r\n    \"...     bacon_file.write('Bacon is not a vegetable.')\\n\",\r\n    \"25\\n\",\r\n    \"\\n\",\r\n    \">>> with open('bacon.txt') as bacon_file:\\n\",\r\n    \"...     content = bacon_file.read()\\n\",\r\n    \"\\n\",\r\n    \">>> print(content)\\n\",\r\n    \"Hello world!\\n\",\r\n    \"Bacon is not a vegetable.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Saving Variables with the shelve Module\\n\",\r\n    \"\\n\",\r\n    \"To save variables:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import shelve\\n\",\r\n    \"\\n\",\r\n    \">>> cats = ['Zophie', 'Pooka', 'Simon']\\n\",\r\n    \">>> with shelve.open('mydata') as shelf_file:\\n\",\r\n    \"...     shelf_file['cats'] = cats\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"To open and read variables:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> with shelve.open('mydata') as shelf_file:\\n\",\r\n    \"...     print(type(shelf_file))\\n\",\r\n    \"...     print(shelf_file['cats'])\\n\",\r\n    \"<class 'shelve.DbfilenameShelf'>\\n\",\r\n    \"['Zophie', 'Pooka', 'Simon']\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Just like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the list() function to get them in list form.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> with shelve.open('mydata') as shelf_file:\\n\",\r\n    \"...     print(list(shelf_file.keys()))\\n\",\r\n    \"...     print(list(shelf_file.values()))\\n\",\r\n    \"['cats']\\n\",\r\n    \"[['Zophie', 'Pooka', 'Simon']]\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Saving Variables with the pprint.pformat() Function\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import pprint\\n\",\r\n    \"\\n\",\r\n    \">>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]\\n\",\r\n    \"\\n\",\r\n    \">>> pprint.pformat(cats)\\n\",\r\n    \"\\\"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]\\\"\\n\",\r\n    \"\\n\",\r\n    \">>> with open('myCats.py', 'w') as file_obj:\\n\",\r\n    \"...     file_obj.write('cats = {}\\\\n'.format(pprint.pformat(cats)))\\n\",\r\n    \"83\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Reading ZIP Files\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import zipfile, os\\n\",\r\n    \"\\n\",\r\n    \">>> os.chdir('C:\\\\\\\\')    # move to the folder with example.zip\\n\",\r\n    \">>> with zipfile.ZipFile('example.zip') as example_zip:\\n\",\r\n    \"...     print(example_zip.namelist())\\n\",\r\n    \"...     spam_info = example_zip.getinfo('spam.txt')\\n\",\r\n    \"...     print(spam_info.file_size)\\n\",\r\n    \"...     print(spam_info.compress_size)\\n\",\r\n    \"...     print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))\\n\",\r\n    \"\\n\",\r\n    \"['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']\\n\",\r\n    \"13908\\n\",\r\n    \"3828\\n\",\r\n    \"'Compressed file is 3.63x smaller!'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Extracting from ZIP Files\\n\",\r\n    \"\\n\",\r\n    \"The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current working directory.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import zipfile, os\\n\",\r\n    \"\\n\",\r\n    \">>> os.chdir('C:\\\\\\\\')    # move to the folder with example.zip\\n\",\r\n    \"\\n\",\r\n    \">>> with zipfile.ZipFile('example.zip') as example_zip:\\n\",\r\n    \"...     example_zip.extractall()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The extract() method for ZipFile objects will extract a single file from the ZIP file. Continue the interactive shell example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> with zipfile.ZipFile('example.zip') as example_zip:\\n\",\r\n    \"...     print(example_zip.extract('spam.txt'))\\n\",\r\n    \"...     print(example_zip.extract('spam.txt', 'C:\\\\\\\\some\\\\\\\\new\\\\\\\\folders'))\\n\",\r\n    \"'C:\\\\\\\\spam.txt'\\n\",\r\n    \"'C:\\\\\\\\some\\\\\\\\new\\\\\\\\folders\\\\\\\\spam.txt'\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Creating and Adding to ZIP Files\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import zipfile\\n\",\r\n    \"\\n\",\r\n    \">>> with zipfile.ZipFile('new.zip', 'w') as new_zip:\\n\",\r\n    \"...     new_zip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"This code will create a new ZIP file named new.zip that has the compressed contents of spam.txt.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## JSON, YAML and configuration files\\n\",\r\n    \"\\n\",\r\n    \"### JSON\\n\",\r\n    \"\\n\",\r\n    \"Open a JSON file with:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import json\\n\",\r\n    \"with open(\\\"filename.json\\\", \\\"r\\\") as f:\\n\",\r\n    \"    content = json.loads(f.read())\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Write a JSON file with:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import json\\n\",\r\n    \"\\n\",\r\n    \"content = {\\\"name\\\": \\\"Joe\\\", \\\"age\\\": 20}\\n\",\r\n    \"with open(\\\"filename.json\\\", \\\"w\\\") as f:\\n\",\r\n    \"    f.write(json.dumps(content, indent=2))\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### YAML\\n\",\r\n    \"\\n\",\r\n    \"Compared to JSON, YAML allows a much better humain maintainance and gives ability to add comments.\\n\",\r\n    \"It is a convinient choice for configuration files where human will have to edit.\\n\",\r\n    \"\\n\",\r\n    \"There are two main librairies allowing to access to YAML files:\\n\",\r\n    \"\\n\",\r\n    \"- [PyYaml](https://pypi.python.org/pypi/PyYAML)\\n\",\r\n    \"- [Ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml)\\n\",\r\n    \"\\n\",\r\n    \"Install them using `pip install` in your virtual environment.\\n\",\r\n    \"\\n\",\r\n    \"The first one it easier to use but the second one, Ruamel, implements much better the YAML\\n\",\r\n    \"specification, and allow for example to modify a YAML content without altering comments.\\n\",\r\n    \"\\n\",\r\n    \"Open a YAML file with:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"from ruamel.yaml import YAML\\n\",\r\n    \"\\n\",\r\n    \"with open(\\\"filename.yaml\\\") as f:\\n\",\r\n    \"    yaml=YAML()\\n\",\r\n    \"    yaml.load(f)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Anyconfig\\n\",\r\n    \"\\n\",\r\n    \"[Anyconfig](https://pypi.python.org/pypi/anyconfig) is a very handy package allowing to abstract completly the underlying configuration file format. It allows to load a Python dictionary from JSON, YAML, TOML, and so on.\\n\",\r\n    \"\\n\",\r\n    \"Install it with:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"%%bash\\n\",\r\n    \"pip install anyconfig\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Usage:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import anyconfig\\n\",\r\n    \"\\n\",\r\n    \"conf1 = anyconfig.load(\\\"/path/to/foo/conf.d/a.yml\\\")\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Debugging\\n\",\r\n    \"\\n\",\r\n    \"### Raising Exceptions\\n\",\r\n    \"\\n\",\r\n    \"Exceptions are raised with a raise statement. In code, a raise statement consists of the following:\\n\",\r\n    \"\\n\",\r\n    \"- The raise keyword\\n\",\r\n    \"- A call to the Exception() function\\n\",\r\n    \"- A string with a helpful error message passed to the Exception() function\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> raise Exception('This is the error message.')\\n\",\r\n    \"Traceback (most recent call last):\\n\",\r\n    \"  File \\\"<pyshell#191>\\\", line 1, in <module>\\n\",\r\n    \"    raise Exception('This is the error message.')\\n\",\r\n    \"Exception: This is the error message.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Often it’s the code that calls the function, not the function itself, that knows how to handle an expection. So you will commonly see a raise statement inside a function and the try and except statements in the code calling the function.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"def box_print(symbol, width, height):\\n\",\r\n    \"    if len(symbol) != 1:\\n\",\r\n    \"      raise Exception('Symbol must be a single character string.')\\n\",\r\n    \"    if width <= 2:\\n\",\r\n    \"      raise Exception('Width must be greater than 2.')\\n\",\r\n    \"    if height <= 2:\\n\",\r\n    \"      raise Exception('Height must be greater than 2.')\\n\",\r\n    \"    print(symbol * width)\\n\",\r\n    \"    for i in range(height - 2):\\n\",\r\n    \"        print(symbol + (' ' * (width - 2)) + symbol)\\n\",\r\n    \"    print(symbol * width)\\n\",\r\n    \"for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):\\n\",\r\n    \"    try:\\n\",\r\n    \"        box_print(sym, w, h)\\n\",\r\n    \"    except Exception as err:\\n\",\r\n    \"        print('An exception happened: ' + str(err))\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Getting the Traceback as a String\\n\",\r\n    \"\\n\",\r\n    \"The traceback is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import traceback\\n\",\r\n    \"\\n\",\r\n    \">>> try:\\n\",\r\n    \">>>      raise Exception('This is the error message.')\\n\",\r\n    \">>> except:\\n\",\r\n    \">>>      with open('errorInfo.txt', 'w') as error_file:\\n\",\r\n    \">>>          error_file.write(traceback.format_exc())\\n\",\r\n    \">>>      print('The traceback info was written to errorInfo.txt.')\\n\",\r\n    \"116\\n\",\r\n    \"The traceback info was written to errorInfo.txt.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The 116 is the return value from the write() method, since 116 characters were written to the file. The traceback text was written to errorInfo.txt.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"Traceback (most recent call last):\\n\",\r\n    \"  File \\\"<pyshell#28>\\\", line 2, in <module>\\n\",\r\n    \"Exception: This is the error message.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Assertions\\n\",\r\n    \"\\n\",\r\n    \"An assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity checks are performed by assert statements. If the sanity check fails, then an AssertionError exception is raised. In code, an assert statement consists of the following:\\n\",\r\n    \"\\n\",\r\n    \"- The assert keyword\\n\",\r\n    \"- A condition (that is, an expression that evaluates to True or False)\\n\",\r\n    \"- A comma\\n\",\r\n    \"- A string to display when the condition is False\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> pod_bay_door_status = 'open'\\n\",\r\n    \"\\n\",\r\n    \">>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \\\"open\\\".'\\n\",\r\n    \"\\n\",\r\n    \">>> pod_bay_door_status = 'I\\\\'m sorry, Dave. I\\\\'m afraid I can\\\\'t do that.'\\n\",\r\n    \"\\n\",\r\n    \">>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \\\"open\\\".'\\n\",\r\n    \"\\n\",\r\n    \"Traceback (most recent call last):\\n\",\r\n    \"  File \\\"<pyshell#10>\\\", line 1, in <module>\\n\",\r\n    \"    assert pod_bay_door_status == 'open', 'The pod bay doors need to be \\\"open\\\".'\\n\",\r\n    \"AssertionError: The pod bay doors need to be \\\"open\\\".\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"In plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have to check before finding the code that’s causing the bug.\\n\",\r\n    \"\\n\",\r\n    \"Disabling Assertions\\n\",\r\n    \"\\n\",\r\n    \"Assertions can be disabled by passing the -O option when running Python.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Logging\\n\",\r\n    \"\\n\",\r\n    \"To enable the logging module to display log messages on your screen as your program runs, copy the following to the top of your program (but under the #! python shebang line):\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import logging\\n\",\r\n    \"\\n\",\r\n    \"logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Say you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going wrong. Save the program as factorialLog.py.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import logging\\n\",\r\n    \">>>\\n\",\r\n    \">>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\\n\",\r\n    \">>>\\n\",\r\n    \">>> logging.debug('Start of program')\\n\",\r\n    \">>>\\n\",\r\n    \">>> def factorial(n):\\n\",\r\n    \">>>\\n\",\r\n    \">>>     logging.debug('Start of factorial(%s)' % (n))\\n\",\r\n    \">>>     total = 1\\n\",\r\n    \">>>\\n\",\r\n    \">>>     for i in range(1, n + 1):\\n\",\r\n    \">>>         total *= i\\n\",\r\n    \">>>         logging.debug('i is ' + str(i) + ', total is ' + str(total))\\n\",\r\n    \">>>\\n\",\r\n    \">>>     logging.debug('End of factorial(%s)' % (n))\\n\",\r\n    \">>>\\n\",\r\n    \">>>     return total\\n\",\r\n    \">>>\\n\",\r\n    \">>> print(factorial(5))\\n\",\r\n    \">>> logging.debug('End of program')\\n\",\r\n    \"2015-05-23 16:20:12,664 - DEBUG - Start of program\\n\",\r\n    \"2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)\\n\",\r\n    \"2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0\\n\",\r\n    \"2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0\\n\",\r\n    \"2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0\\n\",\r\n    \"2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0\\n\",\r\n    \"2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0\\n\",\r\n    \"2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0\\n\",\r\n    \"2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)\\n\",\r\n    \"0\\n\",\r\n    \"2015-05-23 16:20:12,684 - DEBUG - End of program\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Logging Levels\\n\",\r\n    \"\\n\",\r\n    \"Logging levels provide a way to categorize your log messages by importance. There are five logging levels, described in Table 10-1 from least to most important. Messages can be logged at each level using a different logging function.\\n\",\r\n    \"\\n\",\r\n    \"| Level      | Logging Function     | Description                                                                                                                    |\\n\",\r\n    \"| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\\n\",\r\n    \"| `DEBUG`    | `logging.debug()`    | The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems.                 |\\n\",\r\n    \"| `INFO`     | `logging.info()`     | Used to record information on general events in your program or confirm that things are working at their point in the program. |\\n\",\r\n    \"| `WARNING`  | `logging.warning()`  | Used to indicate a potential problem that doesn’t prevent the program from working but might do so in the future.             |\\n\",\r\n    \"| `ERROR`    | `logging.error()`    | Used to record an error that caused the program to fail to do something.                                                       |\\n\",\r\n    \"| `CRITICAL` | `logging.critical()` | The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely.   |\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Disabling Logging\\n\",\r\n    \"\\n\",\r\n    \"After you’ve debugged your program, you probably don’t want all these log messages cluttering the screen. The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging calls by hand.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import logging\\n\",\r\n    \"\\n\",\r\n    \">>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')\\n\",\r\n    \"\\n\",\r\n    \">>> logging.critical('Critical error! Critical error!')\\n\",\r\n    \"2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!\\n\",\r\n    \"\\n\",\r\n    \">>> logging.disable(logging.CRITICAL)\\n\",\r\n    \"\\n\",\r\n    \">>> logging.critical('Critical error! Critical error!')\\n\",\r\n    \"\\n\",\r\n    \">>> logging.error('Error! Error!')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Logging to a File\\n\",\r\n    \"\\n\",\r\n    \"Instead of displaying the log messages to the screen, you can write them to a text file. The logging.basicConfig() function takes a filename keyword argument, like so:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"import logging\\n\",\r\n    \"\\n\",\r\n    \"logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Lambda Functions\\n\",\r\n    \"\\n\",\r\n    \"This function:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def add(x, y):\\n\",\r\n    \"        return x + y\\n\",\r\n    \"\\n\",\r\n    \">>> add(5, 3)\\n\",\r\n    \"8\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Is equivalent to the *lambda* function:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> add = lambda x, y: x + y\\n\",\r\n    \">>> add(5, 3)\\n\",\r\n    \"8\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"It's not even need to bind it to a name like add before:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> (lambda x, y: x + y)(5, 3)\\n\",\r\n    \"8\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Like regular nested functions, lambdas also work as lexical closures:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def make_adder(n):\\n\",\r\n    \"        return lambda x: x + n\\n\",\r\n    \"\\n\",\r\n    \">>> plus_3 = make_adder(3)\\n\",\r\n    \">>> plus_5 = make_adder(5)\\n\",\r\n    \"\\n\",\r\n    \">>> plus_3(4)\\n\",\r\n    \"7\\n\",\r\n    \">>> plus_5(4)\\n\",\r\n    \"9\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Note: lambda can only evaluate an expression, like a single line of code.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Ternary Conditional Operator\\n\",\r\n    \"\\n\",\r\n    \"Many programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, otherwise it evaluates the second expression.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"<expression1> if <condition> else <expression2>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Example:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> age = 15\\n\",\r\n    \"\\n\",\r\n    \">>> print('kid' if age < 18 else 'adult')\\n\",\r\n    \"kid\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Ternary operators can be changed:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> age = 15\\n\",\r\n    \"\\n\",\r\n    \">>> print('kid' if age < 13 else 'teenager' if age < 18 else 'adult')\\n\",\r\n    \"teenager\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"The code above is equivalent to:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"if age < 18:\\n\",\r\n    \"    if age < 12:\\n\",\r\n    \"        print('kid')\\n\",\r\n    \"    else:\\n\",\r\n    \"        print('teenager')\\n\",\r\n    \"else:\\n\",\r\n    \"    print('adult')\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## args and kwargs\\n\",\r\n    \"\\n\",\r\n    \"The names ```args and kwargs``` are arbitrary - the important thing are the ```*``` and ```**``` operators. They can mean:\\n\",\r\n    \"\\n\",\r\n    \"1. In a function declaration, ```*``` means “pack all remaining positional arguments into a tuple named `<name>`”, while ```**``` is the same for keyword arguments (except it uses a dictionary, not a tuple).\\n\",\r\n    \"\\n\",\r\n    \"2. In a function call, ```*``` means “unpack tuple or list named `<name>` to positional arguments at this position”, while ```**``` is the same for keyword arguments.\\n\",\r\n    \"\\n\",\r\n    \"For example you can make a function that you can use to call any other function, no matter what parameters it has:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"def forward(f, *args, **kwargs):\\n\",\r\n    \"    return f(*args, **kwargs)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Inside forward, args is a tuple (of all positional arguments except the first one, because we specified it - the f), kwargs is a dict. Then we call f and unpack them so they become normal arguments to f.\\n\",\r\n    \"\\n\",\r\n    \"You use ```*args``` when you have an indefinite amount of positional arguments.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def fruits(*args):\\n\",\r\n    \">>>    for fruit in args:\\n\",\r\n    \">>>       print(fruit)\\n\",\r\n    \"\\n\",\r\n    \">>> fruits(\\\"apples\\\", \\\"bananas\\\", \\\"grapes\\\")\\n\",\r\n    \"\\n\",\r\n    \"\\\"apples\\\"\\n\",\r\n    \"\\\"bananas\\\"\\n\",\r\n    \"\\\"grapes\\\"\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Similarly, you use ```**kwargs``` when you have an indefinite number of keyword arguments.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def fruit(**kwargs):\\n\",\r\n    \">>>    for key, value in kwargs.items():\\n\",\r\n    \">>>        print(\\\"{0}: {1}\\\".format(key, value))\\n\",\r\n    \"\\n\",\r\n    \">>> fruit(name = \\\"apple\\\", color = \\\"red\\\")\\n\",\r\n    \"\\n\",\r\n    \"name: apple\\n\",\r\n    \"color: red\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> def show(arg1, arg2, *args, kwarg1=None, kwarg2=None, **kwargs):\\n\",\r\n    \">>>   print(arg1)\\n\",\r\n    \">>>   print(arg2)\\n\",\r\n    \">>>   print(args)\\n\",\r\n    \">>>   print(kwarg1)\\n\",\r\n    \">>>   print(kwarg2)\\n\",\r\n    \">>>   print(kwargs)\\n\",\r\n    \"\\n\",\r\n    \">>> data1 = [1,2,3]\\n\",\r\n    \">>> data2 = [4,5,6]\\n\",\r\n    \">>> data3 = {'a':7,'b':8,'c':9}\\n\",\r\n    \"\\n\",\r\n    \">>> show(*data1,*data2, kwarg1=\\\"python\\\",kwarg2=\\\"cheatsheet\\\",**data3)\\n\",\r\n    \"1\\n\",\r\n    \"2\\n\",\r\n    \"(3, 4, 5, 6)\\n\",\r\n    \"python\\n\",\r\n    \"cheatsheet\\n\",\r\n    \"{'a': 7, 'b': 8, 'c': 9}\\n\",\r\n    \"\\n\",\r\n    \">>> show(*data1, *data2, **data3)\\n\",\r\n    \"1\\n\",\r\n    \"2\\n\",\r\n    \"(3, 4, 5, 6)\\n\",\r\n    \"None\\n\",\r\n    \"None\\n\",\r\n    \"{'a': 7, 'b': 8, 'c': 9}\\n\",\r\n    \"\\n\",\r\n    \"# If you do not specify ** for kwargs\\n\",\r\n    \">>> show(*data1, *data2, *data3)\\n\",\r\n    \"1\\n\",\r\n    \"2\\n\",\r\n    \"(3, 4, 5, 6, \\\"a\\\", \\\"b\\\", \\\"c\\\")\\n\",\r\n    \"None\\n\",\r\n    \"None\\n\",\r\n    \"{}\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### Thinks to Remember(args)\\n\",\r\n    \"\\n\",\r\n    \"1. Functions can accept a variable number of positional arguments by using ```*args``` in the def statement.\\n\",\r\n    \"2. You can use the items from a sequence as the positional arguments for a function with the ```*``` operator.\\n\",\r\n    \"3. Using the ```*``` operator with a generator may cause your program to run out of memory and crash.\\n\",\r\n    \"4. Adding new positional parameters to functions that accept ```*args``` can introduce hard-to-find bugs.\\n\",\r\n    \"\\n\",\r\n    \"### Thinks to remember(kwargs)\\n\",\r\n    \"\\n\",\r\n    \"1. Function arguments can be specified by position or by keyword.\\n\",\r\n    \"2. Keywords make it clear what the purpose of each argument is when it would be confusing with only positional arguments.\\n\",\r\n    \"3. Keyword arguments with default values make it easy to add new behaviors to a function, especially when the function has existing callers.\\n\",\r\n    \"4. Optional keyword arguments should always be passed by keyword instead of by position.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Context Manager\\n\",\r\n    \"\\n\",\r\n    \"While Python's context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes.\\n\",\r\n    \"\\n\",\r\n    \"### with statement\\n\",\r\n    \"\\n\",\r\n    \"A context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the with statement. It takes care of the notifying.\\n\",\r\n    \"\\n\",\r\n    \"For example, file objects are context managers. When a context ends, the file object is closed automatically:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> with open(filename) as f:\\n\",\r\n    \">>>     file_contents = f.read()\\n\",\r\n    \"\\n\",\r\n    \"# the open_file object has automatically been closed.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Anything that ends execution of the block causes the context manager's exit method to be called. This includes exceptions, and can be useful when an error causes you to prematurely exit from an open file or connection. Exiting a script without properly closing files/connections is a bad idea, that may cause data loss or other problems. By using a context manager you can ensure that precautions are always taken to prevent damage or loss in this way.\\n\",\r\n    \"\\n\",\r\n    \"### Writing your own contextmanager using generator syntax\\n\",\r\n    \"\\n\",\r\n    \"It is also possible to write a context manager using generator syntax thanks to the ```contextlib.contextmanager``` decorator:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> import contextlib\\n\",\r\n    \">>> @contextlib.contextmanager\\n\",\r\n    \"... def context_manager(num):\\n\",\r\n    \"...     print('Enter')\\n\",\r\n    \"...     yield num + 1\\n\",\r\n    \"...     print('Exit')\\n\",\r\n    \">>> with context_manager(2) as cm:\\n\",\r\n    \"...     # the following instructions are run when the 'yield' point of the context\\n\",\r\n    \"...     # manager is reached.\\n\",\r\n    \"...     # 'cm' will have the value that was yielded\\n\",\r\n    \"...     print('Right in the middle with cm = {}'.format(cm))\\n\",\r\n    \"Enter\\n\",\r\n    \"Right in the middle with cm = 3\\n\",\r\n    \"Exit\\n\",\r\n    \"\\n\",\r\n    \">>>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## `__main__` Top-level script environment\\n\",\r\n    \"\\n\",\r\n    \"`__main__` is the name of the scope in which top-level code executes.\\n\",\r\n    \"A module’s __name__ is set equal to `__main__` when read from standard input, a script, or from an interactive prompt.\\n\",\r\n    \"\\n\",\r\n    \"A module can discover whether or not it is running in the main scope by checking its own `__name__`, which allows a common idiom for conditionally executing code in a module when it is run as a script or with `python -m` but not when it is imported:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> if __name__ == \\\"__main__\\\":\\n\",\r\n    \"...     # execute only if run as a script\\n\",\r\n    \"...     main()\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m\\n\",\r\n    \"\\n\",\r\n    \"For example we are developing script which is designed to be used as module, we should do:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> # Python program to execute function directly\\n\",\r\n    \">>> def add(a, b):\\n\",\r\n    \"...     return a+b\\n\",\r\n    \"...\\n\",\r\n    \">>> add(10, 20) # we can test it by calling the function save it as calculate.py\\n\",\r\n    \"30\\n\",\r\n    \">>> # Now if we want to use that module by importing we have to comment out our call,\\n\",\r\n    \">>> # Instead we can write like this in calculate.py\\n\",\r\n    \">>> if __name__ == \\\"__main__\\\":\\n\",\r\n    \"...     add(3, 5)\\n\",\r\n    \"...\\n\",\r\n    \">>> import calculate\\n\",\r\n    \">>> calculate.add(3, 5)\\n\",\r\n    \"8\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### Advantages\\n\",\r\n    \"\\n\",\r\n    \"1. Every Python module has it’s `__name__` defined and if this is `__main__`, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.\\n\",\r\n    \"2. If you import this script as a module in another script, the __name__ is set to the name of the script/module.\\n\",\r\n    \"3. Python files can act as either reusable modules, or as standalone programs.\\n\",\r\n    \"4. if `__name__ == “main”:` is used to execute some code only if the file was run directly, and not imported.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## setup.py\\n\",\r\n    \"\\n\",\r\n    \"The setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing.\\n\",\r\n    \"\\n\",\r\n    \"The `setup.py` file is at the heart of a Python project. It describes all of the metadata about your project. There a quite a few fields you can add to a project to give it a rich set of metadata describing the project. However, there are only three required fields: name, version, and packages. The name field must be unique if you wish to publish your package on the Python Package Index (PyPI). The version field keeps track of different releases of the project. The packages field describes where you’ve put the Python source code within your project.\\n\",\r\n    \"\\n\",\r\n    \"This allows you to easily install Python packages. Often it's enough to write:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"%%bash\\n\",\r\n    \"python setup.py install\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"and module will install itself.\\n\",\r\n    \"\\n\",\r\n    \"Our initial setup.py will also include information about the license and will re-use the README.txt file for the long_description field. This will look like:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from distutils.core import setup\\n\",\r\n    \">>> setup(\\n\",\r\n    \"...    name='pythonCheatsheet',\\n\",\r\n    \"...    version='0.1',\\n\",\r\n    \"...    packages=['pipenv',],\\n\",\r\n    \"...    license='MIT',\\n\",\r\n    \"...    long_description=open('README.txt').read(),\\n\",\r\n    \"... )\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Find more information visit [http://docs.python.org/install/index.html](http://docs.python.org/install/index.html).\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Dataclasses\\n\",\r\n    \"\\n\",\r\n    \"`Dataclasses` are python classes but are suited for storing data objects.\\n\",\r\n    \"This module provides a decorator and functions for automatically adding generated special methods such as `__init__()` and `__repr__()` to user-defined classes.\\n\",\r\n    \"\\n\",\r\n    \"### Features\\n\",\r\n    \"\\n\",\r\n    \"1. They store data and represent a certain data type. Ex: A number. For people familiar with ORMs, a model instance is a data object. It represents a specific kind of entity. It holds attributes that define or represent the entity.\\n\",\r\n    \"\\n\",\r\n    \"2. They can be compared to other objects of the same type. Ex: A number can be greater than, less than, or equal to another number.\\n\",\r\n    \"\\n\",\r\n    \"Python 3.7 provides a decorator dataclass that is used to convert a class into a dataclass.\\n\",\r\n    \"\\n\",\r\n    \"python 2.7\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> class Number:\\n\",\r\n    \"...     def __init__(self, val):\\n\",\r\n    \"...         self.val = val\\n\",\r\n    \"...\\n\",\r\n    \">>> obj = Number(2)\\n\",\r\n    \">>> obj.val\\n\",\r\n    \"2\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"with dataclass\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> @dataclass\\n\",\r\n    \"... class Number:\\n\",\r\n    \"...     val: int\\n\",\r\n    \"...\\n\",\r\n    \">>> obj = Number(2)\\n\",\r\n    \">>> obj.val\\n\",\r\n    \"2\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### Default values\\n\",\r\n    \"\\n\",\r\n    \"It is easy to add default values to the fields of your data class.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> @dataclass\\n\",\r\n    \"... class Product:\\n\",\r\n    \"...     name: str\\n\",\r\n    \"...     count: int = 0\\n\",\r\n    \"...     price: float = 0.0\\n\",\r\n    \"...\\n\",\r\n    \">>> obj = Product(\\\"Python\\\")\\n\",\r\n    \">>> obj.name\\n\",\r\n    \"Python\\n\",\r\n    \">>> obj.count\\n\",\r\n    \"0\\n\",\r\n    \">>> obj.price\\n\",\r\n    \"0.0\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"### Type hints\\n\",\r\n    \"\\n\",\r\n    \"It is mandatory to define the data type in dataclass. However, If you don't want specify the datatype then, use ```typing.Any```.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \">>> from dataclasses import dataclass\\n\",\r\n    \">>> from typing import Any\\n\",\r\n    \"\\n\",\r\n    \">>> @dataclass\\n\",\r\n    \"... class WithoutExplicitTypes:\\n\",\r\n    \"...    name: Any\\n\",\r\n    \"...    value: Any = 42\\n\",\r\n    \"...\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"## Virtual Environment\\n\",\r\n    \"\\n\",\r\n    \"The use of a Virtual Environment is to test python code in encapsulated environments and to also avoid filling the base Python installation with libraries we might use for only one project.\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### virtualenv\\n\",\r\n    \"\\n\",\r\n    \"1. Install virtualenv\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"pip install virtualenv\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"1. Install virtualenvwrapper-win (Windows)\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"pip install virtualenvwrapper-win\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Usage:\\n\",\r\n    \"\\n\",\r\n    \"1. Make a Virtual Environment\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"mkvirtualenv HelloWold\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Anything we install now will be specific to this project. And available to the projects we connect to this environment.\\n\",\r\n    \"\\n\",\r\n    \"1. Set Project Directory\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"To bind our virtualenv with our current working directory we simply enter:\\n\",\r\n    \"\\n\",\r\n    \"    setprojectdir .\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"1. Deactivate\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"To move onto something else in the command line type ‘deactivate’ to deactivate your environment.\\n\",\r\n    \"\\n\",\r\n    \"    deactivate\\n\",\r\n    \"\\n\",\r\n    \"Notice how the parenthesis disappear.\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"1. Workon\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"Open up the command prompt and type ‘workon HelloWold’ to activate the environment and move into your root project folder\\n\",\r\n    \"\\n\",\r\n    \"    workon HelloWold\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### pipenv\\n\",\r\n    \"\\n\",\r\n    \"> [Pipenv](https://pipenv.readthedocs.io/en/latest/) is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.\\n\",\r\n    \"\\n\",\r\n    \"1. Install pipenv\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"pip install pipenv\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"1. Enter your Project directory and install the Packages for your project\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"cd my_project\\n\",\r\n    \"pipenv install <package>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Pipenv will install your package and create a Pipfile for you in your project’s directory. The Pipfile is used to track which dependencies your project needs in case you need to re-install them.\\n\",\r\n    \"\\n\",\r\n    \"1. Uninstall Packages\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"pipenv uninstall <package>\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"1. Activate the Virtual Environment associated with your Python project\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"pipenv shell\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"1. Exit the Virtual Environment\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"exit\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Find more information and a video in [docs.pipenv.org](https://docs.pipenv.org/).\\n\",\r\n    \"\\n\",\r\n    \"[*Return to the Top*](#python-cheatsheet)\\n\",\r\n    \"\\n\",\r\n    \"### anaconda\\n\",\r\n    \"\\n\",\r\n    \"[Anaconda](https://anaconda.org/) is another popular tool to manage python packages.\\n\",\r\n    \"\\n\",\r\n    \"> Where packages, notebooks, projects and environments are shared. \\n\",\r\n    \"Your place for free public conda package hosting.\\n\",\r\n    \"\\n\",\r\n    \"Usage:\\n\",\r\n    \"\\n\",\r\n    \"1. Make a Virtual Environment\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"conda create -n HelloWorld\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"2. To use the Virtual Environment, activate it by:\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"conda activate HelloWorld\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"Anything installed now will be specific to the project HelloWorld\\n\",\r\n    \"\\n\",\r\n    \"3. Exit the Virtual Environment\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"code\",\r\n   \"execution_count\": null,\r\n   \"metadata\": {},\r\n   \"outputs\": [],\r\n   \"source\": [\r\n    \"conda deactivate\\n\"\r\n   ]\r\n  },\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"[*Return to the Top*](#python-cheatsheet)\"\r\n   ]\r\n  }\r\n ],\r\n \"metadata\": {},\r\n \"nbformat\": 4,\r\n \"nbformat_minor\": 2\r\n}\r\n"
  },
  {
    "path": "README.md",
    "content": "# Cheat-Sheets\n\n<p align=\"center\">\n  <img src=\"Cheat Sheets.png\">\n</p>\n\nA cheat sheets can be really helpful when you're trying a set of exercises related to a specific topic, or working on a project. Because you can only fit so much information on a single sheet of paper, most cheat sheets are a simple listing of syntax rules. This set of cheat sheets aims to remind you of syntax rules, but also remind you of important concepts as well.\n\n# Table of Contents\n\n* [Angular](https://github.com/black-shadows/Cheat-Sheets/tree/master/Angular)\n* [BigO](https://github.com/black-shadows/Cheat-Sheets/tree/master/BigO)\n* [Bits](https://github.com/black-shadows/Cheat-Sheets/tree/master/Bits)\n* [C++](https://github.com/black-shadows/Cheat-Sheets/tree/master/C%2B%2B)\n* [C](https://github.com/black-shadows/Cheat-Sheets/tree/master/C)\n* [Command Line](https://github.com/black-shadows/Cheat-Sheets/tree/master/Command%20Line)\n* [Django](https://github.com/black-shadows/Cheat-Sheets/tree/master/Django)\n* [Elixir](https://github.com/black-shadows/Cheat-Sheets/tree/master/Elixir)\n* [Git](https://github.com/black-shadows/Cheat-Sheets/tree/master/Git)\n* [Golang](https://github.com/black-shadows/Cheat-Sheets/tree/master/Golang)\n* [Java](https://github.com/black-shadows/Cheat-Sheets/tree/master/Java)\n* [JavaScript](https://github.com/black-shadows/Cheat-Sheets/tree/master/JavaScript)\n* [Kotlin](https://github.com/black-shadows/Cheat-Sheets/tree/master/Kotlin)\n* [MATLAB](https://github.com/black-shadows/Cheat-Sheets/tree/master/MATLAB)\n* [Markdown](https://github.com/black-shadows/Cheat-Sheets/tree/master/Markdown)\n* [Oracle SQL](https://github.com/black-shadows/Cheat-Sheets/tree/master/Oracle%20SQL)\n* [PHP](https://github.com/black-shadows/Cheat-Sheets/tree/master/PHP)\n* [Perl](https://github.com/black-shadows/Cheat-Sheets/tree/master/Perl)\n* [Python](https://github.com/black-shadows/Cheat-Sheets/tree/master/Python)\n* [React](https://github.com/black-shadows/Cheat-Sheets/tree/master/React)\n* [Ruby on Rails](https://github.com/black-shadows/Cheat-Sheets/tree/master/Ruby%20on%20Rails)\n* [Ruby](https://github.com/black-shadows/Cheat-Sheets/tree/master/Ruby)\n* [Scala](https://github.com/black-shadows/Cheat-Sheets/tree/master/Scala)\n* [Swift](https://github.com/black-shadows/Cheat-Sheets/tree/master/Swift)\n* [System Design](https://github.com/black-shadows/Cheat-Sheets/tree/master/System%20Design)\n\n# Contribute\n\nAll contributions are welcome:\n\n* Read the issues, Fork the repository and do a Pull Request.\n* Request a new topic creating a New issue with the enhancement tag.\n* Find any kind of errors in the cheat sheets and create a New issue with the details or fork the repository and do a Pull Request.\n* Suggest a better or more organized way for existing examples.\n\nIf you have any questions about the cheat sheets you can find here, feel free to contact me **abhisheksharma.0517@gmail.com**.\n"
  },
  {
    "path": "React/README.md",
    "content": "# 🌈 React Cheat Sheet\r\n\r\n> A simple cheat sheet for facilitate the process in the workshops and event about React. Let me know if you see any problem, I'll love a pull request for improve this document.\r\n\r\n## Table of contents\r\n\r\n- [x] [Installation](#installation)\r\n- [x] [No configuration](#no-configuration)\r\n- [x] [ReactDOM](#reactdom)\r\n- [x] [Functional Stateless Component](#functional-stateless-component)\r\n- [x] [Class Component](#class-component)\r\n- [x] [Composition](#composition)\r\n- [x] [Module component](#module-component)\r\n- [x] [Hot Module Replacement](#hot-module-replacement)\r\n- [x] [Props](#props)\r\n- [x] [State](#state)\r\n- [x] [Methods and Events](#methods-and-events)\r\n- [x] [State manipulation](#state-manipulation)\r\n- [x] [Bindings](#bindings)\r\n- [ ] [Refs](#refs)\r\n- [ ] [Keys](#keys)\r\n- [ ] [Component Lifecycle](#component-lifecycle)\r\n- [ ] [Inline Styles](#inline-styles)\r\n- [ ] [React Router](#react-router)\r\n- [ ] [Storybook](#storybook)\r\n- [ ] [Tests](#tests)\r\n- [ ] [a11y](#a11y)\r\n- [ ] [API comunication](#api-comunication)\r\n- [ ] [Flux](#flux)\r\n- [ ] [Redux](#redux)\r\n- [ ] [MobX](#mobx)\r\n- [ ] [Best Practices](#best-practices)\r\n- [ ] [Concepts](Concepts)\r\n    - [ ] [Immutable](#immutable)\r\n    - [ ] [Functionnal programing](#functionnal-programing)\r\n    - [ ] [Virtual Dom](#virtual-dom)\r\n- [x] [ES6](#es6)\r\n    - [x] [Arrow Functions](#arrow-functions)\r\n        - [x] [Syntax](#syntax)\r\n        - [x] [Advanced Syntax](#advanced-syntax)\r\n    - [x] [Spread Operations](#spread-operations)\r\n        - [x] [Spread in array literals](#spread-in-array-literals)\r\n        - [x] [Spread in object literals](#spread-in-object-literals)\r\n\r\n---\r\n\r\n## Installation\r\n\r\n* Add the tags in your HTML\r\n    ```HTML\r\n    <script src=\"https://unpkg.com/react@16/umd/react.development.js\" crossorigin></script>\r\n    <script src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\" crossorigin></script>\r\n    ```\r\n* Run this scripts in your terminal\r\n    ```SSH\r\n    $ npm install react react-dom\r\n    ```\r\n \r\n **[⬆ back to top](#table-of-contents)**\r\n---\r\n \r\n## No configuration\r\n\r\nJust start with React no configuration (run the scripts bellow in your terminal)\r\n* Install the React\r\n    ```SSH\r\n    $ npm install -g create-react-app\r\n    ```\r\n* Create your application (change `myApp` to your application name)\r\n    ```\r\n    $ create-react-app myApp\r\n    ```\r\n* Go to the application folder and install the dependencies\r\n    ```\r\n    $ cd myApp\r\n    $ npm install\r\n    ```\r\n* Start your application\r\n    ```\r\n    $ npm start\r\n    ```\r\n* Go to the browser by `URL` bellow and see your beautiful application   \r\n    - [localhost:8080](http://localhost:8080)\r\n\r\n**[⬆ back to top](#table-of-contents)** \r\n---\r\n\r\n## ReactDOM\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\nimport ReactDOM from 'react-dom';\r\n\r\nReactDOM.render( <h1>Hello React Ladies</h1>, document.getElementById('root') );\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## Functional Stateless Component\r\n\r\n```JS\r\nimport React from 'react';\r\n\r\nconst Button = () =>\r\n    <button> Apply</button>\r\n\r\nexport default Button;\r\n```\r\n\r\n```JS\r\nimport React from 'react';\r\n\r\nconst Button = ({ onClick, className = 'button', children  }) =>\r\n    <button\r\n        onClick={ onClick }\r\n        className={ className }\r\n        type='button'\r\n    >\r\n        { children }\r\n    </button>\r\n\r\nexport default Button;\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## Class Component\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass MyComponent extends Component {\r\n    render() {\r\n        return (\r\n            <div className=\"main\">\r\n                <h1>Helo Devas</h1>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default MyComponent;\r\n```\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass MyComponent () extends Compnent {\r\n    constructor ( props ) {\r\n    super(props);\r\n    this.state = { message: 'Helo Devas' }\r\n    };\r\n\r\n    render() {\r\n        return (\r\n            <div className=\"main\">\r\n                <h1>{ this.state.message }</h1>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default MyComponent;\r\n\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n--- \r\n\r\n## Composition\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\nimport ReactDOM from 'react-dom';\r\n\r\nclass Love extends Component {\r\n    render() {\r\n        return (\r\n            <div clssName=\"love\">\r\n                <h1>My love</h1>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nclass LoveList extends Component {\r\n    render() {\r\n        return (\r\n            <div>\r\n                <Love />\r\n                <Love />\r\n                <Love />\r\n                <Love />\r\n            </>\r\n        );\r\n    }\r\n}\r\n\r\nReactDOM.render(\r\n    <Love />,\r\n    document.getElementById(´root´)\r\n);\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n```\r\n\r\n## Module component\r\n\r\n```JS\r\n//App.js\r\nimport React, { Component } from 'react';\r\n\r\nclass App extends Component {\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <p>My App</p>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default App\r\n```\r\n\r\n```JS\r\n//Index.js\r\nimport React, { Component } from 'react';\r\nimport ReactDOM from 'react-dom';\r\nimport App from './App.js';\r\n\r\nclass Index extends Component {\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <App />\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\n\r\nReactDOM.render (\r\n    <Index />,\r\n    document.getElementById('root')\r\n);\r\n\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## Hot Module Replacement\r\n* Retain application state which is lost during a full reload.\r\n* Save valuable development time by only updating what's changed.\r\n* Tweak styling faster -- almost comparable to changing styles in the browser's debugger.\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\nimport ReactDOM from 'react-dom';\r\nimport MyComponent from './MyComponent';\r\n\r\nReactDOM.render( <MyComponent />, document.getElementById('root') );\r\n\r\nif (module.hot) {\r\n    module.hot.accept();\r\n}\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## Props\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass App extends Component {\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <p>My App {this.props.name}</p>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nclass Index extends Component {\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <App name=\"Simone\"/>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default Index;\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## State\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass App extends Component {\r\n    constructor(props) {\r\n        super(props);\r\n        this.state = {messages: 0};\r\n    } \r\n\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <p>My messages: {this.state.messages}</p>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default App;\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## Methods and Events\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass App extends Component {\r\n\r\n    escreve() {\r\n      console.log(\"Eu te amo\");\r\n    }\r\n\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <button onClick={this.escreve}>save</button>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default App;\r\n```\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\n\r\n## State manipulation\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass App extends Component {\r\n    constructor() {\r\n        super();\r\n        this.state = { like: 0 };\r\n    } \r\n\r\n    isLiked = () => {\r\n      this.setState({ like: this.state.like + 1});\r\n    }\r\n\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <button onClick={ this.isLiked }>{ this.state.like }</button>\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default App;\r\n```\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass App extends Component {\r\n    constructor() {\r\n        super();\r\n        this.state = { messages: ['JS', 'React'] };\r\n    } \r\n\r\n    addMessages = () => {\r\n        const updateMessages = [...this.state.messages, 'Polymer']\r\n        this.setState({ messages: [...updateMessages] })\r\n    }\r\n\r\n    render() {\r\n        return (\r\n            <div className=\"app\">\r\n                <button onClick={this.addMessages}>add</button>\r\n                {console.log(this.state.messages) /* ['JS', 'React', 'Polymer'] */}\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default App;\r\n```\r\n\r\n\r\n**[⬆ back to top](#table-of-contents)**\r\n---\r\nd\r\n## Bindings\r\n\r\n```JS\r\nimport React, { Component } from 'react';\r\n\r\nclass MyComponent extends Component {\r\n    constructor () {\r\n    super();\r\n\r\n    this.state = { list: list };\r\n\r\n    this.doSomethingElse = this.doSomethingElse.bind(this);\r\n    };\r\n\r\n    doSomething = () => {\r\n        // do something\r\n        /* if don't have a parameter, you can use arrow function\r\n           and don't need to use bind */\r\n    }\r\n\r\n    doSomethingElse ( itemId ) {\r\n        // do something else\r\n    }\r\n\r\n    render() {\r\n        return (\r\n            <div className=\"main\">\r\n                {this.state.list.map( item =>\r\n                ...\r\n                    <button \r\n                        onClick={ this.doSomething } \r\n                        type=\"button\"\r\n                    >\r\n                        Some Thing\r\n                    </button>\r\n\r\n                    <button \r\n                        onClick={ () => this.doSomethingElse( item.objectID ) } \r\n                        type=\"button\"\r\n                    >\r\n                        Some Thing Else\r\n                    </button>\r\n                ...\r\n                )}\r\n            </div>\r\n        );\r\n    }\r\n}\r\n\r\nexport default MyComponent;\r\n```\r\n\r\n---\r\n\r\n# ES6\r\n\r\n## Arrow Functions\r\n\r\n### Syntax\r\n\r\n  #### Basic syntax\r\n    ```JS\r\n    ( param1, param2, ..., paramN ) => { statements }\r\n\r\n    ( param1, param2, ..., paramN ) =>  expression\r\n\r\n    ( singleParam ) => { statements }\r\n\r\n    singleParam => { statements }\r\n\r\n    () => { statements }\r\n    ```\r\n  #### Advanced Syntax\r\n    ```JS\r\n    params => ({ foo: bar }) /* return an object literal expression */\r\n\r\n    ( param1, param2, ...ladies ) =>  { statements } /* rest parameters */\r\n\r\n    ( language = JS, ladies, ..., framework = React ) => { statements } /* default parameters */\r\n\r\n    const sum = ( [num1, num2] = [1, 2], { x: num3 } = { x : num1 + num2 } ) => num1 + num2 + num3  /*  destructuring within the parameter list */\r\n    sum() /* 6 */\r\n    ```\r\n\r\n---\r\n\r\n## Spread Operations\r\n\r\n### Spread in array literals\r\n```JS\r\nconst basics = [ 'JS', 'HTML', 'CSS' ];\r\nconst frameworks = [ 'React', 'Vue' ];\r\nconst web = [ ...basics, ...frameworks ]; \r\nconsole.log(web); /* ['JS', 'HTML', 'CSS', 'React', 'Vue'] */\r\n\r\nconst addWeb = [ ...web, 'al11' ];\r\nconsole.log(addWeb); /* ['JS', 'HTML', 'CSS', 'React', 'Vue', 'al11'] */\r\n```\r\n\r\n### Spread in object literals\r\n```JS\r\nconst basics = { behavior: 'JS', markup: 'HTML' };\r\nconst style = 'CSS';\r\nconst web = { ...basics, style }; \r\nconsole.log(web); /* { behavior: \"JS\", markup: \"HTML\", style: \"CSS\" } */\r\n\r\nconst devFront = { framework: 'react', event: 'React Conf' };\r\nconst devBack = { framework: 'django', state: 'cool' };\r\n\r\nconst cloneDev = { ...devFront };\r\nconsole.log(cloneDev); /* { framework: 'react', event: 'React Conf' } */\r\n\r\nconst merged = { ...devFront, ...devBack };\r\nconsole.log(cloneDev); /* { framework: 'django', event: 'React Conf', state: 'cool' } */\r\n```"
  },
  {
    "path": "React/react-placar.md",
    "content": "\r\n![template-placar](img/template-placar.PNG)\r\n\r\n# React Placar\r\n\r\n> Um Simples exemplo de uso da biblioteca React.js by [Aprendendo React na prática - Props (Parte 8)](https://www.youtube.com/watch?v=eQV-UV0oz9k)\r\n\r\nPassos dos componentes:\r\n- Tudo começa no `App.js` que é o componente que possui os dados\r\n- Esses dados são passados como propriedade para o componente `PlacarContainer`\r\n- O componente `PlacarContainer` contém dois estados `gols_casa` e `gols_visitante` que são manipulados pelos métodos `marcarGolCasa` e `marcarGolVisitante`\r\n- O componente `PlacarContainer` contém mais dois componentes `Partida` e `Time` que recebem as propriedades que o componente `PlacarContainer` herdou do componente  `App.js`\r\n- O componente `Time` utiliza a informação recebida por `PlacarContainer`, renderiza e repassa uma função para o componente `BotaoGol` informando como ele deve marcar um gol\r\n- O componente `BotaoGol` recebe a informação através de propriedade e segue os comandos repassados, que na verdade altera o estada do componente `PlacarContainer`\r\n\r\n```JS\r\n`src/app.js`\r\n\r\nimport React from 'react';\r\nimport ReactDOM from 'react-dom';\r\nimport App from './src/components/App';\r\n\r\nReactDOM.render(<App />, document.getElementById('root'));\r\n```\r\n\r\n```JS\r\n`src/components/App.js`\r\n\r\nimport React, { Component } from 'react';\r\nimport PlacarContainer from './src/components/PlacarContainer';\r\n\r\nclass App extends Component {\r\n\r\nconst dados = {\r\n  partida: {\r\n    estadio: \"Maracanã/RJ\",\r\n    data: \"22/05/2017\",\r\n    horario: \"19h\"\r\n  },\r\n  casa: {\r\n    nome: \"Vasco\"\r\n  },\r\n  visitante: {\r\n    nome: \"Flamengo\"\r\n  }\r\n}\r\n\r\n  render() {\r\n    //- passando as propriedades do componente `App` para o componente `PlacarContainer`\r\n    return <PlacarContainer partida={ dados.partida}\r\n                            casa={ dados.casa}\r\n                            visitante={ dados.visitante} />;\r\n}\r\n\r\nexport default App;\r\n```\r\n\r\n```JS\r\n`src/components/PlacarContainer.js`\r\n\r\nimport React, { Component } from 'react';\r\nimport Time from './src/components/Time';\r\nimport Partida from './src/components/Partida';\r\n\r\nclass PlacarContainer extends Component {\r\n  constructor() {\r\n    super();\r\n    this.state = {\r\n      gols_casa: 0,\r\n      gols_visitante: 0\r\n    }\r\n\r\n    marcarGolCasa() {\r\n      this.setState({\r\n        gols_casa: this.setState.gols_casa + 1\r\n      })\r\n    }\r\n\r\n    marcarGolVisitante() {\r\n      this.setState({\r\n        gols_visitante: this.setState.gols_visitante + 1\r\n      })\r\n    }\r\n  }\r\n\r\n  render() {\r\n    return (\r\n      <div>\r\n        <div>\r\n          <h3>casa</h3>\r\n          <Time nome={this.props.casa.nome} \r\n                gols={this.state.gols_casa}\r\n                marcarGol={this.marcarGolCasa.bind(this)} />\r\n        </div>\r\n        <div>\r\n          <Partida estadio={this.props.partida.estadio} \r\n                   data={this.props.partida.data}\r\n                   horario={this.props.partida.horario />\r\n        </div>\r\n        <div>\r\n          <h3>Visitante</h3>\r\n          <Time nome={this.props.visitante.nome} \r\n                gols={this.state.gols_visitante}\r\n                marcarGol={this.marcarGolvisitante.bind(this)} />\r\n        </div>\r\n      </div>\r\n    )\r\n}\r\n\r\nexport default PlacarContainer;\r\n```\r\n\r\n```JS\r\n`src/components/Time.js`\r\n\r\nimport React, { Component } from 'react';\r\nimport BotaoGol from './src/components/BotaoGol';\r\n\r\nclass Time extends Component {\r\n\r\n  render() {\r\n    return (\r\n      <div>\r\n        <h1>{this.props.nome}</h1>\r\n        <h1>{this.props.gols}</h1>\r\n        <BotaoGol marcarGol={this.props.marcarGol} />\r\n      </div>\r\n    )\r\n}\r\n\r\nexport default Time;\r\n```\r\n\r\n```JS\r\n`src/components/Partida.js`\r\n\r\nimport React, { Component } from 'react';\r\n\r\nclass Partida extends Component {\r\n\r\n  render() {\r\n    return (\r\n      <div>\r\n        h2>{this.props.estadio}</h2>\r\n        <div>\r\n          <span>{this.props.data}</span>\r\n          <span>-</span>\r\n          <span>{this.props.horario}</span>\r\n        </div>\r\n      </div>\r\n    )\r\n}\r\n\r\nexport default Partida;\r\n```\r\n\r\n```JS\r\n`src/components/BotaoGol.js`\r\n\r\nimport React, { Component } from 'react';\r\n\r\nclass BotaoGol extends Component {\r\n  thishandleClick(event) {\r\n    event.preventDefault(); //- ação para cancelar o evento padrão do botão.\r\n    this.props.marcarGol(); //- ao clicar irá acionar esse método  que pertence ao componente PlacarContainer \r\n  }\r\n\r\n  render() {\r\n    return (\r\n      <button onClick={thishandleClick.bind(this)}><button>\r\n    )\r\n}\r\n\r\nexport default BotaoGol;\r\n```"
  },
  {
    "path": "Ruby/README.md",
    "content": "# Ruby Cheatsheet\r\n\r\nRuby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.\r\n\r\n## Table of Contents  \r\n* [Basics](#basics)  \r\n* [Vars, Constants, Arrays, Hashes & Symbols](#vars-constants-arrays-hashes--symbols)  \r\n* [Methods](#methods)\r\n* [Classes](#classes)\r\n* [Modules](#modules)\r\n* [Blocks and Procs](#blocks-and-procs)  \r\n* [Lambdas](#lambdas)\r\n* [Calculation](#calculation)  \r\n* [Comment](#comment)  \r\n* [Conditions](#conditions)  \r\n* [Printing and Putting](#printing-and-putting)  \r\n* [User Input](#user-input)\r\n* [Loops](#loops)\r\n* [Sorting and Comparing](#sorting-and-comparing)  \r\n* [Useful Methods](#useful-methods)  \r\n\r\n## Basics\r\n*$ irb –– to write ruby in the terminal*  \r\n*don't use ' in ruby, use \" instead*  \r\n*you can replace most {} with do end and vice versa –– not true for hashes or #{} escapings*  \r\n*Best Practice: end names that produce booleans with question mark*\r\n*CRUD: create, read, update, delete*  \r\n*[1,2].map(&:to_i)*\r\n*integer = number without decimal || float = number with decimal*\r\n*tag your variables: $ = global, @ = instance, @@ = class variable*  \r\n*1_000_000 = 1000000 –– just easier to read*  \r\n\r\n## Vars, Contants, Arrays, Hashes & Symbols\r\n```Ruby\r\nmy_variable = “Hello”  \r\nmy_variable.capitalize! # ! changes the value of the var same as my_name = my_name.capitalize\r\nmy_variable ||= \"Hi\" # ||= is a conditional assignment only set the variable if it was not set before. \r\n```\r\n**Constants**\r\n```Ruby\r\nMY_CONSTANT = # something\r\n```\r\n**Arrays**\r\n```Ruby  \r\nmy_array = [a,b,c,d,e]  \r\nmy_array[1] –– b  \r\nmy_array[2..-1] # c , d , e  \r\nmulti_d = [[0,1],[0,1]]\r\n[1, 2, 3] << 4 # [1, 2, 3, 4] same as [1, 2, 3].push(4)\r\n```\r\n**Hashes**\r\n```Ruby  \r\nhash = { \"key1\" => \"value1\", \"key2\" => \"value2\" } # same as objects in JavaScript\r\nhash = { key1: \"value1\", key2: \"value2\" } # the same hash using symbols instead of strings\r\nmy_hash = Hash.new # same as my_hash = {} – set a new key like so: pets[\"Stevie\"] = \"cat\"\r\npets[\"key1\"] # value1\r\npets[\"Stevie\"] # cat\r\nmy_hash = Hash.new(\"default value\")\r\nhash.select{ |key, value| value > 3 } # selects all keys in hash that have a value greater than 3\r\nhash.each_key { |k| print k, \" \" } # ==> key1 key2\r\nhash.each_value { |v| print v } # ==> value1value2\r\n\r\nmy_hash.each_value { |v| print v, \" \" }\r\n# ==> 1 2 3\r\n```\r\n**Symbols**\r\n```Ruby\r\n:symbol # symbol is like an ID in html. :Symbols != \"Strings\"\r\n# Symbols are often used as Hash keys or referencing method names.\r\n# They can not be changed once created. They save memory (only one copy at a given time). Faster.\r\n:test.to_s # converts to \"test\"\r\n\"test\".to_sym # converts to :test\r\n\"test\".intern # :test\r\n# Symbols can be used like this as well:\r\nmy_hash = { key: \"value\", key2: \"value\" } # is equal to { :key => \"value\", :key2 => \"value\" }\r\n```\r\n\r\n#### Functions to create Arrays\r\n```Ruby\r\n\"bla,bla\".split(“,”) # takes sting and returns an array (here  [\"bla\",\"bla\"])\r\n```\r\n\r\n## Methods\r\n**Methods**\r\n```Ruby\r\ndef greeting(hello, *names) # *name is a splat argument, takes several parameters passed in an array\r\n  return \"#{hello}, #{names}\"\r\nend\r\n\r\nstart = greeting(\"Hi\", \"Justin\", \"Maria\", \"Herbert\") # call a method by name\r\n\r\ndef name(variable=default)\r\n  ### The last line in here get's returned by default\r\nend\r\n```\r\n\r\n## Classes\r\n*custom objects*\r\n```Ruby\r\nclass ClassName # class names are rather written in camelcase\r\n  @@count = 0\r\n  attr_reader :name # make it readable\r\n  attr_writer :name # make it writable\r\n  attr_accessor :name # makes it readable and writable\r\n\r\n  def Methodname(parameter) \r\n    @classVariable = parameter\r\n    @@count += 1\r\n  end\r\n\r\n  def self.show_classVariable\r\n    @classVariable\r\n  end\r\n\r\n  def Person.get_counts # is a class method\r\n    return @@count\r\n  end \r\n  \r\n  private\r\n  \r\n  def private_method; end # Private methods go here\r\nend\r\n\r\nmatz = Person.new(\"Yukihiro\")\r\nmatz.show_name # Yukihiro\r\n```\r\n*inheritance*\r\n```Ruby\r\nclass DerivedClass < BaseClass; end # if you want to end a Ruby statement without going to a new line, you can just type a semicolon.\r\n\r\nclass DerivedClass < Base\r\n  def some_method\r\n    super(optional args) # When you call super from inside a method, that tells Ruby to look in the superclass of the current class and find a method with the same name as the one from which super is called. If it finds it, Ruby will use the superclass' version of the method.\r\n      # Some stuff\r\n    end\r\n  end\r\nend\r\n\r\n# Any given Ruby class can have only one superclass. Use mixins if you want to incorporate data or behavior from several classes into a single class.\r\n```\r\n\r\n## Modules\r\n```Ruby\r\nmodule ModuleName # module names are rather written in camelcase\r\n  # variables in modules doesn't make much sence since modules do not change. Use constants. \r\nend\r\n\r\nMath::PI # using PI constant from Math module. Double colon = scope resolution operator = tells Ruby where you're looking for a specific bit of code.\r\n\r\nrequire 'date' # to use external modules.\r\nputs Date.today # 2016-03-18\r\n\r\nmodule Action\r\n  def jump\r\n    @distance = rand(4) + 2\r\n    puts \"I jumped forward #{@distance} feet!\"\r\n  end\r\nend\r\n\r\nclass Rabbit\r\n  include Action # Any class that includes a certain module can use those module's methods! This now is called a Mixin.\r\n  extend Action # extend keyword mixes a module's methods at the class level. This means that class itself can use the methods, as opposed to instances of the class.\r\n  attr_reader :name\r\n  def initialize(name)\r\n    @name = name\r\n  end\r\nend\r\n\r\npeter = Rabbit.new(\"Peter\")\r\npeter.jump # include\r\nRabbit.jump # extend\r\n```\r\n\r\n## Blocks and Procs\r\n**Code Blocks**  \r\n*Blocks are not objects* A block is just a bit of code between do..end or {}. It's not an object on its own, but it can be passed to methods like .each or .select.\r\n```Ruby\r\ndef yield_name(name)\r\n  yield(\"Kim\") # print \"My name is Kim. \"\r\n  yield(name) # print \"My name is Eric. \"\r\nend\r\n\r\nyield_name(\"Eric\") { |n| print \"My name is #{n}. \" } # My name is Kim. My name is Eric. \r\nyield_name(\"Peter\") { |n| print \"My name is #{n}. \" } # My name is Kim. My name is Eric. My name is Kim. My name is Peter. \r\n```\r\n**Proc**\r\n*saves blocks and are objects* A proc is a saved block we can use over and over.\r\n```Ruby\r\ncube = Proc.new { |x| x ** 3 }\r\n[1, 2, 3].collect!(&cube) # [1, 8, 27] # the & is needed to transform the Proc to a block.\r\ncube.call # call procs directly\r\n```\r\n\r\n## Lambdas\r\n```Ruby\r\nlambda { |param| block }\r\nmultiply = lambda { |x| x * 3 }\r\ny = [1, 2].collect(&multiply) # 3 , 6\r\n```\r\nDiff between blocs and lambdas:  \r\n- a lambda checks the number of arguments passed to it, while a proc does not (This means that a lambda will throw an error if you pass it the wrong number of arguments, whereas a proc will ignore unexpected arguments and assign nil to any that are missing.)  \r\n- when a lambda returns, it passes control back to the calling method; when a proc returns, it does so immediately, without going back to the calling method.\r\nSo: A lambda is just like a proc, only it cares about the number of arguments it gets and it returns to its calling method rather than returning immediately.\r\n\r\n## Calculation\r\nAddition (+)  \r\nSubtraction (-)  \r\nMultiplication (*)  \r\nDivision (/)  \r\nExponentiation (**)  \r\nModulo (%)  \r\nyou can do 1 += 1 –– which gives you 2 but 1++ and 1-- does not exist in ruby  \r\nThe concatenation operator (<<)\r\n\"A \" << \"B\" # \"A B\" but \"A \" + \"B\" would work as well but \"A \" + 4 + \" B\" not so rather use \r\nstring interpolation (#{4})\r\n\"A #{4} B\" # \"A 4 B\"\r\n\r\n## Comment\r\n```Ruby\r\n=begin  \r\nBla\r\nMultyline comment  \r\n=end\r\n```  \r\n```Ruby\r\n# single line comment\r\n```\r\n\r\n## Conditions\r\n**IF**\r\n```Ruby\r\nif 1 < 2  \r\nputs “one smaller than two”  \r\nelsif 1 > 2 # *careful not to mistake with else if. In ruby you write elsif*  \r\nputs “elsif”  \r\nelse  \r\nputs “false”  \r\nend\r\n# or\r\nputs \"be printed\" if true\r\nputs 3 > 4 ? \"if true\" : \"else\" # else will be putted\r\n```  \r\n**unless**\r\n```Ruby\r\nunless false # unless checks if the statement is false (opposite to if).  \r\nputs “I’m here”  \r\nelse \r\nputs “not here”  \r\nend\r\n# or\r\nputs \"not printed\" unless true\r\n```  \r\n**case**\r\n```Ruby\r\ncase my_var\r\n  when \"some value\"\r\n    ###\r\n  when \"some other value\"\r\n    ###\r\n  else\r\n    ###\r\nend\r\n# or\r\ncase my_var\r\n  when \"some value\" then ###\r\n  when \"some other value\" then ###\r\n  else ###\r\nend\r\n```\r\n\r\n**&&** –– and  **||** –– or  **!** –– not  \r\n**(x && (y || w)) && z** –– use parenthesis to combine arguments  \r\nproblem = false  \r\nprint \"Good to go!\" unless problem –– prints out because problem != true  \r\n\r\n## Printing and Putting\r\n```Ruby\r\nprint “bla” \r\nputs “test” # puts the text in a separate line\r\n```\r\n\r\n## String Methods\r\n```Ruby\r\n“Hello”.length # 5  \r\n\"Hello”.reverse # “olleH”  \r\n\"Hello”.upcase # “HELLO”  \r\n\"Hello”.downcase # “hello”  \r\n“hello”.capitalize # “Hello”  \r\n“Hello”.include? “i” # equals to false because there is no i in Hello  \r\n“Hello”.gsub!(/e/, “o”) # Hollo\r\n\"1\".to_i # transform string to integer –– 1\r\n\"test\".to_sym # converts to :test\r\n\"test\".intern # :test\r\n:test.to_s # converts to \"test\"\r\n```  \r\n\r\n## User Input\r\n```Ruby\r\ngets # is the Ruby equivalent to prompt in javascript (method that gets input from the user)\r\ngets.chomp # removes extra line created after gets (usually used like this)\r\n```\r\n\r\n## Loops\r\n**While loop:**  \r\n```Ruby\r\ni = 1  \r\nwhile i < 11  \r\n  puts i  \r\n  i = i + 1  \r\nend  \r\n```\r\n\r\n**Until loop:**  \r\n```Ruby\r\ni = 0  \r\nuntil i == 6  \r\n  puts i  \r\n  i += 1  \r\nend\r\n```  \r\n\r\n**For loop**  \r\n```Ruby\r\nfor i in 1...10 # ... tells ruby to exclude the last number (here 10 if we .. only then it includes the last num)  \r\n  puts i  \r\nend  \r\n```\r\n\r\n**Loop iterator**  \r\n```Ruby\r\ni = 0  \r\nloop do\r\n  i += 1  \r\n  print \"I'm currently number #{i}” # a way to have ruby code in a string   \r\n  break if i > 5  \r\nend  \r\n```\r\n\r\n**Next**  \r\n```Ruby\r\nfor i in 1..5  \r\n  next if i % 2 == 0 # If the remainder of i / 2 is zero, we go to the next iteration of the loop.  \r\n  print i  \r\nend  \r\n```\r\n\r\n**.each**  \r\n```Ruby\r\nthings.each do |item| # for each things in things do something while storing that things in the variable item  \r\n  print “#{item}\"  \r\nend  \r\n```\r\non hashes like so:  \r\n```Ruby\r\nhashes.each do |x,y|\r\n  print \"#{x}: #{y}\"\r\nend\r\n```\r\n\r\n**.times**  \r\n```Ruby\r\n10.times do  \r\n  print “this text will appear 10 times”  \r\nend  \r\n```\r\n\r\n**.upto / .downto**\r\n```Ruby\r\n10.upto(15) { |x| print x, \" \" } # 10 11 12 13 14 15  \r\n\"a\".upto(\"c\") { |x| print x, \" \" } # a b c  \r\n```\r\n\r\n## Sorting and Comparing\r\n```Ruby\r\narray = [5,4,1,3,2]\r\narray.sort! # = [1,2,3,4,5] – works with text and other as well.\r\n\"b\" <=> \"a\" # = 1 – combined comparison operator. Returns 0 if first = second, 1 if first > second, -1 if first < second\r\narray.sort! { |a, b| b <=> a } # to sort from Z to A instead of A to Z\r\n```\r\n\r\n## Useful Methods\r\n```Ruby\r\n1.is_a? Integer # returns true\r\n:1.is_a? Symbol # returns true\r\n\"1\".is_a? String # returns true\r\n[1,2,3].collect!() # does something to every element (overwrites original with ! mark)\r\n.map() # is the same as .collect\r\n1.2.floor # 1 # rounds a float (a number with a decimal) down to the nearest integer.\r\ncube.call # implying that cube is a proc, call calls procs directly \r\nTime.now # displays the actual time\r\n```\r\n"
  },
  {
    "path": "Ruby on Rails/README.md",
    "content": "Looking for [Ruby](../Ruby-Cheatsheet.md)?  \r\n\r\n#Ruby on Rails Cheatsheet\r\n\r\n##### Table of Contents  \r\n[Basics](#basics)   \r\n[Connect a Database](#connect-a-database)   \r\n[Rake](#rake)   \r\n[Troubleshoots](#troubleshoots)\r\n\r\n##Basics\r\n####request/response cycle  \r\ncontroller > route > view  \r\nlearn request/response cycle: https://www.codecademy.com/articles/request-response-cycle-forms  \r\n\r\n####1. Generate a new Rails app\r\n```\r\n$ rails new MySite\r\n–– or using Postgress –– $ rails new myapp --database=postgresql\r\n$ bundle install\r\n$ rails server\r\n\r\n> http://localhost:8000 –– or similar Number up and running!\r\n```\r\n\r\n####2. Generate a controller and add an action\r\n```\r\n$ rails generate controller Pages\r\n```\r\ngenerates a new controller named Pages  \r\n\r\nOpen: app/controllers/pages_controller.rb\r\n```Ruby\r\nclass PagesController < ApplicationController\r\n  \r\n  def home # add the home action/method to the pages controller\r\n  end\r\n\r\nend\r\n```\r\n\r\n####3. Create a route that maps a URL to the controller action  \r\nOpen: config/routes.rb\r\n```Ruby\r\nRails.application.routes.draw do\r\n\r\n  get 'welcome' => 'pages#home'\r\n\r\nend\r\n```\r\n\r\n####4. Create a view with HTML and CSS  \r\nOpen: app/views/pages/home.html.erb\r\n```html\r\n<!-- write some html -->\r\n<div class=\"main\">\r\n  <div class=\"container\">\r\n    <h1>Hello my name is King</h1>\r\n    <p>I make Rails apps.</p>\r\n  </div>\r\n</div>\r\n```\r\n\r\n##Connect a Database\r\n\r\n####Example: messaging system:\r\n\r\n####1. Generate a new Model\r\n```\r\n$ rails generate model Message\r\n```\r\ncreate model named Message. With two files: model file app/models/message.rb. Represents a table in database. Migration file db/migrate/. Way to update database.  \r\nOpen: db/migrate/*.rb –– *The name of the migration file starts with the timestamp of when it was created\r\n```Ruby\r\nclass CreateMessages < ActiveRecord::Migration\r\n  def change\r\n    create_table :messages do |t|\r\n\t\t\tt.text :content # add this\r\n      t.timestamps\r\n    end\r\n  end\r\nend\r\n```\r\n1) The change method tells Rails what change to make to the database. Here create_table method create a new table in database for storing messages.  \r\n2) t.text :content. Create text column called content in the messages tables.  \r\n3) t.timestamps is a Rails command that creates two more columns in the messages table called created_at and updated_at. These columns are automatically set when a message is created and updated.  \r\nOpen: db/seeds.rb\r\n```Ruby\r\nm1 = Message.create(content: \"We're at the beach so you should meet us here! I make a mean sandcastle. :)\")\r\nm2 = Message.create(content: \"Let's meet there!\")\r\n```\r\nJust to have dummy messages to load with db:seed     \r\nin Terminal run\r\n```\r\n$ rails db:migrate\r\n$ rake db:setup\r\n$ rake db:migrate\r\n$ rake db:seed\r\n```\r\nupdates the database with the new messages data model.  \r\nseeds the database with sample data from db/seeds.rb\r\n\r\n\r\n####2. Generate a controller and add actions\r\n```\r\n$ rails generate controller Messages\r\n```  \r\n\r\nOpen: app/controllers/messages_controller.rb\r\n```Ruby\r\nclass MessagesController < ApplicationController\r\n\r\n  # Rails defines standard controller actions can be used to do common things such as display and modify data.\r\n  # index, show, new, create, edit, update, and destroy\r\n  # code below is optional\r\n\r\n  def index \r\n    @messages = Message.all # retrieves all messages from database and stores them in variable @messages.\r\n  end\r\n  \r\n  def new\r\n    @message = Message.new # \r\n  end\r\n  \r\n  def create \r\n    @message = Message.new(message_params) \r\n    if @message.save \r\n      redirect_to '/messages' \r\n    else \r\n      render 'new' \r\n    end \r\n  end\r\n  \r\n  private\r\n  \r\n  def message_params\r\n    params.require(:message).permit(:content)\r\n  end\r\n\r\nend\r\n```\r\n\r\n####3. Create a route that maps a URL to the controller action  \r\nOpen: config/routes.rb\r\n```Ruby\r\nRails.application.routes.draw do\r\n  \r\n  get 'messages' => 'messages#index'\r\n  get 'messages/new' => 'messages#new'\r\n  post 'messages' => 'messages#create'\r\n\r\nend\r\n```\r\n\r\n####4. Create a view with HTML and CSS  \r\nOpen: app/views/messages/index.html.erb\r\n```html\r\n<div class=\"messages\">\r\n  <div class=\"container\">\r\n  \r\n    <% @messages.each do |message| %> <!-- iterates through each message in @messages created in the Messages controller's index -->\r\n      <div class=\"message\"> \r\n        <p class=\"content\"><%= message.content %></p> \r\n        <p class=\"time\"><%= message.created_at %></p> \r\n      </div> \r\n    <% end %>\r\n    \r\n    <%= link_to 'New Message', \"messages/new\" %> <!-- Sets a link to the creation page -->\r\n\r\n  </div>\r\n</div>\r\n```\r\nOpen: app/views/messages/new.html.erb\r\n```html\r\n<div class=\"create\">\r\n  <div class=\"container\">\r\n    \r\n    <!-- Create a form with a textarea field -->\r\n    <%= form_for(@message) do |f| %>  \r\n      <div class=\"field\"> \r\n        <%= f.label :message %><br> \r\n        <%= f.text_area :content %> \r\n      </div> \r\n      <div class=\"actions\"> \r\n        <%= f.submit \"Create\" %> \r\n      </div> \r\n    <% end %>\r\n    \r\n  </div>\r\n</div>\r\n```\r\n\r\n##Rake\r\n\r\n```\r\nrake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databa...\r\nrake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in...\r\nrake db:fixtures:load                   # Load fixtures into the current environment's database\r\nrake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)\r\nrake db:migrate:status                  # Display status of migrations\r\nrake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)\r\nrake db:schema:cache:clear              # Clear a db/schema_cache.dump file\r\nrake db:schema:cache:dump               # Create a db/schema_cache.dump file\r\nrake db:schema:dump                     # Create a db/schema.rb file that is portable against any DB supported by AR\r\nrake db:schema:load                     # Load a schema.rb file into the database\r\nrake db:seed                            # Load the seed data from db/seeds.rb\r\n```\r\n\r\n##Troubleshoots\r\n1. When seeing only a blank page after running rails server:  \r\nhttp://stackoverflow.com/questions/25951969/rails-4-2-and-vagrant-get-a-blank-page-and-nothing-in-the-logs  \r\n2. Follow instructions to use postgres:   \r\nhttps://www.digitalocean.com/community/tutorials/how-to-setup-ruby-on-rails-with-postgres  "
  },
  {
    "path": "Scala/README.md",
    "content": "---\r\nlayout: page\r\ntitle: Cheat Sheet\r\n---\r\n\r\nThere are certainly a lot of things that can be improved! If you would like to contribute, you have two options:\r\n\r\n- Click the \"Edit\" button on this file on GitHub:  \r\n  [https://github.com/lampepfl/progfun-wiki/blob/gh-pages/CheatSheet.md](https://github.com/lampepfl/progfun-wiki/blob/gh-pages/CheatSheet.md)  \r\n  You can submit a pull request directly from there without checking out the git repository to your local machine.\r\n\r\n- Fork the repository [https://github.com/lampepfl/progfun-wiki](https://github.com/lampepfl/progfun-wiki) and check it out locally. To preview your changes, you need [jekyll](http://jekyllrb.com/). Navigate to your checkout and invoke `jekyll serve`, then open the page [http://localhost:4000/CheatSheet.html](http://localhost:4000/CheatSheet.html).\r\n\r\n## Evaluation Rules\r\n\r\n- Call by value: evaluates the function arguments before calling the function\r\n- Call by name: evaluates the function first, and then evaluates the arguments if need be\r\n\r\n<!-- code -->\r\n```scala\r\n    def example = 2      // evaluated when called\r\n    val example = 2      // evaluated immediately\r\n    lazy val example = 2 // evaluated once when needed\r\n    \r\n    def square(x: Double)    // call by value\r\n    def square(x: => Double) // call by name\r\n    def myFct(bindings: Int*) = { ... } // bindings is a sequence of int, containing a varying # of arguments\r\n```\r\n\r\n## Higher order functions\r\n\r\nThese are functions that take a function as a parameter or return functions.\r\n```scala\r\n    // sum() returns a function that takes two integers and returns an integer  \r\n    def sum(f: Int => Int): (Int, Int) => Int = {  \r\n      def sumf(a: Int, b: Int): Int = {...}  \r\n      sumf  \r\n    } \r\n    \r\n    // same as above. Its type is (Int => Int) => (Int, Int) => Int  \r\n    def sum(f: Int => Int)(a: Int, b: Int): Int = { ... } \r\n\r\n    // Called like this\r\n    sum((x: Int) => x * x * x)          // Anonymous function, i.e. does not have a name  \r\n    sum(x => x * x * x)                 // Same anonymous function with type inferred\r\n\r\n    def cube(x: Int) = x * x * x  \r\n    sum(x => x * x * x)(1, 10) // sum of cubes from 1 to 10\r\n    sum(cube)(1, 10)           // same as above      \r\n```\r\n\r\n## Currying\r\n\r\nConverting a function with multiple arguments into a function with a\r\nsingle argument that returns another function.\r\n```scala\r\n    def f(a: Int, b: Int): Int // uncurried version (type is (Int, Int) => Int)\r\n    def f(a: Int)(b: Int): Int // curried version (type is Int => Int => Int)\r\n```\r\n    \r\n## Classes\r\n```scala\r\n    class MyClass(x: Int, y: Int) {           // Defines a new type MyClass with a constructor  \r\n      require(y > 0, \"y must be positive\")    // precondition, triggering an IllegalArgumentException if not met  \r\n      def this (x: Int) = { ... }             // auxiliary constructor   \r\n      def nb1 = x                             // public method computed every time it is called  \r\n      def nb2 = y  \r\n      private def test(a: Int): Int = { ... } // private method  \r\n      val nb3 = x + y                         // computed only once  \r\n      override def toString =                 // overridden method  \r\n          member1 + \", \" + member2 \r\n    }\r\n\r\n    new MyClass(1, 2) // creates a new object of type\r\n```\r\n\r\n`this` references the current object, `assert(<condition>)` issues `AssertionError` if condition\r\nis not met. See `scala.Predef` for `require`, `assume` and `assert`.\r\n\r\n## Operators\r\n\r\n`myObject myMethod 1` is the same as calling `myObject.myMethod(1)`\r\n\r\nOperator (i.e. function) names can be alphanumeric, symbolic (e.g. `x1`, `*`, `+?%&`, `vector_++`, `counter_=`)\r\n    \r\nThe precedence of an operator is determined by its first character, with the following increasing order of priority:\r\n\r\n    (all letters)\r\n    |\r\n    ^\r\n    &\r\n    < >\r\n    = !\r\n    :\r\n    + -\r\n    * / %\r\n    (all other special characters)\r\n   \r\nThe associativity of an operator is determined by its last character: Right-associative if ending with `:`, Left-associative otherwise.\r\n   \r\nNote that assignment operators have lowest precedence. (Read Scala Language Specification 2.9 sections 6.12.3, 6.12.4 for more info)\r\n\r\n## Class hierarchies\r\n```scala\r\n    abstract class TopLevel {    // abstract class  \r\n      def method1(x: Int): Int   // abstract method  \r\n      def method2(x: Int): Int = { ... }  \r\n    }\r\n\r\n    class Level1 extends TopLevel {  \r\n      def method1(x: Int): Int = { ... }  \r\n      override def method2(x: Int): Int = { ...} // TopLevel's method2 needs to be explicitly overridden  \r\n    }\r\n\r\n    object MyObject extends TopLevel { ... } // defines a singleton object. No other instance can be created\r\n```\r\n\r\nTo create a runnable application in Scala:\r\n\r\n```scala\r\n    object Hello {  \r\n      def main(args: Array[String]) = println(\"Hello world\")  \r\n    }\r\n```\r\n    \r\nor\r\n```scala\r\n    object Hello extends App {\r\n      println(\"Hello World\")\r\n    }\r\n```\r\n\r\n## Class Organization\r\n\r\n- Classes and objects are organized in packages (`package myPackage`).\r\n\r\n- They can be referenced through import statements (`import myPackage.MyClass`, `import myPackage._`,\r\n`import myPackage.{MyClass1, MyClass2}`, `import myPackage.{MyClass1 => A}`)\r\n\r\n- They can also be directly referenced in the code with the fully qualified name (`new myPackage.MyClass1`)\r\n\r\n- All members of packages `scala` and `java.lang` as well as all members of the object `scala.Predef` are automatically imported.\r\n\r\n- Traits are similar to Java interfaces, except they can have non-abstract members:\r\n```scala\r\n        trait Planar { ... }\r\n        class Square extends Shape with Planar\r\n```\r\n\r\n- General object hierarchy:\r\n\r\n  - `scala.Any` base type of all types. Has methods `hashCode` and `toString` that can be overridden\r\n  - `scala.AnyVal` base type of all primitive types. (`scala.Double`, `scala.Float`, etc.)\r\n  - `scala.AnyRef` base type of all reference types. (alias of `java.lang.Object`, supertype of `java.lang.String`, `scala.List`, any user-defined class)\r\n  - `scala.Null` is a subtype of any `scala.AnyRef` (`null` is the only instance of type `Null`), and `scala.Nothing` is a subtype of any other type without any instance.\r\n\r\n## Type Parameters\r\n\r\nConceptually similar to C++ templates or Java generics. These can apply to classes, traits or functions.\r\n```scala\r\n    class MyClass[T](arg1: T) { ... }  \r\n    new MyClass[Int](1)  \r\n    new MyClass(1)   // the type is being inferred, i.e. determined based on the value arguments  \r\n```\r\n\r\nIt is possible to restrict the type being used, e.g.\r\n```scala\r\n    def myFct[T <: TopLevel](arg: T): T = { ... } // T must derive from TopLevel or be TopLevel\r\n    def myFct[T >: Level1](arg: T): T = { ... }   // T must be a supertype of Level1\r\n    def myFct[T >: Level1 <: Top Level](arg: T): T = { ... }\r\n```\r\n\r\n## Variance\r\n\r\nGiven `A <: B`\r\n\r\nIf `C[A] <: C[B]`, `C` is covariant\r\n\r\nIf `C[A] >: C[B]`, `C` is contravariant\r\n\r\nOtherwise C is nonvariant\r\n```scala\r\n    class C[+A] { ... } // C is covariant\r\n    class C[-A] { ... } // C is contravariant\r\n    class C[A]  { ... } // C is nonvariant\r\n```\r\n\r\nFor a function, if `A2 <: A1` and `B1 <: B2`, then `A1 => B1 <: A2 => B2`.\r\n\r\nFunctions must be contravariant in their argument types and covariant in their result types, e.g.\r\n```scala\r\n    trait Function1[-T, +U] {\r\n      def apply(x: T): U\r\n    } // Variance check is OK because T is contravariant and U is covariant\r\n\r\n    class Array[+T] {\r\n      def update(x: T)\r\n    } // variance checks fails\r\n```\r\n\r\nFind out more about variance in\r\n[lecture 4.4](https://class.coursera.org/progfun-2012-001/lecture/81)\r\nand [lecture 4.5](https://class.coursera.org/progfun-2012-001/lecture/83)\r\n\r\n## Pattern Matching\r\n\r\nPattern matching is used for decomposing data structures:\r\n```scala\r\n    unknownObject match {\r\n      case MyClass(n) => ...\r\n      case MyClass2(a, b) => ...\r\n    }\r\n```\r\n\r\nHere are a few example patterns\r\n```scala\r\n    (someList: List[T]) match {\r\n      case Nil => ...          // empty list\r\n      case x :: Nil => ...     // list with only one element\r\n      case List(x) => ...      // same as above\r\n      case x :: xs => ...      // a list with at least one element. x is bound to the head,\r\n                               // xs to the tail. xs could be Nil or some other list.\r\n      case 1 :: 2 :: cs => ... // lists that starts with 1 and then 2\r\n      case (x, y) :: ps => ... // a list where the head element is a pair\r\n      case _ => ...            // default case if none of the above matches\r\n    }\r\n```\r\n\r\nThe last example shows that every pattern consists of sub-patterns: it\r\nonly matches lists with at least one element, where that element is a\r\npair. `x` and `y` are again patterns that could match only specific\r\ntypes.\r\n\r\n### Options\r\n\r\nPattern matching can also be used for `Option` values. Some\r\nfunctions (like `Map.get`) return a value of type `Option[T]` which\r\nis either a value of type `Some[T]` or the value `None`:\r\n```scala\r\n    val myMap = Map(\"a\" -> 42, \"b\" -> 43)\r\n    def getMapValue(s: String): String = {\r\n      myMap get s match {\r\n        case Some(nb) => \"Value found: \" + nb\r\n        case None => \"No value found\"\r\n      }\r\n    }\r\n    getMapValue(\"a\")  // \"Value found: 42\"\r\n    getMapValue(\"c\")  // \"No value found\"\r\n```\r\n\r\nMost of the times when you write a pattern match on an option value,\r\nthe same expression can be written more concisely using combinator\r\nmethods of the `Option` class. For example, the function `getMapValue`\r\ncan be written as follows: \r\n```scala\r\n    def getMapValue(s: String): String =\r\n      myMap.get(s).map(\"Value found: \" + _).getOrElse(\"No value found\")\r\n```\r\n\r\n### Pattern Matching in Anonymous Functions\r\n\r\nPattern matches are also used quite often in anonymous functions:\r\n```scala\r\n    val pairs: List[(Char, Int)] = ('a', 2) :: ('b', 3) :: Nil\r\n    val chars: List[Char] = pairs.map(p => p match {\r\n      case (ch, num) => ch\r\n    })\r\n```\r\n\r\nInstead of `p => p match { case ... }`, you can simply write `{case ...}`, so the above example becomes more concise:\r\n```scala\r\n    val chars: List[Char] = pairs map {\r\n      case (ch, num) => ch\r\n    }\r\n```\r\n\r\n## Collections\r\n\r\nScala defines several collection classes:\r\n\r\n### Base Classes\r\n- [`Iterable`](http://www.scala-lang.org/api/current/index.html#scala.collection.Iterable) (collections you can iterate on)\r\n- [`Seq`](http://www.scala-lang.org/api/current/index.html#scala.collection.Seq) (ordered sequences)\r\n- [`Set`](http://www.scala-lang.org/api/current/index.html#scala.collection.Set)\r\n- [`Map`](http://www.scala-lang.org/api/current/index.html#scala.collection.Map) (lookup data structure)\r\n\r\n### Immutable Collections\r\n- [`List`](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List) (linked list, provides fast sequential access)\r\n- [`Stream`](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream) (same as List, except that the tail is evaluated only on demand)\r\n- [`Vector`](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Vector) (array-like type, implemented as tree of blocks, provides fast random access)\r\n- [`Range`](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Range) (ordered sequence of integers with equal spacing)\r\n- [`String`](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html) (Java type, implicitly converted to a character sequence, so you can treat every string like a `Seq[Char]`)\r\n- [`Map`](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map) (collection that maps keys to values)\r\n- [`Set`](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Set) (collection without duplicate elements)\r\n\r\n### Mutable Collections\r\n- [`Array`](http://www.scala-lang.org/api/current/index.html#scala.Array) (Scala arrays are native JVM arrays at runtime, therefore they are very performant)\r\n- Scala also has mutable maps and sets; these should only be used if there are performance issues with immutable types\r\n\r\n### Examples\r\n```scala\r\n    val fruitList = List(\"apples\", \"oranges\", \"pears\")\r\n    // Alternative syntax for lists\r\n    val fruit = \"apples\" :: (\"oranges\" :: (\"pears\" :: Nil)) // parens optional, :: is right-associative\r\n    fruit.head   // \"apples\"\r\n    fruit.tail   // List(\"oranges\", \"pears\")\r\n    val empty = List()\r\n    val empty = Nil\r\n\r\n    val nums = Vector(\"louis\", \"frank\", \"hiromi\")\r\n    nums(1)                     // element at index 1, returns \"frank\", complexity O(log(n))\r\n    nums.updated(2, \"helena\")   // new vector with a different string at index 2, complexity O(log(n))\r\n    \r\n    val fruitSet = Set(\"apple\", \"banana\", \"pear\", \"banana\")\r\n    fruitSet.size    // returns 3: there are no duplicates, only one banana\r\n\r\n    val r: Range = 1 until 5 // 1, 2, 3, 4\r\n    val s: Range = 1 to 5    // 1, 2, 3, 4, 5\r\n    1 to 10 by 3  // 1, 4, 7, 10\r\n    6 to 1 by -2  // 6, 4, 2\r\n\r\n    val s = (1 to 6).toSet\r\n    s map (_ + 2) // adds 2 to each element of the set\r\n\r\n    val s = \"Hello World\"\r\n    s filter (c => c.isUpper) // returns \"HW\"; strings can be treated as Seq[Char]\r\n\r\n    // Operations on sequences\r\n    val xs = List(...)\r\n    xs.length   // number of elements, complexity O(n)\r\n    xs.last     // last element (exception if xs is empty), complexity O(n)\r\n    xs.init     // all elements of xs but the last (exception if xs is empty), complexity O(n)\r\n    xs take n   // first n elements of xs\r\n    xs drop n   // the rest of the collection after taking n elements\r\n    xs(n)       // the nth element of xs, complexity O(n)\r\n    xs ++ ys    // concatenation, complexity O(n)\r\n    xs.reverse  // reverse the order, complexity O(n)\r\n    xs updated(n, x)  // same list than xs, except at index n where it contains x, complexity O(n)\r\n    xs indexOf x      // the index of the first element equal to x (-1 otherwise)\r\n    xs contains x     // same as xs indexOf x >= 0\r\n    xs filter p       // returns a list of the elements that satisfy the predicate p\r\n    xs filterNot p    // filter with negated p \r\n    xs partition p    // same as (xs filter p, xs filterNot p)\r\n    xs takeWhile p    // the longest prefix consisting of elements that satisfy p\r\n    xs dropWhile p    // the remainder of the list after any leading element satisfying p have been removed\r\n    xs span p         // same as (xs takeWhile p, xs dropWhile p)\r\n    \r\n    List(x1, ..., xn) reduceLeft op    // (...(x1 op x2) op x3) op ...) op xn\r\n    List(x1, ..., xn).foldLeft(z)(op)  // (...( z op x1) op x2) op ...) op xn\r\n    List(x1, ..., xn) reduceRight op   // x1 op (... (x{n-1} op xn) ...)\r\n    List(x1, ..., xn).foldRight(z)(op) // x1 op (... (    xn op  z) ...)\r\n    \r\n    xs exists p    // true if there is at least one element for which predicate p is true\r\n    xs forall p    // true if p(x) is true for all elements\r\n    xs zip ys      // returns a list of pairs which groups elements with same index together\r\n    xs unzip       // opposite of zip: returns a pair of two lists\r\n    xs.flatMap f   // applies the function to all elements and concatenates the result\r\n    xs.sum         // sum of elements of the numeric collection\r\n    xs.product     // product of elements of the numeric collection\r\n    xs.max         // maximum of collection\r\n    xs.min         // minimum of collection\r\n    xs.flatten     // flattens a collection of collection into a single-level collection\r\n    xs groupBy f   // returns a map which points to a list of elements\r\n    xs distinct    // sequence of distinct entries (removes duplicates)\r\n\r\n    x +: xs  // creates a new collection with leading element x\r\n    xs :+ x  // creates a new collection with trailing element x\r\n\r\n    // Operations on maps\r\n    val myMap = Map(\"I\" -> 1, \"V\" -> 5, \"X\" -> 10)  // create a map\r\n    myMap(\"I\")      // => 1  \r\n    myMap(\"A\")      // => java.util.NoSuchElementException  \r\n    myMap get \"A\"   // => None \r\n    myMap get \"I\"   // => Some(1)\r\n    myMap.updated(\"V\", 15)  // returns a new map where \"V\" maps to 15 (entry is updated)\r\n                            // if the key (\"V\" here) does not exist, a new entry is added\r\n\r\n    // Operations on Streams\r\n    val xs = Stream(1, 2, 3)\r\n    val xs = Stream.cons(1, Stream.cons(2, Stream.cons(3, Stream.empty))) // same as above\r\n    (1 to 1000).toStream // => Stream(1, ?)\r\n    x #:: xs // Same as Stream.cons(x, xs)\r\n             // In the Stream's cons operator, the second parameter (the tail)\r\n             // is defined as a \"call by name\" parameter.\r\n             // Note that x::xs always produces a List\r\n```\r\n\r\n## Pairs (similar for larger Tuples)\r\n```scala\r\n    val pair = (\"answer\", 42)   // type: (String, Int)\r\n    val (label, value) = pair   // label = \"answer\", value = 42  \r\n    pair._1 // \"answer\"  \r\n    pair._2 // 42  \r\n```\r\n\r\n## Ordering\r\n\r\nThere is already a class in the standard library that represents orderings: `scala.math.Ordering[T]` which contains\r\ncomparison functions such as `lt()` and `gt()` for standard types. Types with a single natural ordering should inherit from \r\nthe trait `scala.math.Ordered[T]`.\r\n```scala\r\n    import math.Ordering  \r\n\r\n    def msort[T](xs: List[T])(implicit ord: Ordering) = { ...}  \r\n    msort(fruits)(Ordering.String)  \r\n    msort(fruits)   // the compiler figures out the right ordering  \r\n```\r\n\r\n## For-Comprehensions\r\n\r\nA for-comprehension is syntactic sugar for `map`, `flatMap` and `filter` operations on collections.\r\n\r\nThe general form is `for (s) yield e`\r\n\r\n- `s` is a sequence of generators and filters\r\n- `p <- e` is a generator\r\n- `if f` is a filter\r\n- If there are several generators (equivalent of a nested loop), the last generator varies faster than the first\r\n- You can use `{ s }` instead of `( s )` if you want to use multiple lines without requiring semicolons\r\n- `e` is an element of the resulting collection\r\n\r\n### Example 1\r\n```scala\r\n    // list all combinations of numbers x and y where x is drawn from\r\n    // 1 to M and y is drawn from 1 to N\r\n    for (x <- 1 to M; y <- 1 to N)\r\n      yield (x,y)\r\n```\r\n\r\nis equivalent to\r\n```scala        \r\n    (1 to M) flatMap (x => (1 to N) map (y => (x, y)))\r\n```\r\n\r\n### Translation Rules\r\n\r\nA for-expression looks like a traditional for loop but works differently internally\r\n\r\n`for (x <- e1) yield e2` is translated to `e1.map(x => e2)`\r\n\r\n`for (x <- e1 if f) yield e2` is translated to `for (x <- e1.filter(x => f)) yield e2`\r\n\r\n`for (x <- e1; y <- e2) yield e3` is translated to `e1.flatMap(x => for (y <- e2) yield e3)`\r\n\r\nThis means you can use a for-comprehension for your own type, as long\r\nas you define `map`, `flatMap` and `filter`.\r\n\r\nFor more, see [lecture 6.5](https://class.coursera.org/progfun-2012-001/lecture/111).\r\n\r\n### Example 2\r\n```scala\r\n    for {  \r\n      i <- 1 until n  \r\n      j <- 1 until i  \r\n      if isPrime(i + j)  \r\n    } yield (i, j)  \r\n```\r\n\r\nis equivalent to\r\n```scala\r\n    for (i <- 1 until n; j <- 1 until i if isPrime(i + j))\r\n        yield (i, j)  \r\n```\r\n\r\nis equivalent to\r\n```scala\r\n    (1 until n).flatMap(i => (1 until i).filter(j => isPrime(i + j)).map(j => (i, j)))\r\n```\r\n"
  },
  {
    "path": "Swift/README.md",
    "content": "# Swift Cheat Sheet\r\n\r\nNotes taken from [The Swift Programming Language](https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_467).\r\n\r\n## Topics\r\n\r\n- [The Basics](#the-basics)\r\n- [Basic Operators](#basic-operators)\r\n- [Strings and Characters](#strings-and-characters)\r\n- [Collection Types](#collection-types)\r\n- [Control Flow](#control-flow)\r\n- [Functions](#functions)\r\n- [Closures](#closures)\r\n- [Enumerations](#enumerations)\r\n- [Classes & Structures](#classes--structures)\r\n- [Properties](#properties)\r\n- [Methods](#methods)\r\n- [Subscripts](#subscripts)\r\n- [Inheritance](#inheritance)\r\n- [Initialization](#initialization)\r\n- [Deinitialization](#deinitialization)\r\n- [Automatic Reference Counting](#automatic-reference-counting)\r\n- [Optional Chaining](#optional-chaining)\r\n- [Type Casting](#type-casting)\r\n- [Nested Types](#nested-types)\r\n- [Extensions](#extensions)\r\n- [Protocols](#protocols)\r\n- [Generics](#generics)\r\n- [Access Control](#access-control)\r\n\r\n## The Basics\r\n\r\n### Constants & Variables\r\n\r\n  * Declaring Constants & Variables\r\n\r\n      ```swift\r\n      // Constant\r\n      let maximumNumberOfLoginAttempts = 10\r\n\r\n      // Variable\r\n      var currentLoginAttempt = 0\r\n      var x = 0.0, y = 0.0, z = 0.0\r\n      ```\r\n\r\n  * Type Annotations\r\n\r\n    ```swift\r\n    var welcomeMessage: String\r\n    var red, green, blue: Double\r\n    ```\r\n\r\n    * Rare that you need to write type annotations\r\n      * If you provide an initial value, Swift can infer the type to be used\r\n  * Naming Constants and Variables\r\n    * Constant/variable names can contain almost any character, including Unicode:\r\n\r\n      ```swift\r\n      let π = 3.14159\r\n      let 你好 = \"你好世界\"\r\n      let  = \"dogcow\"\r\n      ```\r\n\r\n    * If const/var is reserved Swift keyword, surround with back ticks (\\`), avoid if you can\r\n  * Printing Constants & Variables\r\n\r\n    ```swift\r\n    println(friendlyWelcome)\r\n    println(\"Current value \\(friendlyWelcome)\")\r\n    ```\r\n\r\n### Comments\r\n\r\n```swift\r\n// this is a comment\r\n/* multiple lines comment */\r\n/* /* nested multilines supported */ */\r\n```\r\n\r\n### Semicolons\r\n\r\n```swift\r\n// No semicolon, unless for multiple statements on a single line\r\nlet cat=\"hello\"; println(cat)\r\n```\r\n\r\n### Integers\r\n\r\n  * Whole numbers with no fractional component, signed or unsigned\r\n  * Swift provides signed & unsigned integers in 8, 16, 32 and 64 bits\r\n    * Follow naming convention similar to C, e.g.\r\n      * UInt8\r\n      * Int32\r\n  * Integer Bounds\r\n\r\n    ```swift\r\n    let minValue = UInt8.min // 0\r\n    let maxValue = UInt8.max // 255\r\n    ```\r\n\r\n  * Int\r\n    * If you don't need specific size, use Int, same size with current platform's native word size\r\n      * 32-bit platform, Int = Int32\r\n      * 64-bit platform, Int = Int64\r\n    * Unless you need to use specific size, always use Int, for codes consistency and interoperability.\r\n    * On 32-bit platform Int values: -2,147,483,648 => 2,147,483,648, large enough\r\n  * UInt\r\n    * When you specifically need unsigned integer, else Int is preferred\r\n    * A consistent use of Int aids code interoperability, avoids the need to convert to different number types, matches integer type inference as described in Type Safety and Type Inference\r\n\r\n### Floating Point Numbers\r\n\r\n  * Numbers with a fractional component, e.g. 3.14159\r\n  * Represent a much wider range of values than integer types\r\n  * Can store numbers much larger/smaller than can be stored in an Int\r\n  * Types:\r\n    * Double\r\n      * 64-bit floating point number\r\n        * Use it when floating-point values must be very large or particularly precise\r\n    * Float\r\n      * 32-bit floating point number\r\n        * Use it when floating point values do not require 64-bit precision\r\n  * Double has a precision of at least 15 decimal digits, and Float 6 decimal digits\r\n\r\n### Type Safety and Type Inference\r\n\r\n  * Type safe language\r\n    * Encourages you to be clear about types of values\r\n    * Type checking, compile errors if there is a mismatch\r\n  * Type Inference\r\n    * Does not mean you nave to specify the type of every constant/variable\r\n    * Enables a compiler to deduce the type of a particular expression automatically by examining the values you provide\r\n    * Because of type inference, Swift requires fewer type of declarations than C or Objective-C\r\n\r\n    ```swift\r\n    let meaningOfLife = 42    // Inferred as Int\r\n    let pi = 3.14159          // Infered as double, Swift always chooses Double rather than Float\r\n    let anotherPi  = 3 + 0.14 // Also inferred as double\r\n    ```\r\n\r\n### Numeric Literals\r\n\r\n  * All of these integer literals have a decimal value of 17:\r\n\r\n    ```swift\r\n    let decimalInteger = 17\r\n    let binaryInteger = 0b10001   // 17 in binary notation\r\n    let octalInteger = 0o21       // 17 in octal notation\r\n    let hexadecimalInteger = 0x11 // 17 hexa decimal notation\r\n    ```\r\n\r\n  * Floating-point literals can be decimal or hexadecimal.They must have a number on both sides of the decimal point\r\n    * Optional exponent, indicated by and uppercase/lowercase e for decimal floats or an p for hexadecimal floats\r\n    * For decimal numbers with an exponent of exp, the base number is multiplied by 10exp:\r\n\r\n      ```swift\r\n      1.25e2  // = 1.25 x 102 = 125.0\r\n      1.25e-2 // = 1.25 x 10-2 = 0.0125\r\n      ```\r\n\r\n    * For hexadecimal numbers with an exponent of exp, the base is multiplied by 2exp:\r\n\r\n      ```swift\r\n      0xFp2 // means 15x22 = 60.0\r\n      0xFp2 // means 15x2-2 = 3.75\r\n      ```\r\n\r\n    * All of these floating numbers have a decimal value of 12.1875\r\n\r\n      ```swift\r\n      let decimalDouble = 12.1875\r\n      let exponentDouble = 1.21875e1\r\n      let hexDouble = 0xC.3p0\r\n      ```\r\n\r\n  * Numeric literals can contain extra formatting to make them easier to read\r\n    * Padded with extra zeroes or contain underscores\r\n    * Not affecting the value:\r\n\r\n      ```swift\r\n      let paddedDouble = 000123.456\r\n      let oneMillion = 1_000_000\r\n      let justOverOneMillion = 1_000_000.000_000_1\r\n      ```\r\n\r\n### Numeric Type Conversion\r\n\r\n  * Overview\r\n    * Use Int for most of the cases\r\n    * Use others only when needed\r\n    * Use others to catch any accidental value overflows & implicitly documents the nature of data being used\r\n  * Integer Conversion\r\n    * Compilation error if a number does not fit into a variable integer type\r\n\r\n      ```swift\r\n      let cannotBeNegative: UInt8 = -1\r\n      ```\r\n\r\n    * Because of limited range of values, you must opt in to number type conversion on a case-by-case basis\r\n    * Opt-in approach prevents hidden conversion errors\r\n    * To convert:\r\n\r\n      ```swift\r\n      * let twoThousand: UInt16 = 2_000\r\n      * let one: UInt 8 - 1\r\n      * let twoThousandAndOne = twoThousand + UInt16(one)\r\n      ```\r\n\r\n    * SomeType(ofInitialValue) => default in Swift and pass in an initial value\r\n      * UInt16 has initialiser that accepts a UInt8 value\r\n      * You can't pass in any type here, it has to be a type which UInt16 provides an init\r\n      * Extending inits to cover other types covered in Extensions\r\n  * Integer & Floating Point Conversion\r\n    * Conversion between integer to floating point has to be explicit:\r\n\r\n      ```swift\r\n      let three = 3\r\n      let floatNumber = 0.14\r\n      let pi = Double(three) + floatNumber\r\n      let intPi = Int(pi) // 3\r\n      ```\r\n\r\n    * Rules for combining numeric constants/variables are different than numeric literals\r\n\r\n      ```swift\r\n      let c = 3 + 0.14 // is fine\r\n      ```\r\n\r\n      * Because their type is inferred only at the point they are evaluated by the compiler\r\n\r\n### Type Aliases\r\n\r\n  * Define alternative name for an existing type\r\n  * When you want to refer to an existing type by a name, that is contextually more appropriate\r\n  * When working with data of a specific size from an external source\r\n\r\n    ```swift\r\n    typealias AudioSample = UInt16\r\n    var maxAmplitudeFound = AudioSample.min // UInt16.min = 0\r\n    ```\r\n\r\n### Booleans\r\n\r\n  * Bool\r\n\r\n    ```swift\r\n    let orangesAreOrange = true\r\n    ```\r\n\r\n  * Type safety prevents this:\r\n\r\n    ```swift\r\n    let i = 1\r\n    if i { // error }\r\n    if i == 1 { // fine }\r\n    ```\r\n\r\n### Tuples\r\n\r\n  * Group multiple values into a single compound value\r\n  * Values do not have to be the same type as each other\r\n\r\n    ```swift\r\n    let http404Error = (404, \"Not found\")\r\n    let (statusCode, statusMessage) = http404Error\r\n    let (justStatusCode, _) = http404Error\r\n    println(\"Status code is \\(http404Error.0), message: \\(http404Error.1)\")\r\n    let http200Status = (statusCode: 200, description: \"OK\")\r\n    println(\"Status code: \\(http200Status.statusCode)\")\r\n    ```\r\n\r\n  * Useful to return values of  functions, by returning a tuple with two distinct values, each of a different type the function provides more useful info about its outcome\r\n  * Note\r\n    * Tuples useful for temporary groups of related values, not suited for creation of complex data structures\r\n    * If data structure likely to persist beyond a temp scope, model it as a class or structure.\r\n\r\n### Optionals\r\n\r\n  * Use optional where a value may be present\r\n  * If there is a value, it equals to x, or there isn't a value at all\r\n  * Note\r\n    * Optionals don't exist in C/Obj-C. Nearest is to return nil.\r\n    * Only works for objects, doesn't work for structures, basic C types, and enums.\r\n    * Usually Obj-C methods return a special value NSNotFound to indicate absence of a a value\r\n    * Swift optionals let you indicate the absence of a value for any type at all\r\n\r\n      ```swift\r\n      let possibleNumber = \"123\"\r\n      let convertedNumber = possibleNumber.toInt()  // converted number is inferred to be of type \"Int?\" or \"optional Int\"\r\n      ```\r\n\r\n      * Because toInt might fail\r\n      * Optional Int is written as Int?\r\n  * nil\r\n    * Set an optional variable to a valueless by assigning to nil\r\n\r\n      ```swift\r\n      var serverResponseCode: Int? = 404 // 404\r\n      serverResponseCode = nil  // no value\r\n      ```\r\n\r\n    * nil cannot be used with non optional constants/variables\r\n    * If your variables/constants may not have any value, use optional\r\n    * Default to nil\r\n\r\n      ```swift\r\n      var surveyAnswer: String? // nil\r\n      ```\r\n\r\n    * Note\r\n      * Swift's nil is different from Objective-C's.\r\n      * In Objective-C nil is a pointer to a nonexistent object\r\n      * In Swift it is not a pointer, it is an absence value of a certain type\r\n      * Optionals of any type can be set to nil, not just object types\r\n  * If statements & Forced Unwrapping\r\n\r\n    ```swift\r\n    if convertedNumber != nil {\r\n      println(\"Coverted value: \\(convertedValue)!\"))\r\n    }\r\n    ```\r\n\r\n    * Trying to use ! to access non-existent optional value will trigger an error\r\n  * Optional Binding\r\n    * To find out whether an optional contains a value, if so make the value available as a temporary constant or variable\r\n    * Can be used in if/while statement\r\n\r\n      ```swift\r\n      if let constantName = someOptional {\r\n        // statements\r\n      }\r\n      ```\r\n\r\n  * Implicitly Unwrapped Optionals\r\n    * Sometimes it is clear that an optional will always have a value\r\n    * To remove the need to check and unwrap optional's value every time it is accessed\r\n\r\n      ```swift\r\n      let assumedString: String! = \"Implicitly unwrapped\"\r\n      let implicitString: String = unassumedString\r\n\r\n      if assumedString != nil { println(assumedString) }\r\n\r\n      if let definiteString = assumedString { ... }\r\n      ```\r\n\r\n    * If you try to access an implicitly unwrapped optional when it does not contain value, it will trigger runtime error, same with optional\r\n\r\n### Assertions\r\n\r\n  * Some cases, not possible for code to continue, use assertions end code execution, to provide an opportunity to debug\r\n\r\n    ```swift\r\n    let age = -3\r\n    assert(age >=0, \"A person's age cannot be less than 0)\r\n    ```\r\n\r\n  * When to use Assertions\r\n    * An integer subscript index is passed to a custom subscript implementation, but the subscript index value could be too low or too high\r\n    * Value passed to a function, check for invalid value\r\n    * An optional value is currently nil, but a non-nil value is essential for subsequent code to execute\r\n  * Assertion cause app to terminate, an effective way to check conditions before app is published\r\n\r\n## Basic Operators\r\n\r\n### Overview\r\n\r\n  * Operator is a special symbol or phrase that you use to check, change or combine values\r\n  * Supports most standard C operators, and improves several capabilities to eliminate common coding errors\r\n    * Assignment (=) does not return a value, to prevent mistakenly used for ===\r\n    * Arithmetic operators (+, -...) detect and disallow value overflow to avoid unexpected result\r\n    * You can opt-in to value overflow behaviour using Swift's overflow operator in \"Overflow Operators\"\r\n    * C lets you perform remainder(%) operator on floating numbers\r\n    * Provides two range operators a...<b and a...b\r\n\r\n### Terminology\r\n\r\n```swift\r\n// Unary\r\nprefix: !b\r\npostfix: i++\r\n\r\n// Binary\r\n2 + 3\r\n\r\n// Ternary\r\na ? b : c\r\n```\r\n\r\n### Assignment Operator\r\n\r\n  ```swift\r\n  let b = 10\r\n  let (x,y) = (1,2)\r\n  if x = y { // invalid }\r\n  ```\r\n\r\n  * Does not allow value to be overflow\r\n  * You can option to value overflow behaviour by using\r\n\r\n    ```swift\r\n    a &+ b\r\n    ```\r\n\r\n  * Addition operator also supported for string \"hello \" + \"world\"\r\n  * Two Character values, one char, one String, can be added together\r\n\r\n    ```swift\r\n    let dog :Character = \"\"\r\n    let cow: Character = \"\"\r\n    let dogCow = dog + cow\r\n    // dogCow is equal to \"\r\n    ```\r\n\r\n### Arithmetic Operators\r\n\r\n  * Overview\r\n    * Addition (+)\r\n    * Substraction (-)\r\n    * MUltiplication (*)\r\n    * Division (/)\r\n  * Remainder Operator\r\n    * Works out how many multiples b will fit inside a and returns the value that is left over (remainder)\r\n    * Known as modulo operator, its behaviour in Swift for negative numbers, strictly speaking a remainder rather than a modulo operation\r\n    * Formula:\r\n\r\n      ```swift\r\n      a % b\r\n      a = (b × some multiplier) + remainder\r\n      ```\r\n    * Example:\r\n\r\n      ```swift\r\n      9 % 4 = 1\r\n      -9 % 4 = -1\r\n      9 % -4 = 1\r\n      ```\r\n\r\n  * Floating-Point Remainder Calculations\r\n    * Unlike the remainder operator in C or Obj-C, it also works on floating-point numbers:\r\n\r\n      ```swift\r\n      8 % 2.5 // = 0.5\r\n      ```\r\n\r\n  * Increment & Decrement Operators\r\n    * ++ and ---\r\n\r\n      ```swift\r\n      var i = 0\r\n      ++i // i = 1\r\n      ```\r\n\r\n    * If used as prefix, it increments the variable before returning its value\r\n    * If used as suffix, it increments the variable after returning its value\r\n\r\n      ```swift\r\n      var a = 0\r\n      let b = ++a // b = 1\r\n      let c = a++ // a = 2, but c = 1\r\n      ```\r\n\r\n  * Unary Plus Operator\r\n\r\n    ```swift\r\n    let three = 3\r\n    let minusTree = -three    // -3\r\n    let plusTree = -minusTree // 3\r\n    ```\r\n\r\n    * Prepended without any space\r\n  * Unary Plus Operator\r\n    * Returns the value without any change\r\n\r\n      ```swift\r\n      let minusSix = -6\r\n      let alsoMinusSix = +minusSix // -6\r\n      ```\r\n\r\n### Compound Assignment Operators\r\n\r\n  * +=, -=\r\n\r\n    ```swift\r\n    var a = 1\r\n    a += 2 // a = a + 2\r\n    ```\r\n\r\n  * Does not return a value\r\n\r\n### Comparison Operators\r\n\r\n  * Supports all standard C comparison operators\r\n\r\n    ```swift\r\n    a == b\r\n    a != b\r\n    a > b\r\n    a < b\r\n    a >= b\r\n    a <= b\r\n    ```\r\n\r\n  * Swift also provides two identity operators === and !==\r\n    * Test two object references both refer to the same object instance\r\n\r\n### Ternary Conditional Operator\r\n\r\n  * question ? answer1 : answer2\r\n\r\n### Nil Coalescing Operator\r\n\r\n  * a ?? b\r\n  * Unwraps an optional a if it contains a value or returns a default value b if a is nil\r\n  * a is always an optional type\r\n  * Shorthand for\r\n\r\n    ```swift\r\n    a != nil ? a! : b\r\n    ```\r\n\r\n### Range Operators\r\n\r\n  * Closed Range Operator\r\n    * a..b\r\n    * Defines a range that runs from a to be, and includes the values of a and b\r\n\r\n    ```swift\r\n    for index in 1...5 { ... }\r\n    ```\r\n\r\n  * Half-Open Range Operator\r\n\r\n    ```swift\r\n    a..<b\r\n    ```\r\n\r\n    * Defines a range that runs from a to b, but does not include b\r\n    * Useful when work with zero-based lists, such as arrays\r\n\r\n      ```swift\r\n      let names = [\"Anna\", \"Alex\", \"Brian\", \"Jack\"]\r\n      let count = names.count\r\n      for i in 0..<count {\r\n        println(\"Person \\(i + 1) is called \\(names[i])\")\r\n      }\r\n      ```\r\n\r\n### Logical Operators\r\n\r\n  * Logical Not Operator (!a)\r\n    * Inverts Boolean value, true becomes false and vice versa\r\n  * Logical AND Operator (a && b)\r\n  * Logical OR Operator (a || b)\r\n  * Combining Logical Operators\r\n\r\n    ```swift\r\n    if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword\r\n    ```\r\n\r\n  * Explicit Parantheses\r\n\r\n    ```swift\r\n    if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {\r\n    ```\r\n\r\n## Strings and Characters\r\n\r\n### Overview\r\n\r\n  ```swift\r\n  \"hello world\"\r\n  ```\r\n\r\n  * Represented by String, a collection of values of Character type\r\n  * Unicode compliant\r\n  * Swift's string is bridged seamlessly to Foundation's NSString, the entire NSString API is available to call on any String value you create, in addition to the String features described later on.\r\n  * You can also use String value with any API that requires NSString instance\r\n  * More info, check Using Swift with Cocoa & Obj-C\r\n\r\n### String Literals\r\n\r\n```swift\r\nlet someString = \"Some string literal value\"\r\n```\r\n\r\n### Initializing an Empty String\r\n\r\n```swift\r\nvar emptyString = \"\"\r\nvar anotherEmptyString = String()\r\n\r\nemptyString == anotherEmptyString\r\n\r\nif emptyString.isEmpty { ... }\r\n```\r\n\r\n### String Mutability\r\n\r\n```swift\r\nlet constantString = \"hello\"\r\nconstantString += \" world\"   // compilation error\r\n```\r\n\r\n### String Are Value Types\r\n\r\n  * String value is copied when it is passed to a function or method or\r\n    * when it is assigned to a constant or a variable\r\n  * New copy is created, passed and assigned not the original version\r\n  * Note\r\n    * Different from NSString in Cocoa, it is also pass by reference\r\n  * Behind the scenes, Swift's compiler optimises string usage, so copying only takes place when necessary\r\n\r\n### Working with Characters\r\n\r\n  * Strings are collection of characters\r\n\r\n    ```swift\r\n    for char in \"Dog!\" { println(char) }\r\n    ```\r\n\r\n  * Create a single character\r\n\r\n    ```swift\r\n    let yenSign: Character = \"¥\"\r\n    ```\r\n\r\n### Concatenating Strings & Characters\r\n\r\n  ```swift\r\n  var welcome = \"string1\" + \"string2\"\r\n  welcome.append(\"!\")\r\n  ```\r\n\r\n### String Interpolation\r\n\r\n  ```swift\r\n  let multiplier = 3\r\n  let message = \"\\(multiplier) times 2.5 is \\(Double(multiplier) * 2.5)\"\r\n  ```\r\n\r\n### Unicode\r\n\r\n  * An international standard for encoding, representing, and processing text in different writing systems\r\n    * Represent characters from any language in standardised form, and to read/write those chars to and from external source such as text file or web page\r\n  * Unicode Scalars\r\n    * Swift's native String type is built from Unicode scalar values.\r\n    * A unique 21-bit number for a character/modifier such as:\r\n      * U+0061 for LATIN SMALL LETTER A (\"a\")\r\n      * U+1F425 for FRONT-FACING BABY CHICK (\"\")\r\n    * Note\r\n      * Unicode scalara is any unicode code point in the range of U+0000 to U+D7FF inclusive or U+E000 to U+10FFFF inclusive.\r\n      * Unicode scalars do not include the Unicode surrogate pair code points, which are code points in the range of U+D800 to U+DFFF inclusive\r\n    * Not all 21-bit Unicode scalars are assigned to a char, some are reserved for future assignment\r\n  * Special Unicode Characters in String Literals\r\n    * \\0: null character\r\n    * \\\\: backslash\r\n    * \\t: horizontal tab\r\n    * \\n: line feed\r\n    * \\r: carriage return\r\n    * \\\": double quote\r\n    * \\': single quote\r\n    * An arbitrary unicode scalar, written as \\u{n}, where n is between one and eight hexadecimal digits\r\n\r\n      ```swift\r\n      \"\\u{24}\"    // $\r\n      \"\\u{2665}\"  // ♥\r\n      \"\\u{1F496}\" //   - Unicode scalar: U+1F496\r\n      ```\r\n\r\n  * Extended Grapheme Clusters\r\n    * Every instance of Swift's Character type represents a single extended grapheme cluster\r\n      * A sequence of one or more Unicode scalars that (when combined) produce a single human-readable character\r\n\r\n      ```swift\r\n      let eAcute: Character = \"\\u{E9}\"                         // é\r\n      let combinedEAcute: Character = \"\\u{65}\\u{301}\"          // e followed by ́eAcute is é, combinedEAcute is é\r\n      ```\r\n\r\n    * To represent many complex script characters as a single character value.\r\n      * Hangul syllables from the Korean alphabet, can be represented as either a precomposed or decomposed sequence\r\n\r\n      ```swift\r\n      let precomposed: Character = \"\\u{D55C}\"                 // 한\r\n      let decomposed: Character = \"\\u{1112}\\u{1161}\\u{11AB}\"  // ᄒ, ᅡ,  precomposed is 한, decomposed is 한\r\n      let enclosedEAcute: Character = \"\\u{E9}\\u{20DD}\"        // enclosedEAcute is  é⃝\r\n      ```\r\n\r\n### Counting Characters\r\n\r\n  ```swift\r\n  let unusualMenagerie = \"Koala , Snail , Penguin , Dromedary\"\r\n  println(\"unusualMenagerie has \\(countElements(unusualMenagerie)) character\r\n  // prints \"unusualMenagerie has 40 characters\r\n  ```\r\n\r\n  * Use of extended grapheme clusters for Character values means character count may not be affected\r\n\r\n    ```swift\r\n    var word = \"cafe\" +  \"\\u{301}\"  // café\r\n    countElements(word)             // 4\r\n    ```\r\n\r\n  * Note\r\n    * The number of chars in a string cannot be calculated without iterating through the whole string, beware of countElements must iterate over the whole string\r\n    * countElements is not the same with length\r\n      * length is based on the number of 16-bit code units within the string's UTF-16 representation, not the number of Unicode extended grapheme clusters within the string\r\n        * To reflect this fact, the length property from NSString is called utf16Count when it is accessed on a Swift String value\r\n\r\n### Comparing Strings\r\n\r\n  * String & Character Equality\r\n    * == and !=\r\n    * Two String values (or two Character values) are considered equal if their extended grapheme clusters are canonically equivalent\r\n      * If they have the same linguistic metalling or appearance, even if they are composed from different Unicode scalars behind the scene\r\n\r\n    ```swift\r\n    \"\\u{E9}\" == \"\\u{65}\\u{301}\" //  é - true\r\n    \"\\u{41}\" == \"\\u{0410}\" // false - latinCapitalLetterA & cyrillicCapitalLetterA different linguistic meaning\r\n    ```\r\n\r\n    * Note\r\n      * String and character comparisons in Swift are not locale sensitive\r\n  * Prefix & Suffix Equality\r\n    * hasPrefix, hasSuffix\r\n\r\n### Unicode Representations of Strings\r\n\r\n  * UTF-8 Representation\r\n    * When written to a file, Unicode scalars are encoded in one of several Unicode-defined encoding forms.\r\n    * Each form encodes the string in small chunks known as code units, which include:\r\n      * UTF-8 encoding form, as 8-bit code units\r\n      * UTF-16\r\n      * UTF-32\r\n    * Several ways to access Unicode representation of strings\r\n      * Iterate with for-in, access each Character values as Unicode extended grapheme clusters.\r\n      * Access a String value in one of the three Unicode-compliant representation\r\n        * Collection of UTF-8 code units (string's utf8 property)\r\n        * Collection of UTF-16 units (utf16 property)\r\n        * Collection of 21-bit Unitcode scalar values, or equivalent to UTF-32 encoding form (unicodeScalars property)\r\n    * Next is an example different presentation of D, o, g, !! (double exclamation mark, U+203c) and (U+1F436)\r\n      * let dogString = \"Dog‼\"\r\n  * UTF-8 Representation\r\n\r\n    ```swift\r\n    for codeUnit in dogString.utf8 {\r\n      print(\"\\(codeUnit) \")\r\n    }\r\n    print(\"\\n\")\r\n    // 68 111 103 226 128 188 240 159 144 182\r\n    //  68, 111, 103 = D, o, g\r\n    //  226, 128, 188 = 3-byte UTF-8 representation of DOUBLE EXCLAMATION MARK character\r\n    //  \"240, 159, 144, 182 = 4-byte UTF-8 representation of the DOG FACE\r\n    ```\r\n\r\n  * UTF-16 Representation\r\n\r\n    ```swift\r\n    for codeUnit in dogString.utf16 {\r\n      print(\"\\(codeUnit) \")\r\n    }\r\n    print(\"\\n\")\r\n    // 68 111 103 8252 55357 56374\r\n    // 8252 = decimal equivalent of hexadecimal value of 203C which represent Unicode+203C for double Exclamation Mark, this character represented as a single code unit in UTF-16\r\n    //  55357,  56374 = UTF-16 surrogate pair representation of  the DOG FACE\r\n    ```\r\n\r\n      * These values are high-surrogate value of U+83D (55357) and low-surrogate value U+DC36 (56374)\r\n  * Unicode Scalar Representation\r\n\r\n    ```swift\r\n    for scalar in dogString.unicodeScalars {\r\n      print(\"\\(scalar.value) \")\r\n      println(\"\\(scalar) \") // print the characters\r\n    }\r\n    print(\"\\n\")\r\n    // 68 111 103 8252 128054\r\n    // 8252 = decimal of U+203C = double exclamation mark\r\n    // 128054 = decimal of U+1F436 of the dog face character\r\n    ```\r\n\r\n## Collection Types\r\n\r\n### Overview\r\n\r\n  * Arrays and dictionaries in Swift are always clear about the types of values and keys that they can store.\r\n  * You cannot insert a value of the wrong type\r\n  * Swift's array and dictionaries are implemented as generic collections.\r\n\r\n### Mutability of Collections\r\n\r\n  * If you create a collection and assign it to a variable, it is mutable\r\n  * It is immutable for a constant\r\n\r\n### Arrays\r\n\r\n  * Overview\r\n    * Swift's Array differ from Objective-C's NSArray or NSMutableArray which can store any kind of object\r\n    * In Swift, the type of values is always made clear, explicitly or through type inference\r\n  * Array Type Shorthand Syntax\r\n    * **Array<SomeType> or [SomeType] (preferred)**\r\n  * Array Literals\r\n\r\n    ```swift\r\n    [value 1, value 2, value 3]\r\n    var shoppingList: [String] = [\"Eggs\", \"Milk\"]\r\n    ```\r\n\r\n  * Accessing and Modifying An Array\r\n\r\n    ```swift\r\n    var shoppingList: [String] = [\"Eggs\", \"Milk\"]\r\n    shoppingList.count\r\n    shoppingList.isEmpty\r\n    shoppingList.append(\"Flour\")\r\n    shoppingList += [\"BakingPowder\", \"Cheese\"] // Add new items to an array\r\n\r\n    var firstItem = shoppingList[0] // subscript syntax\r\n    shoppingList[0] = \"Six eggs\"\r\n    shoppingList[4...6] = [\"Bananas\", \"Apples\"] // Shopping list now has 4 items\r\n    shoppingList.insert(\"Maple Syrup\", atIndex: 0)\r\n\r\n    let mapleSyrup = shoppingList.removeAtIndex(0)\r\n    let apples = shoppingList.removeLast()\r\n    ```\r\n\r\n\r\n    * Note\r\n      * Subscript can't be used to append a new item to an array\r\n      * Out of range index, cause runtime error\r\n  * Iterating Over an Array\r\n\r\n    ```swift\r\n    for item in shoppingList { println(item) }\r\n    ```\r\n\r\n    * Enumerate function\r\n\r\n      ```swift\r\n      for (index, value) in enumerate(shoppingList) {\r\n        println(\"Item \\(index + 1): \\(value)\")\r\n      }\r\n      ```\r\n\r\n  * Creating and Initialising an Array\r\n\r\n    ```swift\r\n    var someInts = [Int]()\r\n    someInts.append(3)\r\n    someInts = [] // reset to empty Int array\r\n    var xyz = [] // runtime error, cause type unknown\r\n    var threeDoubles = [Double](count: 3, repeatedValue: 2.5) // [2.5, 2.5, 2.5]\r\n    ```\r\n\r\n\r\n### Dictionaries\r\n\r\n  * Overview\r\n    * Swift dictionaries are specific about the types of keys and values\r\n  * Dictionary Type Shorthand Syntax\r\n    * **Dictionary<KeyType, ValueType> or [KeyType: ValueType]** (preferred)\r\n  * Dictionary Literals\r\n\r\n    ```swift\r\n    [key 1: value 1, key 2: value 2, key 3: value 3]\r\n    var airports: [String: String] = [\"TYO\": \"Tokyo\", \"DUB\": Dublin\"]\r\n    ```\r\n\r\n    * If key and values are consistent, you could skip the type definition\r\n\r\n      ```swift\r\n      var airports = [\"TYO\": \"Tokyo\", \"DUB\": \"Dublin\"]\r\n      ```\r\n\r\n  * Accessing and Modifying a Dictionary\r\n\r\n    ```swift\r\n    airports.count\r\n    airports.isEmpty\r\n    airports[\"LHR\"] = \"London\"\r\n    airports.updateValue(\"Dublin International\", forKey: \"DUB\")\r\n    airports[\"APL\"] = nil\r\n    airports.removeValueForKey(\"DUB\")\r\n    ```\r\n\r\n  * Iterating Over a Dictionary\r\n\r\n    ```swift\r\n    for (airportCode, airportName) in airports { ... }\r\n    for key in airport.keys { ... }\r\n    for value in airport.values { ... }\r\n    ```\r\n\r\n    * Swift's Dictionary is an unordered collection\r\n  * Creating and Empty Dictionary\r\n\r\n    ```swift\r\n    var namesOfIntegers = [Int: String]() // empty dictionary\r\n    namesOfIntegers[:]                    // reset to empty, once the context is already known\r\n    ```\r\n\r\n  * Hash Values for Dictionary Key Types\r\n    * A type must be hash able to be used as dictionary's key type\r\n    * A hash value is an Int value that is the same for all object that compare equal if a == b, a.hashValue == b.hashValue\r\n    * All Swift's basic types are hash able by default\r\n    * Enumeration member values without associated values are hash able by default\r\n    * Note\r\n      * Make custom typ to conform to Hashable protocol\r\n      * To provide hashValue and \"==\" operator property implementation\r\n      * hashValue not required to be the same across different executions or in different programs\r\n\r\n## Control Flow\r\n\r\n### For Loops\r\n\r\n  * For-In\r\n    * Index is only within the scope of the loop\r\n\r\n      ```swift\r\n      for index in 1...5 {\r\n        println(\"\\(index) times 5 is \\(index * 5)\")\r\n      }\r\n      ```\r\n\r\n    * If you don't need the index value\r\n\r\n      ```swift\r\n      for _ in 1...power { ... }\r\n      ```\r\n\r\n    * You can use for in for array and dictionaries too:\r\n\r\n      ```swift\r\n      for name in names { ... }\r\n      for (key, value) in dictionaries { ... }\r\n      ```\r\n\r\n    * String character\r\n\r\n      ```swift\r\n      for char in \"hello\" { ... }\r\n      ```\r\n\r\n  * For\r\n\r\n    ```swift\r\n    for var i = 0; i < 3; ++i { ... }\r\n    ```\r\n\r\n\r\n### While Loops\r\n\r\n  * While\r\n\r\n    ```swift\r\n    while [cond] { ... }\r\n    ```\r\n\r\n  * Do-While\r\n\r\n    ```swift\r\n    do { ... } while [cond]\r\n    ```\r\n\r\n\r\n### Conditional Statements\r\n\r\n  * If\r\n\r\n    ```swift\r\n    if [cond]  { ... }\r\n    if [cond] { ... } else { ... }\r\n    if [cond] { ... } else if [cond] { ...  }\r\n    ```\r\n\r\n  * Switch\r\n\r\n    ```swift\r\n    switch [value] {\r\n      case [value 1]:\r\n      // respond to value 1\r\n      case [value 2], [value 3]:\r\n      // respond to value 2 or 3\r\n      default:\r\n      // otherwise, do something else\r\n    }\r\n    ```\r\n\r\n    * default is a must\r\n  * No Implicit Fall through\r\n    * In contrast with switch statements in C and Objective-C, switch statement in Swift do not fall through the bottom of each case\r\n    * Though break is not required in Swift, you can still use a break statement to match and ignore a particular case or to break out from a case before it is completed\r\n    * Body of each case must contain one executable statement\r\n    * To opt-in for fall through behaviour, use the **fallthough** keyword\r\n  * Range matching\r\n\r\n    ```swift\r\n    switch count {\r\n      case 1...3:\r\n      // statement here\r\n    }\r\n    ```\r\n\r\n  * Tuples\r\n    * You can use tuple to test multiple values in a switch statement\r\n\r\n      ```swift\r\n      let somePoint = (1, 1)\r\n\r\n      switch somePoint {\r\n        case (0, 0):\r\n          ....\r\n        case (_, 0):\r\n          ...\r\n        case (-2...2, -2...2):\r\n          ...\r\n        default:\r\n          ...\r\n      }\r\n      ```\r\n\r\n  * Value Bindings\r\n    * Bind value or values it matches to temporary constants or variables for use in the body of the case, known as value binding\r\n\r\n      ```swift\r\n      switch anotherPoint {\r\n        case (let x, 0):\r\n          ...\r\n        case let (x, y):\r\n          ...\r\n        }\r\n      ```\r\n\r\n    * Note that on this case the default statement is not required, cause every possible case as been catered for\r\n  * Where\r\n    * To check additional conditions\r\n\r\n      ```swift\r\n      case let (x, y) where x == y:\r\n      ```\r\n\r\n### Control Transfer Statements\r\n\r\n  * Continue\r\n    * Tells a loop to stop what it is doing, and start again at the beginning of the next iteration\r\n  * Break\r\n    * Break In a Loop Statement\r\n    * Break In a Switch Statement\r\n      * Used to match and ignore one or more cases in switch statement\r\n      * Switch does not allow empty case, to deliberately match & ignore a case\r\n  * Fallthrough\r\n    * Switch statements in Swift do not fall through the bottom of each case into the next one\r\n    * To enable fall through the next case use fallthrough keyword\r\n\r\n      ```swift\r\n      case abc:\r\n        // fallthrough\r\n      case next:\r\n        // executed again\r\n        // fallthrough\r\n      default:\r\n        // executed again\r\n      ```\r\n\r\n    * Fallthrough does not check the next condition\r\n  * Labeled Statements\r\n    * You can nest switch statement inside another loop statement\r\n    * Sometimes it is important to be explicit which statement you want to break/continue\r\n    * You can mark a loop statement or switch statement with a statement label\r\n    * Format:\r\n      * [label name]:  while [condition] { ... }\r\n\r\n      ```swift\r\n      gameLoop: while [condition] {\r\n        switch [variable] {\r\n          case [condition]\r\n            break grameLoop\r\n        }\r\n      }\r\n      ```\r\n\r\n## Functions\r\n\r\n### Defining and Calling Functions\r\n\r\n```swift\r\nfunc sayHello(personName: String) -> String {\r\n  let greeting = \"Hello, \" + personName + \"!\"\r\n  return greeting\r\n}\r\n\r\nsayHello(\"Anna\")\r\n```\r\n\r\n### Function Parameters & Return Values\r\n\r\n  * Multiple Input Parameters\r\n\r\n    ```swift\r\n    func halfOpenRangeLength(start: Int, end: Int) -> Int {\r\n      return end - start\r\n    }\r\n    println(halfOpenRangeLength(1, 10)) // prints \"9\"\r\n    ```\r\n      * Functions without Parameters\r\n\r\n        ```swift\r\n        func sayHelloWorld() -> String {\r\n          return \"hello, world\"\r\n        }\r\n        println(sayHelloWorld())\r\n        ```\r\n\r\n      * Functions without Return Values\r\n\r\n        ```swift\r\n        func sayGoodbye(personName: String) {\r\n          println(\"Goodbye, \\(personName)!\")\r\n        }\r\n        sayGoodbye(\"Dave\")\r\n        ```\r\n\r\n      * Functions with Multiple Return Values\r\n        ```swift\r\n        func minMax(array: [Int]) -> (min: Int, max: Int) {\r\n          var currentMin = array[0]\r\n          var currentMax = array[0]\r\n          for value in array[1..<array.count] {\r\n            if value < currentMin {\r\n              currentMin = value\r\n            } else if value > currentMax {\r\n              currentMax = value\r\n            }\r\n          }\r\n          return (currentMin, currentMax)\r\n        }\r\n\r\n        let bounds = minMax([8, -6, 2, 109, 3, 71])\r\n        bounds.min\r\n        bounds.max\r\n        ```\r\n\r\n  * Optional Tuple Return Types\r\n    * -> (Int, Int)?\r\n    * It's different from (Int?, Int?)\r\n    * if let bounds = minMax(...) { ... }\r\n\r\n### Function Parameter Names\r\n\r\n```swift\r\nfund someFunction(paramName: Int) { ... }\r\n```\r\n\r\n    * Param only be used inside the function\r\n  * External Parameter Names\r\n    * Sometimes it is useful to use a different param when you call a function\r\n    * To do that, define an external parameter name for each parameter\r\n\r\n      ```swift\r\n      func someFunction(paramExt  paramName: Int) { ... }\r\n      someFunc(paramExt: 2)\r\n      ```\r\n\r\n    * Consider using external param names when the purpose of a function's argument are not clear\r\n  * Shorthand External Parameter Names\r\n    * If the local param name the same with external param name, use the hash symbol (#)\r\n    * func someFunction(#paramName: Int)\r\n  * Default Parameter Values\r\n    * Place params with default values at the end of a function's param list.\r\n    * Ensures that all calls to the func use the same order for their non-default args\r\n\r\n      ```swift\r\n      func someFunc(paramName: String = \" \") { ... }\r\n      ```\r\n\r\n  * External Names for Parameters with Default Values\r\n    * Swift provides an automatic external name for any param that has a default value, and it is the same with the paramName just like using the hash symbol\r\n\r\n      ```swift\r\n      func someFunc(joiner: String = \" \")\r\n      someFunc(joiner: \"-\")\r\n      ```\r\n\r\n    * You can opt out of this behaviour by writing an underscore (_) instead of an explicit external name when you define a parameter\r\n      * Not recommended\r\n  * Variadic Parameters\r\n    * Accepts 0 or more values for a specified type\r\n    * [someType]...\r\n\r\n      ```swift\r\n      func average(numbers: Double...) -> Double\r\n      average(1, 2, 3, 4, 5)\r\n      ```\r\n\r\n    * At most one variadic param, must be as the last in the parameter list\r\n    * If there are default values as well, place variadic param after all the defaulted parameters\r\n  * Constant & Variable Parameters\r\n    * Function params are constants by default\r\n    * Sometimes it is useful to have a variable copy to work with\r\n\r\n      ```swift\r\n      func someFunc(var paramName: String)\r\n      ```\r\n\r\n    * Changes made to a variable param do not persist beyond the end of each call, not visible outside the function's body\r\n    * Variable param only exists for the lifetime of that function call\r\n  * In-Out Parameters\r\n    * If you want a function to modify a parameter's value, and want the changes to persist.\r\n    * Use 'inout' keyword at the start of the parameter definition\r\n    * You can only pass a variable not a constant\r\n    * You place an & before a variable's name when you pass it as an argument\r\n    * Can not have default values, and variadic params can not be marked as inout. If you mark it as inout, you can't mark it as var or let\r\n\r\n      ```swift\r\n      func someFunc(inout paramName: Int)\r\n\r\n      var locName = 3\r\n      someFunc(&locName)\r\n      ```\r\n\r\n### Function Types\r\n\r\n```swift\r\n// Function Type as a parameter type for another function\r\nfunc printMathResult(mathFunc: (Int, Int) -> Int, a: Int, b:Int) { ... }\r\nprintMathResult(addTwoInts, 3, 5)\r\n\r\n// Function Type as Return Types\r\nfunc someFunc(backwards: Bool) -> (Int) -> Int {\r\n  return backwards ? stepBackward : stepForward\r\n}\r\n```\r\n\r\n### Nested Functions\r\n\r\n```swift\r\nfunc chooseStepFunction(backwards: Bool) -> (Int) -> Int {\r\n  func stepForward(input: Int) -> Int { return input + 1 }\r\n  func stepBackward(input: Int) -> Int { return input - 1 }\r\n  return backwards ? stepBackward : stepForward\r\n}\r\n```\r\n\r\n## Closures\r\n\r\n### Overview\r\n\r\n  * Three forms:\r\n    * Global functions are closures that have a name and do not capture any values\r\n    * Nested functions are closures that have name and can capture values from their enclosing function\r\n    * Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context\r\n  * Swift closures have clean & clear style with optimisations:\r\n    * Inferring parameter and return types from the context\r\n    * Implicit returns from single-expression closures\r\n    * Shorthand argument names\r\n    * Trailing closure syntax\r\n\r\n### Closure Expressions\r\n\r\n  * A way to write inline closure in a brief focused syntax\r\n  * The Sorted Function\r\n\r\n      ```swift\r\n      let names = [\"Chris\", \"Alex\", \"Ewa\", \"Barry\", \"Daniella\"]\r\n      func backwards(s1: String, s2: String) -> Bool { return s1 > s2 }\r\n      var reversed = sorted(names, backwards)\r\n      ```\r\n\r\n  * Closure Expression Syntax\r\n\r\n    ```swift\r\n    { ([parameters] -> [return type] in\r\n      [statements]\r\n    }\r\n    ```\r\n\r\n    * Can use constant, variable and inout parameters.\r\n    * **Default values cannot be provided**\r\n    * Variadic parameters can be used\r\n    * Tuples can also be used as parameter types and return types\r\n\r\n      ```swift\r\n      reversed = sorted(names, { (s1: String, s2: String) -> Bool in\r\n        return s1 -> s2\r\n      })\r\n      ```\r\n\r\n    * Closure can be written on a single line\r\n  * Inferring Type from Context\r\n    * Because sorting closure is passed as an argument to a function, Swift can infer the types of its parameters and return from the type of the sorted function's second parameter.\r\n\r\n      ```swift\r\n      reversed = sorted(names, { s1, s2 in return s1 > s2 })\r\n      ```\r\n\r\n    * You never need to write an inline closure in it fullest form when closure is used as a function argument\r\n    * You can still make types explicit to avoid ambiguity for readers\r\n  * Implicit Returns from Single-Expression Closures\r\n    * Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration:\r\n\r\n      ```swift\r\n      reversed = sorted(names, { s1, s2 in s1 > s2 })\r\n      ```\r\n\r\n  * Shorthand Argument Names\r\n    * $0, $1, $2\r\n    * You can omit closure's argument list from its definition\r\n    * The in keyword can also be omitted because the closure expression is made up entirely of its body\r\n\r\n      ```swift\r\n      reversed = sorted(names, { $0 > $1 })\r\n      ```\r\n\r\n  * Operator Functions\r\n    * There's actually an even shorter way to write the closure expression above\r\n    * Swift's String type defines its string specific implementation of the > operator as a function that has two parameters of type String, and returns Bool\r\n    * It matches the function type needed for the sorted function\r\n    * Thus Swift can infer that you want to use its string specific implementation:\r\n\r\n      ```swift\r\n      reversed = sorted(names, >)\r\n      ```\r\n\r\n### Trailing Closures\r\n\r\n  * If closure is long and passed as function's final argument\r\n  * Write outside of (and after) the parentheses of the function call it supports:\r\n\r\n    ```swift\r\n    func someFunc(closure: () -> ()) { ... }\r\n    someFunc({  // closure body })\r\n    someFunc() { // trailing's closure body }\r\n    ```\r\n\r\n  * If a closure expression is provided as the function's only argument, you provide that expression as a trailing closure, you can omit a pair of parentheses ()\r\n\r\n    ```swift\r\n    reversed = sorted(names) { $0 > $1 }\r\n    ```\r\n\r\n    * Map example:\r\n\r\n      ```swift\r\n        let strings = numbers.map {\r\n          (var number) -> String in\r\n\r\n          var output = \"\"\r\n          while number > 0 {\r\n            output = digitNames[number % 10]! + output\r\n            number /= 10\r\n\r\n          }\r\n          return output\r\n        }\r\n      ```\r\n\r\n### Capturing Values\r\n\r\n  * Closure capture constants and variables from the surrounding context in which it is defined\r\n  * Closure can refer and modify those values even if the original scope no longer exists\r\n  * Simplest form of a closure in Swift is a nested function\r\n\r\n    ```swift\r\n    func makeIncrementor(forIncrement amount: Int) -> () -> Int {\r\n      var runningTotal = 0\r\n\r\n      func incrementor() -> Int {\r\n        runningTotal += amount\r\n        return runningTotal\r\n      }\r\n      return incrementor\r\n    }\r\n\r\n    let incrementByTen = makeIncrementor(forIncrement: 10)\r\n    incrementByTen() // 10\r\n    incrementByTen() // 20\r\n    ```\r\n\r\n  * If you assign a closure to a property of a class instance\r\n    * The closure captures that instance by referring to the instance or its members, this will create strong reference cycle\r\n  * Swift uses capture lists to break these strong reference cycles, more info later\r\n\r\n### Closures are Reference Types\r\n\r\n  * Whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function/closure\r\n  * Example above, it is the choice of closure that incrementByTen refers to that is constant, not the contents of the closure itself\r\n  * Meaning if you assign a closure to two different constants/variables, both refer to the same closure\r\n\r\n    ```swift\r\n    let alsoIncrementByTen = incrementByTen\r\n    alsoIncrementByTen()\r\n    ```\r\n\r\n## Enumerations\r\n\r\n### Overview\r\n\r\n  * Defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code\r\n  * C enums assign related names to set a of integer values\r\n  * Enums in Swift are more flexible, and do not have to provide a value for each member of the enumeration\r\n  * If a value (raw value) is provided for each enumeration member, the value can be a string, a character, a value, of any integer or floating-point type\r\n  * Adopt many features traditionally supported only by classes, such as:\r\n    * computed properties to provide additional info about enum's current value\r\n    * instance methods\r\n    * define initialisers to provide an initial member value\r\n    * extended to expand their functionality\r\n    * conform to protocols\r\n\r\n### Enumeration Syntax\r\n\r\n  ```swift\r\n  enum SomeEnumeration {\r\n    // enumeration definition goes here\r\n  }\r\n\r\n  enum CompassPoint {\r\n    case North\r\n    case South\r\n    case East\r\n    case West\r\n  }\r\n  ```\r\n\r\n  * Unlike C & Obj-C, Swift enumeration members are not assigned with a default integer value when they are created\r\n    * Instead, the different enumeration members are fully fledged values in their own right, with an explicitly defined type of CompassPoint\r\n  * Multiple member values:\r\n\r\n    ```swift\r\n    enum Planet {\r\n      case Mercury, Venus, Earth\r\n    }\r\n    ```\r\n\r\n  * Each enum defines a brand new type\r\n  * Name should start with a capital letter\r\n  * Singular format\r\n\r\n    ```swift\r\n    var directionToHead = CompassPoint.West\r\n    ```\r\n\r\n  * Once directionToHead is defined, you can use a shorthand notation\r\n\r\n    ```swift\r\n    directionHead = .East\r\n    ```\r\n\r\n### Matching Enumeration Values with a Switch Statement\r\n\r\n  ```swift\r\n  directionToHead = .South\r\n    switch directionToHead {\r\n      case .North:\r\n        println(\"Lots of planets have a north\")\r\n      case .South:\r\n        println(\"Watch out for penguins\")\r\n      case .East:\r\n        println(\"Where the sun rises\")\r\n      case .West:\r\n        println(\"Where the skies are blue\")\r\n    }\r\n  ```\r\n  * Switch statement must be exhaustive considering an enumeration's members, if .West is omitted, there'll be a compilation error.\r\n\r\n### Associated Values\r\n\r\n  * Sometimes it is useful to store associated values of other types along with these member values.\r\n  * This enables you to store additional custom info along with the member value, and permit this info to vary each time you use that member in your code.\r\n  * Associated value can be any given type, and the value type can be different for each member of the enumeration\r\n  * Enumerations similar to these are known as **discriminated unions, tagged unions and variants** in other programming language.\r\n\r\n    ```swift\r\n    enum Barcode {\r\n      case UPCA(Int, Int, Int, Int)\r\n      case QRCode(String)\r\n    }\r\n    var productBarCode = Barcode.UPCA(8, 85909, 51226, 3)\r\n    productBarCode = .QRCode(\"ABCDEF\")\r\n    ```\r\n\r\n    * Switch statement:\r\n\r\n      ```swift\r\n      switch productBarcode {\r\n        case .UPCA(let numberSystem, let manufacturer, let product, let check):\r\n          println(\"UPC-A: \\(numberSystem), \\(manufacturer), \\(product), \\(check).\")\r\n\r\n        case .QRCode(let productCode):\r\n          println(\"QR code: \\(productCode).\")\r\n      }\r\n\r\n      // prints \"QR code: ABCDEFGHIJKLMNOP.\"\r\n      ```\r\n\r\n    * You can place a single var/let before the member name for brevity:\r\n\r\n      ```swift\r\n      switch productBarcode {\r\n        case let .UPCA(numberSystem, manufacturer, product, check):\r\n          println(\"UPC-A: \\(numberSystem), \\(manufacturer), \\(product), \\(check).\")\r\n        case let .QRCode(productCode):\r\n          println(\"QR code: \\(productCode).\")\r\n      }\r\n      // prints \"QR code: ABCDEFGHIJKLMNOP.\r\n      ```\r\n\r\n### Raw Values\r\n\r\n  * Enumeration members can come repopulated with default values (raw values), which are all of the same type\r\n\r\n    ```swift\r\n    enum ASCIIControlCharacter: Character {\r\n      case Tab = \"\\t\"\r\n      case LineFeed = \"\\n\"\r\n      case CarriageReturn = \"\\r\"\r\n    }\r\n    ```\r\n\r\n  * Raw value has to be unique, raw value for a particular enumeration number is always the same\r\n  * When integers are used for raw values, they auto-increment\r\n\r\n    ```swift\r\n    enum Planet: Int {\r\n      case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune\r\n    }\r\n\r\n    let earthsOrder = Planet.Earth.rawValue // 3\r\n    let possiblePLanet = Planet(rawValue: 2)\r\n    ```\r\n\r\n## Classes & Structures\r\n\r\n### Overview\r\n\r\n  * Swift does not require you to create separate interface implementation files for custom classes and structures\r\n\r\n### Comparing Classes and Structures\r\n\r\n  * Things in common\r\n    * Define properties to store values\r\n    * Define methods to provide functionality\r\n    * Define subscripts to provide access to their values using subscript syntax\r\n    * Define initializers to setup their initial state\r\n    * Extended to expand their functionality\r\n    * Conform to protocols\r\n  * Classes have additional capabilities that structures do not:\r\n    * Inheritance\r\n    * Type casting\r\n    * Deinitializers\r\n    * Reference counting allows more than one reference to a class instance\r\n      * Structures are always copied when they are passed in your code, they don't use reference counting\r\n  * Definition Syntax\r\n    * Similar between Class & Structure\r\n    * Syntax:\r\n\r\n      ```swift\r\n      class SomeClass { ... }\r\n      struct SomeStructure { ... }\r\n      ```\r\n\r\n    * When you define a new class or structure, you define a new Swift type.\r\n\r\n      ```swift\r\n      struct Resolution {\r\n        var width = 0\r\n        var height = 0\r\n      }\r\n\r\n      class VideoMode {\r\n        var resolution = Resolution()\r\n        var interlaced = false\r\n        var frameRate = 0.0\r\n        var name: String?\r\n      }\r\n      ```\r\n\r\n  * Class and Structure Instances\r\n\r\n    ```swift\r\n    let someResolution = Resolution()\r\n    let someVideoMode = VideoMode()\r\n    ```\r\n\r\n  * Accessing Properties\r\n\r\n    ```swift\r\n    someResolution.width // 0\r\n    someVideoMode.resolution.width // 0\r\n    someVideoMode.resolution.width = 1280\r\n    ```\r\n\r\n    * Note\r\n      * Unlike Obj-C, Swift enables you to set sub properties of a structure property directly.\r\n      * You are able to set resolution.width directly, without the need to set the entire resolution property\r\n  * Memberwise Initializers for Structure Types\r\n    * Use it to initialise member properties of new structure instances\r\n    * Initial values can be passed to the member wise init by name:\r\n\r\n      ```swift\r\n      let vga = Resolution(width: 640, height: 480)\r\n      ```\r\n\r\n    * Class does not have default member wise initialiser.\r\n\r\n### Structures and Enumerations are Value Types\r\n\r\n  * A value type, means its value is copied when ascend to a variable or a constant or when it is passed to a function, including all types in Swift, i.e. integers, floating-point numbers, booleans, etc.\r\n\r\n### Classes Are Reference Types\r\n\r\n  * Reference types are not copied when they are assigned to a variable/constant or when they are passed to a function. Reference to the same instance is used instead.\r\n  * **Identity Operators**\r\n    * Comparing if two objects are the same instance (===)\r\n    * Equal means two instances having the same values (!==)\r\n  * **pointers**\r\n    * A swift constant or variable that refers to an instance is similar to a pointer in C, but is not a direct pointer to an address in memory and does not require you to write an asterisk\r\n    * These references are defined like any other constant/variable in Swift\r\n\r\n### Choosing Between Classes and Structures\r\n\r\n  * Consider structure if:\r\n    * Primary purpose is to encapsulate a few relatively simple data values\r\n    * Expect that the encapsulated values are copied rather than referenced\r\n    * Any properties stores by the structure a themselves of value types, which would be expected to be copied\r\n    * Does not need to inherit properties or behaviour from another existing type\r\n  * Examples of structures\r\n    * Size of a geometric shape, with width, height properties, both of type Double\r\n    * A way to refer ranges within a series perhaps encapsulating a start and length properties, both of type Int\r\n    * A point in a 3D coordinate system, perhaps encapsulating, x, y, z properties, of type Double\r\n\r\n### Assignment and Copy Behavior for Strings, Arrays, and Dictionaries\r\n\r\n  * String, Array, Dictionary types are implemented as structures\r\n  * Different from NSString, NSArray, and NSDictionary which are implemented as classes, which are passed by reference.\r\n  * Swift only performs actual copy behind the scenes when absolutely necessary, it manages all value copying to ensure optimal performance\r\n\r\n## Properties\r\n\r\n### Overview\r\n\r\n  * Associate values with a particular class, structure or enumeration\r\n  * Stored properties store constant and variable values as part of an instance\r\n    * Provided only by classes and structures\r\n  * Computed properties are provided by classes, structures and enumerations.\r\n  * Stored and computed properties are associated with instances, but properties can be associated to the type itself, known as type properties\r\n  * You can define property observer, for properties you define or properties that a subclass inherits from its superclass.\r\n\r\n### Stored Properties\r\n\r\n  * Is a constant or variable that is stored as part of an instance of a particular class or structure\r\n\r\n    ```swift\r\n    struct FixedLengthRange {\r\n      var firstValue: Int\r\n      let length: Int\r\n    }\r\n\r\n    var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)  // the range represents integer values 0, 1, and 2\r\n    rangeOfThreeItems.firstValue = 6 // the range now represents integer values 6, 7, and 8\r\n    ```\r\n\r\n  * Stored Properties of Constant Structure Instances\r\n    * When an instance of a value type is marked as a constant, so are all of its properties, but not true for classes.\r\n\r\n      ```swift\r\n      let someStruct = SomeStruct(x: 0, y: 0)\r\n      someStruct.x = 12 // compile-error\r\n      ```\r\n\r\n  * Lazy Stored Properties\r\n    * Property whose initial value is not calculated until the first time it is used\r\n    * Use 'lazy' modifier before its declaration\r\n    * Must always declare lazy as a var\r\n    * Useful for a property that is dependent on outside factors, whose values are not known after an initialisation completes, e.g. computationally expensive\r\n\r\n      ```swift\r\n      class DataImporter {\r\n        var fileName = \"data.txt\"\r\n        // the DataImporter class would provide data importing functionality here\r\n      }\r\n\r\n      class DataManager {\r\n        lazy var importer = DataImporter()\r\n        var data = [String]()\r\n        // the DataManager class would provide data management functionality here\r\n      }\r\n\r\n      let manager = DataManager()\r\n      manager.data.append(\"Some data\")\r\n      manager.data.append(\"Some more data\")\r\n      // the DataImporter instance for the importer property has not yet been created\r\n      ```\r\n\r\n    * DataImporter instance for the importer property is only created when the importer property is first accessed, e.g.\r\n      * manager.importer.fileName\r\n  * Stored Properties and Instance Variables\r\n    * Obj-C provides two ways to store values and references as apart of a class instance\r\n      * In additional to properties, you can use instance variables as a backing store for values store in a property\r\n    * Swift unifies these concepts into a single property declaration\r\n      * It does not have a corresponding instance variable, and the backing store for a property is not accessed directly\r\n      * To simplify and avoid confusion\r\n\r\n### Computed Properties\r\n\r\n  * Do not store a value, provides a getter and optional setting to retrieve and set other properties/values directly\r\n\r\n    ```swift\r\n    struct Point {\r\n        var x = 0.0, y = 0.0\r\n    }\r\n    struct Size {\r\n        var width = 0.0, height = 0.0\r\n    }\r\n    struct Rect {\r\n        var origin = Point()\r\n        var size = Size()\r\n        var center: Point {\r\n            get {\r\n                let centerX = origin.x + (size.width / 2)\r\n                let centerY = origin.y + (size.height / 2)\r\n                return Point(x: centerX, y: centerY)\r\n            }\r\n            set(newCenter) {\r\n                origin.x = newCenter.x - (size.width / 2)\r\n                origin.y = newCenter.y - (size.height / 2)\r\n            }\r\n        }\r\n    }\r\n\r\n    var square = Rect(origin: Point(x: 0.0, y: 0.0),\r\n        size: Size(width: 10.0, height: 10.0))\r\n\r\n    let initialSquareCenter = square.center\r\n    square.center = Point(x: 15.0, y: 15.0)\r\n    ```\r\n\r\n  * Shorthand Setting Declaration\r\n    * If computed property's setting does not define a name for the new value to be set, \"newValue\" is used:\r\n\r\n      ```swift\r\n      set {\r\n        origin.x = newValue.x - (size.width / 2)\r\n        origin.y = newValue.y - (size.height / 2)\r\n      }\r\n      ```\r\n\r\n  * Read-Only Computed Properties\r\n    * Has getter but no setter\r\n    * You must declare computed properties, including read only properties as variable properties with 'var' keyword, because their value is not fixed.\r\n    * _You can simplify read-only computed property by removing the get keyword and its braces_:\r\n\r\n    ```swift\r\n    struct Cuboid {\r\n      var width = 0.0, height = 0.0, depth = 0.0\r\n      var volume: Double {\r\n        return width * height * depth\r\n      }\r\n    }\r\n\r\n    let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)\r\n    ```\r\n\r\n### Property Observers\r\n\r\n  * You can add property observers to any stored properties you define, apart from the lazy stored properties\r\n  * Any inherited property by overriding the property within a subclass\r\n  * Note\r\n    * You don't need to define property observers for non-overridden computed properties, because you can observe and respond to changes to their value directly from within the computed property's setter.\r\n  * You have the option to define either or both of these observers on a property\r\n    * willSet - called before the value is stored\r\n      * default param \"newValue\", you can override\r\n    * didSet - called immediately after the new value is stored\r\n      * default old property param name is \"oldValue\"\r\n  * Note\r\n    * willSet and didSet are not called when a property is first initialised, only called when its value is set outside the initialisation context\r\n    * If you assign a value to a property within its own didSet observer, the new value will replace the one that you just set\r\n\r\n      ```swift\r\n      class StepCounter {\r\n        var totalSteps: Int = 0 {\r\n          willSet(newTotalSteps) { }\r\n          didSet { if totalSteps > oldValue { ... } }\r\n        }\r\n      }\r\n      ```\r\n\r\n### Global and Local Variables\r\n\r\n  * Capabilities above to observe properties are for both global and local properties\r\n  * Global variables are defined outside any function, method, closure or type context\r\n  * Global constants and variables are always computed lazily, similar to Lazy Stored Properties\r\n\r\n### Type Properties\r\n\r\n  * For value types (structures and enumerations), you can define stored and computed type properties,\r\n  * For classes, you can define computed type properties only\r\n  * Stored type properties for value types can be variables or constants.\r\n    * Computed type properties are always declared as variable properties in the same way as computed instance properties\r\n  * Type Property Syntax\r\n    * In C and Obj-C, you define static constants and variables associated with a type as global static variables\r\n    * In Swift type properties are written as part of type's definition, with \"**static**\" keyword for value types, and and \"**class**\" for class types.\r\n\r\n      ```swift\r\n      struct SomeStructure {\r\n\r\n        static var storedTypeProperty = \"Some value.\"\r\n        static var computedTypeProperty: Int {\r\n            // return an Int value here\r\n        }\r\n      }\r\n\r\n      enum SomeEnumeration {\r\n        static var storedTypeProperty = \"Some value.\"\r\n        static var computedTypeProperty: Int {\r\n            // return an Int value here\r\n        }\r\n      }\r\n\r\n      class SomeClass {\r\n        class var computedTypeProperty: Int {\r\n            // return an Int value here\r\n        }\r\n      }\r\n      ```\r\n\r\n    * The computed type property are for read-only, but you can define read-write computed type properties with the same syntax for computed instance properties\r\n  * Querying and Setting Type Properties\r\n\r\n    ```swift\r\n    println(SomeClass.computedTypeProperty)    // prints \"42\"\r\n    println(SomeStructure.storedTypeProperty)  // prints \"Some value.\"\r\n    SomeStructure.storedTypeProperty = \"Another value.\r\n    ```\r\n\r\n    * Setting type property\r\n\r\n## Methods\r\n\r\n### Overview\r\n\r\n  * Functions associated with a particular type\r\n  * Classes, structures and enumerations can define instance and type methods.\r\n  * Major difference from C and Obj-C. In Obj-C, only classes can define methods.\r\n\r\n### Instance Methods\r\n\r\n```swift\r\nclass Counter {\r\n    var count = 0\r\n    func increment() {\r\n        count++\r\n    }\r\n    func incrementBy(amount: Int) {\r\n        count += amount\r\n    }\r\n    func reset() {\r\n        count = 0\r\n    }\r\n}\r\n```\r\n  * Local and External Parameter Names for Methods\r\n    * Function params can have both local and external name, same wit method parameters\r\n      * Methods are just functions associated with a type\r\n      * But the default behaviour is different for functions and methods\r\n    * Methods in Swift similar to Obj-C, name of a method refers to the method's first parameter using a preposition such as \"width\", \"for\", \"by\", e.g. incrementBy(amount:, numberOfTimes). Easy to read as a sentence\r\n    * Swift makes this naming convention easy to write by using a different default approach for method parameters than it uses for functions\r\n      * It gives the **first parameter** name in a method a **local parameter name** by default\r\n      * And gives the **second and subsequent parameter names** both **local and external parameter** names by default\r\n\r\n        ```swift\r\n          class Counter {\r\n            var count: Int = 0\r\n            func incrementBy(amount: Int, numberOfTimes: Int) {\r\n              count += amount * numberOfTimes\r\n            }\r\n          }\r\n        ```\r\n\r\n      * You can call the method as follows:\r\n\r\n        ```swift\r\n        let counter = Counter()\r\n        counter.incrementBy(5, numberOftimes: 3)\r\n        ```\r\n\r\n      * Default behaviour as if\r\n\r\n        ```swift\r\n        func incrementBy(amount: Int, #numberOfTimes: Int) {\r\n          count += amount * numberOfTimes\r\n        }\r\n        ```\r\n  * Modifying External Parameter Name Behaviour for Methods\r\n    * Use # or add external parameter name for the first param\r\n    * To disable second param onwards, add _\r\n  * The self Property\r\n    * self refers to current instance\r\n    * You don't usually need to declare\r\n    * Unless when a parameter name has the same name as the property of that instance\r\n  * Modifying Value Types from Within Instance Methods\r\n    * Structures and enumeration are value types, which properties of a value type cannot be modified from within its instance methods.\r\n    * You can opt-in to mutating behaviour for that method, the method can also assign a completely new instance to its implicit self property\r\n    * Use \"mutating\" keyword before the \"func\" for the method:\r\n\r\n      ```swift\r\n      struct Point {\r\n        var x = 0.0, y = 0.0\r\n        mutating func moveByX(deltaX: Double, y deltaY: Double) {\r\n          x += deltaX\r\n          y += deltaY\r\n        }\r\n      }\r\n\r\n      var somePoint = Point(x: 1.0, y: 1.0)\r\n      somePoint.moveByX(2.0, y: 3.0)\r\n      ```\r\n\r\n    * Note that you cannot call a mutating method on a constant structure\r\n\r\n      ```swift\r\n      let fixedPoint = Point(x: 3.0, y: 3.0)\r\n      fixedPoint.moveByX(2.0, y: 3.0) // this will report an error\r\n      ```\r\n\r\n  * Assigning to self Within a Mutating Method\r\n\r\n      ```swift\r\n      struct Point {\r\n        var x = 0.0, y = 0.0\r\n        mutating func moveByX(deltaX: Double, y deltaY: Double) {\r\n          self = Point(x: x + deltaX, y: y + deltaY)\r\n        }\r\n      }\r\n      ```\r\n\r\n    * Mutating methods for enumerations can set the self to a different member of the same enumeration\r\n\r\n      ```swift\r\n      enum TriStateSwitch {\r\n\r\n        case Off, Low, High\r\n        mutating func next() {\r\n            switch self {\r\n            case Off:\r\n                self = Low\r\n            case Low:\r\n                self = High\r\n            case High:\r\n                self = Off\r\n            }\r\n        }\r\n      }\r\n      var ovenLight = TriStateSwitch.Low\r\n      ovenLight.next()\r\n      // ovenLight is now equal to .High\r\n      ovenLight.next()\r\n      // ovenLight is now equal to .Off\"\r\n      ```\r\n\r\n### Type Methods\r\n\r\n  * You indicate type methods for classes by writing the keyword \"class\" before the method's fund keyword, and type methods for structures and enumerations by writing the keyword \"static\" before the method's fund keyword\r\n  * In Obj-C type methods only for classes, in Swift for all classes, structures, and enumerations.\r\n\r\n    ```swift\r\n    class SomeClass {\r\n      class func someTypeMethod() {\r\n        // type method implementation goes here\r\n      }\r\n    }\r\n\r\n    SomeClass.someTypeMethod()\r\n    ```\r\n\r\n  * self refers to type itself\r\n  * Accessing type methods from the same scope, doesn't require a self:\r\n\r\n    ```swift\r\n    struct LevelTracker {\r\n        static var highestUnlockedLevel = 1\r\n\r\n        static func unlockLevel(level: Int) {\r\n            if level > highestUnlockedLevel { highestUnlockedLevel = level }\r\n        }\r\n\r\n        static func levelIsUnlocked(level: Int) -> Bool {\r\n            return level <= highestUnlockedLevel\r\n        }\r\n\r\n        var currentLevel = 1\r\n        mutating func advanceToLevel(level: Int) -> Bool {\r\n            if LevelTracker.levelIsUnlocked(level) {\r\n                currentLevel = level\r\n                return true\r\n            } else {\r\n                return false\r\n            }\r\n        }\r\n    }\r\n    ```\r\n\r\n## Subscripts\r\n\r\n### Overview\r\n\r\n  * Classes, structures, enumerations can define subscripts\r\n  * Shortcuts for accessing the member elements of a collection, list or sequence\r\n  * Use subscripts to set/get values by index without the need for separate methods\r\n    * E.g. someArray[index], someDictionary[key]\r\n  * You can define multiple subscripts for a single type\r\n    * Appropriate subscript overload is based on the type of index value passed to the subscript\r\n    * Not limited to a single dimensions\r\n    * You can define multiple input params to suit your custom type's needs\r\n\r\n### Subscript Syntax\r\n\r\n  * Similar to instance methods, but can be read-write or read-only\r\n\r\n    ```swift\r\n    subscript(index: Int) -> Int {\r\n        get {\r\n            // return an appropriate subscript value here\r\n        }\r\n        set(newValue) {\r\n            // perform a suitable setting action here\r\n        }\r\n    }\r\n    ```\r\n\r\n    * As with read-only computed properties, you can drop the get keyword:\r\n\r\n      ```swift\r\n      subscript(index: Int) -> Int {\r\n          // return an appropriate subscript value here\r\n      }\r\n\r\n      struct TimesTable {\r\n          let multiplier: Int\r\n          subscript(index: Int) -> Int {\r\n              return multiplier * index\r\n          }\r\n      }\r\n\r\n      let threeTimesTable = TimesTable(multiplier: 3)\r\n      println(\"six times three is \\(threeTimesTable[6])\") // prints \"six times three is 18\r\n      ```\r\n\r\n### Subscript Usage\r\n\r\n  * Exact meaning of \"subscript\" depends on the context which it is used\r\n\r\n    ```swift\r\n    var numberOfLegs = [\"spider\": 8, \"ant\": 6, \"cat\": 4]\r\n    numberOfLegs[\"bird\"] = 2\r\n    ```\r\n\r\n    * Dictionary type implements its key-value subscripting, takes and receives an optional type\r\n\r\n      ```swift\r\n      numberofLegs[\"bird\"] returns a value of type Int?\r\n      ```\r\n\r\n### Subscript Options\r\n\r\n  * Can take any number of input parameters, and can be of any type\r\n    * Subscripts can also return any type\r\n    * Can you variable parameters, and variadic parameters\r\n    * No in-out params or default parameter values\r\n  * There could be more than one subscript implementations, which subscript to used will be inferred based on the type s of the value or values that are contained in subscript braces, i.e. subscript overloading\r\n  * Support multiple parameters\r\n\r\n    ```swift\r\n    struct Matrix {\r\n        let rows: Int, columns: Int\r\n        var grid: [Double]\r\n        init(rows: Int, columns: Int) {\r\n            self.rows = rows\r\n            self.columns = columns\r\n            grid = Array(count: rows * columns, repeatedValue: 0.0)\r\n        }\r\n        func indexIsValidForRow(row: Int, column: Int) -> Bool {\r\n            return row >= 0 && row < rows && column >= 0 && column < columns\r\n        }\r\n        subscript(row: Int, column: Int) -> Double {\r\n            get {\r\n                assert(indexIsValidForRow(row, column: column), \"Index out of range\")\r\n                return grid[(row * columns) + column]\r\n            }\r\n            set {\r\n                assert(indexIsValidForRow(row, column: column), \"Index out of range\")\r\n                grid[(row * columns) + column] = newValue\r\n            }\r\n        }\r\n    }\r\n    ```\r\n\r\n## Inheritance\r\n\r\n### Overview\r\n\r\n  * Classes can also add property observers to inherited properties\r\n  * Property observers can be added to any property, stored or computed\r\n\r\n### Defining a base class\r\n\r\n  * Any class that does not inherit from another class is known s base class\r\n  * Swift classes do not inherit from a universal base class\r\n  * Classes you define without a superclass, are base classes.\r\n\r\n    ```swift\r\n    class Vehicle {\r\n        var currentSpeed = 0.0\r\n        var description: String {\r\n            return \"traveling at \\(currentSpeed) miles per hour\"\r\n        }\r\n        func makeNoise() {\r\n            // do nothing - an arbitrary vehicle doesn't necessarily make a noise\r\n        }\r\n    }\r\n\r\n    let someVehicle = Vehicle()\r\n    someVehicle.description\r\n    ```\r\n\r\n### Subclassing\r\n\r\n  * Extending a new class based on an existing class\r\n\r\n    ```swift\r\n    class SomeSubclass: SomeSuperClass { ...}\r\n    ```\r\n\r\n### Overriding\r\n\r\n  * Use override keyword to clearly show the intent or error\r\n    * Compiler will also check if you are overriding any of the superclass methods\r\n  * Accessing superclass Methods, Properties, and Subscripts\r\n    * super.someMethod, super.someProperty, super[someIndex]\r\n  * Overriding methods\r\n\r\n    ```swift\r\n    class Train: Vehicle {\r\n        override func makeNoise() {\r\n            println(\"Choo Choo\")\r\n        }\r\n    }\r\n    ```\r\n\r\n  * Overring properties\r\n    * To provide your own implementation or to add property observer\r\n  * Overriding property Getters and Setters\r\n    * You can present an inherited read-only property as read-write property\r\n    * You can not present an inherited read-write property as a read only\r\n    * Note\r\n      * If you provide a setter, you need to provide the getter as well\r\n      * If you don't want to modify the inherited property's value within the overriding getter, just return the super class value, i.e. super.someProperty\r\n\r\n      ```swift\r\n      class Car: Vehicle {\r\n        var gear = 1\r\n        override var description: String {\r\n          return super.description + \" in gear \\(gear)\"\r\n        }\r\n      }\r\n      ```\r\n\r\n  * Overriding property Observers\r\n    * Override the property to add the observers\r\n    * Note\r\n      * You can not add property observers to inherited constant stored properties or inherited read-only computed properties, because these properties cannot be set\r\n      * You can't override both setter and property observer for the same property\r\n      * If you already provide custom setter, observe any value changes from within the custom setter instead\r\n    * Example:\r\n\r\n      ```swift\r\n      class AutomaticCar: Car {\r\n        override var currentSpeed: Double {\r\n          didSet {\r\n            gear = Int(currentSpeed / 10.0) + 1\r\n          }\r\n        }\r\n      }\r\n      ```\r\n\r\n### Preventing Overrides\r\n\r\n  * Mark it as \"final\", e.g. final var, final fund, final class fund, final subscript\r\n\r\n## Initialization\r\n\r\n### Overview\r\n\r\n  * Unlike Obj-C inits, Swift inits do not return value\r\n  * Instance of class types can also implement a deinitializer\r\n\r\n### Setting Initial Values for Stored Properties\r\n\r\n  * Classes and structures must set all their stored properties to an init value by the time an instance is created\r\n  * You can store initial value of a stored property in an initialiser, or by assigning default value\r\n  * Note\r\n    * When you assign the default value to a stored property, or sets the initial value within the initializers, the property is set directly without calling property observers.\r\n  * Initializers\r\n\r\n    ```swift\r\n    init() {\r\n      // perform some initialization here\r\n    }\r\n\r\n    struct Fahrenheit {\r\n      var temperature: Double\r\n\r\n      init() {\r\n        temperature = 32.0\r\n      }\r\n    }\r\n    ```\r\n\r\n### Customizing Initialization\r\n\r\n  * Initialization Parameters\r\n\r\n    ```swift\r\n    struct Celsius {\r\n        var temperatureInCelsius: Double\r\n        init(fromFahrenheit fahrenheit: Double) {\r\n            temperatureInCelsius = (fahrenheit - 32.0) / 1.8\r\n        }\r\n        init(fromKelvin kelvin: Double) {\r\n            temperatureInCelsius = kelvin - 273.15\r\n        }\r\n    }\r\n    let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)\r\n    // boilingPointOfWater.temperatureInCelsius is 100.0\r\n    let freezingPointOfWater = Celsius(fromKelvin: 273.15)\r\n    // freezingPointOfWater.temperatureInCelsius is 0.0\"\r\n    ```\r\n\r\n  * Local & External Parameter Names\r\n    * Initializers do not have an identifying function name, thus the names and types of an init parameters play an important role identifying which init to call.\r\n    * Swift provide an automatic external name to be the same with the local name\r\n\r\n      ```swift\r\n      struct Color {\r\n\r\n        let red, green, blue: Double\r\n        init(red: Double, green: Double, blue: Double) {\r\n          self.red   = red\r\n          self.green = green\r\n          self.blue  = blue\r\n        }\r\n\r\n        init(white: Double) {\r\n          red   = white\r\n          green = white\r\n          blue  = white\r\n        }\r\n      }\r\n\r\n      let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)\r\n      let halfGray = Color(white: 0.5)  // without external name will trigger an error\r\n      ```\r\n\r\n  * Initializer Parameters Without External Names\r\n\r\n      ```swift\r\n      // Use \"_\" as the external name\r\n      init(_ celsius: Double) {\r\n        temperatureInCelsius = celsius\r\n      }\r\n      Celcius(37.0)\r\n      ```\r\n\r\n  * Optional Property Types\r\n    * Optional property types are automatically initialised with a value of nil\r\n\r\n      ```swift\r\n      class SurveyQuestion {\r\n\r\n          var text: String\r\n          var response: String?\r\n          init(text: String) {\r\n              self.text = text\r\n          }\r\n          func ask() {\r\n              println(text)\r\n          }\r\n      }\r\n\r\n      let cheeseQuestion = SurveyQuestion(text: \"Do you like cheese?\")\r\n      cheeseQuestion.ask()\r\n      cheeseQuestion.response = \"Yes, I do like cheese.\"\r\n      ```\r\n\r\n  * **Modifying Constant Properties during Initialization**\r\n    * You can modify the value of a constant property during initialisation\r\n    * Can only be modified in class init, not sub-class init.\r\n\r\n### Default Initializers\r\n\r\n  * If no init is provided, Swift provide default init, optional parameters will be set to nil, example:\r\n\r\n    ```swift\r\n    class ShoppingListItem {\r\n      var name: String?\r\n      var quantity = 1\r\n      var purchased = false\r\n    }\r\n\r\n    var item = ShoppingListItem()\r\n    ```\r\n\r\n  * Memberwise Initialisers for Structure Types\r\n    * Structure types automatically receive a member wise initialiser if there is no custom initialisers\r\n    * Memberwise initializer is a shorthand way to initialise the member properties of new structure instances\r\n    * Initial values can be passed to the init by name\r\n\r\n      ```swift\r\n      struct Size {\r\n         var width = 0.0, height = 0.0\r\n      }\r\n\r\n      let twoByTwo = Size(width: 2.0, height: 2.0)\r\n      ```\r\n\r\n### Initializer Delegation for Value Types\r\n\r\n  * The rules are different for value types and class types.\r\n    * Value types (structures and enumerations) do not support inheritance, so their initialiser delegation process is relatively simple, they can only delegate to another initialiser, class has superclass.\r\n  * self.init can only be called within an initialiser\r\n  * If custom initialiser is defined, you won't have access to the default initialiser\r\n\r\n    ```swift\r\n    struct Size {\r\n        var width = 0.0, height = 0.0\r\n    }\r\n    struct Point {\r\n        var x = 0.0, y = 0.0\r\n    }\r\n    struct Rect {\r\n        var origin = Point()\r\n        var size = Size()\r\n        init() {}\r\n        init(origin: Point, size: Size) {\r\n            self.origin = origin\r\n            self.size = size\r\n        }\r\n        init(center: Point, size: Size) {\r\n            let originX = center.x - (size.width / 2)\r\n            let originY = center.y - (size.height / 2)\r\n            self.init(origin: Point(x: originX, y: originY), size: size)\r\n        }\r\n    }\r\n\r\n    let basicRect = Rect()              // basicRect's origin is (0.0, 0.0) and its size is (0.0, 0.0)\r\n    let originRect = Rect(origin: Point(x: 2.0, y: 2.0),\r\nsize: Size(width: 5.0, height: 5.0))   // originRect's origin is (2.0, 2.0) and its size is (5.0, 5.0)\r\n    ```\r\n\r\n  * Note\r\n    * For an alternative way to write this example without defining the init() and init(origin:size:) initializers yourself, see Extensions.\r\n\r\n### Class Inheritance and Initialization\r\n\r\n  * All of class's stored properties must be assigned to an initial value during initialisation\r\n  * Designated Initializers & Convenience Initializers\r\n    * Designated inits are primary inits for a class\r\n      * Init all properties in that class and calls its superclass chain inits\r\n      * Quite common to have only one\r\n    * Convenience inits, secondary support inits\r\n  * Syntax for Designated and Convenienc initialisers\r\n    * init ([parameters]) { ... }\r\n    * convenience init([parameters]) { ... }\r\n  * Init Chaining\r\n    * Rules to simply relationship between designated & convenience inits\r\n      1. Designated init must call a designated init from its immediate class\r\n      2. Convenience init must call another init from the same class\r\n      3. Convenience init must ultimately call a designated init\r\n    * Simple way to remember:\r\n      * Designated init delegates up\r\n      * Convenience init delegates across\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/A662D106-1ACE-41E3-A32B-BA295C62B660.png)\r\n    * More complex example, designated inits act as a funnel:\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/8E788FC3-DCC0-437D-93F0-8D16CB1D2AC5.png)\r\n  * Two-Phase Initialization\r\n    * Two phases:\r\n      * Phase 1\r\n        * Each stored property is assigned an initial value\r\n      * Phase 2\r\n        * Each class is given the opportunity to customise its stored properties further before new instance is ready to use\r\n    * Two-phase init prevents property values being accessed before they are initialised, and prevent property values being set to a different value by another initialiser unexpectedly\r\n      * Similar to Obj-C, the main difference during Phase 1, Objc-C assigns zero or null values (0 or nil) to every property.\r\n      * Swift's init is more flexible, lets you set custom initial values, and can cope with types for which 0 or nil is not a valid default value\r\n    * Compiler performs four helpful safety checks:\r\n      * Safety Check 1\r\n        * A designated init must sensor that all the properties introduced by its class are initialised before it delegates up to a superclass init\r\n      * Safety Check 2\r\n        * A designated init must delegate up to a superclass init before assigning a value to an inherited property\r\n        * If it does't the new value the designated init assigns will be overwritten by the superclass\r\n      * Safety Check 3\r\n        * A convenience init must delegate to another init  before assigning a value to any property.\r\n        * If it doesn't the new value the convenience init assigns will be overwritten by its own class designated init\r\n      * Safety Check 4\r\n        * An init cannot call any instances methods, read the values of any instance properties, or refer to self as a value until the first phase of init is complete\r\n  * Phase 1\r\n    * A designated or convenience init is called\r\n    * Memory for a new instance of that class is allocated, the memory is not initialised yet\r\n    * A designated init for that class confirms that all stored properties introduced by that class have a value, the memory for those stored properties is now initialised\r\n    * The designated initialiser hands off to a superclass init to perform the same task for its own stored properties\r\n    * This continues up the class inheritance chain until top chain is reached\r\n    * The final class in the chain has ensured that all its stored properties have a value, instance's memory is considered fully initialised, phase 1 is complete\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/35412844-C46F-4742-B664-2BBA53595A36.png)\r\n  * Phase 2\r\n    * Working back down from the top of the chain, each designated initialiser in the chain has the option customise the instance further.\r\n      * Inits are now able to access self and can modify its properties, call its instance methods and so on\r\n    * Finally any convenience inits in the chain have the option to customise the instance to work with self.\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/2AFC7723-9E2A-4E1C-9A2D-748DC9696C45.png)\r\n  * Init Inheritance and Overriding\r\n    * **Unlike subclass in Obj-C, Swift subclass do not inherit their superclass init by default**\r\n    * Note\r\n      * Superclass inits are inherited in certain circumstances, only when it is safe and appropriate, more info in the next section\r\n    * If you want to the same init from the superclass, override the init with \"override modifier.\r\n    * If you write subclass init that matches superclass convenience init, superclass convenience init can never be called directly by your subclass, as described in Init Chaining\r\n      * **Therefore your subclass is not providing an override of the superclass init**\r\n      * Thus you do not write the override modifier when providing a matching implementation of a superclass convenience initialiser\r\n\r\n      ```swift\r\n      class Vehicle {\r\n\r\n        var numberOfWheels = 0\r\n        var description: String {\r\n            return \"\\(numberOfWheels) wheel(s)\"\r\n        }\r\n      }\r\n\r\n      class Bicycle: Vehicle {\r\n        override init() {\r\n            super.init()\r\n            numberOfWheels = 2\r\n        }\r\n      }\r\n      ```\r\n\r\n    * Note\r\n      * Subclasses are only allowed to modify variable superclass properties during initialisation. Subclasses cannot modify inherited constant properties.\r\n  * Automatic Init Inheritance\r\n    * Subclass do not inherit their superclass inits by default, unless certain conditions are met\r\n    * In practice, you do not need to write init overrides in many common scenarios, and can inherit superclass inits with minimal efforts\r\n    * Assuming you provide default values for any new properties you introduce in a subclass, the following two rules apply:\r\n      * Rule 1\r\n        * If your subclass **does not define any designated inits**, it automatically **inherits all its superclass initializers**\r\n      * Rule 2\r\n        * If your subclass provides an implementation of **all its superclass designated initialisers** - either by inheriting them as per rule 1 or by custom implementation, it automatically inherits all of the superclass convenience inits\r\n    * Note\r\n      * A subclass can implement a superclass designated init as subclass convenience init as part of satisfying rule 2\r\n  * Designated and Convenience Inits in Action\r\n\r\n    ```swift\r\n    class Food {\r\n        var name: String\r\n        init(name: String) {\r\n            self.name = name\r\n        }\r\n        convenience init() {\r\n            self.init(name: \"[Unnamed]\")\r\n        }\r\n    }\r\n    ```\r\n\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/EAC71E1D-8420-452D-95EA-7E9073F9983A.png)\r\n\r\n    ```swift\r\n    class RecipeIngredient: Food {\r\n        var quantity: Int\r\n        init(name: String, quantity: Int) {\r\n            self.quantity = quantity\r\n            super.init(name: name)\r\n        }\r\n        override convenience init(name: String) {\r\n            self.init(name: name, quantity: 1)\r\n        }\r\n    }\r\n\r\n    let oneMysteryItem = RecipeIngredient()\r\n    let oneBacon = RecipeIngredient(name: \"Bacon\")\r\n    let sixEggs = RecipeIngredient(name: \"Eggs\", quantity: 6)\r\n    ```\r\n\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/DB577B70-0B89-42A4-AD52-8C0D314A2040.png)\r\n\r\n\r\n    ```swift\r\n    class ShoppingListItem: RecipeIngredient {\r\n        var purchased = false\r\n        var description: String {\r\n            var output = \"\\(quantity) x \\(name)\"\r\n            output += purchased ? \" ✔\" : \" ✘\"\r\n            return output\r\n        }\r\n    }\r\n    var breakfastList = [\r\n\r\n        ShoppingListItem(),\r\n\r\n        ShoppingListItem(name: \"Bacon\"),\r\n\r\n        ShoppingListItem(name: \"Eggs\", quantity: 6),\r\n\r\n    ]\r\n    ```\r\n\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/83B2D621-68B2-4016-88F3-2EAB2DC2E3B0.png)\r\n  * Required Inits\r\n    * To indicate every subclass  must implement that initialiser:\r\n\r\n      ```swift\r\n      class SomeClass {\r\n        required init() {\r\n          // initializer implementation goes here\r\n        }\r\n      }\r\n      ```\r\n\r\n    * You do not write the override modifier when overriding:\r\n\r\n\r\n      ```swift\r\n      class SomeSubclass: SomeClass {\r\n        required init() {\r\n          // subclass implementation of the required initializer goes here\r\n        }\r\n      }\r\n      ```\r\n\r\n    * You do not have to provide an explicit implementation if the init can be inherited.\r\n\r\n### Setting a Default Property Value with a Closure or Function\r\n\r\n\r\n```swift\r\nclass SomeClass {\r\n    let someProperty: SomeType = {\r\n        // create a default value for someProperty inside this closure\r\n        // someValue must be of the same type as SomeType\r\n        return someValue\r\n        }()\r\n}\r\n```\r\n\r\n  * Note\r\n    * If you use closure to init a property, remember the rest of the instance has not been initialised yet\r\n    * You cannot access any other properties, and you cannot use \"self\"\r\n\r\n      ```swift\r\n      struct Checkerboard {\r\n          let boardColors: [Bool] = {\r\n              var temporaryBoard = [Bool]()\r\n              var isBlack = false\r\n              for i in 1...10 {\r\n                  for j in 1...10 {\r\n                      temporaryBoard.append(isBlack)\r\n                      isBlack = !isBlack\r\n                  }\r\n                  isBlack = !isBlack\r\n              }\r\n              return temporaryBoard\r\n              }()\r\n          func squareIsBlackAtRow(row: Int, column: Int) -> Bool {\r\n              return boardColors[(row * 10) + column]\r\n          }\r\n      }\r\n      ```\r\n\r\n\r\n## Deinitialization\r\n\r\n### Overview\r\n\r\n  * Called immediately before a class instance is deallocated\r\n  * deinit keyword, only for class types\r\n\r\n### How Deinitialization works\r\n\r\n  * Swift uses ARC to manage memory for the instance, typically you won't need to perform manual cleanup\r\n  * When you are working with your own resources, you probably would, ex.g. create a custom class to open a file/write some data to it, you need to close the file before the class instance is deallocated\r\n  * You are not allowed to call a reinit yourself\r\n  * Superclass deinits are inherited by their subclasses, and called automatically at the end of a subclass deinit. Always called even if subclass does not implement a reinit.\r\n\r\n### Deinitializers in Action\r\n\r\n```swift\r\nstruct Bank {\r\n    static var coinsInBank = 10_000\r\n\r\n    static func vendCoins(var numberOfCoinsToVend: Int) -> Int {\r\n        numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)\r\n        coinsInBank -= numberOfCoinsToVend\r\n        return numberOfCoinsToVend\r\n\r\n    }\r\n\r\n    static func receiveCoins(coins: Int) {\r\n        coinsInBank += coins\r\n    }\r\n\r\n}\r\n\r\nclass Player {\r\n    var coinsInPurse: Int\r\n\r\n    init(coins: Int) {\r\n        coinsInPurse = Bank.vendCoins(coins)\r\n    }\r\n\r\n    func winCoins(coins: Int) {\r\n        coinsInPurse += Bank.vendCoins(coins)\r\n    }\r\n\r\n    deinit {\r\n        Bank.receiveCoins(coinsInPurse)\r\n    }\r\n}\r\n\r\nvar playerOne: Player? = Player(coins: 100)\r\n\r\nprintln(\"A new player has joined the game with \\(playerOne!.coinsInPurse) coins\")\r\n// prints \"A new player has joined the game with 100 coins\"\r\n\r\nprintln(\"There are now \\(Bank.coinsInBank) coins left in the bank\")\r\n// prints \"There are now 9900 coins left in the bank\r\n\r\nplayerOne!.winCoins(2_000)\r\n\r\nprintln(\"PlayerOne won 2000 coins & now has \\(playerOne!.coinsInPurse) coins\")\r\n// prints \"PlayerOne won 2000 coins & now has 2100 coins\"\r\n\r\nprintln(\"The bank now only has \\(Bank.coinsInBank) coins left\")\r\n// prints \"The bank now only has 7900 coins left\r\n\r\nplayerOne = nil\r\n\r\nprintln(\"PlayerOne has left the game\")\r\n// prints \"PlayerOne has left the game\"\r\n\r\nprintln(\"The bank now has \\(Bank.coinsInBank) coins\")\r\n// prints \"The bank now has 10000 coins\r\n```\r\n\r\n\r\n## Automatic Reference Counting\r\n\r\n### Overview\r\n\r\n  * To track and manage your app's memory usage\r\n  * Memory management just works, in a few cases ARC requires more info about the relationship between parts of your code.\r\n  * Reference counting only applies to classes, Structures and Enumerations are value types\r\n\r\n### How ARC Works\r\n\r\n  * To make sure that instances don't disappear when they are still needed, when you assign a class instance to a property, constant or variable, it makes a strong reference. It does not allow it to be deallocated, as long as strong reference remains.\r\n\r\n### ARC In Action\r\n\r\n```swift\r\nclass Person {\r\n    let name: String\r\n    init(name: String) {\r\n        [self.name][2] = name\r\n        println(\"\\(name) is being initialized\")\r\n    }\r\n    deinit {\r\n        println(\"\\(name) is being deinitialized\")\r\n    }\r\n}\r\nvar reference1: Person?\r\nvar reference2: Person?\r\nvar reference3: Person?\r\n\r\nreference1 = Person(name: \"John Appleseed\")\r\n// prints \"John Appleseed is being initialised\"\r\n\r\nreference2 = reference1\r\nreference3 = reference1\r\nreference1 = nil\r\nreference2 = nil\r\nreference3 = nil\r\n// prints \"John Appleseed is being deinitialized\r\n```\r\n\r\n### Strong Reference Cycles Between Class Instances\r\n\r\n  * Two class instances holding a strong reference to each other\r\n  * You resolve strong reference cycles by defining some of the relationships between classes as weak or unowned references instead of as strong references.\r\n\r\n\r\n    ```swift\r\n    class Person {\r\n        let name: String\r\n        init(name: String) { [self.name][2] = name }\r\n        var apartment: Apartment?\r\n        deinit { println(\"\\(name) is being deinitialized\") }\r\n    }\r\n\r\n    class Apartment {\r\n        let number: Int\r\n        init(number: Int) { self.number = number }\r\n        var tenant: Person?\r\n        deinit { println(\"Apartment #\\(number) is being deinitialized\") }\r\n    }\r\n    var john: Person?\r\n    var number73: Apartment?\r\n    john = Person(name: \"John Appleseed\")\r\n    number73 = Apartment(number: 73)\r\n    ```\r\n\r\n\r\n  * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/598B95C0-D50B-4ECD-9CD5-126685263ACA.png)\r\n\r\n\r\n    ```swift\r\n      john!.apartment = number73\r\n      number73!.tenant = john\r\n    ```\r\n\r\n  * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/3DCF8042-9FC0-4B33-A406-E4DFEE2D7291.png)\r\n\r\n    ```swift\r\n      john = nil\r\n      number73 = nil\r\n      // reference count does not frop to 0\r\n\r\n    ```\r\n\r\n  * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/EC4DBFFE-F082-4689-B812-9872A63A5417.png)\r\n\r\n### Resolving Strong Reference Cycles Between Class Instances\r\n\r\n  * Two ways:\r\n    * weak references\r\n      * Use weak reference whenever it is valid for the reference to become nil at some point during its lifetime\r\n    * unowned references\r\n      * When you know that the reference will never be nil once it has been set during initialization\r\n  * Weak References\r\n    * Enable one instance in the reference cycle to refer to the other instance without keeping a strong hold on it\r\n    * Use keyword \"weak\"\r\n    * Optional, constant not allowed\r\n    * ARC will set to nil when it is deallocated\r\n\r\n      ```swift\r\n      class Person {\r\n          let name: String\r\n          init(name: String) { [self.name][2] = name }\r\n          var apartment: Apartment?\r\n          deinit { println(\"\\(name) is being deinitialized\") }\r\n      }\r\n\r\n      class Apartment {\r\n          let number: Int\r\n          init(number: Int) { self.number = number }\r\n          weak var tenant: Person?\r\n          deinit { println(\"Apartment #\\(number) is being deinitialized\") }\r\n      }\r\n      ```\r\n\r\n      * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/EC725EFA-13D4-411A-8236-D9A53047D7EE.png)\r\n  * Unowned References\r\n    * Like weak reference, but it is assumed to always have a value\r\n    * Non-optional type\r\n    * Use \"unowned\" keyword\r\n    * ARC cannot set the reference to nil when it is deallocated\r\n    * Note\r\n      * If you try to access an unowned reference after the instance that it references is deallocated, will trigger a runtime error\r\n      * Use unowned references only when you are sure that the reference refers to an instance\r\n\r\n        ```swift\r\n        class Customer {\r\n\r\n          let name: String\r\n          var card: CreditCard?\r\n          init(name: String) {\r\n              [self.name][2] = name\r\n          }\r\n          deinit { println(\"\\(name) is being deinitialized\") }\r\n        }\r\n\r\n        class CreditCard {\r\n          let number: UInt64\r\n          unowned let customer: Customer\r\n          init(number: UInt64, customer: Customer) {\r\n              self.number = number\r\n              self.customer = customer\r\n          }\r\n          deinit { println(\"Card #\\(number) is being deinitialized\") }\r\n        }\r\n        ```\r\n\r\n    * Note\r\n      * The number property of the CreditCard class is defined with a type of UInt64 rather than Int, to ensure that the number property's capacity is large enough to store a 16-digit card number on both 32-bit and 64-bit systems.\r\n\r\n        ```swift\r\n        var john: Customer?\r\n        john = Customer(name: \"John Appleseed\")\r\n        john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)\r\n        ```\r\n      * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/6E29FF73-6FD5-44AC-BFF2-A44366DAD7A0.png)\r\n\r\n        ```swift\r\n        john = nil\r\n        // prints \"John Appleseed is being deinitialized\"\r\n        // prints \"Card #1234567890123456 is being reinitialised\"\r\n        ```\r\n\r\n      * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/64747DE2-441C-43EF-99E2-12B37CEA1E8D.png)\r\n  * **Unowned References and Implicitly Unwrapped Optional Properties**\r\n    * Third scenario which both properties should have a value\r\n    * Combine unowned property on one class with an implicit unwrapped optional property on the other class\r\n    * Enables both properties to be accessed directly without optional unwrapping once init is complete, while avoiding reference cycle\r\n\r\n      ```swift\r\n      class Country {\r\n\r\n        let name: String\r\n        let capitalCity: City!\r\n        init(name: String, capitalName: String) {\r\n            [self.name][2] = name\r\n            self.capitalCity = City(name: capitalName, country: self)\r\n        }\r\n      }\r\n\r\n      class City {\r\n        let name: String\r\n        unowned let country: Country\r\n        init(name: String, country: Country) {\r\n            [self.name][2] = name\r\n            self.country = country\r\n        }\r\n      }\r\n\r\n      var country = Country(name: \"Canada\", capitalName: \"Ottawa\")\r\n      println(\"\\(country.name)'s capital city is called \\(country.[capitalCity.name][3])\")\r\n      // prints \"Canada's capital city is called Ottawa\"\r\n      ```\r\n\r\n### Strong Reference Cycles for Closures\r\n\r\n  * Can occur if you assign a closure to a property of a class instance, and the body of that closure captures that instance, such as\r\n    * self.someProperty or\r\n    * self.someMethod()\r\n    * Captures self creating a strong reference cycle\r\n  * Closure are reference types, when you assign to a property, you are assigning a reference to that closure\r\n    * Class instance and a closure keeping each other alive\r\n  * Solution to use a \"closure capture list\"\r\n\r\n    ```swift\r\n    class HTMLElement {\r\n        let name: String\r\n        let text: String?\r\n\r\n        lazy var asHTML: () -> String = {\r\n            if let text = self.text {\r\n                return \"<\\(self.name)>\\(text)</\\(self.name)>\"\r\n            } else {\r\n                return \"<\\(self.name) />\"\r\n            }\r\n        }\r\n\r\n        init(name: String, text: String? = nil) {\r\n            [self.name][2] = name\r\n            self.text = text\r\n        }\r\n\r\n        deinit {\r\n            println(\"\\(name) is being deinitialized\")\r\n        }\r\n\r\n    }\r\n    var paragraph: HTMLElement? = HTMLElement(name: \"p\", text: \"hello, world\")\r\n    println(paragraph!.asHTML())\r\n    // prints \"<p>hello, world</p>\r\n    ```\r\n\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/92D56D5E-0877-48C0-8873-816A21C3CCCC.png)\r\n\r\n### Resolving Strong Reference Cycles for Closures\r\n\r\n  * Define a capture list as part of the closure's definition\r\n  * Capture list defines the rules to use when capturing one or more reference types within the closure's body\r\n  * You can declare captured reference to be a weak or unknown reference\r\n  * Note\r\n    * Write self.someProperty or self.someMethod, instead of removing the self to help you remember that it's possible to capture self by accident\r\n  * Defining Capture List\r\n\r\n    ```swift\r\n    lazy var someClosure: (Int, String) -> String = {\r\n        [unowned self] (index: Int, stringToProcess: String) -> String in\r\n        // closure body goes here\r\n    }\r\n    ```\r\n      * Or\r\n\r\n      ```swift\r\n      lazy var someClosure: () -> String = {\r\n        [unowned self] in\r\n        // closure body goes here\r\n      }\r\n      ```\r\n\r\n  * Weak and Unknowned References\r\n    * If captured reference will never become nil, it should be captured as an unowned reference, rather than a weak reference\r\n\r\n## Optional Chaining\r\n\r\n### Overview\r\n\r\n  * Process of querying and calling properties, methods, and subscripts on an optional that might currently be nil\r\n  * If the called entity is nil, it will return nil if not the value\r\n  * Multiple queries can be chained together, and fail gracefully if any of the link chain is nil\r\n  * Note\r\n    * Optional chaining in Swift similar to messaging nil in Obj-C, but that works for any type, and that can be checked for success or failure.\r\n\r\n### Optional Chaining as an Alternative to Forced Unwrapping\r\n\r\n  * Place a question mark (?) after the optional value to chain\r\n\r\n    ```swift\r\n    class Person {\r\n        var residence: Residence?\r\n    }\r\n\r\n    class Residence {\r\n        var numberOfRooms = 1\r\n    }\r\n\r\n    let john = Person()\r\n    let roomCount = john.residence!.numberOfRooms // this trigger a runtime error\r\n    ```\r\n\r\n  * Use optional chaining:\r\n\r\n    ```swift\r\n    if let roomCount = john.residence?.numberOfRooms {\r\n        println(\"John's residence has \\(roomCount) room(s).\")\r\n    } else {\r\n        println(\"Unable to retrieve the number of rooms.\")\r\n    }\r\n    ```\r\n\r\n### Defining Model Classes for Optional Chaining\r\n\r\n  * Optional chaining can be more than on level\r\n  * Model classes\r\n\r\n    ```swift\r\n    class Person {\r\n        var residence: Residence?\r\n    }\r\n\r\n    class Residence {\r\n        var rooms = [Room]()\r\n        var numberOfRooms: Int {\r\n            return rooms.count\r\n        }\r\n        subscript(i: Int) -> Room {\r\n            get {\r\n                return rooms[i]\r\n            }\r\n            set {\r\n                rooms[i] = newValue\r\n            }\r\n        }\r\n        func printNumberOfRooms() {\r\n            println(\"The number of rooms is \\(numberOfRooms)\")\r\n        }\r\n        var address: Address?\r\n    }\r\n\r\n    class Room {\r\n        let name: String\r\n        init(name: String) { [self.name][2] = name }\r\n    }\r\n\r\n    class Address {\r\n        var buildingName: String?\r\n        var buildingNumber: String?\r\n        var street: String?\r\n        func buildingIdentifier() -> String? {\r\n            if buildingName != nil {\r\n                return buildingName\r\n            } else if buildingNumber != nil {\r\n                return buildingNumber\r\n            } else {\r\n                return nil\r\n            }\r\n        }\r\n    }\r\n    ```\r\n\r\n### Accessing Properties Through Optional Chaining\r\n\r\n  * Use optional chaining to access property on optional value or to check if property access is successful\r\n\r\n    ```swift\r\n    let john = Person()\r\n    if let roomCount = john.residence?.numberOfRooms {\r\n        println(\"John's residence has \\(roomCount) room(s).\")\r\n    } else {\r\n        println(\"Unable to retrieve the number of rooms.\")\r\n    }\r\n    ```\r\n\r\n### Calling Methods Through Optional Chaining\r\n\r\n  * Use optional chaining to call a method on an optional value or to check whether a method call is successful, even if the method does not define a return value\r\n\r\n    ```swift\r\n    * Residence#printNumberOfRooms\r\n    func printNumberOfRooms() {\r\n      println(\"The number of rooms is \\(numberOfRooms)\")\r\n    }\r\n    ```\r\n\r\n  * Method has no return tip, bbut have an implicit value of Void\r\n    * Means they return a value of () or an empty tubule.\r\n  * If you call this on an optional value with optional chaining, the return type will be Void/ not Void, because the return values are always of an optional type when called with  optional chaining\r\n\r\n    ```swift\r\n    if john.residence?.printNumberOfRooms() != nil {\r\n      println(\"It was possible to print the number of rooms.\")\r\n    } else {\r\n      println(\"It was not possible to print the number of rooms.\")\r\n    }\r\n    // prints \"It was not possible to print the number of rooms.\r\n    ```\r\n\r\n### Accessing SubscriptsThrough Optional Chaining\r\n\r\n  * Overview\r\n    * To retrieve and set a value of a subscript on an optional value, and to check if the subscript call is successful\r\n    * Note\r\n      * Place the question mark before the subscript's braces, not after\r\n\r\n      ```swift\r\n      if let firstRoomName = john.residence?[0].name \" { ... }\r\n      ```\r\n\r\n  * Accessing Subscripts of Optional Type\r\n    * If a subscript returns a value of optional type, such as the key subscript of Swift's Dictionary type, place  question mark after the subscript's closing bracket to chain on its optional return value.\r\n\r\n      ```swift\r\n      var testScores = [\"Dave\": [86, 82, 84], \"Bev\": [79, 94, 81]]\r\n      testScores[\"Dave\"]?[0] = 91\r\n      testScores[\"Bev\"]?[0]++\r\n      testScores[\"Brian\"]?[0] = 72\r\n\r\n      // the \"Dave\" array is now [91, 82, 84] and the \"Bev\" array is now [80, 94, 81]\r\n      ```\r\n\r\n### Linking Multiple Levels of Chaining\r\n\r\n  * You can link multiple levels of optional chaining\r\n    * If the type you are trying to retrieve is not optional, it will become optional because of optional chaining\r\n    * If the type you are trying to retrieve is already optional, it will not become more optional because of the chaining\r\n    * Thus if you retrieve an Int through optional chaining, and Int? is always returned\r\n\r\n\r\n      ```swift\r\n      if let johnsStreet = john.residence?.address?.street {\r\n          println(\"John's street name is \\(johnsStreet).\")\r\n      } else {\r\n          println(\"Unable to retrieve the address.\")\r\n      }\r\n      // prints \"Unable to retrieve the address.\r\n      let johnsAddress = Address()\r\n      johnsAddress.buildingName = \"The Larches\"\r\n      johnsAddress.street = \"Laurel Street\"\r\n      john.residence!.address = johnsAddress\r\n\r\n      if let johnsStreet = john.residence?.address?.street {\r\n          println(\"John's street name is \\(johnsStreet).\")\r\n      } else {\r\n          println(\"Unable to retrieve the address.\")\r\n      }\r\n\r\n      // prints \"John's street name is Laurel Street.\r\n      ```\r\n\r\n### Chaining on Methods with Optional Return Values\r\n\r\n  * Use optional chaining to call a method that returns a value of optional type, and to chain the method's return value if needed\r\n\r\n\r\n    ```swift\r\n    if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {\r\n        println(\"John's building identifier is \\(buildingIdentifier).\")\r\n    }\r\n    // prints \"John's building identifier is The Larches.\"\r\n    if let beginsWithThe =\r\n        john.residence?.address?.buildingIdentifier()?.hasPrefix(\"The\") {\r\n            if beginsWithThe {\r\n                println(\"John's building identifier begins with \\\"The\\\".\")\r\n            } else {\r\n                println(\"John's building identifier does not begin with \\\"The\\\".\")\r\n            }\r\n    }\r\n    // prints \"John's building identifier begins with \"The\".\"\r\n\r\n    ```\r\n\r\n## Type Casting\r\n\r\n### Overview\r\n\r\n  * A way to check the type of an instance or\r\n  * To treat that instance as if it is a different superclass/subclass from somewhere else in its own hierarchy\r\n  * Implemented with \"**is**\" and \"**as**\" operators.\r\n    * To check the type of a value or cast a value to a different type\r\n  * Also used to check whether a type conforms to a protocol\r\n\r\n### Defining a Class Hierarchy for Type Casting\r\n\r\n```swift\r\nclass MediaItem {\r\n    var name: String\r\n    init(name: String) {\r\n        [self.name][2] = name\r\n    }\r\n}\r\nclass Movie: MediaItem {\r\n    var director: String\r\n    init(name: String, director: String) {\r\n        self.director = director\r\n        super.init(name: name)\r\n    }\r\n}\r\n\r\nclass Song: MediaItem {\r\n    var artist: String\r\n    init(name: String, artist: String) {\r\n        self.artist = artist\r\n        super.init(name: name)\r\n    }\r\n}\r\nlet library = [\r\n    Movie(name: \"Casablanca\", director: \"Michael Curtiz\"),\r\n    Song(name: \"Blue Suede Shoes\", artist: \"Elvis Presley\"),\r\n    Movie(name: \"Citizen Kane\", director: \"Orson Welles\"),\r\n    Song(name: \"The One And Only\", artist: \"Chesney Hawkes\"),\r\n    Song(name: \"Never Gonna Give You Up\", artist: \"Rick Astley\")\r\n]\r\n```\r\n\r\n### Checking Type\r\n\r\n  * Use type check operator (is) to check whether an instance is a certain subclass type\r\n\r\n    ```swift\r\n    var movieCount = 0\r\n    var songCount = 0\r\n\r\n    for item in library {\r\n        if item is Movie {\r\n            ++movieCount\r\n        } else if item is Song {\r\n            ++songCount\r\n        }\r\n    }\r\n    ```\r\n\r\n### Downcasting\r\n\r\n  * Downcast a subclass type with type operator (as)\r\n    * Downcasting can fail, there are two types:\r\n      * as? returns optional value\r\n      * as, attempts to downcast and force-unwraps result as a single compound action\r\n\r\n    ```swift\r\n    for item in library {\r\n        if let movie = item as? Movie {\r\n            println(\"Movie: '\\(movie.name)', dir. \\(movie.director)\")\r\n        } else if let song = item as? Song {\r\n            println(\"Song: '\\(song.name)', by \\(song.artist)\")\r\n        }\r\n    }\r\n    ```\r\n\r\n### Type Casting for Any and AnyObject\r\n\r\n  * Swift provide two special type aliases for working with non-specific types\r\n    * AnyObject: an instance of any class type\r\n    * Any: an instance of any type at all apart from function types\r\n  * Note\r\n    * Use Any and AnyObject when you explicitly need the behaviour and capabilities.\r\n    * It is always better to be specific with the types you work with.\r\n  * AnyObject\r\n    * When you work with CocoaAPI, it is common to receive an array of [AnyObject]\r\n    * Because Obj-C does not have an Array of explicitly typed objects\r\n    * Use as to downcast each item in the array\r\n\r\n      ```swift\r\n      let someObjects: [AnyObject] = [\r\n        Movie(name: \"2001: A Space Odyssey\", director: \"Stanley Kubrick\"),\r\n        Movie(name: \"Moon\", director: \"Duncan Jones\"),\r\n        Movie(name: \"Alien\", director: \"Ridley Scott\")\r\n      ]\r\n\r\n      for object in someObjects {\r\n\r\n      let movie = object as Movie\r\n      println(\"Movie: '\\(movie.name)', dir. \\(movie.director)\")\r\n      }\r\n      ```\r\n\r\n      * Shorter version\r\n      ```swift\r\n        for movie in someObjects as [Movie] {\r\n          println(\"Movie: '\\(movie.name)', dir. \\(movie.director)\")\r\n        }\r\n      ```\r\n  * Any\r\n    * To work with a mix of different types including non-class types\r\n\r\n      ```swift\r\n      var things = [Any]()\r\n\r\n      things.append(0)\r\n      things.append(0.0)\r\n      things.append(42)\r\n      things.append(3.14159)\r\n      things.append(\"hello\")\r\n      things.append((3.0, 5.0))\r\n      things.append(Movie(name: \"Ghostbusters\", director: \"Ivan Reitman\"))\r\n      ```\r\n    * Contains Int, Double, String, (Double, Double), Movie\r\n\r\n      ```swift\r\n      for thing in things {\r\n          switch thing {\r\n          case 0 as Int:\r\n              println(\"zero as an Int\")\r\n          case 0 as Double:\r\n              println(\"zero as a Double\")\r\n          case let someInt as Int:\r\n              println(\"an integer value of \\(someInt)\")\r\n          case let someDouble as Double where someDouble > 0:\r\n              println(\"a positive double value of \\(someDouble)\")\r\n          case is Double:\r\n              println(\"some other double value that I don't want to print\")\r\n          case let someString as String:\r\n              println(\"a string value of \\\"\\(someString)\\\"\")\r\n          case let (x, y) as (Double, Double):\r\n              println(\"an (x, y) point at \\(x), \\(y)\")\r\n          case let movie as Movie:\r\n              println(\"a movie called '\\(movie.name)', dir. \\(movie.director)\")\r\n          default:\r\n              println(\"something else\")\r\n          }\r\n      }\r\n      ```\r\n\r\n    * Note\r\n      * The case of a switch statement, use the forced version of type cast operator, as.\r\n\r\n## Nested Types\r\n\r\n### Overview\r\n\r\n  * Enums often created to support a specific class or structure's functionality\r\n  * It can be convenient to define utility classes and structures purely for use within the context of a more complex type\r\n  * Define nested types:\r\n    * Nest supporting enumerations, classes, structures within the definition of the type they support\r\n\r\n### Nested Types in Action\r\n\r\n```swift\r\nstruct BlackjackCard {\r\n    // nested Suit enumeration\r\n    enum Suit: Character {\r\n        case Spades = \"♠\", Hearts = \"♡\", Diamonds = \"♢\", Clubs = \"♣\"\r\n    }\r\n\r\n    // nested Rank enumeration\r\n    enum Rank: Int {\r\n        case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten\r\n        case Jack, Queen, King, Ace\r\n\r\n        struct Values {\r\n            let first: Int, second: Int?\r\n        }\r\n\r\n        var values: Values {\r\n            switch self {\r\n              case .Ace:\r\n                  return Values(first: 1, second: 11)\r\n              case .Jack, .Queen, .King:\r\n                  return Values(first: 10, second: nil)\r\n              default:\r\n                  return Values(first: self.toRaw(), second: nil)\r\n            }\r\n        }\r\n    }\r\n\r\n    // BlackjackCard properties and methods\r\n    let rank: Rank, suit: Suit\r\n    var description: String {\r\n        var output = \"suit is \\(suit.toRaw()),\"\r\n        output += \" value is \\(rank.values.first)\"\r\n\r\n        if let second = rank.values.second {\r\n            output += \" or \\(second)\"\r\n        }\r\n\r\n        return output\r\n    }\r\n}\r\n\r\nlet theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)\r\nprintln(\"theAceOfSpades: \\(theAceOfSpades.description)\")\r\n// prints \"theAceOfSpades: suit is ♠, value is 1 or 11\r\n```\r\n\r\n### Referring to Nested Types\r\n\r\n```swift\r\n  let heartsSymbol = BlackjackCard.Suit.Hearts.toRaw()\r\n  // heartsSymbol is \"♡\"\r\n```\r\n\r\n## Extensions\r\n\r\n### Overview\r\n\r\n  * Add new functionality to existing class, structure or enumeration type\r\n  * Extend types for which you do not have access to the original source code (retroactive modelling)\r\n  * Extension similar to categories in Obj-C, except it does not have names.\r\n  * Extensions in Swift can:\r\n    * Add computed properties and computed static properties\r\n    * Define instance and type methods\r\n    * Provide new inits\r\n    * Define subscripts\r\n    * Define and use new nested types\r\n    * Make an existing type conform to a protocol\r\n  * Note\r\n    * Extensions can add new functionality, but can not override existing functionality\r\n\r\n### Extension Syntax\r\n\r\n```swift\r\nextension SomeType {\r\n  // new functionality to add to SomeType goes here\r\n}\r\n\r\n// Extend with protocols\r\nextension SomeType: SomeProtocol, AnotherProtocol {\r\n  // implementation of protocol requirements goes here\r\n}\r\n```\r\n  * If you define an extension, the new functionality will be available to all instances, even if they were created before the extension was defined.\r\n\r\n### Computed Properties\r\n\r\n  * Can add computed properties and computed type properties to existing types:\r\n\r\n    ```swift\r\n    extension Double {\r\n        var km: Double { return self * 1_000.0 }\r\n        var m: Double { return self }\r\n        var cm: Double { return self / 100.0 }\r\n        var mm: Double { return self / 1_000.0 }\r\n        var ft: Double { return self / 3.28084 }\r\n    }\r\n\r\n    let oneInch = [25.4.mm][4]\r\n    println(\"One inch is \\(oneInch) meters\")      // prints \"One inch is 0.0254 meters\"\r\n\r\n    let threeFeet = 3.ft\r\n    println(\"Three feet is \\(threeFeet) meters\")  // prints \"Three feet is 0.914399970739201 meters\r\n\r\n    let aMarathon = 42.km + 195.m\r\n    ```\r\n\r\n  * Extensions add new computed properties but they cannot add stored properties, add property observers to existing properties\r\n\r\n### Initializers\r\n\r\n  * Extensions can add new convenience initialisers to a class, but they cannot add new designated initialisers or deinitializers to a class\r\n  * Designated initialisers and deinitializer must always be provided by original class implementation\r\n\r\n    ```swift\r\n    struct Size {\r\n        var width = 0.0, height = 0.0\r\n    }\r\n\r\n    struct Point {\r\n        var x = 0.0, y = 0.0\r\n    }\r\n\r\n    struct Rect {\r\n        var origin = Point()\r\n        var size = Size()\r\n    }\r\n\r\n    let defaultRect = Rect()\r\n    let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0))\r\n\r\n    extension Rect {\r\n        init(center: Point, size: Size) {\r\n            let originX = center.x - (size.width / 2)\r\n            let originY = center.y - (size.height / 2)\r\n            self.init(origin: Point(x: originX, y: originY), size: size)\r\n        }\r\n    }\r\n\r\n    let centerRect = Rect(center: Point(x: 4.0, y: 4.0),\r\n        size: Size(width: 3.0, height: 3.0))\r\n    ```\r\n\r\n### Methods\r\n\r\n  * Add new instance methods and type methods to existing types\r\n\r\n    ```swift\r\n    extension Int {\r\n        func repetitions(task: () -> ()) {\r\n            for i in 0..<self {\r\n                task()\r\n            }\r\n        }\r\n    }\r\n\r\n    3.repetitions({\r\n        println(\"Hello!\")\r\n    })\r\n    ```\r\n\r\n  * Mutating Instance Methods\r\n    * Instance methods added with extension can also modify (mutate the instance itself\r\n\r\n      ```swift\r\n      extension Int {\r\n        mutating func square() {\r\n          self = self * self\r\n        }\r\n      }\r\n      ```\r\n\r\n### Subscripts\r\n\r\n\r\n```swift\r\nextension Int {\r\n    subscript(var digitIndex: Int) -> Int {\r\n        var decimalBase = 1\r\n        while digitIndex > 0 {\r\n            decimalBase *= 10\r\n            --digitIndex\r\n        }\r\n        return (self / decimalBase) % 10\r\n    }\r\n}\r\n746381295[0]  // returns 5\r\n746381295[1]  // returns 9\r\n746381295[2]  // returns 2\r\n746381295[8]  // returns 7\r\n746381295[9]  // returns 0, as if you had requested:\r\n0746381295[9]\r\n```\r\n\r\n### Nested Types\r\n\r\n```swift\r\nextension Int {\r\n    enum Kind {\r\n        case Negative, Zero, Positive\r\n    }\r\n\r\n    var kind: Kind {\r\n        switch self {\r\n        case 0:\r\n            return .Zero\r\n        case let x where x > 0:\r\n            return .Positive\r\n        default:\r\n            return .Negative\r\n        }\r\n    }\r\n}\r\n\r\nfunc printIntegerKinds(numbers: [Int]) {\r\n    for number in numbers {\r\n        switch number.kind {\r\n        case .Negative:\r\n            print(\"- \")\r\n        case .Zero:\r\n            print(\"0 \")\r\n        case .Positive:\r\n            print(\"+ \")\r\n        }\r\n    }\r\n    print(\"\\n\")\r\n}\r\n\r\nprintIntegerKinds([3, 19, -27, 0, -6, 0, 7])  // prints \"+ + - 0 - 0 +\"\r\n```\r\n\r\n## Protocols\r\n\r\n### Overiew\r\n\r\n  * Defines a blueprint of methods, properties, and other quirements to suit a particular task or piece of functionality.\r\n  * Does not provide an implementation, only describes what an implementation will look like\r\n  * Can be adopted by a class, structure or enumeration\r\n  * Any type that satisfies the requirements conform to that protocol\r\n\r\n### Protocol Syntax\r\n\r\n```swift\r\nprotocol SomeProtocol {\r\n  // protocol definition goes here\r\n}\r\n\r\nstruct SomeStructure: FirstProtocol, AnotherProtocol {\r\n  // structure definition goes here\r\n}\r\nclass SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {\r\n  // class definition goes here\r\n}\r\n```\r\n\r\n### Protocol Requirements\r\n\r\n  * Getter & setter requirements\r\n\r\n    ```swift\r\n    protocol SomeProtocol {\r\n      var mustBeSettable: Int { get set }\r\n      var doesNotNeedToBeSettable: Int { get }\r\n    }\r\n    ```\r\n\r\n  * Type property protocol, use \"static\" keyword for structure or enumeration\r\n\r\n    ```swift\r\n    protocol AnotherProtocol {\r\n      class var someTypeProperty: Int { get set }\r\n    }\r\n    ```\r\n\r\n  * Protocol with a single instance property requirements:\r\n\r\n    ```swift\r\n    protocol FullyNamed {\r\n        var fullName: String { get }\r\n    }\r\n    ```\r\n\r\n    * Simple structure conforms to FullyNamed protocol\r\n\r\n      ```swift\r\n      struct Person: FullyNamed {\r\n\r\n        var fullName: String\r\n      }\r\n      let john = Person(fullName: \"John Appleseed\")\r\n      // john.fullName is \"John Appleseed\"\r\n      ```\r\n\r\n    * Class conforms to the protocol:\r\n\r\n      ```swift\r\n      class Starship: FullyNamed {\r\n\r\n        var prefix: String?\r\n        var name: String\r\n        init(name: String, prefix: String? = nil) {\r\n            [self.name][2] = name\r\n            self.prefix = prefix\r\n        }\r\n        var fullName: String {\r\n            return (prefix != nil ? prefix! + \" \" : \"\") + name\r\n        }\r\n      }\r\n      var ncc1701 = Starship(name: \"Enterprise\", prefix: \"USS\")\r\n      // ncc1701.fullName is \"USS Enterprise\"\r\n      ```\r\n\r\n### Method Requirements\r\n\r\n  * Protocol can require specific instance methods or type methods to be implemented\r\n  * Use the same syntax as normal methods, but are not allowed to specify default values for method params.\r\n\r\n    ```swift\r\n    protocol SomeProtocol {\r\n        class func someTypeMethod()\r\n    }\r\n    protocol RandomNumberGenerator {\r\n\r\n        func random() -> Double\r\n\r\n    }\r\n    ```\r\n\r\n### Mutating Method Requirements\r\n\r\n  * If you mark a protocol instance method requirements as mutating, you do not need to write he mutating keyword when writing an implementation of that method for a class\r\n  * Mutating only used by structures and enumerations\r\n\r\n    ```swift\r\n    protocol Togglable {\r\n        mutating func toggle()\r\n    }\r\n\r\n    enum OnOffSwitch: Togglable {\r\n        case Off, On\r\n        mutating func toggle() {\r\n            switch self {\r\n            case Off:\r\n                self = On\r\n            case On:\r\n                self = Off\r\n            }\r\n        }\r\n    }\r\n\r\n    var lightSwitch = OnOffSwitch.Off\r\n    lightSwitch.toggle()  // lightSwitch is now equal to .On\r\n    ```\r\n\r\n### Initializer Requirements\r\n\r\n  * Same way as normal inits, but without curly braces or an init body:\r\n\r\n    ```swift\r\n    protocol SomeProtocol {\r\n      init(someParameter: Int)\r\n    }\r\n    ```\r\n\r\n  * Class implementations of Protocol initialisers requirements\r\n    * You can implement a protocol initialiser requirement on a conforming class as either a designated initialiser requirement  or a convenience initializer.\r\n    * In both cases you must mark the initialiser implementation with the \"required\" modifier:\r\n\r\n      ```swift\r\n      class SomeClass: SomeProtocol {\r\n\r\n        required init(someParameter: Int) {\r\n          // initializer implementation goes here\r\n        }\r\n      }\r\n      ```\r\n\r\n    * Required modifier ensures that you provide explicit or inherited implementation of the initialiser requirement on all subclasses.\r\n    * Note\r\n      * You do not need to mark protocol init with required modifier on classes marked with the final modifier, because final classes can not be subclassed.\r\n  * Subclass implementation, note the override:\r\n\r\n    ```swift\r\n    protocol SomeProtocol {\r\n        init()\r\n    }\r\n\r\n    class SomeSuperClass {\r\n        init() {\r\n            // initializer implementation goes here\r\n        }\r\n    }\r\n\r\n    class SomeSubClass: SomeSuperClass, SomeProtocol {\r\n        // \"required\" from SomeProtocol conformance; \"override\" from SomeSuperClass\r\n        required override init() {\r\n            // initializer implementation goes here\r\n        }\r\n    }\r\n    ```\r\n\r\n### Protocols as Types\r\n\r\n  * Protocol you create will become a fully-fledged type for use in your code\r\n  * Thus, you can use protocol in many places, including:\r\n    * As a parameter type or return type in a function, method or init\r\n    * As a  type of a constant, variable or property\r\n    * As a type of items in an array, dictionary or other container\r\n\r\n    ```swift\r\n    class Dice {\r\n        let sides: Int\r\n        let generator: RandomNumberGenerator\r\n        init(sides: Int, generator: RandomNumberGenerator) {\r\n            self.sides = sides\r\n            self.generator = generator\r\n        }\r\n        func roll() -> Int {\r\n            return Int(generator.random() * Double(sides)) + 1\r\n        }\r\n    }\r\n\r\n    var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())\r\n\r\n    for _ in 1...5 {\r\n        println(\"Random dice roll is \\(d6.roll())\")\r\n    }\r\n    ```\r\n\r\n### Delegation\r\n\r\n  * A design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type\r\n  * Implemented by defining a protocol that encapsulates the delegated responsibilities\r\n\r\n  ```swift\r\n  protocol DiceGame {\r\n      var dice: Dice { get }\r\n      func play()\r\n  }\r\n\r\n  protocol DiceGameDelegate {\r\n      func gameDidStart(game: DiceGame)\r\n      func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)\r\n      func gameDidEnd(game: DiceGame)\r\n  }\r\n\r\n  class SnakesAndLadders: DiceGame {\r\n      let finalSquare = 25\r\n      let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())\r\n      var square = 0\r\n      var board: [Int]\r\n      init() {\r\n          board = [Int](count: finalSquare + 1, repeatedValue: 0)\r\n          board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02\r\n          board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08\r\n      }\r\n      var delegate: DiceGameDelegate?\r\n      func play() {\r\n          square = 0\r\n          delegate?.gameDidStart(self)\r\n          gameLoop: while square != finalSquare {\r\n              let diceRoll = dice.roll()\r\n              delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)\r\n              switch square + diceRoll {\r\n              case finalSquare:\r\n                  break gameLoop\r\n              case let newSquare where newSquare > finalSquare:\r\n                  continue gameLoop\r\n              default:\r\n                  square += diceRoll\r\n                  square += board[square]\r\n              }\r\n          }\r\n          delegate?.gameDidEnd(self)\r\n      }\r\n  }\r\n\r\n  class DiceGameTracker: DiceGameDelegate {\r\n      var numberOfTurns = 0\r\n      func gameDidStart(game: DiceGame) {\r\n          numberOfTurns = 0\r\n          if game is SnakesAndLadders {\r\n              println(\"Started a new game of Snakes and Ladders\")\r\n          }\r\n          println(\"The game is using a \\(game.dice.sides)-sided dice\")\r\n      }\r\n      func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {\r\n          ++numberOfTurns\r\n          println(\"Rolled a \\(diceRoll)\")\r\n      }\r\n      func gameDidEnd(game: DiceGame) {\r\n          println(\"The game lasted for \\(numberOfTurns) turns\")\r\n      }\r\n  }\r\n\r\n  let tracker = DiceGameTracker()\r\n  let game = SnakesAndLadders()\r\n  game.delegate = tracker\r\n  game.play()\r\n  ```\r\n\r\n### Adding Protocol Conformance with an Extension\r\n\r\n  * You can extend existing type to adopt and conform to a new protocol, even if you do not have access to the source code.\r\n  * Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol demand.\r\n\r\n    ```swift\r\n    protocol TextRepresentable {\r\n      func asText() -> String\r\n    }\r\n\r\n    extension Dice: TextRepresentable {\r\n      func asText() -> String {\r\n        return \"A \\(sides)-sided dice\"\r\n      }\r\n    }\r\n    ```\r\n\r\n  * Declaring Protocol Adoption with Extension\r\n    * If a type already conforms to a protocol, but has not adopted that protocol you can make it adopt the protocol with an empty extension:\r\n\r\n      ```swift\r\n      struct Hamster {\r\n        var name: String\r\n\r\n        func asText() -> String {\r\n          return \"A hamster named \\(name)\"\r\n        }\r\n      }\r\n\r\n      extension Hamster: TextRepresentable {}\r\n      let simonTheHamster = Hamster(name: \"Simon\")\r\n      let somethingTextRepresentable: TextRepresentable = simonTheHamster\"\r\n      ```\r\n\r\n    * Note\r\n      * Types do not automatically adopt a protocol  by just satisfying its requirements, they must explicitly declare their adoption of the protocol\r\n\r\n### Collections of Protocol Types\r\n\r\n  * Protocol can be used as the type to be stored in collection as as array/dictionary:\r\n\r\n    ```swift\r\n    let things: [TextRepresentable] = [game, d12, simonTheHamster]\r\n    for thing in things {\r\n        println(thing.asText())\r\n    }\r\n    ```\r\n\r\n### Protocol Inheritance\r\n\r\n  * Protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits:\r\n\r\n    ```swift\r\n    protocol InheritingProtocol: SomeProtocol, AnotherProtocol {\r\n        // protocol definition goes here\r\n    }\r\n\r\n    protocol PrettyTextRepresentable: TextRepresentable {\r\n        func asPrettyText() -> String\r\n    }\r\n    ```\r\n\r\n### Class-Only Protocol\r\n\r\n  * Limit protocol adoption to class types (and not structures or enumerations) by adding the class keyword to a protocol's inheritance list:\r\n\r\n    ```swift\r\n    protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol {\r\n      // class-only protocol definition goes here\r\n    }\r\n    ```\r\n\r\n  * Note\r\n    * Use a class-only protocol when the behaviour defined that protocol's requirements assumes or requires that a conforming type has reference semantics rather than value semantics.\r\n\r\n### Protocol Composition\r\n\r\n  * You can combine multiple protocols into a single protocol composition.\r\n    * protocol<SomeProtocol, AnotherProtocol>\r\n\r\n    ```swift\r\n    protocol Named {\r\n        var name: String { get }\r\n    }\r\n    protocol Aged {\r\n        var age: Int { get }\r\n    }\r\n    struct Person: Named, Aged {\r\n        var name: String\r\n        var age: Int\r\n    }\r\n    func wishHappyBirthday(celebrator: protocol<Named, Aged>) {\r\n        println(\"Happy birthday \\(celebrator.name) - you're \\(celebrator.age)!\")\r\n    }\r\n    let birthdayPerson = Person(name: \"Malcolm\", age: 21)\r\n    wishHappyBirthday(birthdayPerson)  // prints \"Happy birthday Malcolm - you're 21!\"\r\n    ```\r\n\r\n  * Note\r\n    * Protocol compositions do not define a new, permanent protocol type, rather they define a temporary local protocol that has the combined requirements of all protocols in the composition.\r\n\r\n### Checking for Protocol Conformance\r\n\r\n  * You can use is and as operators\r\n\r\n    ```swift\r\n    @objc protocol HasArea {\r\n      var area: Double { get }\r\n    }\r\n    ```\r\n\r\n  * Note\r\n    * You can check protocol conformance only if your protocol is marked with the @objc attribute\r\n    * It indicates that protocol should be exposed to Objective-C Code\r\n    * @objc protocols can be adopted only by classes, not by structures or enumerations\r\n\r\n\r\n    ```swift\r\n    class Circle: HasArea {\r\n        let pi = 3.1415927\r\n        var radius: Double\r\n        var area: Double { return pi * radius * radius }\r\n        init(radius: Double) { self.radius = radius }\r\n    }\r\n\r\n    class Country: HasArea {\r\n        var area: Double\r\n        init(area: Double) { self.area = area }\r\n    }\r\n\r\n    for object in objects {\r\n        if let objectWithArea = object as? HasArea {\r\n            println(\"Area is \\(objectWithArea.area)\")\r\n        } else {\r\n            println(\"Something that doesn't have an area\")\r\n        }\r\n    }\r\n    ```\r\n\r\n### Optional Protocol Requirements\r\n\r\n  * These requirements do not have to be implemented by types that conform to the protocol\r\n  * Prefixed by \"optional\"\r\n  * Optional protocol requirement can be called with optional chaining\r\n  * You can check implementation of an optional requirement by writing a question mark after the name of the requirement\r\n    * someOptionalMethod?(someArgument)\r\n  * Optional property/method requirements will return an optional value\r\n  * Note\r\n    * Optional protocol can only be specified if the protocol is marked with the @objc attribute\r\n    * Even if you are not interoperating with Obj-C you need to mark your protocols with @objc\r\n    * @objc can only be adopted by classes, not structures/enumerations\r\n\r\n    ```swift\r\n    @objc protocol CounterDataSource {\r\n        optional func incrementForCount(count: Int) -> Int\r\n        optional var fixedIncrement: Int { get }\r\n    }\r\n\r\n    @objc class Counter {\r\n        var count = 0\r\n        var dataSource: CounterDataSource?\r\n        func increment() {\r\n            if let amount = dataSource?.incrementForCount?(count) {\r\n                count += amount\r\n            } else if let amount = dataSource?.fixedIncrement? {\r\n                count += amount\r\n            }\r\n        }\r\n    }\r\n\r\n    class ThreeSource: CounterDataSource {\r\n        let fixedIncrement = 3\r\n    }\r\n\r\n    var counter = Counter()\r\n    counter.dataSource = ThreeSource()\r\n\r\n    for _ in 1...4 {\r\n        counter.increment()\r\n        println(counter.count)\r\n    }\r\n\r\n    class TowardsZeroSource: CounterDataSource {\r\n        func incrementForCount(count: Int) -> Int {\r\n            if count == 0 {\r\n                return 0\r\n            } else if count < 0 {\r\n                return 1\r\n            } else {\r\n                return -1\r\n            }\r\n        }\r\n    }\r\n\r\n    counter.count = -4\r\n    counter.dataSource = TowardsZeroSource()\r\n\r\n    for _ in 1...5 {\r\n        counter.increment()\r\n        println(counter.count)\r\n    }\r\n    // -3\r\n    // -2\r\n    // -1\r\n    // 0\r\n    // 0\r\n    ```\r\n\r\n## Generics\r\n\r\n### Overview\r\n\r\n  * Enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.\r\n  * Avoid duplication and expresses its intent in a clear, abstracted manner\r\n  * Most powerful feature of Swift, much of the Swift standard library is built with generic code.\r\n  * You have been using generics throughoutLanguage Guide\r\n    * Swift's Array and Dictionary types are both generic collections\r\n    * You can create an array of any types\r\n\r\n### The Problem That Generic Solve\r\n\r\n  * Fixed Type Example\r\n\r\n    ```swift\r\n    func swapTwoInts(inout a: Int, inout b: Int) {\r\n        let temporaryA = a\r\n        a = b\r\n        b = temporaryA\r\n    }\r\n\r\n    var someInt = 3\r\n    var anotherInt = 107\r\n\r\n    swapTwoInts(&someInt, &anotherInt)\r\n    println(\"someInt is now \\(someInt), and anotherInt is now \\(anotherInt)\")\r\n    // prints \"someInt is now 107, and anotherInt is now 3\r\n\r\n    func swapTwoStrings(inout a: String, inout b: String) {\r\n        let temporaryA = a\r\n        a = b\r\n        b = temporaryA\r\n    }\r\n\r\n    func swapTwoDoubles(inout a: Double, inout b: Double) {\r\n        let temporaryA = a\r\n        a = b\r\n        b = temporaryA\r\n    }\r\n    ```\r\n\r\n  * In all 3 functions, it is important that the types a and b are defined to be the same as each other.\r\n\r\n### Generic Functions\r\n\r\n```swift\r\nfunc swapTwoValues<T>(inout a: T, inout b: T) {\r\n    let temporaryA = a\r\n    a = b\r\n    b = temporaryA\r\n}\r\n```\r\n\r\n  * Comparison\r\n\r\n    ```swift\r\n    func swapTwoInts(inout a: Int, inout b: Int)\r\n    func swapTwoValues<T>(inout a: T, inout b: T)\r\n\r\n    var someInt = 3\r\n    var anotherInt = 107\r\n    swapTwoValues(&someInt, &anotherInt)\r\n    // someInt is now 107, and anotherInt is now 3\r\n\r\n    var someString = \"hello\"\r\n    var anotherString = \"world\"\r\n    swapTwoValues(&someString, &anotherString)\r\n    // someString is now \"world\", and anotherString is now \"hello\"\r\n    ```\r\n\r\n    * Note\r\n      * swapTwoValues inspired by generic function called swap, which is part of Swift standard library, is automatically made available for you to use in your apps\r\n\r\n### Type Parameters\r\n\r\n  * In the swapTwoValues, the placeholder T is an example of a type parameter.\r\n    * Type parameter specify and name a placeholder type, and are written immediately after the function's name, between a pair of matching angle bracket (such as <T>)\r\n    * Once you specify the type parameter, you can use it to define the type of a function's parameter, function's return type and or as a type annotation within the body of the function\r\n    * You can provide more than one type parameter by writing type parameter name within the angle bracket.\r\n  * Naming Type Parameters\r\n    * Traditional to use single-character name T\r\n    * But, you can use any valid identifier for the type parameter name\r\n    * Complex generic functions, or generic types with multiple parameters, useful to provide more descriptive parameter names.\r\n    * Example:\r\n      * Dictionary uses KeyType and ValueType\r\n    * Note\r\n      * Always give type parameters UpperCamelCase to indicate they are placeholder for a type not a value\r\n\r\n### Generic Types\r\n\r\n  * Custom classes, structures, and enumerations that can work with any type, similar to Array and Dictionary\r\n  * Example, create a Stack\r\n    * The concept of stack is used by UINavigationController.\r\n    * Call pushViewController:animated and popViewControllerAnimated:\r\n    * Last in, first out\r\n    * ![](iOS%3A%20Swift%20Programming%20(iBook).resources/CC626F62-D041-4B0F-8F78-4DEA2FD8B5D9.png)\r\n  * Integer Stack:\r\n\r\n    ```swift\r\n    struct InStack {\r\n        var items = [Int]()\r\n        mutating func push(item: Int) {\r\n            items.append(item)\r\n        }\r\n\r\n        mutating func pop() -> Int {\r\n            return items.removeLast()\r\n        }\r\n    }\r\n    ```\r\n\r\n  * Generic Stack:\r\n\r\n    ```swift\r\n    struct Stack<T> {\r\n        var items = [T]()\r\n\r\n        mutating func push(item: T) {\r\n            items.append(item)\r\n        }\r\n\r\n        mutating func pop() -> T {\r\n            return items.removeLast()\r\n        }\r\n    }\r\n\r\n    var stackOfStrings = Stack<String>()\r\n    stackOfStrings.push(\"uno\")\r\n    stackOfStrings.push(\"dos\")\r\n    stackOfStrings.push(\"tres\")\r\n    ```\r\n\r\n### Extending a Generic Type\r\n\r\n  * When you extend a generic type, you do not provide a type parameter list as part of the extension's definition.\r\n  * Type parameter list from the original type definition is available within the body of the extension\r\n  * The original type parameter names are used to refer to the type parameters of the original definition\r\n\r\n    ```swift\r\n    extension Stack {\r\n        var topItem: T? {\r\n            return items.isEmpty ? nil: items[items.count - 1]\r\n        }\r\n    }\r\n    ```\r\n\r\n### Type Constraints\r\n\r\n  * Overview\r\n    * To enforce certain type constraints on the types that can be used with generic functions and generic types\r\n    * Type constraints specify a type parameter must inherit from a specific class or conform to a protocol composition\r\n    * Dictionary places a limitation on the types that can be used as keys for a dictionary\r\n    * Keys must be hashable, conform to the Hashable protocol\r\n  * Type Constraint Syntax\r\n\r\n    ```swift\r\n    extension Stack {\r\n        var topItem: T? {\r\n            return items.isEmpty ? nil: items[items.count - 1]\r\n        }\r\n    }\r\n    ```\r\n\r\n  * Type Constraints in Action\r\n    * Type specific version\r\n\r\n      ```swift\r\n      func findStringIndex(array: [String], valueToFind: String) -> Int? {\r\n        for (index, value) in enumerate(array) {\r\n            if value == valueToFind {\r\n                return index\r\n            }\r\n        }\r\n        return nil\r\n      }\r\n\r\n      let strings = [\"cat\", \"dog\", \"llama\", \"parakeet\", \"terrapin\"]\r\n\r\n      if let foundIndex = findStringIndex(strings, \"llama\") {\r\n        println(\"Found index: \\(foundIndex)\")\r\n      }\r\n      ```\r\n\r\n      * Generic version\r\n\r\n        ```swift\r\n        func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {\r\n          for (index, value) in enumerate(array) {\r\n              if value == valueToFind {\r\n                  return index\r\n              }\r\n          }\r\n\r\n          return nil\r\n        }\r\n\r\n        let doubleIndex = findIndex([3.14, 0.1, 0.25], 9.3)\r\n        let stringIndex = findIndex([\"Mike\", \"John\", \"Andrea\"], \"John\")\r\n        ```\r\n\r\n### Associated Types\r\n\r\n  * Overview\r\n    * When defining a protocol, sometimes, it is useful to declare one or more associated types as part of the protocol's definition.\r\n    * Gives a placeholder name (alias) to a type that is used as part of the protocol\r\n    * Actual type to use for the associated type is not specified until the protocol is adopted\r\n  * Associated Types in Action\r\n\r\n    ```swift\r\n    protocol Container {\r\n      typealias ItemType\r\n      mutating func append(item: ItemType)\r\n\r\n      var count: Int { get }\r\n      subscript(i: Int) -> ItemType { get }\r\n    }\r\n    ```\r\n\r\n    * Int Stack Implementation\r\n\r\n      ```swift\r\n      struct IntStack: Container {\r\n          // original IntStack implementation\r\n          var items = [Int]()\r\n          mutating func push(item: Int) {\r\n              items.append(item)\r\n          }\r\n\r\n          mutating func pop() -> Int {\r\n              return items.removeLast()\r\n          }\r\n\r\n          // conformance to the Container protocol\r\n          typealias ItemType = Int\r\n          mutating func append(item: Int) {\r\n              self.push(item)\r\n          }\r\n\r\n          var count: Int {\r\n              return items.count\r\n          }\r\n\r\n          subscript(i: Int) -> Int {\r\n              return items[i]\r\n          }\r\n      }\r\n      ```\r\n\r\n    * Generic Type Implementation, Swift is able to infer that T refers to ItemAlias in the protocol:\r\n\r\n      ```swift\r\n      struct Stack<T>: Container {\r\n          var items = [T]()\r\n\r\n          mutating func push(item: T) {\r\n              items.append(item)\r\n          }\r\n\r\n          mutating func pop() -> T {\r\n              return items.removeLast()\r\n          }\r\n\r\n          // conformance to Container protocol\r\n          mutating func append(item: T) {\r\n              self.push(item)\r\n          }\r\n\r\n          var count: Int {\r\n              return items.count\r\n          }\r\n\r\n          subscript(i: Int) -> T {\r\n              return items[i]\r\n          }\r\n      }\r\n      ```\r\n\r\n### Where Clause\r\n\r\n  * Define requirements on the type parameters associated with a generic function or type\r\n  * Define where clauses as part of a type parameter list\r\n  * Where clause allows you to require that an associated type conforms to a certain protocol **and/or** certain taupe parameters an associated types to be the same\r\n\r\n    ```swift\r\n    func allItemsMatch<C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable> (someContainer: C1, anotherContainer: C2) -> Bool {\r\n        if someContainer.count != anotherContainer.count {\r\n            return false\r\n        }\r\n\r\n        for i in 0..<someContainer.count {\r\n            if someContainer[i] != anotherContainer[i] {\r\n                return false\r\n            }\r\n        }\r\n\r\n        return true\r\n    }\r\n\r\n    var stackOfStrings = Stack<String>()\r\n    stackOfStrings.push(\"1\")\r\n    stackOfStrings.push(\"2\")\r\n    stackOfStrings.push(\"3\")\r\n\r\n    //var arrayOfStrings = [\"1\", \"2\", \"3\"]\r\n    // Error cause array of String does not conform to Container protocol\r\n    var arrayOfStrings = Stack<String>()\r\n    arrayOfStrings.push(\"1\")\r\n    arrayOfStrings.push(\"2\")\r\n    arrayOfStrings.push(\"3\")\r\n\r\n    if allItemsMatch(stackOfStrings, arrayOfStrings) {\r\n        println(\"All items match.\")\r\n    } else {\r\n        println(\"Not all items match.\")\r\n    }\r\n    ```\r\n\r\n## Access Control\r\n\r\n### Overview\r\n\r\n  * Restricst access to parts of your code from code in other source files and modules\r\n  * You can assign specific access levels to individual types (classes, structures, and enumerations), as well as properties, methods, initialisers, subscripts\r\n  * Protocols can be restricted to a certain context, as can global constants, variables and functions\r\n  * Reduces the need to specify explicit access control levels by providing default access levels for typical scenarios\r\n  * Note\r\n    * Various aspics of your code that can have access control (properties, types, functions, etc) are referred as entities\r\n\r\n### Modules and Source Files\r\n\r\n  * Swift's access control model is base on the concept of modules and source files\r\n  * Module is a single unit code of distributions\r\n    * A framework or application buildt and shipped as a single entity that can be imported by another module with Swift's **import** keyword\r\n    * Each build target (such as an app bundle or framework) in Xcode is treated as a separate module in Swift\r\n  * A source file is a single Swift source code within a module (in effect a single file within an app or framework\r\n    * Though it is common to define individual types in a separate source files, a single source file can contain multiple types, functions, and so on\r\n\r\n### Access Levels\r\n\r\n  * **Overview**\r\n    * 3 different access levels\r\n      * Public access\r\n        * Entities to be used within any source file from their defining module and also in a source file from another module that imports the defining module\r\n        * When specifying the public interface to a framework\r\n      * Internal access\r\n        * Entities to be used within any source file from their defining module, but not in any source file outside that module\r\n        * When defining an app's or framework's internal structure\r\n      * Private access\r\n        * Restrict the use of an entity to its own defining source file\r\n        * To hide implementation of a specific piece of functionality\r\n  * **Guiding Principle of Access Levels**\r\n    * No entity can be defined in terms of another entity that has a lower (more restrictive) access level\r\n    * Example:\r\n      * A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used\r\n      * A function cannot have a higher access level than its parameter types and return type\r\n  * **Default Access Levels**\r\n    * Internal access with a few exceptions\r\n  * **Access Levels for Single-Target App**\r\n    * Typically you only need an internal access, unless you want to mark some parts of your code as private in order to hide their implementation details from other app's module.\r\n  * **Access Levels for Framework**\r\n    * Public access, as you are building public facing interface\r\n    * Note\r\n      * Any internal implementation details can still be internal or private.\r\n\r\n### Access Control Syntax\r\n\r\n  * Syntax\r\n\r\n    ```swift\r\n    public class SomePublicClass {}\r\n    internal class SomeInternalClass {}\r\n    private class SomePrivateClass {}\r\n\r\n    public var somePublicVariable = 0\r\n    internal let someInternalConstant = 0\r\n    private func somePrivateFunction() {}\r\n    ```\r\n\r\n    * Implicit - internal access\r\n\r\n      ```swift\r\n      class SomeInternalClass {}              // implicitly internal\r\n      var someInternalConstant = 0            // implicitly internal\r\n      ```\r\n\r\n  * Custom Types\r\n    * If you want to specify an explicit access level to a custom type, do at the point that you define the type.\r\n      * The new type can then be used whenever its access level permits.\r\n      * Access level of a type also affects the default access level of type's members (properties, methods, inits and subscripts)\r\n      * If type's access level i private, all its members default level is also private\r\n    * Note\r\n      * A public type defaults to having internal members, not public members\r\n      * If you want type member to be public, you must explicitly mark it as such\r\n      * Ensure API is something you opt-in to publish\r\n\r\n      ```swift\r\n      public class SomePublicClass {         // explicitly public class\r\n          public var somePublicProperty = 0 // explicitly public class member\r\n          var someInternalProperty = 0 // implicitly internal class member\r\n          private func somePrivateMethod() {} // explicitly private class member\r\n      }\r\n\r\n      class SomeInternalClass {              // implicitly internal class\r\n          var someInternalProperty = 0 // implicitly internal class member\r\n          private func somePrivateMethod() {} // explicitly private class member\r\n      }\r\n\r\n      private class SomePrivateClass {       // explicitly private class\r\n          var somePrivateProperty = 0 // implicitly private class member\r\n          func somePrivateMethod() {}         // implicitly private class member\r\n      }\r\n      ```\r\n\r\n    * Tuple Types\r\n      * Access level for a tuple type is the most restrictive access level of all types used in the tuple.\r\n      * If members of the tuple comprises of internal and private access, tuple will be private\r\n      * Note\r\n        * Tuple does not have a standalone definition in a way that classes, structures, enums and functions do\r\n        * Tuple type's access is deduced automatically when the tuple is used\r\n    * Function Types\r\n      * Access level for a function type is calculated as the most restrictive access level of the function's parameter types and return type\r\n\r\n        ```swift\r\n        func someFunction() -> (SomeInternalClass, SomePrivateClass) {\r\n          // function implementation goes here\r\n        }\r\n        ```\r\n\r\n        * Because the function's return type is private, you must mark the function's overall access level with private:\r\n\r\n          ```swift\r\n          private func someFunction() -> (SomeInternalClass, SomePrivateClass) {\r\n          // function implementation goes here\r\n          }\r\n          ```\r\n\r\n    * Enumeration Types\r\n      * Individual cases of an enums automatically receive the same access level as the enum they belong to\r\n      * Can't specify different access level for individual enum cases\r\n\r\n        ```swift\r\n        public enum CompassPoint {\r\n          case North\r\n          case South\r\n          case East\r\n          case West\r\n        }\r\n        ```\r\n\r\n    * Raw Values and Association Type\r\n      * The types used for any raw values or associated values in enum must have an access level at least as high as the enum's access level\r\n      * You cannot use a private type as the raw value type of an enumeration with an internal access level for example.\r\n    * Nested Types\r\n      * Nested types within a private type will be private\r\n      * Nested types in a public type or internal type will be internal\r\n      * Explicitly declare public type as public to be public\r\n  * Subclassing\r\n    * Subclass cannot have a higher level access level than its superclass\r\n    * You can override any class member that is visible in a certain access context\r\n      * An override can make inherited class more accessible than its superclass\r\n        * public class A {\r\n        * private func someMethod() {}\r\n        * }\r\n          * internal class B: A {\r\n        * override internal func someMethod() {}\r\n        * }\r\n    * Valid for a subclass member to call a superclass member that has lower access permission, as long as the call takes place within the allowed access level context\r\n      * same source file as the superclass for a private member call\r\n      * within the same module for internal member call\r\n\r\n      ```swift\r\n      public class A {\r\n          private func someMethod() {}\r\n      }\r\n\r\n      internal class B: A {\r\n          override internal func someMethod() {\r\n              super.someMethod()\r\n          }\r\n      }\r\n      ```\r\n\r\n### Constants, Variables, Properties, and Subscripts\r\n\r\n  * A contant, variable or property cannot be more public than its type\r\n  * If a class member makes use of a private type, the member must also be declared as private\r\n    * private var privateInstance = SomePrivateClass()\r\n  * **Getters and Setters**\r\n    * Getters and setters for class members (constants, vars, props, subscripts) automatically receive the same access they belong to\r\n    * You can give setter a lower access level than its corresponding getter to restrict the read-write scope of that member.\r\n      * By writing **private(set)** or **internal(set)** before the var or subscript introducer\r\n    * Note\r\n      * This rule apply for stored and computed properties\r\n\r\n        struct TrackedString {\r\n            private(set) var numberOfEdits = 0\r\n            var value: String = \"\" {\r\n                didSet {\r\n                    numberOfEdits++\r\n                }\r\n            }\r\n        }\r\n\r\n        var stringToEdit = TrackedString()\r\n        stringToEdit.value = \"This string will be tracked.\"\r\n        stringToEdit.value += \" This edit will increment numberOfEdits.\"\r\n        stringToEdit.value += \" So will this one.\"\r\n        println(\"The number of edits is \\(stringToEdit.numberOfEdits)\")\r\n        // prints \"The number of edits is 3\"\r\n\r\n      * You can assign explicit access level for both getter and setter if required, e.g. numberOfEdits getter is public and set is private:\r\n\r\n        ```swift\r\n        public struct TrackedString {\r\n            public private(set) var numberOfEdits = 0\r\n            public var value: String = \"\" {\r\n                didSet {\r\n                    numberOfEdits++\r\n                }\r\n            }\r\n            public init() {}\r\n        }\r\n        ```\r\n\r\n### Initializers\r\n\r\n  * Custom inits can be assigned access level <= type they initialise\r\n  * Except for required init must have the same access level as the class it belongs to\r\n  * As with functions/methods, types of params cannot be more private than the init\r\n  * **Default Initializers**\r\n    * Default init has the same access level as the type initializes\r\n    * For a public type, the default init is considered internal\r\n      * Declare as public if you need to expose it\r\n  * **Default Memberwise Initializers for Structure Types**\r\n    * Default member wise init for a structure is considered private if any of the structure's stored properties are private\r\n    * Otherwise it is internal\r\n\r\n### Protocols\r\n\r\n  * If you want to assign an explicit level to a protocol type, do so at the point that you define a protocol\r\n    * Access level of each requirement within a protocol definition is automatically set to the same access level as the protocol\r\n    * Cannot set a different access level than the protocol it supports\r\n    * Ensure that all the protocol's requirements will be visible on any type that adopts the protocol\r\n  * Note\r\n    * If you define public protocol, the protocol's requirements require a public access level for those requirements when they are implemented\r\n  * **Protocol Inheritance**\r\n    * Inherited protocol have the same access level with its parent.\r\n    * You cannot write a public protocol that inherits from an internal protocol\r\n  * **Protocol Conformance**\r\n    * A type can conform to a protocol with a lower access level than the type itself\r\n    * The context type conforms to a  particular protocol is the min of the type's access level and the protocol's access level\r\n      * If a type is public, and protocol is internal, type's conformance to that protocol is also internal\r\n    * Implementation of each protocol requirement has at least the same access level as the type's conformance to that protocol\r\n      * If a public type conforms to a internal protocol, the type's implementation of each protocol requirement must be at least internal\r\n    * Note\r\n      * In Swift as in Obj-C protocol conformance is global, it is not possible for a type to conform to a protocol in two different ways within the same program\r\n\r\n### Extensions\r\n\r\n  * Any members added in an extension have the same default access level as the type members declared in the original type being extended.\r\n  * **Adding a protocol conformance with an extension**\r\n    * You cannot provide an explicit access level modifier for an extension if you are using that extension to add protocol conformance.\r\n    * Protocol's own access level is used to privde the default access for each of the protocol requirements.\r\n\r\n### Generics\r\n\r\n  * Access level for a generic type/function is the minimum of the access level of the generic type/function itself and the access level of any type constraints on its type parameters.\r\n\r\n### TypeAliases\r\n\r\n  * Any type aliases you define are treated as distinct types for the purpose of access control\r\n  * A type alias can have an access level less <= access level of the type it aliases.\r\n  * Note\r\n    * This rule also applies to type aliases for associated types used to satisfy protocol conformances\r\n\r\n## References\r\n\r\n* [The Swift Programming Language](https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-XID_0)\r\n* [Swift - Apple Developer](https://developer.apple.com/swift/)\r\n\r\n\r\n"
  },
  {
    "path": "TypeScript/README.md",
    "content": "# TypeScript Cheatsheet\nSet of basic functionalities from TypeScript in one place. <br>\nPlease note that some functionalities are part of ES201x but they are frequently used in TypeScript as well.\n\n# Table of Contents\n\n<!--ts-->\n   * [Types, variables and functions](#Types,-variables-and-functions)\n      * [Basic variable types](#Basic-variable-types)\n      * [Destructing and spread](#Destructing-and-spread)\n      * [Array functions](#Array-functions)\n      * [Functions](#Functions)\n   * [Classes](#Classes)\n      * [Inheritance](#Inheritance)\n      * [Accessors](#Accessors)\n      * [Abstract class](#Abstract-class)\n   * [Interfaces](#Interfaces)\n      * [Index signature](#Index-signature)\n   * [Generics](#Generics)\n      * [Extending generics](#Extending-generics)\n   * [Enums](#Enums)\n      * [Constant and computed enum members](#Constant-and-computed-enum-members)\n      * [Reverse enum member](#Reverse-enum-member)\n   * [Advanced types](#Advanced-types)\n      * [Types intersection and union](#Types-intersection-and-union)\n      * [Type guards](#Type-guards)\n      * [Type aliases](#Type-aliases)\n      * [Conditional types](#Conditional-types)\n      * [Index types](#Index-types)\n      * [Infer](#Infer)\n   * [Symbols](#Symbols)\n   * [Modules](#Modules)\n      * [Namespaces](#Namespaces)\n      * [Ambient modules](#Ambient-modules)\n   * [Decorators](#Decorators)\n   * [Generators](#Generators)\n   * [Interview questions](#Interview-questions)\n<!--te-->\n\nTypes, variables and functions\n=================\n\nCommand-line interface for Angular - set of commands that will help us during development.\n\n## Basic variable types\n\n| Type  | Example | Notes |\n| ------------- | ------------- | ------------- |\n| number | let myNumber: number = 6 | Represent all numbers : integer, float, hex etc.\n| string | let fullName: string = `Bob Bobbington`| Text with all text functions (indexOf, replace etc.)\n| boolean | let isTrue: boolean = true| true/false value\n| Array | let list: Array<number> = [1, 2, 3] | Shorter version: let list: number[] = [1, 2, 3];\n| Tuple | let x: [string, number] = ['test', 2]; | Array contains  ains items with various types\n| any | let x: any = 2; | Everything can be assigned to value with any type\n| Enum | enum Color {Red, Blue } | Usage: let c: Color = Color.Blue; \n| Never | function fail(): never {while(true) {}} | Indicating that something never should happen\n| Null or undefined | let u: undefined = undefined; | In TS there is dedicated type for null and undefined\n| Object | let x:Object = {id: 2}; | Represents any object\n| Function | let myFn:Function = function() {...} | Represents any function\n\n## Destructing and spread\nThis is ES functionality \n\n**Spread**\n\nSpread can be used to merge two object or arrays:\n\n```ts\nlet first = [1, 2];\nlet second = [3, 4];\nlet both = [0, ...first, ...second, 5];\n}\n```\n\nboth variable is equal to [0, 1, 2, 3, 4, 5].\n\nSame for objects:\n\n```ts\nlet first = { id: 2 };\nlet second = { name: \"test\", ...first };\n```\nSecond is equal to {name: \"test\", id: 2 }\n\n**Destructuring**\n\nReversed spread - we can split one object into multiple\n\n```ts\nlet input = [1, 2];\nlet [first, second] = input;\n```\nfirst is equal to 1 and second is equal to 2\n\nWe can also use \"...\" operator\n\n```ts\nlet input = [1, 2, 3];\nlet [first, ...rest] = input;\n```\nfirst is equal to 1\n\nrest is equal to [2, 3]\n \n## Array functions\n\nThis is ES functionality \n\n```ts\nvar numArray: Array<number> = [1, 2, 3]; // number[] can be used instead of Array<number> \nvar numArray2: Array<number> = [4,5];\nvar stringArray: Array<number> = [\"a\", \"b\", \"c\"];\n\nvar objectArray: Array<User> = [\n  {name: \"Iva\", age: 31},\n  {name: \"John\", age: 39},\n  {name: \"Monica\", age: 22}\n]; \n```\n\n| Function  | Result | Notes | \n| ------------- | ------------- | ------------- | \n| concat | numArray.concat(numArray2) -> [1,2,3,4,5] | Push values from one array to another and return it as a new array |\n| every | objectArray.every(x=> x.age > 20) -> true | Check if all items are passing condition |\n| some | objectArray.some(x=> x.age > 30) -> true | Check if any item is passing condition |\n| filter | objectArray.filter(x=> x.age >= 35)) -> [{name: \"Iva\", age: 39}] | Get only items which are passing condition |\n| forEach | numArray.forEach(x=> console.log(x)) | Perform some logic for each array item |\n| join | stringArray.join(\",\") -> \"a,b,c\" | Merge text items into one value (add ',' between) |\n| indexOf | stringArray.indexOf(\"b\") -> 1 | Return index(position) array item |\n| map | stringArray.map(x => x + \"1\") -> [\"a1\", \"b1\", \"c1\"] | Create new array/object applying some logic for each element |\n| push | stringArray.push(\"d\") -> [\"a\", \"b\", \"c\", \"d\"] | Add element to the end of the array  |\n| unshift | stringArray.unshift(\"d\") -> [\"d\", \"a\", \"b\", \"c\"] | Add element to the begin of the array  |\n| reduce | numArray.reduce((x, y) => x + y) -> 16 | Merge array into one value performing some logic on a way |\n| shift | numArray.shift() -> [2, 3] | Removes the first element from an array and returns it.|\n| sort | [\"b\", \"c\", \"a\"].sort((x,y) => x > y) -> [\"a\", \"b\", \"c\"] | Sort array by some logic |\n\n## Functions\n\nThis is ES functionality \n\n| Type  | Example |\n| ------------- | ------------- |\n| Named function | function add(x: number, y:number): number {} | \n| Anonymous function | let myAdd = function(x: number, y: number = 1): number | \n| Arrow function | myArrowAdd = (x: number, y:number): number | \n\n\nClasses\n=================\n\nSample class:\n\n```ts\nclass NewGreeter {\n   private greeting: string; \n   constructor(message: string) { \n    this.greeting = message;\n   }\n\n   greet() {\n    return \"Hello, \" + this.greeting;\n   }\n}\n\nvar greeter = new Greeter('friend');\n```\n\nNotes:\n\n1. Only one constructor inside a class\n2. constructor(**this** message: string) will automatically create message property and assign to its value from message property\n3. Instead of private - public or protected can be used\n\n## Inheritance\n\n```ts\nclass MyObject {\n   protected value = 0;\n   static staticValue = 0;\n\n   getValue() {\n    return this.value;\n   }\n}\nclass ChildObject extends MyObject {\n   getParentValue() {\n    return this.value;\n   }\n }\n```\n\n## Accessors\n\nTypeScript supports getters/setters as a way of intercepting accesses to a member of an object. You can add logic while the property is changing value or it is read by something\n\n```ts\nprivate _value = 0;\nget value(): number {\n\treturn this.value;\n}\nset value(newValue: number): void {\n\tthis.value = newValue;\n}\n```\n\n## Abstract class\n\nAbstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members. \n\n```ts\nabstract class MyAbstractObject {\n    constructor(public value: string) { }\n    abstract getValue(): string; \n}\n```\n\n`getValue` function must be implemented in derived classes. A derived class must also call super() in a constructor, example:\n\n```ts\nabstract class MyAbstractObject extends Department {\n    constructor() {\n       super(\"test value\");\n    }\n    getValue(): string {\n       // some logic here\n    }\n}\n```\n\nInterfaces\n=================\n\nA class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. The interface is the only skeleton for our classes implementing them\n\n**Interface for object**\n\n```ts\ninterface MyObject {\n     label: string \n}\n\nfunction MyFunction(obj: MyObject) \n```\n\n`obj` parameter has to contain label property\n\n**Interface for class**\n\n```ts\ninterface ComesFromString {\n    name: string;\n}\n\nclass MadeFromString implements ComesFromString {\n    constructor (public name: string) {\n\n    }\n}\n```\n\nclass `MadeFromString` has to contain 'name' property\n\n`obj` parameter has to contain label property\n\n## Index signature\n\nIndex signature can be used to allow object/class contain multiple different properties with the same type, for example, we have such an interface:\n\n```ts\ninterface MyObject {\n\t[propName: string]: string\n}\n```\nand `MyObject` that is implementing it. \n\nSample correct implementation of `MyObject`:\n\n```ts\nlet MyObject: MyObject  = {\n\tfistName: 'test',\n\tlastName: 'test'\n}\n```\n\nSample incorrect implementation of `MyObject`:\n\n```ts\nlet MyObject: MyObject  = {\n\tfirstName: 'test',\n\tage: 2\n}\n```\n\nBecause age is number and our index signature indicate that our properties should have a string type\n\n\nGenerics\n=================\nSometimes same function/class/object can be used with different types and we don't want to declare it to one specific type. We can use generic type then\n\nExample:\n\n```ts\nfunction changeUndefinedToNull<T>(value: T): T {\n\treturn (typeof value !== \"undefined\") ? value : null;\n}\n```\n\nand now it can be used with diffrent types used for value parameter:\n\n```ts\nconst result = changeUndefinedToNull<string>(\"Test\");\n```\n```ts\nconst result = changeUndefinedToNull<number>(21);\n```\n```ts\nconst result = changeUndefinedToNull<Object>({name: \"Test\"});\n```\n\nMore than just one generic type can be used:\n\n```ts\nfunction doSth<T,Y> (value: T, category: Y) {}\n```\n\n## Extending generics\n\nGeneric classes can be extended - it can be the implementation of some interface/object. Extending allow your object to inherit the features of another object type, so can be used for instance when you expect that object will contain some of properties or functions that will be used further. \n\nExample:\n\n```ts\nfunction mySubStr<T extends string>(arg: T): string {\n\treturn arg.substr(1, 10);\n}\n```\n\narg has to object that is equal or extending string, for example, string or:\n\n```ts\ninterface ExtendedString extends String{\n\tnewStringFunction(): number\n}\n\nmySubStr(arg: ExtendedString);\n```\n\nanother example - let's assume that we need to use length property from our object, so we would like to be sure that this property will exist in object. Let's create `ILengthwise` interface:\n\n```ts\ninterface ILengthwise {\n   length: number\n}\n```\n\nand now we can use it to ensure that our generic will contain length property:\n\n```ts\nfunction doSthWithLength<T extends ILengthwise>(arg: T): number {\n\treturn arg.length;  // we can be sure that length property exists here\n}\n```\n\nEnums\n=================\n\nEnums allow us to define a set of named constants and then used them like a dictionary.\n\nSample enum:\n\n```ts\nenum Direction {\n\tUp,\n\tDown = 1,  // custom values can be assigned to enums\n\tLeft,\n\tRight,\n}\n```\n\nusage:\n\n```ts\nfunction move(direction: Direction): void {\n\tif(direction == Direction.Up) {\n\t\t// some code here\n\t}\n}\n```\n\n## Constant and computed enum members\n\nSome enum members have pre-set value and some members are computed during compilation\n\n```ts\nenum FileAccess {\n    // constant members\n    None,\n    Read    = 1 << 1,\n    Write   = 1 << 2,\n    ReadWrite  = Read | Write,\n    // computed member\n    G = \"123\".length,\n    F = Read + Write\n}\n```\n\n## Reverse enum member\n\n```ts\nenum MyEnum {\n\tA, \n\tB\n}\nconst member = MyEnum[0];\n```\n\nmember variable is equal to \"A\"\n\n\nAdvanced types\n=================\n\n## Types intersection and union\n\n**Intersection**\n\n```ts\ninterface Type1 {name: string;}\ninterface Type2 {age: number}\n\nlet myObject: Type1 & Type2\n```\n\n`Type1 & Type2` means that there will be object containing properties both from `Type1 & Type2`\n \nSample correct `myObject` value:\n\n```ts\nmyObject = {name: \"test\", age: 33}\n```\n\nSample incorrect `myObject` values:\n\n```ts\nmyObject = {name: \"test\"}\n```\n```ts\nmyObject = {name: \"test\", age: \"test\"}\n```\n\n**Union**\n\n```ts\nconst value: string | boolean \n```\n\nValue can be `string` OR `boolean`.\n\nIt is correct:\n\n```ts\nvalue = \"Test\";\n```\n```ts\nvalue = true\n```\n\nand that is incorrect:\n\n```ts\nvalue = 2\n```\n\n## Type guards\n\nType guard can be used to tell TypeScript what type is any value in a specific block of code.\n\nSample Type Guard implementation:\n\n```ts\nfunction isNumber(x: any): x is number {\n    return (<number>x).toPrecision !== undefined;\n}\n```\n\nSample Type Guard usage\n\n```ts\nfunction doSth<T>(value: T) {\n    if (isNumber(value)) {\n\treturn value.toPrecision; // it's ok as TypeScript know that here value is number\n    } else {\n\treturn value.toPrecision; // Error - we don't have access to toPrecision here\n    } \n}\n```\nthanks to 'x is number' typescript know in which scope we have access to toPrecision \n\n## Type aliases\n\nOwn custom types can be declared, for example\n\n```ts\ntype MyType<T> = { parameter: T};\n```\n\nUsage:\n\n```ts\nlet myString: MyType<string> = {parameter: \"Test\"}\nlet myNumber: MyType<number> = {parameter: 2}\n```\n\n## Difference between Types and Interfaces\n\n**Types**\n\nCreate a tree structure for an object. You can't do the same with the interface because of lack of intersection (&)\n\n```ts\ntype Tree<T> = T & { parent: Tree<T> };\n```\n\ntype to restrict a variable to assign only a few values. Interfaces don't have union (|)\n\n```ts\ntype Choise = \"A\" | \"B\" | \"C\"\n```\n\nthanks to types, you can declare NonNullable type thanks to a conditional mechanism.\n\n```ts\ntype NonNullable<T> = T extends null | undefined ? never : T;\n```\n\n**Interfaces**\n\nYou can use interface for OOP and use `implements` to define object/class skeleton\n\n```ts\ninterface UserBase {\n    user: string;\n    password: string;\n    login: (user: string, password: string) => boolean;\n}\n\nclass User implements UserBase {\n    user = \"user1\"\n    password = \"password1\"\n\n    login(user: string, password: string) {\n        return (user == user && password == password)\n    }\n}\n```\n\nYou can extend interfaces with other interfaces\n\n```ts\ninterface MyObject {\n\tlabel: string,\n}\n\ninterface MyObjectWithSize extends MyObject {\n\tsize?: number\n}\n```\n\n## Conditional types\n\nGeneric types can be different depending on some condition\n\n```ts\ntype MyStringType<T> = T extends string ? string : Text;\n```\n\nif `T` extends string (contains all string properties and functions) then it will be a string type. Otherwise, it will be our custom Text type. \n\nanother example:\n\n```ts\ntype NonNullable<T> = T extends null | undefined ? never : T;\n```\n\nNonNullable type will check if a avalue isn't equal to null or undefined (it should never be equal to null or undefined)\n\n## Index types\n\n***keyof*** keyword is indicating all keys for specifed object, for example:\n\n```ts\ntype testType = keyof {id: \"test\", age: 2};\n```\n\nonly \"id\" or \"age\" values can be assigned to variable with 'testType' type\n\nExample 2:\n\n```ts\ninterface IMyInterface {\n    id: number;\n    name: string;\n}\n\ntype Keys = {id: 1, name: \"T\" }[keyof IMyInterface];\n```\n\nusing `[keyof ...]` instead of \"keyof\" before object means that we are revesing keyof behavior and now only 1 and \"T\" can be assigned to value with Keys type (values, not property keys)\n\nExample 3:\n\n```ts\ntype Key<T> = { [K in keyof T]: K }[keyof T];\n```\n\nThis will point to all keys in the T object (just like `keyof T`).\nBut this construction can be used to for example check type of keys:\n\n```ts\ntype FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];\n```\n\nThis type will require values equal to keys of T object, but only these ones which are functions\n\n## Infer\n\n\"Within the extends clause of a conditional type, it is now possible to have infer declarations that introduce a type variable to be inferred. Such inferred type variables may be referenced in the true branch of the conditional type. It is possible to have multiple infer locations for the same type variable.\"\n\nExample:\n\n```ts\ntype MyUnionTypesBase<T> = T extends Array<infer U> ? U : never;\nlet myValue: MyUnionTypesBase<[number, string, boolean]>;\n```\n\nMy value can be type number | string | boolean (number or string or boolean)\n\nSymbols\n=================\n\nInstead of using normal string keys in object it can be used predefined and assigned to variable Symbol\nexample:\n\n```ts\nconst getSthSymbol = Symbol(\"getSth\");\n\nclass SampleClass {\n    [getSthSymbol](){\n\treturn \"something\";\n    }\n}\n```\n\n**Symbols are unique**\n\n```ts\nlet sym2 = Symbol(\"key\");\nlet sym3 = Symbol(\"key\");\n```\n\n`sym2` is not equal to `sym3` (`sym2` != `sym3`)\n\nModules\n=================\n\nImport and export mechanism (between files and objects)\n\nExample:\n\n`data.ts` file\n\n```ts\nexport class DataClass {\n    ...\n}\nexport interface Operations {\n    ...\n}\n```\n\nImport other file \n\n```ts\nimport {DataClass as ImportedDataClass} from './data.ts'\n```\n\nImport all:\n\n```ts\nimport * from './data.ts'\n```\n\n## Namespaces\n\nEncapsulated scope of classes, objects, functions, interfaces and others. \n\nExample:\n\n```ts\nnamespace UserArea {\n\texport interface IUser {}\n\texport class User {}\n\tclass Person {}\n}\nlet user = UserArea.User;\n```\n\n## Ambient modules\n\nEncapsulated scope of classes, objects, functions, interfaces, and others - that is available to export/import.\n\"We call declarations that don’t define an implementation “ambient”. Typically, these are defined in .d.ts files. \"\n\nExample\n\n```ts\ndeclare module \"path\" {\n\texport function normalize(p: string): string;\n\texport function join(...paths: any[]): string;\n\texport var sep: string;\n}\n```\n\nand then we can import it\n\n```ts\nimport * as URL from „path\"\n```\n\n## replace global function\n\nSome functions in JS are global and we may have not type for them. We can use 'declare' keyword here\n\n```ts\ndeclare const System: OurSystemObject;\n```\n\nDecorators\n=================\n\n\"Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.\"\n\n```ts\nfunction customMethodDecorator(value: string) {\n    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {  \n\tdescriptor.value = () => {\n\t    return \"Hello, \" + value;\n\t};\n    };\n}\n```\n\nit will change return value of decorated function so it will return \"Hello \" + value from decorator\n\n```ts\n@customMethodDecorator(\"here is hacker\")\n    greet() {\n\treturn \"Hello, \" + this.greeting;\n    }\n```\n\ngreet() will return \"Hello, here is hacker\"\n\nGenerators\n=================\n\nLoops can be executed \"step by step\"\n\nExample:\n\n```ts\nfunction* idMaker(){\n\tlet index = 0;\n\twhile(index < 3)\n\t\tyield index++;\n}\n\nlet gen = idMaker();\n\nlet value;\nvalue = gen.next().value // result 1\nvalue = gen.next().value // result 2\nvalue = gen.next().value // result 3\n```\n\nInterview questions\n=================\n\n**Q: What is Tuple type?**\n\nA: Array contains items with various types. See [types](https://github.com/delprzemo/typescript-cheatsheet#Basic-variable-types \"Basic-variable-types\") \n\n**Q: When never type can be useful?**\n\nA: Never is information that this particular part shouldn't be reachable. For example in this code\n\n```ts\nfunction do(): never {\n    while (true) {}\n}\n```\n\nwe have an infinite loop and we don't want to iterate infinite loop. Simply as that.\n\nBut a real question is how can it be useful for us? It might be helpful for instance while creating more advanced types to point what they are not\n\nFor example, let's declare our own NonNullable type:\n\n```ts\ntype NonNullable<T> = T extends null | undefined ? never : T;\n```\nHere we are checking if T is null or undefined. If it is then we are pointing that it should never happen. Then while using this type:\n\n```ts\nlet value: NonNullable<string>;\nvalue = \"Test\";\nvalue = null; // error\n```\n\n**Q: What is a difference between named, anonymous and arrow functions?**\n\nA: See [basic function types](https://github.com/delprzemo/typescript-cheatsheet#Functions \"Functions\") \n\n**Q: How many constructors can be implemented for class**\n\nA: Only one - there is no overloading for TypeScript class constructor\n\n**Q: What is a difference between \"extends\" and \"implements\"**\n\nA: Classes can extend other classes or objects, but when it comes to interfaces then they should be implemented\n\nFor `MyObject`\n```ts\nclass ChildObject extends MyObject \n```\n\nFor `IMyObject`\n```ts\nclass ChildObject implements IMyObject \n```\n\n**Q: What is a difference between types and interfaces?**\n\nA: See [Difference between types and interfaces](https://github.com/delprzemo/typescript-cheatsheet#difference-between-types-and-interfaces \"difference-between-types-and-interfaces\") \n\n**Q: What is keyof?**\n\nA: ***keyof*** keyword is indicating all keys for specifed object, for example:\n\n```ts\ntype testType = keyof {id: \"test\", age: 2} ;\n```\n\ntestType = \"id\" | \"age\"\n\nSee [Index types](https://github.com/delprzemo/typescript-cheatsheet#index-types \"index-types\") \n\n**Q: What is tsconfig.json file?**\n\nA: File specifies the root files and the compiler options required to compile the project.\n\n**Q: What is computed enum value?**\n\nA: Computed value will be assigned during compilation. See [Enum computed value](https://github.com/delprzemo/typescript-cheatsheet#constant-and-computed-enum-members \"constant-and-computed-enum-members\") \n\n**Q: What are files with the d.ts extension for?**\n\nA: They are usually module template file where we can keep typings for JS code. \n\n**Q: List few predefined conditional types in TypeScript**\n\nA: \n\nExclude<T, U> – Exclude from T those types that are assignable to U.\n\nExtract<T, U> – Extract from T those types that are assignable to U.\n\nNonNullable<T> – Exclude null and undefined from T.\n\t\nReturnType<T> – Obtain the return type of a function type.\n\t\nInstanceType<T> – Obtain the instance type of a constructor function type.\n\nSee [TypeScript 2.8](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html)\n\n**Q: What will be type box here?**\n\n```ts\ninterface MyInterface {\n   name: string;\n}\n\ninterface MyInterface {\n   age: number;\n}\n\nlet box: MyInterface \n```\n\nA: ```{name: string, age: number}; ```\n\n**Q: What is 'unknown' type in TypeScript?**\n\nA: Unknown is used to describe the least-capable type in TypeScript.  It doesn't allow typical operations for a particular type\n\n```ts\nfunction f10(x: unknown) {\n\tx == 5;\n\tx = \"5\";\n\tx = x + 1; // not allowed\n\tx = null; \n\tx > 0  // not allowed\n\tx.Test() // not allowed\n}\n```\n\n**Q: Can typescript be used without JavaScript?**\n\nA: No, TypeScript is compiled to JavaScript, so it can't be used without it\n\n**Q: What is DefinitelyTyped repository?**\n\nA: It's GitHub repository with already written types for most popular JS libraries. They can be installed by npm with @types prefix, for example npm install @types/node\n"
  }
]