diff options
50 files changed, 2847 insertions, 510 deletions
diff --git a/amd.html.markdown b/amd.html.markdown new file mode 100644 index 00000000..b3237dc7 --- /dev/null +++ b/amd.html.markdown @@ -0,0 +1,212 @@ +---
+category: tool
+tool: amd
+contributors:
+ - ["Frederik Ring", "https://github.com/m90"]
+filename: learnamd.js
+---
+
+## Getting Started with AMD
+
+The **Asynchronous Module Definition** API specifies a mechanism for defining
+JavaScript modules such that the module and its dependencies can be asynchronously
+loaded. This is particularly well suited for the browser environment where
+synchronous loading of modules incurs performance, usability, debugging, and
+cross-domain access problems.
+
+### Basic concept
+```javascript
+// The basic AMD API consists of nothing but two methods: `define` and `require`
+// and is all about module definition and consumption:
+// `define(id?, dependencies?, factory)` defines a module
+// `require(dependencies, callback)` imports a set of dependencies and
+// consumes them in the passed callback
+
+// Let's start by using define to define a new named module
+// that has no dependencies. We'll do so by passing a name
+// and a factory function to define:
+define('awesomeAMD', function(){
+ var isAMDAwesome = function(){
+ return true;
+ };
+ // The return value of a module's factory function is
+ // what other modules or require calls will receive when
+ // requiring our `awesomeAMD` module.
+ // The exported value can be anything, (constructor) functions,
+ // objects, primitives, even undefined (although that won't help too much).
+ return isAMDAwesome;
+});
+
+// Now, let's define another module that depends upon our `awesomeAMD` module.
+// Notice that there's an additional argument defining our
+// module's dependencies now:
+define('loudmouth', ['awesomeAMD'], function(awesomeAMD){
+ // dependencies will be passed to the factory's arguments
+ // in the order they are specified
+ var tellEveryone = function(){
+ if (awesomeAMD()){
+ alert('This is sOoOo rad!');
+ } else {
+ alert('Pretty dull, isn\'t it?');
+ }
+ };
+ return tellEveryone;
+});
+
+// As we do know how to use define now, let's use `require` to
+// kick off our program. `require`'s signature is `(arrayOfDependencies, callback)`.
+require(['loudmouth'], function(loudmouth){
+ loudmouth();
+});
+
+// To make this tutorial run code, let's implement a very basic
+// (non-asynchronous) version of AMD right here on the spot:
+function define(name, deps, factory){
+ // notice how modules without dependencies are handled
+ define[name] = require(factory ? deps : [], factory || deps);
+}
+
+function require(deps, callback){
+ var args = [];
+ // first let's retrieve all the dependencies needed
+ // by the require call
+ for (var i = 0; i < deps.length; i++){
+ args[i] = define[deps[i]];
+ }
+ // satisfy all the callback's dependencies
+ return callback.apply(null, args);
+}
+// you can see this code in action here: http://jsfiddle.net/qap949pd/
+```
+
+### Real-world usage with require.js
+
+In contrast to the introductory example, `require.js` (the most popular AMD library) actually implements the **A** in **AMD**, enabling you to load modules and their dependencies asynchronously via XHR:
+
+```javascript
+/* file: app/main.js */
+require(['modules/someClass'], function(SomeClass){
+ // the callback is deferred until the dependency is loaded
+ var thing = new SomeClass();
+});
+console.log('So here we are, waiting!'); // this will run first
+```
+
+By convention, you usually store one module in one file. `require.js` can resolve module names based on file paths, so you don't have to name your modules, but can simply reference them using their location. In the example `someClass` is assumed to be in the `modules` folder, relative to your configuration's `baseUrl`:
+
+* app/
+ * main.js
+ * modules/
+ * someClass.js
+ * someHelpers.js
+ * ...
+ * daos/
+ * things.js
+ * ...
+
+This means we can define `someClass` without specifying a module id:
+
+```javascript
+/* file: app/modules/someClass.js */
+define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
+ // module definition, of course, will also happen asynchronously
+ function SomeClass(){
+ this.method = function(){/**/};
+ // ...
+ }
+ return SomeClass;
+});
+```
+To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`:
+
+```javascript
+/* file: main.js */
+requirejs.config({
+ baseUrl : 'app',
+ paths : {
+ // you can also load modules from other locations
+ jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+});
+require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){
+ // a `main` file needs to call require at least once,
+ // otherwise no code will ever run
+ coolLib.doFancyStuffWith(helpers.transform($('#foo')));
+});
+```
+`require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>A hundred script tags? Never again!</title>
+</head>
+<body>
+ <script src="require.js" data-main="app/main"></script>
+</body>
+</html>
+```
+
+### Optimizing a whole project using r.js
+
+Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load.
+
+`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption.
+
+Install it using `npm`:
+```shell
+$ npm install requirejs -g
+```
+
+Now you can feed it with a configuration file:
+```shell
+$ r.js -o app.build.js
+```
+
+For our above example the configuration might look like:
+```javascript
+/* file : app.build.js */
+({
+ name : 'main', // name of the entry point
+ out : 'main-built.js', // name of the file to write the output to
+ baseUrl : 'app',
+ paths : {
+ // `empty:` tells r.js that this should still be loaded from the CDN, using
+ // the location specified in `main.js`
+ jquery : 'empty:',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+})
+```
+
+To use the built file in production, simply swap `data-main`:
+```html
+<script src="require.js" data-main="app/main-built"></script>
+```
+
+An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo.
+
+### Topics not covered in this tutorial
+* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html)
+* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html)
+* [Advanced configuration](http://requirejs.org/docs/api.html#config)
+* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim)
+* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss)
+* [Using almond.js for builds](https://github.com/jrburke/almond)
+
+### Further reading:
+
+* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD)
+* [Why AMD?](http://requirejs.org/docs/whyamd.html)
+* [Universal Module Definition](https://github.com/umdjs/umd)
+
+### Implementations:
+
+* [require.js](http://requirejs.org)
+* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
+* [cujo.js](http://cujojs.com/)
+* [curl.js](https://github.com/cujojs/curl)
+* [lsjs](https://github.com/zazl/lsjs)
+* [mmd](https://github.com/alexlawrence/mmd)
diff --git a/bash.html.markdown b/bash.html.markdown index dc7d32b6..11c1f3a2 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -9,6 +9,7 @@ contributors: - ["akirahirose", "https://twitter.com/akirahirose"] - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] filename: LearnBash.sh --- @@ -199,4 +200,12 @@ sort file.txt uniq -d file.txt # prints only the first column before the ',' character cut -d ',' -f 1 file.txt +# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) +sed -i 's/okay/great/g' file.txt +# print to stdout all lines of file.txt which match some regex, the example prints lines which begin with "foo" and end in "bar" +grep "^foo.*bar$" file.txt +# pass the option "-c" to instead print the number of lines matching the regex +grep -c "^foo.*bar$" file.txt +# if you literally want to search for the string, and not the regex, use fgrep (or grep -F) +fgrep "^foo.*bar$" file.txt ``` diff --git a/c++.html.markdown b/c++.html.markdown index 5bf7e2ea..9f357b08 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -3,346 +3,588 @@ language: c++ filename: learncpp.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] lang: en --- -I am writing this to highlight the differences and -additions that C++ has with respect to C. My -suggestion would be to follow the C tutorial first -then look here for the additions and differences. +C++ is a systems programming language that, +[according to its inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +was designed to + +- be a "better C" +- support data abstraction +- support object-oriented programming +- support generic programming + +Though its syntax can be more difficult or complex than newer languages, +it is widely used because it compiles to native instructions that can be +directly run by the processor and offers tight control over hardware (like C) +while offering high-level features such as generics, exceptions, and classes. +This combination of speed and functionality makes C++ +one of the most widely-used programming languages. ```c++ -/////////////////////////////////////// -// C++ differences -/////////////////////////////////////// +////////////////// +// Comparison to C +////////////////// + +// C++ is _almost_ a superset of C and shares its basic syntax for +// variable declarations, primitive types, and functions. +// However, C++ varies in some of the following ways: + +// A main() function in C++ should return an int, +// though void main() is accepted by most compilers (gcc, clang, etc.) +// This value serves as the program's exit status. +// See http://en.wikipedia.org/wiki/Exit_status for more information. +int main(int argc, char** argv) +{ + // Command line arguments are passed in by argc and argv in the same way + // they are in C. + // argc indicates the number of arguments, + // and argv is an array of C-style strings (char*) + // representing the arguments. + // The first argument is the name by which the program was called. + // argc and argv can be omitted if you do not care about arguments, + // giving the function signature of int main() + + // An exit status of 0 indicates success. + return 0; +} +// In C++, character literals are one byte. +sizeof('c') == 1 -//In C++ -//cannot use void main() -int main() { //or int main(int argc, char **argv) - //cannot end with return; - return 0; - //Can also end without return statement -} - -//In C++ -/* - //This could lead to compiler errors and is discouraged - //#if 0 #endif pairs are encouraged instead -*/ - -//In C++ -sizeof(10) //Typically 4 -sizeof('c') == 1 +// In C, character literals are the same size as ints. +sizeof('c') == sizeof(10) -//In C -sizeof('c') == sizeof(10) //true chars are passed as ints +// C++ has strict prototyping +void func(); // function which accepts no arguments -//In C++ strict prototyping -void func(); //function which accepts no arguments +// In C +void func(); // function which may accept any number of arguments -//In C -void func(); //function which may accept arguments - - -//In C++ -for(int i = 0; i < 10; i++) {;} -//In C must int i must be declared before +// Use nullptr instead of NULL in C++ +int* ip = nullptr; +// C standard headers are available in C++, +// but are prefixed with "c" and have no .h suffix. +#include <cstdio> -//C++ Supports Function overloading -//Provided each function takes different -//parameters +int main() +{ + printf("Hello, world!\n"); + return 0; +} -void printing(char const *myString) -{printf("String %s\n",myString);} //Hello +/////////////////////// +// Function overloading +/////////////////////// -void printing(int myInt) -{printf("My int is %d",myInt);} //15 +// C++ supports function overloading +// provided each function takes different parameters. -int main () -{ - printing("Hello"); - printing(15); -} - +void print(char const* myString) +{ + printf("String %s\n", myString); +} +void print(int myInt) +{ + printf("My int is %d", myInt); +} -//C++ Default Function Arguments -void two_ints(int a = 1, int b = 4); +int main() +{ + print("Hello"); // Resolves to void print(const char*) + print(15); // Resolves to void print(int) +} -int main() -{ - two_ints(); // arguments: 1, 4 - two_ints(20); // arguments: 20, 4 - two_ints(20, 5); // arguments: 20, 5 -} +///////////////////////////// +// Default function arguments +///////////////////////////// +// You can provide default arguments for a function +// if they are not provided by the caller. -//C++ added the nullptr which is different from 0 -int *ip = nullptr; // OK -int value = nullptr; // error: value is no pointer +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Do something with the ints here +} +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} -/////////////////////////////////////// -// C++ Additions ontop of C -/////////////////////////////////////// +// Default arguments must be at the end of the arguments list. +void invalidDeclaration(int a = 1, int b) // Error! +{ +} -/////////////////////////////////////// -// C++ Namespace -/////////////////////////////////////// -//Namespaces allow you to define your own -//functions and variables for use +///////////// +// Namespaces +///////////// + +// Namespaces provide separate scopes for variable, function, +// and other declarations. +// Namespaces can be nested. + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // end namespace Nested +} // end namespace First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} -// Use '::' to change variable (or function) scope -// Putting '::' before a function or variable will -// reference a global scope +void foo() +{ + printf("This is global foo\n"); +} -// This allows you to make normal c library calls -// std is for standard library -using namespace std; +int main() +{ + // Assume everything is from the namespace "Second" + // unless otherwise specified. + using namespace Second; -#include <stdio.h> + foo(); // prints "This is Second::foo" + First::Nested::foo(); // prints "This is First::Nested::foo" + ::foo(); // prints "This is global foo" +} -int counter = 50; // global variable +/////////////// +// Input/Output +/////////////// -int main() -{ - for (int counter = 1; // this refers to the - counter < 2; // local variable - counter++) - { - printf("Global var %d local var %d\n", - ::counter, // global variable - counter); // local variable - // => Global var 50 local var 1 - } -} +// C++ input and output uses streams +// cin, cout, and cerr represent stdin, stdout, and stderr. +// << is the insertion operator and >> is the extraction operator. -// Namespaces can be nested +#include <iostream> // Include for I/O streams +using namespace std; // Streams are in the std namespace (standard library) -namespace myFirstNameSpace -{ - namespace myInnerSoul - { - cos(int x) - { - printf("My inner soul was made to program."); - } - } -} +int main() +{ + int myInt; -namespace anotherNameSpace -{ - cos(int x) {;} //does nothing -} - -int main() -{ - //Specify the full path because main is outside of both namespaces. - //Will print out My inner soul was made to program. - myFirstNameSpace::myInnerSoul::cos(60); -} + // Prints to stdout (or terminal/screen) + cout << "Enter your favorite number:\n"; + // Takes in input + cin >> myInt; + // cout can also be formatted + cout << "Your favorite number is " << myInt << "\n"; + // prints "Your favorite number is <myInt>" -/////////////////////////////////////// -// C++ Strings -/////////////////////////////////////// + cerr << "Used for error messages"; +} -//Strings in C++ are Objects and have many functions -myString = "Hello"; -myOtherString = " World"; +////////// +// Strings +////////// -myString + myOtherString; // => "Hello World" +// Strings in C++ are objects and have many member functions +#include <string> -myString + ' You'; // => "Hello You" +using namespace std; // Strings are also in the namespace std (standard library) -myString != myOtherString; //True +string myString = "Hello"; +string myOtherString = " World"; -//An example of a string method -myString.append(" Dog"); // => "Hello Dog" +// + is used for concatenation. +cout << myString + myOtherString; // "Hello World" +cout << myString + " You"; // "Hello You" -/////////////////////////////////////// -// C++ Input Output -/////////////////////////////////////// +// C++ strings are mutable and have value semantics. +myString.append(" Dog"); +cout << myString; // "Hello Dog" -//C++ input and output streams -//cin, cout, cerr, << is insertion and >> is extraction operator -#include <iostream> -using namespace std; +///////////// +// References +///////////// -int main() -{ +// In addition to pointers like the ones in C, +// C++ has _references_. +// These are pointer types that cannot be reassigned once set +// and cannot be null. +// They also have the same syntax as the variable itself: +// No * is needed for dereferencing and +// & (address of) is not used for assignment. - int myInt; - - //Prints to stdout (or terminal/screen) - cout << "Enter your fav number:\n"; - //Takes in input - cin >> myInt; +using namespace std; - //cout can also be formatted - cout << "Your fav number is " << myInt << "\n"; - //Your fav number is ## +string foo = "I am foo"; +string bar = "I am bar"; - cerr << "Used for error messages"; -} +string& fooRef = foo; // This creates a reference to foo. +fooRef += ". Hi!"; // Modifies foo through the reference +cout << fooRef; // Prints "I am foo. Hi!" -/////////////////////////////////////// -// C++ Classes -/////////////////////////////////////// +fooRef = bar; // Error: references cannot be reassigned. +const string& barRef = bar; // Create a const reference to bar. +// Like C, const values (and pointers and references) cannot be modified. +barRef += ". Hi!"; // Error, const references cannot be modified. -//First example of classes -#include <iostream> +////////////////////////////////////////// +// Classes and object-oriented programming +////////////////////////////////////////// -//define a class -class Doggie -{ - std::string name; - int weight; +// First example of classes +#include <iostream> - // These are only the declarations - //Can also have private and protected - public: - //The public methods (can also include variables) +// Declare a class. +// Classes are usually declared in header (.h or .hpp) files. +class Dog { + // Member variables and functions are private by default. + std::string name; + int weight; - // Default constructor - Doggie(); +// All members following this are public +// until "private:" or "protected:" is found. +public: - void setName(std::string dogsName); - void setWeight(int dogsWeight); - void printDog(); + // Default constructor + Dog(); - //Can define functions within class declaration too - void dogBark() {std::cout << "Bark Bark\n"} + // Member function declarations (implementations to follow) + // Note that we use std::string here instead of placing + // using namespace std; + // above. + // Never put a "using namespace" statement in a header. + void setName(const std::string& dogsName); - //Destructors are methods that free the allocated space - ~doggieDestructor(); - //if no destructor compiler defines the trivial destructor + void setWeight(int dogsWeight); -//Classes are similar to structs and must close the } with ; -}; + // Functions that do not modify the state of the object + // should be marked as const. + // This allows you to call them if given a const reference to the object. + // Also note the functions must be explicitly declared as _virtual_ + // in order to be overridden in derived classes. + // Functions are not virtual by default for performance reasons. + virtual void print() const; -// This is the implementation of the class methods -// Also called the definition -void Doggie::Doggie () { - std::cout << "A doggie is born. Woof!\n"; -} - -void Doggie::setName (std::string doggie_name) { - name = doggie_name; -} + // Functions can also be defined inside the class body. + // Functions defined as such are automatically inlined. + void bark() const { std::cout << name << " barks!\n" } -void Doggie::setWeight (int doggie_weight) { - weight = doggie_weight; -} + // Along with constructors, C++ provides destructors. + // These are called when an object is deleted or falls out of scope. + // This enables powerful paradigms such as RAII + // (see below) + // Destructors must be virtual to allow classes to be derived from this one. + virtual ~Dog(); -void Doggie::printDog () { - std::cout << "Dog is " << name << " weighs" << weight << "\n"; -} +}; // A semicolon must follow the class definition. -void Doggie::~doggieDestructor () { - delete[] name; - delete weight; -} +// Class member functions are usually implemented in .cpp files. +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} -int main () { - Doggie deedee; // prints out a doggie is born. Woof! - deedee.setName ("Barkley"); - deedee.setWeight(1000000); - deedee.printDog; - //prints => Dog is Barkley weighs 1000000 - return 0; -} +// Objects (such as strings) should be passed by reference +// if you are modifying them or const reference if you are not. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} -//C++ Class inheritance +// Notice that "virtual" is only needed in the declaration, not the definition. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} -class German_Sheperd : public Doggie +void Dog::~Dog() { - //This class now inherits everything public and protected from Doggie class - - //Good practice to put d_ in front of datatypes in classes - std::string d_type; - - public: - void dogType() {d_type = "German Sheperd";} -}; - - - -/////////////////////////////////////// -// C++ Exception Handling -/////////////////////////////////////// - -try { - throw 12.25; // throws a double no handler declared -} catch (int errorNum) -{ - std::cout << "I caught an int " << errorNum << "\n"; -//default catcher -} catch (...) -{ - std::cout << "I got an error. Not sure what but I can pass it up."; - throw; -} - - -/////////////////////////////////////// -// C++ Operator Overloading -/////////////////////////////////////// - -// In C++ you can overload operators such as +, -, new, etc. - -#include <iostream> -using namespace std; - -class Vector { - public: - double x,y; - Vector () {}; - Vector (double a, double b) : x(a), y(b) {} - Vector operator + (const CVector&); - Vector operator += (const CVector&); -}; - -Vector Vector::operator+ (const Vector& rhs) -{ - Vector temp; - temp.x = x + rhs.x; - temp.y = y + rhs.y; - return temp; -} - -Vector Vector::operator+= (const Vector& rhs) -{ - x += rhs.x; - y += rhs.y; - return *this; -} - -int main () { - Vector up (0,1); - Vector right (1,0); - Vector result; - // This calls the Vector + operator - // Vector up calls the + (function) with right as its paramater - result = up + right; - // prints out => Result is upright (1,1) - cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; - return 0; + cout << "Goodbye " << name << "\n"; } +int main() { + Dog myDog; // prints "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg" + return 0; +} // prints "Goodbye Barkley" + +// Inheritance: + +// This class inherits everything public and protected from the Dog class +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // Override the behavior of the print function for all OwnedDogs. See + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // for a more general introduction if you are unfamiliar with + // subtype polymorphism. + // The override keyword is optional but makes sure you are actually + // overriding the method in a base class. + void print() const override; + +private: + std::string owner; +}; + +// Meanwhile, in the corresponding .cpp file: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Call the print function in the base Dog class + std::cout << "Dog is owned by " << owner << "\n"; + // Prints "Dog is <name> and weights <weight>" + // "Dog is owned by <owner>" +} + +////////////////////////////////////////// +// Initialization and Operator Overloading +////////////////////////////////////////// + +// In C++ you can overload the behavior of operators such as +, -, *, /, etc. +// This is done by defining a function which is called +// whenever the operator is used. + +#include <iostream> +using namespace std; + +class Point { +public: + // Member variables can be given default values in this manner. + double x = 0; + double y = 0; + + // Define a default constructor which does nothing + // but initialize the Point to the default value (0, 0) + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* Do nothing except initialize the values */ } + + // Overload the + operator. + Point operator+(const Point& rhs) const; + + // Overload the += operator + Point& operator+=(const Point& rhs); + + // It would also make sense to add the - and -= operators, + // but we will skip those for brevity. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Create a new point that is the sum of this one and rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // This calls the Point + operator + // Point up calls the + (function) with right as its paramater + Point result = up + right; + // Prints "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////// +// Exception Handling +///////////////////// + +// The standard library provides a few exception types +// (see http://en.cppreference.com/w/cpp/error/exception) +// but any type can be thrown an as exception +#include <exception> + +// All exceptions thrown inside the _try_ block can be caught by subsequent +// _catch_ handlers. +try { + // Do not allocate exceptions on the heap using _new_. + throw std::exception("A problem occurred"); +} +// Catch exceptions by const reference if they are objects +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Catches any exception not caught by previous _catch_ blocks +} catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // Re-throws the exception +} + +/////// +// RAII +/////// + +// RAII stands for Resource Allocation Is Initialization. +// It is often considered the most powerful paradigm in C++, +// and is the simple concept that a constructor for an object +// acquires that object's resources and the destructor releases them. + +// To understand how this is useful, +// consider a function that uses a C file handle: +void doSomethingWithAFile(const char* filename) +{ + // To begin with, assume nothing can fail. + + FILE* fh = fopen(filename, "r"); // Open the file in read mode. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Close the file handle. +} + +// Unfortunately, things are quickly complicated by error handling. +// Suppose fopen can fail, and that doSomethingWithTheFile and +// doSomethingElseWithIt return error codes if they fail. +// (Exceptions are the preferred way of handling failure, +// but some programmers, especially those with a C background, +// disagree on the utility of exceptions). +// We now have to check each call for failure and close the file handle +// if a problem occurred. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) // The returned pointer is null on failure. + reuturn false; // Report that failure to the caller. + + // Assume each function returns false if it failed + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + + fclose(fh); // Close the file handle so it doesn't leak. + return true; // Indicate success +} + +// C programmers often clean this up a little bit using goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + reuturn false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indicate success + +failure: + fclose(fh); + return false; // Propagate the error +} + +// If the functions indicate errors using exceptions, +// things are a little cleaner, but still sub-optimal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) + throw std::exception("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Be sure to close the file if an error occurs. + throw; // Then re-throw the exception. + } + + fclose(fh); // Close the file + // Everything succeeded +} + +// Compare this to the use of C++'s file stream class (fstream) +// fstream uses its destructor to close the file. +// Recall from above that destructors are automatically called +// whenver an object falls out of scope. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream is short for input file stream + std::ifstream fh(filename); // Open the file + + // Do things with the file + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // The file is automatically closed here by the destructor + +// This has _massive_ advantages: +// 1. No matter what happens, +// the resource (in this case the file handle) will be cleaned up. +// Once you write the destructor correctly, +// It is _impossible_ to forget to close the handle and leak the resource. +// 2. Note that the code is much cleaner. +// The destructor handles closing the file behind the scenes +// without you having to worry about it. +// 3. The code is exception safe. +// An exception can be thrown anywhere in the function and cleanup +// will still occur. + +// All idiomatic C++ code uses RAII extensively for all resources. +// Additional examples include +// - Memory using unique_ptr and shared_ptr +// - Containers - the standard library linked list, +// vector (i.e. self-resizing array), hash maps, and so on +// all automatically destroy their contents when they fall out of scope. +// - Mutexes using lock_guard and unique_lock ``` -Futher Reading +Futher Reading: + +An up-to-date language reference can be found at +<http://cppreference.com/w/cpp> -for more resources see: http://www.icce.rug.nl/documents/cplusplus/ -for other reference material: http://www.cplusplus.com/doc/tutorial/ +Additional resources may be found at <http://cplusplus.com> diff --git a/c.html.markdown b/c.html.markdown index 10e6fa45..6daabe94 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adam Bard", "http://adambard.com/"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] + - ["Marco Scannadinari", "https://marcoms.github.io"] --- @@ -21,6 +22,10 @@ memory management and C will take you as far as you need to go. Multi-line comments look like this. They work in C89 as well. */ +/* +Multi-line comments don't nest /* Be careful */ // comment ends on this line... +*/ // ...not this one! + // Constants: #define <keyword> #define DAYS_IN_YEAR 365 @@ -74,10 +79,10 @@ int main() { long long x_long_long = 0; // floats are usually 32-bit floating point numbers - float x_float = 0.0; + float x_float = 0.0f; // 'f' suffix here denotes floating point literal // doubles are usually 64-bit floating-point numbers - double x_double = 0.0; + double x_double = 0.0; // real numbers without any suffix are doubles // Integral types may be unsigned. unsigned short ux_short; diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 08134e35..c4ecb5e8 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -431,7 +431,7 @@ nil ; for false - and the empty list :walked (walker (1- n)))) -(walker) ; => :walked +(walker 5) ; => :walked ;; Most of the time, we use DOLIST or LOOP diff --git a/csharp.html.markdown b/csharp.html.markdown index 136f6c50..f6708590 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -508,7 +508,7 @@ on a new line! ""Wow!"", the masses cried"; // LINQ - maps a store to IQueryable<T> objects, with delayed execution // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document - var db = new BikeRespository(); + var db = new BikeRepository(); // execution is delayed, which is great when querying a database var filter = db.Bikes.Where(b => b.HasTassles); // no query run @@ -767,9 +767,9 @@ on a new line! ""Wow!"", the masses cried"; /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// </summary> - public class BikeRespository : DbSet + public class BikeRepository : DbSet { - public BikeRespository() + public BikeRepository() : base() { } diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index df6267f9..2c548961 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell lang: de-de contributors: - ["Adit Bhargava", "http://adit.io"] diff --git a/elixir.html.markdown b/elixir.html.markdown index c0abc815..0a20e3df 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -2,6 +2,7 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] filename: learnelixir.ex --- @@ -59,7 +60,7 @@ tail #=> [2,3] # the tuples have different sizes. # {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} -# There's also binaries +# There are also binaries <<1,2,3>> # binary # Strings and char lists @@ -108,7 +109,7 @@ div(10, 2) #=> 5 # To get the division remainder use `rem` rem(10, 3) #=> 1 -# There's also boolean operators: `or`, `and` and `not`. +# There are also boolean operators: `or`, `and` and `not`. # These operators expect a boolean as their first argument. true and true #=> true false or true #=> true @@ -119,7 +120,6 @@ false or true #=> true 1 || true #=> 1 false && 1 #=> false nil && 20 #=> nil - !true #=> false # For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` @@ -165,12 +165,12 @@ case {:one, :two} do {:four, :five} -> "This won't match" {:one, x} -> - "This will match and assign `x` to `:two`" + "This will match and bind `x` to `:two`" _ -> "This will match any value" end -# It's common practice to assign a value to `_` if we don't need it. +# It's common to bind the value to `_` if we don't need it. # For example, if only the head of a list matters to us: [head | _] = [1,2,3] head #=> 1 @@ -190,7 +190,7 @@ cond do "But I will" end -# It is common to see a last condition equal to `true`, which will always match. +# It is common to see the last condition equal to `true`, which will always match. cond do 1 + 1 == 3 -> "I will never be seen" @@ -301,7 +301,7 @@ end Recursion.sum_list([1,2,3], 0) #=> 6 # Elixir modules support attributes, there are built-in attributes and you -# may also add custom attributes. +# may also add custom ones. defmodule MyMod do @moduledoc """ This is a built-in attribute on a example module. @@ -312,21 +312,24 @@ defmodule MyMod do end ## --------------------------- -## -- Records and Exceptions +## -- Structs and Exceptions ## --------------------------- -# Records are basically structures that allow you to associate a name with -# a particular value. -defrecord Person, name: nil, age: 0, height: 0 +# Structs are extensions on top of maps that bring default values, +# compile-time guarantees and polymorphism into Elixir. +defmodule Person do + defstruct name: nil, age: 0, height: 0 +end -joe_info = Person.new(name: "Joe", age: 30, height: 180) -#=> Person[name: "Joe", age: 30, height: 180] +joe_info = %Person{ name: "Joe", age: 30, height: 180 } +#=> %Person{age: 30, height: 180, name: "Joe"} # Access the value of name joe_info.name #=> "Joe" # Update the value of age -joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] +older_joe_info = %{ joe_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Joe"} # The `try` block with the `rescue` keyword is used to handle exceptions try do @@ -394,5 +397,7 @@ self() #=> #PID<0.27.0> * [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) * [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) * ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert -* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 41a7c68b..203ee3bb 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -1,8 +1,9 @@ --- -language: julia +language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] - - ["Guillermo Garza" ] +translators: + - ["Guillermo Garza", "http://github.com/ggarza"] filename: learnjulia-es.jl lang: es-es --- diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown new file mode 100644 index 00000000..3882734d --- /dev/null +++ b/fr-fr/brainfuck-fr.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +filename: learnbrainfuck-fr.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Baptiste Fontaine", "http://bfontaine.net"] +lang: fr-fr +--- + +Brainfuck (sans majuscule à part au début d’une phrase) est un langage +Turing-complet extrêmement simple avec seulement 8 commandes. + +``` +Tout caractère en dehors de "><+-.,[]" (en dehors des guillements) est ignoré. + +Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et +un pointeur de données pointant sur la cellule courante. + +Il y a huit commandes : ++ : Incrémente la valeur de la cellule courante de un. +- : Décrémente la valeur de la cellule courante de un. +> : Déplace le pointeur de données sur la cellule suivante (à droite). +< : Déplace le pointeur de données sur la cellule précédente (à gauche). +. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A'). +, : Lit un caractère et le place dans la cellule courante. +[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant. + Sinon, continue avec la commande suivante. +] : Si la valeur dans la cellule courante vaut 0, continue avec la commande + suivante. Sinon, retourne au [ correspondant. + +[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment +aller par paires. + +Regardons quelques programmes simples en brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ce programme affiche la lettre 'A'. Il commence par incrémenter la première +cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde +cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la +décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6 +décrémentations de la première cellule pour la faire atteindre 0, ce qui fait +sortir de la boucle). + +À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0, +tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur +celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur. +En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. + +, [ > + < - ] > . + +Ce programme lit un caractère sur l’entrée standard et le copie dans la +première cellule. Il commence ensuite une boucle : il bouge sur la seconde +cellule, incrémente sa valeur, retourne sur la première et décrémente sa +valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0, +et que la seconde cellule contienne l’ancienne valeur de la première. Comme +nous sommes sur la première cellule à la fin de la boucle, il bouge sur la +seconde et affiche sa valeur en ASCII. + +Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité, +vous pourriez tout aussi aisément écrire le programme comme ceci : + +,[>+<-]>. + +Essayez et devinez ce que ce programme fait : + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ce programme prend deux nombres en entrée, et les multiplie. + +Il commence par lire deux entrées, puis commence une boucle externe, qui a une +condition sur la première cellule. Il bouge ensuite sur la seconde, et commence +une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a +cependant un problème : à la fin de la boucle interne, la valeur de la seconde +cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une +seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième +cellule, puis recopions sa valeur dans la seconde cellule. +À la fin, la troisième cellule contient le résultat de la multiplication. +``` + +Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez +écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck +dans un autre langage. L’interpréteur est relativement simple à implémenter, +mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en… +brainfuck. diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown index 989db1d5..d9d3151f 100644 --- a/fr-fr/haskell.html.markdown +++ b/fr-fr/haskell.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] translators: diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index 922d6ebc..b4e2a161 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua filename: learnlua-fr.lua contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown new file mode 100644 index 00000000..e3ac5a92 --- /dev/null +++ b/fr-fr/markdown.html.markdown @@ -0,0 +1,288 @@ +--- +language: markdown +contributors: +- ["Andrei Curelaru", "http://www.infinidad.fr"] +filename: markdown.md +--- + +Markdown a été créé par Jhon Gruber en 2004. Il se veut être d'une syntaxe +facile à lire et à écrire, aisément convertible en HTML + (et beaucoup d'autres formats aussi à présent). + +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request! + + +```markdown +<!-- Markdown est une sorte de cousin du HTML, si bien que tout document HTML +est un document Markdown valide. Autrement dit, vous pouvez utiliser des +balises HTML dans un fichier Markdown, comme la balise commentaire dans +laquelle nous sommes à présent, car celle-ci ne sera pas affectée par +le parser( analyseur syntaxique ) Markdown. --> + +<!-- Toutefois, si vous voulez créer un élément HTML dans un fichier Markdown, + vous ne pourrez pas utiliser du Markdown à l'intérieur de ce dernier. --> + +<!-- Le Markdown est implémenté de différentes manières, selon le parser. +Ce guide va alors tenter de trier les fonctionnalités universelles de celles +spécifiques à un parser. --> + +<!-- Headers ( En-têtes ) --> +<!-- Vous pouvez facilement créer des éléments HTML <h1> à <h6> en précédant + le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, + selon le niveau de titre souhaité. --> +# Ceci est un <h1> +## Ceci est un <h2> +### Ceci est un <h3> +#### Ceci est un <h4> +##### Ceci est un <h5> +###### Ceci est un <h6> + +<!-- +Markdown fournit également une façon alternative de marquer les h1 et h2 +--> + +Ceci est un h1 +============= + +Ceci est un h2 +------------- + +<!-- Styles basiques pour du texte --> +<!-- On peut facilement rendre un texte "gras" ou "italique" en Markdown --> + +*Ce texte est en italique.* +_Celui-ci aussi._ + +**Ce texte est en gras.** +__Celui-là aussi.__ + +***Ce texte a les deux styles.*** +**_Pareil ici_** +*__Et là!__* + +<!-- Dans le "Github Flavored Markdown", utilisé pour interpréter le Markdown +sur Github, on a également le strikethrough ( texte barré ) : --> + +~~Ce texte est barré avec strikethrough.~~ + +<!-- Les Paragraphes sont représentés par une ou plusieurs lignes de texte +séparées par une ou plusieurs lignes vides. --> + +Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? + +Maintenant je suis dans le paragraphe 2. +Je suis toujours dans le paragraphe 2! + + +Puis là, eh oui, le paragraphe 3! + +<!-- +Si jamais vous souhaitez insérer une balise HTML <br />, vous pouvez ajouter +un ou plusieurs espaces à la fin de votre paragraphe, et en commencer +un nouveau. +--> + +J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). + +Bigre, il y a un <br /> au dessus de moi! + +<!-- Les 'Blocs de Citations' sont générés aisément, grâce au caractère > --> + +> Ceci est une superbe citation. Vous pouvez même +> revenir à la ligne quand ça vous chante, et placer un `>` +> devant chaque bout de ligne faisant partie +> de la citation. +> La taille ne compte pas^^ tant que chaque ligne commence par un `>`. + +> Vous pouvez aussi utiliser plus d'un niveau +>> d'imbrication! +> Classe et facile, pas vrai? + +<!-- les Listes --> +<!-- les Listes non ordonnées sont marquées par des asterisques, +signes plus ou signes moins. --> + +* Item +* Item +* Un autre item + +ou + ++ Item ++ Item ++ Encore un item + +ou + +- Item +- Item +- Un dernier item + +<!-- les Listes Ordonnées sont générées via un nombre suivi d'un point --> + +1. Item un +2. Item deux +3. Item trois + +<!-- Vous pouvez même vous passer de tout numéroter, et Markdown générera +les bons chiffres. Ceci dit, cette variante perd en clarté.--> + +1. Item un +1. Item deux +1. Item trois +<!-- ( cette liste sera interprétée de la même façon que celle au dessus ) --> + +<!-- Vous pouvez également utiliser des sous-listes --> + +1. Item un +2. Item deux +3. Item trois +* Sub-item +* Sub-item +4. Item quatre + +<!-- Il y a même des "listes de Taches". Elles génèrent des champs HTML +de type checkbox. --> + +Les [ ] ci dessous, n'ayant pas de [ x ], +deviendront des cases à cocher HTML non-cochées. + +- [ ] Première tache à réaliser. +- [ ] Une autre chose à faire. +La case suivante sera une case à cocher HTML cochée. +- [x] Ça ... c'est fait! + +<!-- les Blocs de Code --> +<!-- Pour marquer du texte comme étant du code, il suffit de commencer +chaque ligne en tapant 4 espaces (ou un Tab) --> + + echo "Ça, c'est du Code!"; + var Ça = "aussi !"; + +<!-- L'indentation par tab ou série de quatre espaces +fonctionne aussi à l'intérieur du bloc de code --> + + my_array.each do |item| + puts item + end + +<!-- Des bouts de code en mode 'inline' s'ajoutent en les entourant de ` --> + +La fonction `run()` ne vous oblige pas à aller courir! + +<!-- Via Github Flavored Markdown, vous pouvez utiliser +des syntaxes spécifiques --> + +\`\`\`ruby +<!-- mais enlevez les backslashes quand vous faites ça, +gardez juste ```ruby ( ou nom de la synatxe correspondant à votre code )--> +def foobar +puts "Hello world!" +end +\`\`\` <!-- pareil, pas de backslashes, juste ``` en guise de fin --> + +<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github +va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> + +<!-- Ligne Horizontale (<hr />) --> +<!-- Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets, +avec ou sans espaces entre chaque un. --> + +*** +--- +- - - +**************** + +<!-- Liens --> +<!-- Une des fonctionnalités sympathiques du Markdown est la facilité +d'ajouter des liens. Le texte du lien entre [ ], l'url entre ( ), +et voilà l'travail. +--> + +[Clic moi!](http://test.com/) + +<!-- +Pour ajouter un attribut Title, collez le entre guillemets, avec le lien. +--> + +[Clic moi!](http://test.com/ "Lien vers Test.com") + +<!-- les Liens Relatifs marchent aussi --> + +[En avant la musique](/music/). + +<!-- Les liens façon "références" sont eux aussi disponibles en Markdown --> + +[Cliquez ici][link1] pour plus d'information! +[Regardez aussi par ici][foobar] si vous voulez. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + +<!-- Le titre peut aussi être entouré de guillemets simples, +entre parenthèses ou absent. Les références peuvent être placées +un peu où vous voulez dans le document, et les identifiants +(link1, foobar, ...) quoi que ce soit tant qu'ils sont uniques --> + +<!-- Il y a également le "nommage implicite" qui transforme le texte du lien + en identifiant --> + +[Ceci][] est un lien. + +[ceci]: http://ceciestunlien.com/ + +<!-- mais ce n'est pas beaucoup utilisé. --> + +<!-- Images --> +<!-- Pour les images, la syntaxe est identique aux liens, sauf que précédée + d'un point d'exclamation! --> + +![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") + +<!-- Là aussi, on peut utiliser le mode "références" --> + +![Ceci est l'attribut ALT de l'image][monimage] + +[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." + +<!-- Divers --> +<!-- Liens Automatiques --> + +<http://testwebsite.com/> est équivalent à : +[http://testwebsite.com/](http://testwebsite.com/) + +<!-- Liens Automatiques pour emails --> + +<foo@bar.com> + +<!-- Escaping --> +Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ + +Pour taper *ce texte* entouré d'astérisques mais pas en italique : +Tapez \*ce texte\*. + +<!-- Tableaux --> +<!-- les Tableaux ne sont disponibles que dans le Github Flavored Markdown + et c'est ce n'est pas super agréable d'utilisation. + Mais si vous en avez besoin : + --> + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Alignement Gauche | Centé | Alignement Droite | +| bla | bla | bla | + +<!-- ou bien, pour un résultat équivalent : --> + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ough que c'est moche | svp | arrêtez + +<!-- Fin! --> + +``` + +Pour plus d'information : + consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, + et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard.
\ No newline at end of file diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index da562138..a43edf16 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -1,12 +1,11 @@ --- language: Scala -filename: learnscala.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] translators: - - ["Anne-Catherine Dehier", "https://github.com/spellart"] -filename: learn.scala + - ["Anne-Catherine Dehier", "https://github.com/spellart"] +filename: learnscala-fr.scala lang: fr-fr --- diff --git a/fr-fr/xml-fr.html.markdown b/fr-fr/xml-fr.html.markdown new file mode 100644 index 00000000..ed5f55ff --- /dev/null +++ b/fr-fr/xml-fr.html.markdown @@ -0,0 +1,128 @@ +--- +language: xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Geoffrey Liu", "https://github.com/g-liu"] +filename: learnxml-fr.xml +lang: fr-fr +--- + +XML est un langage de balisage conçu pour stocker et transporter les informations. + +Contrairement à HTML, XML ne spécifie pas comment afficher ou formater les informations, juste comment les porter. + +* La syntaxe XML + +```xml +<!-- Les commentaires en XML ressemblent ceci --> + +<?xml version="1.0" encoding="UTF-8"?> +<librairie> + <livre categorie="CUISINE"> + <titre lang="en">Everyday Italian</titre> + <auteur>Giada De Laurentiis</auteur> + <an>2005</an> + <prix>30.00</prix> + </livre> + <livre categorie="ENFANTS"> + <titre lang="en">Harry Potter</titre> + <auteur>J. K. Rowling</auteur> + <an>2005</an> + <prix>29.99</prix> + </livre> + <livre categorie="WEB"> + <titre lang="en">Learning XML</titre> + <auteur>Erik T. Ray</auteur> + <an>2003</an> + <prix>39.95</prix> + </livre> +</librairie> + +<!-- Ce qui suit est un fichier XML typique. + Il commence par une déclaration, qui informe certaines métadonnées (en option). + +XML utilise une structure arborescente. Ci-dessus, le nœud racine est «librairie», qui a + trois nœuds enfants, qui sont appelés «livres». Ces nœuds ont plus de nœuds enfants, et ainsi de suite ... + +On crée les nœuds avec des balises d'ouverture / fermeture, et les enfants sont les nœuds juste entre + les balises d'ouverture et de fermeture. --> + + +<!-- XML porte deux types d'informations: + 1 - Les attributs -> les métadonnées sur un nœud. + Habituellement, l'analyseur XML utilise cette information pour bien stocker les données. + 2 - Les éléments -> les informations pures. + C'est ce que l'analyseur retrouvera du fichier XML. + Les éléments apparaissent entre les balises d'ouverture et de fermeture, sans parenthèses. --> + + +<!-- Ci-dessous, un élément avec deux attributs --> +<fichier type="gif" id="4293">ordinateur.gif</fichier> + + +``` + +* Un document bien formaté & le validation + +Un document XML est bien formaté s'il est syntaxiquement correct. +Cependant, il est possible d'injecter plus de contraintes dans le document, +en utilisant les définitions de documents, tels que les schémas DTD et XML. + +Un document XML qui suit une définition de document est dit valide, +en ce qui concerne ce document. + +Avec cet outil, vous pouvez vérifier les données XML en dehors de la logique de l'application. + +```xml + +<!-- Ci-dessous, vous pouvez voir une version simplifiée du document de librairie, + avec l'addition de définition DTD. --> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "Librairie.dtd"> +<librairie> + <livre categorie="CUISINE"> + <titre>Everyday Italian</titre> + <prix>30.00</prix> + </livre> +</librairie> + +<!-- Cette DTD pourrait être quelque chose comme: --> + +<!DOCTYPE note +[ +<!ELEMENT librairie (livre+)> +<!ELEMENT livre (titre,prix)> +<!ATTLIST livre categorie CDATA "Littérature"> +<!ELEMENT titre (#PCDATA)> +<!ELEMENT prix (#PCDATA)> +]> + +<!-- La DTD commence par une déclaration. + Après, le nœud racine est déclaré, qui exige un ou plusieurs nœuds enfants. + Chaque «livre» doit contenir exactement un «titre» et «prix» et un attribut + appelé «catégorie», avec «littérature» comme valeur par défaut. + Les nœuds de «titre» et «prix» contiennent des informations de caractère analysés + (Anglais: «parsed character data») --> + +<!-- La DTD pourrait être déclarée dans le fichier XML lui-même --> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT librairie (livre+)> +<!ELEMENT livre (titre,prix)> +<!ATTLIST livre categorie CDATA "Littérature"> +<!ELEMENT titre (#PCDATA)> +<!ELEMENT prix (#PCDATA)> +]> + +<librairie> + <livre categorie="CUISINE"> + <titre>Everyday Italian</titre> + <prix>30.00</prix> + </livre> +</librairie> +``` diff --git a/haml.html.markdown b/haml.html.markdown new file mode 100644 index 00000000..aed3dcae --- /dev/null +++ b/haml.html.markdown @@ -0,0 +1,155 @@ +--- +language: haml +filename: learnhaml.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] +--- + +Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of inline code. It is a popular alternative to using Rails templating language (.erb) and allows you to embed Ruby code into your markup. + +It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. + +You can also use Haml on a project independent of Ruby, by installing the Haml gem on your machine and using the command line to convert it to html. + +$ haml input_file.haml output_file.html + + +```haml +/ ------------------------------------------- +/ Indenting +/ ------------------------------------------- + +/ + Because of the importance indentation has on how your code is rendered, the + indents should be consistent throughout the document. Any differences in + indentation will throw an error. It's common-practice to use two spaces, + but it's really up to you, as long as they're constant. + + +/ ------------------------------------------- +/ Comments +/ ------------------------------------------- + +/ This is what a comment looks like in Haml. + +/ + To write a multi line comment, indent your commented code to be + wrapped by the forward slash + +-# This is a silent comment, which means it wont be rendered into the doc at all + + +/ ------------------------------------------- +/ Html elements +/ ------------------------------------------- + +/ To write your tags, use the percent sign followed by the name of the tag +%body + %header + %nav + +/ Notice no closing tags. The above code would output + <body> + <header> + <nav></nav> + </header> + </body> + +/ The div tag is the default element, so they can be written simply like this +.foo + +/ To add content to a tag, add the text directly after the declaration +%h1 Headline copy + +/ To write multiline content, nest it instead +%p + This is a lot of content that we could probably split onto two + separate lines. + +/ + You can escape html by using the ampersand and equals sign ( &= ). This + converts html-sensitive characters (&, /, :) into their html encoded + equivalents. For example + +%p + &= "Yes & yes" + +/ would output 'Yes & yes' + +/ You can unescape html by using the bang and equals sign ( != ) +%p + != "This is how you write a paragraph tag <p></p>" + +/ which would output 'This is how you write a paragraph tag <p></p>' + +/ CSS classes can be added to your tags either by chaining .classnames to the tag +%div.foo.bar + +/ or as part of a Ruby hash +%div{:class => 'foo bar'} + +/ Attributes for any tag can be added in the hash +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ For boolean attributes assign the value 'true' +%input{:selected => true} + +/ To write data-attributes, use the :data key with its value as another hash +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Inserting Ruby +/ ------------------------------------------- + +/ + To output a Ruby value as the contents of a tag, use an equals sign followed + by the Ruby code + +%h1= book.name + +%p + = book.author + = book.publisher + + +/ To run some Ruby code without rendering it to the html, use a hyphen instead +- books = ['book 1', 'book 2', 'book 3'] + +/ Allowing you to do all sorts of awesome, like Ruby blocks +- books.shuffle.each_with_index do |book, index| + %h1= book + + if book do + %p This is a book + +/ + Again, no need to add the closing tags to the block, even for the Ruby. + Indentation will take care of that for you. + + +/ ------------------------------------------- +/ Inline Ruby / Ruby interpolation +/ ------------------------------------------- + +/ Include a Ruby variable in a line of plain text using #{} +%p Your highest scoring game is #{best_game} + + +/ ------------------------------------------- +/ Filters +/ ------------------------------------------- + +/ + Use the colon to define Haml filters, one example of a filter you can + use is :javascript, which can be used for writing inline js + +:javascript + console.log('This is inline <script>'); + +``` + +## Additional resources + +- [What is HAML?](http://haml.info/) - A good introduction that does a much better job of explaining the benefits of using HAML. +- [Official Docs](http://haml.info/docs/yardoc/file.REFERENCE.html) - If you'd like to go a little deeper. diff --git a/haskell.html.markdown b/haskell.html.markdown index e0489710..2785405c 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] --- @@ -171,8 +171,8 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- 4. More functions ---------------------------------------------------- --- currying: if you don't pass in all the arguments to a function, --- it gets "curried". That means it returns a function that takes the +-- partial application: if you don't pass in all the arguments to a function, +-- it gets "partially applied". That means it returns a function that takes the -- rest of the arguments. add a b = a + b diff --git a/javascript.html.markdown b/javascript.html.markdown index 7c869b28..792cab98 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -39,13 +39,14 @@ doStuff() // 1. Numbers, Strings and Operators // JavaScript has one number type (which is a 64-bit IEEE 754 double). -// As with Lua, don't freak out about the lack of ints: doubles have a 52-bit -// mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. +// Doubles have a 52-bit mantissa, which is enough to store integers +// up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 -// All the basic arithmetic works as you'd expect. +// Some basic arithmetic works as you'd expect. 1 + 1; // = 2 +.1 + .2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 @@ -77,13 +78,13 @@ false; !true; // = false !false; // = true -// Equality is == -1 == 1; // = true -2 == 1; // = false +// Equality is === +1 === 1; // = true +2 === 1; // = false -// Inequality is != -1 != 1; // = false -2 != 1; // = true +// Inequality is !== +1 !== 1; // = false +2 !== 1; // = true // More comparisons 1 < 10; // = true @@ -97,11 +98,13 @@ false; // and are compared with < and > "a" < "b"; // = true -// Type coercion is performed for comparisons... +// Type coercion is performed for comparisons with double equals... "5" == 5; // = true +null == undefined; // = true // ...unless you use === "5" === 5; // = false +null === undefined; // = false // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' diff --git a/julia.html.markdown b/julia.html.markdown index feb38463..3a52018c 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -1,5 +1,5 @@ --- -language: julia +language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] filename: learnjulia.jl diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 850587a0..b4a018ef 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua category: language contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown index 80f324f3..1f53221f 100644 --- a/ko-kr/php-kr.html.markdown +++ b/ko-kr/php-kr.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP category: language contributors: - ["Malcolm Fell", "http://emarref.net/"] diff --git a/lua.html.markdown b/lua.html.markdown index be9f3141..0809215f 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] filename: learnlua.lua diff --git a/markdown.html.markdown b/markdown.html.markdown index 3d4d0af6..7541f904 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -126,6 +126,14 @@ render the numbers in order, but this may not be a good idea --> * Sub-item 4. Item four +<!-- There are even task lists. This creates HTML checkboxes. --> + +Boxes below without the 'x' are unchecked HTML checkboxes. +- [ ] First task to complete. +- [ ] Second task that needs done +This checkbox below will be a checked HTML checkbox. +- [x] This task has been completed + <!-- Code blocks --> <!-- You can indicate a code block (which uses the <code> element) by indenting a line with four spaces or a tab --> diff --git a/matlab.html.markdown b/matlab.html.markdown index 9dae8ef2..121f16de 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -40,36 +40,41 @@ ctrl-c % Abort current computation edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window -profile viewer % Open profiler +profile on % turns on the code profiler +profile of % turns off the code profiler +profile viewer % Open profiler -help command % Displays documentation for command in Command Window -doc command % Displays documentation for command in Help Window -lookfor command % Searches for a given command +help command % Displays documentation for command in Command Window +doc command % Displays documentation for command in Help Window +lookfor command % Searches for command in the first commented line of all functions +lookfor command -all % searches for command in all functions % Output formatting -format short % 4 decimals in a floating number -format long % 15 decimals -format bank % only two digits after decimal point - for financial calculations -fprintf +format short % 4 decimals in a floating number +format long % 15 decimals +format bank % only two digits after decimal point - for financial calculations +fprintf('text') % print "text" to the screen +disp('text') % print "text" to the screen % Variables & Expressions -myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 % Calling functions can be done in either of two ways: % Standard function syntax: -load('myFile.mat', 'y') +load('myFile.mat', 'y') % arguments within parantheses, spererated by commas % Command syntax: -load myFile.mat y % no parentheses, and spaces instead of commas +load myFile.mat y % no parentheses, and spaces instead of commas % Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: -[V,D] = eig(A) % this has no equivalent in command form +[V,D] = eig(A); % this has no equivalent in command form +[~,D] = eig(A); % if you only want D and not V @@ -100,6 +105,10 @@ a = {'one', 'two', 'three'} a(1) % ans = 'one' - returns a cell char(a(1)) % ans = one - returns a string +% Structures +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; % Vectors x = [4 32 53 7 1] @@ -160,6 +169,10 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 +% this is the same as +vertcat(A,A); + + [A , A] % Concatenation of matrices (horizontally) %ans = @@ -168,6 +181,8 @@ A(1,:) % All columns in row 1 % 4 5 42 4 5 42 % 7 8 9 7 8 9 +% this is the same as +horzcat(A,A); A(:, [3 1 2]) % Rearrange the columns of original matrix @@ -180,10 +195,13 @@ A(:, [3 1 2]) % Rearrange the columns of original matrix size(A) % ans = 3 3 A(1, :) =[] % Delete the first row of the matrix +A(:, 1) =[] % Delete the first column of the matrix +transpose(A) % Transpose the matrix, which is the same as: +A' ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -transpose(A) % Transpose the matrix, without taking complex conjugate + diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown new file mode 100644 index 00000000..cd12b1d0 --- /dev/null +++ b/nl-nl/brainfuck-nl.html.markdown @@ -0,0 +1,86 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jelle Besseling", "https://github.com/Jell-E"] +lang: nl-nl +--- + +Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een +zin) is een extreem +minimalistische Turing-complete programmeertaal met maar acht commando's. + +``` +Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. + +Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel +gevuld is met nullen en een pointer die wijst naar de huidige cel. + +Dit zijn de acht commando's: ++ : Verhoog de huidige cell met 1. +- : Verminder de huidige cell met 1. +> : Beweeg de pointer naar de volgende cell (één naar rechts). +< : Beweeg de pointer naar de vorige cell (één naar links). +. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A'). +, : Lees een karakter in de huidige cell. +[ : Als de huidige cell nul is ga dan naar de bijbehorende ] . + Als het geen nul is, ga dan gewoon verder. +] : Als de huidige cell nul is ga dan gewoon verder. + Als het geen nul is, ga dan terug naar de bijbehorende [ . + +[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn + +Laten we een kijkje nemen naar een paar brainfuck programma's. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6. +Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat +naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en +verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1 +weer op nul, waarna het doorgaat naar het einde van de loop (]) en +verder gaat). + +De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2 +heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt +het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan +de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal. + + +, [ > + < - ] > . + +Dit programma leest een karakter van de gebruiker in put en kopieert dat +karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in +cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door +totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we +op cel #1 staan verplaatst > de pointer één naar rechts en . print het +karakter in cel #2. + +Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het +bovenstaande programma net zo goed schrijven als: + +,[>+<-]>. + +Probeer maar eens te bedenken wat het volgende programma doet: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Dit programma neemt twee getallen als input, en vermenigvuldigt ze. + +In het begin leest het twee karakters in cel #1 en #2. Dan start het de +buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het +de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar +dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop. +Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal +uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2. +Het resultaat komt in cel #3 te staan. +``` + +En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol +brainfuck programma's gaan schrijven, of je kan een interpreter schrijven +voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te +implementeren aangezien brainfuck maar acht commando's heeft. En als je een +masochist bent kan je ook nog proberen om brainfuck te implementeren… in +brainfuck. diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown index 70dcd463..dc0b1e19 100644 --- a/nl-nl/coffeescript-nl.html.markdown +++ b/nl-nl/coffeescript-nl.html.markdown @@ -5,23 +5,24 @@ contributors: - ["Xavier Yao", "http://github.com/xavieryao"] translators: - ["Jelle Besseling", "https://github.com/Jell-E"] + - ["D.A.W. de Waal", "http://github.com/diodewaal"] filename: coffeescript-nl.coffee lang: nl-nl --- -CoffeeScript is een kleine programmeertaal die compileerd naar JavaScript, -er is geen interpretatie tijdens het uitvoeren. -Als een van de nakomelingen van JavaScript probeert CoffeeScript om leesbare, -goed geformatteerdeen goed draaiende JavaScript code te genereren, -die in elke JavaScript runtime werkt. +CoffeeScript is een kleine programmeertaal die direct compileert naar +JavaScript en er is geen interpretatie tijdens het uitvoeren. +CoffeeScript probeert om leesbare, goed geformatteerde en goed draaiende +JavaScript code te genereren, die in elke JavaScript runtime werkt, als een +opvolger van JavaScript. -Op [de CoffeeScript website](http://coffeescript.org/), staat een -vollediger tutorial voor CoffeeScript. +Op [de CoffeeScript website](http://coffeescript.org/), staat een +volledigere tutorial voor CoffeeScript. ``` coffeescript # CoffeeScript is een taal voor hipsters. # Het gaat mee met alle trends van moderne talen. -# Dus commentaar begint met een hekje, net zoals bij Python en Ruby. +# Commentaar begint dus met een hekje, net zoals bij Python en Ruby. ### Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /* @@ -47,7 +48,7 @@ vul = (houder, vloeistof = "koffie") -> # #vul = function(houder, vloeistof) { # if (vloeistof == null) { -# vloeistof = "coffee"; +# vloeistof = "koffie"; # } # return "Nu de " + houder + " met " + vloeistof + " aan het vullen..."; #}; @@ -75,12 +76,12 @@ wedstrijd = (winnaar, lopers...) -> # return print(winnaar, lopers); #}; -# Bestaan: +# Aanwezigheid: alert "Ik wist het!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } # Lijst abstractie: -derdemachten = (wiskunde.derdemacht num for num in lijst) +derdemachten = (wiskunde.derdemacht num for num in lijst) #=>derdemachten = (function() { # var _i, _len, _results; # _results = []; diff --git a/ocaml.html.markdown b/ocaml.html.markdown index b9505f13..f9db7080 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -93,7 +93,7 @@ let inc_int (x: int) : int = x + 1 ;; (* You need to mark recursive function definitions as such with "rec" keyword. *) let rec factorial n = if n = 0 then 1 - else factorial n * factorial (n-1) + else n * factorial (n-1) ;; (* Function application usually doesn't need parentheses around arguments *) diff --git a/perl6.html.markdown b/perl6.html.markdown index ee27ff42..52625bc2 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -64,7 +64,7 @@ say "Interpolate an array using [] : @array[]"; my @keys = 0, 2; @array[@keys] = @letters; # Assign using an array -say @array; #=> a 2 b +say @array; #=> a 6 b # There are two more kinds of lists: Parcel and Arrays. # Parcels are immutable lists (you can't modify a list that's not assigned). diff --git a/php.html.markdown b/php.html.markdown index e1bb86a0..039288a0 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown new file mode 100644 index 00000000..9e8ade5b --- /dev/null +++ b/pl-pl/perl-pl.html.markdown @@ -0,0 +1,169 @@ +--- +name: perl +category: language +language: perl +filename: learnperl.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Michał Kupczyński", "http://github.com/ukoms"] +lang: pl-pl +--- + +Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania +z ponad 25 latami nieustannego rozwoju. + +Perl 5 używany jest na ponad 100 różnych platformach (od przenośnych do w +pełni stacjonarnych) i nadaje się zarówno do szybkiego prototypowania jak +i projektów deweloperskich prowadzonych na szeroką skalę. + +```perl + +# Pojedyncza linia komentarza zaczyna się od znaku hasha (płotka) "#". + +#### Typy zmiennych w Perlu + +# Zmienna zaczyna się od symbolu dolara "$". +# Prawidłowa nazwa zmiennej zaczyna się od litery lub podkreślnika "_", +# po których następuje dowolna ilość liter, cyfr i podkreślników. + +### W Perlu występują trzy główne typy zmiennych: skalary, tablice i hasze. + +## Skalary +# Skalar przechowuje pojedynczą wartość: +my $zwierze = "wielbłąd"; +my $odpowiedź = 42; + +# Wartości skalarne mogą być ciągami znaków, liczbami całkowitymi lub +# zmiennoprzecinkowymi, zaś Perl automatycznie dokonuje konwersji pomiędzy nimi, +# w zależności od wykonywanego kodu/kontekstu. + +## Tablice +# Tablica przechowuje listę wartości: +my @zwierzęta = ("wielbłąd", "alpaka", "sowa"); +my @liczby = (23, 42, 69); +my @mieszanka = ("wielbłąd", 42, 1.23); + +## Hasze +# Hasz przechowuje zestawy par klucz-wartość: +my %kolor_owocu = ('jabłko', 'czerwony', 'banan', 'żółty'); + +# Możesz używać białych znaków (spacje, tabulatory) i operatora strzałki "=>" +# by czytelniej sformatować zapis hasza: +my %kolor_owocu = ( + jabłko => 'czerwony', + banan => 'żółty', +); + +# Skalary, tablice i hasze są bardziej wyczerpująco udokumentowane w dokumencie +# [perldoc perldata](http://perldoc.perl.org/perldata.html). + +# Bardziej złożone typy danych mogą być stworzone poprzez używanie referencji, +# które pozwalają Ci zbudować listy i hasze wewnątrz list i haszy. + +#### Warunki logiczne i pętle + +# W Perlu występują typowe warunki i pętle. +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (warunek) { + ... +} +# Powyższy zapis jest równoznaczny zapisowi "if (!warunek)" + +# Perlowy skrócony zapis warunków: +print "Siema!" if $rozochocony; +print "Nie mamy bananów" unless $banany; + +# Pętla while +while (warunek) { + ... +} + +# Pętle for oraz foreach +for ($i = 0; $i <= $max; $i++) { + ... +} + +foreach (@tablica) { + print "Tym elementem jest $_\n"; +} + +# lub + +foreach my $iterator (@tablica) { + print "Iterowanym elementem jest $iterator\n"; +} + +#### Wyrażenia regularne + +# Perlowe wyrażenia regularne są tematem tak rozległym, jak wymagającym. +# Istnieje ogromna ilość dokumentacji w artykułach takich jak +# [perlrequick](http://perldoc.perl.org/perlrequick.html), +# [perlretut](http://perldoc.perl.org/perlretut.html) i inne. +# W dużym skrócie, podstawy perlowych wyrażeń regularnych są następujące: + +# Proste dopasowanie: +if (/foo/) { ... } # prawda jeżeli $_ zawiera "foo" +if ($a =~ /foo/) { ... } # prawda jeżeli $a zawiera "foo" + +# Prosta zamiana: +# Zamienia "foo" na "bar" w zmiennej $a +$a =~ s/foo/bar/; +# Zamienia WSZYSTKIE WYSTĄPIENIA "foo" na "bar" w zmiennej $a +$a =~ s/foo/bar/g; + +#### Pliki i I/O + +# Możesz otworzyć plik do odczytu lub zapisu używając funkcji "open ()". +open (my $odczyt, "<", "odczyt.txt") or die "Błąd otwierania input.txt: $!"; +open (my $zapis, ">", "zapis.txt") or die "Błąd otwierania output.txt: $!"; +open (my $dopisanie, ">>", "my.log") or die "Błąd otwierania my.log: $!"; + +# Pliki możesz odczytywać z otworzonego handlera używając operatora "<>" +# (operator diamentowy). W kontekście skalarnym (przypisanie wyniku do skalara) +# operator ten zczytuje pojedynczą linię pliku, w kontekście listowym +# (przypisanie wyniku do tablicy) zczytuje całą zawartość pliku, przypisując +# każdą linię jako kolejny element listy: +my $linia = <$in>; +my @linie = <$in>; + +#### Perlowe funkcje (procedury) + +# Pisanie funkcji (procedur) jest proste: +sub logger { + my $wiadomosc_do_loga = shift; + open (my HANDLER, ">>", "my.log") or die "Błąd otwierania my.log: $!"; + print HANDLER $wiadomosc_do_loga; +} + +# Teraz można używać napisanej funkcji, tak jak każdej innej wbudowanej +# funkcji perlowej: +logger ("Mamy funkcję perlową"); + +``` + +#### Używanie modułów perlowych + +Moduły perlowe dostarczają szeroki wachlarz możliwości, byś nie musiał +wynajdywać koła na nowo. Moduły te można pobrać z [CPAN](http://www.cpan.org). +Sam Perl zawiera w swoich dystrybucjach kilka najpopularniejszych modułów +z repozytorium [CPAN](http://www.cpan.org). + +Najczęściej zadawane pytania [perlfaq](http://perldoc.perl.org/perlfaq.html) +- zawierają pytania i odpowiedzi dotyczące wielu typowo realizowanych zadań. +Często znajdziesz tam również sugestie dotyczące użycia najlepszego modułu +z repozytorium CPAN do zrealizowania konkretnego zadania. + + +#### Do doczytania + + - [perl-tutorial](http://perl-tutorial.org/) + - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - wbudowane w Perla: `perldoc perlintro`
\ No newline at end of file diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown new file mode 100644 index 00000000..885d5b27 --- /dev/null +++ b/pt-br/groovy-pt.html.markdown @@ -0,0 +1,435 @@ +--- +language: Groovy +category: language +filename: learngroovy.groovy +contributors: + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] +translators: + - ["João Farias", "https://github.com/JoaoGFarias"] +lang: pt-br +--- + +Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://groovy.codehaus.org) + +```groovy + +/* + Prepara-se: + + 1) Instale a máquina virtual de Groovy - http://gvmtool.net/ + 2) Intalse o Groovy: gvm install groovy + 3) Inicie o console groovy digitando: groovyConsole + +*/ + +// Comentário de uma linha inicia-se com duas barras +/* +Comentário de múltiplas linhas são assim. +*/ + +// Olá Mundo! +println "Olá mundo!" + +/* + Variáveis: + + Você pode atribuir valores a variáveis para uso posterior +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + Coleções e mapeamentos +*/ + +//Criando uma lista vazia +def tecnologias = [] + +/*** Adicionando elementos à lista ***/ + +// Assim como Java +tecnologias.add("Grails") + +// Shift para esquerda adiciona e retorna a lista +tecnologias << "Groovy" + +// Adição de múltiplos elementos +tecnologias.addAll(["Gradle","Griffon"]) + +/*** Removendo elementos da lista ***/ + +// Assim como Java +tecnologias.remove("Griffon") + +// Subtração também funciona +tecnologias = technologies - 'Grails' + +/*** Iterando sobre listas ***/ + +// Itera sobre os elementos da lista +tecnologias.each { println "Tecnologias: $it"} +tecnologias.eachWithIndex { it, i -> println "$i: $it"} + +/*** Checando os elementos da lista ***/ + +//Avalia se a lista contém o elemento 'Groovy' +contem = tecnologias.contains( 'Groovy' ) + +// Ou +contem = 'Groovy' in tecnologias + +// Checagem por múltiplos elementos +tecnologias.containsAll(['Groovy','Grails']) + +/*** Ordenando listas ***/ + +// Ordena a lista (altera a lista in-place) +tecnologias.sort() + +// Para ordenar a lista sem alterar a original +tecnologiasOrdenadas = tecnologias.sort( false ) + +/*** Manipulando listas ***/ + +//Substitue todos os elementos da lista +Collections.replaceAll(tecnologias, 'Gradle', 'gradle') + +//Desorganiza a lista +Collections.shuffle(tecnologias, new Random()) + +//Limpa a lista +technologies.clear() + +//Criando um mapeamento vazio +def devMap = [:] + +//Adicionando valores +devMap = ['nome':'Roberto', 'framework':'Grails', 'linguagem':'Groovy'] +devMap.put('ultimoNome','Perez') + +//Iterando sobre os elementos do mapeamento +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +//Avalia se um mapeamento contém uma chave +assert devMap.containsKey('nome') + +//Avalia se um mapeamento contém um valor +assert devMap.containsValue('Roberto') + +//Pega as chaves de um mapeamento +println devMap.keySet() + +//Pega os valores de um mapeamento +println devMap.values() + +/* + Groovy Beans + + GroovyBeans são JavaBeans com uma sintaxe muito mais simples. + + Quando Groovy é compilado para bytecode, as seguintes regras são usadas: + + * Se o nome é declarado com um modificador de acesso(public, private or + protected) então um atributo é gerado. + + * Um nome declarado sem modificador de acesso gera um campo privado com + getter e setter públicos (ou seja, uma propriedade). + + * Se uma propriedade é declarada como final, um campo private final é criado + e o setter não é gerado. + + * Você pode declarar uma propriedade e também declarar seus próprios getters + e setters. + + * Você pode declarar uma propriedade e um campo com o mesmo nome, a propriedade + usará este campo. + + * Se você quer uma propriedade private ou protected, você deve prover seus + próprios getters e setter, que devem ser declarados como private ou protected. + + * Se você acessar uma propriedade dentro da classe e esta propriedade é definida + em tempo de compilação com 'this', implícito ou explícito (por exemplo, + this.foo, ou simplesmente foo), Groovy acessará este campo diretamente, sem + passar pelo getter ou setter. + + * Se você acessar uma propriedade que não existe usando foo, explicitamente ou + implicitamente, então Groovy irá acessar esta propriedade através da meta + classe, o que pode falhar em tempo de execução. + +*/ + +class Foo { + // propriedade de leitura, apenas + final String nome = "Roberto" + + // propriedade de leitura, apenas, com getter e setter públicos + String linguagem + protected void setLinguagem(String linguagem) { this.linguagem = linguagem } + + // propriedade tipada dinamicamente + def ultimoNome +} + +/* + Condicionais e loops +*/ + +//Groovy suporta a sintaxe if-else +def x = 3 + +if(x==1) { + println "Um" +} else if(x==2) { + println "Dois" +} else { + println "X é maior que Dois" +} + +//Groovy também suporta o operador ternário +def y = 10 +def x = (y > 1) ? "functionou" : "falhou" +assert x == "functionou" + +//Loop 'for' +//Itera sobre um intervalo (range) +def x = 0 +for (i in 0 .. 30) { + x += i +} + +//Itera sobre uma lista +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +//Itera sobre um array +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +//Itera sobre um mapa +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} + +/* + Operadores + + Sobrecarregamento de Operadores para uma lsita dos operadores comuns que + Grooby suporta: + http://groovy.codehaus.org/Operator+Overloading + + Operadores Groovy úteis +*/ +//Operador de espalhamento: invoca uma ação sobre todos os itens de um +//objeto agregador. +def tecnologias = ['Groovy','Grails','Gradle'] +tecnologias*.toUpperCase() // = to tecnologias.collect { it?.toUpperCase() } + +//Operador de navegação segura: usado para evitar NullPointerException. +def usuario = User.get(1) +def nomeUsuario = usuario?.nomeUsuario + + +/* + Closures + Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método. + É um pedação de código que é definido e executado em um momento posterior. + + Mais informação em: http://groovy.codehaus.org/Closures+-+Formal+Definition +*/ +//Exemplo: +def clos = { println "Hello World!" } + +println "Executando o closure:" +clos() + +//Passando parêmetros para um closure +def soma = { a, b -> println a+b } +soma(2,4) + +//Closdures por referir-se a variáveis que não estão listadas em sua +//lista de parêmetros. +def x = 5 +def multiplicarPor = { num -> num * x } +println multiplicarPor(10) + +// Se você tiver um closure que tem apenas um argumento, você pode omitir +// o parâmetro na definição do closure +def clos = { print it } +clos( "oi" ) + +/* + Groovy pode memorizar resultados de closures [1][2][3] +*/ +def cl = {a, b -> + sleep(3000) // simula processamento + a + b +} + +mem = cl.memoize() + +def chamaClosure(a, b) { + def inicio = System.currentTimeMillis() + mem(a, b) + println "Os inputs(a = $a, b = $b) - tomam ${System.currentTimeMillis() - inicio} msecs." +} + +chamaClosure(1, 2) +chamaClosure(1, 2) +chamaClosure(2, 3) +chamaClosure(2, 3) +chamaClosure(3, 4) +chamaClosure(3, 4) +chamaClosure(1, 2) +chamaClosure(2, 3) +chamaClosure(3, 4) + +/* + Expando + + A classe Expando é um bean dinâmico que permite adicionar propriedade e + closures como métodos a uma instância desta classe + + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def usuario = new Expando(nome:"Roberto") + assert 'Roberto' == nome.name + + nome.lastName = 'Pérez' + assert 'Pérez' == nome.lastName + + nome.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println nome.showInfo(sw) + + +/* + Metaprogramação (MOP) +*/ + +//Usando a ExpandoMetaClasse para adicionar comportamento +String.metaClass.testAdd = { + println "adicionamos isto" +} + +String x = "teste" +x?.testAdd() + +//Interceptando chamadas a métodos +class Test implements GroovyInterceptable { + def soma(Integer x, Integer y) { x + y } + + def invocaMetodo(String name, args) { + System.out.println "Invoca método $name com argumentos: $args" + } +} + +def teste = new Test() +teste?.soma(2,3) +teste?.multiplica(2,3) + +//Groovy suporta propertyMissing para lidar com tentativas de resolução de +//propriedades. +class Foo { + def propertyMissing(String nome) { nome } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + TypeChecked e CompileStatic + Groovy, por natureza, é e sempre será uma linguagem dinâmica, mas ela também + suporta typecheked e compilestatic + + Mais informações: http://www.infoq.com/articles/new-groovy-20 +*/ +//TypeChecked +import groovy.transform.TypeChecked + +void testeMethod() {} + +@TypeChecked +void test() { + testeMethod() + + def nome = "Roberto" + + println noomee + +} + +//Outro exemplo: +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numeros = [1,2,3,4] + + Date dia = numeros[1] + + return "Teste" + +} + +//Exemplo de CompileStatic : +import groovy.transform.CompileStatic + +@CompileStatic +int soma(int x, int y) { + x + y +} + +assert soma(2,5) == 7 + + +``` + +## Referências + +[Groovy documentation](http://groovy.codehaus.org/Documentation) + +[Groovy web console](http://groovyconsole.appspot.com/) + +Junte-se a um [grupo de usuários Groovy](http://groovy.codehaus.org/User+Groups) + +## Livro + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html + + + diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 55f90bd6..788dc1d2 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] translators: diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index 344df43a..0e710742 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] diff --git a/python.html.markdown b/python.html.markdown index 390c7b76..ba236fb3 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -3,6 +3,7 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: learnpython.py --- @@ -54,19 +55,22 @@ to Python 2.x. Look for another tour of Python 3 soon! # Modulo operation 7 % 3 # => 1 +# Exponentiation (x to the y'th power) +2**4 # => 16 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 # Boolean Operators -+# Note "and" and "or" are case-sensitive -+True and False #=> False -+False or True #=> True -+ -+# Note using Bool operators with ints -+0 and 2 #=> 0 -+-5 or 0 #=> -5 -+0 == False #=> True -+2 == True #=> False +# Note "and" and "or" are case-sensitive +True and False #=> False +False or True #=> True + +# Note using Bool operators with ints +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False 1 == True #=> True # negate with not diff --git a/python3.html.markdown b/python3.html.markdown index a94f4eae..e478e57f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -3,6 +3,7 @@ language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: learnpython3.py --- @@ -50,6 +51,9 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Modulo operation 7 % 3 # => 1 +# Exponentiation (x to the y'th power) +2**4 # => 16 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 diff --git a/ru-ru/coffeescript-ru.html.markdown b/ru-ru/coffeescript-ru.html.markdown new file mode 100644 index 00000000..f8416f38 --- /dev/null +++ b/ru-ru/coffeescript-ru.html.markdown @@ -0,0 +1,104 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["asaskevich", "http://github.com/asaskevich"] +filename: learncoffee-ru.coffee +lang: ru-ru +--- + +CoffeeScript - это небольшой язык, который компилируется один-в-один в эквивалентный код на языке JavaScript, а потому он не интерпретируется во время исполнения JavaScript кода. +Ключевой особенностью CoffeeScript является то, что он пытается создать читабельный, качественно оформленный и плавный JavaScript код, прекрасно работающий в любой среде JavaScript. + +Также загляните на официальный сайт [языка](http://coffeescript.org/), где можно найти весьма полное учебное пособие по CoffeeScript. + +```coffeescript +# CoffeeScript - язык хипстеров. +# Язык использует самое модное из множества современных языков. +# Эти комментарии по стилю похожи на комментарии Ruby или Python, они используют "решетку" в качестве знака комментария. + +### +Блоки комментариев выделяются тремя символами "решетки", в результирующем JavaScript коде они будут преобразованы в '/ * и '* /'. + +Перед тем, как идти далее, Вам нужно понимать семантику JavaScript. +### + +# Присвоение: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Условия: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Функции: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Заполняем #{container} жидкостью #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Заполняем " + container + " жидкостью " + liquid + "..."; +#}; + +# Списки и диапазоны: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Объекты: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# Многоточия: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +#}; + +# Проверка на существование объекта: +alert "Так и знал!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Так и знал!"); } + +# Итерации по массивам: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` + +## На почитать + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) +- [CoffeeScript на русском](http://cidocs.ru/coffeescript/) diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown index 03e66d05..e15fe6b7 100644 --- a/ru-ru/haskell-ru.html.markdown +++ b/ru-ru/haskell-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell contributors: - ["Adit Bhargava", "http://adit.io"] translators: diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown index cd55e116..29392604 100644 --- a/ru-ru/julia-ru.html.markdown +++ b/ru-ru/julia-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: julia +language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] translators: diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown new file mode 100644 index 00000000..eb8e4881 --- /dev/null +++ b/ru-ru/markdown-ru.html.markdown @@ -0,0 +1,279 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] + - ["Pirogov Alexey", "http://twitter.com/alex_pir"] +filename: markdown-ru.md +lang: ru-ru +--- + +Язык разметки Markdown создан Джоном Грубером (англ. John Gruber) +и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году. +Авторы задавались целью создать максимально удобочитаемый +и удобный в публикации облегчённый язык разметки, +пригодный для последующего преобразования в HTML +(а также и в другие форматы). + + ```markdown +<!-- Markdown является надмножеством HTML, поэтому любой HTML-файл является +валидным документом Markdown, что позволяет использовать напрямую +любые элементы HTML-разметки, такие, например, как этот комментарий. + Встроенные в документ HTML-элементы не затрагиваются парсером Markdown +и попадают в итоговый HTML без изменений. Однако, следует понимать, +что эта же особенность не позволяет использовать разметку Markdown внутри +HTML-элементов --> + +<!-- Ещё одна особенность формата Markdown состоит в том, что поддерживаемые +возможности разметки зависят от конкретной реализации парсера. В данном +руководстве возможности, поддерживаемые лишь определёнными парсерами, +сопровождаются соответствующими примечаниями. --> + +<!-- Заголовки --> + +<!-- HTML-элементы от <h1> до <h6> размечаются очень просто: +текст, который должен стать заголовком, предваряется +соответствующим количеством символов "#": --> +# Это заголовок h1 +## Это заголовок h2 +### Это заголовок h3 +#### Это заголовок h4 +##### Это заголовок h5 +###### Это заголовок h6 + +<!-- Markdown позволяет размечать заголовки <h1> и <h2> ещё одним способом: --> +Это заголовок h1 +================ + +А это заголовок h2 +------------------ + +<!-- Простейшая стилизация текста --> + +<!-- Текст легко сделать полужирным и/или курсивным: --> + +*Этот текст будет выведен курсивом.* +_Так же, как этот._ + +**А этот текст будет полужирным.** +__И этот тоже.__ + +***Полужирный курсив.*** +**_И тут!_** +*__И даже здесь!__* + +<!-- В Github Flavored Markdown (версии Markdown, использующейся в Github, +для рендеринга Markdown-документов) текст можно сделать зачёркнутым: --> + +~~Зачёркнутый текст.~~ + +<!-- Абзацами являются любые строки, следующие друг за другом. +Разделяются же абзацы одной или несколькими пустыми строками: --> + +Это абзац. Всё предельно просто. + +А тут уже параграф №2. +Эта строка всё ещё относится к параграфу №2! + + +О, а вот это уже параграф №3! + +<!-- Для вставки принудительных переносов можно использовать HTML-тэг <br/>: --> + +Принудительный <br/> перенос! + +<!-- Цитаты размечаются с помощью символа ">": --> + +> Это цитата. В цитатах можно +> принудительно переносить строки, вставляя ">" в начало каждой следующей строки. А можно просто оставлять достаточно длинными, и такие длинные строки будут перенесены автоматически. +> Разницы между этими двумя подходами к переносу строк нет, коль скоро +> каждая строка начинается с символа ">" + +> А ещё цитаты могут быть многоуровневыми: +>> как здесь +>>> и здесь :) +> Неплохо? + +<!-- Списки --> +<!-- Маркированные списки размечаются вставкой в начало каждого элемента +одного из символов "*", "+" или "-": +(символ должен быть одним и тем же для всех элементов) --> + +* Список, +* Размеченный +* Звёздочками + +либо + ++ Список, ++ Размеченный ++ Плюсами + +либо + +- Список, +- Размеченный +- Дефисами + +<!-- В нумерованных списках каждая строка начинается +с числа и точки вслед за ним: --> + +1. Первый элемент +2. Второй элемент +3. Третий элемент + +<!-- Заметьте, нумеровать элементы корректно необязательно. Достаточно указать +любое число в начале каждого элемента и рендер пронумерует элементы сам! +Правда, злоупотреблять этим не стоит :) --> + +1. Первый элемент +1. Второй элемент +1. Третий элемент +<!-- (Этот список будет отрендерен так же, как и предыдущий!) --> + +<!-- Списки могут быть вложенными: --> + +1. Введение +2. Начало работы +3. Примеры использования + * Простые + * Сложные +4. Заключение + +<!-- Блоки с исходным кодом --> +<!-- Фрагменты исходного кода выделяются очень просто - каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции --> + + Это код, + причём - многострочный + +<!-- Дополнительные отступы в коде следует делать с помощью четырёх пробелов: --> + + my_array.each do |item| + puts item + end + +<!-- Иногда бывает нужно вставить фрагмент кода прямо в строку текста, +не выделяя код в блок. Для этого фрагменты кода нужно обрамлять +символами "`": --> + +Например, можно выделить имя функции `go_to()` прямо посреди текста. + +<!-- Github Flavored Markdown позволяет указать для блока кода синтаксис оного. +В этом случае синтаксис внутри блока будет подсвечен. Пример: --> + +\`\`\`ruby <!-- Только нужно будет убрать символы "\", оставив лишь "```ruby" --> +def foobar + puts "Hello world!" +end +\`\`\` <!-- И здесь тоже backslashes нужно убрать, т.е. оставить "```" --> + +<-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами, +поскольку Github сам в состоянии определить границы блока - по строкам "```" --> + +<!-- Горизонтальный разделитель (<hr />) --> +<!-- Разделители добавляются вставкой строки из трёх и более +(одинаковых) символов "*" или "-": --> + +*** +--- +- - - <!-- между символами допустимы пробелы --> +**************** + +<!-- Ссылки --> +<!-- Одной из сильных сторон Markdown можно смело считать то, +как просто размечаются гиперссылки. Для создания ссылки укажите +текст ссылки, заключив его в квадратные скобки, +и сразу после - url, заключенный в "круглые" --> + +[Ссылка!](http://test.com/) + +<!-- Также для ссылки можно указать всплывающую подсказку: --> + +[Ссылка!](http://test.com/ "Ссылка на Test.com") + +<!-- В url можно использовать относительные пути: --> + +[Перейти к музыке](/music/). + +<!-- Markdown позволяет размечать ссылку в виде сноски: --> + +[Здесь][link1] высможете узнать больше! +А можно кликнуть [сюда][foobar], если очень хочется. + +<!-- где-нибудь внизу --> +[link1]: http://test.com/ "Круто!" +[foobar]: http://foobar.biz/ "Тоже хорошо!" + +<!-- Примечания: +- Подсказка может быть заключена в одинарные кавычки вместо двойных, + а также в круглые скобки. +- Сноска может находиться в любом месте документа и может иметь +идентификатор (далее ID) произвольной длины, +лишь бы это ID был уникальным. --> + +<!-- Также при разметке ссылок-сносок можно опустить ID, +если текст ссылки уникален в пределах документа: --> + +Ссылка на [Google][]. + +[google]: http://google.com/ + +<!-- Правда, эта возможность не очень распространена. --> + +<!-- Изображения --> +<!-- Разметка изображений очень похожа на разметку ссылок. +Нужно всего лишь добавить "!" перед ссылкой! --> + +![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка") + +<!-- Изображения тоже могут быть оформлены, как сноски: --> + +![Альтернативный текст][myimage] + +![То же изображение ещё раз][myimage] + +[myimage]: relative/urls/cool/image.jpg "подсказка" + +<!-- Ещё немного ссылок: --> +<!-- Автоссылки --> + +Ссылка вида <http://testwebsite.com/> эквивалентна +[http://testwebsite.com/](http://testwebsite.com/) + +<!-- Автоссылки для адресов электронной почты --> + +<foo@bar.com> + +<!-- Экранирование символов --> + +<!-- Может потребоваться вставить спецсимвол в текст "как есть", +т.е. защитить его от обработки парсером. +Такой символ должен быть "экранирован" с помощью обратной косой черты +(символа "\"): --> + +\*текст, заключённый в звёздочки!\* + +<!-- Таблицы --> +<!-- Таблицы официально поддерживаются только в Github Flavored Markdown, +да и синтаксис имеют не слишком удобный. +Но если очень нужно, размечайте таблицы так: --> + +| Столбец 1 | Столбец 2 | Столбец 3 | +| :----------- | :----------: | -----------: | +| Выравнивание | Выравнивание | Выравнивание | +| влево | по центру | вправо | + +<!-- Или более компактно --> + +Колонка 1|Колонка 2|Колонка 3 +:--|:-:|--: +Выглядит|это|страшновато... + +<!-- Ну вот и всё! --> + +``` + +За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown. + +Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Adam Pritchard. + +Если вдруг встретите ошибки в переводе или же захотите его дополнить, делайте pull requests - авторы всегда рады обратной связи! diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index edcac4dd..53b2f916 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] diff --git a/rust.html.markdown b/rust.html.markdown index 0b9a5e58..3717a7d9 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -255,8 +255,8 @@ fn main() { ## Further reading There’s a lot more to Rust—this is just the basics of Rust so you can -understand the most important things. To learn more about Rust, read the -[Rust tutorial](http://doc.rust-lang.org/tutorial.html) and check out the +understand the most important things. To learn more about Rust, read [The Rust +Guide](http://doc.rust-lang.org/guide.html) and check out the [/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel on irc.mozilla.org are also always keen to help newcomers. diff --git a/swift.html.markdown b/swift.html.markdown index 77047355..005e511c 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -13,6 +13,9 @@ The official [Swift Programming Language](https://itunes.apple.com/us/book/swift See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```swift +// import a module +import UIKit + // // MARK: Basics // @@ -24,9 +27,12 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre println("Hello, world") +// variables (var) value can change after being set +// constants (let) value can NOT be changed after being set + var myVariable = 42 let øπΩ = "value" // unicode variable names -let myConstant = 3.1415926 +let π = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon let `class` = "keyword" // backticks allow keywords to be used as variable names @@ -34,9 +40,58 @@ let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation -var optionalString: String? = "optional" // Can be nil -optionalString = nil +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation + +// Build Specific values +// uses -D build configuration +#if false + println("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals are a Swift language feature that allows you to store a `Some` or + `None` value. + + Because Swift requires every property to have a value, even nil must be + explicitly stored as an Optional value. + + Optional<T> is an enum. +*/ +var someOptionalString: String? = "optional" // Can be nil +// same as above, but ? is a postfix operator (syntax candy) +var someOptionalString2: Optional<String> = "optional" + +if someOptionalString != nil { + // I am not nil + if someOptionalString!.hasPrefix("opt") { + println("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// implicitly unwrapped optional +var unwrappedString: String! = "Value is expected." +// same as above, but ! is a postfix operator (more syntax candy) +var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // has `Some` value, non-nil + if !someOptionalStringConstant.hasPrefix("ok") { + // does not have the prefix + } +} + +// Swift has support for storing a value of any type. +// AnyObject == id +// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." /* Comment here @@ -49,10 +104,17 @@ Comment here // MARK: Collections // +/* + Array and Dictionary types are structs. So `let` and `var` also indicate + that they are mutable (var) or immutable (let) when declaring these types. +*/ + // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = [String]() +let emptyArray = [String]() // immutable +var emptyMutableArray = [String]() // mutable + // Dictionary var occupations = [ @@ -60,7 +122,8 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = [String: Float]() +let emptyDictionary = [String: Float]() // immutable +var emptyMutableDictionary = [String: Float]() // mutable // @@ -84,9 +147,10 @@ for (key, value) in dict { } // for loop (range) -for i in -1...1 { // [-1, 0, 1] +for i in -1...shoppingList.count { println(i) } +shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number // while loop @@ -123,14 +187,14 @@ default: // required (in order to cover all possible input) // Function with Swift header docs (format as reStructedText) /** - A greet operation +A greet operation - - A bullet in docs - - Another bullet in the docs +- A bullet in docs +- Another bullet in the docs - :param: name A name - :param: day A day - :returns: A string containing the name and day value. +:param: name A name +:param: day A day +:returns: A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." @@ -141,9 +205,19 @@ greet("Bob", "Tuesday") func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) } +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignore Tuple (or other) values by using _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // true +println("Gas price: \(price)") // Variadic Args -func setup(numbers: Int...) {} +func setup(numbers: Int...) { + // its an array + let number = numbers[0] + let argCount = numbers.count +} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { @@ -155,6 +229,17 @@ func makeIncrementer() -> (Int -> Int) { var increment = makeIncrementer() increment(7) +// pass by ref +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + // // MARK: Closures @@ -197,7 +282,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { let names: [String] - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -239,7 +324,7 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) @@ -255,8 +340,9 @@ internal class Rect: Shape { } init(sideLength: Int) { - super.init() self.sideLength = sideLength + // always super.init last when init custom properties + super.init() } func shrink() { @@ -313,7 +399,7 @@ enum Suit { // // `protocol`s can require that conforming types have specific -// instance properties, instance methods, type methods, +// instance properties, instance methods, type methods, // operators, and subscripts. protocol ShapeGenerator { @@ -321,7 +407,6 @@ protocol ShapeGenerator { func buildShape() -> Shape } -/* // Protocols declared with @objc allow optional functions, // which allow you to check for conformance @objc protocol TransformShape { @@ -331,17 +416,17 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 - + if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() } } } -*/ + // // MARK: Other @@ -363,7 +448,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } @@ -372,7 +457,7 @@ extension Int { println(7.customProperty) // "This is 7" println(14.multiplyBy(2)) // 42 -// Generics: Similar to Java. Use the `where` keyword to specify the +// Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { diff --git a/tmux.html.markdown b/tmux.html.markdown index 8d7aa752..ebc312ed 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -2,22 +2,23 @@ category: tool tool: tmux contributors: - - ["kaernyk", "http://github.com/kaernyk"] + - ["kaernyk", "https://github.com/kaernyk"] + - ["jmaud", "https://github.com/jmaud"] filename: LearnTmux.txt --- <a href="http://tmux.sourceforge.net/"> -tmux</a> is a terminal multiplexer: it enables a number of terminals -to be created, accessed, and controlled from a single screen. tmux +tmux</a> is a terminal multiplexer: it enables a number of terminals +to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background then later reattached. ``` + tmux [command] # Run a command - # 'tmux' with no commands will create a new - session + # 'tmux' with no commands will create a new session new # Create a new session -s "Session" # Create named session @@ -54,7 +55,7 @@ then later reattached. ## Key Bindings -# The method of controlling an attached tmux session is via key +# The method of controlling an attached tmux session is via key # combinations called 'Prefix' keys. ---------------------------------------------------------------------- @@ -63,47 +64,48 @@ then later reattached. (M-1) = Meta + 1 -or- Alt + 1 ---------------------------------------------------------------------- - ? # List all key bindings - : # Enter the tmux command prompt - r # Force redraw of the attached client - c # Create a new window + ? # List all key bindings + : # Enter the tmux command prompt + r # Force redraw of the attached client + c # Create a new window - ! # Break the current pane out of the window. - % # Split the current pane into two, left and right - " # Split the current pane into two, top and bottom + ! # Break the current pane out of the window. + % # Split the current pane into two, left and right + " # Split the current pane into two, top and bottom - n # Change to the next window - p # Change to the previous window - { # Swap the current pane with the previous pane - } # Swap the current pane with the next pane + n # Change to the next window + p # Change to the previous window + { # Swap the current pane with the previous pane + } # Swap the current pane with the next pane - s # Select a new session for the attached client + s # Select a new session for the attached client interactively - w # Choose the current window interactively - 0 to 9 # Select windows 0 to 9 + w # Choose the current window interactively + 0 to 9 # Select windows 0 to 9 - d # Detach the current client - D # Choose a client to detach + d # Detach the current client + D # Choose a client to detach - & # Kill the current window - x # Kill the current pane + & # Kill the current window + x # Kill the current pane - Up, Down # Change to the pane above, below, left, or right - Left, Right + Up, Down # Change to the pane above, below, left, or right + Left, Right - M-1 to M-5 # Arrange panes: - # 1) even-horizontal - # 2) even-vertical - # 3) main-horizontal - # 4) main-vertical - # 5) tiled + M-1 to M-5 # Arrange panes: + # 1) even-horizontal + # 2) even-vertical + # 3) main-horizontal + # 4) main-vertical + # 5) tiled - C-Up, C-Down # Resize the current pane in steps of one cell - C-Left, C-Right + C-Up, C-Down # Resize the current pane in steps of one cell + C-Left, C-Right - M-Up, M-Down # Resize the current pane in steps of five cells - M-Left, M-Right + M-Up, M-Down # Resize the current pane in steps of five cells + M-Left, M-Right +``` ### Configuring ~/.tmux.conf @@ -111,30 +113,59 @@ then later reattached. tmux.conf can be used to set options automatically on start up, much like how .vimrc or init.el are used. + +``` # Example tmux.conf -# 2014.9 +# 2014.10 + + +### General +########################################################################### + +# Enable UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Scrollback/History limit +set -g history-limit 2048 + +# Index Start +set -g base-index 1 + +# Mouse +set-option -g mouse-select-pane on + +# Force reload of config file +unbind r +bind r source-file ~/.tmux.conf ### Keybinds -###################################################################### +########################################################################### # Unbind C-b as the default prefix -unbind-key C-befix C-a +unbind C-b + +# Set new default prefix +set-option -g prefix ` # Return to previous window when prefix is pressed twice -bind-key C-a last-window -bind-key ` last-window +bind C-a last-window +bind ` last-window # Allow swapping C-a and ` using F11/F12 -bind-key F11 set-option -g prefix C-a -bind-key F12 set-option -g prefix ` +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` -# Activate inner-most session (when nesting tmux) -# to send commands -bind-key a send-prefix +# Keybind preference +setw -g mode-keys vi +set-option -g status-keys vi -# Index Start -set -g base-index 1 +# Moving between panes with vim movement keys +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R # Window Cycle/Swap bind e previous-window @@ -142,23 +173,20 @@ bind f next-window bind E swap-window -t -1 bind F swap-window -t +1 -# easy-to-remember split pane commands -bind | split-window -h +# Easy split pane commands +bind = split-window -h bind - split-window -v unbind '"' unbind % -# moving between panes with vim movement keys -bind h select-pane -L -bind j select-pane -D -bind k select-pane -U -bind l select-pane -R +# Activate inner-most session (when nesting tmux) to send commands +bind a send-prefix ### Theme -##################################################################### +########################################################################### -# Statusbar Color Palette +# Statusbar Color Palatte set-option -g status-justify left set-option -g status-bg black set-option -g status-fg white @@ -187,14 +215,7 @@ setw -g window-status-activity-fg yellow ### UI -###################################################################### - -# Statusbar -set-option -g status-utf8 on - -# Keybind preference -setw -g mode-keys vi -set-option -g status-keys vi +########################################################################### # Notification setw -g monitor-activity on @@ -202,41 +223,20 @@ set -g visual-activity on set-option -g bell-action any set-option -g visual-bell off -# Mouse -setw -g mode-mouse on -set-option -g mouse-select-pane on -set -g mouse-resize-pane on -set -g mouse-select-window on - # Automatically set window titles set-option -g set-titles on - -# window number,program name,active (or not) -set-option -g set-titles-string '#H:#S.#I.#P #W #T' +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) # Statusbar Adjustments -set -g status-left '#[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default]' -set -g status-interval 3 - -# Statusbar with right-aligned Date / Time -#set -g status-right '#[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default]' +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" # Show performance counters in statusbar # Requires https://github.com/thewtex/tmux-mem-cpu-load/ -#set -g status-right '#[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default]' +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" - -### Misc -###################################################################### - -# Scrollback/History limit -set -g history-limit 4096 - -bind r source-file ~/.tmux.conf ``` -### External Resources - <a href="http://tmux.sourceforge.net/">Tmux | Home</a><br> <a href="http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux">Tmux Manual page</a><br> <a href="http://wiki.gentoo.org/wiki/Tmux">Archlinux Wiki</a><br> diff --git a/tr-tr/php-tr.html.markdown b/tr-tr/php-tr.html.markdown index 3db437cf..5258d785 100644 --- a/tr-tr/php-tr.html.markdown +++ b/tr-tr/php-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP filename: learnphp-tr.php contributors: - ["Malcolm Fell", "http://emarref.net/"] diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown index bdb88204..1bcc94a0 100644 --- a/vi-vn/git-vi.html.markdown +++ b/vi-vn/git-vi.html.markdown @@ -2,14 +2,15 @@ category: tool
tool: git
contributors:
- - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Jake Prather", "http://github.com/JakeHP"] + - ["Vinh Nguyen", "https://twitter.com/vinhnx"]
filename: LearnGit-vi.txt
lang: vi-vn
---
Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system).
-Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, and nó hoạt động
+Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động
với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và
quản lý mã nguồn của bạn.
@@ -19,7 +20,7 @@ quản lý mã nguồn của bạn. Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian.
-### Centralized Versioning VS Distributed Versioning
+### So sánh giữa Centralized Versioning và Distributed Versioning
* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin.
* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất.
@@ -75,7 +76,7 @@ con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nh ### HEAD và head (thành phần của thư mục .git)
-HEAD là một con trỏ đến nhánh hiện tại. Một repo chỉ có một HEAD *đang hoạt động*.
+HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*.
head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head.
### Các Tài Nguyên Mang Tính Khái Niệm
@@ -165,29 +166,29 @@ $ git add ./*.java ### branch
-Quản lý nhánh. Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này.
+Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này.
```bash
-# liệt kê các nhanh đang có và ở remote
+# liệt kê các branch đang có và ở remote
$ git branch -a
-# tạo nhánh mới
+# tạo branch mới
$ git branch myNewBranch
-# xóa một nhánh
+# xóa một branch
$ git branch -d myBranch
-# đặt tên lại một nhánh
+# đặt tên lại một branch
# git branch -m <oldname> <newname>
$ git branch -m myBranchName myNewBranchName
-# chỉnh sủa diễn giải của một nhánh
+# chỉnh sửa diễn giải của một branch
$ git branch myBranchName --edit-description
```
### checkout
-Cập nhật tất cả các file torng tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể.
+Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể.
```bash
# Checkout (chuyển) một repo - mặc định là nhánh master
@@ -201,8 +202,8 @@ $ git checkout -b newBranch ### clone
Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm
-các nhánh có remote-tracking cho mỗi nhánh trong một repo được nhân bản, mà
-cho phép bạn push đến một nhánh remote.
+các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà
+cho phép bạn push đến một remote branch.
```bash
# Nhân bản learnxinyminutes-docs
@@ -211,7 +212,7 @@ $ git clone https://github.com/adambard/learnxinyminutes-docs.git ### commit
-Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một lời nhắn (ghi chú) tạo ra bởi người dùng.
+Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng.
```bash
# commit với một ghi chú
@@ -279,7 +280,7 @@ $ git log --merges "Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại.
```bash
-# Merge nhánh cụ thể vào nhánh hiện tại.
+# Merge branch cụ thể vào branch hiện tại.
$ git merge branchName
# Luôn khởi tạo một merge commit khi trộn (merge)
@@ -304,30 +305,35 @@ $ git mv -f myFile existingFile ### pull
-Kéo (tải) về từ một repo và merge nó vào nhánh khác.
+Pull về từ một repo và merge nó vào branch khác.
```bash
-# Cập nhật repo cục bộ của bạn, bằng cách merge các thay đổi mới
+# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới
# từ remote "origin" và nhánh "master".
# git pull <remote> <branch>
# git pull => hoàn toàn mặc định như => git pull origin master
$ git pull origin master
-# Merge các thay đổi từ nhánh remote và rebase
-# các commit nhánh lên trên thư mục cục bộ, như: "git pull <remote> <branch>, git rebase <branch>"
+# Merge các thay đổi từ remote branch và rebase
+# các commit trong branch lên trên local repo, như sau: "git pull <remote> <branch>, git rebase <branch>"
$ git pull origin master --rebase
```
### push
-Đẩy và trộn (mege) các tay đổi từ một nhánh đế một remote & nhánh.
-
-```bash
-# Push và merge các thay đổi từ repo cục bộ đến một
-# remote tên là "origin" và nhánh "master".
-# git push <remote> <branch>
-# git push => hoàn toàn defaults to => git push origin master
-$ git push origin master
+push và merge các thay đổi từ một branch đến một remote & branch.
+
+```bash +# Push và merge các thay đổi từ một repo local đến một +# remote có tên là "origin" và nhánh "master". +# git push <remote> <branch> +# git push => mặc định ẩn đến => git push origin master +$ git push origin master + +# Để liên kết đến một branch local với một branch remote, thêm vào cờ -u: +$ git push -u origin master +# Từ lúc này, bất cứ khi nào bạn muốn push từ cùng một nhánh local đó, sử dụng lối tắt: +$ git push ```
### rebase (thận trọng)
@@ -390,4 +396,8 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
+* [GitGuys](http://www.gitguys.com/) + +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) +
+ diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index 223f6e35..1e10416e 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -566,7 +566,7 @@ typedef void (*my_fnp_type)(char *); '\'' // 单引号 '\"' // 双引号 '\xhh' // 十六进制数字. 例子: '\xb' = vertical tab -'\ooo' // 十进制数字. 例子: '\013' = vertical tab +'\ooo' // 八进制数字. 例子: '\013' = vertical tab // 打印格式: "%d" // 整数 @@ -579,7 +579,7 @@ typedef void (*my_fnp_type)(char *); "%c" // 字母 "%p" // 指针 "%x" // 十六进制 -"%o" // 十进制 +"%o" // 八进制 "%%" // 打印 % /////////////////////////////////////// diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index 8d51f144..cb7ccdee 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell filename: learn-haskell-zh.hs contributors: - ["Adit Bhargava", "http://adit.io"] diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 7afc9043..1f91d52c 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: julia +language: Julia filename: learn-julia-zh.jl contributors: - ["Jichao Ouyang", "http://oyanglul.us"] diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 3ba098ec..53a603a2 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua lang: zh-cn contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index 24939681..2def7f1c 100644 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] |