diff options
88 files changed, 7681 insertions, 640 deletions
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown new file mode 100644 index 00000000..9ee33ebc --- /dev/null +++ b/CONTRIBUTING.markdown @@ -0,0 +1,70 @@ +# Contributing + +All contributions are welcome, from the tiniest typo to a brand new article. +Translations in all languages are welcome (or, for that matter, original +articles in any language). Send a pull request or open an issue any time of day +or night. + +**Please prepend the tag `[language/lang-code]` to your issues and pull +requests.** For example, `[python/en]` for English Python. This will help +everyone pick out things they care about. + +We're happy for any contribution in any form, but if you're making more than one +major change (i.e. translations for two different languages) it would be super +cool of you to make a separate pull request for each one so that someone can +review them more effectively and/or individually. + +## Style Guidelines + +- **Keep lines of under 80 chars** + + Try to keep **line length in code blocks to 80 characters or fewer**. + + Otherwise, the text will overflow and look odd. +- **Prefer example to exposition** + + Try to use as few words as possible. + + Code examples are preferred over exposition in all cases. +- **Eschew surplusage** + + We welcome newcomers, but the target audience for this site is programmers + with some experience. + + Try to avoid explaining basic concepts except for those specific to the + language in question. + + Keep articles succinct and scannable. We all know how to use Google here. +- **Use UTF-8** + + For translations (or EN articles with non-ASCII characters) please make sure + your file is UTF-8 encoded. + + Try to leave out the byte-order-mark at the start of the file. (`:set nobomb` + in Vim) + + +### Header configuration + +The actual site uses Middleman to generate HTML files from these Markdown ones. +Middleman, or at least the custom scripts underpinning the site, requires that +some key information be defined in the header. + +The following fields are necessary for English articles about programming +languages: + +- **language** The *programming language* in question +- **contributors** A list of [author, URL] lists to credit + +Other fields: + +- **filename**: The filename for this article's code. It will be fetched, mashed + together, and made downloadable. + + For non-English articles, *filename* should have a language-specific + suffix. +- **lang**: For translations, the human language this article is in. For + categorization, mostly. + +Here's an example header for an Esperanto translation of Ruby: + +```yaml +--- +language: ruby +filename: learnruby-epo.ruby +contributors: + - ["Doktor Esperanto", "http://example.com/"] + - ["Someone else", "http://someoneelseswebsite.com/"] +lang: ep-ep +--- +``` diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..3f55e3fb --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,4 @@ +- [ ] PR touches only one file (or a set of logically related files with similar changes made) +- [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts) +- [ ] YAML Frontmatter formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown) + - [ ] Seriously, look at it now. Watch for quotes and double-check field names. diff --git a/README.markdown b/README.markdown index 94afbcbe..a71e85bd 100644 --- a/README.markdown +++ b/README.markdown @@ -1,88 +1,45 @@ -# [Learn X in Y minutes](http://learnxinyminutes.com) +# [Learn X in Y minutes][1] Whirlwind tours of (several, hopefully many someday) popular and -ought-to-be-more-popular programming languages, presented as valid, -commented code and explained as they go. +ought-to-be-more-popular programming languages, presented as valid, commented +code and explained as they go. ## We need YOU!... -... to write more inline code tutorials. Just grab an existing file from -this repo and copy the formatting (don't worry, it's all very simple). -Make a new file, send a pull request, and if it passes muster I'll get it up pronto. -Remember to fill in the "contributors" fields so you get credited -properly! +... to write more inline code tutorials. Just grab an existing file from this +repo and copy the formatting (don't worry, it's all very simple). Make a new +file, send a pull request, and if it passes muster I'll get it up pronto. +Remember to fill in the "contributors" fields so you get credited properly! ## Contributing -All contributions are welcome, from the tiniest typo to a brand new article. Translations -in all languages are welcome (or, for that matter, original articles in any language). -Send a pull request or open an issue any time of day or night. +All contributions are welcome, from the tiniest typo to a brand new article. +Translations in all languages are welcome (or, for that matter, original +articles in any language). Send a pull request or open an issue any time of day +or night. -**Please tag your issues and pull requests with [language/lang-code] at the beginning** -**(e.g. [python/en] for English Python).** This will help everyone pick out things they -care about. +**Please prepend the tag `[language/lang-code]` to your issues and pull +requests.** For example, `[python/en]` for English Python. This will help +everyone pick out things they care about. -We're happy for any contribution in any form, but if you're making more than one major change -(i.e. translations for two different languages) it would be super cool of you to make a -separate pull request for each one so that someone can review them more effectively and/or -individually. +We're happy for any contribution in any form, but if you're making more than one +major change (i.e. translations for two different languages) it would be super +cool of you to make a separate pull request for each one so that someone can +review them more effectively and/or individually. -### Style Guidelines +For a detailed style guide, please review the full [CONTRIBUTING][2] guidelines. -* **Keep lines under 80 chars** -* **Prefer example to exposition** -* **Eschew surplusage** -* **Use UTF-8** - -Long version: - -* Try to keep **line length in code blocks to 80 characters or fewer**, or they'll overflow - and look odd. - -* Try to use as few words as possible. Code examples are preferred over exposition in all cases. - -* We welcome newcomers, but the target audience for this site is programmers with some experience. - So, try to avoid explaining basic concepts except for those specific to the language in question, - to keep articles succinct and scannable. We all know how to use Google here. - -* For translations (or English articles with non-ASCII characters), please make sure your file is - UTF-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim) - -### Header configuration - -The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least -the custom scripts underpinning the site, required that some key information be defined in the header. - -The following fields are necessary for English articles about programming languages: - -* **language** The *programming language* in question -* **contributors** A list of [author, URL] lists to credit - -Other fields: - -* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable. - For non-English articles, *filename* should have a language-specific suffix. -* **lang**: For translations, the human language this article is in. For categorization, mostly. - -Here's an example header for an Esperanto translation of Ruby: +## License -```yaml ---- -language: ruby -filename: learnruby-epo.ruby -contributors: - - ["Doktor Esperanto", "http://example.com/"] - - ["Someone else", "http://someoneelseswebsite.com/"] -lang: ep-ep ---- -``` +Contributors retain copyright to their work, and can request removal at any +time. By uploading a doc here, you agree to publish your work under the default +[Creative Commons Attribution-ShareAlike 3.0 Unported][3] licensing included on +each doc page. -## License +Anything not covered by the above -- basically, this README -- you can use as +you wish, I guess. -Contributors retain copyright to their work, and can request removal at any time. -By uploading a doc here, you agree to publish your work under the default -[Creative Commons Attribution-ShareAlike 3.0 Unported](http://creativecommons.org/licenses/by-sa/3.0/deed.en_US) -licensing included on each doc page. -Anything not covered by the above -- basically, this README -- you can use -as you wish, I guess. +[1]: http://learnxinyminutes.com +[2]: /CONTRIBUTING.markdown +[3]: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown new file mode 100644 index 00000000..8326c581 --- /dev/null +++ b/asciidoc.html.markdown @@ -0,0 +1,122 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/"] +filename: asciidoc.md +--- + +AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. + +Document Header + +Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. + +Title Only + +``` += Document Title + +First sentence of document. +``` + +Title and Author + +``` += Document Title +First Last <first.last@learnxinyminutes.com> + +Start of this document. +``` + +Multiple Authors + +``` += Document Title +John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com> + +Start of a doc with multiple authors. +``` + +Revision Line (requires an author line) + +``` += Doc Title V1 +Potato Man <chip@crunchy.com> +v1.0, 2016-01-13 + +This article about chips is going to be fun. +``` + +Paragraphs + +``` +You don't need anything special for paragraphs. + +Add a blank line between paragraphs to separate them. + +To create a line blank add a + +and you will receive a line break! +``` + +Formatting Text + +``` +_underscore creates italics_ +*asterisks for bold* +*_combine for extra fun_* +`use ticks to signify monospace` +`*bolded monospace*` +``` + +Section Titles + +``` += Level 0 (may only be used in document's header) + +== Level 1 <h2> + +=== Level 2 <h3> + +==== Level 3 <h4> + +===== Level 4 <h5> + +====== Level 5 <h6> + +======= Level 6 <h7> + +``` + +Lists + +To create a bulleted list use asterisks. + +``` +* foo +* bar +* baz +``` + +To create a numbered list use periods. + +``` +. item 1 +. item 2 +. item 3 +``` + +You can nest lists by adding extra asterisks or periods up to five times. + +``` +* foo 1 +** foo 2 +*** foo 3 +**** foo 4 +***** foo 5 + +. foo 1 +.. foo 2 +... foo 3 +.... foo 4 +..... foo 5 +``` diff --git a/bash.html.markdown b/bash.html.markdown index 211d2944..bd2d5984 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -83,7 +83,7 @@ echo Hello, $Name! # We have the usual if structure: # use 'man test' for more info about conditionals -if [ $Name -ne $USER ] +if [ $Name != $USER ] then echo "Your name isn't your username" else @@ -91,12 +91,12 @@ else fi # NOTE: if $Name is empty, bash sees the above condition as: -if [ -ne $USER ] +if [ != $USER ] # which is invalid syntax # so the "safe" way to use potentially empty variables in bash is: -if [ "$Name" -ne $USER ] ... +if [ "$Name" != $USER ] ... # which, when $Name is empty, is seen by bash as: -if [ "" -ne $USER ] ... +if [ "" != $USER ] ... # which works as expected # There is also conditional execution diff --git a/brainfuck.html.markdown b/bf.html.markdown index a76169c8..c8bbee61 100644 --- a/brainfuck.html.markdown +++ b/bf.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/c++.html.markdown b/c++.html.markdown index f4aa2f5a..a02e7e5b 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -330,7 +330,7 @@ ECarTypes GetPreferredCarType() } // As of C++11 there is an easy way to assign a type to the enum which can be -// useful in serialization of data and converting enums back-and-forth between +// useful in serialization of data and converting enums back-and-forth between // the desired type and their respective constants enum ECarTypes : uint8_t { @@ -352,7 +352,7 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType) } // On the other hand you may not want enums to be accidentally cast to an integer -// type or to other enums so it is instead possible to create an enum class which +// type or to other enums so it is instead possible to create an enum class which // won't be implicitly converted enum class ECarTypes : uint8_t { @@ -468,7 +468,7 @@ int main() { // Inheritance: // This class inherits everything public and protected from the Dog class -// as well as private but may not directly access private members/methods +// as well as private but may not directly access private members/methods // without a public or protected method for doing so class OwnedDog : public Dog { @@ -820,6 +820,76 @@ std::map<Foo, int, compareFunction> fooMap; fooMap[Foo(1)] = 1; fooMap.find(Foo(1)); //true +/////////////////////////////////////// +// Lambda Expressions (C++11 and above) +/////////////////////////////////////// + +// lambdas are a convenient way of defining an anonymous function +// object right at the location where it is invoked or passed as +// an argument to a function. + +// For example, consider sorting a vector of pairs using the second +// value of the pair + +vector<pair<int, int> > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// Pass a lambda expression as third argument to the sort function +// sort is from the <algorithm> header + +sort(tester.begin(), tester.end(), [](const pair<int, int>& lhs, const pair<int, int>& rhs) { + return lhs.second < rhs.second; + }); + +// Notice the syntax of the lambda expression, +// [] in the lambda is used to "capture" variables +// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how. +// It can be either: +// 1. a value : [x] +// 2. a reference : [&x] +// 3. any variable currently in scope by reference [&] +// 4. same as 3, but by value [=] +// Example: + +vector<int> dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++) { + dog_ids.push_back(i); +} + +int weight[3] = {30, 50, 10}; + +// Say you want to sort dog_ids according to the dogs' weights +// So dog_ids should in the end become: [2, 0, 1] + +// Here's where lambda expressions come in handy + +sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { + return weight[lhs] < weight[rhs]; + }); +// Note we captured "weight" by reference in the above example. +// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 + +/////////////////////////////// +// Range For (C++11 and above) +/////////////////////////////// + +// You can use a range for loop to iterate over a container +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout << elem << endl; +} + +// You can use "auto" and not worry about the type of the elements of the container +// For example: + +for(auto elem: arr) { + // Do something with each element of arr +} + ///////////////////// // Fun stuff ///////////////////// @@ -870,20 +940,50 @@ Foo f1; f1 = f2; -// How to truly clear a container: -class Foo { ... }; -vector<Foo> v; -for (int i = 0; i < 10; ++i) - v.push_back(Foo()); +/////////////////////////////////////// +// Tuples (C++11 and above) +/////////////////////////////////////// + +#include<tuple> + +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// its elements are accessed by their order in the tuple. + +// We start with constructing a tuple. +// Packing values into tuple +auto first = make_tuple(10, 'A'); +const int maxN = 1e9; +const int maxL = 15; +auto second = make_tuple(maxN, maxL); + +// printing elements of 'first' tuple +cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A + +// printing elements of 'second' tuple +cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 + +// Unpacking tuple into variables + +int first_int; +char first_char; +tie(first_int, first_char) = first; +cout << first_int << " " << first_char << "\n"; // prints : 10 A + +// We can also create tuple like this. + +tuple<int, char, double> third(11, 'A', 3.14141); +// tuple_size returns number of elements in a tuple (as a constexpr) + +cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3 + +// tuple_cat concatenates the elements of all the tuples in the same order. -// Following line sets size of v to 0, but destructors don't get called -// and resources aren't released! -v.empty(); -v.push_back(Foo()); // New value is copied into the first Foo we inserted +auto concatenated_tuple = tuple_cat(first, second, third); +// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141) -// Truly destroys all values in v. See section about temporary objects for -// explanation of why this works. -v.swap(vector<Foo>()); +cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 +cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 +cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' ``` Further Reading: diff --git a/c.html.markdown b/c.html.markdown index 8226ddef..d92d2ee6 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -239,7 +239,7 @@ int main (int argc, char** argv) z = (e > f) ? e : f; // => 10 "if e > f return e, else return f." // Increment and decrement operators: - char *s = "iLoveC"; + char *s = "ILoveC"; int j = 0; s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. j = 0; @@ -321,7 +321,7 @@ int main (int argc, char** argv) break; default: // if `some_integral_expression` didn't match any of the labels - fputs("error!\n", stderr); + fputs("Error!\n", stderr); exit(-1); break; } @@ -497,7 +497,7 @@ int add_two_ints(int x1, int x2) /* Functions are call by value. When a function is called, the arguments passed to -≈the function are copies of the original arguments (except arrays). Anything you +the function are copies of the original arguments (except arrays). Anything you do to the arguments in the function do not change the value of the original argument where the function was called. @@ -726,7 +726,7 @@ Header files are an important part of c as they allow for the connection of c source files and can simplify code and definitions by seperating them into seperate files. -Header files are syntaxtically similar to c source files but reside in ".h" +Header files are syntactically similar to c source files but reside in ".h" files. They can be included in your c source file by using the precompiler command #include "example.h", given that example.h exists in the same directory as the c file. diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 2b1f5de4..9a23bc26 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -339,7 +339,7 @@ nil ; for false - and the empty list ;; The () in the above is the list of arguments for the function (defun hello (name) - (format nil "Hello, ~a " name)) + (format nil "Hello, ~a" name)) (hello "Steve") ; => "Hello, Steve" @@ -430,7 +430,7 @@ nil ; for false - and the empty list (defun walker (n) (if (zerop n) :walked - (walker (1- n)))) + (walker (- n 1)))) (walker 5) ; => :walked diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 637f0ab6..b5e5894f 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -1,10 +1,12 @@ --- language: markdown +lang: cs-cz contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] filename: markdown.md +lang: cs-cz --- Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná diff --git a/csharp.html.markdown b/csharp.html.markdown index 677c2591..7d7f4340 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -630,7 +630,7 @@ on a new line! ""Wow!"", the masses cried"; public static class Extensions { - // EXTENSION FUNCTIONS + // EXTENSION METHODS public static void Print(this object obj) { Console.WriteLine(obj.ToString()); diff --git a/d.html.markdown b/d.html.markdown index 6f88cf84..edb3bff5 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -254,7 +254,7 @@ void main() { // Use an index, access every array element by reference (because we're // going to change each element) and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { - ref = sqrt(i + 1.0); + elem = sqrt(i + 1.0); } } ``` diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d3a192fe..94f48e65 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -4,17 +4,16 @@ filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] - ["Dennis Keller", "https://github.com/denniskeller"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de --- -Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in -der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in -der realen Welt zu lösen. - -Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung -und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu -verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern -Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große -Programmierprojekte. +Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007 +benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele +Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und +benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente +für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen +Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten +erleichtert. Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine aktive Community. @@ -24,7 +23,7 @@ aktive Community. /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// Wie bei Java gehört jede Quelldatei einem Paket an (Modularisierung). // "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. @@ -40,7 +39,7 @@ import ( // Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des -// Programms. Vergessen Sie nicht die geschweiften Klammern! +// Programms. func main() { // Println gibt eine Zeile zu stdout aus. // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. @@ -50,8 +49,8 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert, -// die aber auch bei keinen Parametern erforderlich sind. +// Funktionen können Parameter akzeptieren. Diese werden in Klammern deklariert, +// die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. @@ -99,7 +98,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre // Vorzüge, aber slices werden viel häufiger verwendet s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse - s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0 + s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Wert 0 var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung bs := []byte("eine slice") // Umwandlungs-Syntax @@ -201,7 +200,8 @@ type pair struct { x, y int } -// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface. +// Definiere eine Methode von "pair". +// Dieser Typ erfüllt jetzt das Stringer interface. func (p pair) String() string { // p ist der Empfänger // Sprintf ist eine weitere öffentliche Funktion von fmt. // Der Syntax mit Punkt greift auf die Felder zu. @@ -255,8 +255,9 @@ func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für // maps, slices und Kanäle. c := make(chan int) - // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. + // Starte drei parallele "Goroutines". + // Die Zahlen werden parallel (concurrently) erhöht. + // Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) @@ -306,14 +307,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ``` ## Weitere Resourcen -Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel -Dokumentation lesen. +Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/). +Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor +allem aber Dokumentation zur Sprache und den Paketen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr -kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen -ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). -Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen +ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/) +einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil +verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). - diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown index 2c18b8fd..ee9c6e3e 100644 --- a/de-de/latex-de.html.markdown +++ b/de-de/latex-de.html.markdown @@ -6,19 +6,19 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] translators: - ["Moritz Kammerer", "https://github.com/phxql"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de filename: latex-de.tex --- ``` -% Alle Kommentare starten fangen mit % an -% Es gibt keine Kommentare über mehrere Zeilen +% Alle Kommentare starten mit einem Prozentzeichen % -% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% LaTeX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. % MS Word oder OpenOffice Writer -% Jedes LateX-Kommando startet mit einem Backslash (\) +% Jedes LaTeX-Kommando startet mit einem Backslash (\) -% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% LaTeX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen % Weitere Dokumententypen sind z.B. book, report, presentations, etc. % Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall % wollen wir einen 12 Punkte-Font verwenden. @@ -26,7 +26,7 @@ filename: latex-de.tex % Als nächstes definieren wir die Pakete, die wir verwenden wollen. % Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, -% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% musst du die Fähigkeiten von LaTeX durch Hinzufügen von Paketen erweitern. % Wir verwenden die Pakete float und caption für Bilder. \usepackage{caption} \usepackage{float} @@ -34,30 +34,41 @@ filename: latex-de.tex % Mit diesem Paket können leichter Umlaute getippt werden \usepackage[utf8]{inputenc} +% Es gibt eigentlich keine Kommentare über mehrere Zeilen, solche kann man +% aber selbst durch die Angabe eigener Kommandos definieren. +% Dieses Kommando kann man später benutzen. +\newcommand{\comment}[1]{} + % Es können durchaus noch weitere Optione für das Dokument gesetzt werden! \author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} \date{\today} -\title{Learn LaTeX in Y Minutes!} +\title{Learn \LaTeX\ in Y Minutes!} % Nun kann's losgehen mit unserem Dokument. % Alles vor dieser Zeile wird die Preamble genannt. -\begin{document} +\begin{document} + +\comment{ + Dies ist unser selbst-definierter Befehl + für mehrzeilige Kommentare. +} + % Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann -% LateX für uns eine Titelseite generieren +% LaTeX für uns eine Titelseite generieren \maketitle -% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an. % Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem % Inhalt erscheinen. % Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. \begin{abstract} - LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! + \LaTeX -Documentation geschrieben in \LaTeX ! Wie ungewöhnlich und garantiert nicht meine Idee! \end{abstract} % Section Befehle sind intuitiv. % Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. \section{Einleitung} -Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! +Hi, mein Name ist Moritz und zusammen werden wir \LaTeX\ erforschen! \section{Noch eine section} Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. @@ -71,16 +82,16 @@ So ist's schon viel besser. % Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. % Das funktioniert auch bei anderen Befehlen. -\section*{Das ist eine unnummerierte section} -Es müssen nicht alle sections nummeriert sein! +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle Sections nummeriert sein! \section{Ein paar Notizen} -LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +\LaTeX\ ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge \textbackslash\textbackslash in den Code ein.\\ \section{Listen} -Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +Listen sind eine der einfachsten Dinge in \LaTeX. Ich muss morgen einkaufen gehen, also lass uns eine Einkaufsliste schreiben: \begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. % \item bringt enumerate dazu, eins weiterzuzählen. @@ -96,7 +107,7 @@ also lass uns eine Einkaufsliste schreiben: \section{Mathe} -Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Einer der Haupteinsatzzwecke von \LaTeX\ ist das Schreiben von akademischen Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle Symbole zu unserem Paper hinzuzufügen! \\ @@ -106,18 +117,18 @@ Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstabe um nur ein paar zu nennen.\\ Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen -Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ +Papern. So schreibt man in \LaTeX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ -% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LaTeX schreiben, % geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings % nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und % ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. -Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den \LaTeX nicht kennt! Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: -Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), Logarithmus und Exponenten ($\log$, $\exp$), Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. Lass uns eine Gleichung schreiben: \\ @@ -127,7 +138,7 @@ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ Brüche (Zähler / Nenner) können so geschrieben werden: % 10 / 7 -$^{10}/_{7}$ +$^{10}/_{7}$ % Komplexere Brüche können so geschrieben werden: % \frac{Zähler}{Nenner} @@ -142,19 +153,19 @@ Wir können Gleichungen auch in einer equation Umgebung verwenden. \end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen Wir können nun unsere Gleichung referenzieren! -Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: Grafiken, Gleichungen, Sections, etc. Summen und Integrale können mit den sum und int Befehlen dargestellt werden: -% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen -\begin{equation} +% Manche LaTeX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Grafiken} @@ -164,7 +175,7 @@ Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. \begin{figure}[H] % H ist die Platzierungsoption \centering % Zentriert die Grafik auf der Seite % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Auskommentiert, damit es nicht im Dokument auftaucht. \caption{Dreieck mit den Seiten $a$, $b$, $c$} \label{fig:right-triangle} @@ -177,7 +188,7 @@ Wir können Tabellen genauso wie Grafiken einfügen. \caption{Überschrift der Tabelle.} % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt \hline % Eine horizontale Linie 1 & Biggus & Dickus \\ @@ -187,36 +198,36 @@ Wir können Tabellen genauso wie Grafiken einfügen. % \section{Links} % Kommen bald! -\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} -Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll -in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +\section{Verhindern, dass \LaTeX\ etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem \LaTeX-Dokument. \LaTeX\ soll +in diesem Fall nicht den Quelltext als \LaTeX-Kommandos interpretieren, sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden wir eine verbatim Umgebung. % Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) % aber verbatim ist das simpelste. -\begin{verbatim} +\begin{verbatim} print("Hello World!") a%b; % Schau dir das an! Wir können % im verbatim verwenden! random = 4; #decided by fair random dice roll \end{verbatim} -\section{Kompilieren} +\section{Kompilieren} Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ Dafür musst du folgende Schritte durchführen: \begin{enumerate} - \item Schreibe das Dokument. (den LateX-Quelltext). - \item Kompiliere den Quelltext in ein PDF. + \item Schreibe das Dokument. (den \LaTeX -Quelltext). + \item Kompiliere den Quelltext in ein PDF. Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} -Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +Manche \LaTeX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt 2 wird unsichtbar im Hintergrund ausgeführt. Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet diff --git a/edn.html.markdown b/edn.html.markdown index d0bdddfc..ca04df89 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -14,7 +14,7 @@ Clojure, there are implementations of EDN for many other languages. The main benefit of EDN over JSON and YAML is that it is extensible. We will see how it is extended later on. -```Clojure +```clojure ; Comments start with a semicolon. ; Anything after the semicolon is ignored. diff --git a/elixir.html.markdown b/elixir.html.markdown index 720e080c..bf3c42a6 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -411,7 +411,7 @@ self() #=> #PID<0.27.0> ## References -* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) +* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](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) diff --git a/elm.html.markdown b/elm.html.markdown index 8c191509..944ab770 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -38,11 +38,10 @@ not False -- True 1 < 10 -- True -- Strings and characters -"This is a string." -'a' -- character -'You cant use single quotes for strings.' -- error! +"This is a string because it uses double quotes." +'a' -- characters in single quotes --- Strings can be appended +-- Strings can be appended. "Hello " ++ "world!" -- "Hello world!" {-- Lists, Tuples, and Records --} @@ -53,10 +52,10 @@ not False -- True -- The second example can also be written with two dots. [1..5] --- Append lists just like strings +-- Append lists just like strings. [1..5] ++ [6..10] == [1..10] -- True --- To add one item, use "cons" +-- To add one item, use "cons". 0 :: [1..5] -- [0, 1, 2, 3, 4, 5] -- The head and tail of a list are returned as a Maybe. Instead of checking @@ -64,6 +63,7 @@ not False -- True List.head [1..5] -- Just 1 List.tail [1..5] -- Just [2, 3, 4, 5] List.head [] -- Nothing +-- List.functionName means the function lives in the List module. -- Every element in a tuple can be a different type, but a tuple has a -- fixed length. @@ -74,23 +74,28 @@ List.head [] -- Nothing fst ("elm", 42) -- "elm" snd ("elm", 42) -- 42 --- Records are like tuples but the fields have names. --- Notice that equals signs, not colons, are used. -{ x = 3, y = 7} +-- The empty tuple, or "unit", is sometimes used as a placeholder. +-- It is the only value of its type, also called "Unit". +() + +-- Records are like tuples but the fields have names. The order of fields +-- doesn't matter. Notice that record values use equals signs, not colons. +{ x = 3, y = 7 } -- Access a field with a dot and the field name. -{ x = 3, y = 7}.x -- 3 +{ x = 3, y = 7 }.x -- 3 --- Or with an accessor fuction, a dot and then the field name. -.y { x = 3, y = 7} -- 7 +-- Or with an accessor fuction, which is a dot and the field name on its own. +.y { x = 3, y = 7 } -- 7 -- Update the fields of a record. (It must have the fields already.) { person | name = "George" } -{ physics | - position = physics.position + physics.velocity, - velocity = physics.velocity + physics.acceleration } +-- Update multiple fields at once, using the current values. +{ particle | + position = particle.position + particle.velocity, + velocity = particle.velocity + particle.acceleration } {-- Control Flow --} @@ -111,11 +116,16 @@ else -- Use case statements to pattern match on different possibilities. case aList of [] -> "matches the empty list" + [x]-> "matches a list of exactly one item, " ++ toString x x::xs -> "matches a list of at least one item whose head is " ++ toString x +-- Pattern matches go in order. If we put [x] last, it would never match because +-- x::xs also matches (xs would be the empty list). Matches do not "fall through". +-- The compiler will alert you to missing or extra cases. +-- Pattern match on a Maybe. case List.head aList of Just x -> "The head is " ++ toString x - Nothing -> "The list was empty" + Nothing -> "The list was empty." {-- Functions --} @@ -126,7 +136,7 @@ case List.head aList of multiply a b = a * b --- Apply (call) a function by passing it arguments (no commas necessay). +-- Apply (call) a function by passing it arguments (no commas necessary). multiply 7 6 -- 42 -- Partially apply a function by passing only some of its arguments. @@ -151,8 +161,8 @@ area (width, height) = area (6, 7) -- 42 --- Use curly brackets to pattern match record field names --- Use let to define intermediate values +-- Use curly brackets to pattern match record field names. +-- Use let to define intermediate values. volume {width, height, depth} = let area = width * height @@ -161,21 +171,22 @@ volume {width, height, depth} = volume { width = 3, height = 2, depth = 7 } -- 42 --- Functions can be recursive +-- Functions can be recursive. fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2) -List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34] +List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34] +-- Another recursive function (use List.length in real code). listLength aList = case aList of [] -> 0 x::xs -> 1 + listLength xs --- Function application happens before any infix operation +-- Function calls happen before any infix operator. Parens indicate precedence. cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 -- First degrees is applied to 30, then the result is passed to the trig -- functions, which is then squared, and the addition happens last. @@ -191,7 +202,7 @@ cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 True : Bool -- Functions have types too. Read -> as "goes to". Think of the rightmost type --- as the type of the return value. +-- as the type of the return value, and the others as arguments. not : Bool -> Bool round : Float -> Int @@ -220,34 +231,41 @@ origin = { x = 0, y = 0, z = 0 } -- You can give existing types a nice name with a type alias. -type alias Point3D = { x : Float, y : Float, z : Float } +type alias Point3D = + { x : Float, y : Float, z : Float } -- If you alias a record, you can use the name as a constructor function. otherOrigin : Point3D -otherOrigin = Point3D 0 0 0 +otherOrigin = + Point3D 0 0 0 --- But it's still the same type, you can equate them +-- But it's still the same type, so you can equate them. origin == otherOrigin -- True -- By contrast, defining a union type creates a type that didn't exist before. -- A union type is so called because it can be one of many possibilities. -- Each of the possibilities is represented as a "tag". -type Direction = North | South | East | West +type Direction = + North | South | East | West -- Tags can carry other values of known type. This can work recursively. -type IntTree = Leaf | Node Int IntTree IntTree - +type IntTree = + Leaf | Node Int IntTree IntTree -- "Leaf" and "Node" are the tags. Everything following a tag is a type. + -- Tags can be used as values or functions. root : IntTree -root = Node 7 Leaf Leaf +root = + Node 7 Leaf Leaf -- Union types (and type aliases) can use type variables. -type Tree a = Leaf | Node a (Tree a) (Tree a) +type Tree a = + Leaf | Node a (Tree a) (Tree a) +-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a." --- You can pattern match union tags. The uppercase tags must be matched exactly. --- The lowercase variables will match anything. Underscore also matches --- anything, but signifies that you aren't using it. +-- Pattern match union tags. The uppercase tags will be matched exactly. The +-- lowercase variables will match anything. Underscore also matches anything, +-- but signifies that you aren't using it. leftmostElement : Tree a -> Maybe a leftmostElement tree = case tree of @@ -260,21 +278,20 @@ leftmostElement tree = {-- Modules and Imports --} --- The core libraries are organized into modulues, as are any third-party --- libraries you may use. For large projects, you can define your own modulues. +-- The core libraries are organized into modules, as are any third-party +-- libraries you may use. For large projects, you can define your own modules. -- Put this at the top of the file. If omitted, you're in Main. module Name where --- By default, everything is exported. --- Limit what values and types are exported -module Name (Type, value) where +-- By default, everything is exported. You can specify exports explicity. +module Name (MyType, myValue) where -- One common pattern is to export a union type but not its tags. This is known -- as an "opaque type", and is frequently used in libraries. --- Import code from other modules to use it in this one --- Places Dict in scope, so you can call Dict.insert +-- Import code from other modules to use it in this one. +-- Places Dict in scope, so you can call Dict.insert. import Dict -- Imports the Dict module and the Dict type, so your annotations don't have to @@ -318,6 +335,8 @@ $ elm repl -- Install a new package, and record it in elm-package.json. $ elm package install evancz/elm-html +-- See what changed between versions of a package. +$ elm package diff evancz/elm-html 3.0.0 4.0.2 -- Elm's package manager enforces semantic versioning, so minor version bumps -- will never break your build! ``` @@ -335,12 +354,14 @@ Here are some useful resources. * Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of: * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default - * Data structures like [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) + * [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) and its cousin [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), commonly used for missing values or error handling + * Data structures like [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) * JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) -* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay with examples on how to organize code into components. +* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay by Elm's creator with examples on how to organize code into components. * The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful. +* [Scope in Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) and [How to Read a Type Annotation](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). More community guides on the basics of Elm, written for JavaScript developers. Go out and write some Elm! diff --git a/es-es/brainfuck-es.html.markdown b/es-es/bf-es.html.markdown index 550511da..c93b8c3a 100644 --- a/es-es/brainfuck-es.html.markdown +++ b/es-es/bf-es.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown new file mode 100644 index 00000000..aff3c603 --- /dev/null +++ b/es-es/latex-es.html.markdown @@ -0,0 +1,213 @@ +--- +language: latex +lang: es-es +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +filename: learn-latex-es.tex +--- + +```tex +% Todas las líneas comentadas comienzan con % +% No existen los comentarios multilínea + +% LaTeX NO es un software de procesamiento de texto que cumple con +% "Lo que ves es lo que tienes" como MS Word u OpenOffice + +% Todos los comandos de LaTeX comienzan con una contrabarra (\) + +% Los documentos LaTeX comienzan definiendo el tipo de documento que se va a +% compilar. Algunos tipos de documentos son libros, informes, presentaciones, +% etc. Las opciones para el documento comienzan en los corchetes []. En este +% caso, se especifica que queremos utilizar una fuente de tamaño 12pt. +\documentclass[12pt]{article} + +% A continuación, definimos los paquetes que utilizará el documento. +% Si quieres incluir gráficos, texto coloreado o código fuente de otro lenguaje, +% debes extender las funciones de LaTeX. Esto se consigue añadiendo paquetes. +% A continuación se incluirán los paquetes float y caption para figuras. +\usepackage{caption} +\usepackage{float} + +% También podemos definir otras propiedades en el documento +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Ahora estamos preparados para comenzar el documento +% Todo lo que se encuentre antes de esta línea se llama "El Preámbulo" +\begin{document} +% Si especificamos el autor, fecha y título, LaTeX creará una página como título +% por nosotros +\maketitle + +% La mayoría de los artículos de investigación tienen un abstract. Es posible +% utilizar comandos predefinidos para ello. +% Esto debería aparecer en su orden lógico. Tras el título pero antes de las +% secciones principales del cuerpo. +% Este comando está disponible en los tipos de documentos article y report. +\begin{abstract} + Documentación de LaTex escrita en LaTex. +\end{abstract} + +% Los comandos de sección son intuitivos. +% Todos los títulos de secciones son añadidos automáticamente a la tabla de contenidos. +\section{Introducción} +Hola, mi nombre es Mario Pérez y estoy traduciendo este documento para aprender LaTex. + +\section{Otra sección} +Este es el texto de otra sección. Creo que necesitará una subsección. + +\subsection{Esto es una subsección} % Las subsecciones también son fáciles. +Creo que necesitamos otra más. + +\subsubsection{Pitágoras} +Mejor ahora. +\label{subsec:pitagoras} + +% Utilizando el asterisco podemos decirle a LaTeX que no ponga los números de secciones y subsecciones. +% Esto también funciona con otros comandos de LaTeX. +\section*{Esto es una sección no numerada} +¡No todas las secciones tienen que estar numeradas! + +\section{Algunas notas} +LaTeX es generalmente bastante bueno situando el texto donde debe ir. Si una lína \\ necesita \\ ser \\ rota \\ puedes poner \textbackslash\textbackslash en el código fuente. \\ + +\section{Listas} +Las listas son de las cosas más fáciles de crear en LaTeX. Necesito ir a comprar mañana, así que vamos a crear una lista de la compra. +\begin{enumerate} % Esto crea una lista numerada. + % \item crea un elemento + \item Ensalada. + \item 27 sandías. + \item Pescado. + % podemos incluso sobreescribir el número del ítem usando [] + \item[cuántos?] Plátanos. + + No es un ítem de la lista, pero sigue siendo parte de la enumeración. + +\end{enumerate} % Todos los contextos deben tener un final. + +\section{Matemáticas} + +Uno de los usos principales de LaTeX es la producción de artículos académicos o técnicos. Normalmente relacionados con la ciencia y las matemáticas. Debido a esto, necesitamos poder añadir símbolos especiales a nuestro artículo.\\ + +En matemáticas hay muchos símbolos. Más de los que podemos encontrar en un teclado. Flechas o letras por nombrar un par.\\ + +Algunos símbolos juegan un papel fundamental en muchos artículos de investigación matemática. Así es como se establece que todo Y pertenece a X: $\forall$ x $\in$ X. \\ +He necesitado añadir el signo $ antes de los símbolos. Esto se debe a que cuando escribimos, estamos en modo texto. Sin embargo, los símbolos solo pueden utilizarse en modo matemático, al cual se entra con el signo $. +% Lo opuesto también se cumple. Una variable también puede ser mostrada en modo matemático, al que también se puede entrar con \[\] + +\[a^2 + b^2 = c^2 \] + +Mi letra griega favorita es $\xi$. También me gustan $\beta$, $\gamma$ y $\sigma$. +Todavía no he encontrado una letra griega que LaTeX no conozca. + +Los operadores son también una parte esencial de un documento matemático: +funciones trigonométricas ($\sin$, $\cos$, $\tan$), logaritmos y exponenciales ($\log$, $\exp$), límites ($\lim$), etc. tienen comandos predefinidos en LaTeX. + +Vamos a escribir una ecuación para ver cómo se hace: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Las fracciones (numeradores-denominadores) pueden escribirse de la siguiente forma: + +% 10 / 7 +$^{10}/_{7}$ + +% Las fracciones relativamente complejas pueden escribirse como +% \frac{numerador}{denominador} +$\frac{n!}{k!(n - k)!}$ \\ + +También podemos insertar ecuaciones en un contexto de ecuación. + +% Mostrar matemáticas en el contexto de ecuaciones +\begin{equation} % entra en modo matemático + c^2 = a^2 + b^2. + \label{eq:pitagoras} % para referencias +\end{equation} % Todos los contextos deben tener un final. + +Podemos referenciar nuestra nueva ecuación. +Ecuación ~\ref{eq:pythagoras} también se conoce como el Teorema de Pitágoras, el cual también se encuentra en la sección ~\ref{subsec:pythagoras}. Muchas cosas pueden ser etiquetadas: figures, equations, sections, etc. + +Los sumatorios e integrales son escritor son los comandos sum e int: + +% Algunos compiladores de LaTeX se quejarán si hay líneas en blanco +% En un contexto de ecuación. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figuras} + +Vamos a insertar una figura. Situarla puede ser algo complicado. + +\begin{figure}[H] % H aquí establece la situación de la figura. + \centering % centra la figura en la página + % Inserta una figura escalada por 0.8 el ancho de la página. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % La línea anterior ha sido comentada para poder compilar este archivo. Por favor, usa tu imaginación. + \caption{Triángulo con lados $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tablas} +También podemos insertar tablas de la misma manera que las figuras. + +\begin{table}[H] + \caption{Título para la tabla.} + % los argumentos en {} describen cómo cada fila va a ser representada. + \begin{tabular}{c|cc} + Número & Nombre & Apellido \\ + \hline % una línea horizontal + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Hyperlinks} % En construcción + +\section{Haciendo que LaTeX no compile algo (por ejemplo, código fuente)} +Digamos que queremos incluir código fuente dentro de nuestro documento LaTex. En ese caso, debemos indicarle a LaTeX que no trate de compilarlo y simplemente lo muestre en el documento. Esto lo realizamos en el contexto verbatim. + +% Hay otros paquetes para esta misma tarea, pero verbatim es el más básico. +\begin{verbatim} + print("Hola Mundo!") + a%b; % Podemos usar los signos % en verbatim. + aleatorio = 4; # Número aleatorio +\end{verbatim} + +\section{Compilación} + +Ahora mismo te estarás preguntando cómo compilar este fabuloso documento y obtener un documento PDF.\\ +Para obtener el documento final utilizando LaTeX hay que seguir los siguientes pasos: + \begin{enumerate} + \item Escribe el documento en texto plano. + \item Compila el código para producir un PDF. + Los pasos de compilación serán algo parecido a esto (en Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Un gran número de editores LaTeX combinan ambos pasos para que sea más sencillo obtener el documento. + +Escribe toda la información de formato en el paso 1 y con el paso 2 obtendrás el documento que has definido en el paso anterior. + +\section{End} + +Esto es todo por ahora. + +% fin del documento +\end{document} +``` + +## Más información sobre LaTeX + +* El wikilibro LaTeX: [https://es.wikibooks.org/wiki/Manual_de_LaTeX](https://es.wikibooks.org/wiki/Manual_de_LaTeX) +* Un tutorial real: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown new file mode 100644 index 00000000..fa52353c --- /dev/null +++ b/es-es/php-es.html.markdown @@ -0,0 +1,825 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +lang: es-es +filename: learnphp-es.php +--- + +Este documento explica el funcionamiento de PHP 5+. + +```php +<?php // El código PHP debe estar dentro de etiquetas <?php + +// Si tu fichero php solo contiene código php, es una buena práctica +// omitir la etiqueta de cierre php para prevenir salidas acidentales. + +// Dos barras comienzan un comentario de una línea. + +# También lo hará una almohadilla, pero // es más común + +/* + Escribir texto entre una barra-asterisco y asterisco-barra + crea un comentario multilínea. +*/ + +// Utiliza "echo" o "print" para imprimir por pantalla +print('Hola '); // Imprime "Hola " sin salto de línea + +// () son opcionales para print y echo +echo "Mundo\n"; // Imprime "Mundo" con un salto de línea +// (todas las sentencias deben finalizar con un punto y coma) + +// Cualquier cosa fuera de las etiquetas <?php se imprime automáticamente +?> +¡Hola Mundo de nuevo! +<?php + + +/************************************ + * Tipos y variables + */ + +// Las variables comienzan con el símbolo $. +// Una variable válida comienza con una letra o guión bajo, +// seguida de cualquier cantidad de letras, números o guiones bajos. + +// Las variables booleanas no distinguen entre mayúsculas o minúsculas +$boolean = true; // o TRUE o True +$boolean = false; // o FALSE o False + +// Enteros +$int1 = 12; // => 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (un 0 al comienzo declara un número octal) +$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal) + +// Floats (también conocidos como doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Eliminar variable +unset($int1); + +// Operaciones aritméticas +$suma = 1 + 1; // 2 +$diferencia = 2 - 1; // 1 +$producto = 2 * 2; // 4 +$cociente = 2 / 1; // 2 + +// Operaciones aritméticas de escritura rápida +$numero = 0; +$numero += 1; // Incrementa $numero en 1 +echo $numero++; // Imprime 1 (incremento después la evaluación) +echo ++$numero; // Imprime 3 (incremento antes de la evaluación) +$numero /= $float; // Divide y asigna el cociente a $numero + +// Las cadenas de caracteres deben declararse entre comillas simples +$sgl_quotes = '$String'; // => '$String' + +// Evita utilizar comillas dobles excepto para embeber otras variables +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Los caracteres especiales solo son válidos entre comillas dobles +$escaped = "Esto contiene \t un caracter tabulador."; +$unescaped = 'Esto solo contiene una barra y una t: \t'; + +// Rodea una variable entre corchetes si es necesario +$dinero = "Tengo $${numero} en el banco."; + +// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs interpola cadenas de caracteres +$heredoc = <<<END +Multi line +$sgl_quotes +END; + +// La concatenación de cadenas de caracteres se realiza con . +echo 'Esta cadena de caracteres ' . 'está concatenada'; + +// Las cadenas de caracteres pueden ser pasadas como parámetros en un echo +echo 'Multiples', 'Parametros', 'Validos'; // Devuelve 'MultiplesParametrosValidos' + + +/******************************** + * Constantes + */ + +// Una constante se define utilizando define() +// y nunca puede ser cambiada en tiempo de ejecución + +// un nombre válido para una constante debe comenzar con una letra o guión bajo, +// seguido por cualquier número de letras, números o guiones bajos. +define("FOO", "algo"); + +// el acceso a una constante se puede realizar llamando a la variable elegida sin un símbolo de $ +echo FOO; // Devuelve 'algo' +echo 'Esto imprime '.FOO; // Devuelve 'Esto imprime algo' + + + +/******************************** + * Arrays + */ + +// Todos los arrays en PHP son asociativos (hashmaps), + +// Los arrays asociativos son conocidos como hashmaps en algunos lenguajes. + +// Funciona con todas las versiones de php +$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3); + +// PHP 5.4 introdujo una nueva sintaxis +$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3]; + +echo $asociativo['Uno']; // imprime 1 + +// Lista literales implícitamente asignados con claves enteras +$array = ['Uno', 'Dos', 'Tres']; +echo $array[0]; // => "Uno" + +// Añadir un elemento al final de un array +$array[] = 'Cuatro'; +// o +array_push($array, 'Cinco'); + +// Eliminar un elemento de un array +unset($array[3]); + +/******************************** + * Salidas por pantalla + */ + +echo('¡Hola Mundo!'); +// Imprime ¡Hola Mundo! en stdout. +// Stdout es la página web si se está ejecutando en un navegador. + +print('!Hola Mundo!'); // Es lo mismo que echo + +// No es necesario el paréntesis en echo y print +echo '¡Hola Mundo!'; +print '¡Hola Mundo!'; + +$parrafo = 'parrafo'; + +echo 100; // Haz echo de escalares directamente +echo $parrafo; // o de variables + +// Si las etiquetas cortas estás configuradas y tu versión de PHP es +// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo +?> +<p><?= $parrafo?></p> +<?php + +$x = 1; +$y = 2; +$x = $y; // $x ahora contiene el mismo valor que $y +$z = &$y; +// $z contiene ahora una referencia a $y. Un cambio en el valor de +// $z cambiará también el valor de $y, y viceversa. +// $x sin embargo, tendrá el valor original de $y + +echo $x; // => 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Dump muestra el tipo y valor de una variable en stdout +var_dump($z); // imprime int(0) + +// Para mostrar el valor de una variable en un formato legible para humanos +print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres ) + +/******************************** + * Lógica + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert lanza una advertencia si su argumento no es verdadero + +// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos. +assert($a == $b); // igualdad +assert($c != $a); // desigualdad +assert($c <> $a); // desigualdad alternativa +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operador 'Spaceship' (desde PHP 7) +// Devuelve 0 si ambos valores son iguales +// Devuelve 1 si el valor de la izquierda es mayor +// Devuelve -1 si el valor de la derecha es mayor + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 porque son iguales +echo $a <=> $b; // -1 porque $a < $b +echo $b <=> $a; // 1 porque $b > $a + +// Las variables pueden ser convertidas entre tipos, dependiendo de su uso. + +$entero = 1; +echo $entero + $entero; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (los strings son convertidos a enteros) + +$string = 'uno'; +echo $string + $string; // => 0 +// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número + +// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo + +$boolean = (boolean) 1; // => true + +$cero = 0; +$boolean = (boolean) $cero; // => false + +// También hay funciones dedicadas a la conversión de tipos +$entero = 5; +$string = strval($entero); + +$var = null; // Valor nulo + + +/******************************** + * Estructuras de control + */ + +if (true) { + print 'He sido imprimido'; +} + +if (false) { + print 'Yo no'; +} else { + print 'He sido imprimido'; +} + +if (false) { + print 'No se imprime'; +} elseif(true) { + print 'Sí se imprime'; +} + +// operador ternario +print (false ? 'No se imprime' : 'Sí se imprime'); + +// atajo para el operador ternario desde PHP 5.3 +// equivalente de "$x ? $x : 'Sí'"" +$x = false; +print($x ?: 'Sí'); + +// operador 'no definido' desde php 7 +$a = null; +$b = 'Imprime'; +echo $a ?? 'a no está definido'; // imprime 'a no está definido' +echo $b ?? 'b no está definido'; // imprime 'Imprime' + + +$x = 0; +if ($x === '0') { + print 'No imprime'; +} elseif($x == '1') { + print 'No imprime'; +} else { + print 'Imprime'; +} + + + +// Esta sintaxis alternativa se utiliza para plantillas: +?> + +<?php if ($x): ?> +Esto se muestra si la evaluación es verdadera. +<?php else: ?> +En otro caso, se muestra esto. +<?php endif; ?> + +<?php + +// Utiliza el switch para tener algo más de lógica. +switch ($x) { + case '0': + print 'Switch does type coercion'; + break; // Debes incluir un break para no seguir con los casos 'Dos' y 'Tres' + case 'Dos': + case 'Tres': + // Hacer algo si la variables es 'Dos' o 'Tres' + break; + default: + // Hacer algo por defecto +} + +// Los bucles While, do...while y for te serán familiares +$i = 0; +while ($i < 5) { + echo $i++; +}; // Imprime "01234" + +echo "\n"; + +$i = 0; +do { + echo $i++; +} while ($i < 5); // Imprime "01234" + +echo "\n"; + +for ($x = 0; $x < 10; $x++) { + echo $x; +} // Imprime "0123456789" + +echo "\n"; + +$ruedas = ['bicicleta' => 2, 'coche' => 4]; + +// Los bucles foreach pueden iterar por arrays +foreach ($ruedas as $numero_ruedas) { + echo $numero_ruedas; +} // Imprime "24" + +echo "\n"; + +// También se puede iterar sobre las claves, así como sobre los valores +foreach ($ruedas as $vehiculo => $numero_ruedas) { + echo "Un $vehiculo tiene $numero_ruedas ruedas"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Sale fuera del bucle while + } + echo $i++; +} // Imprime "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Se salta esta iteración del bucle + } + echo $i; +} // Imprime "0124" + + +/******************************** + * Funciones + */ + +// Define una función con "function": +function mi_funcion () { + return 'Hola'; +} + +echo mi_funcion(); // => "Hola" + +// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier +// número de letras, números o guiones bajos. + +function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1 + $resultado = $x + $y; + return $resultado; +} + +echo anadir(4); // => 5 +echo anadir(4, 2); // => 6 + +// $resultado no es accesible fuera de la función +// print $resultado; // Devuelve una advertencia. + +// Desde PHP 5.3 se pueden declarar funciones anónimas +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Las funciones pueden devolver funciones +function bar ($x, $y) { + // Utiliza 'use' para meter variables de fuera de la función + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Imprime "A - B - C" + +// Puedes llamar a funciones utilizando cadenas de caracteres +$nombre_funcion = 'add'; +echo $nombre_funcion(1, 2); // => 3 +// Es útil para determinarl qué función ejecutar. +// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]); + + +// Puedes obtener todos los parámetros pasados a una función +function parametros() { + $numero_argumentos = func_num_args(); + if ($numero_argumentos > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo | + +// Desde PHP 5.6 se puede obtener un número variable de argumentos +function variable($palabra, ...$lista) { + echo $palabra . " || "; + foreach ($lista as $item) { + echo $item . ' | '; + } +} + +variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo | + +/******************************** + * Includes + */ + +<?php +// Los ficheros PHP incluidos deben comenzar también con la etiqueta de <?php + +include 'mi-fichero.php'; +// El código de mi-fichero.php ya está disponible en el entorno actual. +// Si el fichero no puede ser incluido (por ejemplo porque no se ha encontrado), +// se muestra una advertencia. + +include_once 'mi-fichero.php'; +// Si el código del fichero mi-fichero.php ya ha sido incluido, ya no se +// incluirá de nuevo. Este previene errores por múltiples declaraciones. + +require 'mi-fichero.php'; +require_once 'mi-fichero.php'; +// Es lo mismo que el include(), pero require() causará un error fatal si el archivo +// no ha podido ser incluido. + +// Contenido de mi-include.php: +<?php + +return 'Cualquier cosa.'; +// acabar archivo + +// Los include y require también pueden devolver un valor. +$valor = include 'mi-include.php'; + +// Los archivos son incluidos en función de la ruta data o, si ninguna ruta es +// especificada se utilizará la directiva de configuración de include_path. Si el +// fichero no se encuentra en el include_path, include comprobará la ruta del código +// que lo llama antes de fallar. +/* */ + +/******************************** + * Clases + */ + +// Las clases son definidas con la palabra clave class + +class MiClase +{ + const MI_CONSTANTE = 'valor'; // Una constante + + static $staticVar = 'static'; + + // Las variables estáticas y su visibilidad + public static $publicStaticVar = 'publicStatic'; + // Accesible solo dentro de su clase + private static $privateStaticVar = 'privateStatic'; + // Accesible desde la clase y las subclases + protected static $protectedStaticVar = 'protectedStatic'; + + // Las propiedades deben declarar su visibilidad + public $propiedad = 'public'; + public $instanceProp; + protected $prot = 'protected'; // Accesible desde la clase y las subclases + private $priv = 'private'; // Accesible solo desde la clase + + // Crear un constructor con __construct + public function __construct($instanceProp) { + // Accede a las variables de la instancia con $this + $this->instanceProp = $instanceProp; + } + + // Los métodos son declarados como funciones dentro de una clase + public function miMetodo() + { + print 'MiClase'; + } + + // la palabra clave final hará una función no sobreescribible + final function noMePuedesSobreEscribir() + { + } + +/* + * Declarar propiedades de clase o métodos como estáticos los hace accesibles sin + * necesidad de instanciar la clase. Una propiedad declarada como estática no + * puede ser accedida mediante una instancia de la clase, pero sí mediante un + * método estático. + */ + + public static function miMetodoEstatico() + { + print 'Soy estático'; + } +} + +// Las constantes de una clase siempre pueden ser accedidas estáticamente +echo MiClase::MI_CONSTANTE; // Muestra 'valor'; + +echo MiClase::$staticVar; // Muestra 'static'; +MiClase::miMetodoEstatico(); // Muestra 'Soy estático'; + +// Instancia una clase usando new +$mi_clase = new MiClase('Una instancia'); +// Los paréntesis son opcionales si no se pasa ningún argumento. + +// Accede a los miembros de una clase utilizando -> +echo $mi_clase->propiedad; // => "public" +echo $mi_clase->instanceProp; // => "Una instancia" +$mi_clase->miMetodo(); // => "MiClase" + + +// Extender clases utilizando "extends" +class MiOtraClase extends MiClase +{ + function imprimePropiedadProtegida() + { + echo $this->prot; + } + + // Sobreescribe un método + function miMetodo() + { + parent::miMetodo(); + print ' > MiOtraClase'; + } +} + +$mi_otra_clase = new MiOtraClase('Propiedad de instancia'); +$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected" +$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase" + +final class NoMePuedesExtender +{ +} + +// Puedes utilizar "métodos mágicos" para crear los getters y setters +class MiClaseMapeada +{ + private $propiedad; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MiClaseMapeada(); +echo $x->propiedad; // Utilizará el método __get() +$x->propiedad = 'Algo'; // Utilizará el método __set() + +// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o +// implementando interfaces (utilizando la palabra clave implements). +// Una interfaz puede ser declarada con la palabra clave interface. + +interface InterfazUno +{ + public function hazAlgo(); +} + +interface InterfazDos +{ + public function hazOtraCosa(); +} + +// las interfaces pueden ser extendidas +interface InterfazTres extends InterfazDos +{ + public function hazCualquierOtraCosa(); +} + +abstract class MiClaseAbstracta implements InterfazUno +{ + public $x = 'hazAlgo'; +} + +class MiOtraClase extends MiClaseAbstracta implements InterfazDos +{ + public function hazAlgo() + { + echo $x; + } + + public function hazOtraCosa() + { + echo 'hazOtraCosa'; + } +} + + +// Las clases pueden implementar más de una interfaz +class CualquierOtraClase implements InterfazUno, InterfazDos +{ + public function hazAlgo() + { + echo 'hazAlgo'; + } + + public function hazOtraCosa() + { + echo 'hazOtraCosa'; + } +} + + +/******************************** + * Traits + */ + +// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait" + +trait MiTrait +{ + public function miMetodoTrait() + { + print 'Tengo trait'; + } +} + +class MiClaseTrait +{ + use MiTrait; +} + +$cls = new MiClaseTrait(); +$cls->miMetodoTrait(); // Imprime "Tengo trait" + + +/******************************** + * Namespaces + */ + +// Esta sección está separada porque una declaración de namespace debe +// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso + +<?php + +// Por defecto, las clases existen en el namespace global y pueden ser llamadas +// explícitamente con una contrabarra. + +$cls = new \MiClase(); + + + +// Estableder el namespace para un archivo +namespace Mi\Namespace; + +class MiClase +{ +} + +// (de otro archivo) +$cls = new Mi\Namespace\MiClase; + +// O de otro namespace. +namespace Mi\Otro\Namespace; + +use Mi\Namespace\MiClase; + +$cls = new MiClase(); + +// O se puede asignar un ales al namespace + +namespace Mi\Otro\Namespace; + +use Mi\Namespace as OtroNamespace; + +$cls = new OtroNamespace\MiClase(); + + +/********************** +* Late Static Binding +* +*/ + +class ClasePadre { + public static function quien() { + echo "Soy una " . __CLASS__ . "\n"; + } + public static function test() { + // Auto referencia a la clase en la que el método está definido + self::quien(); + // Referencia estáticamente a la clase donde el método ha sido llamado + static::quien(); + } +} + +ClasePadre::test(); +/* +Soy una ClasePadre +Soy una ClasePadre +*/ + +class ClaseHija extends ClasePadre { + public static function quien() { + echo "Pero soy una " . __CLASS__ . "\n"; + } +} + +ClaseHija::test(); +/* +Soy una ClasePadre +Pero soy una ClaseHija +*/ + + +/********************** +* Manejo de errores +* +*/ + +// Una simple gestión de errores puede ser realizada con un bloque try catch + +try { + // Haz algo +} catch (Exception $e) { + // Maneja la excepción +} + +// Cuando se utilicen bloques try catch en un entorno con namespaces hay que +// usar lo siguiente + +try { + // Haz algo +} catch (\Exception $e) { + // Maneja la excepción +} + +// Excepciones personalizadas + +class MiExcepcion extends Exception {} + +try { + + $condicion = true; + + if ($condicion) { + throw new MiExcepcion('Ha pasado algo'); + } + +} catch (MiExcepcion $e) { + // Manejar la excepción +} + +``` + +## Más información + +Visita la [documentación oficial de PHP](http://www.php.net/manual/) para más referencias +y apoyo de la comunidad. + +Si estás interesado en buenas prácticas, visita +[PHP The Right Way](http://www.phptherightway.com/). + +Si vienes de un lenguaje con una buena gestión de paquetes, visita +[Composer](http://getcomposer.org/). + +Para estándares comunes, visita el PHP Framework Interoperability Group +[PSR standards](https://github.com/php-fig/fig-standards). diff --git a/fa-ir/brainfuck-fa.html.markdown b/fa-ir/bf-fa.html.markdown index ef2bcba3..bc5d8dc4 100644 --- a/fa-ir/brainfuck-fa.html.markdown +++ b/fa-ir/bf-fa.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] lang: fa-ir diff --git a/factor.html.markdown b/factor.html.markdown new file mode 100644 index 00000000..a0726420 --- /dev/null +++ b/factor.html.markdown @@ -0,0 +1,182 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor +--- + +Factor is a modern stack-based language, based on Forth, created by Slava Pestov. + +Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. + +``` +! This is a comment + +! Like Forth, all programming is done by manipulating the stack. +! Stating a literal value pushes it onto the stack. +5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode + +! Those numbers get added to the stack, from left to right. +! .s prints out the stack non-destructively. +.s ! 5 2 3 56 76 23 65 + +! Arithmetic works by manipulating data on the stack. +5 4 + ! No output + +! `.` pops the top result from the stack and prints it. +. ! 9 + +! More examples of arithmetic: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! A number of words are provided to manipulate the stack, collectively known as shuffle words. + +3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 +2 5 swap / ! swap the top with the second element: 5 / 2 +4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 +1 2 3 nip .s ! remove the second item (similar to drop): 1 3 +1 2 clear .s ! wipe out the entire stack +1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 + +! Creating Words +! The `:` word sets Factor into compile mode until it sees the `;` word. +: square ( n -- n ) dup * ; ! No output +5 square . ! 25 + +! We can view what a word does too. +! \ suppresses evaluation of a word and pushes its identifier on the stack instead. +\ square see ! : square ( n -- n ) dup * ; + +! After the name of the word to create, the declaration between brackets gives the stack effect. +! We can use whatever names we like inside the declaration: +: weirdsquare ( camel -- llama ) dup * ; + +! Provided their count matches the word's stack effect: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok + +! Where Factor differs from Forth is in the use of quotations. +! A quotation is a block of code that is pushed on the stack as a value. +! [ starts quotation mode; ] ends it. +[ 2 + ] ! Quotation that adds 2 is left on the stack +4 swap call . ! 6 + +! And thus, higher order words. TONS of higher order words. +2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 +3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 +4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values +2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack + +! Conditionals +! Any value is true except the built-in value f. +! A built-in value t does exist, but its use isn't essential. +! Conditionals are higher order words as with the combinators above. + +5 [ "Five is true" . ] when ! Five is true +0 [ "Zero is true" . ] when ! Zero is true +f [ "F is true" . ] when ! No output +f [ "F is false" . ] unless ! F is false +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true + +! By default the conditionals consume the value under test, but starred variants +! leave it alone if it's true: + +5 [ . ] when* ! 5 +f [ . ] when* ! No output, empty stack, f is consumed because it's false + + +! Loops +! You've guessed it.. these are higher order words too. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Loop through the list: +{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack + +! Loop reducing or building lists: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 +1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } + +! If all else fails, a general purpose while loop: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times + ! Yes, it's hard to read + ! That's what all those variant loops are for + +! Variables +! Usually Factor programs are expected to keep all data on the stack. +! Using named variables makes refactoring harder (and it's called Factor for a reason) +! Global variables, if you must: + +SYMBOL: name ! Creates name as an identifying word +"Bob" name set-global ! No output +name get-global . ! "Bob" + +! Named local variables are considered an extension but are available +! In a quotation.. +[| m n ! Quotation captures top two stack values into m and n + | m n + ] ! Read them + +! Or in a word.. +:: lword ( -- ) ! Note double colon to invoke lexical variable extension + 2 :> c ! Declares immutable variable c to hold 2 + c . ; ! Print it out + +! In a word declared this way, the input side of the stack declaration +! becomes meaningful and gives the variable names stack values are captured into +:: double ( a -- result ) a 2 * ; + +! Variables are declared mutable by ending their name with a shriek +:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a + a ! Push a + a 2 * a! ! Multiply a by 2 and store result back in a + a ; ! Push new value of a +5 mword2 ! Stack: 5 10 + +! Lists and Sequences +! We saw above how to push a list onto the stack + +0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 +10 { 1 2 3 4 } nth ! Error: sequence index out of bounds +1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 +10 { 1 2 3 4 } ?nth ! No error if out of bounds: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! And if you want to get meta, quotations are sequences and can be dismantled.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Ready For More? + +* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown new file mode 100644 index 00000000..52c60182 --- /dev/null +++ b/fi-fi/ruby-fi.html.markdown @@ -0,0 +1,608 @@ +--- +language: ruby +filename: learnruby-fi.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] +translators: + - ["Oliver Vartiainen", "https://github.com/firoxer"] +lang: fi-fi +--- + +```ruby +# Tässä yhden rivin kommentti + +=begin +Tässä usean rivin kommentti +Näitä ei kylläkään käytetä +Joten käytetään vastedes vain yksirivisiä +=end + +# Tärkeintä on muistaa, että Rubyssa kaikki pohjautuu olioihin. + +# Luvutkin ovat olioita: + +3.class #=> Fixnum + +3.to_s #=> "3" + +# Peruslaskutoimituksia: +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# Bittioperaatioita: +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Laskutoimitukset ovat vain syntaksisokeria lukuolion laskumetodin kutsulle: +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Erityisarvotkin ovat olioita: + +nil # vastaa joidenkin kielten "null"-arvoa +true # tosi +false # epätosi + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Samanvertaisuuden testaus: +1 == 1 #=> true +2 == 1 #=> false + +# ...ja sama eriarvoisuudelle: +1 != 1 #=> false +2 != 1 #=> true + +# "nil" ja "false" ovat ainoat epätodet arvot; kaikki muu ymmärretään todeksi: +!nil #=> true +!false #=> true +!0 #=> false + +# Lisää vertailuoperaatioita: +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Kahdensuuntainen vertailuoperaattori: +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Logiikkaoperaattorit: +true && false #=> false +true || false #=> true +!true #=> false + +# Merkkipohjaisten logiikkaoperaattorien vaihtoehtona on sanalliset muodot, +# joilla on hyvin matala presedenssi. Niillä voi muokata ohjelman kulkua +# esimerkiksi väitelausekkeita ketjuttaen. + +# Metodia `do_something_else` kutsutaan vain, jos `do_something` onnistuu: +do_something() and do_something_else() +# Metodia `log_error` kutsutaan vain, jos `do_something` epäonnistuu: +do_something() or log_error() + +# Merkkijonot ovat olioita: + +'Tässä on merkkijono'.class #=> String +"Rajaavat lainausmerkit voivat olla yksin- tai kaksinkertaisia".class #=> String + +täyte = 'sisällyttää muita merkkijonoja' +"Kaksinkertaisilla lainausmerkeillä voi #{täyte}" +#=> "Kaksinkertaisilla lainausmerkeillä voi sisällyttää muita merkkijonoja" + +# Yksinkertaisia lainausmerkkejä kannattaa silti suosia, sillä kaksinkertaiset +# merkit saattavat aiheuttaa turhia kielensisäisiä tarkistuksia. + +# Merkkijonoja voi yhdistellä toisiinsa: +'hello ' + 'world' #=> "hello world" + +# ...mutta luvut vaativat ensin tyyppimuunnoksen: +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Merkkijonoja voi soveltaa laskutoimituksiin... odotettavin seurauksin: +'hello ' * 3 #=> "hello hello hello " + +# Merkkijonoa voi jatkaa toisella: +'hello' << ' world' #=> "hello world" + +# Tulosteen luonti kera rivinvaihdon: +puts "I'm printing!" +#=> I'm printing! +#=> nil + +# ...ja ilman rivinvaihtoa: +print "I'm printing!" +#=> I'm printing! => nil + +# Muuttujien määrittely: +x = 25 #=> 25 +x #=> 25 + +# Arvon asettaminen palauttaa arvon itsensä, joten usean muuttujan arvon +# yhtäaikainen määrittely käy vaivatta: +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Muuttujien sanaerottimena käytetään alaviivaa: +snake_case = true + +# Lisäksi Rubyssa suositaan ytimekkäitä nimiä: +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Symbolit + +# Symbolit ovat muuttumattomia, uudelleenkäytettäviä vakioita. +# Niitä käytetään merkkijonojen sijaan, kun tarkoitus on viitata arvoon, +# jolla on tietty, pysyvä merkitys: + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Taulukot + +# Tässä taulukko: +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Taulukko saa koostua erityyppisistä arvoista: +[1, 'hello', false] #=> [1, "hello", false] + +# Taulukon alkioihin voi viitata järjestysnumerolla nollasta alkaen: +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + +# Kuten laskutoimituksissa nähty syntaksisokeri on myös taulukon alkioiden haku +# pohjimmiltaan vain taulukko-olioon kuuluvan "[]"-metodin kutsu: +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Haku käy myös lopustapäin: +array[-1] #=> 5 +array.last #=> 5 + +# Alitaulukon haku käy indeksiparilla... +array[2, 3] #=> [3, 4, 5] + +# ...tai määrittelemällä väli: +array[1..3] #=> [2, 3, 4] + +# Taulukon voi kääntää: +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Ja sitä voi jatkaa näin... +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# ...tai näin: +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Alkion olemassaolon tarkistus: +array.include?(1) #=> true + +# Hashit eli assosiaatiotaulut ovat Rubyn tärkein avain-/arvoparirakenne. +# Hash luodaan aaltosulkeilla: +hash = { 'color' => 'green', 'number' => 5 } + +hash.keys #=> ['color', 'number'] + +# Hash toimii erityisen nopeasti, kun haetaan arvoa avaimen perusteella: +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Jos hashistä ei löyty avainta vastaavaa arvoa, palautetaan nil-arvo: +hash['nothing here'] #=> nil + +# Symbolihashin määrittelylle on oma syntaksinsa (alkaen Rubyn versiosta 1.9): +new_hash = { defcon: 3, action: true } +new_hash.keys #=> [:defcon, :action] + +# Hashin avaimen ja arvon olemassaolon tarkistus: +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true + +# Vinkki! Sekä taulukot että hashit sisältävät Enumerable-moduulin, +# johon kuuluu useita hyödyllisiä iterointimetodeja kuten .each, .map, +# .reduce ja .count + +# Rakenteita + +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# HUOMAA, että for-rakennetta kannattaa välttää, sillä Rubyssa suosittu +# each-metodi ajaa saman asian idiomaattisemmin. Each-metodi ottaa ainoana +# argumenttinaan lohkon. Lohkot toimivat pitkälti samoin kuin muiden kielten +# anonyymit funktiot, lambdat tai sulkeumat. + +# Lukuvälit vastaavat each-metodiin, jolloin sille annettu lohko ajetaan +# kerran jokaiselle välin kokonaisluvulle. +# Lukuvälin each-rakenne lohkoineen näyttää tältä: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Lohkoa ympäröivät do/end-avainsanat voi korvata myös aaltosulkeilla: +(1..5).each { |counter| puts "iteration #{counter}" } + +# Lukuvälien lisäksi myös tietorakenteita voidaan iteroida each-metodilla: +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +# Taulukoita voi iteroida metodilla each_with_index, jolloin lohko saa +# argumenteikseen sekä alkion että indeksin: +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Each-metodin lisäksi Rubyssa on useita muita iterointimetodeja kuten +# "map" ja "reduce". Näistä "map" kutsuttuna taulukolla ottaa argumentikseen +# lohkon, suorittaa sen kerran jokaiselle rakenteen jäsenelle, ja lopuksi +# palauttaa uuden taulukon, jonka jäsenet ovat lohkon suorituksen tuloksia. + +array = [1, 2, 3, 4, 5] +doubled = array.map do |element| + element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + +# Case-rakenne siirtää ohjelman kulun yhdelle monista määritellyistä poluista: + +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# Case-rakenteessa voidaan hyödyntää lukuvälejä: +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Virheidenkäsittely: +begin + # Seuraava koodinpätkä aiheuttaa NoMemoryError-poikkeuksen + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end + +# Ylimmän näkyvyysalueen metodi näyttää itsenäiseltä funktiolta: +def double(x) + x * 2 +end + +# Funktiot (ja lohkot) palauttavat implisiittisesti +# viimeiseksi ajamansa lausekkeen arvon: +double(2) #=> 4 + +# Metodikutsun argumentteja ympäröivät kaarisulkeet voi jättää pois, +# kunhan koodi ei muutu monitulkintaiseksi: + +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Argumentit erotetaan pilkuilla: + +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# Kaikilla metodeilla on implisiittinen lohkoparametri, +# joka voidaan suorittaa yield-avainsanalla: + +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + +# Metodille annetun lohkon voi nimetä parametrilistassa &-merkin avulla, +# minkä jälkeen se suoritetaan call-metodilla: +def guests(&block) + block.call 'some_argument' +end + +# Metodille voi antaa vaihtelevan määrän muuttujia. Ne siirretään taulukkoon, +# jolle annetaan parametrilistassa nimi \*-merkin avulla +def guests(*array) + array.each { |guest| puts guest } +end + +# Luokan määritys aloitetaan class-avainsanalla: + +class Human + + # Tässä luokkamuuttuja, joka on yhteinen kaikille luokan olioille: + @@species = 'H. sapiens' + + # Alustusmetodin määrittely: + def initialize(name, age = 0) + # name-oliomuuttujan arvon asetus metodille annetun name-muuttujan mukaan: + @name = name + + # Jos tätä metodia kutsuessa jätetään toinen argumentti (age) antamatta, + # saa se parametriluettelossa määritetyn arvon 0: + @age = age + end + + # Tyypillinen oliomuuttujan arvon asettava metodi: + def name=(name) + @name = name + end + + # Tyypillinen oliomuuttujan arvon palauttava metodi: + def name + @name + end + + # Edelliset kaksi metodia voi ilmaista idiomaattisemmin myös näin: + attr_accessor :name + + # Lisäksi arvon palauttavan ja asettavan metodin voi määritellä erikseen: + attr_reader :name + attr_writer :name + + # Luokkametodeissa käytetään avainsanaa self erotuksena oliometodeista. + # Luokkametodia voi kutsua vain luokalla itsellään, ei olioilla: + def self.say(msg) + puts msg + end + + def species + @@species + end +end + +# Olion luonti: + +jim = Human.new('Jim Halpert') + +dwight = Human.new('Dwight K. Schrute') + +# Olion metodien kutsuja: +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Luokkametodin kutsu: +Human.say('Hi') #=> "Hi" + +# Muuttujan näkyvyysalueen voi määritellä etuliitteellä. + +# $-alkuiset muuttujat ovat globaaleja: +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# @-alkuiset muuttujat kuuluvat oliolle, +# jonka näkyvyysalueella määrittely tehdään: +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# @@-alkuiset muuttujat kuuluvat vastaavasti näkyvyysalueensa luokalle: +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Isolla alkukirjaimella nimetyt muuttujat ovatkin vakioita: +Var = "I'm a constant" +defined? Var #=> "constant" + +# Kuten odottaa saattaa, myös luokat itsessään ovat olioita. +# Siksi niille voi määritellä muuttujia, jotka ovat yhteisiä kaikille +# luokan ilmentymille ja perillisille. + +# Tavallisen luokan määrittely: + +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Perillisluokan määrittely: + +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Oliomuuttuja on kuitenkin olion oma eikä periydy: + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# Moduulien lisääminen luokkaan "include"-avainsanalla siirtää moduulin metodit +# luokan ilmentymille, kun taas "extend" avainsana siirtää metodit +# luokalle itselleen: + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Callback-tyyppiset metodit suoritetaan moduulia sisällyttäessä: + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Lisämateriaalia englanniksi + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Selaimessa tehtäviä harjoituksia tämän dokumentin hengessä +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - Virallinen dokumentaatio +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas +- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown index fdde9107..4d2da921 100644 --- a/fr-fr/HTML-fr.html.markdown +++ b/fr-fr/HTML-fr.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] lang: fr-fr --- + HTML signifie HyperText Markup Language. C'est un langage (format de fichiers) qui permet d'écrire des pages internet. C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). @@ -17,7 +18,7 @@ Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parl Cet article porte principalement sur la syntaxe et quelques astuces. -```HTML +```html <!-- Les commentaires sont entouré comme cette ligne! --> <!-- #################### Les balises #################### --> diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/bf-fr.html.markdown index 545e407e..0fae6032 100644 --- a/fr-fr/brainfuck-fr.html.markdown +++ b/fr-fr/bf-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf filename: learnbrainfuck-fr.bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index d9bd9b48..bfb9f2ce 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -```d +```c // Commençons par un classique module hello; @@ -30,7 +30,7 @@ D est activement développé par de nombreuses personnes très intelligents, gui [Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). Après cette petite introduction, jetons un coup d'oeil à quelques exemples. -```d +```c import std.stdio; void main() { @@ -75,7 +75,7 @@ On peut définir de nouveaux types avec les mots-clés `struct`, `class`, `union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés) De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. -```d +```c // Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java. struct LinkedList(T) { T data = null; @@ -140,7 +140,7 @@ une méthode qui peut se comporter comme une lvalue. On peut donc utiliser la syntaxe des structures classiques (`struct.x = 7`) comme si il s'agissait de méthodes getter ou setter. -```d +```c // Considérons une classe paramétrée avec les types 'T' et 'U' class MyClass(T, U) { T _data; @@ -212,7 +212,7 @@ de premier ordre, les fonctions `pure` et les données immuables. De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter) sont disponibles dans le module `std.algorithm`. -```d +```c import std.algorithm : map, filter, reduce; import std.range : iota; // construit un intervalle excluant la dernière valeur. @@ -242,7 +242,7 @@ est de type A, comme si c'était une méthode de A. J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça Voyons comment on le fait en D ! -```d +```c import std.stdio; import std.parallelism : parallel; import std.math : sqrt; diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 16558e7e..9d8bef70 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -3,7 +3,7 @@ name: Go category: language language: Go lang: fr-fr -filename: learngo.go +filename: learngo-fr.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown new file mode 100644 index 00000000..48d24549 --- /dev/null +++ b/fr-fr/make-fr.html.markdown @@ -0,0 +1,268 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] +translators: + - ["altaris", "https://github.com/altaris"] +filename: Makefile-fr +lang: fr-fr +--- + +Un makefile est un fichier qui définit un ensemble de règles liées entre elles +pour créer une ou plusieurs cibles. L'idée est d'effectuer le moins de travail +possible afin de mettre à jour la ou les cibles en fonction des dépendances. + +Écrit en un week-end par Stuart Feldman en 1976, le make et les +makefiles sont encore très utilisés (principalement dans les systèmes Unix), +malgré la concurrence et les critiques faites à son égard. + +Le programme make a plusieurs variantes. Dans ce tutoriel, nous utiliserons +l'implémentation standard : GNU make. + +```make + +# Ceci est un commentaire. + +# Un makefile devrait être nommé "Makefile" (avec ou sans la +# majuscule). Il peut alors être exécuté par `make <cible>`. +# Ce nommage n'est toutefois pas obligatoire : utiliser +# `make -f "fichier" <cible>`. + +# ATTENTION : l'indentation est quant à elle obligatoire, et se fait avec des +# tabulations, pas avec des espaces ! + +#----------------------------------------------------------------------- +# Les basiques +#----------------------------------------------------------------------- + +# Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. +fichier0.txt: + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. + +# Cette règle ne sera exécutée que si fichier0.txt est plus récent que +# fichier1.txt. +fichier1.txt: fichier0.txt + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. + +# Une règle peut avoir plusieurs cibles et plusieurs dépendances. +fichier2.txt fichier3.txt: fichier0.txt fichier1.txt + touch fichier2.txt + touch fichier3.txt + +# Make affichera un avertissement si le makefile comporte plusieurs règles pour +# une même cible. Cependant les règles vides ne comptent pas, et peuvent être +# utilisées pour ajouter des dépendances plus facilement. + +#----------------------------------------------------------------------- +# Fausses règles +#----------------------------------------------------------------------- + +# Une fausse règle est une règle qui ne correspond pas à un fichier. +# Par définition, elle ne peut pas être à jour, et donc make l’exécutera à +# chaque demande. +all: maker process + +# La déclaration des règles peut être faite dans n'importe quel ordre. +maker: + touch ex0.txt ex1.txt + +# On peut transformer une règle en fausse règle grâce à la cible spéciale +# suivante : +.PHONY: all maker process + +# Une règle dépendante d'une fausse règle sera toujours exécutée. +ex0.txt ex1.txt: maker + +# Voici quelques exemples fréquents de fausses règles : all, make, clean, +# install... + +#----------------------------------------------------------------------- +# Variables automatiques et wildcards +#----------------------------------------------------------------------- + +# Utilise un wildcard pour des noms de fichier +process: fichier*.txt + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. + +# Même si la définition de la règle est scindée en plusieurs morceaux, $^ +# listera toutes les dépendances indiquées. +process: ex1.txt fichier0.txt +# Ici, fichier0.txt est un duplicata dans $+. + +#----------------------------------------------------------------------- +# Pattern matching +#----------------------------------------------------------------------- + +# En utilisant le pattern matching, on peut par exemple créer des règles pour +# convertir les fichiers d'un certain format dans un autre. +%.png: %.svg + inkscape --export-png $^ + +# Make exécute une règle même si le fichier correspondant est situé dans un sous +# dossier. En cas de conflit, la règle avec la meilleure correspondance est +# choisie. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Dans ce type de conflit (même cible, même dépendances), make exécutera la +# dernière règle déclarée... +%.png: %.svg + @echo cette règle est choisie + +# Dans ce type de conflit (même cible mais pas les mêmes dépendances), make +# exécutera la première règle pouvant être exécutée. +%.png: %.ps + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + +# Make a des règles pré établies. Par exemple, il sait comment créer la cible +# *.o à partir de *.c. + +# Les makefiles plus vieux utilisent un matching par extension de fichier. +.png.ps: + @echo cette règle est similaire à une règle par pattern matching + +# Utiliser cette règle spéciale pour déclarer une règle comme ayant un +# matching par extension de fichier. +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables, ou macros +#----------------------------------------------------------------------- + +# Les variables sont des chaînes de caractères. + +variable = Ted +variable2="Sarah" + +echo: + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + +# Les variables sont déclarées de 4 manières, de la plus grande priorité à la +# plus faible : +# 1 : dans la ligne de commande qui invoque make, +# 2 : dans le makefile, +# 3 : dans les variables d’environnement du terminal qui invoque make, +# 4 : les variables prédéfinies. + +# Assigne la variable si une variable d’environnement du même nom n'existe pas +# déjà. +variable4 ?= Jean + +# Empêche cette variable d'être modifiée par la ligne de commande. +override variable5 = David + +# Concatène à une variable (avec un espace avant). +variable4 +=gris + +# Assignations de variable pour les règles correspondant à un pattern +# (spécifique à GNU make). +*.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous + # leurs descendants, la variable variable2 vaudra + # "Sara". +# Si le jeux des dépendances et descendances devient vraiment trop compliqué, +# des incohérences peuvent survenir. + +# Certaines variables sont prédéfinies par make : +affiche_predefinies: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables : le retour +#----------------------------------------------------------------------- + +# Les variables sont évaluées à chaque instance, ce qui peut être coûteux en +# calculs. Pour parer à ce problème, il existe dans GNU make une seconde +# manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule +# fois seulement. + +var := A B C +var2 ::= $(var) D E F # := et ::= sont équivalents. + +# Ces variables sont évaluées procéduralement (i.e. dans leur ordre +# d'apparition), contrairement aux règles par exemple ! + +# Ceci ne fonctionne pas. +var3 ::= $(var4) et fais de beaux rêves +var4 ::= bonne nuit + +#----------------------------------------------------------------------- +# Fonctions +#----------------------------------------------------------------------- + +# Make a une multitude de fonctions. La syntaxe générale est +# $(fonction arg0,arg1,arg2...). + +# Quelques exemples : + +fichiers_source = $(wildcard *.c */*.c) +fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) + +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Inclut d'autres makefiles. +include meuh.mk + +# Branchements conditionnels. +sport = tennis +report: +ifeq ($(sport),tennis) # Il y a aussi ifneq. + @echo 'jeu, set et match' +else + @echo "C'est pas ici Wimbledon ?" +endif + +truc = true +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' +endif +``` + +## Quelques références + +### En français + ++ [Introduction à Makefile (developpez.com)] +(http://gl.developpez.com/tutoriel/outil/makefile/), ++ [Compilez sous GNU/Linux ! (openclassrooms)] +(https://openclassrooms.com/courses/compilez-sous-gnu-linux). + +### En anglais + ++ [Documentation de GNU make](https://www.gnu.org/software/make/manual/), ++ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/), ++ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) +[ex28](http://c.learncodethehardway.org/book/ex28.html). diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 4e31c4bf..fbe1741e 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -1,5 +1,4 @@ --- - language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] @@ -9,7 +8,6 @@ translators: - ["Yannick Loriot", "https://github.com/YannickL"] filename: LearnObjectiveC-fr.m lang: fr-fr - --- L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. @@ -519,6 +517,7 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es // l'objet est supprimé ``` + ## Lectures Complémentaires [La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown new file mode 100644 index 00000000..7b446259 --- /dev/null +++ b/fr-fr/wolfram-fr.html.markdown @@ -0,0 +1,167 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] +translators: + - ["altaris", "http://github.com/altaris/"] +filename: learnwolfram-fr.nb +lang: fr-fr +--- + +Le langage Wolfram est utilisé dans les programmes suivants : +* La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas +gérer des éléments graphiques. +* _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques : +appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule +contenant le résultat. +* _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage +Wolfram. + +Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, le +copier-coller directement dans Mathematica peut causer des problèmes de +formatage, car il ne contient aucune information de mise en page. + +``` +(* Ceci est un commentaire *) + +(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des + cellules de texte et insérer de jolies images *) + +(* Saisissez une opération et appuyez sur Shift + Entrée pour obtenir le + résultat *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Appels de fonction *) +Sin[Pi/2] (* 1 *) +(* Syntaxe alternative pour les appels de fonction à 1 paramètre *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Attention : le langage est sensible à la casse ! *) + +(* Toutes les expressions sont en réalité des appels de fonction *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Utiliser une variable pour la première fois la déclare globalement *) +x = 5 (* 5 *) +x == 5 (* True, l'assignation et le test d'égalité est écrit comme + en C *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) +x (* 20 *) + +(* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des + variables non déclarées est légal *) +truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation + s'arrête là *) +truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) +% (* 15 + truc, % représente le dernier résultat *) +% - truc (* 15, les variables non déclarées peuvent quand même + s'annuler *) +chose = truc + 5 (* Attention : chose est ici une expression et non un nombre *) + +(* Déclaration d'une fonction *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) + +(* En programmation impérative, utiliser ; pour séparer les expressions *) +Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +Salut[] (* Hello World *) + +(* Boucles For à la C *) +Compter[x_] := For[y=0, y<x, y++, (Print[y])] (* L'évaluation des boucles For + se fait comme en C *) +Compter[5] (* 0 1 2 3 4 *) + +(* Boucles While *) +x = 0; While[x < 2, (Print@x; x++)] (* De nouveau, comme en C *) + +(* Expressions conditionnelles et If *) +x = 8; If[x==8, Print@"Huit", Print@"Pas huit"] (* If [condition, si vrai, + si faux] *) +Switch[x, 2, Print@"Deux", 8, Print@"Huit"] (* Switch par valeur *) +Which[x==2, Print@"Deux", x==8, Print@"Huit"] (* Switch du type if, else if, + else if, ..., else *) + +(* Les variables autres que les paramètres de fonctions sont par défaut + globales, même à l'intérieur des fonctions *) +y = 10 (* 10, y est une variable globale *) +Compter[5] (* 0 1 2 3 4 *) +y (* 5, y a été modifiée par Compter *) +x = 20 (* 20, x est une variable globale *) +Compter[5] (* 0 1 2 3 4 *) +x (* 20, dans Compter, le paramètre x masque la variable + globale x *) + +(* La fonction Module permet d'utiliser des variables locales *) +MieuxCompter[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])] +y = 20 (* y est une variable globale *) +MieuxCompter[5] (* 0 1 2 3 4 *) +y (* 20, y n'a pas été modifiée car le y du Module masque le + y global. C'est bien mieux comme ça ! *) + +(* Module permet de faire des déclarations globales aussi *) +Module[{compte}, compte=0; (* compte est une variable locale *) + (Incrementer[] := ++compte); (* Ce module déclare des fonctions, mais elles + ne sont globales. Elles ont cependant accès + aux variables locales au module. *) + (Decrementer[] := --compte)] +compte (* compte, car il n'y a pas de variable globale nommée + compte *) +Incrementer[] (* 1, la fonction utilise la variable compte du module *) +Incrementer[] (* 2, le précédent appel de Incrementer a modifié compte *) +Decrementer[] (* 1 *) +compte (* compte, car il n'existe toujours pas de variable globale + nommé compte *) + +(* Listes *) +liste = {1, 2, 3, 4} (* {1, 2, 3, 4} *) +liste[[1]] (* 1, les indexes commencent à 1 et non 0 !!! *) +Map[Double, liste] (* {2, 4, 6, 8}, appliquer une fonction à une liste de + manière fonctionnelle *) +Double /@ liste (* {2, 4, 6, 8}, syntaxe abrégée de la ligne + précédente *) +Scan[Print, liste] (* 1 2 3 4, boucle impérative sur une liste *) +Fold[Plus, 0, liste] (* 10 (0+1+2+3+4) *) +FoldList[Plus, 0, liste] (* {0, 1, 3, 6, 10}, variante de la fonction + précédente qui donne aussi les résultats + intermédiaires *) +Append[liste, 5] (* {1, 2, 3, 4, 5}, liste n'est pas modifiée... *) +Prepend[liste, 5] (* {5, 1, 2, 3, 4}, ... mais elle peut l'être en + écrivant "liste = " *) +Join[liste, {3, 4}] (* {1, 2, 3, 4, 3, 4} *) +liste[[2]] = 5 (* {1, 5, 3, 4}, ceci modifie bien la liste *) + +(* Tables associatives, ou dictionnaires *) +table = <|"Vert" -> 2, "Rouge" -> 1|> (* Crée une table associative *) +table[["Vert"]] (* 2, l'utilise *) +table[["Vert"]] := 5 (* 5, la modifie *) +table[["Bleu"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) +Keys[table] (* {Rouge, Bleu} *) +Values[table] (* {1, 3.5} *) + +(* Pour finir, toute bonne démonstration du langage Wolfram contient un + Manipulate ! *) +Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui + affiche y^2, permettant à l'utilisateur de + modifier la valeur de y grâce à un contrôle + allant de 0 à 20. Ne fonctionne que si le + logiciel utilisé gère les éléments graphiques. *) +``` + +## Envie d'aller plus loin ? + +* [Documentation du langage Wolfram (en anglais)] +(http://reference.wolfram.com/language/) diff --git a/groovy.html.markdown b/groovy.html.markdown index 492c1ba2..94678c39 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -13,8 +13,8 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://www.g /* Set yourself up: - 1) Install GVM - http://gvmtool.net/ - 2) Install Groovy: gvm install groovy + 1) Install SDKMAN - http://sdkman.io/ + 2) Install Groovy: sdk install groovy 3) Start the groovy console by typing: groovyConsole */ @@ -280,7 +280,7 @@ def clos = { print it } clos( "hi" ) /* - Groovy can memorize closure results [1][2][3] + Groovy can memoize closure results [1][2][3] */ def cl = {a, b -> sleep(3000) // simulate some time consuming processing diff --git a/haskell.html.markdown b/haskell.html.markdown index 34eee748..4ce1a839 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -189,16 +189,16 @@ foo = add 10 -- foo is now a function that takes a number and adds 10 to it foo 5 -- 15 -- Another way to write the same thing -foo = (+10) +foo = (10+) foo 5 -- 15 -- function composition --- the (.) function chains functions together. +-- the operator `.` chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, -- multiplies the result of that by 4, and then returns the final value. -foo = (*4) . (+10) +foo = (4*) . (10+) --- (5 + 10) * 4 = 60 +-- 4*(10 + 5) = 60 foo 5 -- 60 -- fixing precedence @@ -222,7 +222,7 @@ even . fib $ 7 -- false -- 5. Type signatures ---------------------------------------------------- --- Haskell has a very strong type system, and everything has a type signature. +-- Haskell has a very strong type system, and every valid expression has a type. -- Some basic types: 5 :: Integer @@ -259,7 +259,7 @@ case args of _ -> putStrLn "bad args" -- Haskell doesn't have loops; it uses recursion instead. --- map applies a function over every element in an array +-- map applies a function over every element in a list map (*2) [1..5] -- [2, 4, 6, 8, 10] @@ -279,7 +279,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 -- This is the same as (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl is left-handed, foldr is right- +-- foldl is left-handed, foldr is right-handed foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- This is now the same as @@ -318,7 +318,7 @@ Nothing -- of type `Maybe a` for any `a` -- it is not hard to explain enough to get going. -- When a Haskell program is executed, `main` is --- called. It must return a value of type `IO ()`. For example: +-- called. It must return a value of type `IO a` for some type `a`. For example: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) @@ -361,7 +361,7 @@ sayHello = do -- You can think of a value of type `IO a` as representing a -- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also +-- name and reuse this value using `<-`. We can also -- make our own action of type `IO String`: action :: IO String @@ -401,11 +401,26 @@ main'' = do let foo = 5 --- You can see the type of any value with `:t`: +-- You can see the type of any value or expression with `:t`: ->:t foo +> :t foo foo :: Integer +-- Operators, such as `+`, `:` and `$`, are functions. +-- Their type can be inspected by putting the operator in parentheses: + +> :t (:) +(:) :: a -> [a] -> [a] + +-- You can get additional information on any `name` using `:i`: + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + -- You can also run any action of type `IO ()` > sayHello @@ -417,7 +432,7 @@ Hello, Friend! There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final -Haskell example: an implementation of quicksort in Haskell: +Haskell example: an implementation of a quicksort variant in Haskell: ```haskell qsort [] = [] diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown index 169f2b8e..f2fe4e5d 100644 --- a/hu-hu/ruby-hu.html.markdown +++ b/hu-hu/ruby-hu.html.markdown @@ -1,7 +1,7 @@ --- language: ruby lang: hu-hu -filenev: learnruby.rb +filename: learnruby-hu.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] @@ -13,7 +13,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - translators: +translators: - ["Zsolt Prontvai", "https://github.com/prozsolt"] --- diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown new file mode 100644 index 00000000..37ce4cb2 --- /dev/null +++ b/hu-hu/yaml-hu.html.markdown @@ -0,0 +1,147 @@ +--- +language: yaml +filename: learnyaml-hu.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +lang: hu-hu +--- + +A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is +olvasható és írható legyen emberi szemmel. + +A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt +szintaktikai jelentéssel bíró sortörésekkel és indentációval, +a Pythonhoz hasonlóan. A Pythonnal ellentétben azonban a YAML nem engedélyezi +a közvetlen tab karakterek jelenlétét. + +Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő, +a kódolást a tartalomban explicit nem kell (és nem is lehet) feltüntetni. + +```yaml +# A kommentek YAML-ban így néznek ki. + +################## +# Skalár típusok # +################## + +# A gyökér objektumunk (az egész dokumentumra értve) egy map, +# ami a más nyelvekből ismert dictionary, hash vagy object típusokkal egyenértékű. +kulcs: érték +masik_kulcs: Másik érték jön ide. +egy_szam: 100 +tudomanyos_jelolessel: 1e+12 +boolean: true +null_value: null +kulcs benne szóközökkel: érték +# Látható, hogy a sztringeket nem szükséges idézőjelek közé zárni, bár szabad. +Továbbá: "Idézőjelekkel megadott sztring." +"A kulcs is lehet idézőjeles.": "Hasznos lehet, ha ':'-ot akarsz a kulcsban." + +# Többsoros sztringek írhatóak 'literal block'-ként ('|' jelet használva) +# vagy 'folded block'-ként is ('>' jelet használva). +literal_block: | + Ez az egész szöveg-blokk lesz az értéke a literal_block kulcsnak, + a sortöréseket megtartva. + + Az ilyen sztringet az indentáció visszahúzása zárja le, a behúzás pedig + eltávolításra kerül. + + A 'még jobban' behúzott részek megtartják a behúzásukat - + ezeknek a soroknak 4 szóköz behúzása lesz. +folded_style: > + Az az egész szöveg-blokk lesz az értéke a 'folded_style' kulcsnak, de + ezúttal minden sortörés egy szóközre lesz cserélve. + + Az üres sorok, mint a fenti, új sor karakterre cserélődnek. + + A 'még jobban' behúzott sorok megtartják a sortöréseiket, - + ez a szöveg két sorban jelenik meg. + +###################### +# Gyűjtemény típusok # +###################### + +# Egymásba ágyazás a behúzás változtatásával érhető el. +beagyazott_map: + key: value + another_key: Another Value + masik_beagyazott_map: + hello: hello + +# A mapeknek nem csak sztring kulcsaik lehetnek. +0.25: lebegőpontos kulcs + +# A kulcsok lehetnek többsoros objektumok is, ? jellel jelezve a kulcs kezdetét +? | + Ez itt egy + többsoros kulcs +: és ez az értéke + +# Szintén engedélyezett a kollekció típusok használata kulcsként, de egyéb +# nyelvekben ez gyakran problémákat fog okozni. + +# Szekvenciák (listákkal vagy tömbökkel egyenértékűek) így néznek ki: +egy_szekvencia: + - Item 1 + - Item 2 + - 0.5 # Többféle típust is tartalmazhat + - Item 4 + - key: value + another_key: another_value + - + - Ez egy szekvencia + - egy másik szekvenciába ágyazva + +# Mivel a YAML a JSON befoglaló halmazát alkotja, JSON szintaxisú +# mapek és szekvenciák is használhatóak: +json_map: {"key": "value"} +json_seq: [3, 2, 1, "takeoff"] + +######################### +# EXTRA YAML KÉPESSÉGEK # +######################### + +# A YAML-ben ún. 'anchor'-ök segítségével könnyen lehet duplikálni +# tartalmakat a dokumentumon belül. A következő kulcsok azonos értékkel bírnak: +anchored_tartalom: &anchor_neve Ez a sztring két kulcs értéke is lesz. +másik_anchor: *anchor_neve + +# Vannak a YAML-ben tagek is, amivel explicit lehet típusokat jelölni. +explicit_string: !!str 0.5 +# Bizonyos implementációk nyelv-specifikus tageket tartalmaznak, mint +# például ez a Python komplex szám típusának jelölésére: +python_complex_number: !!python/complex 1+2j + +###################### +# EXTRA YAML TÍPUSOK # +###################### + +# Nem a sztringek és a számok az egyedüli skalár típusok YAML-ben. +# ISO-formátumú dátumok és dátumot jelölő literal kifejezések is értelmezettek. +datetime: 2001-12-15T02:59:43.1Z +datetime_with_spaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# A !!binary tag jelöli, hogy egy sztring valójában base64-kódolású +# reprezentációja egy bináris blob-nak +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# Létezik a YAML-ban egy halmaz típus (set) is, ami így néz ki: +set: + ? elem1 + ? elem2 + ? elem3 + +# Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti +# halmaz egyenértékű a következővel: +set2: + elem1: null + elem2: null + elem3: null +```
\ No newline at end of file diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..34d6e5f5 --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,848 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php +<?php // Skrip PHP harus diawali dengan tag <?php + +// Jika dokumen PHP hanya mengandung kode PHP, sebaiknya tidak menggunakan +// tag penutup PHP untuk menghindari ketidaksengajaan tampilnya sesuatu. + +// Dua garis miring diawal digunakan untuk komentar satu baris. + +/* + Membatasi teks dalam garis miring-bintang dan bintang-garis miring + membuat komentar untuk banyak-baris sekaligus. +*/ + +// Gunakan "echo" or "print" untuk menampilkan sesuatu +print('Halo '); // Menampilkan "Halo " tanpa baris baru + +// () boleh tidak digunakan dalam menggunakan "print" dan "echo" +echo "Dunia\n"; // Menampilkan "Dunia" dengan baris baru +// (semua perintah harus diakhiri dengan titik koma) + +// Apapun yang berada diluar tag <?php akan ditampilkan secara otomatis +?> +Halo Dunia, lagi! +<?php + + +/************************************ + * Tipe Data & Variabel + */ + +// Variabel diawali dengan simnbol $. +// Nama variabel yang benar diawali dengan huruf atau garis-bawah, +// diikuti dengan beberapa huruf, angka, dan garis-bawah lainnya. + +// Nilai Boolean adalah case-insensitive +$boolean = true; // atau TRUE atau True +$boolean = false; // atau FALSE atau False + +// Nilai Integer +$int1 = 12; // => 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = <<<END +Banyak baris +$sgl_quotes +END; + +// Menyambung string dapat dilakukan menggunakan . +echo 'String ini ' . 'tersambung'; + +// String dapat dijadikan parameter pada "echo" +echo 'Banyak', 'Parameter', 'String'; // Menampilkan 'BanyakParameterString' + + +/******************************** + * Konstan + */ + +// Sebuah konstan didifinisikan menggunakan fungsi define() +// dan tidak bisa diganti/rubah selama program berjalan! + +// Nama konstan yang benar diawali dengan huruf dan garis-bawah, +// diikuti dengan beberapa huruf, angka, atau garis-bawah. +define("FOO", "sesuatu"); + +// Mengakses konstan memungkinkan untuk dapat dipanggil tanpa menggunakan simbol $ +echo FOO; // Menampilkan 'sesuatu' +echo 'Keluaran ini adalah ' . FOO; // Menampilkan 'Keluaran ini adalah sesuatu' + + + +/******************************** + * Larik (Array) + */ + +// Semua larik dalam PHP bersifat asosiatif (saling berhubungan). + +// Berfungsi pada semua versi PHP +$asosiatif = array('Satu' => 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +<p><?= $paragraf ?></p> +<?php + +$x = 1; +$y = 2; +$x = $y; // $x sekarang berisi nilai yang sama dengan $y +$z = &$y; +// $z sekarang berisi referensi ke $y. Mengubah nilai dari $z +// akan mengubah nilai dari $y juga, begitupun sebaliknya. +// $x tetap tidak berubah sebagaimana nilai asli dari $y + +echo $x; // => 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + +<?php if ($x): ?> +Ini ditampilkan jika pengujian benar. +<?php else: ?> +Selain tersebut ini yang akan ditampilkan. +<?php endif; ?> + +<?php + +// Gunakan "switch" untuk menghemat logika. +switch ($x) { + case '0': + print 'Switch mendukung tipe paksaan'; + break; // Kata kunci "break" harus disertakan, jika tidak + // maka logika tersebut akan berlanjut ke bagian "dua" dan "tiga" + case 'dua': + case 'tiga': + // Lakukan sesuatu jika $x bernilai "dua" atau "tiga" + break; + default: + // Aksi cadangan +} + +// "while", "do...while" dan perulangan "for" +$i = 0; +while ($i < 5) { + echo $i++; +}; // Menampilkan "01234" + +echo "\n"; + +$i = 0; +do { + echo $i++; +} while ($i < 5); // Menampilkan "01234" + +echo "\n"; + +for ($x = 0; $x < 10; $x++) { + echo $x; +} // Menampilkan "0123456789" + +echo "\n"; + +$roda = ['sepeda' => 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +<?php +// Skrip PHP yang berada dalam dokumen "include" juga harus dibuka dengan tag PHP. + +include 'dokumen-saya.php'; +// Kode yang ada dalam dokumen-saya.php sekarang dapat diakses dari cakupan saat ini. +// Jika dokumen tidak dapat disertakan (include, seperti dokumen tidak ditemukan), maka pesan peringatan akan muncul. + +include_once 'dokumen-saya.php'; +// Jika dokumen-saya telah disertakan (include) oleh perintah sebelumnya, maka +// dokumen tersebut tidak akan disertakan lagi. Ini bertujuan untuk menghindari kesalahan +// yang diakibatkan oleh deklarasi ganda. + +require 'dokumen-saya.php'; +require_once 'dokumen-saya.php'; +// Memiliki fungsi yang sama dengan "include", namun jika dokumen tidak ditemukan +// atau tidak dapat disertakan maka akan menghasilkan pesan kesalahan fatal. + +// Isi dari dokumen-saya.php: +<?php + +return 'Apapun yang kamu suka.'; +// akhir dari dokumen + +// "include" dan "require" dapat mengembalikan sebuah nilai. +$nilai = include 'dokumen-saya.php'; + +// Dokumen akan disertakan berdasarkan lokasi direktori dokumen (file path) yang diberikan, jika tidak didefinisikan +// maka akan digunakan konfigurasi dari "include_path". Jika dokumen tidak ditemukan dalam "include_path", +// fungsi include akan melakukan pengecekan pada direktori yang sama dengan dokumen yang menggunakan fungsi include tersebut, +// jika tidak ditemukan juga maka pesan gagal akan dimunculkan. +/* */ + +/******************************** + * Kelas (class) + */ + +// Kelas didefinisikan dengan kata "class" + +class KelasSaya +{ + const NILAI_KONSTAN = 'nilai'; // Sebuah konstan + + static $nilaiStatis = 'statis'; + + // Variabel statis dan hak jenis aksesnya + public static $variabelStatisPublik = 'nilaiStatisPublik'; + // Hanya dapat diakses dalam kelas + private static $variabelStatisPrivat = 'nilaiStatisPrivat'; + // Dapat diakses dalam kelas dan kelas turunan + protected static $variabelStatisTerlindungi = 'nilaiStatisTerlindungi'; + + // Properti harus mendeklarasikan hak aksesnya + public $properti = 'publik'; + public $PropertiInstansi; + protected $variabel = 'terlindungi'; // Dapat diakses dari kelas itu sendiri dan kelas turunannya + private $variabel = 'tersembunyi'; // Hanya dapat diakses dari kelas itu sendiri + + // Membuat konstruktor dengan perintah __construct + public function __construct($PropertiInstansi) { + // Akses variabel instansi menggunakan perintah $this + $this->PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya +{ + function tampilkanPropertiTerlindungi() + { + echo $this->properti; + } + + // "override" terhadap sebuah method + function methodSaya() + { + parent::methodSaya(); + print ' > KelasSayaLainnya'; + } +} + +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" + +final class SayaTidakBisaDiturunkan +{ +} + +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya +{ + private $properti; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); + +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". + +interface InterfaceSatu +{ + public function kerjakanSesuatu(); +} + +interface InterfaceDua +{ + public function kerjakanYangLain(); +} + +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua +{ + public function kerjakanYangBerbeda(); +} + +abstract class KelasAbstrakSaya implements InterfaceSatu +{ + public $x = 'kerjakanSesuatu'; +} + +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo +{ + public function kerjakanSesuatu() + { + echo $x; + } + + public function kerjakanYangLain() + { + echo 'kerjakanYangLain'; + } +} + +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua +{ + public function kerjakanSesuatu() + { + echo 'kerjakanSesuatu'; + } + + public function kerjakanYangLain() + { + echo 'kerjakanYangLain'; + } +} + + +/******************************** + * Sifat (Traits) + */ + +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" + +trait TraitSaya +{ + public function methodTraitSaya() + { + print 'Saya menggunakan Trait'; + } +} + +class KelasTraitSaya +{ + use TraitSaya; +} + +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" + + +/******************************** + * Namespaces + */ + +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen. + +<?php + +// Secara default, kelas tersedia sebagai namespace umum, dan dapat +// secara khusus dipanggil dengan garis-miring terbalik (backslash). + +$kls = new \KelasSaya(); + + +// Menentukan namespace untuk sebuah dokumen +namespace Saya\Namespace; + +class KelasSaya +{ +} + +// (dari dokumen lainnya) +$kls = new Saya\Namespace\KelasSaya; + +// Atau dari dalam namespace lainnya. +namespace Saya\Lainnya\Namespace; + +use Saya\Namespace\KelasSaya; + +$kls = new KelasSaya(); + +// Namespace dapat menggunakan alias + +namespace Saya\Lainnya\Namespace; + +use Saya\Namespace as SuatuKelasLainnya; + +$kls = new SuatuKelasLainnya\KelasSaya(); + + +/********************** +* Late Static Binding +* +*/ + +class KelasInduk { + public static function siapa() { + echo "Ini adalah " . __CLASS__ . "\n"; + } + public static function coba() { + // kata kunci "self" merujuk pada method yang berada dalam satu kelas + self::who(); + // kata kunci "static" merujuk pada method yang berada di kelas dimana method itu dijalankan + static::who(); + } +} + +KelasInduk::coba(); +/* +Ini adalah KelasInduk +Ini adalah KelasInduk +*/ + +class KelasAnak extends KelasInduk { + public static function siapa() { + echo "Tapi ini adalah " . __CLASS__ . "\n"; + } +} + +KelasAnak::tes(); +/* +Ini adalah KelasInduk +Tapi ini adalah KelasAnak +*/ + +/********************** +* Magic constants +* +*/ + +// Mendapatkan nama dari suatu kelas. Harus dideklarasikan didalam kelas tersebut. +echo "Nama kelas ini adalah " . __CLASS__; + +// Mendapatkan alamat lengkap direktori +echo "Alamat direktori ini adalah " . __DIR__; + + // Beberapa yang banyak digunakan + require __DIR__ . '/vendor/autoload.php'; + +// Mendapatkan alamat lengkap dokumen +echo "Alamat dokumen ini adalah " . __FILE__; + +// Mendapatkan nama fungsi +echo "Nama fungsi ini adalah " . __FUNCTION__; + +// Mendapatkan nomor baris perintah +echo "Nomor baris perintah ini adalah " . __LINE__; + +// Mendapatkan nama method. Hanya mengembalikan sebuah nilai jika berada didalam trait atau deklarasi objek. +echo "Nama method ini adalah " . __METHOD__; + +// Mendapatkan nama namespace +echo "Namespace saat ini adalah " . __NAMESPACE__; + +// Mendapatkan nama dari trait. Hanya mengembalikan sebuah nilai jika berada didalam trait atau deklarasi objek. +echo "Namespace saat ini adalah " . __TRAIT__; + +/********************** +* Penanganan Kesalahan (Error) +* +*/ + +// Penanganan error sederhana menggunakan "try...catch" + +try { + // Kerjakan sesuatu +} catch (Exception $e) { + // Penanganan exception +} + +// Menggunakan "try...catch" blok pada namespace + +try { + // Kerjakan sesuatu +} catch (\Exception $e) { + // Penanganan exception +} + +// Exception khusus + +class ExceptionSaya extends Exception {} + +try { + + $kondisi = true; + + if ($kondisi) { + throw new ExceptionSaya('Terjadi sesuatu'); + } + +} catch (ExceptionSaya $e) { + // Penanganan untuk exception khusus +} + +``` + +## Informasi lainnya + +Kunjungi [Dokumentasi resmi PHP](http://www.php.net/manual/) untuk referensi dan masukan komunitas. + +Jika anda tertarik untuk belajar lebih dalam, kunjungi +[PHP The Right Way](http://www.phptherightway.com/). + +Jika anda terbiasa dengan manajemen paket, kunjungi +[Composer](http://getcomposer.org/). + +Untuk standar umum, kunjungi PHP Framework Interoperability Group's +[PSR standards](https://github.com/php-fig/fig-standards). diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index 8b8d72ae..fedba711 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -5,19 +5,76 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. +XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. XML mudah dibaca oleh manusia dan mesin. Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya. -* Sintaks XML +Terdapat perbedaan antara **konten** dan **markup**. Singkatnya, konten dapat berupa apapun dan markup adalah sebagai penentu. + +## Definisi dan Pendahuluan + +Dokumen XML pada dasarnya disusun oleh *elemen* yang dapat memiliki *atribut* untuk menjelaskan elemen tersebut dan dapat memiliki beberapa konten tekstual atau beberapa elemen sebagai anak-nya. Setiap dokumen XML hendaknya memiliki satu elemen akar, yang menjadi induk dari semua elemen dalam dokumen XML. + +Pengurai XML dirancang menjadi sangat ketat, dan akan berhenti melakukan penguraian terhadap dokumen yang cacat. Oleh karena itu semua dokumen XML harus mengikuti [Aturan Sintaks XML](http://www.w3schools.com/xml/xml_syntax.asp). ```xml -<!-- Komentar di XML seperti ini --> +<!-- Ini adalah komentar. Komentar harus memiliki dua tanda penghubung secara berurutan (-). --> +<!-- Komentar dapat renggang + menjadi banyak baris --> + +<!-- Elemen --> +<!-- Elemen merupakan komponen dasar dari XML. Ada dua tipe dari elemen, kosong: --> +<elemen1 atribut="nilai" /> <!-- Elemen kosong tidak memiliki konten apapun --> +<!-- dan tidak-kosong: --> +<elemen2 atribut="nilai">Konten</elemen2> +<!-- Nama elemen hanya dapat berupa huruf dan angka saja. --> + +<kosong /> <!-- Elemen yang terdiri dari tag elemen kosong… --> +<!-- …tidak memiliki content apapun dan murni markup. --> + +<tidakkosong> <!-- Atau, elemen ini memiliki tag pembuka… --> + <!-- …suatu konten… --> +</tidakkosong> <!-- dan sebuah tag penutup. --> + +<!-- Nama elemen merupakan *case sensitive*. --> +<elemen /> +<!-- …tidak sama dengan elemen sebelumnya --> +<eLEMEN /> + +<!-- Atribut --> +<!-- Sebuah atribut merupakan hubungan kunci-nilai yang terdapat pada elemen. --> +<elemen atribut="nilai" lainnya="nilaiLainnya" banyakNilai="daftar nilai ber-spasi" /> +<!-- Sebuah atribut digunakan hanya sekali dalam sebuah elemen. Dan hanya memiliki satu nilai. + Salah satu solusi untuk mengatasi permasalahan tersebut adalah dengan menggunakan daftar nilai ber-spasi. --> + +<!-- Elemen bersarang --> +<!-- Konten dari sebuah elemen dapat berupa elemen lainnya:: --> +<ayah> + <anak>Teks</anak> + <oranglain /> +</ayah> +<!-- Mengikuti standar tatanan pohon. Setiap elemen disebut *node*. + Induk yang berada satu tingkat diatasnya disebut *parent*, keturunan yang berada satu tingkat dibawahnya disebut *children*. + Elemen yang berada pada *parent* yang sama disebut Saudara (*siblings*). --> + +<!-- XML mempertahankan spasi. --> +<anak> + Teks +</anak> +<!-- …tidak sama dengan --> +<anak>Teks</anak> +``` + + +## Dokumen XML +```xml <?xml version="1.0" encoding="UTF-8"?> +<!-- XML prolog, boleh tidak digunakan namun direkomendasikan untuk digunakan. --> <tokobuku> <buku category="MEMASAK"> <judul lang="en">Everyday Italian</judul> @@ -65,7 +122,7 @@ Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, ``` -* Dokumen yang well-formated & Validasi +## Dokumen yang well-formated & Validasi Sebuah dokumen XML disebut well-formated jika sintaksisnya benar. Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen, @@ -128,3 +185,17 @@ Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi. </buku> </tokobuku> ``` +## Kompatibilitas DTD dan Definisi Skema XML + +Dukungan untuk DTD dapat ditemukan dimana-mana karena sudah sangat lama. Namun sayangnya, fitur XML terkini seperti *namespaces* tidak didukung oleh DTD. XML Xchema Definitions (XSDs) bertujuan untuk mengganti DTD dalam mendefinisikan tatabahasa dokumen XML. + +## Sumber + +* [Validasi dokumen XML](http://www.xmlvalidation.com) + +## Bacaan lainnya + +* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML Tutorial](http://www.w3schools.com/xml/default.asp) +* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) diff --git a/inform7.html.markdown b/inform7.html.markdown new file mode 100644 index 00000000..7f1da0e0 --- /dev/null +++ b/inform7.html.markdown @@ -0,0 +1,195 @@ +--- +language: Inform7 +contributors: + - ["Hyphz", "http://github.com/hyphz/"] +filename: LearnInform.Inform +--- +Inform 7 is a natural language based language created by Graham Nelson and Emily Short for writing text adventures, but also potentially usable for other text based applications, especially data backed ones. + +``` +"LearnInform" by Hyphz + +[This is a comment.] + +[Inform 7 is a language designed for building text adventures. +It can be used for other purposes too, although the default +library builds a text adventure. Inform 7 is object oriented.] + +[This creates a class by subclassing. "Value" is the universal subclass, +but "object" is the most basic that behaves like an OO object.] +A datablock is a kind of object. + +[Classes can have properties.] +A datablock can be broken. [This creates a boolean property.] +A datablock is usually not broken. [This sets its default value.] +A datablock can be big or small. [This creates an enumerated property.] +A datablock is usually small. [This sets its default value.] +A datablock has a number called the sequence number. [This creates a typed property.] +A datablock has some text called the name. ["Some text" means a string.] +A datablock has a datablock called the chain. [Declared classes become types.] + +[This creates a global named instance.] +Block1 is a datablock. +The sequence number of Block1 is 1. +The name of Block1 is "Block One." + +[Functions and procedures are defined as "phrases".] +To do the thing everyone does with their first program: + say "Hello World.". [Full stop indicates the end, indent indicates the scope.] + +To dump (the block - a datablock): [That's how we create a parameter.] + say the sequence number of the block; + say the name of the block; + if the block is broken, say "(Broken)". + +To toggle (the block - a datablock): + if the block is broken: [Conditional.] + now the block is not broken; [Updating a property.] + else: + now the block is broken. + +[Multiple parameters.] +To fix (the broken block - a datablock) using (the repair block - a datablock): + if the broken block is not broken, stop; [Comma for a non indented single command.] + if the repair block is broken, stop; + now the sequence number of the broken block is the sequence number of the repair block; + now the broken block is not broken. + +[Because of its text adventure origins, Inform 7 doesn't generally allow objects +to be created dynamically, although there's a language extension that enables it.] +Block2 is a datablock. +Block2 is broken. +The sequence number of Block2 is 2. +The name of Block2 is "Block two." + +To demonstrate calling a phrase with two parameters: + Let the second block be block2; [Local pointer variable.] + fix the second block using Block1; + say the sequence number of the second block. [1.] + +[Lists.] +To show how to use list types: + let the list be a list of datablocks; + add Block1 to the list; + add Block2 to the list; + say the list; ["Block1 and Block2"] + [Membership.] + if Block1 is listed in the list: + say "Block1 is there."; + [Loop.] + repeat with the block running through the list: + dump the block; [1 Block One. 1 Block Two.] + [Remember block two's sequence number was changed above.] + let X be entry 2 of the list; [Counting starts at 1.] + dump X; ["1 Block two."] + remove X from the list; + say the list. [Block1] + +[Here's how we define a function and do arithmetic.] + +To decide which number is the sum of all numbers up to (X - a number) (this is summing up): + let the total so far be a number; + repeat with the current number running from 1 to X: + now the total so far is the total so far + the current number; + decide on the total so far. [This is the return statement.] + +[ We have higher order functions too. ] + +To demonstrate a higher order function: + say summing up applied to {1, 2, 3, 4}. + +To decide which number is the result of applying (phrase - phrase A -> A) twice to (B - a value of kind A): + let b1 be phrase applied to B; + let b2 be phrase applied to b1; + decide on b2. + +To demonstrate defining a higher order function: + let X be 5; + say the result of applying summing up twice to X. + +[ Rulebooks allow a number of functions which apply to the same type under different conditions to be stacked. ] + +Datablock validation rules is a datablock based rulebook. + +A datablock validation rule for a broken datablock: rule fails. +A datablock validation rule for a datablock (called the block): + dump the block; + rule succeeds. + +To demonstrate invoking a rulebook: + follow datablock validation rules for Block1; + follow datablock validation rules for Block2. + +[ Objects can also have relations, which resemble those in a relational database. ] +A dog is a kind of thing. +Rover is a dog. +The kennel is a container. [This is a built in base class.] +Rover is in the kennel. [This creates an inbuilt relation called "containment".] + +[We can create relations by declaring their type.] + +Guide dog ownership relates one dog to one person. [One-to-one.] +Property ownership relates various things to one person. [Many-to-one.] +Friendship relates various people to various people. [Many-to-many.] + +[To actually use them we must assign verbs or prepositions to them.] + +The verb to own means the property ownership relation. +The verb to be the guide dog of means the guide dog ownership relation. +The verb to be guided by means the reversed guide dog ownership relation. +The verb to be friends with means the friendship relation. + +Edward is a person. A person can be blind. Edward is blind. +Edward is guided by Rover. +Benny is a person. Edward is friends with Benny. + +To demonstrate looking something up with a relation: + repeat with the dog running through things that are the guide dog of Edward: + say the dog; + repeat with the friend running through things that are friends with Edward: + say the friend. + +[We can also define relations that exist procedurally.] + +Helpfulness relates a person (called the helper) to a person (called the helpee) when the helpee is blind and the helper is not blind. +The verb to be helpful to means the helpfulness relation. +To demonstrate using a procedural relation: + repeat with the helper running through people that are helpful to Edward: + say the helper. + + +[ Interface to the text adventure harness to allow the above code to be run. ] +Tutorial room is a room. +"A rather strange room full of buttons. Push them to run the exercises, or turn on the robot to run them all." +A button is a kind of thing. A button is fixed in place. + +The red button is a button in tutorial room. +Instead of pushing the red button, do the thing everyone does with their first program. +The green button is a button in tutorial room. +Instead of pushing the green button, demonstrate calling a phrase with two parameters. +The blue button is a button in tutorial room. +Instead of pushing the blue button, show how to use list types. +The cyan button is a button in tutorial room. +Instead of pushing the cyan button, say the sum of all numbers up to 5. +The purple button is a button in tutorial room. +Instead of pushing the purple button, demonstrate a higher order function. +The black button is a button in tutorial room. +Instead of pushing the black button, demonstrate defining a higher order function. +The white button is a button in tutorial room. +Instead of pushing the white button, demonstrate invoking a rulebook. +The puce button is a button in tutorial room. +Instead of pushing the puce button, demonstrate looking something up with a relation. +The orange button is a button in tutorial room. +Instead of pushing the orange button, demonstrate using a procedural relation. + +The robot is an object in tutorial room. +Instead of switching on the robot: + say "The robot begins to frantically flail its arms about."; + repeat with button running through buttons in the tutorial room: + say "The robot randomly hits [the button]."; + try pushing button. +``` + +##Ready For More? + +* [Inform 7](http://www.inform7.com/) diff --git a/it-it/brainfuck-it.html.markdown b/it-it/bf-it.html.markdown index 08d2ede9..a79710d0 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/bf-it.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown new file mode 100644 index 00000000..3a4099e7 --- /dev/null +++ b/it-it/python-it.html.markdown @@ -0,0 +1,647 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] +filename: learnpython.py +translators: + - ["Ale46", "http://github.com/Ale46/"] +lang: it-it +--- +Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari +linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente +pseudocodice eseguibile. + +Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] + +Nota: Questo articolo è valido solamente per Python 2.7, ma dovrebbe andar bene anche per +Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). + +```python + +# I commenti su una sola linea iniziano con un cancelletto + +""" Più stringhe possono essere scritte + usando tre ", e sono spesso usate + come commenti +""" + +#################################################### +## 1. Tipi di dati primitivi ed Operatori +#################################################### + +# Hai i numeri +3 # => 3 + +# La matematica è quello che vi aspettereste +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# La divisione è un po' complicata. E' una divisione fra interi in cui viene +# restituito in automatico il risultato intero. +5 / 2 # => 2 + +# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats. +2.0 # Questo è un float +11.0 / 4.0 # => 2.75 ahhh...molto meglio + +# Il risultato di una divisione fra interi troncati positivi e negativi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funziona anche per i floats +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Operazione Modulo +7 % 3 # => 1 + +# Elevamento a potenza (x alla y-esima potenza) +2**4 # => 16 + +# Forzare le precedenze con le parentesi +(1 + 3) * 2 # => 8 + +# Operatori Booleani +# Nota "and" e "or" sono case-sensitive +True and False #=> False +False or True #=> True + +# Note sull'uso di operatori Bool con interi +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# nega con not +not True # => False +not False # => True + +# Uguaglianza è == +1 == 1 # => True +2 == 1 # => False + +# Disuguaglianza è != +1 != 1 # => False +2 != 1 # => True + +# Altri confronti +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# I confronti possono essere concatenati! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Le stringhe sono create con " o ' +"Questa è una stringa." +'Anche questa è una stringa.' + +# Anche le stringhe possono essere sommate! +"Ciao " + "mondo!" # => Ciao mondo!" +# Le stringhe possono essere sommate anche senza '+' +"Ciao " "mondo!" # => Ciao mondo!" + +# ... oppure moltiplicate +"Hello" * 3 # => "HelloHelloHello" + +# Una stringa può essere considerata come una lista di caratteri +"Questa è una stringa"[0] # => 'Q' + +# % può essere usato per formattare le stringhe, in questo modo: +"%s possono essere %s" % ("le stringhe", "interpolate") + +# Un nuovo modo per fomattare le stringhe è il metodo format. +# Questo metodo è quello consigliato +"{0} possono essere {1}".format("le stringhe", "formattate") +# Puoi usare delle parole chiave se non vuoi contare +"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna") + +# None è un oggetto +None # => None + +# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None +# Usa "is" invece +"etc" is None # => False +None is None # => True + +# L'operatore 'is' testa l'identità di un oggetto. Questo non è +# molto utile quando non hai a che fare con valori primitivi, ma lo è +# quando hai a che fare con oggetti. + +# None, 0, e stringhe/liste vuote sono tutte considerate a False. +# Tutti gli altri valori sono True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Variabili e Collections +#################################################### + +# Python ha una funzione di stampa +print "Sono Python. Piacere di conoscerti!" + +# Non c'è bisogno di dichiarare una variabile per assegnarle un valore +una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores +una_variabile # => 5 + +# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. +# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni. +un_altra_variabile # Genera un errore di nome + +# if può essere usato come un'espressione +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Liste immagazzinano sequenze +li = [] +# Puoi partire con una lista pre-riempita +altra_li = [4, 5, 6] + +# Aggiungi cose alla fine di una lista con append +li.append(1) # li ora è [1] +li.append(2) # li ora è [1, 2] +li.append(4) # li ora è [1, 2, 4] +li.append(3) # li ora è [1, 2, 4, 3] +# Rimuovi dalla fine della lista con pop +li.pop() # => 3 e li ora è [1, 2, 4] +# Rimettiamolo a posto +li.append(3) # li ora è [1, 2, 4, 3] di nuovo. + +# Accedi ad una lista come faresti con un array +li[0] # => 1 +# Assegna nuovo valore agli indici che sono già stati inizializzati con = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Nota: è resettato al valore iniziale +# Guarda l'ultimo elemento +li[-1] # => 3 + +# Guardare al di fuori dei limiti è un IndexError +li[4] # Genera IndexError + +# Puoi guardare gli intervalli con la sintassi slice (a fetta). +# (E' un intervallo chiuso/aperto per voi tipi matematici.) +li[1:3] # => [2, 4] +# Ometti l'inizio +li[2:] # => [4, 3] +# Ometti la fine +li[:3] # => [1, 2, 4] +# Seleziona ogni seconda voce +li[::2] # =>[1, 4] +# Copia al contrario della lista +li[::-1] # => [3, 4, 2, 1] +# Usa combinazioni per fare slices avanzate +# li[inizio:fine:passo] + +# Rimuovi arbitrariamente elementi da una lista con "del" +del li[2] # li è ora [1, 2, 3] +# Puoi sommare le liste +li + altra_li # => [1, 2, 3, 4, 5, 6] +# Nota: i valori per li ed altra_li non sono modificati. + +# Concatena liste con "extend()" +li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6] + +# Controlla l'esistenza di un valore in una lista con "in" +1 in li # => True + +# Esamina la lunghezza con "len()" +len(li) # => 6 + + +# Tuple sono come le liste ma immutabili. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Genera un TypeError + +# Puoi fare tutte queste cose da lista anche sulle tuple +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Puoi scompattare le tuple (o liste) in variabili +a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3 +# Le tuple sono create di default se non usi le parentesi +d, e, f = 4, 5, 6 +# Guarda come è facile scambiare due valori +e, d = d, e # d è ora 5 ed e è ora 4 + + +# Dizionari immagazzinano mappature +empty_dict = {} +# Questo è un dizionario pre-riempito +filled_dict = {"uno": 1, "due": 2, "tre": 3} + +# Accedi ai valori con [] +filled_dict["uno"] # => 1 + +# Ottieni tutte le chiavi come una lista con "keys()" +filled_dict.keys() # => ["tre", "due", "uno"] +# Nota - Nei dizionari l'ordine delle chiavi non è garantito. +# Il tuo risultato potrebbe non essere uguale a questo. + +# Ottieni tutt i valori come una lista con "values()" +filled_dict.values() # => [3, 2, 1] +# Nota - Come sopra riguardo l'ordinamento delle chiavi. + +# Controlla l'esistenza delle chiavi in un dizionario con "in" +"uno" in filled_dict # => True +1 in filled_dict # => False + +# Cercando una chiave non esistente è un KeyError +filled_dict["quattro"] # KeyError + +# Usa il metodo "get()" per evitare KeyError +filled_dict.get("uno") # => 1 +filled_dict.get("quattro") # => None +# Il metodo get supporta un argomento di default quando il valore è mancante +filled_dict.get("uno", 4) # => 1 +filled_dict.get("quattro", 4) # => 4 +# nota che filled_dict.get("quattro") è ancora => None +# (get non imposta il valore nel dizionario) + +# imposta il valore di una chiave con una sintassi simile alle liste +filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4 + +# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente +filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5 + + +# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni) +empty_set = set() +# Inizializza un "set()" con un po' di valori +some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4]) + +# l'ordine non è garantito, anche se a volta può sembrare ordinato +another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4]) + +# Da Python 2.7, {} può essere usato per dichiarare un set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Aggiungere elementi ad un set +filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5} + +# Fai intersezioni su un set con & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Fai unioni su set con | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Fai differenze su set con - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Controlla l'esistenza in un set con in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow +#################################################### + +# Dichiariamo una variabile +some_var = 5 + +# Questo è un controllo if. L'indentazione è molto importante in python! +# stampa "some_var è più piccola di 10" +if some_var > 10: + print "some_var è decisamente più grande di 10." +elif some_var < 10: # Questa clausola elif è opzionale. + print "some_var è più piccola di 10." +else: # Anche questo è opzionale. + print "some_var è precisamente 10." + + +""" +I cicli for iterano sulle liste +stampa: + cane è un mammifero + gatto è un mammifero + topo è un mammifero +""" +for animale in ["cane", "gatto", "topo"]: + # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.) + print "{0} è un mammifero".format(animale) + +""" +"range(numero)" restituisce una lista di numeri +da zero al numero dato +stampa: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" restituisce una lista di numeri +dal più piccolo (lower) al più grande (upper) +stampa: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +I cicli while vengono eseguiti finchè una condizione viene a mancare +stampa: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Forma compatta per x = x + 1 + +# Gestisci le eccezioni con un blocco try/except + +# Funziona da Python 2.6 in su: +try: + # Usa "raise" per generare un errore + raise IndexError("Questo è un errore di indice") +except IndexError as e: + pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero. +except (TypeError, NameError): + pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. +else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except + print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni +finally: # Eseguito sempre + print "Possiamo liberare risorse qui" + +# Invece di try/finally per liberare risorse puoi usare il metodo with +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. Funzioni +#################################################### + +# Usa "def" per creare nuove funzioni +def aggiungi(x, y): + print "x è {0} e y è {1}".format(x, y) + return x + y # Restituisce valori con il metodo return + +# Chiamare funzioni con parametri +aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11 + +# Un altro modo per chiamare funzioni è con parole chiave come argomenti +aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine. + + +# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali +# che verranno interpretati come tuple se non usi il * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Puoi definire funzioni che accettano un numero variabile di parole chiave +# come argomento, che saranno interpretati come un dizionario se non usi ** +def keyword_args(**kwargs): + return kwargs + +# Chiamiamola per vedere cosa succede +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Puoi farle entrambi in una volta, se ti va +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) stampa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! +# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs +# sviluppandoli, rispettivamente, con * e ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Funzioni Scope +x = 5 + +def setX(num): + # La variabile locale x non è uguale alla variabile globale x + x = num # => 43 + print x # => 43 + +def setGlobalX(num): + global x + print x # => 5 + x = num # la variabile globable x è ora 6 + print x # => 6 + +setX(43) +setGlobalX(6) + +# Python ha funzioni di prima classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Ci sono anche funzioni anonime +(lambda x: x > 2)(3) # => True + +# Esse sono incluse in funzioni di alto livello +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Possiamo usare la comprensione delle liste per mappe e filtri +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Classi +#################################################### + +# Usiamo una sottoclasse da un oggetto per avere una classe. +class Human(object): + + # Un attributo della classe. E' condiviso da tutte le istanze delle classe + species = "H. sapiens" + + # Costruttore base, richiamato quando la classe viene inizializzata. + # Si noti che il doppio leading e gli underscore finali denotano oggetti + # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato + # dall'utente. Non dovresti usare nomi di questo genere. + def __init__(self, name): + # Assegna l'argomento all'attributo name dell'istanza + self.name = name + + # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Un metodo della classe è condiviso fra tutte le istanze + # Sono chiamate con la classe chiamante come primo argomento + @classmethod + def get_species(cls): + return cls.species + + # Un metodo statico è chiamato senza una classe od una istanza di riferimento + @staticmethod + def grunt(): + return "*grunt*" + + +# Instanziare una classe +i = Human(name="Ian") +print i.say("hi") # stampa "Ian: hi" + +j = Human("Joel") +print j.say("hello") # stampa "Joel: hello" + +# Chiamare metodi della classe +i.get_species() # => "H. sapiens" + +# Cambiare l'attributo condiviso +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chiamare il metodo condiviso +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduli +#################################################### + +# Puoi importare moduli +import math +print math.sqrt(16) # => 4 + +# Puoi ottenere specifiche funzione da un modulo +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Puoi importare tutte le funzioni da un modulo +# Attenzione: questo non è raccomandato +from math import * + +# Puoi abbreviare i nomi dei moduli +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# puoi anche verificare che le funzioni sono equivalenti +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# I moduli di Python sono normali file python. Ne puoi +# scrivere di tuoi ed importarli. Il nome del modulo +# è lo stesso del nome del file. + +# Potete scoprire quali funzioni e attributi +# definiscono un modulo +import math +dir(math) + + +#################################################### +## 7. Avanzate +#################################################### + +# I generatori ti aiutano a fare codice pigro +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un generatore crea valori al volo. +# Invece di generare e ritornare tutti i valori in una volta ne crea uno in ciascuna +# iterazione. Ciò significa che i valori più grandi di 15 non saranno considerati in +# double_numbers. +# Nota xrange è un generatore che fa la stessa cosa di range. +# Creare una lista 1-900000000 occuperebbe molto tempo e spazio. +# xrange crea un oggetto generatore xrange invece di creare l'intera lista +# come fa range. +# Usiamo un underscore finale nel nome delle variabile quando vogliamo usare un nome +# che normalmente colliderebbe con una parola chiave di python +xrange_ = xrange(1, 900000000) + +# raddoppierà tutti i numeri fino a che result >=30 non sarà trovato +for i in double_numbers(xrange_): + print i + if i >= 30: + break + + +# Decoratori +# in questo esempio beg include say +# Beg chiamerà say. Se say_please è True allora cambierà il messaggio +# ritornato +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Per favore! Sono povero :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Puoi comprarmi una birra?" + return msg, say_please + + +print say() # Puoi comprarmi una birra? +print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :( +``` + +## Pronto per qualcosa di più? + +### Gratis Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Libri cartacei + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/ja-jp/bash-jp.html.markdown b/ja-jp/bash-jp.html.markdown index 88e5ff1c..ea8fa49f 100644 --- a/ja-jp/bash-jp.html.markdown +++ b/ja-jp/bash-jp.html.markdown @@ -66,7 +66,7 @@ echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $#" echo "Scripts arguments: $@" -echo "Scripts arguments seperated in different variables: $1 $2..." +echo "Scripts arguments separated in different variables: $1 $2..." # 入力値の読み込み echo "What's your name?" @@ -117,7 +117,7 @@ echo "There are $(ls | wc -l) items here." echo "There are `ls | wc -l` items here." # BashはJavaやC++のように、case文による分岐ができます -case "$VARIABLE" in +case "$VARIABLE" in #分岐条件として使いたいパターンを並べてください 0) echo "There is a zero.";; 1) echo "There is a one.";; diff --git a/ja-jp/php-jp.html.markdown b/ja-jp/php-jp.html.markdown new file mode 100644 index 00000000..112916f4 --- /dev/null +++ b/ja-jp/php-jp.html.markdown @@ -0,0 +1,777 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Kazushige Tominaga", "https://github.com/kazu9su"] +filename: learnphp-jp.php +lang: ja-jp +--- + +このドキュメントでは、 PHP 5+ について説明します。 + +```php +<?php // PHPのコードは、<?php タグで囲む必要があります。 + +// もしあなたのphpファイルがPHPのみで構成される場合、 +// 意図しない出力を防ぐために、phpの閉じタグは省略するのがベストプラクティスです。 +// 一行のコメントを書く場合、2つのスラッシュで始めます。 +# ハッシュ(ポンド記号として知られる)を使いたいでしょうが、//のほうが一般的です +/* + スラッシュとアスタリスク、アスタリスクとスラッシュで囲むと、 + 複数行のコメントを書けます。 +*/ + +// 出力をプリントしたい場合は、"echo" か "print" を使います。 +print('Hello '); // これは "Hello " という改行なしの文字列をプリントします。 + +// カッコ()はprintとecho関数に置いては省略できます。 +echo "World\n"; // これは改行ありの"World"という文字列をプリントします。 +// (全ての命令文では、セミコロンを最後に付けることが必須です。) + +// <?php タグの外側にあるものは、自動的にプリントされます。 +?> +Hello World Again! +<?php + + +/************************************ + * 型と変数について + */ + +// 変数は"$"マークで始まります +// 有効な変数名にするには、文字またはアンダースコア(_)で始めて, +// その後はどんな数字でも、文字でも、アンダースコアで続けても構いません + +//ブーリアン値は大文字、小文字問いません +$boolean = true; // or TRUE or True +$boolean = false; // or FALSE or False + +// 数値 +$int1 = 12; // => 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (先頭の0は8進法を示す) +$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す) + +// floats(浮動小数) (別名double) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// 変数の削除 +unset($int1); + +// 計算式 +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// 式の省略 +$number = 0; +$number += 1; // $numberに1加算Increment $number by 1 +echo $number++; // 1 がプリントされる(式の評価の後に加算される) +echo ++$number; // 3 がプリントされる(式の評価の前に加算される) +$number /= $float; // 割り算した結果の商を$numberに割り当てる + +// 文字列はシングルクォートで囲むのが望ましいです +$sgl_quotes = '$String'; // => '$String' + +// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +// 特殊文字はダブルクォートによってのみ、エスケープされます +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// 必要があれば、変数を波括弧で囲みます +$money = "I have $${number} in the bank."; + +// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます +$nowdoc = <<<'END' +Multi line +string +END; + +// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。 +$heredoc = <<<END +Multi line +$sgl_quotes +END; + +// 文字列の連結は . で行います +echo 'This string ' . 'is concatenated'; + +// 別々のパラメータとしてechoに渡すこともできます +echo 'Multiple', 'Parameters', 'Valid'; + +/******************************** + * 定数 + */ + +// 定数は define() を使って定義します +// また、実行中は変更することができないので注意が必要です! + +// 有効は定数は文字かアンダースコアで始めます +// それ移行のは、どんな数値でも文字列でもアンダースコアでも構いません +define("FOO", "something"); + +// 定義した名前をそのまま($はつけずに)使用することで、定数にアクセスできます +// access to a constant is possible by direct using the choosen name +echo 'This outputs '.FOO; + + +/******************************** + * 配列 + */ + +// PHPの配列はすべて連想配列です + +// 連想配列は、他の言語ではハッシュ(ハッシュマップ)として知られています + +// すべてのバージョンのPHPで動作します +$associative = array('One' => 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 から、新しいシンタックスが導入されました +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // 1とプリントされます + +// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// 配列の最後に要素を追加する +$array[] = 'Four'; +// または、次のようにも書けます +array_push($array, 'Five'); + +// 配列から要素を削除 +unset($array[3]); + +/******************************** + * 出力 + */ + +echo('Hello World!'); +// 標準出力にHello World! とプリントします +// 標準出力はブラウザーで実行していればWebページに出力されます +// Stdout is the web page if running in a browser. + +print('Hello World!'); // echoの結果と同じです + +// echo は言語自体の構成要素であり、括弧なしで呼び出せます +// echo is actually a language construct, so you can drop the parentheses. +echo 'Hello World!'; +print 'Hello World!'; // printも同様です + +$paragraph = 'paragraph'; + +echo 100; // スカラー数値を直接出力します +echo $paragraph; // 変数も使用できます + +// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが +// 5.4.0 以上であれば、短縮echoシンタックスを使用できます +?> +<p><?= $paragraph ?></p> +<?php + +$x = 1; +$y = 2; +$x = $y; // $xに$yの値を代入します +$z = &$y; +// $zは$yへの参照です。 +// $zの値を変更すると$yの値も変更されるでしょう。逆も同様です。 +// $xは$yの最初の値を変わらず保持しています + +echo $x; // => 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// 変数の型と値を標準出力へダンプします +var_dump($z); // int(0) と出力されます + +// 人間が読めるフォーマットで変数を標準出力にプリントします +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * ロジック + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assertは引数がfalseの場合、Exceptionを投げます + +//これらの比較は型が違ったとしても、常に真です。 +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// 次の比較は値が等しく、かつ同じ型である場合のみ真です +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// spaceship演算子はPHP7から使用可能です +$a = 100; +$b = 1000; + +echo $a <=> $a; // 等しいので0になります +echo $a <=> $b; // $a < $b なので -1 です +echo $b <=> $a; // $b > $a なので 1 です + +// 変数は使用するコンテキストによって、変換されます + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (文字列は強制的に数値として処理されます) + +$string = 'one'; +echo $string + $string; // => 0 +// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます + +// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// 型をキャストするため専用の関数も存在します +$integer = 5; +$string = strval($integer); + +$var = null; // Null値 + + +/******************************** + * 制御構造 + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// 三項演算子 +print (false ? 'Does not get printed' : 'Does'); + +// PHP 5.3から、三項演算子の短縮形が使用できます +// $x ? $x : 'Does'と同義です +$x = false; +print($x ?: 'Does'); + +// null合体演算子はPHP 7から使用できます +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// :を用いる別の構文はテンプレートで有用です +?> + +<?php if ($x): ?> +この部分はifが真のとき表示されます +<?php else: ?> +それ以外の場合は、この部分が表示されます +<?php endif; ?> + +<?php + +// いくつかのロジックを保存するにはswitchを使用します +switch ($x) { + case '0': + print 'Switch does type coercion'; + break; // breakを書く必要があります。 + // でなければ、次の'two', 'three'のcase文を続けて実行することになります。 + case 'two': + case 'three': + // 変数が'two'または'three'の場合、何かを実行します + break; + default: + //デフォルトで何かを実行します +} + +// while, do, forの構文は、おそらく他の言語とも共通なものです +$i = 0; +while ($i < 5) { + echo $i++; +}; // Prints "01234" + +echo "\n"; + +$i = 0; +do { + echo $i++; +} while ($i < 5); // Prints "01234" + +echo "\n"; + +for ($x = 0; $x < 10; $x++) { + echo $x; +} // Prints "0123456789" + +echo "\n"; + +$wheels = ['bicycle' => 2, 'car' => 4]; + +//Foreachループによって、 配列を反復処理できます +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// 値と同じ様に、keyも反復処理できます +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * 関数 + */ + +// 関数を"function"で定義します +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は +// どれだけ長い文字、数値、アンダースコアを続けても構いません + +function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result には、関数の外からアクセス出来ません +// print $result; // エラーになります + +// PHP 5.3 から、無名関数が使えます +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// 関数は、関数を返すことができます +function bar ($x, $y) { + // 関数外の変数を利用したいときは、'use'を使います + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// 文字列を使って、定義済みの関数を呼び出すことができます +$function_name = 'add'; +echo $function_name(1, 2); // => 3 + +// プログラミング中に、動的に動かす関数を決める場合に便利です。 +// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます + + +// 特に指定しなくても、渡された引数を受け取ることもできます +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +/******************************** + * ファイルの読み込み + */ + +<?php +// 読み込まれたファイル中のPHPは、同じくPHPのオープンタグで始める必要があります + +include 'my-file.php'; +// my-file.php中のコードは、現在のスコープの中で使用可能です +// もしファイルを読み込めなければ (例:file not found)、警告が発せられます + +include_once 'my-file.php'; +// my-file.phpのコードが既にどこかで読み込まれていれば、 +// ファイルを読み込みません。これは、クラスの多重定義のエラーを防ぎます + +require 'my-file.php'; +require_once 'my-file.php'; +// include()と同じように、require()はもしファイルを読み込むことができなければ、 +// 致命的エラーの原因となります + +// my-include.phpの内容 +<?php + +return 'Anything you like.'; +// End file + +// include()とrequire()は一つの値を返します +$value = include 'my-include.php'; + +// ファイルは与えられたファイルパスを基に読み込まれます。 +// ファイルパスを指定しない場合は、include_path の設定を利用します。 +// もしファイルがinclude_path中に見つからない場合は、 +// 呼び出し元スクリプトのディレクトリと作業ディレクトリの中も探します。 +// それでも見つからない場合、失敗します。 +/* */ + +/******************************** + * クラス + */ + +// クラスはclassキーワードで定義します + +class MyClass +{ + const MY_CONST = 'value'; // クラス定数です + + static $staticVar = 'static'; + + // スタティック変数とアクセス制限 + public static $publicStaticVar = 'publicStatic'; + // クラス内でのみアクセス可能 + private static $privateStaticVar = 'privateStatic'; + // そのクラスと子クラスで参照可能 + protected static $protectedStaticVar = 'protectedStatic'; + + // プロパティはアクセス制限を宣言する必要があります + public $property = 'public'; + public $instanceProp; + protected $prot = 'protected'; // そのクラスと子クラスで参照可能 + private $priv = 'private'; // クラス内でのみアクセス可能 + + // __constructでコンストラクターを生成します + public function __construct($instanceProp) { + // $thisでインスタンス変数にアクセスします + $this->instanceProp = $instanceProp; + } + + // メソッドはクラス内で関数として定義されます + public function myMethod() + { + print 'MyClass'; + } + + // finalキーワードは関数の上書きを禁止します + final function youCannotOverrideMe() + { + } + +/* + * クラスプロパティまたはメソッドをstaticとして作成すれば、 + * クラスをインスタンス化(newすること)しなくてもアクセスできます。 + * プロパティをstaticとして定義すると、 + * インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。 + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// クラス定数は、いつでも静的にアクセスできます。 +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// クラスをインスタンス化するには、newを使います。 +$my_class = new MyClass('An instance property'); +// 括弧はもし引数を渡す必要がなければ省略可能です。 + +// ->を使ってクラスのメンバにアクセスします。 +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// extendsを使用してクラスを継承します。 +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // メソッドを上書きします。 + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// 「マジックメソッド」を使ってゲッターとセッターを生成できます。 +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // __get() メソッドを使用します +$x->property = 'Something'; // __set() メソッドを使用します + +// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、 +// インターフェースを実装することもできます(implementsキーワードを使用します)。 +// インターフェースはinterfaceキーワードで定義します。 + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// インターフェースは継承することができます +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// クラスは1つ以上のインターフェースを実装できます。 +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * トレイト + */ + +// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。 + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * 名前空間 + */ + +// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、 +// 独立しています。 +// そのケースには当てはまらないふりをして続けましょう。 + +<?php + +// デフォルトでは、クラスはグローバルな名前空間に存在し、 +// バックスラッシュによって明確にコールできます。 + +$cls = new \MyClass(); + + + +// ファイルに名前空間をセットします +namespace My\Namespace; + +class MyClass +{ +} + +// (別のファイルからの呼び出し) +$cls = new My\Namespace\MyClass; + +// 異なる名前空間からの呼び出し +namespace My\Other\Namespace; + +use My\Namespace\MyClass; + +$cls = new MyClass(); + +// 名前空間に別名をつけることもできます + +namespace My\Other\Namespace; + +use My\Namespace as SomeOtherNamespace; + +$cls = new SomeOtherNamespace\MyClass(); + +/********************** +* エラーハンドリング +* +*/ + +// シンプルなエラーハンドリングは、try catchを使えば行えます + +try { + // 処理を実行します +} catch ( Exception $e) { + // 例外を処理します +} + +// try catchを名前空間を持った環境で使用するときは、次のようにします。 + +try { + // Do something + // 処理を実行します +} catch (\Exception $e) { + // 例外を処理します +} + +// 例外のカスタマイズ + +class MyException extends Exception {} + +try { + + $condition = true; + + if ($condition) { + throw new MyException('Something just happend'); + } + +} catch (MyException $e) { + // Handle my exception +} + +``` + +## より詳しい情報 + +リファレンスを見るため、またコミュニティへの情報提供のために、 [PHP公式ドキュメント](http://www.php.net/manual/) を訪れてみてください。 + +もし最新のベストプラクティスに興味があるなら、 +[PHP The Right Way](http://www.phptherightway.com/)を訪れてみてください。 + + +もしあなたがよいパッケージマネジメント・システムを持つ言語で開発経験があるのなら、 +[Composer](http://getcomposer.org/)も確かめてみてください。 + + +共通基準を知るためには、PHP Framework Interoperability Groupの +[PSR standards](https://github.com/php-fig/fig-standards)にも訪れてみてください。 diff --git a/java.html.markdown b/java.html.markdown index 74140120..50629ce1 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -175,7 +175,7 @@ public class LearnJava { // Another way to declare & initialize an array int[] y = {9000, 1000, 1337}; String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; - boolean bools[] = new boolean[] {true, false, false}; + boolean bools[] = {true, false, false}; // Indexing an array - Accessing an element System.out.println("intArray @ 0: " + intArray[0]); @@ -438,7 +438,7 @@ public class LearnJava { // You can include other, non-public outer-level classes in a .java file, -// but it is good practice. Instead split classes into separate files. +// but it is not good practice. Instead split classes into separate files. // Class Declaration Syntax: diff --git a/julia.html.markdown b/julia.html.markdown index ef3ea244..2810555e 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -151,12 +151,16 @@ a = Int64[] # => 0-element Int64 Array # 1-dimensional array literals can be written with comma-separated values. b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 # 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] +# Arrays of a particular Type +b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6] + # Add stuff to the end of a list with push! and append! push!(a,1) # => [1] push!(a,2) # => [1,2] diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/bf-kr.html.markdown index c2e4341f..3d366d7c 100644 --- a/ko-kr/brainfuck-kr.html.markdown +++ b/ko-kr/bf-kr.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/latex.html.markdown b/latex.html.markdown index 2492f226..d41f6b2f 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -205,7 +205,7 @@ environment. By now you're probably wondering how to compile this fabulous document and look at the glorious glory that is a LaTeX pdf. -(yes, this document actually does compiles). \\ +(yes, this document actually does compile). \\ Getting to the final document using LaTeX consists of the following steps: \begin{enumerate} \item Write the document in plain text (the "source code"). diff --git a/less.html.markdown b/less.html.markdown index 41d66a54..7195271e 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -8,7 +8,7 @@ contributors: Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code. -```less +```css //Single line comments are removed when Less is compiled to CSS. diff --git a/make.html.markdown b/make.html.markdown index e8cfd2b5..bf934c58 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -11,7 +11,7 @@ target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly
on Unix) despite many competitors and criticisms.
-There are many varieties of make in existance, this article assumes that
+There are many varieties of make in existence, this article assumes that
we are using GNU make which is the standard on Linux.
```make
diff --git a/markdown.html.markdown b/markdown.html.markdown index 8961c995..05eeecbe 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -26,6 +26,7 @@ specific to a certain parser. ## HTML Elements Markdown is a superset of HTML, so any HTML file is valid Markdown. + ```markdown <!--This means we can use HTML elements in Markdown, such as the comment element, and they won't be affected by a markdown parser. However, if you create an HTML element @@ -54,6 +55,7 @@ This is an h1 This is an h2 ------------- ``` + ## Simple text styles Text can be easily styled as italic or bold using markdown. @@ -133,6 +135,7 @@ or - Item - One last item ``` + Ordered lists are done with a number followed by a period. ```markdown @@ -152,6 +155,7 @@ render the numbers in order, but this may not be a good idea. (This renders the same as the above example) You can also use sublists + ```markdown 1. Item one 2. Item two @@ -197,13 +201,13 @@ John didn't even know what the `go_to()` function did! ``` In Github Flavored Markdown, you can use a special syntax for code -```markdown -\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! --> + +<pre> +<code class="highlight">```ruby def foobar puts "Hello world!" end -\`\`\` <!-- here too, no backslashes, just ``` --> -``` +```</code></pre> The above text doesn't require indenting, plus Github will use syntax highlighting of the language you specify after the \`\`\` @@ -212,6 +216,7 @@ highlighting of the language you specify after the \`\`\` Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens, with or without spaces. + ```markdown *** --- @@ -228,58 +233,64 @@ the text to display in hard brackets [] followed by the url in parentheses () [Click me!](http://test.com/) ``` You can also add a link title using quotes inside the parentheses. + ```markdown [Click me!](http://test.com/ "Link to Test.com") ``` Relative paths work too. + ```markdown [Go to music](/music/). ``` + Markdown also supports reference style links. -```markdown -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "Alright!" -``` +<pre><code class="highlight">[<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it! +[<span class="nv">Also check out this link</span>][<span class="ss">foobar</span>] if you want to. + +[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span> +[<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Alright!"</span></code></pre> + The title can also be in single quotes or in parentheses, or omitted entirely. The references can be anywhere in your document and the reference IDs can be anything so long as they are unique. There is also "implicit naming" which lets you use the link text as the id. -```markdown -[This][] is a link. -[this]: http://thisisalink.com/ -``` +<pre><code class="highlight">[<span class="nv">This</span>][] is a link. + +[<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre> + But it's not that commonly used. ## Images Images are done the same way as links but with an exclamation point in front! + ```markdown ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") ``` + And reference style works as expected. -```markdown -![This is the alt-attribute.][myimage] -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" -``` +<pre><code class="highlight">![<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>] +[<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre> ## Miscellany ### Auto-links + ```markdown <http://testwebsite.com/> is equivalent to [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto-links for emails + ```markdown <foo@bar.com> ``` ### Escaping characters + ```markdown I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. @@ -288,6 +299,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys. + ```markdown Your computer crashed? Try sending a <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> @@ -296,6 +308,7 @@ Your computer crashed? Try sending a Tables are only available in Github Flavored Markdown and are slightly cumbersome, but if you really want it: + ```markdown | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | @@ -309,5 +322,6 @@ Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop ``` + --- For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/ms-my/json-my.html.markdown b/ms-my/json-my.html.markdown new file mode 100644 index 00000000..2d2da519 --- /dev/null +++ b/ms-my/json-my.html.markdown @@ -0,0 +1,102 @@ +--- +language: json +filename: learnjson-ms.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] +translators: + - ["abdalim", "https://github.com/abdalim"] +lang: ms-my +--- + +Disebabkan JSON adalah format pertukaran-data yang sangat ringkas, panduan ini +kemungkinan besar adalah Learn X in Y Minutes yang paling mudah. + +JSON dalam bentuk paling aslinya sebenarnya tidak mempunyai sebarang komentar, +tetapi kebanyakan pembaca menerima komen dalam bentuk C (`\\`,`/* */`). Beberapa +pembaca juga bertoleransi terhadap koma terakhir (iaitu koma selepas elemen +terakhir di dalam array atau selepas ciri terakhir sesuatu objek), tetapi semua +ini harus dielakkan dan dijauhkan untuk keserasian yang lebih baik. + +Untuk tujuan ini bagaimanapun, semua di dalam panduan ini adalah 100% JSON yang +sah. Luckily, it kind of speaks for itself. + +Sebuah nilai JSON harus terdiri dari salah satu, iaitu, nombor, string, array, +objek atau salah satu dari nama literal berikut: true, false, null. + +Pelayar web yang menyokong adalah: Firefox 3.5+, Internet Explorer 8.0+, Chrome +1.0+, Opera 10.0+, dan Safari 4.0+. + +Sambungan fail untuk fail - fail JSON adalah ".json" dan jenis MIME untuk teks +JSON adalah "application/json". + +Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan +menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript +mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data. + +Maklumat lebih lanjut boleh dijumpai di http://www.json.org/ + +JSON dibina pada dua struktur: +* Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini +direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table", +senarai berkunci, atau "associative array". +* Sebuah senarai nilai yang tersusun. Dalam kebanyakan bahasa aturcara, ini +direalisasikan sebagai array, vektor, senarai atau urutan. + +Sebuah objek dengan pelbagai pasangan nama/nilai. + +```json +{ + "kunci": "nilai", + + "kekunci": "harus sentiasa dibalut dengan 'double quotes'", + "nombor": 0, + "strings": "Hellø, wørld. Semua unicode dibenarkan, bersama \"escaping\".", + "ada bools?": true, + "tiada apa - apa": null, + + "nombor besar": 1.2e+100, + + "objek": { + "komen": "Sebahagian besar struktur akan terdiri daripada objek.", + + "array": [0, 1, 2, 3, "Array boleh mempunyai sebarang jenis data di dalamnya.", 5], + + "objek lain": { + "komen": "Objek boleh dibina dengan pelbagai lapisan, sangat berguna." + } + }, + + "kebendulan": [ + { + "punca potassium": ["pisang"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "stail alternatif": { + "komen": "cuba lihat ini!" + , "posisi koma": "tidak mengapa - selagi ia adalah sebelum nama atau kunci seterusnya, maka ia sah" + , "komen lain": "sungguh bagus" + } +} +``` + +Sebuah array sahaja yang mengandungi nilai - nilai juga adalah JSON yang sah. + +```json +[1, 2, 3, "text", true] +``` + +Objek - objek boleh menjadi sebahagian dari array juga. + +```json +[{"nama": "Abe", "umur": 25}, {"nama": "Jemah", "umur": 29}, {"name": "Yob", "umur": 31}] +``` diff --git a/nim.html.markdown b/nim.html.markdown index 79271732..4901ebfe 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```nimrod +```javascript var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown deleted file mode 100644 index d5e0022a..00000000 --- a/nl-nl/amd-nl.html.markdown +++ /dev/null @@ -1,235 +0,0 @@ ---- -category: tool -tool: amd -contributors: - - ["Frederik Ring", "https://github.com/m90"] -translators: - - ["Reinoud Kruithof", "https://github.com/reinoudk"] -filename: learnamd-nl.js -lang: nl-nl ---- - -## Aan de slag met AMD - -De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript - modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon - geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het - synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid, - debugging en cross-domain toegangsproblemen. - -### Basis concept -```javascript -// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require` -// and gaat vooral over de definitie en gebruik van modules: -// `define(id?, dependencies?, factory)` definieert een module -// `require(dependencies, callback)` importeert een set van dependencies en -// gebruikt ze in de gegeven callback - -// Laten we starten met het gebruiken van define om een nieuwe module (met naam) -// te creeren, welke geen dependencies heeft. Dit doen we door een naam -// en een zogeheten factory functie door te geven aan define: -define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - // De return waarde van een module's factory functie is - // wat andere modules of require calls ontvangen wanneer - // ze onze `awesomeAMD` module requiren. - // De gexporteerde waarde kan van alles zijn: (constructor) functies, - // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft). - return isAMDAwesome; -}); - - -// We gaan nu een andere module defineren die afhankelijk is van onze -// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument -// is die de dependencies van onze module defineert: -define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){ - // dependencies worden naar de factory's functieargumenten - // gestuurd in de volgorde waarin ze gespecificeert zijn - var vertelIedereen = function(){ - if (awesomeAMD()){ - alert('Dit is zOoOo cool!'); - } else { - alert('Vrij saai, niet?'); - } - }; - return vertelIedereen; -}); - -// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken -// om ons programma mee te starten. De vorm van `require` is -// `(arrayVanDependencies, callback)`. -require(['schreeuwlelijk'], function(schreewlelijk){ - schreeuwlelijk(); -}); - -// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic -// (niet-asynchrone) versie van AMD implementeren: -function define(naam, deps, factory){ - // merk op hoe modules zonder dependencies worden afgehandeld - define[naam] = require(factory ? deps : [], factory || deps); -} - -function require(deps, callback){ - var args = []; - // we halen eerst alle dependecies op die nodig zijn - // om require aan te roepen - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // voldoe aan alle dependencies van de callback - return callback.apply(null, args); -} -// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/ -``` - -### require.js in de echte wereld - -In contrast met het voorbeeld uit de introductie, implementeert `require.js` - (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk - om je modules en hun dependencies asynchroon in the laden via XHR: - -```javascript -/* file: app/main.js */ -require(['modules/someClass'], function(SomeClass){ - // de callback word uitgesteld tot de dependency geladen is - var things = new SomeClass(); -}); -console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd -``` - -De afspraak is dat je over het algemeen n module in n bestand opslaat. -`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie, -dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen - door hun locatie te gebruiken. -In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map, - relatief ten opzichte van de `baseUrl` uit je configuratie. - -* app/ - * main.js - * modules/ - * someClass.js - * someHelpers.js - * ... - * daos/ - * things.js - * ... - -Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren: - -```javascript -/* file: app/modules/someClass.js */ -define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ - // definitie van de module gebeurt, natuurlijk, ook asynchroon - function SomeClass(){ - this.method = function(){/**/}; - // ... - } - return SomeClass; -}); -``` -Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping - aan te passen in je `main.js`: - -```javascript -/* file: main.js */ -requirejs.config({ - baseUrl : 'app', - paths : { - // je kan ook modules uit andere locatie inladen - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibUitBower : '../bower_components/cool-lib/coollib' - } -}); -require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){ - // een `main` bestand moet require minstens eenmaal aanroepen, - // anders zal er geen code uitgevoerd worden - coolLib.doFancyDingenMet(helpers.transform($('#foo'))); -}); -``` -Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`) - welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut. -Deze zal automisch geladen en uitgevoerd worden als de pagina laadt: - -```html -<!DOCTYPE html> -<html> -<head> - <title>Honder script tags? Nooi meer!</title> -</head> -<body> - <script src="require.js" data-main="app/main"></script> -</body> -</html> -``` - -### Een heel project optimaliseren met r.js - -Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de - ontwikkelfase om code op een gezonde manier te organiseren maar - willen nog steeds een enkel scriptbestand gebruiken in productie in - plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. - -`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk -uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de -dependency book van je project analyseert en een enkel bestand bouwt met daarin -al je module (juist genaamd), geminificeerd en klaar voor productie. - -Instaleren met `npm`: -```shell -$ npm install requirejs -g -``` - -Nu kun je het een configuratiebestand voeden: -```shell -$ r.js -o app.build.js -``` - -Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: -```javascript -/* file : app.build.js */ -({ - name : 'main', // naam van het beginpunt - out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt - baseUrl : 'app', - paths : { - // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, - // gebruik makend van de locatie gespecificeert in `main.js` - jquery : 'empty:', - coolLibUitBower : '../bower_components/cool-lib/coollib' - } -}) -``` -Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: -```html -<script src="require.js" data-main="app/main-built"></script> -``` - -Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is -beschikbar in de GitHub repo (Engels). - -Hieronder vind je nog meer informatie over AMD (Engels). - -### Onderwerpen die niet aan bod zijn gekomen -* [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) - -### Verder lezen: - -* [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) - -### Implementaties: - -* [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/nl-nl/brainfuck-nl.html.markdown b/nl-nl/bf.html.markdown index 6062b24c..016e2ba2 100644 --- a/nl-nl/brainfuck-nl.html.markdown +++ b/nl-nl/bf.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/perl.html.markdown b/perl.html.markdown index 1b86f410..61e8cd0e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -5,6 +5,7 @@ language: perl filename: learnperl.pl contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Dan Book", "http://github.com/Grinnz"] --- Perl 5 is a highly capable, feature-rich programming language with over 25 years of development. @@ -14,6 +15,15 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. +#### Strict and warnings + +use strict; +use warnings; + +# All perl scripts and modules should include these lines. Strict causes +# compilation to fail in cases like misspelled variable names, and warnings +# will print warning messages in case of common pitfalls like concatenating +# to an undefined value. #### Perl variable types @@ -37,7 +47,9 @@ my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); - +# Array elements are accessed using square brackets, with a $ to indicate +# one value will be returned. +my $second = $animals[1]; ## Hashes # A hash represents a set of key/value pairs: @@ -50,11 +62,39 @@ my %fruit_color = ( apple => "red", banana => "yellow", ); + +# Hash elements are accessed using curly braces, again with the $ sigil. +my $color = $fruit_color{apple}; + # Scalars, arrays and hashes are documented more fully in perldata. # (perldoc perldata). -# More complex data types can be constructed using references, which allow you -# to build lists and hashes within lists and hashes. +#### References + +# More complex data types can be constructed using references, which allow +# you to build arrays and hashes within arrays and hashes. + +my $array_ref = \@array; +my $hash_ref = \%hash; +my @array_of_arrays = (\@array1, \@array2, \@array3); + +# You can also create anonymous arrays or hashes, returning a reference: + +my $fruits = ["apple", "banana"]; +my $colors = {apple => "red", banana => "yellow"}; + +# References can be dereferenced by prefixing the appropriate sigil. + +my @fruits_array = @$fruits; +my %colors_hash = %$colors; + +# As a shortcut, the arrow operator can be used to dereference and access a +# single value. + +my $first = $array_ref->[0]; +my $value = $hash_ref->{banana}; + +# See perlreftut and perlref for more in-depth documentation on references. #### Conditional and looping constructs @@ -105,6 +145,9 @@ for (@elements) { # the Perlish post-condition way again print for @elements; +# iterating through the keys and values of a referenced hash +print $hash_ref->{$_} for keys %$hash_ref; + #### Regular expressions # Perl's regular expression support is both broad and deep, and is the subject @@ -151,11 +194,101 @@ sub logger { # Now we can use the subroutine just as any other built-in function: logger("We have a logger subroutine!"); -``` -#### Using Perl modules +#### Modules + +# A module is a set of Perl code, usually subroutines, which can be used in +# other Perl code. It is usually stored in a file with the extension .pm so +# that Perl can find it. + +package MyModule; +use strict; +use warnings; + +sub trim { + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +1; + +# From elsewhere: + +use MyModule; +MyModule::trim($string); + +# The Exporter module can help with making subroutines exportable, so they +# can be used like this: + +use MyModule 'trim'; +trim($string); + +# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and +# provide a range of features to help you avoid reinventing the wheel. A +# number of popular modules like Exporter are included with the Perl +# distribution itself. See perlmod for more details on modules in Perl. + +#### Objects + +# Objects in Perl are just references that know which class (package) they +# belong to, so that methods (subroutines) called on it can be found there. +# The bless function is used in constructors (usually new) to set this up. +# However, you never need to call it yourself if you use a module like Moose +# or Moo (see below). + +package MyCounter; +use strict; +use warnings; + +sub new { + my $class = shift; + my $self = {count => 0}; + return bless $self, $class; +} + +sub count { + my $self = shift; + return $self->{count}; +} + +sub increment { + my $self = shift; + $self->{count}++; +} + +1; + +# Methods can be called on a class or object instance with the arrow operator. + +use MyCounter; +my $counter = MyCounter->new; +print $counter->count, "\n"; # 0 +$counter->increment; +print $counter->count, "\n"; # 1 + +# The modules Moose and Moo from CPAN can help you set up your object classes. +# They provide a constructor and simple syntax for declaring attributes. This +# class can be used equivalently to the one above. + +package MyCounter; +use Moo; # imports strict and warnings + +has 'count' => (is => 'rwp', default => 0, init_arg => undef); + +sub increment { + my $self = shift; + $self->_set_count($self->count + 1); +} + +1; + +# Object-oriented programming is covered more thoroughly in perlootut, and its +# low-level implementation in Perl is covered in perlobj. +``` -Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself. +#### FAQ perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. diff --git a/perl6.html.markdown b/perl6.html.markdown index 1829f964..5082a433 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -103,7 +103,7 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` (Perl's "null"-like value) if I don't have + say "I might return `(Any)` (Perl's 'null'-like value) if I don't have an argument passed, or I'll return my argument"; $arg; } @@ -803,9 +803,8 @@ module Foo::Bar { my sub unavailable { # `my sub` is the default say "Can't access me from outside, I'm my !"; } + say ++$n; # increment the package variable and output its value } - - say ++$n; # lexically-scoped variables are still available } say $Foo::Bar::n; #=> 1 Foo::Bar::inc; #=> 2 @@ -1330,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... -### Extra: the MAIN subroutime +### Extra: the MAIN subroutine # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) diff --git a/php.html.markdown b/php.html.markdown index 0504ced2..ce178a15 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -53,6 +53,8 @@ $int1 = 12; // => 12 $int2 = -12; // => -12 $int3 = 012; // => 10 (a leading 0 denotes an octal number) $int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +// Binary integer literals are available since PHP 5.4.0. +$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number) // Floats (aka doubles) $float = 1.234; @@ -116,11 +118,11 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' // a valid constant name starts with a letter or underscore, // followed by any number of letters, numbers, or underscores. -define("FOO", "something"); +define("FOO", "something"); // access to a constant is possible by calling the choosen name without a $ echo FOO; // Returns 'something' -echo 'This outputs '.FOO; // Returns 'This ouputs something' +echo 'This outputs ' . FOO; // Returns 'This ouputs something' @@ -765,6 +767,37 @@ I'm a ParentClass But I'm ChildClass */ +/********************** +* Magic constants +* +*/ + +// Get current class name. Must be used inside a class declaration. +echo "Current class name is " . __CLASS__; + +// Get full path directory of a file +echo "Current directory is " . __DIR__; + + // Typical usage + require __DIR__ . '/vendor/autoload.php'; + +// Get full path of a file +echo "Current file path is " . __FILE__; + +// Get current function name +echo "Current function name is " . __FUNCTION__; + +// Get current line number +echo "Current line number is " . __LINE__; + +// Get the name of the current method. Only returns a value when used inside a trait or object declaration. +echo "Current method is " . __METHOD__; + +// Get the name of the current namespace +echo "Current namespace is " . __NAMESPACE__; + +// Get the name of the current trait. Only returns a value when used inside a trait or object declaration. +echo "Current namespace is " . __TRAIT__; /********************** * Error Handling diff --git a/pl-pl/brainfuck-pl.html.markdown b/pl-pl/bf-pl.html.markdown index 69d814c4..801f1a9a 100644 --- a/pl-pl/brainfuck-pl.html.markdown +++ b/pl-pl/bf-pl.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown index 9e8ade5b..029ca006 100644 --- a/pl-pl/perl-pl.html.markdown +++ b/pl-pl/perl-pl.html.markdown @@ -163,7 +163,7 @@ 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 + - [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` diff --git a/pl-pl/xml-pl.html.markdown b/pl-pl/xml-pl.html.markdown new file mode 100644 index 00000000..7cce138f --- /dev/null +++ b/pl-pl/xml-pl.html.markdown @@ -0,0 +1,137 @@ +--- +language: xml +filename: learnxml-pl.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Tomasz Janiszewski", "https://github.com/janisz"] +lang: pl-pl +--- + +XML (_Extensible Markup Language_) to rozszerzalny język znaczników, stworzony +do przechowywania i transportu danych. + +W przeciwieństwie do HTML, XML nie specyfikuje w jaki sposób wyświetlić dane, a +tylko je przechowuje. + +* Składnia XML + +```xml +<!-- Komentarze w XML wyglądają jak ten --> + +<?xml version="1.0" encoding="UTF-8"?> +<ksiegarnia> + <ksiazka kategoria="GOTOWANIE"> + <tytul lang="pl">Codzienny Włoski</tytul> + <autor>Giada De Laurentiis</autor> + <rok>2005</rok> + <cena>30.00</cena> + </ksiazka> + <ksiazka kategoria="DZIECI"> + <tytul lang="pl">Harry Potter</tytul> + <autor>J K. Rowling</autor> + <rok>2005</rok> + <cena>29.99</cena> + </ksiazka> + <ksiazka kategoria="WEB"> + <tytul lang="pl">Nauka XML</tytul> + <autor>Erik T. Ray</autor> + <rok>2003</rok> + <cena>39.95</cena> + </ksiazka> +</ksiegarnia> + +<!-- Powyżej jest typowy plik XML. + Zaczyna się od deklaracji zawierającej metadane (opcjonalne). + + XML używa drzewiastej struktury. Powyżej, głównym wierzchołkiem jest + 'ksiegarnia' , która zawiera trzy (3) węzły potomne, wszystkie 'ksiazki', + które zawierają swoje węzły potomne, i tak dalej... + + Węzły są tworzone używające otwierających/zamykających znaczników. + Węzły potomne znajdują się pomiędzy otwierającym i zamykającym znacznikiem. +--> + +<!-- XML przechowuje dwa typy danych + 1 - Atrybuty -> metadane o węźle + Zazwyczaj parser XML używa tych informacji do przechowywania danych we + właściwy sposób. Atrybuty nadawane są poprzez wpisanie ich w otwierajacym + znaczniku. + 2 - Elementy -> to są czyste dane. + Dane, które parser otrzymuje z pliku XML. + Elementy są deklarowane pomiędzy otwierajacym i zamykającym znacznikiem, + bez nawiasów. --> + +<!-- Poniższy element ma dwa atrybuty --> +<plik type="gif" id="4293">komputer.gif</plik> + + +``` + +* Dobrze sformatowany dokument i walidacja + +Dokument XML jest dobrze sformatowany gdy jest syntaktycznie poprawny. +Jednakże możliwe jest wstrzykiwanie większej liczby ograniczeń w dokumencie, +używając definicji takich jak DTD i XML Schema. + +Dokument XML, który jest zgodny ze swoją definicją jest poprawny. + + +Korzystając z tych narzędzi możesz sprawdzić dane zawarte w dokumencie poza +logiką aplikacji. + +```xml + + +<!-- Poniżej jest uproszczona wersja dokumentu księgarni, + z dodatkową definicją DTD.--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE notatka SYSTEM "Ksiegarnia.dtd"> +<ksiegarnia> + <ksiazka kategoria="GOTOWANIE"> + <tytul >Everyday Italian</tytul> + <cena>30.00</cena> + </ksiazka> +</ksiegarnia> + +<!-- DTD może wyglądać następująco:--> + +<!DOCTYPE notatka +[ +<!ELEMENT ksiegarnia (ksiazka+)> +<!ELEMENT ksiazka (tytul,cena)> +<!ATTLIST ksiazka kategoria CDATA "Literatura"> +<!ELEMENT tytul (#PCDATA)> +<!ELEMENT cena (#PCDATA)> +]> + + +<!-- DTD zaczyna się od deklaracji + Zaczynając od góry, główny węzeł jest zadeklarowany jako wymagający jednego + lub więcej węzłów potomnych typu 'ksiżka'. + Każda 'ksiażka' powinna zawierać dokładnie jeden 'tytuł' i 'cene' oraz atrybut + 'kategoria' z 'literaturą' jako wartość domyślna. + 'tytuł' i 'cena' to pola typu parsowalnych zmiennyc znakowych, co oznacza że + użyte znaczniki zostaną zinterpretowane < zamienione <. --> + +<!-- DTD moze być deklarowane wewnątrz pliku XML. --> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE notatka +[ +<!ELEMENT ksiegarnia (ksiazka+)> +<!ELEMENT ksiazka (tytul,cena)> +<!ATTLIST ksiazka kategoria CDATA "Literatura"> +<!ELEMENT tytul (#PCDATA)> +<!ELEMENT cena (#PCDATA)> +]> + +<ksiegarnia> + <ksiazka kategoria="GOTOWANIE"> + <tytul >Everyday Italian</tytul> + <cena>30.00</cena> + </ksiazka> +</ksiegarnia> +``` diff --git a/powershell.html.markdown b/powershell.html.markdown index 4bc1ab39..fc944b85 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -18,6 +18,7 @@ rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) If you are uncertain about your environment: + ``` Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned @@ -33,6 +34,7 @@ $PSVersionTable ``` Getting help: + ``` # Find commands Get-Command about_* # alias: gcm @@ -49,6 +51,7 @@ Update-Help # Run as admin ``` The tutorial starts here: + ``` # As you already figured, comments start with # @@ -244,10 +247,12 @@ function New-Website() { [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') # Note that .NET functions MUST be called with parentheses -# while PS functions CANNOT be called with parentheses +# while PS functions CANNOT be called with parentheses. +# If you do call a cmdlet/PS function with parentheses, +# it is the same as passing a single parameter list $writer = New-Object System.IO.StreamWriter($path, $true) $writer.Write([Environment]::NewLine) -$write.Dispose() +$writer.Dispose() ### IO # Reading a value from input: @@ -265,12 +270,14 @@ Get-Command ConvertTo-*,ConvertFrom-* # Refresh your PATH $env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") + # Find Python in path $env:PATH.Split(";") | Where-Object { $_ -like "*python*"} # Change working directory without having to remember previous path Push-Location c:\temp # change working directory to c:\temp Pop-Location # change back to previous working directory +# Aliases are: pushd and popd # Unblock a directory after download Get-ChildItem -Recurse | Unblock-File @@ -292,6 +299,7 @@ $Shortcut.Save() Configuring your shell + ``` # $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` # All code there will be executed when the PS session starts @@ -304,6 +312,7 @@ if (-not (Test-Path $Profile)) { ``` Interesting Projects + * [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials * [PSGet](https://github.com/psget/psget) NuGet for PowerShell * [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!) @@ -314,6 +323,7 @@ Interesting Projects * [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead) Not covered + * WMI: Windows Management Intrumentation (Get-CimInstance) * Multitasking: Start-Job -scriptBlock {...}, * Code Signing diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/bf.html.markdown index 9e4b458d..d6d7c6e9 100644 --- a/pt-br/brainfuck-pt.html.markdown +++ b/pt-br/bf.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 6424214e..59c6890e 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -519,13 +519,13 @@ if (Object.create === undefined){ // Não o sobrescreve se já existir ## Leitura Adicional O [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma +Network](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript) dispõe de uma excelente documentação sobre Javascript e seu uso nos browsers. E mais, é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando os outros compartilhando do seu conhecimento. [Uma re-introdução do JavaScript pela MDN] -(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala somente sobre a linguagem JavaScript em si; se você quiser aprender mais sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre @@ -542,5 +542,5 @@ profundo de todas as partes do JavaScript. / livro de referência. Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está -nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +nesse site e do [Tutorial de JS](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) da Mozilla Developer Network. diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 89a051d4..668cd25f 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -4,6 +4,7 @@ lang: pt-br filename: learnruby-pt.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] + - ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"] translators: - ["Katyanna Moura", "https://twitter.com/amelie_kn"] --- @@ -161,9 +162,6 @@ hash['numero'] #=> 5 hash['nada aqui'] #=> nil # Interar sobre hashes com o método #each: -hash.each do |k, v| - puts "#{k} is #{v}" -end hash.each do |k, v| puts "#{k} é #{v}" @@ -385,3 +383,11 @@ Humano.bar # 0 Doutor.bar # nil ``` + +## Mais sobre Ruby + +- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem. +- [Ruby a partir de outras linguagens](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide* diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/bf.html.markdown index da4c787f..da4c787f 100644 --- a/pt-pt/brainfuck-pt.html.markdown +++ b/pt-pt/bf.html.markdown diff --git a/python.html.markdown b/python.html.markdown index 13cb25e3..2e7fd8be 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -726,6 +726,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) * [Fullstack Python](https://www.fullstackpython.com/) ### Dead Tree diff --git a/python3.html.markdown b/python3.html.markdown index 8cc03320..d88ccec1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -97,13 +97,13 @@ False or True # => True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variables refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to b is a # => True, a and b refer to the same object b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] b is a # => False, a and b do not refer to the same object b == a # => True, a's and b's objects are equal @@ -174,6 +174,10 @@ some_var # => 5 # See Control Flow to learn more about exception handling. some_unknown_var # Raises a NameError +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + # Lists store sequences li = [] # You can start with a prefilled list @@ -780,6 +784,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) * [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) * [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) ### Dead Tree diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 78b62e33..f8d83b98 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -9,6 +9,8 @@ This is a tutorial on how to do some typical statistical programming tasks using ```python + + # 0. Getting set up ==== """ Get set up with IPython and pip install the following: numpy, scipy, pandas, @@ -25,17 +27,17 @@ This is a tutorial on how to do some typical statistical programming tasks using already using Python, there's a benefit to sticking with one language. """ -import requests # for HTTP requests (web scraping, APIs) +import requests # for HTTP requests (web scraping, APIs) import os # web scraping r = requests.get("https://github.com/adambard/learnxinyminutes-docs") -r.status_code # if 200, request was successful -r.text # raw page source -print(r.text) # prettily formatted +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted # save the page source in a file: -os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html","wb") +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html", "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -44,7 +46,7 @@ fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" fn = "pets.csv" r = requests.get(fp + fn) print(r.text) -f = open(fn,"wb") +f = open(fn, "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -58,7 +60,9 @@ f.close() you've used R, you will be familiar with the idea of the "data.frame" already. """ -import pandas as pd, numpy as np, scipy as sp +import pandas as pd +import numpy as np +import scipy as sp pets = pd.read_csv(fn) pets # name age weight species @@ -74,20 +78,20 @@ pets pets.age pets["age"] -pets.head(2) # prints first 2 rows -pets.tail(1) # prints last row +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row -pets.name[1] # 'vesuvius' -pets.species[0] # 'cat' -pets["weight"][2] # 34 +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 # in R, you would expect to get 3 rows doing this, but here you get 2: pets.age[0:2] # 0 3 # 1 6 -sum(pets.age)*2 # 28 -max(pets.weight) - min(pets.weight) # 20 +sum(pets.age) * 2 # 28 +max(pets.weight) - min(pets.weight) # 20 """ If you are doing some serious linear algebra and number-crunching, you may just want arrays, not DataFrames. DataFrames are ideal for combining columns @@ -96,7 +100,8 @@ max(pets.weight) - min(pets.weight) # 20 # 3. Charts ==== -import matplotlib as mpl, matplotlib.pyplot as plt +import matplotlib as mpl +import matplotlib.pyplot as plt %matplotlib inline # To do data vizualization in Python, use matplotlib @@ -105,13 +110,17 @@ plt.hist(pets.age); plt.boxplot(pets.weight); -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); # seaborn sits atop matplotlib and makes plots prettier import seaborn as sns -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); # there are also some seaborn-specific plotting functions # notice how seaborn automatically labels the x-axis on this barplot @@ -141,7 +150,7 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" r = requests.get(url) fp = "hre.csv" -f = open(fp,"wb") +f = open(fp, "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -149,33 +158,33 @@ hre = pd.read_csv(fp) hre.head() """ - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN """ # clean the Birth and Death columns -import re # module for regular expressions +import re # module for regular expressions -rx = re.compile(r'\d+$') # match trailing digits +rx = re.compile(r'\d+$') # match trailing digits """ This function applies the regular expression to an input column (here Birth, Death), flattens the resulting list, converts it to a Series object, and @@ -185,8 +194,9 @@ rx = re.compile(r'\d+$') # match trailing digits - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html """ + def extractYear(v): - return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int)) hre["BirthY"] = extractYear(hre.Birth) hre["DeathY"] = extractYear(hre.Death) @@ -199,17 +209,17 @@ sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); # use scipy to run a linear regression from scipy import stats -(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge) # code source: http://wiki.scipy.org/Cookbook/LinearRegression # check the slope -slope # 0.0057672618839073328 +slope # 0.0057672618839073328 # check the R^2 value: -rval**2 # 0.020363950027333586 +rval**2 # 0.020363950027333586 # check the p-value -pval # 0.34971812581498452 +pval # 0.34971812581498452 # use seaborn to make a scatterplot and plot the linear regression trend line sns.lmplot("BirthY", "EstAge", data=hre); @@ -223,6 +233,7 @@ sns.lmplot("BirthY", "EstAge", data=hre); To see a version of the Holy Roman Emperors analysis using R, see - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R """ + ``` If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. diff --git a/ro-ro/bf-ro.html.markdown b/ro-ro/bf-ro.html.markdown new file mode 100644 index 00000000..61b555ed --- /dev/null +++ b/ro-ro/bf-ro.html.markdown @@ -0,0 +1,90 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +lang: ro-ro +--- + +Brainfuck (un nume propriu care nu primește majusculă inițială decât la începutul +propoziției) este un limbaj de programare Turing-comple extrem de minimalist cu +doar 8 instrucțiuni. + +Puteți încerca brainfuck în navigatorul dumneavoastră cu [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Orice caracter in afara de "><+-.,[]" (fara ghilimele) este ignorat. + +Brainfuck se reprezinta ca un vector de 30 000 de celule initializate cu zero +si un pointer de date care trimite spre celula curenta. + +Exista opt comenzi: ++ : Incrementeaza valoarea celulei curente cu 1. +- : Decrementeaza valoarea celulei curente cu 1. +> : Muta pointerul de date la urmatoarea celula (o celula la dreapta). +< : Muta pointerul de date la celula precedenta (o celula la stanga). +. : Afiseaza valoarea caracterului ASCII din celul caurenta (ex. 65 = 'A'). +, : Citeste un singur caracter si plaseaza valoarea lui in celula curenta. +[ : Daca valoarea in celula curenta este zero, sare la urmatorul caracter ] . + Altfel, merge la urmatoarea instructiune. +] : Daca valoarea in celula curenta este zero, sare la urmatoarea + instructiune. + Altfel, se intoarce la instructiunea de dupa caracterul [ precedent . + +[ and ] formeaza un ciclu. Evident, trebuie ca parantezarea sa fie corecta. + +Sa privim cateva programe brainfuck simple. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Acest program afiseaza litera 'A'. Mai intai, incrementeaza celula #1 pana +la valoarea 6. Celula #1 va fi folosita pentru ciclare. Apoi, intra in ciclu +([) si muta pointerul la celula #2. Incrementeaza celula #2 de 10 ori, +muta pointerul la celula #1 si decrementeaza celula #1. Acest ciclu parcurge +6 iteratii (este nevoie de 6 decrementari pentru ca celula #1 sa ajunga la 0), +iar dupa aceea se trece la caracterul ] corespunzator si se continua executia. + +In acest moment, ne aflam in celula #1, care are valoarea 0, in timp ce celula +#2 are valoarea 60. Ne mutam pe celula #2, incrementam de 5 ori, pentru a +obtine valoarea 65, si apoi afisam valoarea celulei #2. 65 este codul ASCII +pentru 'A', deci se afiseaza 'A' in terminal. + +, [ > + < - ] > . + +Acest program citeste un caracter de la intrarea utilizator si copiaza caracterul +in celula #1. Apoi incepem un ciclu. Se muta pointerul in celula #2, se +incremneteaza valoarea de la celula #2, se muta inapoi la celula #1, se +decrementeaza valoarea de la celula #1. Aceasta continua pana cand celula #1 este +0 iar celula #2 retine vechea valoare a celulei #1. Deoarece ne aflam in celula +#1 la sfarsitul ciclului, ne mutam pe celula #2 si afisam simbolul corespunzator +in ASCII. + +Aveti in vedere ca spatiile sunt doar pentru usurinta citirii. La fel de bine +programul ar fi putut fi scris astfel: + +,[>+<-]>. + +Incercati sa va dati seama ce face acest program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Acest program citeste doua numere ca intrare si le inmulteste. + +Pe scurt, programul citeste doua date de intrare, apoi incepe ciclul +mare, a carui conditie se afla in celula #1; apoi se muta la celula #2 +si incepe un ciclu imbricat a carui conditie de reluare se afla in +celula #2, si care incrementeaza celula #3. Totusi aici intervine o +problema: La sfarsitul ciclului imbricat, celula #2 este zero. In +acest caz, celula ciclul imbricat nu va mai functiona data viitoare. +Pentru a rezolva aceasta problema, incrementam celula si #4, si +recopiem celula #4 in celula #2. In final, celula #3 este rezultatul. + +``` + +Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru +amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți +scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul +este destul de ușor de implementat, dar dacă sunteți masochist, încercați +să implementați un interpretor de brainfuck… în brainfuck.
\ No newline at end of file diff --git a/ro-ro/latex.html.markdown b/ro-ro/latex.html.markdown new file mode 100644 index 00000000..35651e28 --- /dev/null +++ b/ro-ro/latex.html.markdown @@ -0,0 +1,258 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] + - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: brainfuck-ro.clj +filename: learn-latex-ro.tex +lang: ro-ro +--- + +```tex +% Toate comentariile încep cu % +% Nu există comentarii multi-linie + +% LaTeX NU este un program software de procesare text de tipul +% "What You See Is What You Get" +% precum MS Word, sau OpenOffice Writer + +% Toate comenzile LaTeX încep cu backslash. (\) + +% Documentele LaTeX încep cu o linie care definește tipul documentului +% care urmează a fi compilat. Alte tipuri de documente sunt book (carte), +% presentation (prezentare), etc. Opțiunile pentru document apar +% între paranteze drepte. În acest caz, specificăm că vrem să folosim +% un corp de text (font) de 12 puncte. +\documentclass[12pt]{article} + +% Mai apoi definim pachetele pe care documentul le folosește. +% Dacă vreți să includeți grafice, text colorat sau +% cod sursă din alt fișier în documentul dumneavoastră, +% trebuie să îmbogățiți capabilitățile LaTeX. Aceasta se realizează +% adăugând pachete. Voi include pachetele float și caption pentru +% imagini. +\usepackage{caption} +\usepackage{float} +% această comandă este necesară atunci când vreți să scrieți codul +% sursă folosind diacrtice! (cum e cazul aici, unde translatorul +% a vrut să scrie neapărat folosind diacriticele românești) +\usepackage[utf8]{inputenc} + +% De asemenea, putem defini și alte proprietăți pentru documente. +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu \\ Traducere de Petru Dimitriu} +\date{\today} +\title{Învățați LaTeX în Y minute!} + +% Suntem gata să începem documentul. +% Tot ce se află înaintea acestei linii se numește "Preambul" +\begin{document} +% dacă am setat autorul, data și titlul, putem cere LaTeX să +% creeze o pagină de titlu +\maketitle + +% Cele mai multe documente științifice au un abstract; puteți folosi comenzile +% predefinite pentru acesta. Acesta ar trebui să apară, așa cum ar fi logic, +% după titlu, dar înainte de secțiunile principale ale corpului. +% Această comandă este disponibilă în clasele de document article și report. +\begin{abstract} + Documentațue LaTeX scrisă în LaTeX. O idee nicidecum nouă și nicidecum a mea! +\end{abstract} + +% Comenzile pentru secțiuni sunt intuitive. +% Toate titlurile secțiunilor sunt adăugate automat la tabla de materii (cuprins). +\section{Introducere} +Salut, mă numesc Petru. Astăzi vom învăța împreună LaTeX! + +\section{Altă secțiune} +Acesta este textul pentru altă secțiune. Vom face o subsecțiune. + +\subsection{Aceasta este o subsecțiune} % Subsecțiunile sunt și ele intuitive. +Și încă una. + +\subsubsection{Pitagora} +Mult mai bine. +\label{subsec:pitagora} + +% Folosind asteriscul putem suprima numărătoarea automată a LaTeX. +% Aceasta funcționează și pentru alte comenzi LaTeX. +\section*{Secțiune fără numerotare} +Totuși nu toate secțiunile trebuie să fie nenumerotate! + +\section{Note despre text} +În general LaTeX se pricepe să pună textul unde trebuie. Dacă o linie are \\ +nevoie \\ să \\ fie \\ întreruptă, puteți adăuga două caractere backslash +la codul sursă. + +\section{Liste} +Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la +cumpărături așa că fac o listă: +\begin{enumerate} % Aceasta creează un mediu "enumerate" + % \item spune mediului "enumerate" să incrementeze + \item salată + \item 27 pepeni + \item un singur iepuroi + % putem suprascrie numărul elementului folosind [] + \item[câte?] conserve de ton + + Nu este un element din listă, dar încă face parte din "enumerate". + +\end{enumerate} % All environments must have an end. + +\section{Matematică} + +Una dintre principalele întrebuințări ale LaTeX este realizarea +articolelor academice sau a foilor tehnice, de obicei aflate în +universul matematicii și științelor exacte. Astfel, trebuie să putem +adăuga simboluri speciale în documentului nostru! \\ + +Matematica are multe simboluri, mult mai multe decât se găsesc +pe o tastatură - printre ele, simboluri pentru mulțimi și relații, +săgeți, operatori și litere grecești.\\ + +Mulțimile și relațiile sunt de bază în lucrările științifce matematice. +Iată cum se scrie: toți y aparținând lui X.\\ +$\forall$ x $\in$ X. \\ + +% Observați cum am avut nevoie să pun semnul $ înainte și după simboluri. +% Aceasta pentru că atunci când scriem, suntem în modul text (text-mode). +% Totuși simbolurile matematice există numai în modul matematic (math-mode). +% Când ne aflăm în text-mode, putem scrie texte în math-mode punând $ înainte +% și după simboluri. La fel și viceversa. Și variabilele pot fi redate +% în math-mode. Putem intra în math-mode și scriind \[\]. + +\[a^2 + b^2 = c^2 \] + +Litera mea grecească este $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și +$\sigma$. Nu există nicio literă grecească necunoscută pentru LaTeX! + +Operatorii sunt exențiali într-un document matematic! +funcțiile trigonometrice ($\sin$, $\cos$, $\tan$), +logaritmii și exponențialele ($\log$, $\exp$), +limitele ($\lim$), etc. +au comenzi definite în LaTeX pentru fiecare. +Să vedem cum scriem o ecuație: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fracțiile (numărător - numitor) pot fi scrise astfel: +% 10 / 7 +$^{10}/_{7}$ \\ + +% Fracții relativ complexe pot fi scrie ca +% \frac{numărător}{numitor} +$\frac{n!}{k!(n - k)!}$ \\ + +Putem insera ecuații și într-un "mediu pentru ecuații". + +% Afișează text matematic într-un mediu pentru ecuații. +\begin{equation} % intră în math-mode + c^2 = a^2 + b^2. + \label{eq:pitagora} % pentru referențiere +\end{equation} +% toate instrucțiunile cu \begin trebuie să fie cuplate cu o instrucțiune cu \end + +Putem referenția noua nosatră ecuație! +~\ref{eq:pitagora} este cunoscută și ca Teorema lui Pitagora, despre care vorbim și la Sec.~\ref{subsec:pitagora}. Multe lucruri prot fi etichetate: +figuri, ecuații, secțiuni, etc. + +Sumele discrete și integralele se scriu cu comenzile sum și int. + +% Unele compilatoare LaTeX nu acceptă să există linii goala +% într-un mediu pentru ecuații. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figuri} + +Să inserăm o figură. Așezarea figurilor poate fi ușor dificilă. +Eu trebuie să mă uit peste opțiunile de așezare de fiecare dată. + +\begin{figure}[H] % H denumește opțiunle de așezare + \centering % centrează figura pe pagină + % Inserează o figură scalată la 0.8 din lățimea paginii. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Comentat pentru a nu împiedica fișierul să compileze. + \caption{Triunghi dreptunghic cu laturile $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabel} +Putem insera tabele la fel cum inserăm figuri. + +\begin{table}[H] + \caption{Descriere pentru tabel} + % argumentele {} controlează cum vor fi afișate coloanele + \begin{tabular}{c|cc} + Număr & Nume & Prenume \\ % Numele coloanelor sunt separate prin $ + \hline % a linie orizonală + 1 & Popescu & Ion \\ + 2 & Sima & Felix + \end{tabular} +\end{table} + +% \section{Hyperlinkuri} % În curând + +\section{Cum facem ca LaTeX să nu compileze ceva (de exemplu cod sursă)} +Să zicem că vrem să includem niște cod în documentul nostru LaTeX. +Vom avea nevoie ca LaTeX să nu încerce să interpreteze acel cod, +ci doar să îl redea în document. Vom face asta cu un mediu verbatim. + +% Există și alte pachete (i.e. minty, lstlisting, etc.) +% dar verbatim este pachetul cel mai simplu. +\begin{verbatim} + print("Salut lume!") + a%b; % hei! putem folosi % în verbatim + random = 4; +\end{verbatim} + +\section{Compilarea} +Acum vă întrebați cum se compilează acest document minunat și să vă +minunați de rezultatul, un PDF LaTeX. (da, documentul acesta chiar +compilează). \\ +Realizarea documentului cu LaTeX va parcurge următorii pași: + \begin{enumerate} + \item Se scrie documentul în text simplu. (codul sursă) + \item Se compilează documentul pentru a produce un PDF. + Compilarea arată cam așa în Linux:\\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Anumiți editor pentru LaTeX combină pașii 1 și 2 în același produs software. +Așadar, dacă vreți să vedeți realizați pasul 1 dar nu și pasul 2, el se poate +realiza "în spate". + +Scrieți toate informațiile de formatare în pasul 1. Compilarea din pasul 2 +se ocupă de producerea documentului în formatul definit în pasul 1. + +\section{Final} + +Asta e tot pentru moment! + +% De multe ori veți vrea să aveți o secțiune cu bibliografie în document. +% Cea mai ușoară modalitate este folosind mediul thebibliography. +\begin{thebibliography}{1} + % Similar celorlalte liste, comanda \bibitem e folosită pentru a înșirui + % elemente; fiecare element poate fi citat în interiorul textului + \bibitem{latexwiki} Uimitoarea carte wiki LaTeX: {\em https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} Un tutorial propriu-zis: {\em http://www.latex-tutorial.com} +\end{thebibliography} + +% încheie documentul +\end{document} +``` + +## Mai multe despre LaTeX + +* Uimitoarea carte wiki LaTeX: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* Un tutorial propriu-zis: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/bf.html.markdown index fcee185f..20f0fa56 100644 --- a/ru-ru/brainfuck-ru.html.markdown +++ b/ru-ru/bf.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 8f4233fd..162ec4c8 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -7,11 +7,12 @@ contributors: - ["Andre Polykanine", "http://oire.me/"] lang: ru-ru --- + D - современный компилируемый язык общего назначения с Си-подобным синтаксисом, который сочетает удобство, продуманный дизайн и высокую производительность. D - это С++, сделанный правильно. -```d +```c // Welcome to D! Это однострочный комментарий /* многострочный diff --git a/ruby.html.markdown b/ruby.html.markdown index b7f8b4a1..adf5ce81 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -285,7 +285,7 @@ hash.each do |key, value| puts "#{key} is #{value}" end -# If you still need and index you can use "each_with_index" and define an index +# If you still need an index you can use "each_with_index" and define an index # variable array.each_with_index do |element, index| puts "#{element} is number #{index} in the array" @@ -411,6 +411,28 @@ def guests(*array) array.each { |guest| puts guest } end +# If a method returns an array, you can use destructuring assignment +def foods + ['pancake', 'sandwich', 'quesadilla'] +end +breakfast, lunch, dinner = foods +breakfast #=> 'pancake' +dinner #=> 'quesadilla' + +# By convention, all methods that return booleans end with a question mark +5.even? # false +5.odd? # true + +# And if a method ends with an exclamation mark, it does something destructive +# like mutate the receiver. Many methods have a ! version to make a change, and +# a non-! version to just return a new changed version +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +company_name.upcase! # we're mutating company_name this time! +company_name #=> "DUNDER MIFFLIN" + + # Define a class with the class keyword class Human @@ -594,3 +616,4 @@ Something.new.qux # => 'qux' - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) - [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser. diff --git a/scala.html.markdown b/scala.html.markdown index a82983a5..745605ed 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -48,7 +48,7 @@ println(10) // Printing, without forcing a new line on next print print("Hello world") print(10) -// Hello world!10 +// Hello world10 // Declaring values is done using either var or val. // val declarations are immutable, whereas vars are mutable. Immutability is @@ -237,7 +237,7 @@ r foreach println (5 to 1 by -1) foreach (println) -// A while loops +// A while loop var i = 0 while (i < 10) { println("i " + i); i += 1 } @@ -245,17 +245,18 @@ while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very - // fast, faster that Java loops, but using the combinators and - // comprehensions above is easier to understand and parallelize + // fast, but using the combinators and comprehensions above is easier + // to understand and parallelize -// A do while loop +// A do-while loop i = 0 do { println("i is still less than 10") i += 1 } while (i < 10) -// Tail recursion is an idiomatic way of doing recurring things in Scala. +// Recursion is the idiomatic way of repeating an action in Scala (as in most +// other functional languages). // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. def showNumbersInRange(a: Int, b: Int): Unit = { @@ -273,7 +274,7 @@ val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") +if (x == 11) println("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" @@ -621,6 +622,9 @@ import scala.collection.immutable.{List => ImmutableList} // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} +// Java classes can also be imported. Scala syntax can be used +import java.swing.{JFrame, JWindow} + // Your programs entry point is defined in an scala file using an object, with a // single method, main: object Application { diff --git a/solidity.html.markdown b/solidity.html.markdown new file mode 100644 index 00000000..a511bbb3 --- /dev/null +++ b/solidity.html.markdown @@ -0,0 +1,795 @@ +--- +language: Solidity +filename: learnSolidity.sol +contributors: + - ["Nemil Dalal", "https://www.nemil.com"] + - ["Joseph Chow", ""] +--- + +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a +blockchain-based virtual machine that allows the creation and +execution of smart contracts, without needing centralized or trusted parties. + +Solidity is a statically typed, contract programming language that has +similarities to Javascript and C. Like objects in OOP, each contract contains +state variables, functions, and common data types. Contract-specific features +include modifier (guard) clauses, event notifiers for listeners, and custom +global variables. + +Some Ethereum contract examples include crowdfunding, voting, and blind auctions. + +As Solidity and Ethereum are under active development, experimental or beta +features are explicitly marked, and subject to change. Pull requests welcome. + +```javascript +// First, a simple Bank contract +// Allows deposits, withdrawals, and balance checks + +// simple_bank.sol (note .sol extension) +/* **** START EXAMPLE **** */ + +// Start with Natspec comment (the three slashes) +// used for documentation - and as descriptive data for UI elements/actions + +/// @title SimpleBank +/// @author nemild + +/* 'contract' has similarities to 'class' in other languages (class variables, +inheritance, etc.) */ +contract SimpleBank { // CamelCase + // Declare state variables outside function, persist through life of contract + + // dictionary that maps addresses to balances + mapping (address => uint) private balances; + + // "private" means that other contracts can't directly query balances + // but data is still viewable to other parties on blockchain + + address public owner; + // 'public' makes externally readable (not writeable) by users or contracts + + // Events - publicize actions to external listeners + event DepositMade(address accountAddress, uint amount); + + // Constructor, can receive one or many variables here; only one allowed + function AcmeBank() { + // msg provides details about the message that's sent to the contract + // msg.sender is contract caller (address of contract creator) + owner = msg.sender; + } + + /// @notice Deposit ether into bank + /// @return The balance of the user after the deposit is made + function deposit() public returns (uint) { + balances[msg.sender] += msg.value; + // no "this." or "self." required with state variable + // all values set to data type's initial value by default + + DepositMade(msg.sender, msg.value); // fire event + + return balances[msg.sender]; + } + + /// @notice Withdraw ether from bank + /// @dev This does not return any excess ether sent to it + /// @param withdrawAmount amount you want to withdraw + /// @return The balance remaining for the user + function withdraw(uint withdrawAmount) public returns (uint remainingBal) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; + + if (!msg.sender.send(withdrawAmount)) { + // to be safe, may be sending to contract that + // has overridden 'send' which may then fail + balances[msg.sender] += withdrawAmount; + } + } + + return balances[msg.sender]; + } + + /// @notice Get balance + /// @return The balance of the user + // 'constant' prevents function from editing state variables; + // allows function to run locally/off blockchain + function balance() constant returns (uint) { + return balances[msg.sender]; + } + + // Fallback function - Called if other functions don't match call or + // sent ether without data + // Typically, called when invalid data is sent + // Added so ether sent to this contract is reverted if the contract fails + // otherwise, the sender's money is transferred to contract + function () { + throw; // throw reverts state to before call + } +} +// ** END EXAMPLE ** + + +// Now, the basics of Solidity + +// 1. DATA TYPES AND ASSOCIATED METHODS +// uint used for currency amount (there are no doubles +// or floats) and for dates (in unix time) +uint x; + +// int of 256 bits, cannot be changed after instantiation +int constant a = 8; +int256 constant a = 8; // same effect as line above, here the 256 is explicit +uint constant VERSION_ID = 0x123A1; // A hex constant +// with 'constant', compiler replaces each occurrence with actual value + + +// For int and uint, can explicitly set space in steps of 8 up to 256 +// e.g., int8, int16, int24 +uint8 b; +int64 c; +uint248 e; + +// Be careful that you don't overflow, and protect against attacks that do + +// No random functions built in, use other contracts for randomness + +// Type casting +int x = int(b); + +bool b = true; // or do 'var b = true;' for inferred typing + +// Addresses - holds 20 byte/160 bit Ethereum addresses +// No arithmetic allowed +address public owner; + +// Types of accounts: +// Contract account: address set on create (func of creator address, num transactions sent) +// External Account: (person/external entity): address created from public key + +// Add 'public' field to indicate publicly/externally accessible +// a getter is automatically created, but NOT a setter + +// All addresses can be sent ether +owner.send(SOME_BALANCE); // returns false on failure +if (owner.send) {} // typically wrap in 'if', as contract addresses have +// functions have executed on send and can fail + +// can override send by defining your own + +// Can check balance +owner.balance; // the balance of the owner (user or contract) + + +// Bytes available from 1 to 32 +byte a; // byte is same as bytes1 +bytes2 b; +bytes32 c; + +// Dynamically sized bytes +bytes m; // A special array, same as byte[] array (but packed tightly) +// More expensive than byte1-byte32, so use those when possible + +// same as bytes, but does not allow length or index access (for now) +string n = "hello"; // stored in UTF8, note double quotes, not single +// string utility functions to be added in future +// prefer bytes32/bytes, as UTF8 uses more storage + +// Type inferrence +// var does inferred typing based on first assignment, +// can't be used in functions parameters +var a = true; +// use carefully, inference may provide wrong type +// e.g., an int8, when a counter needs to be int16 + +// var can be used to assign function to variable +function a(uint x) returns (uint) { + return x * 2; +} +var f = a; +f(22); // call + +// by default, all values are set to 0 on instantiation + +// Delete can be called on most types +// (does NOT destroy value, but sets value to 0, the initial value) +uint x = 5; + + +// Destructuring/Tuples +(x, y) = (2, 7); // assign/swap multiple value + + +// 2. DATA STRUCTURES +// Arrays +bytes32[5] nicknames; // static array +bytes32[] names; // dynamic array +uint newLength = names.push("John"); // adding returns new length of the array +// Length +names.length; // get length +names.length = 1; // lengths can be set (for dynamic arrays in storage only) + +// multidimensional array +uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages) + +// Dictionaries (any type to any other type) +mapping (string => uint) public balances; +balances["charles"] = 1; +console.log(balances["ada"]); // is 0, all non-set key values return zeroes +// 'public' allows following from another contract +contractName.balances("claude"); // returns 1 +// 'public' created a getter (but not setter) like the following: +function balances(address _account) returns (uint balance) { + return balances[_account]; +} + +// Nested mappings +mapping (address => mapping (address => uint)) public custodians; + +// To delete +delete balances["John"]; +delete balances; // sets all elements to 0 + +// Unlike other languages, CANNOT iterate through all elements in +// mapping, without knowing source keys - can build data structure +// on top to do this + +// Structs and enums +struct Bank { + address owner; + uint balance; +} +Bank b = Bank({ + owner: msg.sender, + balance: 5 +}); +// or +Bank c = Bank(msg.sender, 5); + +c.amount = 5; // set to new value +delete b; +// sets to initial value, set all variables in struct to 0, except mappings + +// Enums +enum State { Created, Locked, Inactive }; // often used for state machine +State public state; // Declare variable from enum +state = State.Created; +// enums can be explicitly converted to ints +uint createdState = uint(State.Created); // 0 + +// Data locations: Memory vs. storage vs. stack - all complex types (arrays, +// structs) have a data location +// 'memory' does not persist, 'storage' does +// Default is 'storage' for local and state variables; 'memory' for func params +// stack holds small local variables + +// for most types, can explicitly set which data location to use + + +// 3. Simple operators +// Comparisons, bit operators and arithmetic operators are provided +// exponentiation: ** +// exclusive or: ^ +// bitwise negation: ~ + + +// 4. Global Variables of note +// ** this ** +this; // address of contract +// often used at end of contract life to send remaining balance to party +this.balance; +this.someFunction(); // calls func externally via call, not via internal jump + +// ** msg - Current message received by the contract ** ** +msg.sender; // address of sender +msg.value; // amount of ether provided to this contract in wei +msg.data; // bytes, complete call data +msg.gas; // remaining gas + +// ** tx - This transaction ** +tx.origin; // address of sender of the transaction +tx.gasprice; // gas price of the transaction + +// ** block - Information about current block ** +now; // current time (approximately), alias for block.timestamp (uses Unix time) +block.number; // current block number +block.difficulty; // current block difficulty +block.blockhash(1); // returns bytes32, only works for most recent 256 blocks +block.gasLimit(); + +// ** storage - Persistent storage hash ** +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + + +// 4. FUNCTIONS AND MORE +// A. Functions +// Simple function +function increment(uint x) returns (uint) { + x += 1; + return x; +} + +// Functions can return many arguments, and by specifying returned arguments +// name don't need to explicitly return +function increment(uint x, uint y) returns (uint x, uint y) { + x += 1; + y += 1; +} +// Call previous functon +uint (a,b) = increment(1,1); + +// 'constant' indicates that function does not/cannot change persistent vars +// Constant function execute locally, not on blockchain +uint y; + +function increment(uint x) constant returns (uint x) { + x += 1; + y += 1; // this line would fail + // y is a state variable, and can't be changed in a constant function +} + +// 'Function Visibility specifiers' +// These can be placed where 'constant' is, including: +// public - visible externally and internally (default) +// external +// private - only visible in the current contract +// internal - only visible in current contract, and those deriving from it + +// Functions hoisted - and can assign a function to a variable +function a() { + var z = b; + b(); +} + +function b() { + +} + + +// Prefer loops to recursion (max call stack depth is 1024) + +// B. Events +// Events are notify external parties; easy to search and +// access events from outside blockchain (with lightweight clients) +// typically declare after contract parameters + +// Declare +event Sent(address from, address to, uint amount); // note capital first letter + +// Call +Sent(from, to, amount); + +// For an external party (a contract or external entity), to watch: +Coin.Sent().watch({}, '', function(error, result) { + if (!error) { + console.log("Coin transfer: " + result.args.amount + + " coins were sent from " + result.args.from + + " to " + result.args.to + "."); + console.log("Balances now:\n" + + "Sender: " + Coin.balances.call(result.args.from) + + "Receiver: " + Coin.balances.call(result.args.to)); + } +} +// Common paradigm for one contract to depend on another (e.g., a +// contract that depends on current exchange rate provided by another) + +// C. Modifiers +// Modifiers validate inputs to functions such as minimal balance or user auth; +// similar to guard clause in other languages + +// '_' (underscore) often included as last line in body, and indicates +// function being called should be placed there +modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } +modifier onlyOwner { if (msg.sender == owner) _ } +// commonly used with state machines +modifier onlyIfState (State currState) { if (currState != State.A) _ } + +// Append right after function declaration +function changeOwner(newOwner) +onlyAfter(someTime) +onlyOwner() +onlyIfState(State.A) +{ + owner = newOwner; +} + +// underscore can be included before end of body, +// but explicitly returning will skip, so use carefully +modifier checkValue(uint amount) { + _ + if (msg.value > amount) { + msg.sender.send(amount - msg.value); + } +} + + +// 6. BRANCHING AND LOOPS + +// All basic logic blocks work - including if/else, for, while, break, continue +// return - but no switch + +// Syntax same as javascript, but no type conversion from non-boolean +// to boolean (comparison operators must be used to get the boolean val) + + +// 7. OBJECTS/CONTRACTS + +// A. Calling external contract +contract infoFeed { + function info() returns (uint ret) { return 42; } +} + +contract Consumer { + InfoFeed feed; // points to contract on blockchain + + // Set feed to existing contract instance + function setFeed(address addr) { + // automatically cast, be careful; constructor is not called + feed = InfoFeed(addr); + } + + // Set feed to new instance of contract + function createNewFeed() { + feed = new InfoFeed(); // new instance created; constructor called + } + + function callFeed() { + // final parentheses call contract, can optionally add + // custom ether value or gas + feed.info.value(10).gas(800)(); + } +} + +// B. Inheritance + +// Order matters, last inherited contract (i.e., 'def') can override parts of +// previously inherited contracts +contract MyContract is abc, def("a custom argument to def") { + +// Override function + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function from def + super.z(); // call immediate parent overriden function + } + } +} + +// abstract function +function someAbstractFunction(uint x); +// cannot be compiled, so used in base/abstract contracts +// that are then implemented + +// C. Import + +import "filename"; +import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; + +// Importing under active development +// Cannot currently be done at command line + + +// 8. OTHER KEYWORDS + +// A. Throwing +// Throwing +throw; // reverts unused money to sender, state is reverted +// Can't currently catch + +// Common design pattern is: +if (!addr.send(123)) { + throw; +} + +// B. Selfdestruct +// selfdestruct current contract, sending funds to address (often creator) +selfdestruct(SOME_ADDRESS); + +// removes storage/code from current/future blocks +// helps thin clients, but previous data persists in blockchain + +// Common pattern, lets owner end the contract and receive remaining funds +function remove() { + if(msg.sender == creator) { // Only let the contract creator do this + selfdestruct(creator); // Makes contract inactive, returns funds + } +} + +// May want to deactivate contract manually, rather than selfdestruct +// (ether sent to selfdestructed contract is lost) + + +// 9. CONTRACT DESIGN NOTES + +// A. Obfuscation +// All variables are publicly viewable on blockchain, so anything +// that is private needs to be obfuscated (e.g., hashed w/secret) + +// Steps: 1. Commit to something, 2. Reveal commitment +sha3("some_bid_amount", "some secret"); // commit + +// call contract's reveal function in the future +// showing bid plus secret that hashes to SHA3 +reveal(100, "mySecret"); + +// B. Storage optimization +// Writing to blockchain can be expensive, as data stored forever; encourages +// smart ways to use memory (eventually, compilation will be better, but for now +// benefits to planning data structures - and storing min amount in blockchain) + +// Cost can often be high for items like multidimensional arrays +// (cost is for storing data - not declaring unfilled variables) + +// C. Data access in blockchain +// Cannot restrict human or computer from reading contents of +// transaction or transaction's state + +// While 'private' prevents other *contracts* from reading data +// directly - any other party can still read data in blockchain + +// All data to start of time is stored in blockchain, so +// anyone can observe all previous data and changes + +// D. Cron Job +// Contracts must be manually called to handle time-based scheduling; can create external +// code to regularly ping, or provide incentives (ether) for others to + +// E. Observer Pattern +// An Observer Pattern lets you register as a subscriber and +// register a function which is called by the oracle (note, the oracle pays +// for this action to be run) +// Some similarities to subscription in Pub/sub + +// This is an abstract contract, both client and server classes import +// the client should implement +contract SomeOracleCallback { + function oracleCallback(int _value, uint _time, bytes32 info) external; +} + +contract SomeOracle { + SomeOracleCallback[] callbacks; // array of all subscribers + + // Register subscriber + function addSubscriber(SomeOracleCallback a) { + callbacks.push(a); + } + + function notify(value, time, info) private { + for(uint i = 0;i < callbacks.length; i++) { + // all called subscribers must implement the oracleCallback + callbacks[i].oracleCallback(value, time, info); + } + } + + function doSomething() public { + // Code to do something + + // Notify all subscribers + notify(_value, _time, _info); + } +} + +// Now, your client contract can addSubscriber by importing SomeOracleCallback +// and registering with Some Oracle + +// F. State machines +// see example below for State enum and inState modifier + + +// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** +// ** START EXAMPLE ** + +// CrowdFunder.sol + +/// @title CrowdFunder +/// @author nemild +contract CrowdFunder { + // Variables set on create by creator + address public creator; + address public fundRecipient; // creator may be different than recipient + uint public minimumToRaise; // required to tip, else everyone gets refund + string campaignUrl; + + // Data structures + enum State { + Fundraising, + ExpiredRefundPending, + Successful, + ExpiredRefundComplete + } + struct Contribution { + uint amount; + address contributor; + } + + // State variables + State public state = State.Fundraising; // initialize on create + uint public totalRaised; + uint public raiseBy; + Contribution[] contributions; + + event fundingReceived(address addr, uint amount, uint currentTotal); + event allRefundsSent(); + event winnerPaid(address winnerAddress); + + modifier inState(State _state) { + if (state != _state) throw; + _ + } + + modifier isCreator() { + if (msg.sender != creator) throw; + _ + } + + modifier atEndOfLifecycle() { + if(state != State.ExpiredRefundComplete && state != State.Successful) { + throw; + } + } + + function CrowdFunder( + uint timeInHoursForFundraising, + string _campaignUrl, + address _fundRecipient, + uint _minimumToRaise) + { + creator = msg.sender; + fundRecipient = _fundRecipient; + campaignUrl = _campaignUrl; + minimumToRaise = _minimumToRaise; + raiseBy = now + (timeInHoursForFundraising * 1 hours); + } + + function contribute() + public + inState(State.Fundraising) + { + contributions.push( + Contribution({ + amount: msg.value, + contributor: msg.sender + }) // use array, so can iterate + ); + totalRaised += msg.value; + + fundingReceived(msg.sender, msg.value, totalRaised); + + checkIfFundingCompleteOrExpired(); + } + + function checkIfFundingCompleteOrExpired() { + if (totalRaised > minimumToRaise) { + state = State.Successful; + payOut(); + + // could incentivize sender who initiated state change here + } else if ( now > raiseBy ) { + state = State.ExpiredRefundPending; + refundAll(); + } + } + + function payOut() + public + inState(State.Successful) + { + if(!fundRecipient.send(this.balance)) { + throw; + } + + winnerPaid(fundRecipient); + } + + function refundAll() + public + inState(State.ExpiredRefundPending) + { + uint length = contributions.length; + for (uint i = 0; i < length; i++) { + if(!contributions[i].contributor.send(contributions[i].amount)) { + throw; + } + } + + allRefundsSent(); + state = State.ExpiredRefundComplete; + } + + function removeContract() + public + isCreator() + atEndOfLifecycle() + { + selfdestruct(msg.sender); + } + + function () { throw; } +} +// ** END EXAMPLE ** + + +// 10. OTHER NATIVE FUNCTIONS + +// Currency units +// Currency is defined using wei, smallest unit of Ether +uint minAmount = 1 wei; +uint a = 1 finney; // 1 ether == 1000 finney +// Other units, see: http://ether.fund/tool/converter + +// Time units +1 == 1 second +1 minutes == 60 seconds + +// Can multiply a variable times unit, as units are not stored in a variable +uint x = 5; +(x * 1 days); // 5 days + +// Careful about leap seconds/years with equality statements for time +// (instead, prefer greater than/less than) + +// Cryptography +// All strings passed are concatenated before hash action +sha3("ab", "cd"); +ripemd160("abc"); +sha256("def"); + + +// 11. LOW LEVEL FUNCTIONS +// call - low level, not often used, does not provide type safety +successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); + +// callcode - Code at target address executed in *context* of calling contract +// provides library functionality +someContractAddress.callcode('function_name'); + + +// 12. STYLE NOTES +// Based on Python's PEP8 style guide + +// Quick summary: +// 4 spaces for indentation +// Two lines separate contract declarations (and other top level declarations) +// Avoid extraneous spaces in parentheses +// Can omit curly braces for one line statement (if, for, etc) +// else should be placed on own line + + +// 13. NATSPEC COMENTS +// used for documentation, commenting, and external UIs + +// Contract natspec - always above contract definition +/// @title Contract title +/// @author Author name + +// Function natspec +/// @notice information about what function does; shown when function to execute +/// @dev Function documentation for developer + +// Function parameter/return value natspec +/// @param someParam Some description of what the param does +/// @return Description of the return value +``` + +## Additional resources +- [Solidity Docs](https://solidity.readthedocs.org/en/latest/) +- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. +- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) +- [Gitter Chat room](https://gitter.im/ethereum/solidity) +- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) +- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) + +## Sample contracts +- [Dapp Bin](https://github.com/ethereum/dapp-bin) +- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) +- [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [State of Dapps](http://dapps.ethercasts.com/) + +## Information purposefully excluded +- Libraries + +## Style +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy + +## Future To Dos +- New keywords: protected, inheritable + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail diff --git a/swift.html.markdown b/swift.html.markdown index e6bf1621..46768375 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -213,7 +213,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift header docs (format as reStructedText) +// Function with Swift header docs (format as Swift-modified Markdown syntax) /** A greet operation @@ -221,9 +221,9 @@ A greet operation - 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. +- Parameter name : A name +- Parameter 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)." @@ -392,7 +392,7 @@ testTryStuff() public class Shape { public func getArea() -> Int { - return 0; + return 0 } } diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown index 56f94ed0..cbe88f1e 100644 --- a/ta_in/css-ta.html.markdown +++ b/ta_in/css-ta.html.markdown @@ -7,9 +7,9 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: learncss.css -lang:in-ta + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss-ta.css +lang: in-ta --- diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown index f0b0a36a..d3fe5a85 100644 --- a/ta_in/javascript-ta.html.markdown +++ b/ta_in/javascript-ta.html.markdown @@ -5,8 +5,8 @@ contributors: - ['Ariel Krakowski', 'http://www.learneroo.com'] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: javascript.js -lang:in-ta +filename: javascript-ta.js +lang: in-ta --- javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown index a9bfa9cd..d782399d 100644 --- a/ta_in/xml-ta.html.markdown +++ b/ta_in/xml-ta.html.markdown @@ -1,11 +1,11 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-ta.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] -lang:in-ta +lang: in-ta --- diff --git a/tmux.html.markdown b/tmux.html.markdown index 868302a8..c9e3db6b 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -7,7 +7,7 @@ filename: LearnTmux.txt --- -[tmux](http://tmux.sourceforge.net) +[tmux](http://tmux.github.io) is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background @@ -240,7 +240,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ### References -[Tmux | Home](http://tmux.sourceforge.net) +[Tmux | Home](http://tmux.github.io) [Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/bf-tr.html.markdown index bd842b17..e7015cd0 100644 --- a/tr-tr/brainfuck-tr.html.markdown +++ b/tr-tr/bf-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf filename: brainfuck-tr contributors: - ["Prajit Ramachandran", "http://prajitr.github.io"] diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index c13f5ecf..15056bb8 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -25,14 +25,14 @@ import UIKit //XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot - listesinde gruplama yapmanıza olanak sağlıyor +//listesinde gruplama yapmanıza olanak sağlıyor // MARK: Bölüm işareti // TODO: Daha sonra yapılacak // FIXME: Bu kodu düzelt -//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print - otomatik olarak yeni satır ekliyor. +//Swift 2 de, println ve print metotları print komutunda birleştirildi. +//Print otomatik olarak yeni satır ekliyor. print("Merhaba dünya") // println print olarak kullanılıyor. print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar. @@ -75,7 +75,7 @@ print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7 */ var baziOptionalString: String? = "optional" // nil olabilir. // yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay -okunabilir) +//okunabilir) var someOptionalString2: Optional<String> = "optional" @@ -104,7 +104,8 @@ if let baziOpsiyonelSabitString = baziOptionalString { // Swift değişkenlerde herhangi bir tip saklanabilir. // AnyObject == id // Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle - çalışabilir (Class, Int, struct, etc) +//çalışabilir +(Class, Int, struct, etc) var herhangiBirObject: AnyObject = 7 herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün" @@ -234,7 +235,7 @@ func fiyatlariGetir() -> (Double, Double, Double) { let fiyatTuple = fiyatlariGetir() let fiyat = fiyatTuple.2 // 3.79 // _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden -gelir +//gelir let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69 print(fiyat1 == fiyatTuple.1) // true print("Benzin fiyatı: \(fiyat)") diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown index 8ee12a93..a860e9a7 100644 --- a/uk-ua/json-ua.html.markdown +++ b/uk-ua/json-ua.html.markdown @@ -22,7 +22,7 @@ JSON - це надзвичайно простий формат обміну да "ключі": "завжди мають бути обгорнуті в подвійні лапки", "числа": 0, - "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".", + "рядки": "Пρивіт, світe. Допускаються всі unicode-символи разом із \"екрануванням\".", "логічний тип": true, "нічого": null, @@ -34,13 +34,13 @@ JSON - це надзвичайно простий формат обміну да "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5], "інший об’єкт": { - "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." + "коментар": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." } }, "безглуздя": [ { - "джерело калія": ["банани"] + "джерело калію": ["банани"] }, [ [1, 0, 0, 0], @@ -56,7 +56,7 @@ JSON - це надзвичайно простий формат обміну да , "інший коментар": "класно" }, - "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON." + "Це було не довго": "І ви впорались! Тепер ви знаєте все про JSON." } Одиничний масив значень теж є правильним JSON diff --git a/wolfram.html.markdown b/wolfram.html.markdown new file mode 100644 index 00000000..4514006d --- /dev/null +++ b/wolfram.html.markdown @@ -0,0 +1,137 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnwolfram.nb +--- + +The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. + +Wolfram Language has several interfaces: +* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. +* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic +* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend + +The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. + +``` +(* This is a comment *) + +(* In Mathematica instead of using these comments you can create a text cell + and annotate your code with nicely typeset text and images *) + +(* Typing an expression returns the result *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Function Call *) +(* Note, function names (and everything else) are case sensitive *) +Sin[Pi/2] (* 1 *) + +(* Alternate Syntaxes for Function Call with one parameter *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Every syntax in WL has some equivalent as a function call *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Using a variable for the first time defines it and makes it global *) +x = 5 (* 5 *) +x == 5 (* True, C-style assignment and equality testing *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) +x (* 20 *) + +(* Because WL is based on a computer algebra system, *) +(* using undefined variables is fine, they just obstruct evaluation *) +cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) +cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) +% (* 15 + cow, % fetches the last return *) +% - cow (* 15, undefined variable cow cancelled out *) +moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) + +(* Defining a function *) +Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS + And _ after x to indicate no pattern matching constraints *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) +(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) + +(* For imperative-style programming use ; to separate statements *) +(* Discards any output from LHS and runs RHS *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical + ;'s precedence is lower than := *) +MyFirst[] (* Hello World *) + +(* C-Style For Loop *) +PrintTo[x_] := For[y=0, y<x, y++, (Print[y])] (* Start, test, incr, body *) +PrintTo[5] (* 0 1 2 3 4 *) + +(* While Loop *) +x = 0; While[x < 2, (Print@x; x++)] (* While loop with test and body *) + +(* If and conditionals *) +x = 8; If[x==8, Print@"Yes", Print@"No"] (* Condition, true case, else case *) +Switch[x, 2, Print@"Two", 8, Print@"Yes"] (* Value match style switch *) +Which[x==2, Print@"No", x==8, Print@"Yes"] (* Elif style switch *) + +(* Variables other than parameters are global by default, even inside functions *) +y = 10 (* 10, global variable y *) +PrintTo[5] (* 0 1 2 3 4 *) +y (* 5, global y clobbered by loop counter inside PrintTo *) +x = 20 (* 20, global variable x *) +PrintTo[5] (* 0 1 2 3 4 *) +x (* 20, x in PrintTo is a parameter and automatically local *) + +(* Local variables are declared using the Module metafunction *) +(* Version with local variable *) +BetterPrintTo[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])] +y = 20 (* Global variable y *) +BetterPrintTo[5] (* 0 1 2 3 4 *) +y (* 20, that's better *) + +(* Module actually lets us declare any scope we like *) +Module[{count}, count=0; (* Declare scope of this variable count *) + (IncCount[] := ++count); (* These functions are inside that scope *) + (DecCount[] := --count)] +count (* count - global variable count is not defined *) +IncCount[] (* 1, using the count variable inside the scope *) +IncCount[] (* 2, incCount updates it *) +DecCount[] (* 1, so does decCount *) +count (* count - still no global variable by that name *) + +(* Lists *) +myList = {1, 2, 3, 4} (* {1, 2, 3, 4} *) +myList[[1]] (* 1 - note list indexes start at 1, not 0 *) +Map[Double, myList] (* {2, 4, 6, 8} - functional style list map function *) +Double /@ myList (* {2, 4, 6, 8} - Abbreviated syntax for above *) +Scan[Print, myList] (* 1 2 3 4 - imperative style loop over list *) +Fold[Plus, 0, myList] (* 10 (0+1+2+3+4) *) +FoldList[Plus, 0, myList] (* {0, 1, 3, 6, 10} - fold storing intermediate results *) +Append[myList, 5] (* {1, 2, 3, 4, 5} - note myList is not updated *) +Prepend[myList, 5] (* {5, 1, 2, 3, 4} - add "myList = " if you want it to be *) +Join[myList, {3, 4}] (* {1, 2, 3, 4, 3, 4} *) +myList[[2]] = 5 (* {1, 5, 3, 4} - this does update myList *) + +(* Associations, aka Dictionaries/Hashes *) +myHash = <|"Green" -> 2, "Red" -> 1|> (* Create an association *) +myHash[["Green"]] (* 2, use it *) +myHash[["Green"]] := 5 (* 5, update it *) +myHash[["Puce"]] := 3.5 (* 3.5, extend it *) +KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* And you can't do any demo of Wolfram without showing this off *) +Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 + and allows y to be adjusted between 0-20 with a slider. + Only works on graphical frontends *) +``` + +##Ready For More? + +* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) diff --git a/zfs.html.markdown b/zfs.html.markdown index 74487e35..39ff84cd 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -9,7 +9,7 @@ filename: LearnZfs.txt [ZFS](http://open-zfs.org/wiki/Main_Page) is a rethinking of the storage stack, combining traditional file systems as well as volume -managers into one cohesive tool. ZFS has some specific teminology that sets it appart from +managers into one cohesive tool. ZFS has some specific terminology that sets it apart from more traditional storage systems, however it has a great set of features with a focus on usability for systems administrators. @@ -23,7 +23,7 @@ types of VDEV's that offer various advantages, including redundancy and speed. VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. -Types of VDEV's +Types of VDEV's * stripe (a single disk, no redundancy) * mirror (n-way mirrors supported) * raidz @@ -39,13 +39,13 @@ increase your IOPS. ### Storage Pools ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow -you to separate the user visable file system from the physcal layout. +you to separate the user visible file system from the physical layout. ### ZFS Dataset -ZFS datasets are analagous to traditional filesystems but with many more features. They +ZFS datasets are analogous to traditional filesystems but with many more features. They provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) -snapshots, quota's, compression and deduplication. +snapshots, quota's, compression and de-duplication. ### Limits @@ -68,7 +68,7 @@ Actions: List zpools ```bash -# Create a raidz zpool +# Create a raidz zpool $ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 # List ZPools @@ -347,7 +347,7 @@ $ zfs promote tank/home/sarlalian_new ### Putting it all together -This following a script utilizing FreeBSD, jails and ZFS to automate +This following a script utilizing FreeBSD, jails and ZFS to automate provisioning a clean copy of a mysql staging database from a live replication slave. @@ -384,7 +384,7 @@ mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local echo "==== Starting the staging db server ====" jail -c staging -echo "==== Make sthe staging database not pull from the master ====" +echo "==== Makes the staging database not pull from the master ====" echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ``` diff --git a/zh-cn/brainfuck-cn.html.markdown b/zh-cn/bf-cn.html.markdown index a6f3fa09..6cea3012 100644 --- a/zh-cn/brainfuck-cn.html.markdown +++ b/zh-cn/bf-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: brainfuck +language: bf lang: zh-cn contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index a8fd2a4c..1e9c38f6 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -302,7 +302,7 @@ class Bicycle { // 构造函数是初始化一个对象的方式 // 以下是一个默认构造函数 - public Bi450635425cycle() { + public Bicycle() { gear = 1; cadence = 50; speed = 5; @@ -328,7 +328,7 @@ class Bicycle { return cadence; } - // void返450635425回值函数没有返回值 + // void返回值函数没有返回值 public void setCadence(int newValue) { cadence = newValue; } diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 098d0ab5..f7065445 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -91,10 +91,10 @@ until num == 0 -- 2. 函数。 ---------------------------------------------------- -function fib(n) - if n < 2 then return 1 end - return fib(n - 2) + fib(n - 1) -end +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end -- 支持闭包及匿名函数: function adder(x) @@ -129,9 +129,11 @@ function f(x) return x * x end f = function (x) return x * x end -- 这些也是等价的: -local function g(x) return math.sin(x) end -local g; g = function (x) return math.sin(x) end --- 'local g'使得g可以自引用。 +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- 以上均因'local g',使得g可以自引用。 +local g = function(x) return math.sin(x) end +-- 等价于 local function g(x)..., 但函数体中g不可自引用 -- 顺便提下,三角函数以弧度为单位。 @@ -210,7 +212,7 @@ f2 = {a = 2, b = 3} metafraction = {} function metafraction.__add(f1, f2) - sum = {} + local sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum @@ -273,7 +275,7 @@ eatenBy = myFavs.animal -- 可以工作!感谢元表 Dog = {} -- 1. function Dog:new() -- 2. - newObj = {sound = 'woof'} -- 3. + local newObj = {sound = 'woof'} -- 3. self.__index = self -- 4. return setmetatable(newObj, self) -- 5. end @@ -307,7 +309,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. LoudDog = Dog:new() -- 1. function LoudDog:makeSound() - s = self.sound .. ' ' -- 2. + local s = self.sound .. ' ' -- 2. print(s .. s .. s) end @@ -328,7 +330,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 如果有必要,子类也可以有new(),与基类相似: function LoudDog:new() - newObj = {} + local newObj = {} -- 初始化newObj self.__index = self return setmetatable(newObj, self) @@ -340,7 +342,9 @@ end --[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 +``` +```lua -- 假设文件mod.lua的内容类似这样: local M = {} @@ -411,4 +415,9 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us * <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a> * <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a> +顺便说一下,整个文件是可运行的Lua; +保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! + +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版. + 使用Lua,欢乐常在! diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 508dd58e..f3327b5b 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -369,7 +369,7 @@ object Dog { // Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类 // 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值 -// 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变 +// 的作用域一般为 private , 只有方法是暴露的。case 类的主要目的是放置不可变 // 数据。它们通常只有几个方法,且方法几乎没有副作用。 case class Person(name: String, phoneNumber: String) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown new file mode 100644 index 00000000..cf865dce --- /dev/null +++ b/zh-cn/tmux-cn.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +filename: LearnTmux-cn.txt +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Arnie97", "https://github.com/Arnie97"] +lang: zh-cn +--- + + +[tmux](http://tmux.github.io)是一款终端复用工具。 +在它的帮助下,你可以在同一个控制台上建立、访问并控制多个终端。 +你可以断开与一个 tmux 终端的连接,此时程序将在后台运行, +当你需要时,可以随时重新连接到这个终端。 + +``` + + tmux [command] # 运行一条命令 + # 如果单独使用 'tmux' 而不指定某个命令,将会建立一个新的会话 + + new # 创建一个新的会话 + -s "Session" # 创建一个会话,并命名为“Session” + -n "Window" # 创建一个窗口,并命名为“Window” + -c "/dir" # 在指定的工作目录中启动会话 + + attach # 连接到上一次的会话(如果可用) + -t "#" # 连接到指定的会话 + -d # 断开其他客户端的会话 + + ls # 列出打开的会话 + -a # 列出所有打开的会话 + + lsw # 列出窗口 + -a # 列出所有窗口 + -s # 列出会话中的所有窗口 + + lsp # 列出窗格 + -a # 列出所有窗格 + -s # 列出会话中的所有窗格 + -t "#" # 列出指定窗口中的所有窗格 + + kill-window # 关闭当前窗口 + -t "#" # 关闭指定的窗口 + -a # 关闭所有窗口 + -a -t "#" # 关闭除指定窗口以外的所有窗口 + + kill-session # 关闭当前会话 + -t "#" # 关闭指定的会话 + -a # 关闭所有会话 + -a -t "#" # 关闭除指定会话以外的所有会话 + +``` + + +### 快捷键 + +通过“前缀”快捷键,可以控制一个已经连入的 tmux 会话。 + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # 在使用下列快捷键之前,需要按这个“前缀”快捷键 + + (M-1) = Meta + 1 或 Alt + 1 +---------------------------------------------------------------------- + + ? # 列出所有快捷键 + : # 进入 tmux 的命令提示符 + r # 强制重绘当前客户端 + c # 创建一个新窗口 + + ! # 将当前窗格从窗口中移出,成为为一个新的窗口 + % # 将当前窗格分为左右两半 + " # 将当前窗格分为上下两半 + + n # 切换到下一个窗口 + p # 切换到上一个窗口 + { # 将当前窗格与上一个窗格交换 + } # 将当前窗格与下一个窗格交换 + + s # 在交互式界面中,选择并连接至另一个会话 + w # 在交互式界面中,选择并激活一个窗口 + 0 至 9 # 选择 0 到 9 号窗口 + + d # 断开当前客户端 + D # 选择并断开一个客户端 + + & # 关闭当前窗口 + x # 关闭当前窗格 + + Up, Down # 将焦点移动至相邻的窗格 + Left, Right + + M-1 到 M-5 # 排列窗格: + # 1) 水平等分 + # 2) 垂直等分 + # 3) 将一个窗格作为主要窗格,其他窗格水平等分 + # 4) 将一个窗格作为主要窗格,其他窗格垂直等分 + # 5) 平铺 + + C-Up, C-Down # 改变当前窗格的大小,每按一次增减一个单位 + C-Left, C-Right + + M-Up, M-Down # 改变当前窗格的大小,每按一次增减五个单位 + M-Left, M-Right + +``` + + +### 配置 ~/.tmux.conf + +tmux.conf 可以在 tmux 启动时自动设置选项,类似于 .vimrc 或 init.el 的用法。 + +``` +# tmux.conf 示例 +# 2014.10 + + +### 通用设置 +########################################################################### + +# 启用 UTF-8 编码 +setw -g utf8 on +set-option -g status-utf8 on + +# 命令回滚/历史数量限制 +set -g history-limit 2048 + +# 从 1 开始编号,而不是从 0 开始 +set -g base-index 1 + +# 启用鼠标 +set-option -g mouse-select-pane on + +# 重新加载配置文件 +unbind r +bind r source-file ~/.tmux.conf + + +### 快捷键设置 +########################################################################### + +# 取消默认的前缀键 C-b +unbind C-b + +# 设置新的前缀键 ` +set-option -g prefix ` + +# 多次按下前缀键时,切换到上一个窗口 +bind C-a last-window +bind ` last-window + +# 按下F11/F12,可以选择不同的前缀键 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Vim 风格的快捷键绑定 +setw -g mode-keys vi +set-option -g status-keys vi + +# 使用 Vim 风格的按键在窗格间移动 +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# 循环切换不同的窗口 +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# 较易于使用的窗格分割快捷键 +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# 在嵌套使用 tmux 的情况下,激活最内层的会话,以便向其发送命令 +bind a send-prefix + + +### 外观主题 +########################################################################### + +# 状态栏颜色 +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# 窗格边框颜色 +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# 消息框颜色 +set-option -g message-fg black +set-option -g message-bg green + +# 窗口状态栏颜色 +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### 用户界面 +########################################################################### + +# 通知方式 +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# 自动设置窗口标题 +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # 窗口编号,程序名称,是否活动 + +# 调整状态栏 +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# 在状态栏中显示性能计数器 +# 需要用到 https://github.com/thewtex/tmux-mem-cpu-load +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### 参考资料 + +[Tmux 主页](http://tmux.github.io) + +[Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[FreeBSDChina Wiki](https://wiki.freebsdchina.org/software/t/tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) + +[Tmux 快速教程](http://blog.jeswang.org/blog/2013/06/24/tmux-kuai-su-jiao-cheng) + +[如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) |