diff options
author | Johnathan Maudlin <maudlin.johnathan@gmail.com> | 2014-10-29 22:13:33 -0400 |
---|---|---|
committer | Johnathan Maudlin <maudlin.johnathan@gmail.com> | 2014-10-29 22:13:33 -0400 |
commit | 259c144eeb7b349a00891eb7bfa26ed564dfe580 (patch) | |
tree | d5620fc0ecba85da3f66d15ea0952eccfa718ebf | |
parent | fe277959606857f2690b4d6dd224fffc6a550d34 (diff) | |
parent | 7d0eaa855959c03b52795a7457001bbd69d88464 (diff) |
Merge pull request #1 from adambard/master
Merge from upstream
-rw-r--r-- | amd.html.markdown | 212 | ||||
-rw-r--r-- | bash.html.markdown | 9 | ||||
-rw-r--r-- | c++.html.markdown | 780 | ||||
-rw-r--r-- | c.html.markdown | 9 | ||||
-rw-r--r-- | common-lisp.html.markdown | 2 | ||||
-rw-r--r-- | de-de/csharp-de.html.markdown | 889 | ||||
-rw-r--r-- | elixir.html.markdown | 35 | ||||
-rw-r--r-- | fr-fr/brainfuck-fr.html.markdown | 87 | ||||
-rw-r--r-- | fr-fr/markdown.html.markdown | 289 | ||||
-rw-r--r-- | fr-fr/xml-fr.html.markdown | 128 | ||||
-rw-r--r-- | haml.html.markdown | 155 | ||||
-rw-r--r-- | haskell.html.markdown | 4 | ||||
-rw-r--r-- | javascript.html.markdown | 23 | ||||
-rw-r--r-- | markdown.html.markdown | 8 | ||||
-rw-r--r-- | matlab.html.markdown | 50 | ||||
-rw-r--r-- | nl-nl/brainfuck-nl.html.markdown | 86 | ||||
-rw-r--r-- | nl-nl/coffeescript-nl.html.markdown | 23 | ||||
-rw-r--r-- | ocaml.html.markdown | 2 | ||||
-rw-r--r-- | pl-pl/perl-pl.html.markdown | 169 | ||||
-rw-r--r-- | pt-br/groovy-pt.html.markdown | 435 | ||||
-rw-r--r-- | ru-ru/markdown-ru.html.markdown | 279 | ||||
-rw-r--r-- | swift.html.markdown | 133 | ||||
-rw-r--r-- | tmux.html.markdown | 4 | ||||
-rw-r--r-- | vi-vn/git-vi.html.markdown | 66 |
24 files changed, 3496 insertions, 381 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/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown new file mode 100644 index 00000000..dc77dda0 --- /dev/null +++ b/de-de/csharp-de.html.markdown @@ -0,0 +1,889 @@ +---
+language: c#
+contributors:
+ - ["Irfan Charania", "https://github.com/irfancharania"]
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Melvyn Laïly", "http://x2a.yt"]
+ - ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
+translators:
+ - ["Frederik Ring", "https://github.com/m90"]
+filename: LearnCSharp-de.cs
+lang: de-de
+---
+C# ist eine elegante, typsichere und objektorientierte Sprache, mit der Entwickler eine Vielzahl sicherer und robuster Anwendungen erstellen können, die im .NET Framework ausgeführt werden.
+
+[Mehr über C# erfährst du hier.](http://msdn.microsoft.com/de-de/library/vstudio/z1zx9t92.aspx)
+
+```c#
+// Einzeilige Kommentare starten mit zwei Schrägstrichen: //
+/*
+Mehrzeile Kommentare wie in C Schrägstrich / Stern
+*/
+/// <summary>
+/// XML-Kommentare können zur automatisierten Dokumentation verwendet werden
+/// </summary>
+
+// Zu Beginn werden die in der Datei verwendeten Namespaces aufgeführt
+using System;
+using System.Collections.Generic;
+using System.Data.Entity;
+using System.Dynamic;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Net;
+using System.Threading.Tasks;
+using System.IO;
+
+// definiert einen Namespace um Code in "packages" zu organisieren
+namespace Learning
+{
+ // Jede .cs-Datei sollte zumindest eine Klasse mit dem Namen der Datei
+ // enthalten. Das ist zwar nicht zwingend erforderlich, es anders zu
+ // handhaben führt aber unweigerlich ins Chaos (wirklich)!
+ public class LearnCSharp
+ {
+ // Zuerst erklärt dieses Tutorial die Syntax-Grundlagen,
+ // wenn du bereits Java oder C++ programmieren kannst:
+ // lies bei "Interessante Features" weiter!
+ public static void Syntax()
+ {
+ // Mit Console.WriteLine kannst du einfachen Text ausgeben:
+ Console.WriteLine("Hallo Welt");
+ Console.WriteLine(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Console.Write erzeugt keinen Zeilenumbruch
+ Console.Write("Hallo ");
+ Console.Write("Welt");
+
+ ///////////////////////////////////////////////////
+ // Typen & Variablen
+ ///////////////////////////////////////////////////
+
+ // Deklariere eine Variable mit <Typ> <Name>
+
+ // Sbyte - Vorzeichenbehaftete 8-Bit Ganzzahl
+ // (-128 <= sbyte <= 127)
+ sbyte fooSbyte = 100;
+
+ // Byte - Vorzeichenlose 8-Bit Ganzzahl
+ // (0 <= byte <= 255)
+ byte fooByte = 100;
+
+ // Short - 16-Bit Ganzzahl
+ // Vorzeichenbehaftet - (-32,768 <= short <= 32,767)
+ // Vorzeichenlos - (0 <= ushort <= 65,535)
+ short fooShort = 10000;
+ ushort fooUshort = 10000;
+
+ // Integer - 32-bit Ganzzahl
+ int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
+ uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
+
+ // Long - 64-bit Ganzzahl
+ long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
+ // Ganze Zahlen werden standardmäßig - je nach Größe - als int oder
+ // uint behandelt. Ein nachgestelltes L markiert den Wert als long
+ // oder ulong.
+
+ // Double - Double-precision 64-bit IEEE 754 Fließkommazahl
+ double fooDouble = 123.4; // Genauigkeit: 15-16 Stellen
+
+ // Float - Single-precision 32-bit IEEE 754 Fließkommazahl
+ float fooFloat = 234.5f; // Genauigkeit: 7 Stellen
+ // Das nachgestellte f zeigt an dass es sich um einen Wert vom Typ
+ // float handelt
+
+ // Decimal - ein 128-Bit-Datentyp mit größerer Genauigkeit als
+ // andere Fließkommatypen, und somit bestens geeignet für
+ // die Berechnung von Geld- und Finanzwerten
+ decimal fooDecimal = 150.3m;
+
+ // Boolean - true & false
+ bool fooBoolean = true; // oder false
+
+ // Char - Ein einzelnes 16-Bit Unicode Zeichen
+ char fooChar = 'A';
+
+ // Strings - im Gegensatz zu allen vorhergehenden Basistypen, die
+ // alle Werttypen sind, ist String ein Referenztyp. Strings sind
+ // somit nullable, Werttypen sind dies nicht.
+ string fooString = "\"maskiere\" Anführungszeichen, und füge \n (Umbrüche) und \t (Tabs) hinzu";
+ Console.WriteLine(fooString);
+
+ // Jeder Buchstabe eines Strings kann über seinen Index
+ // referenziert werden:
+ char charFromString = fooString[1]; // => 'e'
+ // Strings sind unveränderlich:
+ // `fooString[1] = 'X';` funktioniert nicht
+
+ // Ein Vergleich zweier Strings, unter Berücksichtigung der
+ // aktuellen, sprachspezifischen Gegebenheiten (also z.B. a,ä,b,c
+ // in deutschsprachigen Umgebungen), und ohne Beachtung von
+ // Groß- und Kleinschreibung:
+ string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
+
+ // Formatierung, genau wie "sprintf"
+ string fooFs = string.Format("Mikrofon Check, {0} {1}, {0} {1:0.0}", 1, 2);
+
+ // Datumsangaben und Formatierung
+ DateTime fooDate = DateTime.Now;
+ Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
+
+ // Durch ein vorangestelltes @ lässt sich ein mehrzeiliger String
+ // schreiben. Um " zu maskieren benutzt man ""
+ string bazString = @"Hier geht es
+zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
+
+ // Die Keywords const oder readonly kennzeichnen eine
+ // unveränderliche Variable/Konstante. Die Werte von Konstanten
+ // werden übrigens bereits zur Compile-Zeit berechnet.
+ const int HOURS_I_WORK_PER_WEEK = 9001;
+
+ ///////////////////////////////////////////////////
+ // Datenstrukturen
+ ///////////////////////////////////////////////////
+
+ // Arrays - Index beginnt bei Null
+ // Die Größe des Arrays wird bei der Deklaration festgelegt.
+ // Die syntaktische Struktur um ein neues Array zu erzeugen sieht
+ // folgendermaßen aus:
+ // <datatype>[] <varname> = new <datatype>[<array size>];
+ int[] intArray = new int[10];
+
+ // Arrays können auch über ein Array-Literal deklariert werden:
+ int[] y = { 9000, 1000, 1337 };
+
+ // Indizierung eines Arrays - Zugriff auf ein bestimmtes Element
+ Console.WriteLine("intArray @ 0: " + intArray[0]);
+ // Arrays sind veränderbar
+ intArray[1] = 1;
+
+ // Listen
+ // Durch ihre größere Flexibilität kommen Listen in C# weit
+ // häufiger zum Einsatz als Arrays. Eine Liste wird so deklariert:
+ // List<datatype> <varname> = new List<datatype>();
+ List<int> intList = new List<int>();
+ List<string> stringList = new List<string>();
+ List<int> z = new List<int> { 9000, 1000, 1337 };
+ // Die <> kennzeichnen "Generics", mehr dazu unter "Coole Sachen"
+
+ // Listen haben keinen Default-Wert.
+ // Bevor auf einen Index zugegriffen werden kann, muss dieser
+ // auch gesetzt worden sein:
+ intList.Add(1);
+ Console.WriteLine("intList @ 0: " + intList[0]);
+
+ // Andere interessante Datenstrukturen sind:
+ // Stack/Queue
+ // Dictionary (entspricht einer Hash Map)
+ // HashSet
+ // Read-only Collections
+ // Tuple (.Net 4+)
+
+ ///////////////////////////////////////
+ // Operatoren
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Operatoren");
+
+ // kurze Schreibweise um mehrere Deklarationen zusammenzufassen:
+ // (Benutzung vom C# Styleguide aber ausdrücklich abgeraten!)
+ int i1 = 1, i2 = 2;
+
+ // Arithmetik funktioniert wie erwartet:
+ Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
+
+ // Modulo
+ Console.WriteLine("11%3 = " + (11 % 3)); // => 2
+
+ // Vergleiche
+ Console.WriteLine("3 == 2? " + (3 == 2)); // => false
+ Console.WriteLine("3 != 2? " + (3 != 2)); // => true
+ Console.WriteLine("3 > 2? " + (3 > 2)); // => true
+ Console.WriteLine("3 < 2? " + (3 < 2)); // => false
+ Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
+ Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
+
+ // Bitweise Operatoren
+ /*
+ ~ Unäres bitweises NICHT
+ << Verschieben nach links
+ >> Verschieben nach rechts
+ & Bitweises UND
+ ^ Bitweises exklusives ODER
+ | Bitweises inklusives ODER
+ */
+
+ // Inkremente
+ int i = 0;
+ Console.WriteLine("\n->Inkrement / Dekrement");
+ Console.WriteLine(i++); //i = 1. Post-Inkrement
+ Console.WriteLine(++i); //i = 2. Pre-Inkrement
+ Console.WriteLine(i--); //i = 1. Post-Dekrement
+ Console.WriteLine(--i); //i = 0. Pre-Dekrement
+
+ ///////////////////////////////////////
+ // Kontrollstrukturen
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Kontrollstrukturen");
+
+ // If-Statements funktionieren wie in C
+ int j = 10;
+ if (j == 10)
+ {
+ Console.WriteLine("Ich werde ausgegeben");
+ }
+ else if (j > 10)
+ {
+ Console.WriteLine("Ich nicht");
+ }
+ else
+ {
+ Console.WriteLine("Ich leider auch nicht");
+ }
+
+ // Ternärer Operator
+ // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben:
+ // <condition> ? <true> : <false>
+ string isTrue = true ? "Ja" : "Nein";
+
+ // while-Schleife
+ int fooWhile = 0;
+ while (fooWhile < 100)
+ {
+ // Wird 100mal wiederholt, fooWhile 0->99
+ fooWhile++;
+ }
+
+ // do-while-Schleife
+ int fooDoWhile = 0;
+ do
+ {
+ // Wird 100mal wiederholt, fooDoWhile 0->99
+ fooDoWhile++;
+ } while (fooDoWhile < 100);
+
+ //for-Schleifen => for(<start_statement>; <conditional>; <step>)
+ for (int fooFor = 0; fooFor < 10; fooFor++)
+ {
+ // Wird 10mal wiederholt, fooFor 0->9
+ }
+
+ // foreach-Schleife
+ // Die normale Syntax für eine foreach-Schleife lautet:
+ // foreach(<iteratorType> <iteratorName> in <enumerable>)
+ // foreach kann mit jedem Objekt verwendet werden das IEnumerable
+ // oder IEnumerable<T> implementiert. Alle Auflistungs-Typen
+ // (Array, List, Dictionary...) im .NET Framework implementieren
+ // eines dieser beiden Interfaces.
+
+ foreach (char character in "Hallo Welt".ToCharArray())
+ {
+ // Ein Durchgang für jedes Zeichen im String
+ }
+ // (ToCharArray() könnte man hier übrigens auch weglassen,
+ // da String IEnumerable bereits implementiert)
+
+ // Switch Struktur
+ // Ein Switch funktioniert mit byte, short, char und int Datentypen.
+ // Auch Aufzählungstypen können verwendet werden, genau wie
+ // die Klasse String, und ein paar Sonderklassen, die Wrapper für
+ // Primitives sind: Character, Byte, Short und Integer
+ int month = 3;
+ string monthString;
+ switch (month)
+ {
+ case 1:
+ monthString = "Januar";
+ break;
+ case 2:
+ monthString = "Februar";
+ break;
+ case 3:
+ monthString = "März";
+ break;
+ // Man kann für mehrere Fälle auch das selbe Verhalten
+ // definieren. Jeder Block muss aber mit einem break-Statement
+ // abgeschlossen werden. Einzelne Fälle können über
+ // `goto case x` erreicht werden
+ case 6:
+ case 7:
+ case 8:
+ monthString = "Sommer!!";
+ break;
+ default:
+ monthString = "Irgendein anderer Monat";
+ break;
+ }
+
+ ///////////////////////////////////////
+ // Umwandlung von Datentypen und Typecasting
+ ///////////////////////////////////////
+
+ // Umwandlung
+
+ // von String nach Integer
+ // bei einem Fehler wirft diese Code eine Exception
+ int.Parse("123"); //gibt die Ganzzahl 123 zurück
+
+ // TryParse gibt bei einem Fehler den Default-Wert zurück
+ // (im Fall von int: 0)
+ int tryInt;
+ if (int.TryParse("123", out tryInt)) // gibt true oder false zurück
+ {
+ Console.WriteLine(tryInt); // 123
+ }
+
+ // von Integer nach String
+ // Die Klasse Convert stellt Methoden zur Konvertierung von
+ // unterschiedlichsten Daten zur Verfügung:
+ Convert.ToString(123); // "123"
+ // oder
+ tryInt.ToString(); // "123"
+ }
+
+ ///////////////////////////////////////
+ // Klassen
+ ///////////////////////////////////////
+ public static void Classes()
+ {
+
+ // Benutze das new-Keyword um eine Instanz einer Klasse zu erzeugen
+ Bicycle trek = new Bicycle();
+
+ // So werden Methoden der Instanz aufgerufen
+ trek.SpeedUp(3); // Es empfiehlt sich immer Getter und Setter zu benutzen
+ trek.Cadence = 100;
+
+ // ToString ist eine Konvention über die man üblicherweiser
+ // Informationen über eine Instanz erhält
+ Console.WriteLine("Infos zu trek: " + trek.ToString());
+
+ // Wir instantiieren ein neues Hochrad
+ PennyFarthing funbike = new PennyFarthing(1, 10);
+ Console.WriteLine("Infos zu funbike: " + funbike.ToString());
+
+ Console.Read();
+ } // Ende der Methode main
+
+ // Main als Konsolenstartpunkt
+ // Eine Konsolenanwendung muss eine Methode Main als Startpunkt besitzen
+ public static void Main(string[] args)
+ {
+ OtherInterestingFeatures();
+ }
+
+ ///////////////////////////////////////
+ // Interessante Features
+ ///////////////////////////////////////
+
+ // Methodensignaturen
+
+ public // Sichtbarkeit
+ static // Erlaubt einen Zugriff auf der Klasse (nicht auf einer Instanz)
+ int // Typ des Rückgabewerts,
+ MethodSignatures(
+ // Erstes Argument, erwartet int
+ int maxCount,
+ // setzt sich selbst auf 0 wenn kein anderer Wert übergeben wird
+ int count = 0,
+ int another = 3,
+ // enthält alle weiteren der Methode übergebenen Parameter (quasi Splats)
+ params string[] otherParams
+ )
+ {
+ return -1;
+ }
+
+ // Methoden können überladen werden, solange sie eindeutige
+ // Signaturen haben
+ public static void MethodSignatures(string maxCount)
+ {
+ }
+
+ // Generische Typen
+ // Die Typen für TKey und TValue werden erst beim Aufruf der Methode
+ // festgelegt. Diese Methode emuliert z.B. SetDefault aus Python:
+ public static TValue SetDefault<TKey, TValue>(
+ IDictionary<TKey, TValue> dictionary,
+ TKey key,
+ TValue defaultItem)
+ {
+ TValue result;
+ if (!dictionary.TryGetValue(key, out result))
+ {
+ return dictionary[key] = defaultItem;
+ }
+ return result;
+ }
+
+ // Möglichen Typen lassen sich auch über ihr Interface beschränken:
+ public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
+ {
+ // Da T ein IEnumerable ist können wir foreach benutzen
+ foreach (var item in toPrint)
+ {
+ // Item ist ein int
+ Console.WriteLine(item.ToString());
+ }
+ }
+
+ public static void OtherInterestingFeatures()
+ {
+ // Optionale Parameter
+ MethodSignatures(3, 1, 3, "Ein paar", "extra", "Strings");
+ // setzt explizit einen bestimmten Parameter, andere werden übersprungen
+ MethodSignatures(3, another: 3);
+
+ // Erweiterungsmethoden
+ int i = 3;
+ i.Print(); // Weiter unten definiert
+
+ // Nullables - perfekt für die Interaktion mit
+ // Datenbanken / Rückgabewerten
+ // Jeder Wert (d.h. keine Klassen) kann durch das Nachstellen eines ?
+ // nullable gemacht werden: <type>? <varname> = <value>
+ int? nullable = null; // Die explizite Langform wäre Nullable<int>
+ Console.WriteLine("Mein Nullable: " + nullable);
+ bool hasValue = nullable.HasValue; // true wenn nicht null
+
+ // ?? ist "syntaktischer Zucker" um einen Defaultwert für den Fall
+ // dass die Variable null ist festzulegen.
+ int notNullable = nullable ?? 0; // 0
+
+ // Implizit typisierte Variablen
+ // Man kann auch den Typ einer Variable auch vom Compiler
+ // bestimmen lassen:
+ var magic = "magic ist zur Compile-Zeit ein String, folglich geht keine Typsicherheit verloren";
+ magic = 9; // funktioniert nicht da magic vom Typ String ist
+
+ // Generics
+ var phonebook = new Dictionary<string, string>() {
+ {"Resi", "08822 / 43 67"} // Fügt einen Eintrag zum Telefonbuch hinzu
+ };
+
+ // Hier könnte man auch unser generisches SetDefault von
+ // weiter oben benutzen:
+ Console.WriteLine(SetDefault<string,string>(phonebook, "Xaver", "kein Telefon")); // kein Telefon
+ // TKey und TValue müssen nicht zwingend angegeben werden, da sie
+ // auch implizit vom Compiler ermittelt werden können
+ Console.WriteLine(SetDefault(phonebook, "Resi", "kein Telefon")); // 08822 / 43 67
+
+ // Lambdas - konzise Syntax für Inline-Funktionen
+ Func<int, int> square = (x) => x * x; // Das letzte Element vom Typ T ist der Rückgabewert
+ Console.WriteLine(square(3)); // 9
+
+ // Disposables - einfaches Management von nicht verwalteten Ressourcen
+ // So gut wie alle Objekte die auf nicht verwaltete Ressourcen
+ // (Dateien, Geräte, ...) zugreifen, implementieren das Interface
+ // IDisposable. Das using Statement stellt sicher dass die vom
+ // IDisposable benutzten Ressourcen nach der Benutzung wieder
+ // freigegeben werden:
+ using (StreamWriter writer = new StreamWriter("log.txt"))
+ {
+ writer.WriteLine("Alles bestens!");
+ // Am Ende des Codeblocks werden die Ressourcen wieder
+ // freigegeben - auch im Falle einer Exception
+ }
+
+ // Parallel Klasse
+ // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
+ var websites = new string[] {
+ "http://www.google.com", "http://www.reddit.com",
+ "http://www.shaunmccarthy.com"
+ };
+ var responses = new Dictionary<string, string>();
+
+ // Für jeden Request wird ein neuer Thread erzeugt, der nächste
+ // Schritt wird erst nach Beendigung aller Tasks ausgeführt
+ Parallel.ForEach(websites,
+ // maximal 3 Threads gleichzeitig
+ new ParallelOptions() {MaxDegreeOfParallelism = 3},
+ website =>
+ {
+ // Hier folgt eine langwierige, asynchrone Operation
+ using (var r = WebRequest.Create(new Uri(website)).GetResponse())
+ {
+ responses[website] = r.ContentType;
+ }
+ });
+
+ // Dieser Code wird erst nach Beendigung aller Requests ausgeführt
+ foreach (var key in responses.Keys)
+ {
+ Console.WriteLine("{0}:{1}", key, responses[key]);
+ }
+
+ // Dynamische Objekte (gut um mit anderen Sprachen zu arbeiten)
+ dynamic student = new ExpandoObject();
+ // hier muss keine Typ angegeben werden
+ student.FirstName = "Christian";
+
+ // Einem solchen Objekt kann man sogar Methoden zuordnen.
+ // Das Beispiel gibt einen String zurück und erwartet einen String
+ student.Introduce = new Func<string, string>(
+ (introduceTo) => string.Format("Hallo {0}, das ist {1}", student.FirstName, introduceTo));
+ Console.WriteLine(student.Introduce("Bettina"));
+
+ // IQueryable<T> - So gut wie alle Aufzählungstypen implementieren
+ // dieses Interface, welches eine Vielzahl von funktionalen Methoden
+ // wie Map / Filter / Reduce zur Verfügung stellt:
+ var bikes = new List<Bicycle>();
+ // sortiert die Liste
+ bikes.Sort();
+ // sortiert nach Anzahl Räder
+ bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels));
+ var result = bikes
+ // diese Filter können auch aneinandergehängt werden
+ .Where(b => b.Wheels > 3) // (gibt ein IQueryable des vorherigen Typs zurück)
+ .Where(b => b.IsBroken && b.HasTassles)
+ // diese Zuordnung gibt ein IQueryable<String> zurück
+ .Select(b => b.ToString());
+
+ // "Reduce" - addiert alle Räder der Aufzählung zu einem Wert
+ var sum = bikes.Sum(b => b.Wheels);
+
+ // So erzeugt man ein implizit typisiertes Objekt, basierend auf
+ // den Parametern der Elemente:
+ var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
+ // Auch wenn wir es hier nicht demonstrieren können:
+ // In einer IDE wie VisualStudio kriegen wir hier sogar TypeAhead,
+ // da der Compiler in der Lage ist, die passenden Typen zu erkennen.
+ foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
+ {
+ Console.WriteLine(bikeSummary.Name);
+ }
+
+ // AsParallel-Methode
+ // Jetzt kommen die Schmankerl! Die AsParallel-Methode kombiniert
+ // LINQ und parallele Operationen:
+ var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
+ // Diese Berechnung passiert parallel! Benötigte Threads werden
+ // automatisch erzeugt, und die Rechenlast unter ihnen aufgeteilt.
+ // Ein Traum für die Verarbeitung von großen Datenmengen
+ // auf mehreren Cores!
+
+ // LINQ - bildet einen Datenspeicher auf IQueryable<T> Objekte ab
+ // LinqToSql beispielsweise speichert und liest aus einer
+ // SQL-Datenbank, LinqToXml aus einem XML-Dokument.
+ // LINQ-Operationen werden "lazy" ausgeführt.
+ var db = new BikeRepository();
+
+ // Die verzögerte Ausführung ist optimal für Datenbankabfragen
+ var filter = db.Bikes.Where(b => b.HasTassles); // noch keine Abfrage
+ // Es können noch mehr Filter hinzugefügt werden (auch mit
+ // Bedingungen) - ideal für z.B. "erweiterte Suchen"
+ if (42 > 6)
+ {
+ filter = filter.Where(b => b.IsBroken); // immer noch keine Abfrage
+ }
+
+ var query = filter
+ .OrderBy(b => b.Wheels)
+ .ThenBy(b => b.Name)
+ .Select(b => b.Name); // auch hier: immer noch keine Abfrage
+
+ // Erst hier wird die Datenbankabfrage wirklich ausgeführt,
+ // limitiert auf die Elemente die der foreach-Loop verwendet
+ foreach (string bike in query)
+ {
+ Console.WriteLine(result);
+ }
+
+ }
+
+ } // Ende der Klasse LearnCSharp
+
+ // Eine .cs-Datei kann auch mehrere Klassen enthalten
+
+ public static class Extensions
+ {
+ // Erweiterungsmethoden
+ public static void Print(this object obj)
+ {
+ Console.WriteLine(obj.ToString());
+ }
+ }
+
+ // Syntax zur Deklaration einer Klasse:
+ // <public/private/protected/internal> class <class name>{
+ // // Datenfelder, Konstruktoren und Methoden leben alle
+ // // innerhalb dieser Deklaration
+ // }
+
+ public class Bicycle
+ {
+ // Felder/Variablen der Klasse "Bicycle"
+ // Das Keyword public macht das Member von überall zugänglich
+ public int Cadence
+ {
+ get // get definiert eine Methode um die Eigenschaft abzurufen
+ {
+ return _cadence;
+ }
+ set // set definiert eine Methode um die Eigenschaft zu setzen
+ {
+ _cadence = value; // value ist der dem Setter übergebene Wert
+ }
+ }
+ private int _cadence;
+
+ // Das Keyword protected macht das Member nur für die Klasse selbst
+ // und ihre Subklassen zugänglich
+ protected virtual int Gear
+ {
+ get; // erzeugt eine Eigenschaft für die kein "Zwischenwert" benötigt wird
+ set;
+ }
+
+ // Das Keyword internal macht das Member innerhalb der Assembly zugänglich
+ internal int Wheels
+ {
+ get;
+ private set; // get/set kann auch über Keywords modifiziert werden
+ }
+
+ int _speed; // Member ohne vorangestellte Keywords sind standardmäßig
+ // private, sie sind nur innerhalb der Klasse zugänglich.
+ // Man kann aber natürlich auch das Keyword private benutzen.
+ private string Name { get; set; }
+
+ // Ein Enum ist ein klar definierter Satz an benannten Konstanten.
+ // Eigentlich ordnet es diese Konstanten nur bestimmten Werten zu
+ // (einer int-Zahl, solange nicht anders angegeben). Mögliche Typen für
+ // die Werte eines Enums sind byte, sbyte, short, ushort, int, uint,
+ // long, oder ulong. Alle Werte in einem Enum sind eindeutig.
+ public enum BikeBrand
+ {
+ Colnago,
+ EddyMerckx,
+ Bianchi = 42, // so kann man den Wert explizit setzen
+ Kynast // 43
+ }
+ // Nachdem dieser Typ in der Klasse "Bicycle" definiert ist,
+ // sollte Code ausserhalb der Klasse den Typen als Bicycle.Brand referenzieren
+
+ // Nachdem das Enum deklariert ist, können wir den Typen verwenden:
+ public BikeBrand Brand;
+
+ // Als static gekennzeichnete Member gehören dem Typ selbst,
+ // nicht seinen Instanzen. Man kann sie also ohne Referenz zu einem
+ // Objekt benutzen
+ // Console.WriteLine("Schon " + Bicycle.BicyclesCreated + " Fahrräder, nur für dieses Tutorial!");
+ static public int BicyclesCreated = 0;
+
+ // readonly-Werte werden zur Laufzeit gesetzt
+ // Ihr Wert kann nur bei ihrer Deklaration, oder in einem Konstruktor
+ // festgelegt werden
+ readonly bool _hasCardsInSpokes = false; // readonly und private
+
+ // Konstruktoren bestimmen was bei einer Instantiierung passiert.
+ // Das ist ein Default-Konstruktor:
+ public Bicycle()
+ {
+ // Member der Klasse können über das Keyword this erreicht werden
+ this.Gear = 1;
+ // oft ist das aber gar nicht nötig
+ Cadence = 50;
+ _speed = 5;
+ Name = "Bonanzarad";
+ Brand = BikeBrand.Kynast;
+ BicyclesCreated++;
+ }
+
+ // Das ist ein spezifischer Konstruktor (d.h. er erwartet Argumente):
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ string name, bool hasCardsInSpokes, BikeBrand brand)
+ : base() // ruft zuerst den "base"-Konstruktor auf
+ {
+ Gear = startGear;
+ Cadence = startCadence;
+ _speed = startSpeed;
+ Name = name;
+ _hasCardsInSpokes = hasCardsInSpokes;
+ Brand = brand;
+ }
+
+ // Konstruktoren können aneinandergehängt werden:
+ public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
+ this(startCadence, startSpeed, 0, "richtig große Räder", true, brand)
+ {
+ }
+
+ // Syntax für Methoden:
+ // <public/private/protected> <return type> <function name>(<args>)
+
+ // Klassen können Getter und Setter für Werte definieren,
+ // oder diese Werte direkt als Eigenschaft implementieren
+ // (in C# der bevorzugte Weg)
+
+ // Parameter von Methoden können Default-Werte haben.
+ // "SpeedUp" kann man also auch ohne Parameter aufrufen:
+ public void SpeedUp(int increment = 1)
+ {
+ _speed += increment;
+ }
+
+ public void SlowDown(int decrement = 1)
+ {
+ _speed -= decrement;
+ }
+
+ // Eigenschaften mit get/set
+ // wenn es nur um den Zugriff auf Daten geht, ist eine Eigenschaft zu
+ // empfehlen. Diese können Getter und Setter haben, oder auch nur
+ // einen Getter bzw. einen Setter
+ private bool _hasTassles; // private Variable
+ public bool HasTassles // öffentliches Interface
+ {
+ get { return _hasTassles; }
+ set { _hasTassles = value; }
+ }
+
+ // Das kann man auch kürzer schreiben:
+ // Dieser Syntax erzeugt automatisch einen hinterlegten Wert,
+ // (entsprechend `private bool _isBroken`) der gesetzt
+ // bzw. zurückgegeben wird:
+ public bool IsBroken { get; private set; }
+ public int FrameSize
+ {
+ get;
+ // für Getter und Setter kann der Zugriff auch einzeln
+ // beschränkt werden, FrameSize kann also nur von innerhalb
+ // der Klasse "Bicycle" gesetzt werden
+ private set;
+ }
+
+ // Diese Methode gibt eine Reihe an Informationen über das Objekt aus:
+ public virtual string ToString()
+ {
+ return "Gang: " + Gear +
+ " Kadenz: " + Cadence +
+ " Geschwindigkeit: " + _speed +
+ " Name: " + Name +
+ " Hipster-Karten zwischen den Speichen: " + (_hasCardsInSpokes ? "Na klar!" : "Bloß nicht!") +
+ "\n------------------------------\n"
+ ;
+ }
+
+ // Auch Methoden können als static gekennzeichnet werden, nützlich
+ // beispielsweise für Helper-Methoden
+ public static bool DidWeCreateEnoughBicyclesYet()
+ {
+ // In einer statischen Methode können wir natürlich auch nur
+ // statische Member der Klasse referenzieren
+ return BicyclesCreated > 9000;
+ }
+ // Wenn eine Klasse nur statische Member enthält, kann es eine gute Idee
+ // sein die Klasse selbst als static zu kennzeichnen
+
+ } // Ende der Klasse "Bicycle"
+
+ // "PennyFarthing" ist eine Unterklasse von "Bicycle"
+ class PennyFarthing : Bicycle
+ {
+ // (Hochräder - englisch Penny Farthing - sind diese antiken Fahrräder
+ // mit riesigem Vorderrad. Sie haben keine Gangschaltung.)
+
+ // hier wird einfach der Elternkonstruktor aufgerufen
+ public PennyFarthing(int startCadence, int startSpeed) :
+ base(startCadence, startSpeed, 0, "Hochrad", true, BikeBrand.EddyMerckx)
+ {
+ }
+
+ protected override int Gear
+ {
+ get
+ {
+ return 0;
+ }
+ set
+ {
+ throw new ArgumentException("Ein Hochrad hat keine Gangschaltung, doh!");
+ }
+ }
+
+ public override string ToString()
+ {
+ string result = "Hochrad ";
+ result += base.ToString(); // ruft die "base"-Version der Methode auf
+ return result;
+ }
+ }
+
+ // Interfaces (auch Schnittstellen genant) definieren nur die Signaturen
+ // ihrer Member, enthalten aber auf keinen Fall ihre Implementierung:
+ interface IJumpable
+ {
+ // Alle Member eines Interfaces sind implizit public
+ void Jump(int meters);
+ }
+
+ interface IBreakable
+ {
+ // Interfaces können Eigenschaften, Methoden und Events definieren
+ bool Broken { get; }
+ }
+
+ // Eine Klasse kann nur von einer Klasse erben, kann aber eine beliebige
+ // Anzahl von Interfaces implementieren
+ class MountainBike : Bicycle, IJumpable, IBreakable
+ {
+ int damage = 0;
+
+ public void Jump(int meters)
+ {
+ damage += meters;
+ }
+
+ public bool Broken
+ {
+ get
+ {
+ return damage > 100;
+ }
+ }
+ }
+
+ // Das hier stellt eine Datenbankverbindung für das LinqToSql-Beispiel her.
+ // EntityFramework Code First ist großartig
+ // (ähnlich zu Ruby's ActiveRecord, aber bidirektional)
+ // http://msdn.microsoft.com/de-de/data/jj193542.aspx
+ public class BikeRepository : DbSet
+ {
+ public BikeRepository()
+ : base()
+ {
+ }
+
+ public DbSet<Bicycle> Bikes { get; set; }
+ }
+} // Ende des Namespaces
+```
+
+## In dieser Übersicht nicht enthalten sind die Themen:
+
+ * Flags
+ * Attributes
+ * Statische Eigenschaften
+ * Exceptions, Abstraction
+ * ASP.NET (Web Forms/MVC/WebMatrix)
+ * Winforms
+ * Windows Presentation Foundation (WPF)
+
+## Zum Weiterlesen gibt es viele gute Anlaufpunkte:
+
+ * [DotNetPerls](http://www.dotnetperls.com)
+ * [C# in Depth](http://manning.com/skeet2)
+ * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
+ * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
+ * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
+ * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
+ * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
+
+[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
\ No newline at end of file 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/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/markdown.html.markdown b/fr-fr/markdown.html.markdown new file mode 100644 index 00000000..29c0d65d --- /dev/null +++ b/fr-fr/markdown.html.markdown @@ -0,0 +1,289 @@ +--- +language: markdown +contributors: +- ["Andrei Curelaru", "http://www.infinidad.fr"] +filename: markdown.md +lang: fr-fr +--- + +Markdown a été créé par John 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. 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 ad12de2a..2785405c 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -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/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/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/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/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 ebc312ed..de3a8341 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -239,6 +239,6 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | <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> -<a href="https://wiki.archlinux.org/index.php/Tmux">Gentoo Wiki</a><br> +<a href="http://wiki.gentoo.org/wiki/Tmux">Gentoo Wiki</a><br> +<a href="https://wiki.archlinux.org/index.php/Tmux">Archlinux Wiki</a><br> <a href="https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux">Display CPU/MEM % in statusbar</a><br> 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) +
+ |