diff options
187 files changed, 8646 insertions, 1937 deletions
diff --git a/.gitattributes b/.gitattributes index 96d2bb5a..da8c9d63 100644 --- a/.gitattributes +++ b/.gitattributes @@ -46,13 +46,13 @@ json*.html.markdown linguist-language=JSON julia*.html.markdown linguist-language=Julia kotlin*.html.markdown linguist-language=Kotlin latex*.html.markdown linguist-language=latex -less*.html.markdown linguist-language=less +less*.html.markdown linguist-language=Less livescript*.html.markdown linguist-language=LiveScript logtalk*.html.markdown linguist-language=Logtalk lua*.html.markdown linguist-language=Lua make*.html.markdown linguist-language=Makefile markdown*.html.markdown linguist-language=Markdown -matlab*.html.markdown linguist-language=Matlab +matlab*.html.markdown linguist-language=MATLAB nim*.html.markdown linguist-language=Nimrod nix*.html.markdown linguist-language=Nix objective-c*.html.markdown linguist-language=Objective-C diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 6c1efe0d..7bc421a7 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4,3 +4,5 @@ /zh-cn/ @geoffliu @imba-tjd
/zh-tw/ @geoffliu @imba-tjd
/ko-kr/ @justin-themedium
+/pt-pt/ @mribeirodantas
+/pt-br/ @mribeirodantas
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown index 8d2a8320..430ecea0 100644 --- a/CONTRIBUTING.markdown +++ b/CONTRIBUTING.markdown @@ -16,27 +16,29 @@ review them more effectively and/or individually. ## Style Guidelines -- **Keep lines 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) - + You can check if the file contains a BOM on Linux/Unix systems by running +* **Keep lines under 80 chars** + * Try to keep **line length in code blocks to 80 characters or fewer**. + * Otherwise, the text will overflow and look odd. + * This and other potential pitfalls to format the content consistently are + identified by the freely available + [markdownlint](https://github.com/markdownlint/markdownlint). +* **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 ensure + your file is UTF-8 encoded. + * Try to leave out the byte-order-mark at the start of the file (in Vim, use + `:set nobomb`). + * You can check if the file contains a BOM on Linux/Unix systems by running `file language.html.markdown` You will see this if it uses a BOM: - `UTF-8 Unicode (with BOM) text`. - + `UTF-8 Unicode (with BOM) text`. ### Header configuration @@ -47,31 +49,31 @@ 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 +* **language** The *programming language* in question +* **contributors** A list of [author, URL] lists to credit Other fields: -- **category**: The category of the article. So far, can be one of *language*, +* **category**: The category of the article. So far, can be one of *language*, *tool* or *Algorithms & Data Structures*. Defaults to *language* if omitted. -- **filename**: The filename for this article's code. It will be fetched, mashed +* **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 + * 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 ---- +*-- ``` ### Should I add myself as a Contributor? @@ -85,21 +87,25 @@ addition or not. You can build the site locally to test your changes. Follow the steps below. -* Install Ruby language runtime and RubyGems. See [here](https://middlemanapp.com/basics/install/) for more details. -* Clone or zip download the [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site) repo. - * `git clone https://github.com/adambard/learnxinyminutes-site` +* Install Ruby language runtime and RubyGems. See + [here](https://middlemanapp.com/basics/install/) + for more details. +* Clone or zip download the + [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site) + repository. + * `git clone https://github.com/adambard/learnxinyminutes-site` * Install Middleman and other required dependencies using Bundler. - * `cd learnxinyminutes-site/` - * `bundle install` + * `cd learnxinyminutes-site/` + * `bundle install` * Get the source in place - * Copy the contents of your clone of the fork of learnxinyminutes-docs repo - into the `source/docs` folder. There shouldn't be a `learnxinyminutes-docs` - folder inside the `docs` folder, it should just contain all the repo - contents. - * Checkout your fork of the learnxinyminutes-docs repo as `source/docs`. - * `cd source/docs/` - * `git clone https://github.com/YOUR-USERNAME/learnxinyminutes-docs ./source/docs/` + * Copy the contents of your clone of the fork of learnxinyminutes-docs repo + into the `source/docs` folder. There shouldn't be a `learnxinyminutes-docs` + folder inside the `docs` folder, it should just contain all the repo + contents. + * Checkout your fork of the learnxinyminutes-docs repo as `source/docs`. + * `cd source/docs/` + * `git clone https://github.com/YOUR-USERNAME/learnxinyminutes-docs ./source/docs/` * Build the site or run a development server to test your changes (NOTE: run -these commands at `learnxinyminutes-site/`). - * Build - `bundle exec middleman build` - * Dev server - `bundle exec middleman --force-polling --verbose` + these commands at `learnxinyminutes-site/`). + * Build - `bundle exec middleman build` + * Dev server - `bundle exec middleman --force-polling --verbose` diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000..604209a8 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,359 @@ +Creative Commons Legal Code + +Attribution-ShareAlike 3.0 Unported + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR + DAMAGES RESULTING FROM ITS USE. + +License + +THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE +COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY +COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS +AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. + +BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE +TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY +BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS +CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND +CONDITIONS. + +1. Definitions + + a. "Adaptation" means a work based upon the Work, or upon the Work and + other pre-existing works, such as a translation, adaptation, + derivative work, arrangement of music or other alterations of a + literary or artistic work, or phonogram or performance and includes + cinematographic adaptations or any other form in which the Work may be + recast, transformed, or adapted including in any form recognizably + derived from the original, except that a work that constitutes a + Collection will not be considered an Adaptation for the purpose of + this License. For the avoidance of doubt, where the Work is a musical + work, performance or phonogram, the synchronization of the Work in + timed-relation with a moving image ("synching") will be considered an + Adaptation for the purpose of this License. + b. "Collection" means a collection of literary or artistic works, such as + encyclopedias and anthologies, or performances, phonograms or + broadcasts, or other works or subject matter other than works listed + in Section 1(f) below, which, by reason of the selection and + arrangement of their contents, constitute intellectual creations, in + which the Work is included in its entirety in unmodified form along + with one or more other contributions, each constituting separate and + independent works in themselves, which together are assembled into a + collective whole. A work that constitutes a Collection will not be + considered an Adaptation (as defined below) for the purposes of this + License. + c. "Creative Commons Compatible License" means a license that is listed + at https://creativecommons.org/compatiblelicenses that has been + approved by Creative Commons as being essentially equivalent to this + License, including, at a minimum, because that license: (i) contains + terms that have the same purpose, meaning and effect as the License + Elements of this License; and, (ii) explicitly permits the relicensing + of adaptations of works made available under that license under this + License or a Creative Commons jurisdiction license with the same + License Elements as this License. + d. "Distribute" means to make available to the public the original and + copies of the Work or Adaptation, as appropriate, through sale or + other transfer of ownership. + e. "License Elements" means the following high-level license attributes + as selected by Licensor and indicated in the title of this License: + Attribution, ShareAlike. + f. "Licensor" means the individual, individuals, entity or entities that + offer(s) the Work under the terms of this License. + g. "Original Author" means, in the case of a literary or artistic work, + the individual, individuals, entity or entities who created the Work + or if no individual or entity can be identified, the publisher; and in + addition (i) in the case of a performance the actors, singers, + musicians, dancers, and other persons who act, sing, deliver, declaim, + play in, interpret or otherwise perform literary or artistic works or + expressions of folklore; (ii) in the case of a phonogram the producer + being the person or legal entity who first fixes the sounds of a + performance or other sounds; and, (iii) in the case of broadcasts, the + organization that transmits the broadcast. + h. "Work" means the literary and/or artistic work offered under the terms + of this License including without limitation any production in the + literary, scientific and artistic domain, whatever may be the mode or + form of its expression including digital form, such as a book, + pamphlet and other writing; a lecture, address, sermon or other work + of the same nature; a dramatic or dramatico-musical work; a + choreographic work or entertainment in dumb show; a musical + composition with or without words; a cinematographic work to which are + assimilated works expressed by a process analogous to cinematography; + a work of drawing, painting, architecture, sculpture, engraving or + lithography; a photographic work to which are assimilated works + expressed by a process analogous to photography; a work of applied + art; an illustration, map, plan, sketch or three-dimensional work + relative to geography, topography, architecture or science; a + performance; a broadcast; a phonogram; a compilation of data to the + extent it is protected as a copyrightable work; or a work performed by + a variety or circus performer to the extent it is not otherwise + considered a literary or artistic work. + i. "You" means an individual or entity exercising rights under this + License who has not previously violated the terms of this License with + respect to the Work, or who has received express permission from the + Licensor to exercise rights under this License despite a previous + violation. + j. "Publicly Perform" means to perform public recitations of the Work and + to communicate to the public those public recitations, by any means or + process, including by wire or wireless means or public digital + performances; to make available to the public Works in such a way that + members of the public may access these Works from a place and at a + place individually chosen by them; to perform the Work to the public + by any means or process and the communication to the public of the + performances of the Work, including by public digital performance; to + broadcast and rebroadcast the Work by any means including signs, + sounds or images. + k. "Reproduce" means to make copies of the Work by any means including + without limitation by sound or visual recordings and the right of + fixation and reproducing fixations of the Work, including storage of a + protected performance or phonogram in digital form or other electronic + medium. + +2. Fair Dealing Rights. Nothing in this License is intended to reduce, +limit, or restrict any uses free from copyright or rights arising from +limitations or exceptions that are provided for in connection with the +copyright protection under copyright law or other applicable laws. + +3. License Grant. Subject to the terms and conditions of this License, +Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +perpetual (for the duration of the applicable copyright) license to +exercise the rights in the Work as stated below: + + a. to Reproduce the Work, to incorporate the Work into one or more + Collections, and to Reproduce the Work as incorporated in the + Collections; + b. to create and Reproduce Adaptations provided that any such Adaptation, + including any translation in any medium, takes reasonable steps to + clearly label, demarcate or otherwise identify that changes were made + to the original Work. For example, a translation could be marked "The + original work was translated from English to Spanish," or a + modification could indicate "The original work has been modified."; + c. to Distribute and Publicly Perform the Work including as incorporated + in Collections; and, + d. to Distribute and Publicly Perform Adaptations. + e. For the avoidance of doubt: + + i. Non-waivable Compulsory License Schemes. In those jurisdictions in + which the right to collect royalties through any statutory or + compulsory licensing scheme cannot be waived, the Licensor + reserves the exclusive right to collect such royalties for any + exercise by You of the rights granted under this License; + ii. Waivable Compulsory License Schemes. In those jurisdictions in + which the right to collect royalties through any statutory or + compulsory licensing scheme can be waived, the Licensor waives the + exclusive right to collect such royalties for any exercise by You + of the rights granted under this License; and, + iii. Voluntary License Schemes. The Licensor waives the right to + collect royalties, whether individually or, in the event that the + Licensor is a member of a collecting society that administers + voluntary licensing schemes, via that society, from any exercise + by You of the rights granted under this License. + +The above rights may be exercised in all media and formats whether now +known or hereafter devised. The above rights include the right to make +such modifications as are technically necessary to exercise the rights in +other media and formats. Subject to Section 8(f), all rights not expressly +granted by Licensor are hereby reserved. + +4. Restrictions. The license granted in Section 3 above is expressly made +subject to and limited by the following restrictions: + + a. You may Distribute or Publicly Perform the Work only under the terms + of this License. You must include a copy of, or the Uniform Resource + Identifier (URI) for, this License with every copy of the Work You + Distribute or Publicly Perform. You may not offer or impose any terms + on the Work that restrict the terms of this License or the ability of + the recipient of the Work to exercise the rights granted to that + recipient under the terms of the License. You may not sublicense the + Work. You must keep intact all notices that refer to this License and + to the disclaimer of warranties with every copy of the Work You + Distribute or Publicly Perform. When You Distribute or Publicly + Perform the Work, You may not impose any effective technological + measures on the Work that restrict the ability of a recipient of the + Work from You to exercise the rights granted to that recipient under + the terms of the License. This Section 4(a) applies to the Work as + incorporated in a Collection, but this does not require the Collection + apart from the Work itself to be made subject to the terms of this + License. If You create a Collection, upon notice from any Licensor You + must, to the extent practicable, remove from the Collection any credit + as required by Section 4(c), as requested. If You create an + Adaptation, upon notice from any Licensor You must, to the extent + practicable, remove from the Adaptation any credit as required by + Section 4(c), as requested. + b. You may Distribute or Publicly Perform an Adaptation only under the + terms of: (i) this License; (ii) a later version of this License with + the same License Elements as this License; (iii) a Creative Commons + jurisdiction license (either this or a later license version) that + contains the same License Elements as this License (e.g., + Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible + License. If you license the Adaptation under one of the licenses + mentioned in (iv), you must comply with the terms of that license. If + you license the Adaptation under the terms of any of the licenses + mentioned in (i), (ii) or (iii) (the "Applicable License"), you must + comply with the terms of the Applicable License generally and the + following provisions: (I) You must include a copy of, or the URI for, + the Applicable License with every copy of each Adaptation You + Distribute or Publicly Perform; (II) You may not offer or impose any + terms on the Adaptation that restrict the terms of the Applicable + License or the ability of the recipient of the Adaptation to exercise + the rights granted to that recipient under the terms of the Applicable + License; (III) You must keep intact all notices that refer to the + Applicable License and to the disclaimer of warranties with every copy + of the Work as included in the Adaptation You Distribute or Publicly + Perform; (IV) when You Distribute or Publicly Perform the Adaptation, + You may not impose any effective technological measures on the + Adaptation that restrict the ability of a recipient of the Adaptation + from You to exercise the rights granted to that recipient under the + terms of the Applicable License. This Section 4(b) applies to the + Adaptation as incorporated in a Collection, but this does not require + the Collection apart from the Adaptation itself to be made subject to + the terms of the Applicable License. + c. If You Distribute, or Publicly Perform the Work or any Adaptations or + Collections, You must, unless a request has been made pursuant to + Section 4(a), keep intact all copyright notices for the Work and + provide, reasonable to the medium or means You are utilizing: (i) the + name of the Original Author (or pseudonym, if applicable) if supplied, + and/or if the Original Author and/or Licensor designate another party + or parties (e.g., a sponsor institute, publishing entity, journal) for + attribution ("Attribution Parties") in Licensor's copyright notice, + terms of service or by other reasonable means, the name of such party + or parties; (ii) the title of the Work if supplied; (iii) to the + extent reasonably practicable, the URI, if any, that Licensor + specifies to be associated with the Work, unless such URI does not + refer to the copyright notice or licensing information for the Work; + and (iv) , consistent with Ssection 3(b), in the case of an + Adaptation, a credit identifying the use of the Work in the Adaptation + (e.g., "French translation of the Work by Original Author," or + "Screenplay based on original Work by Original Author"). The credit + required by this Section 4(c) may be implemented in any reasonable + manner; provided, however, that in the case of a Adaptation or + Collection, at a minimum such credit will appear, if a credit for all + contributing authors of the Adaptation or Collection appears, then as + part of these credits and in a manner at least as prominent as the + credits for the other contributing authors. For the avoidance of + doubt, You may only use the credit required by this Section for the + purpose of attribution in the manner set out above and, by exercising + Your rights under this License, You may not implicitly or explicitly + assert or imply any connection with, sponsorship or endorsement by the + Original Author, Licensor and/or Attribution Parties, as appropriate, + of You or Your use of the Work, without the separate, express prior + written permission of the Original Author, Licensor and/or Attribution + Parties. + d. Except as otherwise agreed in writing by the Licensor or as may be + otherwise permitted by applicable law, if You Reproduce, Distribute or + Publicly Perform the Work either by itself or as part of any + Adaptations or Collections, You must not distort, mutilate, modify or + take other derogatory action in relation to the Work which would be + prejudicial to the Original Author's honor or reputation. Licensor + agrees that in those jurisdictions (e.g. Japan), in which any exercise + of the right granted in Section 3(b) of this License (the right to + make Adaptations) would be deemed to be a distortion, mutilation, + modification or other derogatory action prejudicial to the Original + Author's honor and reputation, the Licensor will waive or not assert, + as appropriate, this Section, to the fullest extent permitted by the + applicable national law, to enable You to reasonably exercise Your + right under Section 3(b) of this License (right to make Adaptations) + but not otherwise. + +5. Representations, Warranties and Disclaimer + +UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR +OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY +KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, +INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, +FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF +LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, +WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION +OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. + +6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE +LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR +ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES +ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. Termination + + a. This License and the rights granted hereunder will terminate + automatically upon any breach by You of the terms of this License. + Individuals or entities who have received Adaptations or Collections + from You under this License, however, will not have their licenses + terminated provided such individuals or entities remain in full + compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will + survive any termination of this License. + b. Subject to the above terms and conditions, the license granted here is + perpetual (for the duration of the applicable copyright in the Work). + Notwithstanding the above, Licensor reserves the right to release the + Work under different license terms or to stop distributing the Work at + any time; provided, however that any such election will not serve to + withdraw this License (or any other license that has been, or is + required to be, granted under the terms of this License), and this + License will continue in full force and effect unless terminated as + stated above. + +8. Miscellaneous + + a. Each time You Distribute or Publicly Perform the Work or a Collection, + the Licensor offers to the recipient a license to the Work on the same + terms and conditions as the license granted to You under this License. + b. Each time You Distribute or Publicly Perform an Adaptation, Licensor + offers to the recipient a license to the original Work on the same + terms and conditions as the license granted to You under this License. + c. If any provision of this License is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of + the remainder of the terms of this License, and without further action + by the parties to this agreement, such provision shall be reformed to + the minimum extent necessary to make such provision valid and + enforceable. + d. No term or provision of this License shall be deemed waived and no + breach consented to unless such waiver or consent shall be in writing + and signed by the party to be charged with such waiver or consent. + e. This License constitutes the entire agreement between the parties with + respect to the Work licensed here. There are no understandings, + agreements or representations with respect to the Work not specified + here. Licensor shall not be bound by any additional provisions that + may appear in any communication from You. This License may not be + modified without the mutual written agreement of the Licensor and You. + f. The rights granted under, and the subject matter referenced, in this + License were drafted utilizing the terminology of the Berne Convention + for the Protection of Literary and Artistic Works (as amended on + September 28, 1979), the Rome Convention of 1961, the WIPO Copyright + Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 + and the Universal Copyright Convention (as revised on July 24, 1971). + These rights and subject matter take effect in the relevant + jurisdiction in which the License terms are sought to be enforced + according to the corresponding provisions of the implementation of + those treaty provisions in the applicable national law. If the + standard suite of rights granted under applicable copyright law + includes additional rights not granted under this License, such + additional rights are deemed to be included in the License; this + License is not intended to restrict the license of any rights under + applicable law. + + +Creative Commons Notice + + Creative Commons is not a party to this License, and makes no warranty + whatsoever in connection with the Work. Creative Commons will not be + liable to You or any party on any legal theory for any damages + whatsoever, including without limitation any general, special, + incidental or consequential damages arising in connection to this + license. Notwithstanding the foregoing two (2) sentences, if Creative + Commons has expressly identified itself as the Licensor hereunder, it + shall have all rights and obligations of Licensor. + + Except for the limited purpose of indicating to the public that the + Work is licensed under the CCPL, Creative Commons does not authorize + the use by either party of the trademark "Creative Commons" or any + related trademark or logo of Creative Commons without the prior + written consent of Creative Commons. Any permitted use will be in + compliance with Creative Commons' then-current trademark usage + guidelines, as may be published on its website or otherwise made + available upon request from time to time. For the avoidance of doubt, + this trademark restriction does not form part of the License. + + Creative Commons may be contacted at https://creativecommons.org/. diff --git a/ansible.html.markdown b/ansible.html.markdown index 30dfba13..847505c1 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -44,7 +44,7 @@ for, which provides an excellent UI. #### Cons * It is an agent-less tool - every agent consumes up to 16MB ram - in some -environments, it may be noticable amount. +environments, it may be noticeable amount. * It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism that would warn you about some change automatically (this can be achieved with reasonable effort) @@ -691,7 +691,7 @@ to specify the username. Note: You may like to execute Ansible with `--ask-sudo-pass` or add the user to sudoers file in order to allow non-supervised execution if you require 'admin' -privilages. +privileges. [Read more](http://docs.ansible.com/ansible/latest/become.html) @@ -753,3 +753,4 @@ the `register` command. * [A system administrator's guide to getting started with Ansible - FAST!](https://www.redhat.com/en/blog/system-administrators-guide-getting-started-ansible-fast) * [Ansible Tower](https://www.ansible.com/products/tower) - Ansible Tower provides a web UI, dashboard and rest interface to ansible. * [Ansible AWX](https://github.com/ansible/awx) - The Open Source version of Ansible Tower. +* [Ansible Tutorial for Beginners: Ultimate Playbook & Examples](https://spacelift.io/blog/ansible-tutorial) diff --git a/awk.html.markdown b/awk.html.markdown index 3ff3f937..dc22a2bd 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -48,7 +48,7 @@ BEGIN { # the preliminary set-up code, before you process any text files. If you # have no text files, then think of BEGIN as the main entry point. - # Variables are global. Just set them or use them, no need to declare.. + # Variables are global. Just set them or use them, no need to declare. count = 0; # Operators just like in C and friends @@ -118,12 +118,12 @@ BEGIN { # Arrays arr[0] = "foo"; arr[1] = "bar"; - + # You can also initialize an array with the built-in function split() - + n = split("foo:bar:baz", arr, ":"); - - # You also have associative arrays (actually, they're all associative arrays) + + # You also have associative arrays (indeed, they're all associative arrays) assoc["foo"] = "bar"; assoc["bar"] = "baz"; @@ -178,26 +178,26 @@ function arithmetic_functions(a, b, c, d) { # Now, to demonstrate the arithmetic functions # Most AWK implementations have some standard trig functions - localvar = sin(a); - localvar = cos(a); - localvar = atan2(b, a); # arc tangent of b / a + d = sin(a); + d = cos(a); + d = atan2(b, a); # arc tangent of b / a # And logarithmic stuff - localvar = exp(a); - localvar = log(a); + d = exp(a); + d = log(a); # Square root - localvar = sqrt(a); + d = sqrt(a); # Truncate floating point to integer - localvar = int(5.34); # localvar => 5 + d = int(5.34); # d => 5 # Random numbers srand(); # Supply a seed as an argument. By default, it uses the time of day - localvar = rand(); # Random number between 0 and 1. + d = rand(); # Random number between 0 and 1. # Here's how to return a value - return localvar; + return d; } function string_functions( localvar, arr) { @@ -209,14 +209,15 @@ function string_functions( localvar, arr) { # Both return number of matches replaced localvar = "fooooobar"; sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar" - gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar" + gsub("e", ".", localvar); # localvar => "m..t m. at th. bar" # Search for a string that matches a regular expression # index() does the same thing, but doesn't allow a regular expression match(localvar, "t"); # => 4, since the 't' is the fourth character # Split on a delimiter - n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 + n = split("foo-bar-baz", arr, "-"); + # result: a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 # Other useful stuff sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3" @@ -238,9 +239,9 @@ function io_functions( localvar) { # AWK doesn't have file handles, per se. It will automatically open a file # handle for you when you use something that needs one. The string you used # for this can be treated as a file handle, for purposes of I/O. This makes - # it feel sort of like shell scripting, but to get the same output, the string - # must match exactly, so use a variable: - + # it feel sort of like shell scripting, but to get the same output, the + # string must match exactly, so use a variable: + outfile = "/tmp/foobar.txt"; print "foobar" > outfile; @@ -261,7 +262,7 @@ function io_functions( localvar) { # Reads a line from a file and stores in localvar infile = "/tmp/foobar.txt"; - getline localvar < infile; + getline localvar < infile; close(infile); } @@ -273,10 +274,10 @@ function io_functions( localvar) { # When you pass arguments to AWK, they are treated as file names to process. # It will process them all, in order. Think of it like an implicit for loop, # iterating over the lines in these files. these patterns and actions are like -# switch statements inside the loop. +# switch statements inside the loop. /^fo+bar$/ { - + # This action will execute for every line that matches the regular # expression, /^fo+bar$/, and will be skipped for any line that fails to # match it. Let's just print the line: @@ -376,11 +377,15 @@ END { } ``` + Further Reading: * [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) * [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) + GNU Awk is found on most Linux systems. * [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html) -* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical summary and list of "gotchas" (places where different implementations may behave in different or unexpected ways). +* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical + summary and list of "gotchas" (places where different implementations may + behave in different or unexpected ways). * [basic libraries for awk](https://github.com/dubiousjim/awkenough) diff --git a/bash.html.markdown b/bash.html.markdown index 8fdfdf08..e0e4f88a 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -18,6 +18,7 @@ contributors: - ["Harry Mumford-Turner", "https://github.com/harrymt"] - ["Martin Nicholson", "https://github.com/mn113"] - ["Mark Grimwood", "https://github.com/MarkGrimwood"] + - ["Emily Grace Seville", "https://github.com/EmilySeville7cfg"] filename: LearnBash.sh translators: - ["Dimitri Kokkonis", "https://github.com/kokkonisd"] @@ -37,104 +38,107 @@ or executed directly in the shell. # As you already figured, comments start with #. Shebang is also a comment. # Simple hello world example: -echo Hello world! # => Hello world! +echo "Hello world!" # => Hello world! # Each command starts on a new line, or after a semicolon: -echo 'This is the first line'; echo 'This is the second line' -# => This is the first line -# => This is the second line +echo "This is the first command"; echo "This is the second command" +# => This is the first command +# => This is the second command # Declaring a variable looks like this: -Variable="Some string" +variable="Some string" # But not like this: -Variable = "Some string" # => returns error "Variable: command not found" -# Bash will decide that Variable is a command it must execute and give an error +variable = "Some string" # => returns error "variable: command not found" +# Bash will decide that `variable` is a command it must execute and give an error # because it can't be found. # Nor like this: -Variable= 'Some string' # => returns error: "Some string: command not found" -# Bash will decide that 'Some string' is a command it must execute and give an -# error because it can't be found. (In this case the 'Variable=' part is seen -# as a variable assignment valid only for the scope of the 'Some string' -# command.) +variable= "Some string" # => returns error: "Some string: command not found" +# Bash will decide that "Some string" is a command it must execute and give an +# error because it can't be found. In this case the "variable=" part is seen +# as a variable assignment valid only for the scope of the "Some string" +# command. # Using the variable: -echo $Variable # => Some string -echo "$Variable" # => Some string -echo '$Variable' # => $Variable -# When you use the variable itself — assign it, export it, or else — you write +echo "$variable" # => Some string +echo '$variable' # => $variable +# When you use a variable itself — assign it, export it, or else — you write # its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! - -# Parameter expansion ${ }: -echo ${Variable} # => Some string -# This is a simple usage of parameter expansion -# Parameter Expansion gets a value from a variable. -# It "expands" or prints the value -# During the expansion time the value or parameter can be modified -# Below are other modifications that add onto this expansion - -# String substitution in variables -echo ${Variable/Some/A} # => A string -# This will substitute the first occurrence of "Some" with "A" - -# Substring from a variable -Length=7 -echo ${Variable:0:Length} # => Some st +# You can write variable without surrounding quotes but it's not recommended. + +# Parameter expansion ${...}: +echo "${variable}" # => Some string +# This is a simple usage of parameter expansion such as two examples above. +# Parameter expansion gets a value from a variable. +# It "expands" or prints the value. +# During the expansion time the value or parameter can be modified. +# Below are other modifications that add onto this expansion. + +# String substitution in variables: +echo "${variable/Some/A}" # => A string +# This will substitute the first occurrence of "Some" with "A". + +# Substring from a variable: +length=7 +echo "${variable:0:length}" # => Some st # This will return only the first 7 characters of the value -echo ${Variable: -5} # => tring -# This will return the last 5 characters (note the space before -5) +echo "${variable: -5}" # => tring +# This will return the last 5 characters (note the space before -5). +# The space before minus is mandatory here. -# String length -echo ${#Variable} # => 11 +# String length: +echo "${#variable}" # => 11 -# Indirect expansion -OtherVariable="Variable" -echo ${!OtherVariable} # => Some String -# This will expand the value of OtherVariable +# Indirect expansion: +other_variable="variable" +echo ${!other_variable} # => Some string +# This will expand the value of `other_variable`. -# Default value for variable -echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# The default value for variable: +echo "${foo:-"DefaultValueIfFooIsMissingOrEmpty"}" # => DefaultValueIfFooIsMissingOrEmpty -# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. +# This works for null (foo=) and empty string (foo=""); zero (foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. -# Declare an array with 6 elements -array0=(one two three four five six) -# Print first element -echo $array0 # => "one" -# Print first element -echo ${array0[0]} # => "one" -# Print all elements -echo ${array0[@]} # => "one two three four five six" -# Print number of elements -echo ${#array0[@]} # => "6" -# Print number of characters in third element -echo ${#array0[2]} # => "5" -# Print 2 elements starting from forth -echo ${array0[@]:3:2} # => "four five" -# Print all elements. Each of them on new line. -for i in "${array0[@]}"; do - echo "$i" +# Declare an array with 6 elements: +array=(one two three four five six) +# Print the first element: +echo "${array[0]}" # => "one" +# Print all elements: +echo "${array[@]}" # => "one two three four five six" +# Print the number of elements: +echo "${#array[@]}" # => "6" +# Print the number of characters in third element +echo "${#array[2]}" # => "5" +# Print 2 elements starting from fourth: +echo "${array[@]:3:2}" # => "four five" +# Print all elements each of them on new line. +for item in "${array[@]}"; do + echo "$item" done -# Brace Expansion { } -# Used to generate arbitrary strings -echo {1..10} # => 1 2 3 4 5 6 7 8 9 10 -echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z -# This will output the range from the start value to the end value - # Built-in variables: -# There are some useful built-in variables, like +# There are some useful built-in variables, like: echo "Last program's return value: $?" echo "Script's PID: $$" echo "Number of arguments passed to script: $#" echo "All arguments passed to script: $@" echo "Script's arguments separated into different variables: $1 $2..." +# Brace Expansion {...} +# used to generate arbitrary strings: +echo {1..10} # => 1 2 3 4 5 6 7 8 9 10 +echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z +# This will output the range from the start value to the end value. +# Note that you can't use variables here: +from=1 +to=10 +echo {$from..$to} # => {$from..$to} + # Now that we know how to echo and use variables, -# let's learn some of the other basics of bash! +# let's learn some of the other basics of Bash! # Our current directory is available through the command `pwd`. # `pwd` stands for "print working directory". @@ -144,33 +148,46 @@ echo "I'm in $(pwd)" # execs `pwd` and interpolates output echo "I'm in $PWD" # interpolates the variable # If you get too much output in your terminal, or from a script, the command -# `clear` clears your screen +# `clear` clears your screen: clear -# Ctrl-L also works for clearing output +# Ctrl-L also works for clearing output. # Reading a value from input: echo "What's your name?" -read Name # Note that we didn't need to declare a new variable -echo Hello, $Name! +read name +# Note that we didn't need to declare a new variable. +echo "Hello, $name!" -# We have the usual if structure: -# use `man test` for more info about conditionals -if [ $Name != $USER ] -then +# We have the usual if structure. +# Condition is true if the value of $name is not equal to the current user's login username: +if [[ "$name" != "$USER" ]]; then echo "Your name isn't your username" else echo "Your name is your username" fi -# True if the value of $Name is not equal to the current user's login username -# NOTE: if $Name is empty, bash sees the above condition as: -if [ != $USER ] -# which is invalid syntax -# so the "safe" way to use potentially empty variables in bash is: -if [ "$Name" != $USER ] ... -# which, when $Name is empty, is seen by bash as: -if [ "" != $USER ] ... -# which works as expected +# To use && and || with if statements, you need multiple pairs of square brackets: +read age +if [[ "$name" == "Steve" ]] && [[ "$age" -eq 15 ]]; then + echo "This will run if $name is Steve AND $age is 15." +fi + +if [[ "$name" == "Daniya" ]] || [[ "$name" == "Zach" ]]; then + echo "This will run if $name is Daniya OR Zach." +fi +# There are other comparison operators for numbers listed below: +# -ne - not equal +# -lt - less than +# -gt - greater than +# -le - less than or equal to +# -ge - greater than or equal to + +# There is also the `=~` operator, which tests a string against the Regex pattern: +email=me@example.com +if [[ "$email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]] +then + echo "Valid email!" +fi # There is also conditional execution echo "Always executed" || echo "Only executed if first command fails" @@ -193,27 +210,6 @@ bg kill %2 # %1, %2, etc. can be used for fg and bg as well -# To use && and || with if statements, you need multiple pairs of square brackets: -if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ] -then - echo "This will run if $Name is Steve AND $Age is 15." -fi - -if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ] -then - echo "This will run if $Name is Daniya OR Zach." -fi - -# There is also the `=~` operator, which tests a string against a Regex pattern: -Email=me@example.com -if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]] -then - echo "Valid email!" -fi -# Note that =~ only works within double [[ ]] square brackets, -# which are subtly different from single [ ]. -# See https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this. - # Redefine command `ping` as alias to send only 5 packets alias ping='ping -c 5' # Escape the alias and use command with this name instead diff --git a/bf.html.markdown b/bf.html.markdown index 1e415a4d..adc58f02 100644 --- a/bf.html.markdown +++ b/bf.html.markdown @@ -4,12 +4,13 @@ filename: bf.bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] + - ["rilysh", "https://github.com/rilysh"] --- Brainfuck (not capitalized except at the start of a sentence) is an extremely minimal Turing-complete programming language with just 8 commands. -You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). +You can try brainfuck on your browser with [brainfuck-online](https://copy.sh/brainfuck/). ```bf Any character not "><+-.,[]" (excluding quotation marks) is ignored. @@ -80,3 +81,8 @@ And that's brainfuck. Not that hard, eh? For fun, you can write your own brainfuck programs, or you can write a brainfuck interpreter in another language. The interpreter is fairly simple to implement, but if you're a masochist, try writing a brainfuck interpreter… in brainfuck. + +## Further Reading + * [esolang-wiki](https://esolangs.org/wiki/Brainfuck) + * [learn brainfuck](http://cydathria.com/bf/brainfuck.html) + * [other resources](http://www.muppetlabs.com/~breadbox/bf/) diff --git a/c++.html.markdown b/c++.html.markdown index 038c3900..499eb669 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp.cpp contributors: - ["Steven Basart", "https://github.com/xksteven"] @@ -158,6 +158,10 @@ namespace Second { { printf("This is Second::foo\n"); } + void bar() + { + printf("This is Second::bar\n"); + } } void foo() @@ -168,10 +172,12 @@ void foo() int main() { // Includes all symbols from namespace Second into the current scope. Note - // that simply foo() no longer works, since it is now ambiguous whether - // we're calling the foo in namespace Second or the top level. + // that while bar() works, simply using foo() no longer works, since it is + // now ambiguous whether we're calling the foo in namespace Second or the + // top level. using namespace Second; + bar(); // prints "This is Second::bar" Second::foo(); // prints "This is Second::foo" First::Nested::foo(); // prints "This is First::Nested::foo" ::foo(); // prints "This is global foo" diff --git a/c.html.markdown b/c.html.markdown index 90b5ed2d..ef341abf 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -1,16 +1,16 @@ --- -language: c +language: C filename: learnc.c contributors: - - ["Adam Bard", "http://adambard.com/"] - - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - - ["Marco Scannadinari", "https://marcoms.github.io"] - - ["Zachary Ferguson", "https://github.io/zfergus2"] - - ["himanshu", "https://github.com/himanshu81494"] - - ["Joshua Li", "https://github.com/JoshuaRLi"] - - ["Dragos B. Chirila", "https://github.com/dchirila"] - - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] + - ["Adam Bard", "http://adambard.com/"] + - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] + - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] + - ["Marco Scannadinari", "https://marcoms.github.io"] + - ["Zachary Ferguson", "https://github.io/zfergus2"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Joshua Li", "https://github.com/JoshuaRLi"] + - ["Dragos B. Chirila", "https://github.com/dchirila"] + - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -101,6 +101,12 @@ int main (int argc, char** argv) // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 + // take input using scanf + // '&' is used to define the location + // where we want to store the input value + int input; + scanf("%d", &input); + /////////////////////////////////////// // Types /////////////////////////////////////// @@ -118,7 +124,7 @@ int main (int argc, char** argv) // shorts are usually 2 bytes (use the `sizeof` operator to check) short x_short = 0; - // chars are defined as the smallest addressable unit for a processor. + // chars are defined as the smallest addressable unit for a processor. // This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes). char x_char = 0; char y_char = 'y'; // Char literals are quoted with '' @@ -167,19 +173,19 @@ int main (int argc, char** argv) // where the "{0}" part is called an "array initializer". // All elements (if any) past the ones in the initializer are initialized to 0: int my_array[5] = {1, 2}; - // So my_array now has five elements, all but the first two of which are 0: + // So my_array now has five elements, all but the first two of which are 0: // [1, 2, 0, 0, 0] - // NOTE that you get away without explicitly declaring the size + // NOTE that you get away without explicitly declaring the size // of the array IF you initialize the array on the same line: int my_array[] = {0}; - // NOTE that, when not declaring the size, the size of the array is the number + // NOTE that, when not declaring the size, the size of the array is the number // of elements in the initializer. With "{0}", my_array is now of size one: [0] // To evaluate the size of the array at run-time, divide its byte size by the // byte size of its element type: size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]); - // WARNING You should evaluate the size *before* you begin passing the array - // to functions (see later discussion) because arrays get "downgraded" to - // raw pointers when they are passed to functions (so the statement above + // WARNING You should evaluate the size *before* you begin passing the array + // to functions (see later discussion) because arrays get "downgraded" to + // raw pointers when they are passed to functions (so the statement above // will produce the wrong result inside the function). // Indexing an array is like other languages -- or, @@ -247,11 +253,11 @@ int main (int argc, char** argv) (float)i1 / i2; // => 0.5f i1 / (double)i2; // => 0.5 // Same with double f1 / f2; // => 0.5, plus or minus epsilon - + // Floating-point numbers are defined by IEEE 754, thus cannot store perfectly - // exact values. For instance, the following does not produce expected results - // because 0.1 might actually be 0.099999999999 insided the computer, and 0.3 - // might be stored as 0.300000000001. + // exact values. For instance, the following does not produce expected results + // because 0.1 might actually be 0.099999999999 inside the computer, and 0.3 + // might be stored as 0.300000000001. (0.1 + 0.1 + 0.1) != 0.3; // => 1 (true) // and it is NOT associative due to reasons mentioned above. 1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true) @@ -262,7 +268,7 @@ int main (int argc, char** argv) // eventually calls C which uses IEEE 754. It is mentioned this way not to // indicate that this is a poor implementation, but instead as a warning // that when doing floating point comparisons, a little bit of error (epsilon) - // needs to be considered. + // needs to be considered. // Modulo is there as well, but be careful if arguments are negative 11 % 3; // => 2 as 11 = 2 + 3*x (x=3) @@ -411,7 +417,7 @@ int main (int argc, char** argv) */ /* it is generally considered bad practice to do so, except if - you really know what you are doing. See + you really know what you are doing. See https://en.wikipedia.org/wiki/Spaghetti_code#Meaning */ @@ -424,7 +430,7 @@ int main (int argc, char** argv) int x_hex = 0x01; // You can assign vars with hex literals // binary is not in the standard, but allowed by some - // compilers (x_bin = 0b0010010110) + // compilers (x_bin = 0b0010010110) // Casting between types will attempt to preserve their numeric values printf("%d\n", x_hex); // => Prints 1 @@ -626,7 +632,7 @@ printf("first: %d\nsecond: %d\n", first, second); // values will be swapped */ -// Return multiple values. +// Return multiple values. // C does not allow for returning multiple values with the return statement. If // you would like to return multiple values, then the caller must pass in the // variables where they would like the returned values to go. These variables must @@ -637,9 +643,9 @@ int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3) return 0; //return error code (false) //de-reference the pointer so we modify its value - *ret1 = array_of_3[0]; - *ret2 = array_of_3[1]; - *ret3 = array_of_3[2]; + *ret1 = array_of_3[0]; + *ret2 = array_of_3[1]; + *ret3 = array_of_3[2]; return 1; //return error code (true) } @@ -901,10 +907,11 @@ Node createLinkedList(int *vals, int len); #endif /* End of the if precompiler directive. */ ``` + ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some +It is _the_ book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/) (not free). diff --git a/cairo.html.markdown b/cairo.html.markdown new file mode 100644 index 00000000..dd3ca036 --- /dev/null +++ b/cairo.html.markdown @@ -0,0 +1,864 @@ +--- +language: Cairo +filename: learnCairo.sol +contributors: + - ["Darlington Nnam", "https://github.com/Darlington02"] +--- + +# Cairo + +Cairo is a Turing-complete language that allows you write provable programs +(where one party can prove to another that a certain computation was executed +correctly) on StarkNet. + +## StarkNet + +StarkNet is a decentralized ZK-rollup that operates as an Ethereum layer 2 +chain. + +In this document, we are going to be going in-depth into understanding Cairo's +syntax and how you could create and deploy a Cairo smart contract on StarkNet. + +**NB: As at the time of this writing, StarkNet is still at v0.10.3, with Cairo +1.0 coming soon. The ecosystem is young and evolving very fast, so you might +want to check the [official docs](https://www.cairo-lang.org/docs) to confirm +this document is still up-to-date. Pull requests are welcome!** + +## Setting Up A Development Environment + +Before we get started writing codes, we will need to setup a Cairo development +environment, for writing, compiling and deploying our contracts to StarkNet. +For the purpose of this tutorial we are going to be using the +[Protostar Framework](https://github.com/software-mansion/protostar). +Installation steps can be found in the docs +[here](https://docs.swmansion.com/protostar/docs/tutorials/installation). +Note that Protostar supports just Mac and Linux OS, Windows users might need to +use WSL, or go for other alternatives such as the Official +[StarkNet CLI](https://www.cairo-lang.org/docs/quickstart.html) or +[Nile from Openzeppelin](https://github.com/OpenZeppelin/nile) + +Once you're done with the installations, run the command `protostar -v` to +confirm your installation was successful. If successful, you should see your +Protostar version displayed on the screen. + +## Initializing a new project + +Protostar similar to Truffle for solidity development can be installed once and +used for multiple projects. To initialize a new Protostar project, run the +following command: + +``` +protostar init +``` + +It would then request the project's name and the library's directory name, +you'd need to fill in this, and a new project will be initialized successfully. + +## Compiling, Declaring, Deploying and Interacting with StarkNet Contracts + +Within the `src` folder you'll find a boilerplate contract that comes with +initializing a new Protostar project, `main.cairo`. We are going to be +compiling, declaring and deploying this contract. + +### Compiling Contracts + +To compile a Cairo contract using Protostar, ensure a path to the contract is +specified in the `[contracts]` section of the `protostar.toml` file. Once +you've done that, open your terminal and run the command: + +``` +protostar build +``` + +And you should get an output similar to what you see below, with a `main.json` +and `main_abi.json` files created in the `build` folder. +<img src="./images/cairo/build.png" alt="building your contract"> + +### Declaring Contracts + +With the recent StarkNet update to 0.10.3, the DEPLOY transaction was +deprecated and no longer works. To deploy a transaction, you must first declare +a Contract to obtain the class hash, then deploy the declared contract using the +[Universal Deployer Contract](https://community.starknet.io/t/universal-deployer-contract-proposal/1864). + +Before declaring or deploying your contract using Protostar, you should set the +private key associated with the specified account address in a file, or in the +terminal. To set your private key in the terminal, run the command: + +``` +export PROTOSTAR_ACCOUNT_PRIVATE_KEY=[YOUR PRIVATE KEY HERE] +``` + +Then to declare our contract using Protostar run the following command (for +visual clarity, the backslash sign symbolizes the continuing line): + +``` +protostar declare ./build/main.json \ + --network testnet \ + --account 0x0691622bBFD29e835bA4004e7425A4e9630840EbD11c5269DE51C16774585b16 \ + --max-fee auto +``` + +where `network` specifies the network we are deploying to, `account` specifies +account whose private key we are using, `max-fee` specifies the maximum fee to +be paid for the transaction. You should get the class hash outputted as seen +below: +<img src="./images/cairo/declare.png" alt="declaring your contract"> + +### Deploying Contracts + +After obtaining our class hash from declaring, we can now deploy using the +command below: + +``` +protostar \ + deploy 0x02a5de1b145e18dfeb31c7cd7ff403714ededf5f3fdf75f8b0ac96f2017541bc \ + --network testnet \ + --account 0x0691622bBFD29e835bA4004e7425A4e9630840EbD11c5269DE51C16774585b16 \ + --max-fee auto +``` + +where `0x02a5de1b145e18dfeb31c7cd7ff403714ededf5f3fdf75f8b0ac96f2017541bc` is +the class hash of our contract. +<img src="./images/cairo/deploy.png" alt="deploying your contract"> + +### Interacting with Contracts + +To interact with your deployed contract, we will be using `Argent X` +(alternative: `Braavos`), and `Starkscan` (alternative: `Voyager`). To install +and setup `Argent X`, see this +[guide](https://www.argent.xyz/learn/how-to-create-an-argent-x-wallet/). + +Copy your contract address, displayed on screen from the previous step, and +head over to [Starkscan](https://testnet.starkscan.co/) to search for the +contract. Once found, you can make write calls to the contract in the following +sequence: + ++ click on the "connect wallet" button, + <img src="./images/cairo/connect.png" alt="connect wallet"> ++ select `Argent X` and approve the connection + <img src="./images/cairo/connect2.png" alt="connect to argentX"> ++ you can now make read and write calls easily. + +## Let's learn Cairo + +First let's look at a default contract that comes with Protostar which allows +you to set balance on deployment, increase, and get the balance. + +``` +// Language directive - instructs compiler its a StarkNet contract +%lang starknet + +// Library imports from the Cairo-lang library +from starkware.cairo.common.math import assert_nn +from starkware.cairo.common.cairo_builtins import HashBuiltin + +// @dev Storage variable that stores the balance of a user. +// @storage_var is a decorator that instructs the compiler the function +// below it is a storage variable. +@storage_var +func balance() -> (res: felt) {} + +// @dev Constructor writes the balance variable to 0 on deployment +// Constructors sets storage variables on deployment. Can accept arguments too. +@constructor +func constructor{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}() { + balance.write(0); + return(); +} + +// @dev increase_balance updates the balance variable +// @param amount the amount you want to add to balance +// @external is a decorator that specifies the func below it is an external +// function. +@external +func increase_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}(amount: felt){ + with_attr error_message("Amount must be positive. Got: {amount}.") { + assert_nn(amount); + } + + let (res) = balance.read(); + balance.write(res + amount); + return (); +} + +// @dev returns the balance variable +// @view is a decorator that specifies the func below it is a view function. +@view +func get_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}() -> (res: felt) { + let (res) = balance.read(); + return (res,); +} +``` + +Before proceeding to the main lessons, try to build, deploy and interact with +this contract. +NB: You should be at `main.cairo` if you are using Protostar. + +### 1. The Felt data type + +Unlike solidity, where you have access to various data types, Cairo comes with +just a single data type `..felts`. Felts stands for Field elements, and are a +252 bit integer in the range `0<=x<=P` where `P` is a prime number. You can +create a `Uint256` in Cairo by utlizing a struct of two 128 bits felts. + +``` +struct Uint256 { + low: felt, // The low 128 bits of the value. + high: felt, // The high 128 bits of the value. +} +``` + +To avoid running into issues with divisions, it's safer to work with the +`unsigned_div_rem` method from Cairo-lang's library. + +### 2. Lang Directive and Imports + +To get started with writing a StarkNet contract, you must specify the directive: + +``` +%lang starknet +``` + +This directive informs the compiler you are writing a contract and not a +program. The difference between both is contracts have access to StarkNet's +storage, programs don't and as such are stateless. + +There are important functions you might need to import from the official +Cairo-lang library or Openzeppelin's, e.g. + +``` +from starkware.cairo.common.cairo_builtins import HashBuiltin +from cairo_contracts.src.openzeppelin.token.erc20.library import ERC20 +from starkware.cairo.common.uint256 import Uint256 +from starkware.cairo.common.bool import TRUE +``` + +### 3. Data Structures + ++ Storage variables: Cairo's storage is a map with `2^251` slots, where each + slot is a felt which is initialized to `0`. You create one using the + `@storage_var` decorator. + + ``` + @storage_var + func names() -> (name: felt) {} + ``` + ++ Storage mappings: Unlike Solidity where mappings have a separate keyword, in + Cairo you create mappings using storage variables. + + ``` + @storage_var + func names(address: felt) -> (name: felt) {} + ``` + ++ Structs: are a means to create custom data types in Cairo. A `struct` has a + size, which is the sum of the sizes of its members. The size can be + retrieved using `MyStruct.SIZE`. You create a struct in Cairo using the + `struct` keyword. + + ``` + struct Person { + name: felt, + age: felt, + address: felt, + } + ``` + ++ Constants: Constants are fixed and as such can't be altered after being set. + They evaluate to an integer (field element) at compile time. To create a + constant in Cairo, you use the `const` keyword. It's proper practice to + capitalize constant names. + + ``` + const USER = 0x01C6cfC1DB2ae90dACEA243F0a8C2F4e32560F7cDD398e4dA2Cc56B733774E9b + ``` + ++ Arrays: Arrays can be defined as a `pointer(felt*)` to the first element of + the array. As an array is populated, its elements take up contigous memory + cells. The `alloc` keyword can be used to dynamically allocate a new memory + segment, which can be used to store an array: + + ``` + let (myArray: felt*) = alloc (); + assert myArray[0] = 1; + assert myArray[1] = 2; + assert myArray[3] = 3; + ``` + + You can also use the `new` operator to create fixed-size arrays using + tuples. The new operator is useful as it enables you allocate memory and + initialize the object in one instruction + + ``` + func foo() { + tempvar arr: felt* = new (1, 1, 2, 3, 5); + assert arr[4] = 5; + return (); + } + ``` + ++ Tuples: A tuple is a finite, ordered, unchangeable list of elements. It is + represented as a comma-separated list of elements enclosed by parentheses. + Their elements may be of any combination of valid types. + + ``` + local tuple0: (felt, felt, felt) = (7, 9, 13); + ``` + ++ Events: Events allows a contract emit information during the course of its + execution, that can be used outside of StarkNet. An event can be created, + subsequently emitted: + + ``` + @event + func name_stored(address, name) {} + + name_stored.emit(address, name); + ``` + +### 4. Constructors, External and View functions + ++ Constructors: Constructors are a way to intialize state variables on + contract deployment. You create a constructor using the `@constructor` + decorator. + + ``` + @constructor + func constructor{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, + range_check_ptr}(_name: felt) { + let (caller) = get_caller_address(); + names.write(caller, _name); + return (); + } + ``` + ++ External functions: External functions are functions that modifies the state + of the network. You create an external function using the `@external` + decorator: + + ``` + @external + func store_name{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, + range_check_ptr}(_name: felt){ + let (caller) = get_caller_address(); + names.write(caller, _name); + stored_name.emit(caller, _name); + return (); + } + ``` + ++ View functions: View functions do not modify the state of the blockchain. + You can create a view function using the `@view` decorator. + + ``` + @view + func get_name{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, + range_check_ptr}(_address: felt) -> (name: felt){ + let (name) = names.read(_address); + return (name,); + } + ``` + + NB: Unlike Solidity, Cairo supports just External and View function types. + You can alternatively also create an internal function by not adding any + decorator to the function. + +### 5. Decorators + +All functions in Cairo are specified by the `func` keyword, which can be +confusing. Decorators are used by the compiler to distinguish between these +functions. + +Here are the most common decorators you'll encounter in Cairo: + ++ `@storage_var` — used for specifying state variables. ++ `@constructor` — used for specifying constructors. ++ `@external` — used for specifying functions that write to a state variable. ++ `@event` — used for specifying events ++ `@view` — used to specify functions reading from a state variable ++ `@contract_interface` — used for specifying function interfaces. ++ `@l1_handler` — used for specifying functions that processes message sent from + an L1 contract in a messaging bridge. + +### 6. BUILTINS, HINTS & IMPLICIT Arguments + ++ `BUILTINS` are predefined optimized low-level execution units, which are + added to Cairo’s CPU board. They help perform predefined computations like + pedersen hashing, bitwise operations etc, which are expensive to perform in + Vanilla Cairo. Each builtin in Cairo is assigned a separate memory location, + accessible through regular Cairo memory calls using implicit parameters. You + specify them using the `%builtins` directive + + Here is a list of available builtins in Cairo: + + + `output` — the output builtin is used for writing program outputs + + `pedersen` — the pedersen builtin is used for pedersen hashing + computations + + `range_check` — This builtin is mostly used for integer comparisons, + and facilitates check to confirm that a field element is within a range + `[0, 2^128)` + + `ecdsa` — the ecdsa builtin is used for verifying ECDSA signatures + + `bitwise` — the bitwise builtin is used for carrying out bitwise + operations on felts + ++ `HINTS` are pieces of Python codes, which contains instructions that only + the prover sees and executes. From the point of view of the verifier these + hints do not exist. To specify a hint in Cairo, you need to encapsulate it + within `%{` and `%}`. It is good practice to avoid using hints as much as + you can in your contracts, as hints are not added to the bytecode, and thus + do not count in the total number of execution steps. + + ``` + %{ + # Python hint goes here + %} + ``` + ++ `IMPLICIT ARGUMENTS` are not restricted to the function body, but can be + inherited by other functions calls that require them. Implicit arguments are + passed in between curly bracelets, like you can see below: + + ``` + func store_name{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, + range_check_ptr}(_name: felt){ + let (caller) = get_caller_address(); + names.write(caller, _name); + stored_name.emit(caller, _name); + return (); + } + ``` + +### 7. Error Messages and Access Controls + +You can create custom errors in Cairo which is outputted to the user upon failed +execution. This can be very useful for implementing checks and proper access +control mechanisms. An example is preventing a user to call a function except +user is `admin`. + +``` +// imports +from starkware.starknet.common.syscalls import get_caller_address + +// create an admin constant +const ADMIN = 0x01C6cfC1DB2ae90dACEA243F0a8C2F4e32560F7cDD398e4dA2Cc56B733774E9b + +// implement access control +with_attr error_message("You do not have access to make this action!"){ + let (caller) = get_caller_address(); + assert ADMIN = caller; +} + +// using an assert statement throws if condition is not true, thus +// returning the specified error. +``` + +### 8. Contract Interfaces + +Contract interfaces provide a means for one contract to invoke or call the +external function of another contract. To create a contract interface, you use +the `@contract_interface` keyword: + +``` +@contract_interface + namespace IENS { + func store_name(_name: felt) { + } + + func get_name(_address: felt) -> (name: felt) { + } + } +``` + +Once a contract interface is specified, any contract can make calls to that +contract passing in the contract address as the first parameter like this: + +``` +IENS.store_name(contract_address, _name); +``` + +Note that Interfaces exclude the function body/logic and the implicit +arguments. + +### 9. Recursions + +Due to the unavailability of loops, Recursion is the go-to for similar +operations. In simple terms, a recursive function is one which calls itself +repeatedly. + +A good example to demonstrate this is writing a function for getting the nth +fibonacci number: + +``` +@external +func fibonacci{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}(n : felt) -> (result : felt){ + alloc_locals; + if (n == 0){ + return (0); + } + if (n == 1){ + return (1); + } + let (local x) = fibonacci(n - 1); + let (local y) = fibonacci(n - 2); + return (result=(x + y)); +} +``` + +The nth fibonacci term is the sum of the `nth - 1` and the `nth - 2` numbers, +that's why we get these two as `(x,y)` using recursion. + +NB: when implementing recursive functions, always remember to implement a base +case (`n==0`, `n==1` in our case), to prevent stack overflows. + +### 10. Registers + +Registers holds values that may change over time. There are 3 major types of +registers: + ++ `ap` (allocation pointer) points to a yet unused memory. Temporary variables + created using `let`, `tempvar` are held here, and thus susceptible to being + revoked. ++ `fp` (frame pointer) points to the frame of the current function. The address + of all the function arguments and local variables are relative to this + register and as such can never be revoked. ++ `pc` (program counter) points to the current instruction. + +### 11. Revoked References + +Revoked references occur when there is a call instruction to another function, +between the definition of a reference variable that depends on `ap` (temp +variables) and its usage. This occurs as the compiler may not be able to compute +the change of `ap` (as one may jump to the label from another place in the +program, or call a function that might change ap in an unknown way). + +Here is an example to demonstrate what I mean: + +``` +@external +func get_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}() -> (res: felt) { + return (res=100); +} + +@external +func double_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}() -> (res: felt) { + let multiplier = 2; + let (balance) = get_balance(); + let new_balance = balance * multiplier; + return (res=new_balance); +} +``` + +If you run that code, you'll run into the revoked reference error as we are +trying to access the `multiplier` variable after calling the `get_balance` +function. + +In simple cases you can resolve revoked references by adding the keyword +`alloc_locals` within function scopes. In more complex cases you might need to +create a local variable to resolve it. + +``` +// resolving the `double_balance` function: +@external +func double_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}() -> (res: felt) { + alloc_locals; + let multiplier = 2; + let (balance) = get_balance(); + let new_balance = balance * multiplier; + return (res=new_balance); +} +``` + +### 12. Understanding Cairo's Punctuations + ++ `;` (semicolon). Used at the end of each instruction ++ `()` (parentheses). Used in a function declaration, if statements, and in a + tuple declaration ++ `{}` (curly braces). Used in a declaration of implicit arguments and to define + code blocks. ++ `[]` (square brackets). Standalone brackets represent the value at a + particular address location (such as the allocation pointer, `[ap]`). Brackets + following a pointer or a tuple act as a subscript operator, where `x[2]` + represents the element with index `2` in `x`. ++ `*` (single asterisk). Refers to the pointer of an expression. ++ `%` (percent sign). Appears at the start of a directive, such as `%builtins` + or `%lang`. ++ `%{` and `%}` represent Python hints. ++ `_` (underscore). A placeholder to handle values that are not used, such as an + unused function return value. + +## Full Contract Example + +Below is a simple automated market maker contract example that implements most +of what we just learnt! Re-write, deploy, have fun! + +``` +%lang starknet + +from starkware.cairo.common.cairo_builtins import HashBuiltin +from starkware.cairo.common.hash import hash2 +from starkware.cairo.common.alloc import alloc +from starkware.cairo.common.math import (assert_le, assert_nn_le, + unsigned_div_rem) +from starkware.starknet.common.syscalls import (get_caller_address, + storage_read, storage_write) + + +// CONSTANTS +// +// @dev the maximum amount of each token that belongs to the AMM +const BALANCE_UPPER_BOUND = 2 ** 64; + +const TOKEN_TYPE_A = 1; +const TOKEN_TYPE_B = 2; + +// @dev Ensure the user's balances are much smaller than the pool's balance +const POOL_UPPER_BOUND = 2 ** 30; +const ACCOUNT_BALANCE_BOUND = 1073741; // (2 ** 30 / 1000) + + +// STORAGE VARIABLES +// +// @dev A map from account and token type to corresponding balance +@storage_var +func account_balance(account_id: felt, token_type: felt) -> (balance: felt) {} + +// @dev a map from token type to corresponding pool balance +@storage_var +func pool_balance(token_type: felt) -> (balance: felt) {} + + +// GETTERS +// +// @dev returns account balance for a given token +// @param account_id Account to be queried +// @param token_type Token to be queried +@view +func get_account_token_balance{syscall_ptr: felt*, pedersen_ptr: +HashBuiltin*, range_check_ptr}( + account_id: felt, token_type: felt + ) -> (balance: felt) { + return account_balance.read(account_id, token_type); +} + +// @dev return the pool's balance +// @param token_type Token type to get pool balance +@view +func get_pool_token_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}( + token_type: felt + ) -> (balance: felt) { + return pool_balance.read(token_type); +} + + +// EXTERNALS +// +// @dev set pool balance for a given token +// @param token_type Token whose balance is to be set +// @param balance Amount to be set as balance +@external +func set_pool_token_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}( + token_type: felt, balance: felt + ) { + with_attr error_message("exceeds maximum allowed tokens!"){ + assert_nn_le(balance, BALANCE_UPPER_BOUND - 1); + } + + pool_balance.write(token_type, balance); + return (); +} + +// @dev add demo token to the given account +// @param token_a_amount amount of token a to be added +// @param token_b_amount amount of token b to be added +@external +func add_demo_token{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}( + token_a_amount: felt, token_b_amount: felt + ) { + alloc_locals; + let (account_id) = get_caller_address(); + + modify_account_balance(account_id=account_id, token_type=TOKEN_TYPE_A, + amount=token_a_amount); + modify_account_balance(account_id=account_id, token_type=TOKEN_TYPE_B, + amount=token_b_amount); + + return (); +} + +// @dev intialize AMM +// @param token_a amount of token a to be set in pool +// @param token_b amount of token b to be set in pool +@external +func init_pool{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}( + token_a: felt, token_b: felt + ) { + with_attr error_message("exceeds maximum allowed tokens!"){ + assert_nn_le(token_a, POOL_UPPER_BOUND - 1); + assert_nn_le(token_b, POOL_UPPER_BOUND - 1); + } + + set_pool_token_balance(token_type=TOKEN_TYPE_A, balance=token_a); + set_pool_token_balance(token_type=TOKEN_TYPE_B, balance=token_b); + + return (); +} + + +// @dev swaps token between the given account and the pool +// @param token_from token to be swapped +// @param amount_from amount of token to be swapped +// @return amount_to the token swapped to +@external +func swap{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr}( + token_from: felt, amount_from: felt + ) -> (amount_to: felt) { + alloc_locals; + let (account_id) = get_caller_address(); + + // verify token_from is TOKEN_TYPE_A or TOKEN_TYPE_B + with_attr error_message("token not allowed in pool!"){ + assert (token_from - TOKEN_TYPE_A) * (token_from - TOKEN_TYPE_B) = 0; + } + + // check requested amount_from is valid + with_attr error_message("exceeds maximum allowed tokens!"){ + assert_nn_le(amount_from, BALANCE_UPPER_BOUND - 1); + } + + // check user has enough funds + let (account_from_balance) = + get_account_token_balance(account_id=account_id, token_type=token_from); + with_attr error_message("insufficient balance!"){ + assert_le(amount_from, account_from_balance); + } + + let (token_to) = get_opposite_token(token_type=token_from); + let (amount_to) = do_swap(account_id=account_id, token_from=token_from, + token_to=token_to, amount_from=amount_from); + + return (amount_to=amount_to); +} + + +// INTERNALS +// +// @dev internal function that updates account balance for a given token +// @param account_id Account whose balance is to be modified +// @param token_type Token type to be modified +// @param amount Amount Amount to be added +func modify_account_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}( + account_id: felt, token_type: felt, amount: felt + ) { + let (current_balance) = account_balance.read(account_id, token_type); + tempvar new_balance = current_balance + amount; + + with_attr error_message("exceeds maximum allowed tokens!"){ + assert_nn_le(new_balance, BALANCE_UPPER_BOUND - 1); + } + + account_balance.write(account_id=account_id, token_type=token_type, + value=new_balance); + return (); +} + +// @dev internal function that swaps tokens between the given account and +// the pool +// @param account_id Account whose tokens are to be swapped +// @param token_from Token type to be swapped from +// @param token_to Token type to be swapped to +// @param amount_from Amount to be swapped +func do_swap{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, +range_check_ptr}( + account_id: felt, token_from: felt, token_to: felt, amount_from: felt + ) -> (amount_to: felt) { + alloc_locals; + + // get pool balance + let (local amm_from_balance) = get_pool_token_balance(token_type = + token_from); + let (local amm_to_balance) = get_pool_token_balance(token_type=token_to); + + // calculate swap amount + let (local amount_to, _) = unsigned_div_rem((amm_to_balance * + amount_from), (amm_from_balance + amount_from)); + + // update token_from balances + modify_account_balance(account_id=account_id, token_type=token_from, + amount=-amount_from); + set_pool_token_balance(token_type=token_from, balance=(amm_from_balance + + amount_from)); + + // update token_to balances + modify_account_balance(account_id=account_id, token_type=token_to, + amount=amount_to); + set_pool_token_balance(token_type=token_to, balance=(amm_to_balance - + amount_to)); + + return (amount_to=amount_to); +} + + +// @dev internal function to get the opposite token type +// @param token_type Token whose opposite pair needs to be gotten +func get_opposite_token(token_type: felt) -> (t: felt) { + if(token_type == TOKEN_TYPE_A) { + return (t=TOKEN_TYPE_B); + } else { + return (t=TOKEN_TYPE_A); + } +} +``` + +## Additional Resources + ++ [Official documentation](https://www.cairo-lang.org/docs/) ++ [Starknet EDU](https://medium.com/starknet-edu) ++ [Journey through Cairo](https://medium.com/@darlingtonnnam/journey-through-cairo-i-setting-up-protostar-and-argentx-for-local-development-ba40ae6c5524) ++ [Demystifying Cairo whitepaper](https://medium.com/@pban/demystifying-cairo-white-paper-part-i-b71976ad0108) ++ [Learn about StarkNet with Argent](https://www.argent.xyz/learn/tag/starknet/) + +## Development Frameworks + ++ [Protostar](https://docs.swmansion.com/protostar/docs/tutorials/installation) ++ [Nile](https://github.com/OpenZeppelin/nile) ++ [StarkNet CLI](https://www.cairo-lang.org/docs/quickstart.html) + +## Helpful Libraries + ++ [Cairo-lang](https://github.com/starkware-libs/cairo-lang) ++ [Openzeppelin](https://github.com/OpenZeppelin/cairo-contracts) + +## Educational Repos + ++ [StarkNet Cairo 101](https://github.com/starknet-edu/starknet-cairo-101) ++ [StarkNet ERC721](https://github.com/starknet-edu/starknet-erc721) ++ [StarkNet ERC20](https://github.com/starknet-edu/starknet-erc20) ++ [L1 -> L2 Messaging](https://github.com/starknet-edu/starknet-messaging-bridge) ++ [StarkNet Debug](https://github.com/starknet-edu/starknet-debug) ++ [StarkNet Accounts](https://github.com/starknet-edu/starknet-accounts) ++ [Min-Starknet](https://github.com/Darlington02/min-starknet) + +## Security + ++ [Amarna static analysis for Cairo programs](https://blog.trailofbits.com/2022/04/20/amarna-static-analysis-for-cairo-programs/) ++ [Cairo and StarkNet security by Ctrl03](https://ctrlc03.github.io/) ++ [How to hack almost any Cairo smart contract](https://medium.com/ginger-security/how-to-hack-almost-any-starknet-cairo-smart-contract-67b4681ac0f6) ++ [Analyzing Cairo code using Armana](https://dic0de.substack.com/p/analyzing-cairo-code-using-amarna?sd=pf) + +## Future TO-DOs + +Update tutorial to fit Cairo 1.0 diff --git a/citron.html.markdown b/citron.html.markdown index bd3c398c..ce607ca1 100644 --- a/citron.html.markdown +++ b/citron.html.markdown @@ -68,7 +68,7 @@ False not. # True ########################################### # You may assign values to the current scope: -var name is value. # assignes `value` into `name` +var name is value. # assigns `value` into `name` # You may also assign values into the current object's namespace my name is value. # assigns `value` into the current object's `name` property @@ -146,7 +146,7 @@ add(3, 5). # 8 3 `add` 5. # 8 # This call binds as such: add[(3), 5] -# because the default fixity is left, and the default precedance is 1 +# because the default fixity is left, and the default precedence is 1 # You may change the precedence/fixity of this operator with a pragma #:declare infixr 1 add diff --git a/clojure.html.markdown b/clojure.html.markdown index 20812a9b..21d5a088 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -412,7 +412,7 @@ Clojuredocs.org has documentation with examples for most core functions: [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure is a great way to build your clojure/FP skills: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org (yes, really) has a number of getting started articles: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/cobol.html.markdown b/cobol.html.markdown index 1c858396..1350c66f 100644 --- a/cobol.html.markdown +++ b/cobol.html.markdown @@ -132,7 +132,7 @@ organizations. *Now it is time to learn about two related COBOL verbs: string and unstring. - *The string verb is used to concatenate, or put together, two or more stings. + *The string verb is used to concatenate, or put together, two or more strings. *Unstring is used, not surprisingly, to separate a *string into two or more smaller strings. *It is important that you remember to use ‘delimited by’ when you diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown index 36217414..cef8c5ab 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -33,7 +33,7 @@ Go má již v základu vynikající knihovnu a je s ním spojená nadšená komu řádkový komentář */ // Každý zdroják začíná deklarací balíčku (package) -// Main je vyhrazené jméno, které označuje spustitelný soubor, +// main je vyhrazené jméno, které označuje spustitelný soubor, // narozdíl od knihovny package main diff --git a/csharp.html.markdown b/csharp.html.markdown index c85acb1b..1d7d0881 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1,5 +1,5 @@ --- -language: c# +language: C# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] @@ -158,7 +158,7 @@ on a new line! ""Wow!"", the masses cried"; // Arrays - zero indexed // The array size must be decided upon declaration - // The format for declaring an array is follows: + // The format for declaring an array is // <datatype>[] <var name> = new <datatype>[<array size>]; int[] intArray = new int[10]; @@ -172,7 +172,7 @@ on a new line! ""Wow!"", the masses cried"; // Lists // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: + // The format for declaring a list is // List<datatype> <var name> = new List<datatype>(); List<int> intList = new List<int>(); List<string> stringList = new List<string>(); @@ -182,14 +182,14 @@ on a new line! ""Wow!"", the masses cried"; // Lists don't default to a value; // A value must be added before accessing the index intList.Add(1); - Console.WriteLine("intList @ 0: " + intList[0]); + Console.WriteLine("intList at 0: " + intList[0]); - // Others data structures to check out: + // Other data structures to check out: // Stack/Queue // Dictionary (an implementation of a hash map) // HashSet // Read-only Collections - // Tuple (.Net 4+) + // Tuple (.NET 4+) /////////////////////////////////////// // Operators @@ -222,20 +222,20 @@ on a new line! ""Wow!"", the masses cried"; | Bitwise inclusive OR */ - // Incrementations + // Incrementing int i = 0; - Console.WriteLine("\n->Inc/Dec-rementation"); - Console.WriteLine(i++); //Prints "0", i = 1. Post-Incrementation - Console.WriteLine(++i); //Prints "2", i = 2. Pre-Incrementation - Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrementation - Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrementation + Console.WriteLine("\n->Inc/Dec-rement"); + Console.WriteLine(i++); //Prints "0", i = 1. Post-Increment + Console.WriteLine(++i); //Prints "2", i = 2. Pre-Increment + Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrement + Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrement /////////////////////////////////////// // Control Structures /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // If statements are c-like + // If statements are C-like int j = 10; if (j == 10) { @@ -288,7 +288,7 @@ on a new line! ""Wow!"", the masses cried"; // For Each Loop // foreach loop structure => foreach(<iteratorType> <iteratorName> in <enumerable>) // The foreach loop loops over any object implementing IEnumerable or IEnumerable<T> - // All the collection types (Array, List, Dictionary...) in the .Net framework + // All the collection types (Array, List, Dictionary...) in the .NET framework // implement one or both of these interfaces. // (The ToCharArray() could be removed, because a string also implements IEnumerable) foreach (char character in "Hello World".ToCharArray()) @@ -297,7 +297,7 @@ on a new line! ""Wow!"", the masses cried"; } // Switch Case - // A switch works with the byte, short, char, and int data types. + // A switch works with byte, short, char, and int data types. // It also works with enumerated types (discussed in Enum Types), // the String class, and a few special classes that wrap // primitive types: Character, Byte, Short, and Integer. @@ -316,7 +316,7 @@ on a new line! ""Wow!"", the masses cried"; break; // You can assign more than one case to an action // But you can't add an action without a break before another case - // (if you want to do this, you would have to explicitly add a goto case x + // (if you want to do this, you would have to explicitly add a goto case x) case 6: case 7: case 8: @@ -337,14 +337,14 @@ on a new line! ""Wow!"", the masses cried"; // this will throw a FormatException on failure int.Parse("123"); // returns an integer version of "123" - // try parse will default to type default on failure - // in this case: 0 + // TryParse will default to the type's default value on failure + // in this case 0 int tryInt; if (int.TryParse("123", out tryInt)) // Function is boolean Console.WriteLine(tryInt); // 123 // Convert Integer To String - // Convert class has a number of methods to facilitate conversions + // The Convert class has a number of methods to facilitate conversions // String to int @@ -388,7 +388,7 @@ on a new line! ""Wow!"", the masses cried"; Console.Read(); } // End main method - // Available in C# 9 and later, this is basically a syntactic sugar for a class. Records are immutable*. + // Available in C# 9 and later, this is basically syntactic sugar for a class. Records are immutable*. public record ARecord(string Csharp); // CONSOLE ENTRY - A console application must have a main method as an entry point @@ -428,7 +428,7 @@ on a new line! ""Wow!"", the masses cried"; // GENERICS // The classes for TKey and TValue is specified by the user calling this function. - // This method emulates the SetDefault of Python + // This method emulates Python's dict.setdefault() public static TValue SetDefault<TKey, TValue>( IDictionary<TKey, TValue> dictionary, TKey key, diff --git a/de-de/asciidoc-de.html.markdown b/de-de/asciidoc-de.html.markdown index e3f64a00..f7d36b41 100644 --- a/de-de/asciidoc-de.html.markdown +++ b/de-de/asciidoc-de.html.markdown @@ -8,11 +8,15 @@ filename: asciidoc-de.md lang: de-de --- -AsciiDoc ist eine Auszeichnungssprache ähnlich zu Markdown. Sie kann für alles verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart Rackham. Die Sprache ist simpel aber sie ermöglicht eine große Anzahl an Anpassungen. +AsciiDoc ist eine Auszeichnungssprache ähnlich zu Markdown. Sie kann für alles +verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart +Rackham. Die Sprache ist simpel aber sie ermöglicht eine große Anzahl an +Anpassungen. Kopfzeile des Dokuments -Kopfzeilen sind optional und dürfen keine Leerzeilen besitzen. Sie müssen mindestens eine Leerzeile vom Inhalt versetzt sein. +Kopfzeilen sind optional und dürfen keine Leerzeilen besitzen. Sie müssen +mindestens eine Leerzeile vom Inhalt versetzt sein. Nur Titel @@ -104,7 +108,8 @@ Um eine nummerierte Liste zu erstellen, verwendest du Punkte. . item 3 ``` -Um Listen zu verschachteln, musst du zusätzliche Sternchen beziehungsweise Punkte hinzufügen. Dies ist bis zu fünf Mal möglich. +Um Listen zu verschachteln, musst du zusätzliche Sternchen beziehungsweise +Punkte hinzufügen. Dies ist bis zu fünf Mal möglich. ``` * foo 1 diff --git a/de-de/brainfuck-de.html.markdown b/de-de/brainfuck-de.html.markdown index dd62dd67..09f01cd2 100644 --- a/de-de/brainfuck-de.html.markdown +++ b/de-de/brainfuck-de.html.markdown @@ -1,11 +1,11 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["urfuchs", "https://github.com/urfuchs"] -filename: brainfuck-de +filename: brainfuck-de.bf lang: de-de --- diff --git a/de-de/c++-de.html.markdown b/de-de/c++-de.html.markdown index 87e75ad6..cca54c30 100644 --- a/de-de/c++-de.html.markdown +++ b/de-de/c++-de.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-de.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/de-de/c-de.html.markdown b/de-de/c-de.html.markdown index f9090518..3a726b83 100644 --- a/de-de/c-de.html.markdown +++ b/de-de/c-de.html.markdown @@ -1,5 +1,5 @@ --- -language: c +language: C filename: learnc-de.c contributors: - ["caminsha", "https://github.com/caminsha"] diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown index 78bb0a6b..18a23017 100644 --- a/de-de/csharp-de.html.markdown +++ b/de-de/csharp-de.html.markdown @@ -1,5 +1,5 @@ ---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 0896f513..3065a033 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -385,6 +385,4 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) - * [gitflow - Ein Modell um mit Branches zu arbeiten](http://nvie.com/posts/a-successful-git-branching-model/) diff --git a/de-de/qt-de.html.markdown b/de-de/qt-de.html.markdown index 480030fe..7d287cab 100644 --- a/de-de/qt-de.html.markdown +++ b/de-de/qt-de.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: Qt Framework -language: c++ +language: C++ filename: learnqt-de.cpp contributors: - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown index 02bb460a..6208db68 100644 --- a/de-de/rust-de.html.markdown +++ b/de-de/rust-de.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/de-de/vim-de.html.markdown b/de-de/vim-de.html.markdown index 8abf9a14..d0b4eb9d 100644 --- a/de-de/vim-de.html.markdown +++ b/de-de/vim-de.html.markdown @@ -3,95 +3,92 @@ category: tool tool: vim lang: de-de contributors: - - ["RadhikaG", "https://github.com/RadhikaG"] +- ["RadhikaG", "https://github.com/RadhikaG"] translators: - - ["caminsha", "https://github.com/caminsha"] +- ["caminsha", "https://github.com/caminsha"] filename: LearnVim-de.txt --- - [Vim](http://www.vim.org) (Vi IMproved) ist ein Klon von vi, dem bekannten Editor für Unix. Es ist ein -Texteditor, welcher mit Fokus auf Geschwindigkeit und Prouktivität entwickelt -wurde. -Vim hat viele Keybindings für ein schnelles navigieren und schnelles bearbeiten -einer Datei. +Texteditor, welcher mit Fokus auf Geschwindigkeit und Produktivität entwickelt +wurde. Vim hat viele Keybindings für ein schnelles navigieren und schnelles +bearbeiten einer Datei. ## Grundlagen, um in Vim zu navigieren ``` - vim <filename> # Öffne <filename> in Vim - :help <topic> # Open up built-in help docs about <topic> if any exists - :help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn - # es existiert - :q # Schließe vim - :w # Speichere diese Datei - :wq # Speichere diese Datei und schließe vim - ZZ # Speichere diese Datei und schließe vim - :q! # Schließe vim ohne die Datei zu speichern - # ! *zwingt* die Ausführung von :q, - # daher wird die Datei nicht gespeichert. - ZQ # Beende vim ohne die Datei zu speichern - :x # Speichere die Datei und beende vim - # Dies ist eine kürzere Version von :wq - - u # Änderung rückgängig machen - CTRL+R # Änderung wiederherstellen - - h # Den Cursor um ein Zeichen nach links bewegen - j # Den Cursor eine Zeile nach unten bewegen - k # Den Cursor eine Zeile nach oben bewegen - l # Den Cursor um ein Zeichen nach rechts bewegen - - Ctrl+B # Gehe eine Bildschirmanzeige zurück - Ctrl+F # Gehe eine Bildschirmanzeige vorwärts - Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts - Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück - - # Navigieren innerhalb einer Zeile - - 0 # Navigiere zum Anfang der Zeile - $ # Navigiere zum Ende der Zeile - ^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist - - # Im Text suchen - - /word # Hebt alle Ergebnisse nach dem Cursor hervor - ?word # Hebt alle Ergebnisse vor dem Cursor hervor - n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche - N # Bewegt den Cursor zum vorherigen Ergebnis der Suche - - :%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen - :s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile - :%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch - # ein carriage return - - # Zu einzelnen Zeichen springen - - f<character> # Springe vorwärts und auf dem Zeichen <character> - t<character> # Springe vorwärts und lande vor dem Zeichen <character> - - # Zum Beispiel, - f< # Springe vorwärts und lande auf < - t< # Springe vorwärts und lande vor < - - # Wortweise navigieren - - w # Springe um ein Wort vorwärts - b # Gehe ein Wort zurück - e # Springe zum Ende des aktuellen Wortes - - # Weitere Befehle, um zu navigieren - - gg # Gehe an den Start der Datei - G # Gehe an das Ende der Datei - :NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein) - H # Navigiere zum Start der aktuellen Bildschirmanzeige - M # Navigiere in die Mitte der aktuellen Bildschirmanzeige - L # Navigiere an das Ende der aktuellen Bildschirmanzeige +vim <filename> # Öffne <filename> in Vim +:help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn + # es existiert +:q # Schließe vim +:w # Speichere diese Datei +:wq # Speichere diese Datei und schließe vim +ZZ # Speichere diese Datei und schließe vim +:q! # Schließe vim ohne die Datei zu speichern + # ! *zwingt* die Ausführung von :q, + # daher wird die Datei nicht gespeichert. +ZQ # Beende vim ohne die Datei zu speichern +:x # Speichere die Datei und beende vim + # Dies ist eine kürzere Version von :wq + +u # Änderung rückgängig machen +CTRL+R # Änderung wiederherstellen + +h # Den Cursor um ein Zeichen nach links bewegen +j # Den Cursor eine Zeile nach unten bewegen +k # Den Cursor eine Zeile nach oben bewegen +l # Den Cursor um ein Zeichen nach rechts bewegen + +Ctrl+B # Gehe eine Bildschirmanzeige zurück +Ctrl+F # Gehe eine Bildschirmanzeige vorwärts +Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts +Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück + +# Navigieren innerhalb einer Zeile + +0 # Navigiere zum Anfang der Zeile +$ # Navigiere zum Ende der Zeile +^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist + +# Im Text suchen + +/word # Hebt alle Ergebnisse nach dem Cursor hervor +?word # Hebt alle Ergebnisse vor dem Cursor hervor +n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche +N # Bewegt den Cursor zum vorherigen Ergebnis der Suche + +:%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen +:s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile +:%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch + # ein carriage return + +# Zu einzelnen Zeichen springen + +f<character> # Springe vorwärts und auf dem Zeichen <character> +t<character> # Springe vorwärts und lande vor dem Zeichen <character> + +# Zum Beispiel, +f< # Springe vorwärts und lande auf < +t< # Springe vorwärts und lande vor < + +# Wortweise navigieren + +w # Springe um ein Wort vorwärts +b # Gehe ein Wort zurück +e # Springe zum Ende des aktuellen Wortes + +# Weitere Befehle, um zu navigieren + +gg # Gehe an den Start der Datei +G # Gehe an das Ende der Datei +:NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein) +H # Navigiere zum Start der aktuellen Bildschirmanzeige +M # Navigiere in die Mitte der aktuellen Bildschirmanzeige +L # Navigiere an das Ende der aktuellen Bildschirmanzeige ``` -## Hilfsdokumente: +## Hilfsdokumente Vim hat eine eingebaute Dokumentation, welche mit `:help <topic>` aufgerufen werden kann. @@ -99,34 +96,33 @@ Zum Beispiel öffnet `:help navigation` die Dokumentation über das Navigieren `:help` kann auch ohne ein Argument verwendet werden. Dies zeigt den Standard- Hilfsdialog an, welcher den Start mit vim einfacher macht. -that aims to make getting started with vim more approachable! -## Modi: +## Modi Vim basiert auf dem Konzept von **modes**. -- Command Mode - Vim startet in diesem Modus, hier kann man navigieren und Befehle eingeben +- Command Mode - Vims erster Modus, hier kann man navigieren und Befehle eingeben - Insert Mode - Wird verwendet, um Änderungen in der Datei zu machen. -- Visual Mode - Wird verwendet, um Text zu markieren und Operationen durchzuführen +- Visual Mode - Wird verwendet, um Text zu markieren und diesen zu verändern - Ex Mode - Wird verwendet, um im ':'-Prompt Befehle einzugeben ``` - i # Führt vim in den Insert Mode, vor der Cursorposition - a # Führt vim in den Insert Mode, nach der Cursorposition - v # Führt vim in den Visual Mode - : # Führt vim in den Ex Mode - <esc> # Führt zurück in den Command Mode, egal in welchem Mode - # man sich gerade befindet. - - # Kopieren und einfügen von Text - - y # Kopiere alles, was im Moment ausgewählt ist - yy # Kopiert die aktuelle Zeile - d # Löscht alles, was im Moment ausgewählt ist - dd # Löscht die aktuelle Zeile - p # Fügt den kopierten Text nach dem Cursor ein - P # Fügt den kopierten Text vor dem Cursor ein - x # Löscht das Zeichen unter dem Cursor +i # Führt vim in den Insert Mode, vor der Cursorposition +a # Führt vim in den Insert Mode, nach der Cursorposition +v # Führt vim in den Visual Mode +: # Führt vim in den Ex Mode +<esc> # Führt zurück in den Command Mode, egal in welchem Mode + # man sich gerade befindet. + +# Kopieren und einfügen von Text + +y # Kopiere alles, was im Moment ausgewählt ist +yy # Kopiert die aktuelle Zeile +d # Löscht alles, was im Moment ausgewählt ist +dd # Löscht die aktuelle Zeile +p # Fügt den kopierten Text nach dem Cursor ein +P # Fügt den kopierten Text vor dem Cursor ein +x # Löscht das Zeichen unter dem Cursor ``` ## Die 'Grammatik' von Vim @@ -141,68 +137,67 @@ Vim kann als Satz von Kommandos angesehen werden, welche im Format Einige wichtige Beispiele von 'Verb', 'Modifier' und 'Nouns': ``` - # 'Verb' - - d # löschen - c # ändern - y # kopieren - v # visuelles auswählen - - # 'Modifiers' - - i # innerhalb - a # außerhalb - NUM # Nummer (NUM kann irgendeine Zahl sein) - f # Sucht nach etwas und landet darauf - t # Sucht nach etwas und stoppt davor - / # Suche eine Zeichenfolge ab dem Cursor - ? # Suche eine Zeichenfolge vor dem Cursor - - # 'Nouns' - - w # Wort - s # Satz - p # Abschnitt - b # Block - - # Beispielsätze resp. Kommandos - - d2w # lösche zwei Wörter - cis # Ändere innerhalb des Satzes. - yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt, - # in welchem du bist) - ct< # Ändere bis zur spitzen Klammer - # Ändere den Text von deiner aktuellen Cursorposition bis - # zur nächsten spitzen Klammer - d$ # Lösche bis zum Ende der Zeile +# 'Verb' + +d # löschen +c # ändern +y # kopieren +v # visuelles auswählen + +# 'Modifiers' + +i # innerhalb +a # außerhalb +NUM # Nummer (NUM kann irgendeine Zahl sein) +f # Sucht nach etwas und landet darauf +t # Sucht nach etwas und stoppt davor +/ # Suche eine Zeichenfolge ab dem Cursor +? # Suche eine Zeichenfolge vor dem Cursor + +# 'Nouns' + +w # Wort +s # Satz +p # Abschnitt +b # Block + +# Beispielsätze resp. Kommandos + +d2w # lösche zwei Wörter +cis # Ändere innerhalb des Satzes. +yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt, + # in welchem du bist) +ct< # Ändere bis zur spitzen Klammer + # Ändere den Text von deiner aktuellen Cursorposition bis + # zur nächsten spitzen Klammer +d$ # Lösche bis zum Ende der Zeile ``` ## Einige Shortcuts und Tricks ``` - > # Rücke die Auswahl um einen Block ein - < # Lösche eine Einrückung der Auswahl - :earlier 15m # Stellt das Dokument so wieder her, wie es vor 15 - # Minuten war - :later 15m # den oberen Befehl rückgängig machen - ddp # Vertauschen zweier aufeinanderfolgenden Zeilen - # Zuerst dd, dann p - . # Wiederhole die vorherige Aktion - :w !sudo tee % # Speichere die Datei als Root - :set syntax=c # Stelle das Syntax-Highlighting für 'C' ein - :sort # Alle Zeilen sortieren - :sort! # Alle Zeilen rückwärts sortieren - :sort u # Alle Zeilen sortieren und Duplikate entfernen - ~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes - u # Ausgewählten Text zu Kleinschreibung ändern - U # Ausgewählten Text zu Großschreibung ändern - - # Text-Folding (Textfaltung) - zf # Erstelle eine Faltung des ausgewählten Textes - zo # Öffne die aktuelle Faltung - zc # Schließe die aktuelle Faltung - zR # Öffne alle Faltungen - zM # Schließe alle Faltungen +> # Rücke die Auswahl um einen Block ein +< # Lösche eine Einrückung der Auswahl +:earlier 15m # Stellt das Dokument so wieder her, wie es vor 15 Minuten war +:later 15m # den oberen Befehl rückgängig machen +ddp # Vertauschen zweier aufeinanderfolgenden Zeilen + # Zuerst dd, dann p +. # Wiederhole die vorherige Aktion +:w !sudo tee % # Speichere die Datei als Root +:set syntax=c # Stelle das Syntax-Highlighting für 'C' ein +:sort # Alle Zeilen sortieren +:sort! # Alle Zeilen rückwärts sortieren +:sort u # Alle Zeilen sortieren und Duplikate entfernen +~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes +u # Ausgewählten Text zu Kleinschreibung ändern +U # Ausgewählten Text zu Großschreibung ändern + +# Text-Folding (Textfaltung) +zf # Erstelle eine Faltung des ausgewählten Textes +zo # Öffne die aktuelle Faltung +zc # Schließe die aktuelle Faltung +zR # Öffne alle Faltungen +zM # Schließe alle Faltungen ``` ## Makros @@ -213,9 +208,9 @@ Kommandos, welche du braucht, aufgenommen bis die Aufnahme gestoppt wird. Wenn du ein Makro ausführst, werden exakt die gleichen Schritte gemacht. ``` - qa # Starte das Aufnehmen des Makros 'a' - q # Beende das Aufnehmen - @a # Führe das Makro 'a' aus +qa # Starte das Aufnehmen des Makros 'a' +q # Beende das Aufnehmen +@a # Führe das Makro 'a' aus ``` ### Konfigurieren mit ~/.vimrc diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index 0332c912..00e4fd94 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -112,7 +112,7 @@ python_komplexe_Zahlen: !!python/komplex 1+2j #################### # Strings und Zahlen sind nicht die einzigen Skalare, welche YAML versteht. -# ISO-formatierte Datumsangaben and Zeiangaben können ebenso geparsed werden. +# ISO-formatierte Datumsangaben and Zeitangaben können ebenso geparsed werden. DatumZeit: 2001-12-15T02:59:43.1Z DatumZeit_mit_Leerzeichen: 2001-12-14 21:59:43.10 -5 Datum: 2002-12-14 diff --git a/directx9.html.markdown b/directx9.html.markdown index b51f418d..586865c8 100644 --- a/directx9.html.markdown +++ b/directx9.html.markdown @@ -12,7 +12,7 @@ all began with Direct, such as Direct3D, DirectDraw, DirectMusic, DirectPlay, Di Direct3D (the 3D graphics API within DirectX) is widely used in the development of video games for Microsoft Windows and the Xbox line of consoles.<sup>[1]</sup> -In this tutorial we will be focusing on DirectX 9, which is not as low-level as it's sucessors, which are aimed at programmers very familiar with how graphics hardware works. It makes a great starting point for learning Direct3D. In this tutorial I will be using the Win32-API for window handling and the DirectX 2010 SDK. +In this tutorial we will be focusing on DirectX 9, which is not as low-level as it's successors, which are aimed at programmers very familiar with how graphics hardware works. It makes a great starting point for learning Direct3D. In this tutorial I will be using the Win32-API for window handling and the DirectX 2010 SDK. ## Window creation @@ -125,7 +125,7 @@ bool InitD3D(HWND hWnd) { pp.hDeviceWindow = hWnd; // associated window handle pp.Windowed = true; // display in window mode pp.Flags = 0; // no special flags - // Variable to store results of methods to check if everything succeded. + // Variable to store results of methods to check if everything succeeded. HRESULT result{ }; result = _d3d->CreateDevice(D3DADAPTER_DEFAULT, // use default graphics card D3DDEVTYPE_HAL, // use hardware acceleration @@ -144,7 +144,7 @@ bool InitD3D(HWND hWnd) { viewport.Y = 0; // .. viewport.Width = clientRect.right; // use the entire window viewport.Height = clientRect.bottom; // .. - viewport.MinZ = 0.0f; // minimun view distance + viewport.MinZ = 0.0f; // minimum view distance viewport.MaxZ = 100.0f; // maximum view distance // Apply the created viewport. result = _device->SetViewport(&viewport); @@ -157,7 +157,7 @@ bool InitD3D(HWND hWnd) { // ... // Back in our WinMain function we call our initialization function. // ... -// Check if Direct3D initialization succeded, else exit the application. +// Check if Direct3D initialization succeeded, else exit the application. if (!InitD3D(hWnd)) return -1; @@ -197,7 +197,7 @@ Let's create a vertex buffer to store the vertices for our triangle #include <vector> // First we declare a new ComPtr holding a vertex buffer. ComPtr<IDirect3DVertexBuffer9> _vertexBuffer{ }; -// Lets define a funtion to calculate the byte size of a std::vector +// Lets define a function to calculate the byte size of a std::vector template <typename T> unsigned int GetByteSize(const std::vector<T>& vec) { return sizeof(vec[0]) * vec.size(); @@ -253,7 +253,7 @@ if (!InitD3D(hWnd)) return -1; // Define the vertices we need to draw a triangle. // Values are declared in a clockwise direction else Direct3D would cull them. -// If you want to diable culling just call: +// If you want to disable culling just call: // _device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); std::vector<VStruct> vertices { // Bottom left @@ -274,7 +274,7 @@ if (!(_vertexBuffer = CreateBuffer(vertices))) Before we can use the vertex buffer to draw our primitives, we first need to set up the matrices. ```cpp -// Lets create a new funtions for the matrix transformations. +// Lets create a new functions for the matrix transformations. bool SetupTransform() { // Create a view matrix that transforms world space to // view space. @@ -338,7 +338,7 @@ if (FAILED(result)) // Create a world transformation matrix and set it to an identity matrix. D3DXMATRIX world{ }; D3DXMatrixIdentity(&world); -// Create a scalation matrix scaling our primitve by 10 in the x, +// Create a scalation matrix scaling our primitive by 10 in the x, // 10 in the y and keeping the z direction. D3DXMATRIX scaling{ }; D3DXMatrixScaling(&scaling, // matrix to scale @@ -499,7 +499,7 @@ std::vector<D3DVERTEXELEMENT9> vertexDeclDesc { 0, // byte offset from the struct beginning D3DDECLTYPE_FLOAT3, // data type (3d float vector) D3DDECLMETHOD_DEFAULT, // tessellator operation - D3DDECLUSAGE_POSTION, // usage of the data + D3DDECLUSAGE_POSITION, // usage of the data 0 }, // index (multiples usage of the same type) { 0, 12, // byte offset (3 * sizeof(float) bytes) diff --git a/docker.html.markdown b/docker.html.markdown index 1dad267a..0e61151e 100644 --- a/docker.html.markdown +++ b/docker.html.markdown @@ -1,147 +1,281 @@ ---
-language: docker
+category: tool
+tool: docker
filename: docker.bat
contributors:
- ["Ruslan López", "http://javapro.org/"]
- ["Michael Chen", "https://github.com/ML-Chen"]
+ - ["Akshita Dixit", "https://github.com/akshitadixit"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
---
-```bat
-:: download, install and run hello-world image
-docker run hello-world
-
-:: if this is the first time you should be able to see the message
-:: Unable to find image 'hello-world:latest' locally
-:: latest: Pulling from library/hello-world
-:: 1b930d010525: Pull complete
-:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
-:: Status: Downloaded newer image for hello-world:latest
-::
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-:: now let's see currently running images
-docker ps
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: let's see the images we have ran previously
-docker ps -a
-
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
-:: happy_poincare
-:: the name part is generated automatically so it probably will be different for you
-
-:: let's remove our previously generated image
-docker rm happy_poincare
-
-:: let's test if it was really deleted
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: specify a custom name for the container
-docker run --name test_container hello-world
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
-:: test_container
-:: as you can see the name is now what we have specified
-
-:: retrieve logs from a named container
-docker logs test_container
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker rm test_container
-
-docker run ubuntu
-:: Unable to find image 'ubuntu:latest' locally
-:: latest: Pulling from library/ubuntu
-:: 2746a4a261c9: Pull complete
-:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
-:: Status: Downloaded newer image for ubuntu:latest
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
-:: relaxed_nobel
-
-:: running a container in an interactive mode
-docker run -it ubuntu
-:: root@e2cac48323d2:/# uname
-:: Linux
-:: root@e2cac48323d2:/# exit
-:: exit
-
-docker rm relaxed_nobel
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
-:: nifty_goldwasser
-
-docker rm nifty_goldwasser
+Docker is a tool that helps you build, test, ship and run applications
+seamlessly across various machines. It replicates the environment our software
+needs on any machine. You can get Docker for your machine from
+https://docs.docker.com/get-docker/
+
+It has grown in popularity over the last decade due to being lightweight and
+fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker
+does not need a full blown OS of its own to be loaded to start and does not
+compete for resources other than what the application it is running will use.
+VMs on the other hand are pretty resource intensive on our processors, disks and
+memory hence running multiple VMs for various applications becomes a challenge
+in a limited capacity architecture.
+
+<pre>
+┌────────────────────────┐ ┌───────────────────────┐
+│ ┌───────────┐ │ │ ┌───────────┐ │
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ ┌───────────────────┐ │ │ ┌──────────────────┐ │
+│ │ Guest OS │ │ │ │ Guest OS │ │
+│ └───────────────────┘ │ │ └──────────────────┘ │
+│ VM1 │ │ VM2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hypervisor │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Host OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (VM based architecture)
+
+┌────────────────────────┐ ┌───────────────────────┐
+│ ┌───────────┐ │ │ ┌───────────┐ │
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ Container1 │ │ Container2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Docker │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (Docker based architecture)
+
+</pre>
+
+Couple of terms we will encounter frequently are Docker Images and Docker
+Containers. Images are packages or templates of containers all stored in a
+container registry such as [Docker Hub](https://hub.docker.com/). Containers
+are standalone, executable instances of these images which include code,
+runtime, system tools, system libraries and settings - everything required to
+get the software up and running. Coming to Docker, it follows a client-server
+architecture wherein the CLI client communicates with the server component,
+which here is, the Docker Engine using RESTful API to issue commands.
+
+## The Docker CLI
+```bash
+# after installing Docker from https://docs.docker.com/get-docker/
+# To list available commands, either run `docker` with no parameters or execute
+# `docker help`
+$ docker
+
+>>> docker [OPTIONS] COMMAND [ARG...]
+ docker [ --help | -v | --version ]
+
+ A self-sufficient runtime for containers.
+
+ Options:
+ --config string Location of client config files (default "/root/.docker")
+ -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
+ -D, --debug Enable debug mode
+ --help Print usage
+ -H, --host value Daemon socket(s) to connect to (default [])
+ -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
+ --tls Use TLS; implied by --tlsverify
+ --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
+ --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
+ --tlskey string Path to TLS key file (default "/root/.docker/key.pem")
+ --tlsverify Use TLS and verify the remote
+ -v, --version Print version information and quit
+
+ Commands:
+ attach Attach to a running container
+ # […]
+
+$ docker run hello-world
+# `docker run <container-name>` is used to run a container, it will pull the
+# images from Docker Hub if they don't already exist in your system. Here the
+# docker client connects to the daemon which in turn pulls the "hello-world"
+# image from the Docker Hub. The daemon then builds a new container from the
+# image which runs the executable that produces the output streamed back to the
+# client that we see on our terminals.
+
+$ docker run -d ubuntu sleep 60s
+# The -d (or --detach) flag is when we want to run a container in the background
+# and return back to the terminal. Here we detach an ubuntu container from the
+# terminal, the output should be the id and the command exits. If we check
+# running containers, we should still see ours there:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould
+
+$ docker run <container-id> -p 3000:8000
+# The -p (or --publish) flag is used to expose port 8000 inside the container to
+# port 3000 outside the container. This is because the app inside the container
+# runs in isolation, hence the port 8000 where the app runs is private to the
+# container.
+
+$ docker run -i
+# or
+$ docker run -it
+# Docker runs our containers in a non-interactive mode i.e. they do not accept
+# inputs or work dynamically while running. The -i flag keeps input open to the
+# container, and the -t flag creates a pseudo-terminal that the shell can attach
+# to (can be combined as -it)
+
+$ docker ps -a
+# The `docker ps` command only shows running containers by default. To see all
+# containers, use the -a (or --all) flag
+# Running the above command should output something similar in the terminal:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet
+
+
+$ docker stop hello-world
+# or
+$ docker start hello-world
+# The stop command simply stops one or more containers, and the start command
+# starts the container(s) up again! `docker start -a ubuntu` will attach our
+# detached container back to the terminal i.e. runs in the foreground
+
+$ docker create alpine
+# `docker create` creates a new container for us with the image specified (here,
+# alpine), the container does not auto-start unlike `docker run`. This command
+# is used to set up a container configuration and then `docker start` to shoot
+# it up when required. Note that the status is "Created":
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie
+
+$ docker rm 82f84
+# Removes one or more containers using their container ID.
+# P.S.: we can use only the first few characters of the entire ID to identify
+# containers
+
+$ docker images
+# Displays all images and their information, created here means the latest image
+# tag updated on Docker Hub:
+# REPOSITORY TAG IMAGE ID CREATED SIZE
+# ubuntu latest a8780b506fa4 9 days ago 77.8MB
+# alpine latest 9c6f07244728 3 months ago 5.54MB
+# hello-world latest feb5d9fea6a5 13 months ago 13.3kB
+
+$ docker rmi
+# Removes one or more images from your system which do not have their instances
+# (or containers as we know them) running. If the image has an attached
+# container, either delete the container first or use the -f (or --force) flag
+# to forcefully delete both the container and image.
+
+$ docker pull busybox
+# The pull command downloads the specified image on our system from Docker Hub.
+
+$ docker exec -it 7b272 bash
+# This command is used to run a command in the running container's default
+# directory. Here 7b272 was our ubuntu container and the above command would
+# help us interact with the container by opening a bash session.
+
+$docker logs <container-id>
+# Displays the information logged by the specified container
+# root@7b27222e4bb7:/# whoami
+# root
+# root@7b27222e4bb7:/# pwd
+# /
+# root@7b27222e4bb7:/# ls
+# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var
+# root@7b27222e4bb7:/# exit
+# exit
+
+# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/
+```
+## The Dockerfile
+The Dockerfile is a blueprint of a Docker image. We can mention the artifacts
+from our application along with their configurations into this file in the
+specific syntax to let anyone create a Docker image of our application.
+
+### A few things to keep in mind:
+* It is always strictly named `Dockerfile` without any extensions
+* We have to build our custom image on top of some already available Docker base
+image. (there is an empty image called `scratch` which literally lets you build
+an image from scratch)
+* All capitalised commands are part of the syntax, they are not case-sensitive
+but used like a convention
+* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/).
+
+```Dockerfile
+FROM <base-image>
+# define base image
+
+ENV USERNAME='admin'\
+ PWD='****'
+# optionally define environmental variables
+
+RUN apt-get update
+# run linux commands inside container env, does not affect host env
+# This executes during the time of image creation
+
+COPY <src> <target>
+# executes on the host, copies files from src (usually on the host) to target
+# on the container
+
+ENTRYPOINT ["some-script.sh"]
+# executes an entire script as an entrypoint
+
+CMD [<args>,...]
+# always part of dockerfile, introduces entry point linux command e.g.
+# `CMD node server.js`
+# This executes after image creation only when the container from the image
+# is running.
+```
+### Build your images
+Use the `docker build` command after wrapping your application into a Docker
+image to run ( or build) it.
+
+```bash
+
+$docker build <path-to-dockerfile>
+# used to build an image from the specified Dockerfile
+# instead of path we could also specify a URL
+# -t tag is optional and used to name and tag your images for e.g.
+# `$docker build -t my-image:0.1 ./home/app`
+# rebuild images everytime you make changes in the dockerfile
+```
+
+## Push your image to DockerHub
+If you want your application's Docker image to be made publicly available for
+any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a
+registry of Docker images. Make sure you have an account with a username and
+password on Docker Hub.
+
+When pushing an image to Docker Hub, we must specify our Docker Hub username
+as part of the source image name. We need to create the target image with the
+tag name of username/image-name much like GitHub repositories.
+
+```bash
+$docker login
+# to login to Docker Hub using your username and password
+
+$docker tag <src-image>[:<src-tag>] <target-image>[:<target-tag>]
+# this tags a local src-image to a public target-image
+# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app`
+# if tags are not specified, they're defaulted to `latest`
+
+$docker push <target-image>[:<target-tag>]
+# uploads our image to Docker Hub
+# e.g. `docker push akshitadixit/my-sample-app`
+# this image will be accessible under your profile's repositories as
+# `https://hub.docker.com/r/username/image-name`
+
```
diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown index 3e3c0413..ff053384 100644 --- a/dynamic-programming.html.markdown +++ b/dynamic-programming.html.markdown @@ -59,5 +59,3 @@ for i=0 to n-1 * [Optimal Substructure Property](https://www.geeksforgeeks.org/dynamic-programming-set-2-optimal-substructure-property/) * [How to solve a DP problem](https://www.geeksforgeeks.org/solve-dynamic-programming-problem/) * [How to write DP solutions](https://www.quora.com/Are-there-any-good-resources-or-tutorials-for-dynamic-programming-DP-besides-the-TopCoder-tutorial/answer/Michal-Danilák) - -And a [quiz](https://www.commonlounge.com/discussion/cdbbfe83bcd64281964b788969247253) to test your knowledge. diff --git a/erlang.html.markdown b/erlang.html.markdown index a9d280d7..62666c3a 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -1,7 +1,7 @@ --- language: erlang contributors: - - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] + - ["Giovanni Cappellotto", "http://giovanni.curlybrackets.it/"] filename: learnerlang.erl --- diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 8da8f024..725dae1d 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -11,8 +11,8 @@ lang: es-es AWK es una herramienta estándar en cada sistema UNIX compatible con POSIX. Es como un Perl restringido, perfecto para tareas de procesamiento de texto y -otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin -puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo +otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin +puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo desde un script de shell o usarlo como un lenguaje stand-alone para scripting. ¿Por qué elegir AWK sobre Perl? Principalmente, porque AWK es parte de UNIX. @@ -74,8 +74,8 @@ BEGIN { # Bloques formados por múltiples líneas usan llaves while (a < 10) { - print "La concatenación de strings se hace " " con series " - print " de" " strings separados por espacios" + print "La concatenación de strings se hace " " con series " + print " de" " strings separados por espacios" print a a++ @@ -153,13 +153,13 @@ function arithmetic_functions(a, b, c, localvar) { # Todo es global. No es problema en scripts pequeños, pero sí para # scripts más grandes. - # Hay un work-around (mmm... hack). Los argumentos de las funciones son + # Hay un work-around (mmm... hack). Los argumentos de las funciones son # locales para la función, y AWK permite definir más argumentos de función - # de los que necesita, por lo que define las variables locales en la + # de los que necesita, por lo que define las variables locales en la # declaración como en la función de arriba. Como convención, agrega - # espacios en blanco para distinguir los parámetros de la función de las - # variables locales. En este ejemplo, a, b y c son parámetros y localvar es una - # variable local. + # espacios en blanco para distinguir los parámetros de la función de las + # variables locales. En este ejemplo, a, b y c son parámetros y localvar es + # una variable local. # Ahora, a demostrar las funciones aritméticas @@ -196,7 +196,7 @@ function string_functions( localvar, arr) { # Ambas regresan el número de matches remplazados. localvar = "fooooobar" sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" - gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + gsub("e", ".", localvar) # localvar => "m..t m. at th. bar" # Buscar una cadena que haga match con una expresión regular # index() hace lo mismo, pero no permite expresiones regulares @@ -222,10 +222,10 @@ function io_functions( localvar) { # También hay printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un - # handle de archivo cuando use algo que necesite uno. El string que usaste - # para esto puede ser tratada como un handle de archivo para propósitos de I/O. - # Esto lo hace similar al scripting de shell: + # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un + # handle de archivo cuando use algo que necesite uno. El string que usaste + # para esto puede ser tratada como un handle de archivo para propósitos + # de I/O. Esto lo hace similar al scripting de shell: print "foobar" >"/tmp/foobar.txt" @@ -247,17 +247,17 @@ function io_functions( localvar) { close("/tmp/foobar.txt") } -# Como dije al inicio, los programas en AWK son una colección de patrones y +# Como dije al inicio, los programas en AWK son una colección de patrones y # acciones. Ya conociste el patrón BEGIN. otros patrones sólo se usan si estás # procesando líneas desde archivos o stdin. -# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a -# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for +# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a +# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for # implícito, iterando sobre las líneas de estos archivos. Estos patrones y # acciones son como instrucciones switch dentro del ciclo. /^fo+bar$/ { - + # Esta acción se ejecutará por cada línea que haga match con la expresión # regular /^fo+bar$/, y será saltada por cualquier línea que no haga match. # Vamos a sólo mostrar la línea: @@ -268,7 +268,7 @@ function io_functions( localvar) { # $0 es el nombre de la línea actual que se está procesando. # Se crea automáticamente para ti. - # Probablemente puedas adivinar que hay otras variables $. Cada línea es + # Probablemente puedas adivinar que hay otras variables $. Cada línea es # separada implícitamente antes de que se llame cada acción, justo como lo # hace shell. Y, como shell, cada campo puede ser accesado con $. @@ -301,7 +301,7 @@ a > 0 { # Y ya te das una idea. Procesar archivos de texto, leyendo una línea a la vez, # y haciendo algo con ella, particularmente separando en un deliminator, es tan # común en UNIX que AWK es un lenguaje de scripting que hace todo eso por ti -# sin que tengas que pedirlo. Basta con escribir los patrones y acciones +# sin que tengas que pedirlo. Basta con escribir los patrones y acciones # basados en lo que esperas de la entrada y lo quieras quieras hacer con ella. # Aquí está un ejemplo de un script simple, para lo que AWK es perfecto. @@ -343,7 +343,7 @@ $1 == name { nlines++ } -# Otro patrón especial es END. Va a ejecutarse después de procesar todos los +# Otro patrón especial es END. Va a ejecutarse después de procesar todos los # archivos de texto. A diferencia de BEGIN, sólo se ejecuta si le das dado una # entrada a procesar. Se ejecutará después de que todos los archivos hayan sido # leídos y procesados según las reglas y acciones que programaste. El propósito @@ -356,8 +356,10 @@ END { } ``` + Más información: * [Tutorial de AWK](http://www.grymoire.com/Unix/Awk.html) * [Página man de AWK](https://linux.die.net/man/1/awk) -* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): GNU Awk se encuentra en la mayoría de los sistemas Linux. +* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): + GNU Awk se encuentra en la mayoría de los sistemas Linux. diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown index 9db2c802..f624d3c7 100644 --- a/es-es/c++-es.html.markdown +++ b/es-es/c++-es.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-es.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index cae4349e..ae357d91 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -1,5 +1,5 @@ --- -language: c +language: C filename: learnc-es.c contributors: - ["Adam Bard", "http://adambard.com/"] diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown index 62935ebe..9f25425c 100644 --- a/es-es/clojure-es.html.markdown +++ b/es-es/clojure-es.html.markdown @@ -431,7 +431,7 @@ funciones principales (pertenecientes al core): [http://clojuredocs.org/quickref](http://clojuredocs.org/quickref) 4Clojure es una genial forma de mejorar tus habilidades con clojure/FP: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org (sí, de verdad) tiene un buen número de artículos con los que iniciarse en Clojure: [http://clojure-doc.org](http://clojure-doc.org) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 749365d1..dc0dda30 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -410,8 +410,6 @@ $ git rm /directorio/del/archivo/FooBar.c * [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) - * [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index e4181609..355c7f29 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -28,7 +28,7 @@ En Julia los programas están organizados entorno al [despacho múltiple](http:/ * [Buen desempeño](http://julialang.org/benchmarks), comparado al de lenguajes **estáticamente compilados** como C. * [Gestor de paquetes](http://docs.julialang.org/en/release-0.3/stdlib/pkg) integrado. * [Macros tipo Lisp](http://docs.julialang.org/en/release-0.3/manual/metaprogramming/#macros) y otras comodidades para la [meta programación](http://docs.julialang.org/en/release-0.3/manual/metaprogramming). -* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **Matlab** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)). +* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **MATLAB** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)). * [Llamar funciones de C y Fortran](http://docs.julialang.org/en/release-0.3/manual/calling-c-and-fortran-code) **directamente**: sin necesidad de usar envoltorios u APIs especiales. * Poderosas características de **línea de comandos** para [gestionar otros procesos](http://docs.julialang.org/en/release-0.3/manual/running-external-programs). * Diseñado para la [computación paralela y distribuida](http://docs.julialang.org/en/release-0.3/manual/parallel-computing) **desde el principio**. diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown index faa3dead..9290e505 100644 --- a/es-es/matlab-es.html.markdown +++ b/es-es/matlab-es.html.markdown @@ -1,5 +1,5 @@ --- -language: Matlab +language: MATLAB filename: learnmatlab-es.mat contributors: - ["mendozao", "http://github.com/mendozao"] @@ -139,7 +139,7 @@ A.d.e = false; % Vectores x = [4 32 53 7 1] -x(2) % ans = 32, los índices en Matlab comienzan 1, no 0 +x(2) % ans = 32, los índices en MATLAB comienzan 1, no 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -506,7 +506,7 @@ find(x) % Encuentra todos los elementos distintos de cero de x y devuelve sus í % Clases -% Matlab puede soportar programación orientada a objetos. +% MATLAB puede soportar programación orientada a objetos. % Las clases deben colocarse en un archivo del nombre de la clase con la extensión .m. % Para comenzar, creamos una clase simple para almacenar puntos de referencia de GPS. % Comience WaypointClass.m @@ -528,7 +528,7 @@ classdef WaypointClass % El nombre de la clase. end % Si queremos agregar dos objetos Waypoint juntos sin llamar - % a una función especial, podemos sobrecargar la aritmética de Matlab así: + % a una función especial, podemos sobrecargar la aritmética de MATLAB así: function r = plus(o1,o2) r = WaypointClass([o1.latitude] +[o2.latitude], ... [o1.longitude]+[o2.longitude]); @@ -540,7 +540,7 @@ end % Podemos crear un objeto de la clase usando el constructor a = WaypointClass(45.0, 45.0) -% Las propiedades de clase se comportan exactamente como estructuras de Matlab. +% Las propiedades de clase se comportan exactamente como estructuras de MATLAB. a.latitude = 70.0 a.longitude = 25.0 @@ -551,15 +551,15 @@ ans = multiplyLatBy(a,3) % no necesita ser pasado al método. ans = a.multiplyLatBy(a,1/3) -% Las funciones de Matlab pueden sobrecargarse para manejar objetos. -% En el método anterior, hemos sobrecargado cómo maneja Matlab +% Las funciones de MATLAB pueden sobrecargarse para manejar objetos. +% En el método anterior, hemos sobrecargado cómo maneja MATLAB % la adición de dos objetos Waypoint. b = WaypointClass(15.0, 32.0) c = a + b ``` -## Más sobre Matlab +## Más sobre MATLAB * [The official website (EN)](http://www.mathworks.com/products/matlab/) * [The official MATLAB Answers forum (EN)](http://www.mathworks.com/matlabcentral/answers/) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index 7deec286..0b21e479 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -328,7 +328,7 @@ dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} nuestro_iterable = dicc_lleno.keys() print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable -Podemos recorrerla. +# Podemos recorrerla. for i in nuestro_iterable: print(i) # Imprime uno, dos, tres @@ -388,8 +388,8 @@ keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} # Puedes hacer ambas a la vez si quieres def todos_los_argumentos(*args, **kwargs): - print args - print kwargs + print(args) + print(kwargs) """ todos_los_argumentos(1, 2, a=3, b=4) imprime: (1, 2) @@ -462,10 +462,10 @@ class Humano(object): # Instancia una clase i = Humano(nombre="Ian") -print i.decir("hi") # imprime "Ian: hi" +print(i.decir("hi")) # imprime "Ian: hi" j = Humano("Joel") -print j.decir("hello") #imprime "Joel: hello" +print(j.decir("hello")) #imprime "Joel: hello" # Llama nuestro método de clase i.get_especie() #=> "H. sapiens" @@ -548,7 +548,7 @@ def pedir(_decir): @pedir -def say(decir_por_favor=False): +def decir(decir_por_favor=False): mensaje = "¿Puedes comprarme una cerveza?" return mensaje, decir_por_favor diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown index 2b710b27..850952fa 100644 --- a/es-es/r-es.html.markdown +++ b/es-es/r-es.html.markdown @@ -16,7 +16,7 @@ LaTeX. ```r -# Los comentariso inician con símbolos numéricos. +# Los comentarios inician con símbolos numéricos. # No puedes hacer comentarios de múltiples líneas # pero puedes agrupar múltiples comentarios de esta manera. diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown index 63a47e89..8b703df1 100644 --- a/es-es/ruby-es.html.markdown +++ b/es-es/ruby-es.html.markdown @@ -89,10 +89,10 @@ true || false #=> true # Estos son usados como constructores controladores de flujo que encadenan # sentencias hasta que una de ellas retorne verdadero o falso -# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero. -has_algo() and has_otra_cosa() -# `registra_error` solo se llama si `has_algo` falla -has_algo() or registra_error() +# `haz_otra_cosa` solo se llama si `haz_algo` retorna verdadero. +haz_algo() and haz_otra_cosa() +# `registra_error` solo se llama si `haz_algo` falla +haz_algo() or registra_error() # Los strings son objetos diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown index dc48abf5..b0a3873c 100644 --- a/es-es/rust-es.html.markdown +++ b/es-es/rust-es.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index af304099..15acdbae 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -33,7 +33,7 @@ Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön. rivin kommentti */ // Package -lausekkeella aloitetaan jokainen lähdekooditiedosto. -// Main on erityinen nimi joka ilmoittaa +// main on erityinen nimi joka ilmoittaa // suoritettavan tiedoston kirjaston sijasta. package main diff --git a/fortran95.html.markdown b/fortran90.html.markdown index 5fa8ca88..2f2cfdfd 100644 --- a/fortran95.html.markdown +++ b/fortran90.html.markdown @@ -2,16 +2,16 @@ language: Fortran contributors: - ["Robert Steed", "https://github.com/robochat"] -filename: learnfortran.f95 +filename: learnfortran.f90 --- -Fortran is one of the oldest computer languages. It was developed in the 1950s -by IBM for numeric calculations (Fortran is an abbreviation of "Formula +Fortran is one of the oldest computer languages. It was developed in the 1950s +by IBM for numeric calculations (Fortran is an abbreviation of "Formula Translation"). Despite its age, it is still used for high-performance computing such as weather prediction. However, the language has changed considerably over the years, although mostly maintaining backwards compatibility; well known -versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008 and -Fortran 2015. +versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008, +Fortran 2015, and Fortran 2018. This overview will discuss the features of Fortran 95 since it is the most widely implemented of the more recent specifications and the later versions are @@ -30,29 +30,29 @@ program example !declare a program called example. ! Declaring Variables ! =================== - + ! All declarations must come before statements and expressions. - + implicit none !prevents dynamic declaration of variables (recommended!) ! Implicit none must be redeclared in every function/program/module... - + ! IMPORTANT - Fortran is case insensitive. real z REAL Z2 - real :: v,x ! WARNING: default initial values are compiler dependent! + real :: v,x ! WARNING: default initial values are compiler dependent! real :: a = 3, b=2E12, c = 0.01 integer :: i, j, k=1, m real, parameter :: PI = 3.1415926535897931 !declare a constant. logical :: y = .TRUE. , n = .FALSE. !boolean type. complex :: w = (0,1) !sqrt(-1) character (len=3) :: month !string of 3 characters. - + real :: array(6) !declare an array of 6 reals. real, dimension(4) :: arrayb !another way to declare an array. integer :: arrayc(-10:10) !an array with a custom index. real :: array2d(3,2) !multidimensional array. - + ! The '::' separators are not always necessary but are recommended. ! many other variable attributes also exist: @@ -65,8 +65,8 @@ program example !declare a program called example. ! in functions since this automatically implies the 'save' attribute ! whereby values are saved between function calls. In general, separate ! declaration and initialisation code except for constants! - - + + ! Strings ! ======= @@ -75,7 +75,7 @@ program example !declare a program called example. character (len = 30) :: str_b character (len = *), parameter :: a_long_str = "This is a long string." !can have automatic counting of length using (len=*) but only for constants. - + str_b = a_str // " keyboard" !concatenate strings using // operator. @@ -98,7 +98,7 @@ program example !declare a program called example. ! Other symbolic comparisons are < > <= >= == /= b = 4 else if (z .GT. a) then !z greater than a - ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE. + ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE. b = 6 else if (z < a) then !'then' must be on this line. b = 5 !execution block must be on a new line. @@ -145,32 +145,32 @@ program example !declare a program called example. cycle !jump to next loop iteration. enddo - + ! Goto statement exists but it is heavily discouraged though. - goto 10 + goto 10 stop 1 !stops code immediately (returning specified condition code). 10 j = 201 !this line is labeled as line 10 - - + + ! Arrays ! ====== array = (/1,2,3,4,5,6/) array = [1,2,3,4,5,6] !using Fortran 2003 notation. arrayb = [10.2,3e3,0.41,4e-5] array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2]) - + ! Fortran array indexing starts from 1. ! (by default but can be defined differently for specific arrays). v = array(1) !take first element of array. v = array2d(2,2) - + print *, array(3:5) !print all elements from 3rd to 5th (inclusive). print *, array2d(1,:) !print first column of 2d array. - + array = array*3 + 2 !can apply mathematical expressions to arrays. array = array*array !array operations occur element-wise. !array = array*array2d !these arrays would not be compatible. - + ! There are many built-in functions that operate on arrays. c = dot_product(array,array) !this is the dot product. ! Use matmul() for matrix maths. @@ -180,13 +180,13 @@ program example !declare a program called example. c = size(array) print *, shape(array) m = count(array > 0) - + ! Loop over an array (could have used Product() function normally). v = 1 do i = 1, size(array) v = v*array(i) end do - + ! Conditionally execute element-wise assignments. array = [1,2,3,4,5,6] where (array > 3) @@ -196,30 +196,30 @@ program example !declare a program called example. elsewhere array = 0 end where - + ! Implied-DO loops are a compact way to create arrays. array = [ (i, i = 1,6) ] !creates an array of [1,2,3,4,5,6] array = [ (i, i = 1,12,2) ] !creates an array of [1,3,5,7,9,11] array = [ (i**2, i = 1,6) ] !creates an array of [1,4,9,16,25,36] array = [ (4,5, i = 1,3) ] !creates an array of [4,5,4,5,4,5] - + ! Input/Output ! ============ - + print *, b !print the variable 'b' to the command line ! We can format our printed output. print "(I6)", 320 !prints ' 320' - print "(I6.4)", 3 !prints ' 0003' + print "(I6.4)", 3 !prints ' 0003' print "(F6.3)", 4.32 !prints ' 4.320' - - ! The letter indicates the expected type and the number afterwards gives + + ! The letter indicates the expected type and the number afterwards gives ! the number of characters to use for printing the value. - ! Letters can be I (integer), F (real), E (engineering format), + ! Letters can be I (integer), F (real), E (engineering format), ! L (logical), A (characters) ... print "(I3)", 3200 !print '***' since the number doesn't fit. - + ! we can have multiple format specifications. print "(I5,F6.2,E6.2)", 120, 43.41, 43.41 print "(3I5)", 10, 20, 30 !3 repeats of integers (field width = 5). @@ -230,7 +230,7 @@ program example !declare a program called example. read "(2F6.2)", v, x !read two numbers ! To read a file. - open(unit=11, file="records.txt", status="old") + open(unit=11, file="records.txt", status="old") ! The file is referred to by a 'unit number', an integer that you pick in ! the range 9:99. Status can be one of {'old','replace','new'}. read(unit=11, fmt="(3F10.2)") a, b, c @@ -241,39 +241,39 @@ program example !declare a program called example. write(12, "(F10.2,F10.2,F10.2)") c, b, a close(12) - ! There are more features available than discussed here and alternative + ! There are more features available than discussed here and alternative ! variants due to backwards compatibility with older Fortran versions. - - + + ! Built-in Functions ! ================== ! Fortran has around 200 functions/subroutines intrinsic to the language. - ! Examples - + ! Examples - call cpu_time(v) !sets 'v' to a time in seconds. k = ior(i,j) !bitwise OR of 2 integers. v = log10(x) !log base 10. i = floor(b) !returns the closest integer less than or equal to x. v = aimag(w) !imaginary part of a complex number. - + ! Functions & Subroutines ! ======================= - + ! A subroutine runs some code on some input values and can cause ! side-effects or modify the input values. - + call routine(a,c,v) !subroutine call. - + ! A function takes a list of input parameters and returns a single value. - ! However the input parameters may still be modified and side effects + ! However the input parameters may still be modified and side effects ! executed. - + m = func(3,2,k) !function call. - + ! Function calls can also be evoked within expressions. - Print *, func2(3,2,k) - + Print *, func2(3,2,k) + ! A pure function is a function that doesn't modify its input parameters ! or cause any side-effects. m = func3(3,2,k) @@ -297,7 +297,7 @@ contains ! Zone for defining sub-programs internal to the program. function func2(a,b,c) result(f) !return variable declared to be 'f'. implicit none - integer, intent(in) :: a,b !can declare and enforce that variables + integer, intent(in) :: a,b !can declare and enforce that variables !are not modified by the function. integer, intent(inout) :: c integer :: f !function return type declared inside the function. @@ -328,14 +328,14 @@ contains ! Zone for defining sub-programs internal to the program. end program example ! End of Program Definition ----------------------- -! Functions and Subroutines declared externally to the program listing need +! Functions and Subroutines declared externally to the program listing need ! to be declared to the program using an Interface declaration (even if they ! are in the same source file!) (see below). It is easier to define them within ! the 'contains' section of a module or program. elemental real function func4(a) result(res) ! An elemental function is a Pure function that takes a scalar input variable -! but can also be used on an array where it will be separately applied to all +! but can also be used on an array where it will be separately applied to all ! of the elements of an array and return a new array. real, intent(in) :: a res = a**2 + 1.0 @@ -345,7 +345,7 @@ end function func4 ! Modules ! ======= -! A module is a useful way to collect related declarations, functions and +! A module is a useful way to collect related declarations, functions and ! subroutines together for reusability. module fruit @@ -358,7 +358,7 @@ end module fruit module fruity ! Declarations must be in the order: modules, interfaces, variables. ! (can declare modules and interfaces in programs too). - + use fruit, only: apple, pear ! use apple and pear from fruit module. implicit none !comes after module imports. @@ -367,7 +367,7 @@ module fruity public :: apple,mycar,create_mycar ! Declare some variables/functions private to the module (redundant here). private :: func4 - + ! Interfaces ! ========== ! Explicitly declare an external function/procedure within the module @@ -377,14 +377,14 @@ module fruity real, intent(in) :: a end function func4 end interface - + ! Overloaded functions can be defined using named interfaces. interface myabs ! Can use 'module procedure' keyword to include functions already ! defined within the module. module procedure real_abs, complex_abs - end interface - + end interface + ! Derived Data Types ! ================== ! Can create custom structured data collections. @@ -394,19 +394,19 @@ module fruity real :: dimensions(3) !i.e. length-width-height (metres). character :: colour end type car - + type(car) :: mycar !declare a variable of your custom type. ! See create_mycar() routine for usage. - + ! Note: There are no executable statements in modules. - + contains subroutine create_mycar(mycar) ! Demonstrates usage of a derived data type. implicit none type(car),intent(out) :: mycar - + ! Access type elements using '%' operator. mycar%model = "Ford Prefect" mycar%colour = 'r' @@ -414,7 +414,7 @@ contains mycar%dimensions(1) = 5.0 !default indexing starts from 1! mycar%dimensions(2) = 3.0 mycar%dimensions(3) = 1.5 - + end subroutine real function real_abs(x) @@ -425,7 +425,7 @@ contains real_abs = x end if end function real_abs - + real function complex_abs(z) complex :: z ! long lines can be continued using the continuation character '&' diff --git a/fr-fr/awk-fr.html.markdown b/fr-fr/awk-fr.html.markdown index 75c48811..a5db24b2 100644 --- a/fr-fr/awk-fr.html.markdown +++ b/fr-fr/awk-fr.html.markdown @@ -10,37 +10,49 @@ lang: fr-fr --- -AWK est un outil standard présent dans chaque système UNIX conforme aux normes POSIX. -C’est un outil en ligne de commande qui ressemble au Perl et qui est excellent dans les tâches de traitement de fichiers texte. -Vous pouvez l’appeler à partir d’un script shell, ou l’utiliser comme un langage de script autonome. +AWK est un outil standard présent dans chaque système UNIX conforme aux normes +POSIX. C’est un outil en ligne de commande qui ressemble au Perl et qui est +excellent dans les tâches de traitement de fichiers texte. +Vous pouvez l’appeler à partir d’un script shell, ou l’utiliser comme un langage +de script autonome. Pourquoi utiliser AWK au lieu du langage Perl ? -Principalement, car AWK fait partie d'UNIX et est donc présent par défaut sur une très grande partie des systèmes d'exploitation UNIX et Linux. -AWK est aussi plus facile à lire que le langage Perl ; et est l'outil idéal pour ce qui concerne le traitement de texte simple. Notamment le traitement de ceux qui necéssitent de lire des fichiers ligne par ligne ; chaque ligne comportant des champs séparés par des délimiteur. - +Principalement, car AWK fait partie d'UNIX et est donc présent par défaut sur +une très grande partie des systèmes d'exploitation UNIX et Linux. +AWK est aussi plus facile à lire que le langage Perl ; et est l'outil idéal pour +ce qui concerne le traitement de texte simple. Notamment le traitement de ceux +qui nécessitent de lire des fichiers ligne par ligne ; chaque ligne comportant +des champs séparés par des délimiteur. ```awk #!/usr/bin/awk -f # Les commentaires commencent par un # - -# les programmes AWK consistent en une collection de règles et d'actions +# Les programmes AWK consistent en une collection de règles et d'actions. règle1 { action; } règle2 { action; } # AWK lit et analyse automatiquement chaque ligne de chaque fichier fourni. -# Chaque ligne est divisée par un délimiteur FS qui est par défaut l'espace (plusieurs espaces ou une tabulation comptent pour un espace). Ce délimiteur peut être changer grâce à l'option -F ou être renseigné au début d'un bloc (exemple: FS = " "). - -# BEGIN est une règle spécifique exécutée au début du programme. C'est à cet endroit que vous mettrez tout le code à exécuter avant de traiter les fichiers texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le point d’entrée principal du script. -# A l'opposé de BEGIN, il existe la règle END. Cette règle est présente après chaque fin de fichier (EOF : End Of File). +# Chaque ligne est divisée par un délimiteur FS qui est par défaut l'espace +# (plusieurs espaces ou une tabulation comptent pour un espace). Ce délimiteur +# peut être changé grâce à l'option -F ou être renseigné au début d'un bloc +# (exemple: FS = " "). + +# BEGIN est une règle spécifique exécutée au début du programme. C'est à cet +# endroit que vous mettrez tout le code à exécuter avant de traiter les fichiers +# texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le +# point d’entrée principal du script. +# À l'opposé de BEGIN, il existe la règle END. Cette règle est présente après +# chaque fin de fichier (EOF : End Of File). BEGIN { # Les variables sont globales. Pas besoin de les déclarer. count = 0; - # les opérateurs sont identiques au langage C et aux langages similaires (exemple: C#, C++) + # Les opérateurs sont identiques au langage C et aux langages similaires + # (tels que C#, C++, etc.) a = count + 1; # addition b = count - 1; # soustraction c = count * 1; # multiplication @@ -59,7 +71,8 @@ BEGIN { a++; b--; - # En tant qu'opérateur préfixé, c'est la valeur incrémentée qui est retournée + # En tant qu'opérateur préfixé, c'est la valeur incrémentée qui + # est retournée ++a; --b; @@ -74,7 +87,8 @@ BEGIN { # Les blocs sont composés d'une multitude de lignes entre accolades while (a < 10) { - print "La concaténation de chaînes de caractères" " se fait avec des séries de chaînes " " séparées par des espaces"; + print "La concaténation de chaînes de caractères" " se fait avec" + "des séries de chaînes " "séparées par des espaces"; print a; a++; @@ -106,14 +120,14 @@ BEGIN { arr[1] = "bar"; # Vous pouvez aussi initialiser un tableau avec la fonction split() - n = split("foo:bar:baz", arr, ":"); # Il y a aussi les tableaux associatifs assoc["foo"] = "bar"; assoc["bar"] = "baz"; - # et les tableaux multi-dimentions, avec certaines limitations que l'on ne mentionnera pas ici + # et les tableaux multi-dimensions, avec certaines limitations que l'on ne + # mentionnera pas ici multidim[0,0] = "foo"; multidim[0,1] = "bar"; multidim[1,0] = "baz"; @@ -123,7 +137,8 @@ BEGIN { if ("foo" in assoc) print "Fooey!"; - # Vous pouvez aussi utilisez l'opérateur 'in' pour parcourir les clés d'un tableau + # Vous pouvez aussi utilisez l'opérateur 'in' pour parcourir les clés + # d'un tableau for (key in assoc) print assoc[key]; @@ -131,16 +146,16 @@ BEGIN { for (argnum in ARGV) print ARGV[argnum]; - # Vous pouvez supprimer des éléments d'un tableau - # C'est utile pour empêcher AWK de supposer que certains arguments soient des fichiers à traiter. + # Vous pouvez supprimer des éléments d'un tableau. + # C'est utile pour empêcher AWK de supposer que certains arguments soient + # des fichiers à traiter. delete ARGV[1]; - # Le nombre d'arguments de la ligne de commande est dans une variable appellée ARGC + # Le nombre d'arguments de la ligne de commande est assigné à + # la variable ARGC print ARGC; - # AWK inclue trois catégories de fonction. - # On les examinera plus tard - + # AWK inclue trois catégories de fonction. On les examinera plus tard. return_value = arithmetic_functions(a, b, c); string_functions(); io_functions(); @@ -149,22 +164,24 @@ BEGIN { # Voici comment définir une fonction function arithmetic_functions(a, b, c, d) { - # La partie la plus ennuieuse de AWK est probablement l’absence de variables locales. - # Tout est global. Pour les scripts courts, c'est très utile, mais pour les scripts plus longs, - # cela peut poser problème. + # La partie la plus ennuyeuse de AWK est probablement l’absence de variables + # locales. Tout est global. Pour les scripts courts, c'est très utile, mais + # pour les scripts plus longs, cela peut poser un problème. - # Il y a cepandant une solution de contournement (enfin ... une bidouille). + # Il y a cependant une solution de contournement (enfin ... une bidouille). # Les arguments d'une fonction sont locaux à cette fonction. - # Et AWK vous permet de définir plus d'arguments à la fonction que nécessaire. - # Il suffit donc de mettre une variable locale dans la déclaration de fonction, - # comme ci-dessus. La convention veut que vous mettiez quelques espaces supplémentaires - # pour faire la distinction entre les paramètres réels et les variables locales. - # Dans cet exemple, a, b et c sont des paramètres réels, - # alors que d est simplement une variable locale. + # Et AWK vous permet de définir plus d'arguments à la fonction que + # nécessaire. Il suffit donc de mettre une variable locale dans la + # déclaration de fonction, comme ci-dessus. La convention veut que vous + # mettiez quelques espaces supplémentaires pour faire la distinction entre + # les paramètres réels et les variables locales. + # Dans cet exemple, a, b et c sont des paramètres réels, alors que d est + # simplement une variable locale. # Maintenant, les fonctions arithmétiques - # La plupart des implémentations de AWK ont des fonctions trigonométriques standards + # La plupart des implémentations de AWK ont des fonctions trigonométriques + # standards localvar = sin(a); localvar = cos(a); localvar = atan2(b, a); # arc tangente de b / a @@ -180,10 +197,10 @@ function arithmetic_functions(a, b, c, d) { localvar = int(5.34); # localvar => 5 # Les nombres aléatoires - srand(); + srand(); # L'argument de la fonction srand() est la valeur de départ pour générer # les nombres aléatoires . Par défaut, il utilise l'heure du système - + localvar = rand(); # Nombre aléatoire entre 0 et 1. # Maintenant on retourne la valeur @@ -195,18 +212,21 @@ function string_functions( localvar, arr) { # AWK a plusieurs fonctions pour le traitement des chaînes de caractères, # dont beaucoup reposent sur des expressions régulières. - # Chercher et remplacer, la première occurence (sub) ou toutes les occurences (gsub) + # Chercher et remplacer, la première occurrence (sub), ou toutes les + # occurrences (gsub). # Les deux renvoient le nombre de correspondances remplacées localvar = "fooooobar"; sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar" - gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar" + gsub("e", ".", localvar); # localvar => "m..t m. at th. bar" - # Rechercher une chaîne de caractères qui correspond à une expression régulière - # index() fait la même chose, mais n'autorise pas les expressions régulières + # Rechercher une chaîne de caractères qui correspond à une expression + # régulière index() fait la même chose, mais n'autorise pas les expressions + # régulières. match(localvar, "t"); # => 4, puisque 't' est le quatrième caractère # Séparer par un délimiteur - n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 + n = split("foo-bar-baz", arr, "-"); + # résultat : a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 # Autre astuces utiles sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3" @@ -226,26 +246,25 @@ function io_functions( localvar) { printf("%s %d %d %d\n", "Testing", 1, 2, 3); # AWK n'a pas de descripteur de fichier en soi. Il ouvrira automatiquement - # un descripteur de fichier lorsque vous utilisez quelque chose qui en a besoin. - # La chaîne de caractères que vous avez utilisée pour cela peut être traitée - # comme un descripteur de fichier à des fins d'entrée / sortie. - + # un descripteur de fichier lorsque vous utilisez quelque chose qui en a + # besoin. La chaîne de caractères que vous avez utilisée pour cela peut être + # traitée comme un descripteur de fichier à des fins d'entrée / sortie. outfile = "/tmp/foobar.txt"; - print "foobar" > outfile; - # Maintenant, la chaîne de caractères "outfile" est un descripteur de fichier. - # Vous pouvez le fermer + # Maintenant, la chaîne de caractères "outfile" est un descripteur de + # fichier. Vous pouvez le fermer. close(outfile); # Voici comment exécuter quelque chose dans le shell system("echo foobar"); # => affiche foobar - # Lire quelque chose depuis l'entrée standard et la stocker dans une variable locale + # Lire quelque chose depuis l'entrée standard et la stocker dans une + # variable locale getline localvar; - # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une chaine de caractère - # que vous fermerez proprement) + # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une + # chaîne de caractère que vous fermerez proprement) "echo foobar" | getline localvar # localvar => "foobar" close("echo foobar") @@ -256,33 +275,36 @@ function io_functions( localvar) { } # Comme dit au début, AWK consiste en une collection de règles et d'actions. -# Vous connaissez déjà les règles BEGIN et END. Les autres règles ne sont utilisées que si vous traitez -# des lignes à partir de fichiers ou l'entrée standard (stdin). -# Quand vous passez des arguments à AWK, ils sont considérés comme des noms de fichiers à traiter. -# AWK les traitera tous dans l'ordre. Voyez les comme dans à une boucle implicite, -# parcourant les lignes de ces fichiers. -# Ces règles et ces actions ressemblent à des instructions switch dans la boucle. +# Vous connaissez déjà les règles BEGIN et END. Les autres règles ne sont +# utilisées que si vous traitez des lignes à partir de fichiers ou l'entrée +# standard (stdin). +# Quand vous passez des arguments à AWK, ils sont considérés comme des noms de +# fichiers à traiter. AWK les traitera tous dans l'ordre. Voyez les comme dans +# une boucle implicite, parcourant les lignes de ces fichiers. Ces règles et ces +# actions ressemblent à des instructions switch dans la boucle. /^fo+bar$/ { - # Cette action sera exécutée pour chaque ligne qui correspond à l'expression régulière, - # /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond pas. - # Imprimons simplement la ligne: + # Cette action sera exécutée pour chaque ligne qui correspond à l'expression + # régulière, /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond + # pas. Imprimons simplement la ligne : print; # Pas d'argument ! C'est parce que print a un défaut : $0. - # $0 est le nom de la ligne en cours de traitement. Il est créé automatiquement. + # $0 est le nom de la ligne en cours de traitement. Il est créé + # automatiquement. # Vous devinez probablement qu'il existe d'autres variables $. - # Chaque ligne est divisée implicitement avant que chaque action soit exécutée, comme - # le fait le shell. Et, comme le shell, chaque champ est accessible avec un signe dollar + # Chaque ligne est divisée implicitement avant que chaque action soit + # exécutée, comme le fait le shell. Et, comme le shell, chaque champ est + # accessible avec un signe dollar. - # Ceci affichera les deuxième et quatrième champs de la ligne. + # Ceci affichera les deuxième et quatrième champs de la ligne. print $2, $4; - # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous aider - # à inspecter et traiter chaque ligne. La plus importante est NF + # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous + # aider à inspecter et traiter chaque ligne. La plus importante est NF. # Affiche le nombre de champs de la ligne print NF; @@ -291,33 +313,33 @@ function io_functions( localvar) { print $NF; } -# Chaque règle est en réalité un test conditionel. - +# Chaque règle est en réalité un test conditionnel. a > 0 { # Ceci s’exécutera une fois pour chaque ligne, tant que le test est positif } -# Les expressions régulières sont également des tests conditionels. -#Si le test de l'expression régulières n'est pas vrais alors le bloc n'est pas executé -$0 /^fobar/ { - print "la ligne commance par fobar" +# Les expressions régulières sont également des tests conditionnels. +# Si le test de l'expression régulières n'est pas vrais alors le bloc +# n'est pas exécuté. +$0 /^fobar/ { + print "la ligne commence par foobar" } -# Dans le cas où vous voulez tester votre chaine de caractères sur la ligne en cours de traitement -# $0 est optionnelle. - +# Dans le cas où vous voulez tester votre chaîne de caractères sur la ligne +# en cours de traitement $0 est optionnelle. /^[a-zA-Z0-9]$/ { print "La ligne courante ne contient que des caractères alphanumériques."; } +# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en +# fonction de règles établies. Cela est si courant sous UNIX qu'AWK est un +# langage de script. -# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en fonction de règles établies -# Cela est si courant sous UNIX qu'AWK est un langage de script. - -# Ce qui suit est un exemple rapide d'un petit script, pour lequel AWK est parfait. -# Le script lit un nom à partir de l'entrée standard, puis affiche l'âge moyen de toutes les -# personnes portant ce prénom. -# Supposons que vous fournissiez comme argument le nom d'un fichier comportant ces données: +# Ce qui suit est un exemple rapide d'un petit script, pour lequel AWK est +# parfait. Le script lit un nom à partir de l'entrée standard, puis affiche +# l'âge moyen de toutes les personnes portant ce prénom. +# Supposons que vous fournissiez comme argument le nom d'un fichier comportant +# ces données : # # Bob Jones 32 # Jane Doe 22 @@ -330,24 +352,26 @@ $0 /^fobar/ { BEGIN { # Premièrement, on demande à l'utilisateur le prénom voulu - print "Pour quel prénom vouldriez vous savoir l'age moyen ?"; + print "Pour quel prénom voudriez vous savoir l'age moyen ?"; - # On récupère la ligne à partir de l'entrée standard, pas de la ligne de commande + # On récupère la ligne à partir de l'entrée standard, pas de la ligne + # de commande : getline name < "/dev/stdin"; } # Maintenant, pour chaque ligne dont le premier champ est le prénom donné $1 == name { - # Ici, nous avons accès à un certain nombre de variables utiles déjà préchargées : + # Ici, nous avons accès à un certain nombre de variables utiles déjà + # préchargées : # $0 est la ligne entière # $3 est le troisième champ. Ici il correspond à l'age qui nous intéresse # NF est le nombre de champs et vaut 3 # NR est le nombre d'enregistrements (lignes) vus jusqu'à présent # FILENAME est le nom du fichier en cours de traitement # FS est séparateur de champs, ici c'est " " (un espace) - # ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de man. - # Pour cela exécutez "man awk" dans votre terminal + # ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de + # man. Pour cela exécutez "man awk" dans votre terminal. # Garder une trace du total accumulé et du nombre de lignes correspondant. sum += $3; @@ -358,9 +382,9 @@ $1 == name { # les fichiers texte. Contrairement à BEGIN, il ne fonctionne que si vous lui # donnez une entrée à traiter. Il sera exécuté une fois que tous les fichiers # auront été lus et traités conformément aux règles et aux actions que vous -# avez fournies. Le but est généralement de produire un rapport final -# ou de faire quelque chose avec l'ensemble des données que vous avez -# accumulées au cours du script. +# avez fournies. Le but est généralement de produire un rapport final, ou de +# faire quelque chose avec l'ensemble des données que vous avez accumulées +# au cours du script. END { @@ -369,9 +393,11 @@ END { } ``` + Pour plus d'informations : * [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) * [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk est dans la majorité des systèmes Linux. +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) + GNU Awk est dans la majorité des systèmes Linux. * [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html) diff --git a/fr-fr/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown index c8603756..b96d0ad0 100644 --- a/fr-fr/c++-fr.html.markdown +++ b/fr-fr/c++-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-fr.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index 65747c0d..6215e0cf 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -427,7 +427,7 @@ plupart des fonctions principales : 4Clojure est une super manière d'augmenter vos compétences en Clojure et en programmation fonctionnelle : -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org a pas mal d'article pour débuter : [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index 58b3f386..b3bf9c3b 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: c# +language: C# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown index 510459fe..00b6b6e1 100644 --- a/fr-fr/git-fr.html.markdown +++ b/fr-fr/git-fr.html.markdown @@ -574,8 +574,6 @@ $ git rm /chemin/vers/le/fichier/HelloWorld.c * [SalesForce Cheat Sheet (EN)](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) -* [GitGuys (EN)](http://www.gitguys.com/) - * [Git - the simple guide (EN)](http://rogerdudler.github.io/git-guide/index.html) * [Livre Pro Git](http://www.git-scm.com/book/fr/v1) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 9d8bef70..38cc3b52 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -32,7 +32,7 @@ communauté active. multiligne */ // Un paquet débute avec une clause "package" -// "Main" est un nom spécial déclarant un paquet de type exécutable plutôt +// "main" est un nom spécial déclarant un paquet de type exécutable plutôt // qu'une bibliothèque package main diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 186859ab..308f1ca8 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -94,7 +94,7 @@ let banta = "Harry", santa = "Hermione"; // L'égalité est === ou == // === compare la valeur exacte 2 === '2' // = false -// == convertit la valeur pour comparer 2 === '2' // = true +// == convertit la valeur pour comparer 2 == '2' // = true // En général, il vaut mieux utiliser === pour ne pas faire d'erreur. 1 === 1; // = true 2 === 1; // = false diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown index a61f78be..6fc0d07d 100644 --- a/fr-fr/rust-fr.html.markdown +++ b/fr-fr/rust-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: @@ -309,7 +309,7 @@ fn main() { Il y a beaucoup plus à Rust -- ce est juste l'essentiel de Rust afin que vous puissiez comprendre les choses les plus importantes. Pour en savoir plus sur Rust, lire [La Programmation Rust -Langue](http://doc.rust-lang.org/book/index.html) et etudier la +Langue](http://doc.rust-lang.org/book/index.html) et étudier la [/r/rust](http://reddit.com/r/rust) subreddit. Les gens sur le canal de #rust sur irc.mozilla.org sont aussi toujours prêts à aider les nouveaux arrivants. diff --git a/fr-fr/set-theory-fr.html.markdown b/fr-fr/set-theory-fr.html.markdown index 50a4ea30..d1ac2711 100644 --- a/fr-fr/set-theory-fr.html.markdown +++ b/fr-fr/set-theory-fr.html.markdown @@ -1,11 +1,11 @@ -``` --- -category: tool -lang: fr-fr +category: Algorithms & Data Structures name: Set theory +lang: fr-fr contributors: - - ["kieutrang", "https://github.com/kieutrang1729"] + - ["kieutrang", "https://github.com/kieutrang1729"] --- + La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés. * Un ensemble est une collection d'éléments disjoints. @@ -32,9 +32,9 @@ La théorie des ensembles est une branche des mathématiques qui étudie les ens * `ℚ`, l'ensemble des nombres rationnels ; * `ℝ`, l'ensemble des nombres réels. -Quelques mise en gardes sur les ensembles definis ci-dessus: +Quelques mise en gardes sur les ensembles définis ci-dessus: 1. Même si l'ensemble vide ne contient aucun élément, il est lui-même un sous-ensemble de n'importe quel ensemble. -2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitment si l'auteur considère le zéro comme nombre naturel ou pas. +2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitement si l'auteur considère le zéro comme nombre naturel ou pas. ### Cardinalité @@ -43,7 +43,7 @@ La cardinalité, ou taille, d'un ensemble est déterminée par le nombre d'élé Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`. ### L'ensemble vide -* L'ensemble vide peut se définir en comprehension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`. +* L'ensemble vide peut se définir en compréhension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`. * il n'y a qu'un seul ensemble vide. * l'ensemble vide est sous-ensemble de tout ensemble. * la cardinalité de l'ensemble vide est 0, ou `|∅| = 0`. @@ -54,9 +54,9 @@ Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`. Un ensemble peut être defini en extension par une liste de tous les éléments qui sont contenus dans l'ensemble. Par exemple, `S = { a, b, c, d }`. -Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatres premiers. +Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatre premiers. -### Définition par comprehension +### Définition par compréhension C'est une notation plus descriptif qui permet de définir un ensemble à l'aide d'un sujet et d'une propriété, et il est noté `S = { sujet : propriété }`. Par exemple, @@ -76,18 +76,18 @@ D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... } ### Appartenance -* Si l'élement `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`. -* Si l'élement `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`. +* Si l'élément `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`. +* Si l'élément `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`. ### Égalité * On dit que deux ensembles `A` et `B` sont égaux s'ils contiennent les mêmes éléments, et on le note `A = B`. * Les ensembles n'ont pas de notion d'ordre, par exemple `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`. * Un élément ne peut apparaître qu'au plus une seule fois - il n'y a jamais de répétition, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`. -* Deux ensembles `A` and `B` sont égaux si et seulement si `A ⊆ B` and `B ⊆ A`. +* Deux ensembles `A` et `B` sont égaux si et seulement si `A ⊆ B` et `B ⊆ A`. ## Ensemble puissance -* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité d'`A` est `n`, la cardinalité de `P(A)` est `2^n`. +* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité de `A` est `n`, la cardinalité de `P(A)` est `2^n`. ``` P(A) = { x : x ⊆ A } @@ -125,10 +125,8 @@ A △ B = (A \ B) ∪ (B \ A) ``` ### Produit cartésien -Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont la première élément appartient à `A` et la deuxième à `B`. +Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont le premier élément appartient à `A` et le deuxième à `B`. ``` A × B = { (x, y) | x ∈ A, y ∈ B } ``` - -``` diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index c7cb9421..36c33bd1 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -36,6 +36,7 @@ valeur_numérique: 100 notation_scientifique: 1e+12 booléen: true valeur_null: null +une_autre_valeur_null: ~ clé avec espaces: valeur # Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères # entre guillemets, cela reste possible, et parfois utile. diff --git a/func.html.markdown b/func.html.markdown new file mode 100644 index 00000000..da1b2214 --- /dev/null +++ b/func.html.markdown @@ -0,0 +1,338 @@ +--- +language: FunC +filename: learnFunC.fc +contributors: + - ["Ivan Romanovich", "https://t.me/ton_learn"] + - ["Kirill Malev", "https://fslabs.io"] +--- + +The FunC language is used to program smart contracts on the [The Open Network](https://ton.org) blockchain. Contract logic is executed in TVM, the stack-based TON Virtual Machine. + +FunC is a statically typed, which is similar to C. + +# Basic syntax, the first Smart Contract — Data Types, Storage, Functions + +```c +;; Single line comment + + {- This is a multi-line comment + {- this is a comment in the comment -} + -} + + (int) sum(int a, int b) { + ;; This is a function that gets two integer parameters + ;; and return integer result + return a + b; + ;; All integers are signed and are 257 bit long. Overflow throws exception + ;; expressions must end with a semicolon + } + + () f(int i, cell c, slice s, builder b, cont c, tuple t) { + ;; FunC has 7 atomic types: + ;; int - 257 bit signed integers, + ;; cell - basic for TON opaque data structure, + ;; which contains up to 1,023 bits and up to 4 references to other cells, + ;; slice and builder - special objects to read from and write to cells, + ;; continuation - another flavor of cell that contains + ;; ready-to-execute TVM byte-code. + ;; tuple is an ordered collection of up to 255 components, + ;; having arbitrary value types, possibly distinct. + ;; Finally tensor type (A,B, ...) is an ordered collection ready for + ;; mass assigning like: (int, int) a = (3, 5); + ;; Special case of tensor type is the unit type (). + ;; It represents that a function doesn’t return any value, + ;; or has no arguments. + } + + ;; During execution, the contract has read access to local context: + ;; its storage, balance, time, network config, etc. + ;; Contract may change its storage and code, + ;; and also may send messages to other contracts + + ;; Let’s write a counter smart contract that gets a number + ;; from an incoming message, + ;; adds to already stored numbers and stores result in “storage” + + ;; For handling special events, smart contracts have reserved methods: + ;; recv_internal() handles internal messages from other smart contracts + ;; recv_external() handles external messages from the outside world — + ;; e.g., from a user. + + () recv_internal(slice in_msg_body) { + ;; Cells play the role of memory in the stack-based TVM. + ;; A cell can be transformed into a slice, + ;; and then the data bits and references to + ;; other cells from the cell can be obtained + ;; by loading them from the slice. + ;; Data bits and references to other cells can be stored + ;; into a builder, and then the builder can be finalized into a new cell. + ;; recv_internal gets the slice + ;; with incoming message data as an argument. + + ;; As everything else on TON, permanent storage data is stored as a cell. + ;; It can be retrieved via the get_data() method + ;; begin_parse - converts a cell with data into a readable slice + + slice ds = get_data().begin_parse(); + ;; `.` is a syntax sugar: a.b() is equivalent to b(a) + + ;; load_uint is a function from the FunC standard library; + ;; it loads an unsigned n-bit integer from a slice + int total = ds~load_uint(64); ;; `~` is a "modifying" method: + ;; essentially, it is a syntax sugar: `r = a~b(x)` + ;; is equivalent to (a,r) = b(a,x) + + ;; Now let’s read the incoming value from the message body slice + int n = in_msg_body~load_uint(32); + + total += n; + ;; integers support usual +-*/ operations as well as (+-*/)= syntax sugar + + ;; In order to keep a store integer value, we need to do four things: + ;; create a Builder for the future cell - begin_cell() + ;; write a value to total - store_uint(value, bit_size) + ;; create a Cell from the Builder - end_cell() + ;; write the resulting cell into permanent storage - set_data() + + set_data(begin_cell().store_uint(total, 64).end_cell()); + } + + + + ;; The FunC program is essentially a list of + function declarations/definitions and global variable declarations. + + ;; Any function in FunC matches the following pattern: + ;; [<forall declarator>] <return_type> <function_name>(<comma_separated_function_args>) <specifiers> + + + ;; Specifiers: + ;; The impure specifier indicates that + ;; function calls should not be optimized + ;; (whether its result is used or not) + ;; it is important for methods that change the smart contract data + ;; or send messages + + ;; The method_id specifier allows you to call a GET function by name + + ;; For instance, we can create a get method for the contract above + ;; to allow outside viewers to read counter + + int get_total() method_id { + slice ds = get_data().begin_parse(); + int total = ds~load_uint(64); + + ;; Note that (int) and int is the same, + ;; thus brackets in the function declaration + ;; and in the return statement are omitted. + return total; + } + ;; Now any observer can read get_total value via lite-client or explorer +``` + +# Messages + +The actor model is a model of concurrent computation and is at the heart of TON smart contracts. Each smart contract can process one message at a time, change its own state, or send one or several messages. Processing of the message occurs in one transaction, that is, it cannot be interrupted. Messages to one contract are processed consequently one by one. As a result, the execution of each transaction is local and can be parallelized at the blockchain level, which allows for on-demand throughput horizontal scaling and hosting an unlimited number of users and transactions. + +```c +;; For normal internal message-triggered transactions, +;; before passing control to recv_internal TVM puts the following +;; elements on stack. +;;;; Smart contract balance (in nanoTons) +;;;; Incoming message balance (in nanoTons) +;;;; Cell with an incoming message +;;;; Incoming message body, slice type +;; In turn, recv_internal may use only +;; the required number of fields (like 1 in the example above or 4 below) + +;; Let’s dive into message sending + +() recv_internal ( + int balance, int msg_value, cell in_msg_full, slice in_msg_body) { + ;; + ;; Every message has a strict layout, thus by parsing it, + ;; we can get the sender’s address + ;; first, we need to read some tech flags and + ;; then take the address using load_msg_addr + ;; function from FunC standard library - () + var cs = in_msg_full.begin_parse(); + var flags = cs~load_uint(4); + slice sender_address = cs~load_msg_addr(); + + ;; if we want to send a message, we first need to construct it + ;; message serialization in most cases may be reduced to + var msg = begin_cell() + .store_uint(0x18, 6) ;; tech flags + .store_slice(addr) ;; destination address + .store_coins(amount) ;; attached value + .store_uint(0, 107) ;; more tech flags :) + .store_slice(in_msg_body) ;; just put some payload here + .end_cell(); + + ;; to send messages, use send_raw_message from the standard library. + ;; it accepts two arguments message and mode + send_raw_message(msg, 64); + + ;; mode parameter specifies how to process the funds passed into + ;; the smart contract with the message and the smart contract funds + ;; 64 means send everything from the incoming message — + ;; what’s left after the commission is deducted + + ;; Exceptions can be thrown by conditional primitives throw_if and + ;; throw_unless and by unconditional throw + ;; by default, it will automatically cause a bounce message with 64 mode + + var some = 7; + throw_if(102, some == 10); + ;; Throw exception with code 102 conditionally + throw_unless(103, some != 10); + ;; Throw exception with code 103 conditionally + throw(101); ;; Throw exception with code 101 unconditionally +} +``` + +# Flow control: Conditional Statements and Loops; Dictionaries + +```c +;; FunC, of course, supports if statements + +;;;; usual if-else +if (flag) { + ;;do_something(); +} +else { + ;;do_alternative(); +} + +;; If statements are often used as an operation identifier +;; for a smart contract, for example: + +() recv_internal ( + int balance, int msg_value, cell in_msg_full, slice in_msg_body) { + int op = in_msg_body~load_int(32); + if (op == 1) { + ;; smth here + } else { + if (op == 2) { + ;; smth here + } else { + ;; smth here + } + } +} + +;; Loops +;; FunC supports repeat, while and do { ... } until loops. +;; for loop is not supported. + +;; repeat +int x = 1; +repeat(10) { + x *= 2; +} +;; x = 1024 + +;; while +int x = 2; +while (x < 100) { + x = x * x; +} +;; x = 256 + +;; until loops +int x = 0; +do { + x += 3; +} until (x % 17 == 0); +;; x = 51 + +;; In practice, loops in TON smart contracts are often used to work with +;; dictionaries, or as they are also called in TON hashmaps + +;; A hashmap is a data structure represented by a tree. +;; Hashmap maps keys to values of arbitrary type so that +;; quick lookup and modification are possible. + +;; udict_get_next? from FunC standard library in combination with +;; the loop will help, go through the dictionary + +int key = -1; +do { + (key, slice cs, int f) = dic.udict_get_next?(256, key); + +} until (~ f); + +;; udict_get_next? - Calculates the minimum key k in the dictionary dict +;; that is greater than some given value and returns k, +;; the associated value, and a flag indicating success. +;; If the dictionary is empty, returns (null, null, 0). +``` + +# Functions + +```c +;; Most useful functions are slice reader and builder writer primitives, +;; storage handlers and sending messages + +;; slice begin_parse(cell c) - Converts a cell into a slice +;; (slice, int) load_int(slice s, int len) - +;; Loads a signed len-bit integer from a slice. +;; (slice, int) load_uint(slice s, int len) - +;; Loads a unsigned len-bit integer from a slice. +;; (slice, slice) load_bits(slice s, int len) - +;; Loads the first 0 ≤ len ≤ 1023 bits from slice into a separate slice. +;; (slice, cell) load_ref(slice s) - Loads the reference cell from the slice. + +;; builder begin_cell() - Creates a new empty builder. +;; cell end_cell(builder b) - Converts a builder into an ordinary cell. +;; builder store_int(builder b, int x, int len) - +;; Stores a signed len-bit integer x into b for 0 ≤ len ≤ 257. +;; builder store_uint(builder b, int x, int len) - +;; Stores an unsigned len-bit integer x into b for 0 ≤ len ≤ 256. +;; builder store_slice(builder b, slice s) - Stores slice s into builder b. +;; builder store_ref(builder b, cell c) - +;; Stores a reference to cell c into builder b. + +;; cell get_data() - Returns the persistent contract storage cell. +;; () set_data(cell c) - Sets cell c as persistent contract data. + +;; () send_raw_message(cell msg, int mode) - +;; put message msg into sending queue with mode. +;; Note, that message will be sent after a successful execution +;; of the whole transaction + +;; Detailed descriptions of all standard functions can be found +;; in docs https://ton.org/docs/#/func/stdlib +;; +``` + +## Additional resources +- [FunC Lessons](https://github.com/romanovichim/TonFunClessons_Eng) +- [TON Development Onboarding](https://www.tonspace.co) +- [TON Documentation](https://ton.org/docs/#/) +- [FunC Documentation](https://ton.org/docs/#/func/overview) +- [TON Smart Contracts examples](https://github.com/ton-blockchain/ton/tree/master/crypto/smartcont) +- [Community portal](https://society.ton.org) +- [Blockchain portal](https://ton.org) +- [Stackoverflow](https://stackoverflow.com/questions/tagged/ton) + +## Social +- [Developer community](https://t.me/tondev_eng) +- [TON Learn](https://t.me/ton_learn) +- [FunC Lessons Channel](https://github.com/romanovichim/TonFunClessons_Eng) +- [FunC onboarding](https://t.me/func_guide) +- [Tondev News](https://t.me/tondevnews) + +## Useful blogposts +- [Setting up a TON Development Environment](https://society.ton.org/setting-up-a-ton-development-environment) +- [Hello World on TON](https://society.ton.org/ton-hello-world-step-by-step-guide-for-writing-your-first-smart-contract-in-func) + + +## Future To Dos +- Add smart contracts examples +- Add more posts + + +This file is mostly copied from [TonFunClessons 15 minutes intro](https://github.com/romanovichim/TonFunClessons_Eng/blob/main/13lesson/15min.md). + +P.S. If by any chance you're familiar with [Forth](https://learnxinyminutes.com/docs/forth/), you can also take a look at [Fift](https://ton-blockchain.github.io/docs/fiftbase.pdf).
\ No newline at end of file diff --git a/gdscript.html.markdown b/gdscript.html.markdown index 25af0974..0bfac26a 100644 --- a/gdscript.html.markdown +++ b/gdscript.html.markdown @@ -95,7 +95,7 @@ func doing_math(): func control_flow(): x = 8 y = 2 # y was originally a float, - # but we can change it's type to int + # but we can change its type to int # using the power of dynamic typing! if x < y: @@ -114,6 +114,9 @@ func control_flow(): for i in range(20): # GDScript's range is similar to Python's print(i) # so this will print numbers from 0 to 19 + for i in 20: # unlike Python, you can loop over an int directly + print(i) # so this will also print numbers from 0 to 19 + for i in ["two", 3, 1.0]: # iterating over an array print(i) @@ -319,4 +322,4 @@ signal example(arg: int) # ERROR! Signals can't take typed arguments! * [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html) * [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html) * [GDQuest](https://www.gdquest.com/) -* [GDScript.com](https://gdscript.com/)
\ No newline at end of file +* [GDScript.com](https://gdscript.com/) diff --git a/git.html.markdown b/git.html.markdown index a40ef01b..9d33225f 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -124,9 +124,12 @@ To configure settings. Whether it be for the repository, the system itself, or global configurations ( global config file is `~/.gitconfig` ). ```bash -# Print & Set Some Basic Config Variables (Global) +# Set & Print Some Basic Config Variables (Global) $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" + +$ git config --global user.email +$ git config --global user.name ``` [Learn More About git config.](http://git-scm.com/docs/git-config) @@ -579,6 +582,19 @@ $ git rm HelloWorld.c $ git rm /pather/to/the/file/HelloWorld.c ``` +### blame +Examine specific parts of the code's history and find out who was the last author to modify that line. + +```bash +# find the authors on the latest modified lines +$ git blame google_python_style.vim +b88c6a1b (Google Python team 2019-12-30 13:45:23 -0800 12) " See the License for the specific language governing permissions and +b88c6a1b (Google Python team 2019-12-30 13:45:23 -0800 13) " limitations under the License. +b88c6a1b (Google Python team 2019-12-30 13:45:23 -0800 14) +222e6da8 (mshields@google.com 2010-11-29 20:32:06 +0000 15) " Indent Python in the Google way. +222e6da8 (mshields@google.com 2010-11-29 20:32:06 +0000 16) +222e6da8 (mshields@google.com 2010-11-29 20:32:06 +0000 17) setlocal indentexpr=GetGooglePythonIndent(v:lnum) +``` ## Further Information * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) @@ -597,8 +613,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) - * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) diff --git a/go.html.markdown b/go.html.markdown index 39c8ac74..fe69ed43 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -39,14 +39,14 @@ Go comes with a good standard library and a sizeable community. // +build prod, dev, test // A package clause starts every source file. -// Main is a special name declaring an executable rather than a library. +// main is a special name declaring an executable rather than a library. package main // Import declaration declares library packages referenced in this file. import ( "fmt" // A package in the Go standard library. "io/ioutil" // Implements some I/O utility functions. - m "math" // Math library with local alias m. + "math" // Math library with local alias m. "net/http" // Yes, a web server! "os" // OS functions like working with the file system "strconv" // String conversions. diff --git a/groovy.html.markdown b/groovy.html.markdown index 0d589c10..89eee3dd 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -55,6 +55,9 @@ println x //Creating an empty list def technologies = [] +// or create a list with data +technologies = ["Kotlin", "Swift"] + /*** Adding a elements to the list ***/ // As with Java @@ -193,7 +196,7 @@ def say(msg = 'Hello', name = 'world') { assert 'Hello world!' == say() // Right most parameter with default value is eliminated first. assert 'Hi world!' == say('Hi') -assert 'learn groovy' == say('learn', 'groovy') +assert 'learn groovy!' == say('learn', 'groovy') /* Logical Branching and Looping diff --git a/hack.html.markdown b/hack.html.markdown index fb6af8e1..24055503 100644 --- a/hack.html.markdown +++ b/hack.html.markdown @@ -1,308 +1,420 @@ --- language: Hack contributors: + - ["Andrew DiMola", "https://github.com/AndrewDiMola"] - ["Stephen Holdaway", "https://github.com/stecman"] - ["David Lima", "https://github.com/davelima"] filename: learnhack.hh --- -Hack is a superset of PHP that runs under a virtual machine called HHVM. Hack -is almost completely interoperable with existing PHP code and adds a bunch of -useful features from statically typed languages. +[Hack](https://hacklang.org/) lets you write code quickly, while also having safety features built in, like static typechecking. - -Only Hack-specific features are covered here. Details about PHP's syntax are -available in the [PHP article](http://learnxinyminutes.com/docs/php/) on this site. +To run Hack code, [install HHVM](https://docs.hhvm.com/hhvm/installation/introduction), the open-source virtual machine. ```php -<?hh - -// Hack syntax is only enabled for files starting with an <?hh marker -// <?hh markers cannot be interspersed with HTML the way <?php can be. -// Using the marker "<?hh //strict" puts the type checker in strict mode. - - -// Scalar parameter type hints -function repeat(string $word, int $count) -{ - $word = trim($word); - return str_repeat($word . ' ', $count); -} - -// Type hints for return values -function add(...$numbers) : int -{ - return array_sum($numbers); -} - -// Functions that return nothing are hinted as "void" -function truncate(resource $handle) : void -{ - // ... -} - -// Type hints must explicitly allow being nullable -function identity(?string $stringOrNull) : ?string -{ - return $stringOrNull; -} - -// Type hints can be specified on class properties -class TypeHintedProperties -{ - public ?string $name; - - protected int $id; - - private float $score = 100.0; - - // Hack's type checker enforces that typed properties either have a - // default value or are set in the constructor. - public function __construct(int $id) - { - $this->id = $id; - } -} - - -// Concise anonymous functions (lambdas) -$multiplier = 5; -array_map($y ==> $y * $multiplier, [1, 2, 3]); - - -// Generics -class Box<T> -{ - protected T $data; - - public function __construct(T $data) { - $this->data = $data; - } - - public function getData(): T { - return $this->data; - } -} - -function openBox(Box<int> $box) : int -{ - return $box->getData(); -} - - -// Shapes -// -// Hack adds the concept of shapes for defining struct-like arrays with a -// guaranteed, type-checked set of keys -type Point2D = shape('x' => int, 'y' => int); +/* ================================== + * READ THE DOCS! + * ================================== + */ + +/* For more information on the Hack language: + * - About Hack: https://hacklang.org/ + * - Documentation: https://docs.hhvm.com/hack/ + */ + +/* ================================== + * A NOTE ON PHP + * ================================== + */ + +// The Hack language began as a superset of PHP. +// Since then, the languages have (largely) diverged. +// You may encounter the .php extension, which is no longer recommended. + +/* ================================== + * COMMENTS + * ================================== + */ + +// Hack has single-line comments... + +/* Multi-line comments... + * + */ + +/** + * ... and a special syntax for doc comments. + * + * Use doc comments to summarize the purpose of a definition, function, class or method. + */ + +/* ================================== + * NAMESPACES + * ================================== + */ + +// Namespaces contain definitions of classes, interfaces, traits, functions, and constants. + +namespace LearnHackinYMinutes { + + /* ================================== + * TYPES + * ================================== + */ + + function demo_hack_types(): void { + + // Hack has five primitive types: bool, int, float, string, and null. + $is_helpful = true; // bool + $int_value = 10; // int + $precise_value = 2.0; // float + $hello_world = "Hello World!"; // string + $null_string = null; // null -function distance(Point2D $a, Point2D $b) : float -{ - return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); -} + // Create a `shape` with the shape keyword, with a series of field names and values. + $my_point = shape('x' => -3, 'y' => 6, 'visible' => true); -distance( - shape('x' => -1, 'y' => 5), - shape('x' => 2, 'y' => 50) -); + // Create a `tuple` with the tuple keyword, with a series of two or more types as values. + $apple_basket = tuple("apples", 25); // different types are OK + + // Use `arraykey` to represent either an integer or string. + $the_answer = 42; + $is_answer = process_key($the_answer); + + // Similarly, `num` represents either an int or float. + $lucky_number = 7; + $lucky_square = calculate_square($lucky_number); + } + function process_key(arraykey $the_answer): bool { + if ($the_answer is int) { + return true; + } else { + return false; + } // true + } + + function calculate_square(num $arg)[]: float { + return ((float)$arg * $arg); + } + + // Enums are limited to int or string (as an Arraykey), or other enum values. + enum Permission: string { + Read = 'R'; + Write = 'W'; + Execute = 'E'; + Delete = 'D'; + } + + // In contrast, an enum class can be of any value type! + enum class Random: mixed { + int X = 42; + string S = 'foo'; + } + + /* ================================== + * HACK ARRAYS + * ================================== + */ + + // The following line lets us use functions in the `C\` namespace. + use namespace HH\Lib\C; // the `C` library operates on containers + + function demo_hack_arrays(): void { -// Type aliasing -// -// Hack adds a bunch of type aliasing features for making complex types readable -newtype VectorArray = array<int, Vector<int>>; + // vec: ordered + $v = vec[1, 2, 3]; + $letters = vec['a', 'b', 'c']; -// A tuple containing two integers -newtype Point = (int, int); + $letters[0]; // returns 'a' + $letters[] = 'd'; // appends 'd' + + // `inout` provides pass-by-reference behavior + C\pop_back(inout $letters); // removes 'd' + C\pop_front(inout $letters); // removes 'a' + + // keyset: ordered, without duplicates + $k = keyset[1, 2, 3]; // values must be int or string + $colors = keyset['red', 'blue', 'green']; + + // keyset keys are identical to their values + $colors['blue']; // returns 'blue'. + + $colors[] = 'yellow'; // appends 'yellow' + unset($colors['red']); // removes 'red' + + // dict: ordered, by key-value + $d = dict['a' => 1, 'b' => 3]; // keys must be int or string + $alphabet = dict['a' => 1, 'b' => 2]; -function addPoints(Point $p1, Point $p2) : Point -{ - return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); -} + $alphabet['a']; // indexing at 'a' returns `1` + $alphabet['c'] = 3; // adds a new key-value pair of `c => 3` -addPoints( - tuple(1, 2), - tuple(5, 6) -); + unset($alphabet['b']); // removes 'b' + } + /* ================================== + * THE HACK STANDARD LIBRARY (HSL) + * ================================== + */ + + // The Hack Standard Library is a set of functions and classes for the Hack language. + // Namespace use declarations are ideally at the top of your file but are placed here for instruction purposes. + + use namespace HH\Lib\Str; // The `Str` library operates on strings + + function demo_hack_standard_library(): void { + + $letters = vec['a', 'b', 'c']; + $colors = keyset['red', 'blue', 'green']; + $alphabet = dict['a' => 1, 'b' => 2]; + + C\contains($letters, 'c'); // checks for a value; returns 'true' + C\contains($colors, 'purple'); // checks for a value; returns 'false' + C\contains_key($alphabet, 'a'); // checks for a key; returns 'true' + C\contains($alphabet, 'd'); // checks for a value; returns 'false' -// First-class enums -enum RoadType : int -{ - Road = 0; - Street = 1; - Avenue = 2; - Boulevard = 3; -} + Str\length("foo"); // returns `3` + Str\join(vec['foo', 'bar', 'baz'], '!'); // returns `foo!bar!baz` + } + + /* ================================== + * HELLO WORLD! + * ================================== + */ + + use namespace HH\Lib\IO; // the `IO` library is a standard API for input / output + + <<__EntryPoint>> // required attribute for the typical entry/main function + async function main(): Awaitable< + void, + > { // does not need to be named 'main' / is an asynchronous function + await IO\request_output()->writeAllAsync( + "Hello World!\n", + ); // prints 'Hello World'! + } -function getRoadType() : RoadType -{ - return RoadType::Avenue; -} + /* ================================== + * FUNCTIONS + * ================================== + */ + // Functions are defined globally. + // When a function is defined in a class, we refer to the function as a method. -// Constructor argument promotion -// -// To avoid boilerplate property and constructor definitions that only set -// properties, Hack adds a concise syntax for defining properties and a -// constructor at the same time. -class ArgumentPromotion -{ - public function __construct(public string $name, - protected int $age, - private bool $isAwesome) {} -} + // Functions have return types (here: `int`) and must return a value of + // that type or return no value when a void return type annotation was used. -class WithoutArgumentPromotion -{ - public string $name; + function add_one(int $x): int { + return $x + 1; + } - protected int $age; + // Functions can also have defined, default values. + function add_value(int $x, int $y = 1): int { + return $x + $y; + } - private bool $isAwesome; + // Functions can be variadic (unspecified length of arguments). + function sum_ints(int $val, int ...$vals): int { + $result = $val; - public function __construct(string $name, int $age, bool $isAwesome) - { - $this->name = $name; - $this->age = $age; - $this->isAwesome = $isAwesome; + foreach ($vals as $v) { + $result += $v; } -} - - -// Co-operative multi-tasking -// -// Two new keywords "async" and "await" can be used to perform multi-tasking -// Note that this does not involve threads - it just allows transfer of control -async function cooperativePrint(int $start, int $end) : Awaitable<void> -{ - for ($i = $start; $i <= $end; $i++) { - echo "$i "; - - // Give other tasks a chance to do something - await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + return $result; + } + + // Functions can also be anonymous (defined with the `==>` arrow). + // $f = (int $x): int ==> $x + 1; + + /* ================================== + * PIPE OPERATOR + * ================================== + */ + + // The pipe operator, `|>`, evaluates the result of a left-hand expression + // and stores the result in `$$`, the predefined pipe variable. + + use namespace HH\Lib\Vec; + + function demo_pipe_operator(): void { + + Vec\sort(Vec\map(vec[2, 1, 3], $a ==> $a * $a)); // vec[1,4,9] + + // the same result, but using the pipe operator and pipe variable: + $x = vec[2, 1, 3] + |> Vec\map($$, $a ==> $a * $a) // $$ with value vec[2,1,3] + |> Vec\sort($$); // $$ with value vec[4,1,9] + } + + /* ================================== + * ATTRIBUTES + * ================================== + */ + + // Hack provides built-in attributes that can change runtime or static type checking behavior. + // For example, we used the `__EntryPoint` attribute earlier in the "Hello World!" example. + + // As another example, `__Memoize` caches the result of a function. + <<__Memoize>> + async function do_expensive_task(): Awaitable<string> { + $site_contents = await \HH\Asio\curl_exec("http://hacklang.org"); + return $site_contents; + } + + /* ================================== + * CONTEXTS + * ================================== + */ + + // Hack functions are attached to different contexts and capabilities. + // A context is a grouping of capabilities; that is, a grouping of permissions. + + // To declare allowed contexts (and capabilities), use the Context List `[]`. + // If contexts are not defined, your function includes permissions defined in Hack's `defaults` context. + + // Because the context list is NOT defined, the `defaults` context is implicitly declared. + async function implicit_defaults_context(): Awaitable<void> { + await IO\request_output()->writeAllAsync( + "Hello World!\n", + ); // prints 'Hello World'! + } + + // In the function below, the context list is defined to have the `defaults` context. + // A function can have multiple contexts [context1, context2, ...]. + // `defaults` includes most of the capabilities defined by the Hack language. + async function explicit_defaults_context()[defaults]: Awaitable<void> { + await IO\request_output()->writeAllAsync("Hello World!\n"); + } + + // You can also specify zero contexts to create a pure function (no capabilities). + async function empty_context()[]: Awaitable<void> { + // The following line is an error, as the function does not have IO capabilities. + // await IO\request_output()->writeAllAsync("Hello World!\n"); + } + + /* ================================== + * GENERICS + * ================================== + */ + + // Generics allow classes or methods to be parameterized to any set of types. + // That's pretty cool! + + // Hack typically passes by value: use `inout` to pass by reference. + function swap<T>(inout T $input1, inout T $input2): void { + $temp = $input1; + $input1 = $input2; + $input2 = $temp; + } + + /* ================================== + * CLASSES + * ================================== + */ + + // Classes provide a way to group functionality and state together. + // To define a class, use the `class` keyword. To instantiate, use `new`. + // Like other languages, you can use `$this` to refer to the current instance. + + class Counter { + private int $i = 0; + + public function increment(): void { + $this->i += 1; } -} - -// This prints "1 4 7 2 5 8 3 6 9" -AwaitAllWaitHandle::fromArray([ - cooperativePrint(1, 3), - cooperativePrint(4, 6), - cooperativePrint(7, 9) -])->getWaitHandle()->join(); - - -// Attributes -// -// Attributes are a form of metadata for functions. Hack provides some -// special built-in attributes that introduce useful behaviour. - -// The __Memoize special attribute causes the result of a function to be cached -<<__Memoize>> -function doExpensiveTask() : ?string -{ - return file_get_contents('http://example.com'); -} -// The function's body is only executed once here: -doExpensiveTask(); -doExpensiveTask(); - - -// The __ConsistentConstruct special attribute signals the Hack type checker to -// ensure that the signature of __construct is the same for all subclasses. -<<__ConsistentConstruct>> -class ConsistentFoo -{ - public function __construct(int $x, float $y) - { - // ... + public function get(): int { + return $this->i; } + } - public function someMethod() - { - // ... + // Properties and Methods can be static (not requiring instantiation). + class Person { + public static function favoriteProgrammingLanguage(): string { + return "Hack"; } -} + } -class ConsistentBar extends ConsistentFoo -{ - public function __construct(int $x, float $y) - { - // Hack's type checker enforces that parent constructors are called - parent::__construct($x, $y); + function demo_hack_classes(): void { + // Use `new` to instantiate a class. + $c1 = new Counter(); - // ... - } + // To call a static property or method, use `::` + $typical_person = tuple("Andrew", Person::favoriteProgrammingLanguage()); + } - // The __Override annotation is an optional signal for the Hack type - // checker to enforce that this method is overriding a method in a parent - // or trait. If not, this will error. - <<__Override>> - public function someMethod() - { - // ... + // Abstract class can be defined, but not instantiated directly. + abstract class Machine { + public function openDoors(): void { + return; } -} - -class InvalidFooSubclass extends ConsistentFoo -{ - // Not matching the parent constructor will cause a type checker error: - // - // "This object is of type ConsistentBaz. It is incompatible with this object - // of type ConsistentFoo because some of their methods are incompatible" - // - public function __construct(float $x) - { - // ... + public function closeDoors(): void { + return; } - - // Using the __Override annotation on a non-overridden method will cause a - // type checker error: - // - // "InvalidFooSubclass::otherMethod() is marked as override; no non-private - // parent definition found or overridden parent is defined in non-<?hh code" - // - <<__Override>> - public function otherMethod() - { - // ... + } + + /* ================================== + * INTERFACES + * ================================== + */ + + // A class can implement a set of requirements via an interface. + // An interface is a set of method declarations and constants. + + interface Plane { + // A constant is a named value. Once defined, the value cannot be changed. + const MAX_SPEED = 300; + public function fly(): void; + } + + /* ================================== + * TRAITS + * ================================== + */ + + // A trait defines properties and method declarations. + // Traits are recommended when abstracting code for reuse. + // Traits are included in code via the `use` keyword. + + trait Airplane { + // Introduce a class or interface requirement with the following syntax: + require extends Machine; // abstract class + require implements Plane; // interface + + public function takeOff(): void { + $this->openDoors(); + $this->closeDoors(); + $this->fly(); } -} + } + class Spaceship extends Machine implements Plane { + use Airplane; -// Traits can implement interfaces (standard PHP does not support this) -interface KittenInterface -{ - public function play() : void; -} - -trait CatTrait implements KittenInterface -{ - public function play() : void - { - // ... + public function fly(): void { + // fly like the wind } + } + + /* ================================== + * KEEP READING! + * ================================== + */ + + /* This is a simplified guide! + * There's much more to learn, including: + * - Asynchronous Operations: https://docs.hhvm.com/hack/asynchronous-operations/introduction + * - Reified Generics: https://docs.hhvm.com/hack/reified-generics/reified-generics + * - XHP: https://docs.hhvm.com/hack/XHP/setup + * - ... and more! + */ } -class Samuel -{ - use CatTrait; -} - - -$cat = new Samuel(); -$cat instanceof KittenInterface === true; // True - ``` ## More Information -Visit the [Hack language reference](http://docs.hhvm.com/manual/en/hacklangref.php) -for detailed explanations of the features Hack adds to PHP, or the [official Hack website](http://hacklang.org/) -for more general information. - -Visit the [official HHVM website](http://hhvm.com/) for HHVM installation instructions. +Visit the [Hack language reference](http://docs.hhvm.com/hack/) to learn more about the Hack language. -Visit [Hack's unsupported PHP features article](http://docs.hhvm.com/manual/en/hack.unsupported.php) -for details on the backwards incompatibility between Hack and PHP. +For more information on HHVM, including installation instructions, visit the [official HHVM website](http://hhvm.com/). diff --git a/hdl.html.markdown b/hdl.html.markdown index 3c3aff66..6b9a2d80 100644 --- a/hdl.html.markdown +++ b/hdl.html.markdown @@ -12,7 +12,7 @@ It is used by circuit designers to simulate circuits and logic prior to wiring a HDL allows circuit designers to simulate circuits at a high level without being connected to specific components. ## Basic building blocks & introduction to the language--- -This programming language is built by simulating hardware chips and wiring. Normal programming functions are replaced with specialized chips that are added to the current wiring desing. Every base chip must be written as it's own file and imported to be used in the current chip, though they may be reused as often as desired. +This programming language is built by simulating hardware chips and wiring. Normal programming functions are replaced with specialized chips that are added to the current wiring design. Every base chip must be written as it's own file and imported to be used in the current chip, though they may be reused as often as desired. ```verilog // Single line comments start with two forward slashes. @@ -79,7 +79,7 @@ foo(in=a[0..7], out=c); // C is now a 2 bit internal bus // Note that internally defined busses cannot be subbussed! -// To access these elements, output or input them seperately: +// To access these elements, output or input them separately: foo(in[0]=false, in[1..7]=a[0..6], out[0]=out1, out[1]=out2); // out1 and out2 can then be passed into other circuits within the design. diff --git a/hjson.html.markdown b/hjson.html.markdown new file mode 100644 index 00000000..6b3cc3ed --- /dev/null +++ b/hjson.html.markdown @@ -0,0 +1,94 @@ +--- +language: Hjson +filename: learnhjson.hjson +contributors: + - ["MrTeferi", "https://github.com/MrTeferi"] +lang: en +--- + +Hjson is an attempt to make [JSON](https://learnxinyminutes.com/docs/json/) more human readable. + +Hjson is a syntax extension to JSON. +It's NOT a proposal to replace JSON or to incorporate it into the JSON spec itself. +It's intended to be used like a user interface for humans, +to read and edit before passing the JSON data to the machine. + +Let's take a look at examples to see the key syntax differences! + +``` +{ + # Comments are totally supported! + + // With forward slashes too! + + /* + Even block style comments, neat! + /* + + # Strings do not require quotes! + # Just keep it to a single line + human: readable + quotes: "are fine too" + + # Notice that commas are also not required! + # If using commas, strings DO require quotes! + object: { + name: Hjson + properties: [ + readable + exciting + fun + ] + with_commas: [ + "quoted", + "quoty", + "quote" + ] + details: ["this", "is", "fine", "too"] + } + + # Multiline quotes with proper whitespace handling are supported! + diary: + ''' + I wish JSON was more human readable. + If only there was a JSON for my needs! + Oh wait.. there is! It's called Hjson. + ''' + + # Backslashes are interpreted as an escape character ONLY in quoted strings + slash: This will not have a new line\n + slash-quoted: "This will definitely have a new line\n" + + # Make sure to use quotes when mixing whitespace with important punctuation + example1: "If, you're, going, to, comma in a string, use, quotes!" + example2: "Also if you want to use {} or [] or any JSON relevant punctuation!" + example3: [because, this, is, totally, BROKEN!] + example4: this is technically OK though: {}[],: + + # Enjoy working with Hjson! + party-time: { + Hjson-lovers: [ + me + my mom + "my dad" + ] + Hjson-power-level: 9000 + supported: { + python: yes + java: yes + javascript: yes + c++: yes + Go: yes + C#: yes + Rust: yes + } + partial-support: ["C", "Kotlin", "Ruby", "Rust"] + } + +} +``` + +## Further Reading + +* [Hjson.github.io](https://hjson.github.io/) Main Hjson site including editor support, how-to, etc. +* [Hjson Packages](https://github.com/hjson/) Various Hjson packages for different applications. diff --git a/hy.html.markdown b/hy.html.markdown index 1287095f..f6bdead0 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -13,8 +13,7 @@ hy to call native python code or python to call native hy code as well This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11. ```clojure -;; this gives an gentle introduction to hy for a quick trial head to -;; http://try-hy.appspot.com +;; this gives an gentle introduction to hy ;; ; Semicolon comments, like other LISPS diff --git a/images/cairo/build.png b/images/cairo/build.png Binary files differnew file mode 100644 index 00000000..7cadb9ad --- /dev/null +++ b/images/cairo/build.png diff --git a/images/cairo/connect.png b/images/cairo/connect.png Binary files differnew file mode 100644 index 00000000..86146353 --- /dev/null +++ b/images/cairo/connect.png diff --git a/images/cairo/connect2.png b/images/cairo/connect2.png Binary files differnew file mode 100644 index 00000000..08b00a81 --- /dev/null +++ b/images/cairo/connect2.png diff --git a/images/cairo/declare.png b/images/cairo/declare.png Binary files differnew file mode 100644 index 00000000..5b5196ce --- /dev/null +++ b/images/cairo/declare.png diff --git a/images/cairo/deploy.png b/images/cairo/deploy.png Binary files differnew file mode 100644 index 00000000..bdb7e53c --- /dev/null +++ b/images/cairo/deploy.png diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index 449aebfb..a8e0c7b5 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-it.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index 797f6b0b..2af2468d 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -34,7 +34,7 @@ Go include un'ottima libreria standard e ha una community entusiasta. su riga multipla */ // In cima ad ogni file è necessario specificare il package. -// Main è un package speciale che identifica un eseguibile anziché una libreria. +// main è un package speciale che identifica un eseguibile anziché una libreria. package main // Con import sono dichiarate tutte le librerie a cui si fa riferimento diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index b0a123f1..c14bc175 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -253,7 +253,7 @@ Ma non è comunemente usato. Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre! ```md -![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") +![Questo è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") ``` E la modalità a riferimento funziona esattamente come ci si aspetta @@ -307,4 +307,4 @@ Col 1 | Col2 | Col3 ``` --- -Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](https://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown index 38be8848..2668815f 100644 --- a/it-it/matlab-it.html.markdown +++ b/it-it/matlab-it.html.markdown @@ -1,5 +1,5 @@ --- -language: Matlab +language: MATLAB contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] @@ -114,7 +114,7 @@ A.d.e = false; % Vettori x = [4 32 53 7 1] -x(2) % ans = 32, gli indici in Matlab iniziano da 1, non da 0 +x(2) % ans = 32, gli indici in MATLAB iniziano da 1, non da 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -466,7 +466,7 @@ perms(x) % lista tutte le permutazioni di elementi di x % Classi -% Matlab supporta la programmazione orientata agli oggetti. +% MATLAB supporta la programmazione orientata agli oggetti. % La classe deve essere messa in un file con lo stesso nome della classe e estensione .m % Per iniziare, creiamo una semplice classe per memorizzare waypoint GPS % Inizio WaypointClass.m @@ -488,7 +488,7 @@ classdef WaypointClass % Il nome della classe. end % Se si vuole aggiungere due oggetti Waypoint insieme senza chiamare - % una funzione speciale si può sovradefinire una funzione aritmetica di Matlab come questa: + % una funzione speciale si può sovradefinire una funzione aritmetica di MATLAB come questa: function r = plus(o1,o2) r = WaypointClass([o1.latitude] +[o2.latitude], ... [o1.longitude]+[o2.longitude]); @@ -500,7 +500,7 @@ end % Si può creare un oggetto della classe usando un costruttore a = WaypointClass(45.0, 45.0) -% Le proprietà della classe si comportano esattamente come una Struttura Matlab. +% Le proprietà della classe si comportano esattamente come una Struttura MATLAB. a.latitude = 70.0 a.longitude = 25.0 @@ -511,15 +511,15 @@ ans = multiplyLatBy(a,3) % non necessita di essere passato al metodo. ans = a.multiplyLatBy(a,1/3) -% Le funzioni Matlab possono essere sovradefinite per gestire oggetti. -% Nel metodo sopra, è stato sovradefinito come Matlab gestisce +% Le funzioni MATLAB possono essere sovradefinite per gestire oggetti. +% Nel metodo sopra, è stato sovradefinito come MATLAB gestisce % l'addizione di due oggetti Waypoint. b = WaypointClass(15.0, 32.0) c = a + b ``` -## Di più su Matlab +## Di più su MATLAB * Sito ufficiale [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) * Forum ufficiale di MATLAB: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) diff --git a/it-it/qt-it.html.markdown b/it-it/qt-it.html.markdown index d7469f67..ef829493 100644 --- a/it-it/qt-it.html.markdown +++ b/it-it/qt-it.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: Qt Framework -language: c++ +language: C++ filename: learnqt-it.cpp contributors: - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index df4d6279..acb8b8ba 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["Carlo Milanesi", "http://github.com/carlomilanesi"] lang: it-it diff --git a/it-it/solidity.html.markdown b/it-it/solidity.html.markdown new file mode 100644 index 00000000..be747e68 --- /dev/null +++ b/it-it/solidity.html.markdown @@ -0,0 +1,1069 @@ +--- +language: Solidity +filename: learnSolidity-it.sol +contributors: + - ["Nemil Dalal", "https://www.nemil.com"] + - ["Joseph Chow", ""] + - ["Bhoomtawath Plinsut", "https://github.com/varshard"] + - ["Shooter", "https://github.com/liushooter"] + - ["Patrick Collins", "https://gist.github.com/PatrickAlphaC"] +translators: + - ["Al", "http://github.com/al-ias"] +lang: it-it +--- + +Solidity permette di programmare su [Ethereum](https://www.ethereum.org/), una +macchina virtuale basata sulla blockchain che consente la creazione e +l'esecuzione degli smart contract senza che sia richiesta centralizzazione o +fiducia negli attori coinvolti. + +Solidity è un linguaggio di programmazione di contratti tipizzato staticamente e +ha molte cose in comune con Javascript e C. Come per gli oggetti nella +programmazione ad oggetti, ogni contratto contiene variabili di stato, funzioni +e tipi di dato semplici. Tra le funzionalità specifiche dei contratti troviamo +le clausole (guardie) dei modifier, gli event notifier per i listener, e le +variabili globali custom. + +Come esempi di contratti su Ethereum troviamo sistemi di crowdfunding, voto, +[finanza decentralizzata](https://defipulse.com/) e aste al buio. + +Compiere errori nel codice Solidity può portare a rischi e costi alti, quindi +bisogna fare attenzione a testare e rilasciare le modifiche lentamente. A +CAUSA DEI CONTINUI CAMBIAMENTI DI ETHEREUM È IMPROBABILE CHE QUESTO DOCUMENTO +RESTI AGGIORNATO, QUINDI COSNIGLIAMO DI SEGUIRE LA CHAT ROOM DI SOLIDITY E IL +BLOG DI ETHEREUM PER TENERSI AGGIORNATI. TUTTO IL CODICE QUI PRESENTE E' FORNITO +COSÌ COM'È, CON ANNESSI RISCHI SOSTANZIALI DI ERRORI O PATTERN DI PROGRAMMAZIONE +DEPRECATI. + +A differenza di altri linguaggi, potresti aver bisogno di usare pattern di +pausing, deprecation e throttling usage per ridurre il rischio. Questo documento +tratta principalmene la sintassi e quindi esclude molti design pattern in voga. + +Visto che Solidity e Ethereum sono in continuo sviluppo, le funzionalità +sperimentali o beta sono evidenziate e soggette a cambiamenti. Ogni Pull Request +è ben accetta. + + +# Lavorare con Remix e Metamask + +Uno dei modi più semplici di scrivere, distribuire e testare il codice Solidity +è usare : + +1. [L'ambiente di sviluppo online Remix](https://remix.ethereum.org/) +2. [Il wallet Metamask](https://metamask.io/). + +Per cominciare, [scarichiamo l'estesione per browser di Metamask](https://metamask.io/). + +Una volta installata, potremo iniziare ad usare Remix. Il codice seguente è +pre-inizializzato, ma prima di addentrarci, diamo un'occhiata a qualche +trucchetto per iniziare ad usare Remix. Carica tutto il necessario [clickando su questo link](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=f490c0d51141dd0515244db40bbd0c17&runs=200). + +1. Scegli il compilatore per Solidity + +![Solidity-in-remix](../images/solidity/remix-solidity.png) + +2. Apri il file che si caricherà su quel link + +![Solidity-choose-file](../images/solidity/remix-choose-file.png) + +3. Compila il file + +![Solidity-compile](../images/solidity/remix-compile.png) + +4. Fai il deploy + +![Solidity-deploy](../images/solidity/remix-deploy.png) + +5. Smanetta con i contratti + +![Solidity-deploy](../images/solidity/remix-interact.png) + +Hai distribuito il tuo primo contratto! Congratulazioni! + +Potrai testarlo e smanettare con le funzioni già definite. Dai un'occhiata ai +commenti per scoprire cosa fanno. + + +## Lavorare su una testnet + +Distribuire e testare su una testnet è il modo più accurato per mettere alla +prova i tuoi smart contract in Solidity. Per farlo procuriamoci prima degli ETH +di test dalla testnet Kovan. + +[Entra in questo Gitter Channel](https://gitter.im/kovan-testnet/faucet) e +scrivici l'indirizzo del tuo wallet Metamask. + +Sul tuo Metamask, dovrai cambiare la testnet in `Kovan`. + +![Solidity-in-remix](../images/solidity/metamask-kovan.png) + +Riceverai degli Ethereum di test gratuiti. Abbiamo bisogno di Ethereum per +distribuire degli smart contract su una testnet. + +Nell'esempio precedente non avevamo usato una testnet, ma avevamo distribuito +su un ambiente virtuale fittizio. Quando si lavora su una testnet, possiamo +davvero monitorare e interagire con i nostri contratti in maniera persistente. + +Per distribuire su una testnet, allo step `#4 Fai il deploy`, cambia +l'`environment` selezionato in `injected web3`. In questo modo verrà usato +come network su cui fare il deploy qualsiasi network selezionato sul tuo +Metamask. + +![Solidity-in-remix](../images/solidity/remix-testnet.png) + +Per ora continua a usare la `Javascript VM` a meno che non ti sia detto di +cambiarla. Quando distribuisci su una testnet, Metamask aprirà un pop up che +ti chiederà di "confermare" la transazione. Premi `yes` e dopo un certo lasso +di tempo, ti apparirà la stessa interfaccia per il contratto nella parte +inferiore dello schermo. + + +```javascript +// Iniziamo con un semplice contratto su una Banca +// Permette di depositare, prelevare e fare l'estratto conto + +// simple_bank.sol (nota l'estensione .sol) +/* **** INIZIO DELL'ESEMPIO **** */ + +// Dichiara la versione del compilatore per il file sorgente +pragma solidity ^0.6.6; + +// Inizia con il commento Natspec (i tre slash) +// viene usato per la documentazione - e per i dati descrittivi per gli elementi +// dell'interfaccia utente / azioni + +/// @title SimpleBank +/// @author nemild + +/* 'contract' somiglia a 'class' in altri linguaggi (ha variabili di classe, +ereditarietà, etc.) */ +contract SimpleBank { // CapWords + // Dichiariamo le variabili di stato fuori dalle funzioni, persisteranno + // durante tutta la vita del contratto + + // i dizionari mappano gli indirizzi con i saldi + // fai sempre attenzione agli overflow attack che sfruttano i numeri + mapping (address => uint) private balances; + + // "private" significa che che altri contratti non possono leggere i + // saldi ma le informazioni restano visibili ad altri attori sulla blockchain + + address public owner; + // 'public' lo rende leggibile dall'esterno (ma non modificabile) dagli + // utenti e dai contratti + + // Gli 'event' pubblicano le azioni in modo che siano ascoltabili da + // listener esterni + event LogDepositMade(address accountAddress, uint amount); + + // I 'constructor' possono ricevere uno o più parametri; Si può + // dichiarare un solo costruttore + constructor() public { + // 'msg' fornisce i dettagli sul messaggio che è stato mandato al contratto + // 'msg.sender' è chi invoca il contratto (l'indirizzo di chi lo crea) + owner = msg.sender; + } + + /// @notice Deposita ether nella banca + /// @return Il saldo dell'utente dopo che è stato effettualto il deposito + function deposit() public payable returns (uint) { + // Usiamo 'require' per testare gli input dell'utente, 'assert' per gli + // invarianti interni. Qui ci assicuriamo di non avere a che fare con + // un overflow + require((balances[msg.sender] + msg.value) >= balances[msg.sender]); + + balances[msg.sender] += msg.value; + // Non servono "this." o "self." con le variabili di stato + // Tutti i valori iniziali delle variabili sono impostati automaticamente + // al valore di default per quel tipo di dato + + emit LogDepositMade(msg.sender, msg.value); // Fa scattare l'evento + + return balances[msg.sender]; + } + + /// @notice Preleva ether dalla banca + /// @dev Non restituisce gli ether inviati in eccesso + /// @param withdrawAmount L'importo che si vuole ritirare + /// @return remainingBal + function withdraw(uint withdrawAmount) public returns (uint remainingBal) { + require(withdrawAmount <= balances[msg.sender]); + + // Notiamo come per prima cosa scaliamo i soldi dal saldo, prima di + // invarli. Ogni .transfer/.send in questo contratto può chiamare una + // funzione esterna. Questa cosa potrebbe permettere a chi invoca la + // funzione di richiedere un importo maggiore del suo saldo usando + // una chiamata ricorsiva. Miriamo ad aggiornare lo stato prima che sia + // chiamata una funzione esterna, incluse .transfer/.send + balances[msg.sender] -= withdrawAmount; + + // Qui lancia automaticamente un errore se fallisce, il che implica + // che il saldo (non più aggiornato) viene ripristinato a prima della + // transazione + msg.sender.transfer(withdrawAmount); + + return balances[msg.sender]; + } + + /// @notice Recupera il saldo + /// @return Il saldo dell'utente + // 'view' (ex: constant) impedisce alle funzioni di modificare lo stato + // delle variabili; consente alle le funzioni di essere disponibili in + // locale/fuori dalla blockchain + function balance() view public returns (uint) { + return balances[msg.sender]; + } +} +// ** FINE DELL'ESEMPIO ** + + +// Passiamo alle basi di Solidity + +// 1. TIPI DI DATO E I LORO METODI +// uint viene usato per gli importi in valuta (non ci sono double o float) +// e per le date (in unix time) +uint x; + +// int di 256 bit, non possono essere modificati dopo l'istanziazione +int constant a = 8; +int256 constant a = 8; // stesso effetto della riga prima, qui viene +// dichiarato esplicitamente che è di 256 bit +uint constant VERSION_ID = 0x123A1; // Una costante esadecimale +// con 'constant', il compilatore rimpiazza ogni occorrenza con il valore + +// Tutte le variabili di stato (quelle fuori da una funzione) +// sono 'interne' di default e accessibili SOLO dall'interno del contratto +// e da tutti contratti che le ereditano +// Bisogna usare esplicitamente 'public' per consentire l'accesso dai contratti +// esterni +int256 public a = 8; + +// Per int e uint possiamo esplicitamente assegnare una dimensione tra 8 e 256 +// es. int8, int16, int24 +uint8 b; +int64 c; +uint248 e; + +// Attenzione a non andare in overflow e a proteggersi dagli attacchi che lo fanno +// Ad esempio per quanto rigrada l'addizione, conviene fare: +uint256 c = a + b; +assert(c >= a); // 'assert' testa gli invarianti interni; require viene usato +// per gli input +// Per altri esempi di problemi comuni con le operazioni aritmentiche, dai una +// occhiata alla Zeppelin's SafeMath library +// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol + + +// Non ci sono funzioni random built-in, puoi ottenere un numero pseudo-casuale +// hashando l'ultimo blockhash, o ottenere un numero realmente casuale usando +// qualcosa come Chainlink VRF. +// https://docs.chain.link/docs/get-a-random-number + +// Conversione di tipo +int x = int(b); + +bool b = true; // oppure 'var b = true;' per l'inferenza di tipo + +// Indirizzi - contengono indirizzi Ethereum di 20 byte/160 bit +// Non sono consentite operazioni aritmetiche +address public owner; + +// Tipi di account: +// Contract account: l'indirizzo viene impostato quando lo si crea (funzione con +// l'indirzzo di chi lo crea, il numero della transazione inviata) +// External Account: (persona/enitità esterna): l'indirizzo viene creato dalla +// chiave pubblica + +// Aggiungi il campo 'public' per indicare che è pubblico/accessibile dall'esterno +// un getter viene creato automaticamente, ma NON un setter + +// Si possono mandare ether a tutti gli indirizzi +owner.transfer(SOME_BALANCE); // fallisce e, in tal caso, ripristina +// lo stato precedente + +// Possiamo anche usare la funzione di livello più basso .send, che restituisce +// false se fallisce +if (owner.send) {} // RICORDA: metti la send in un 'if' dato che gli indirizzi +// usati nei contratti hanno delle funzioni, che vengono eseguite quando viene +// fatta una send, che possono fallire. +// Inoltre fai attenzione a scalare i saldi PRIMA di provare a fare una send, +// dato il rischio di chiamate riscorsive che potrebbero prosciugare il contratto + +// Possiamo controllare il saldo +owner.balance; // il saldo del propietario (utente o contratto) + + +// I Byte sono disposibili in dimensioni da 1 a 32 +byte a; // 'byte' è la stessa cosa di 'bytes1' +bytes2 b; +bytes32 c; + +// Byte con dimensione dinamica +bytes m; // Un array particolare, la stessa cosa dell'array 'byte[]' (ma scritto stringato) +// È più dispendioso di byte1-byte32, che di solito sono preferibili + +// come bytes, ma non permette di accedere alla lunghezza o all'indice (per ora) +string n = "hello"; // salvato in UTF8, nota i doppi apici, non singoli +// le utility function per le stringhe saranno aggiunte in futuro +// sono preferibili bytes32/bytes, dato che UTF8 occupa più memoria + +// Inferenza di tipo +// 'var' fa inferenza di tipo a seconda del primo assegnamento, +// non può essere usata tra i parametri di una funzione +var a = true; +// da usare con cautela, può inferire un tipo errato +// es. un int8 quando un contatore dev'essere un int16 + +// var può essere usata per assegnare una funzione ad una variabile +function a(uint x) returns (uint) { + return x * 2; +} +var f = a; +f(22); // chiamata + +// di default, tutte le variabili sono impostate a 0 durante l'istanziazione + + +// Delete può essere chiamato sulla maggior parte dei valori +// (NON distrugge il valore, ma lo setta a 0, il valore did default) +uint x = 5; + + +// Destructuring/Tuple +(x, y) = (2, 7); // assegna/scambia più valori + + +// 2. STRUTTURE DATI +// Array +bytes32[5] nicknames; // array statico +bytes32[] names; // array dinamico +uint newLength = names.push("John"); // aggiungere un elemento restituisce +// la nuova dimensione dell'array +// Dimesione +names.length; // ottenere la dimensione +names.length = 1; // la dimensione può essere assegnata (solo per gli array nello storage) + +// array multidimensionali +uint[][5] x; // array con 5 array dinamici (ordine opposto rispetto ad +// altri linguaggi) + +// Dizionari (da un tipo qualsiasi a un tipo qualsiasi) +mapping (string => uint) public balances; +balances["charles"] = 1; +// il risultato balances["ada"] è 0, tutte le chiavi non settate +// restituiscono zero +// 'public' permette che si possa fare questo da un altro contratto: +contractName.balances("charles"); // restituisce 1 +// 'public' ha creato getter (ma non un setter), come il seguente: +function balances(string _account) returns (uint balance) { + return balances[_account]; +} + +// Mapping annidati +mapping (address => mapping (address => uint)) public custodians; + +// Fare una delete +delete balances["John"]; +delete balances; // assegna 0 a tutti gli elementi + +// Diversamente da altri linguaggi NON si può iterare tra gli elementi di un +// mapping senza conoscere le chiavi - ma si può costruire una struttura dati a monte +// che lo faccia + +// Strutture dati +struct Bank { + address owner; + uint balance; +} +Bank b = Bank({ + owner: msg.sender, + balance: 5 +}); +// oppure +Bank c = Bank(msg.sender, 5); + +c.balance = 5; // imposta ad un nuovo valore +delete b; +// reimposta, imposta tutte le variabili della struttura a 0, tranne i mapping + +// Enumerazioni +enum State { Created, Locked, Inactive }; // di solito si usano per gli automi a stati finiti +State public state; // Dichiara una variabile da un enum +state = State.Created; +// Le enum possono essere convertite esplicitamente in int +uint createdState = uint(State.Created); // 0 + +// Data location: Memory vs. storage vs. calldata - tutti i tipi complessi +// (array, struct) hanno una data location +// 'memory' non è persistente, 'storage' sì +// Il default è 'storage' per varibili locali e di stato; +// 'memory' per i parametri delle funzioni +// Lo stack può contenere poche varaibili locali + +// Per la maggior parte dei tipi, si può impostare esplicitamente +// quale data location usare + + +// 3. Operatori semplici +// Ci sono operatori logici, a bit e aritmetici +// Potenza: ** +// Or esclusivo: ^ +// Negazione bitwise: ~ + + +// 4. Variabili globali degne di nota +// ** this ** +this; // indirizzo del contratto +// di solito si usa per trasferire altrove il saldo rimanente +// al termine della vita del contratto +this.balance; +this.someFunction(); // invoca una funzione esterna tramite chiamata, +// non attraverso un salto interno + +// ** msg - Il messaggio corrente ricevuto dal contratto ** +msg.sender; // indirizzo di chi ha inviato msg +msg.value; // l'importo di ether forniti a questo contratto espresso in "wei", +// la funzione dovrebbe essere marcata come "payable" +msg.data; // in bytes, tutti gli argomenti del messaggio +msg.gas; // 'gas' restante + +// ** tx - Questa transazione ** +tx.origin; // l'indirizzo di chi ha avviato questa transazione +tx.gasprice; // il prezzo del "gas" per la transazione + +// ** block - Informazioni sul blocco attuale ** +now; // ora corrente (approssimatamente), alias di block.timestamp (in Unix time) +// Da notare come può essere manipolata dai miner, quindi da usare con cautela + +block.number; // numero del blocco attuale +block.difficulty; // difficulty del blocco attuale +block.blockhash(1); // restituisce un bytes32, funziona solo per i 256 blocchi +// più recenti +block.gasLimit(); + +// ** storage - Memoria persistente (in hash) ** +storage['abc'] = 'def'; // mappa da parole di 256 bit a parole di 256 bit + + +// 4. FUNZIONI E ALTRO +// A. Funzioni +// Una semplice funzione +function increment(uint x) returns (uint) { + x += 1; + return x; +} + +// Le funzioni possono restituire molti valori, +// e visto che i valori di ritorno vengono dichiarati prima +// non è richiesta un'instruzione return esplicita +function increment(uint x, uint y) returns (uint x, uint y) { + x += 1; + y += 1; +} +// Chiama la funzione di cui sopra +uint (a,b) = increment(1,1); + +// 'view' (un alias di 'constant') +// indica che la funzione non cambia / non può cambiare le variabili persistenti +// Le funzioni definite con view vengono eseguite localmente, non sulla blockchain +// N.B. la keyword constant sarà presto deprecata +uint y = 1; + +function increment(uint x) view returns (uint x) { + x += 1; + y += 1; // questa riga fallirebbe + // y è una variabile di stato, e non può essere cambiata in una funzione di view +} + +// 'pure' è più restrittivo di 'view' o 'constant', e non +// permette nemmeno di leggere le varaibili di stato +// In realtà è più complicato, per approfondire su +// view/pure: +// http://solidity.readthedocs.io/en/develop/contracts.html#view-functions + +// Modificatori di visibilità per le funzioni +// Possono essere messi vicino a 'view' e includono: +// public - visibile esternamente e internamente (di default per function) +// external - visible solo esternamente (comprese le chiamate fatte con this.) +// private - visibile solo dal contratto attuale +// internal - visibile solo dal contratto attuale, e da quelli che ne derivano + +// Di solito è una buona idea marcare esplicitamente ogni funzione + +// Le funzioni sono hoisted e si può assegnare una funzione ad una variabile +function a() { + var z = b; + b(); +} + +function b() { + +} + +// Tutte le funzioni che ricevono ether devono essere dichiarate come 'payable' +function depositEther() public payable { + balances[msg.sender] += msg.value; +} + + +// I cicli sono da preferire alla ricorsione +// (la profondità massima dello stack è 1024) +// Inoltre, non impostare dei loop senza limiti, +// perchè potresti raggiungere il limite per il gas + +// B. Eventi +// Gli eventi notificano a terze parti; è facile ispezionare e +// accedere agli eventi al di fuori della blockchain (con client leggeri); +// Tipicamente si dichiarano dopo i parametri del contratto + +// Tipicamente, sono capitalized - si usa Log come prefisso per esplicitarli +// meglio ed evitare che si confondano con una chiamata a funzione + +// Dichiarazione +event LogSent(address indexed from, address indexed to, uint amount); +// Da notare le prime lettere maiuscole + +// Chiamata +LogSent(from, to, amount); + +/** + +Una terza parte esterna (entità o contratto), può osservare usando +la libreria Javascript Web3: + +// Quel che se segue è codice Javascript, non Solidity +Coin.LogSent().watch({}, '', function(error, result) { + if (!error) { + console.log("Trasferimento valuta: " + result.args.amount + + " la valuta è stata mandata da " + result.args.from + + " a " + result.args.to + "."); + console.log("I saldi ora sono:\n" + + "Mittente: " + Coin.balances.call(result.args.from) + + "Destinatario: " + Coin.balances.call(result.args.to)); + } +} +**/ + +// È prassi che un contratto dipenda da un altro (es. che dipenda +// dai tassi di cambio forniti da un altro contratto) + +// C. Modifier +// I modifier validano gli input per conto dele funzioni verificando ad esempio +// il saldo minimo o l'autenticazione dell'utente; +// sono simili alle calusole di guardia di altri linguaggi + +// '_' (underscore) viene spesso posizionato nell'ultima riga del body, e indica +// che la funzione chiamata dev'essere posizionata lì +modifier onlyAfter(uint _time) { require (now >= _time); _; } +modifier onlyOwner { require(msg.sender == owner) _; } +// usate comunemente negli automi a stati finiti +modifier onlyIfStateA (State currState) { require(currState == State.A) _; } + +// Si dichiarano appena dopo la definizione di una funzione +function changeOwner(newOwner) +onlyAfter(someTime) +onlyOwner() +onlyIfState(State.A) +{ + owner = newOwner; +} + +// L'underscore può essere messo prima della fine del body, +// ma un'istruzione di ritorno esplicita lo salterebbe, +// quindi è da usare con cautela +modifier checkValue(uint amount) { + _; + if (msg.value > amount) { + uint amountToRefund = amount - msg.value; + msg.sender.transfer(amountToRefund); + } +} + + +// 6. ISTRUZIONI CONDIZIONALI E CICLI + +// Troviamo tutte le istruzioni condizionali di base - incluse if/else, for, +// while, break, continue e return - ma non c'è lo switch + +// La sintassi è la stessa di javascript, ma non esiste la conversione di tipo +// in booleano dai non booleani (bisogna usare gli operatori logici per +// ottenere il valore boolean) + +// Bisogna stare attenti i loop che iterano in base al comportamento +// dell'utente, dato che i contratti hanno un tetto massimo di gas +// per blocco di codice e falliranno se lo superano +// Ad esempio: +for(uint x = 0; x < refundAddressList.length; x++) { + refundAddressList[x].transfer(SOME_AMOUNT); +} + +// Ci sono due errori nel codice precedente: +// 1. Un fallimento su una transfer impedisce al loop di completare tutti +// i cicli, bloccando dei soldi; +// 2. Questo loop potrebbe essere arbitrariamente lungo (si basa sul numero +// degli utenti che hanno diritto al rimborso), quindi potrebbe fallire sempre +// se supera il tetto massimo di gas per blocco; +// Come soluzione, si permette agli utenti di prelevare +// individualmente dal loro subaccount e segnare il rimborso come riscosso +// Ad es. preferire pull payments ai push payment + + +// 7. OGGETTI/CONTRATTI + +// A. Invocare un contratto esterno +contract InfoFeed { + function info() payable returns (uint ret) { return 42; } +} + +contract Consumer { + InfoFeed feed; // punta ad un contratto sulla blockchain + + // Imposta il feed sull'istanza del contratto esistente + function setFeed(address addr) { + // fare attenzione alla conversione di tipo automatica; + // il costruttore non viene invocato + feed = InfoFeed(addr); + } + + // Imposta il feed ad una nuova istanza del contratto + function createNewFeed() { + feed = new InfoFeed(); // viene creata una nuova istanza; + // viene invocato il costruttore + } + + function callFeed() { + // le parentesi finali invocano il contratto, opzionalmente si può + // specificare un importo custom di ether o di gas + feed.info.value(10).gas(800)(); + } +} + +// B. ereditarietà + +// Conta l'ordine, l'ultimo contratto ereditato (es. 'def') può andare +// in overriding su parti dei contratti precedentemente ereditati +contract MyContract is abc, def("a custom argument to def") { + +// Funzione in overriding + function z() { + if (msg.sender == owner) { + def.z(); // invoca la funzione overridden da def + super.z(); // chiama la funzione overridden del padre + } + } +} + +// Funzioni astratte +function someAbstractFunction(uint x); +// non possono essere compilate, vengono usate nei contratti base/astratti +// e poi verranno implementate + +// C. Import + +import "filename"; +import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; + + +// 8. ALTRE KEYWORD + +// A. Selfdestruct +// autodistrugge il contratto corrente, inviando i fondi ad un indirizzo +// (di solito il creatore) +selfdestruct(SOME_ADDRESS); + +// rimuove il codice e quanto in memoria dal blocco corrente e da tutti i blocchi futuri +// aiuta ad alleggerire i client, ma le informazioni precedenti continueranno +// a persistere sulla blockchain + +// È un pattern comune, permette al proprietario di terminare il contratto +// e ricevere i fondi rimasti +function remove() { + if(msg.sender == creator) { // Solo il creatore del contratto può farlo + selfdestruct(creator); // Cessa l'attività del contratto, trasferisce i fondi + } +} + +// Si potrebbe voler disattivare il contratto manualmente, anzichè usare una +// selfdestruct (gli ether inviati ad un contratto dopo una selfdestruct +// vengono persi) + + +// 9. NOTE SUL DESIGN DEI CONTRATTI + +// A. Offruscamento +// Tutte le variabili sono pubblicamente visibili sulla blockchain, quindi +// qualsiasi informazione privata ha bisogno di essere offruscata (es. hash con una +// chiave segreta) + +// Passi: 1. Impegnarsi pagare una certa cifra, 2. Rivelare l'impegno preso +keccak256("una_puntata_d_asta", "un segreto"); // impegno + +// in futuro, l'invocazione della funzione rivelatrice del contratto +// mostrerà la puntata con il segreto che produce lo SHA3 +reveal(100, "ilMioSegreto"); + +// B. Ottimizzazione della memoria (storage) +// Scrivere dati sulla blockchain può essere costoso visto che vengono +// conservati per sempre; siamo incoraggati ad usare la memoria in maniera +// scaltra (un giorno la compilazione migliorerà, ma per ora è vantaggioso +// pianificare le strutture dati da usare - e conservarne il minimo possibile +// sulla blockchain) + +// I costi per conservare cose come array multidimensionali sono spesso alti +// (costa conservare dati - non dichiarare variabili parzialmente vuote) + +// C. Accesso ai dati sulla blockchain +// Non si può impedire alle persone o ai computer di leggere il contenuto +// o lo stato delle transazioni + +// Anche se 'private' non permette agli altri *contratti* di leggere alcune +// informazioni direttamente, qualsiasi altro attore può leggerle +// sulla blockchain + +// Tutti i dati, dall'inizio, vegono conservati sulla blockchain e +// tutti possono accedere alle informazioni passate e ai cambiamenti futuri + +// D. Oracle e dati esterni +// Gli oracle consentono di interagire con i tuoi smart contract +// al di fuori della blockchain. +// Vengono usati per ricevere informazioni dal mondo reale, mandare +// richieste post al mondo reale o vice versa. + +// Anche le implementazioni che sfruttano l'ora vengono fatte attraverso +// gli oracle, visto che i contratti devono essere chiamati direttamente e +// non possono fare una "subscribe" a un certo orario. +// Data la decentralizzazione degli smart contract, vorrai ricevere informazioni +// in maniera decentralizzata, altrimenti rischi di ricreare l'accentramento +// che la progettazione degli smart contract si prefigge di prevenire. + +// Il modo migliore di ottenere e usare dati decentralizzati già pronti +// è attraverso i Chainlink Data Feeds +// https://docs.chain.link/docs/get-the-latest-price +// Possiamo fare riferimento a certe informazioni della blockchain +// che sono già state aggregate da più fonti e ridistribuite on-chain, +// usandole come "banche dati" di fonti di informazione. + +// Puoi vedere altri esempi che effettuano chiamate alle API qui: +// https://docs.chain.link/docs/make-a-http-get-request + +// E ovviamente puoi costruire la tua rete di orace, ma assicurati di sapere +// quant'è accentrata o decentralizzata la tua applicazione. + +// Mettere su una rete di oracle per conto tuo + +// E. Cron Job +// I contratti devono essere chiamati manualmente per gestire lo scheduling +// in base all'orario; si può creare un codice esterno che li pinghi reglarmente +// oppure fornire degli incentivi (ether) a qualcun'altro che lo faccia + +// F. Pattern Observer +// Un pattern observer permette di iscriversi come osservatore e +// registrare una funzione che verrà chiamata dall'oracle +// (N.B. l'oracolo paga perchè sia eseguita quest'azione) +// Ci sono alcune somoglianze nella registrazione con Pub/sub + +// Questo è un contratto astratto che importano sia il client che il server +// Il client dovrebbe implementarlo +contract SomeOracleCallback { + function oracleCallback(int _value, uint _time, bytes32 info) external; +} + +contract SomeOracle { + SomeOracleCallback[] callbacks; // array di tutti gli osservatori iscritti + + // Osservatori iscritti + function addSubscriber(SomeOracleCallback a) { + callbacks.push(a); + } + + function notify(value, time, info) private { + for(uint i = 0;i < callbacks.length; i++) { + // tutti gli osservatori iscritti dovranno implementare la oracleCallback + callbacks[i].oracleCallback(value, time, info); + } + } + + function doSomething() public { + // Codice che fa qualcosa + + // Notifica a tutti gli iscritti + notify(_value, _time, _info); + } +} + +// Il contratto client può aggiungersi agli iscritti (con addSubscriber) +// del contratto SomeOracle, importando SomeOracleCallback + +// G. Automi a stati finiti +// vedi l'esempio sotto che usa enum per lo stato e il modifier inState +``` + +Prova l'esempio completo qui sotto [usando remix e la `Javascript VM`](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=3d12cd503dcedfcdd715ef61f786be0b&runs=200) + +```javascript +// *** ESEMPIO: Un esempio di crowdfunding (molto simile a Kickstarter) *** +// ** START EXAMPLE ** + +// CrowdFunder.sol +pragma solidity ^0.6.6; + +/// @title CrowdFunder +/// @author nemild +contract CrowdFunder { + // Variabili impostate alla creazione dal creatore + address public creator; + address payable public fundRecipient; // il creatore può essere diverso + // da chi riceve i fondi, che dev'essere payable + uint public minimumToRaise; // è richiesto per chiedere il finanziamento, + // altrimenti tutti ricevono un rimborso + string campaignUrl; + byte version = "1"; + + // Strutture dati + enum State { + Fundraising, + ExpiredRefund, + Successful + } + struct Contribution { + uint amount; + address payable contributor; + } + + // Variabili di stato + State public state = State.Fundraising; // inizializzato alla creazione + uint public totalRaised; + uint public raiseBy; + uint public completeAt; + Contribution[] contributions; + + event LogFundingReceived(address addr, uint amount, uint currentTotal); + event LogWinnerPaid(address winnerAddress); + + modifier inState(State _state) { + require(state == _state); + _; + } + + modifier isCreator() { + require(msg.sender == creator); + _; + } + + // Aspetta 24 settimane dopo l'ultimo cambio di stato prima di consentire + // che in contratto venga distrutto + modifier atEndOfLifecycle() { + require(((state == State.ExpiredRefund || state == State.Successful) && + completeAt + 24 weeks < now)); + _; + } + + function crowdFund( + uint timeInHoursForFundraising, + string memory _campaignUrl, + address payable _fundRecipient, + uint _minimumToRaise) + public + { + creator = msg.sender; + fundRecipient = _fundRecipient; + campaignUrl = _campaignUrl; + minimumToRaise = _minimumToRaise; + raiseBy = now + (timeInHoursForFundraising * 1 hours); + } + + function contribute() + public + payable + inState(State.Fundraising) + returns(uint256 id) + { + contributions.push( + Contribution({ + amount: msg.value, + contributor: msg.sender + }) // usiamo un array per iterare + ); + totalRaised += msg.value; + + emit LogFundingReceived(msg.sender, msg.value, totalRaised); + + checkIfFundingCompleteOrExpired(); + return contributions.length - 1; // restituisce l'id + } + + function checkIfFundingCompleteOrExpired() + public + { + if (totalRaised > minimumToRaise) { + state = State.Successful; + payOut(); + + // qui si può incentivare chi ha provocato il cambiamento di stato + } else if ( now > raiseBy ) { + state = State.ExpiredRefund; // ora i finanziatori possono avere + // il rimborso chiamando getRefund(id) + } + completeAt = now; + } + + function payOut() + public + inState(State.Successful) + { + fundRecipient.transfer(address(this).balance); + LogWinnerPaid(fundRecipient); + } + + function getRefund(uint256 id) + inState(State.ExpiredRefund) + public + returns(bool) + { + require(contributions.length > id && id >= 0 && contributions[id].amount != 0 ); + + uint256 amountToRefund = contributions[id].amount; + contributions[id].amount = 0; + + contributions[id].contributor.transfer(amountToRefund); + + return true; + } + + function removeContract() + public + isCreator() + atEndOfLifecycle() + { + selfdestruct(msg.sender); + // il creatore riceve tutti i fondi che non sono stati riscossi + } +} +// ** END EXAMPLE ** + +``` + +Qualche altra funzionalità. + +```javascript +// 10. ATRE FUNZIONALITA' NATIVE + +// Unità di valuta +// La valuta viene definita partendo dai wei, l'unità più piccola di Ether +uint minAmount = 1 wei; +uint a = 1 finney; // 1 ether == 1000 finney +// Per altre unità, vedi: http://ether.fund/tool/converter + +// Unità temporali +1 == 1 second +1 minutes == 60 seconds + +// Le unità temporali si possono moltiplicare, visto che non vegono salvate +// nelle variabili +uint x = 5; +(x * 1 days); // 5 giorni + +// Attenzione ad usare l'operatore di uguaglianza con i secondi/anni bisestili +// (sono da preferire maggiore/minore di) + +// Crittografia +// Tutte le stringhe che vengono passate vengono concatenate prima di +// calcolare l'hash +sha3("ab", "cd"); +ripemd160("abc"); +sha256("def"); + + +// 11.SICUREZZA + +// I bug possono essere disastrosi per i contratti Ethereum e anche +// i pattern comuni di Solidity potrebbero riverlarsi degli antipattern + +// Dai un'occhiata ai link sulla sicurezza alla fine di questo documento + + +// 12. FUNZIONI DI BASSO LIVELLO +// call - è di basso livello, non viene usata spesso, perchè non è type safe +successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); + +// callcode - Il codice all'indirizzo target viene eseguito *contestualmente* +// alla chiamata del contratto +// fornisce le stesse funzionalità di una libreria +someContractAddress.callcode('function_name'); + + +// 13. NOTE SULLO STILE +// Basate sulla guida allo stile PEP8 di Python +// Guida completa allo stile: http://solidity.readthedocs.io/en/develop/style-guide.html + +// Riassunto veloce: +// 4 spazi per l'indentazione +// Due righe per separare la dichiarazione dei contratti +// (e altre dichirazioni top level) +// Evitare spazi ai lati interni delle parentesi tonde +// Si possono omettere le parentesi graffe per statement monolinea (if, for, etc) +// L'else dovrebbe essere posizionato su una riga a se + +// 14. COMMENTI NATSPEC +// usati per la documentazione, commenti e UI esterne + +// Natspec dei contratti - sempre sopra la definizione del contratto +/// @title Titolo del contratto +/// @author Nome dell'autore + +// Natspec delle funzioni +/// @notice informazioni su quel che fa la funzione; mostrate quando la funzione viene eseguita +/// @dev Documentazione della funzione per sviluppatori + +// Natspec dei parametri/valori di ritorno delle funzioni +/// @param someParam Una descrizione di quel che fa il parametro +/// @return Descrizione del valore di ritorno +``` + +## Risorse Aggiuntive +- [Documentazione di Solidity](https://solidity.readthedocs.org/en/latest/) +- [Tutorial Chainlink per Principianti](https://docs.chain.link/docs/beginners-tutorial) +- [Best Practice per Smart Contract](https://github.com/ConsenSys/smart-contract-best-practices) +- [Superblocks Lab - Ambiente di sviluppo su browser per Solidity](https://lab.superblocks.com/) +- [EthFiddle - Il JsFiddle di Solidity](https://ethfiddle.com/) +- [Solidity Editor su Browser](https://remix.ethereum.org/) +- [Chat Room Gitter su Solidity](https://gitter.im/ethereum/solidity) +- [Stategie di Progettazione Modulare per Contratti Ethereum](https://docs.erisindustries.com/tutorials/solidity/) +- [Documentazione Chainlink](https://docs.chain.link/docs/getting-started) + +## Framework di Sviluppo per Smart Contract +- [Hardhat](https://hardhat.org/) +- [Brownie](https://github.com/eth-brownie/brownie) +- [Truffle](https://www.trufflesuite.com/) + +## Librerie importanti +- [Zeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts): Librerie che offrono pattern comuni (crowdfuding, safemath, ecc) +- [Chainlink](https://github.com/smartcontractkit/chainlink): Codice che permette di interagire con dati esterni + +## Contratti di esempio +- [Dapp Bin](https://github.com/ethereum/dapp-bin) +- [Esempi Defi](https://github.com/PatrickAlphaC/chainlink_defi) +- [Solidity per Contratti a Piccoli Passi](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) +- [Contratti ConsenSys](https://github.com/ConsenSys/dapp-store-contracts) +- [Lo stato delle Dapp](http://dapps.ethercasts.com/) + +## Sicurezza +- [Pensando Alla Sicurezza Degli Smart Contract](https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security/) +- [Sicurezza Degli Smart Contract](https://blog.ethereum.org/2016/06/10/smart-contract-security/) +- [Blog Distribuito di Hacking](http://hackingdistributed.com/) + +## Stile +- [Guida allo Stile di Solidity](http://solidity.readthedocs.io/en/latest/style-guide.html): La guida allo stile di Ethereum deriva in gran parte dalla guida allo stile [PEP 8](https://www.python.org/dev/peps/pep-0008/) di Python. + +## Editor +- [Remix](https://remix.ethereum.org/) +- [Emacs Modalità Solidity](https://github.com/ethereum/emacs-solidity) +- [Vim Solidity](https://github.com/tomlion/vim-solidity) +- Snippet per gli Editor ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) + +## Cose da fare in futuro +- Nuove keyword: protected, inheritable +- Lista dei design pattern comuni (throttling, RNG, upgrade di versione) +-Anti patterns comuni sulla sicurezza + +Sentiti libero di mandare una pull request con qualsiasi modifica - o scrivi una mail a nemild -/at-/ gmail diff --git a/javascript.html.markdown b/javascript.html.markdown index b290b553..41ed7dea 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -620,7 +620,7 @@ function isEven(number) { }; // I put the word "equivalent" in double quotes because a function defined -// using the lambda syntax cannnot be called before the definition. +// using the lambda syntax cannot be called before the definition. // The following is an example of invalid usage: add(1, 8); @@ -671,6 +671,7 @@ Mozilla Developer Network. [5]: http://bonsaiden.github.io/JavaScript-Garden/ [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: https://www.javascripttutorial.net/ [8]: http://eloquentjavascript.net/ [10]: http://jstherightway.org/ [11]: https://javascript.info/ diff --git a/json.html.markdown b/json.html.markdown index 1ccdb5cf..27f6bbe0 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -11,7 +11,7 @@ contributors: JSON is an extremely simple data-interchange format. As [json.org](https://json.org) says, it is easy for humans to read and write and for machines to parse and generate. -A piece of JSON must represent either: +A piece of JSON can be any value of the types listed later, but in practice almost always represents either: * A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence. diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown index 241caf5f..f077c35b 100644 --- a/jsonnet.html.markdown +++ b/jsonnet.html.markdown @@ -131,7 +131,7 @@ assert obj5 == {}; ``` ## Further Reading -There are a few but important concepts that are not touched in this exmaple, including: +There are a few but important concepts that are not touched in this example, including: - Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config) - Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports) diff --git a/julia.html.markdown b/julia.html.markdown index 4d8eb497..336cd2b8 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -356,6 +356,20 @@ intersect(filledSet, otherSet) # => Set([4, 3, 5]) union(filledSet, otherSet) # => Set([4, 2, 3, 5, 6, 1]) setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) +# Assignment with `=` attaches a new label to the same value without copying +a = [1, 2, 3] +b = a +# Now `b` and `a` point to the same value, so changing one affects the other: +a[3] = 5 +b[3] # => 5 + +# The `copy()` function can create a shallow copy of an array, dictionary, +# or other container +a = [1, 2, 3] +c = copy(a) +a[3] = 5 +c[3] # => 3 + #################################################### ## 3. Control Flow #################################################### diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 680c01c1..db842726 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -560,7 +560,7 @@ select avg height by sex from t / => f | 160 / => m | 177.5 -/ If no aggreation function is specified, last is assumed +/ If no aggregation function is specified, last is assumed select by sex from t / => sex| name age height / => ---| ----------------- diff --git a/ko-kr/clojure-kr.html.markdown b/ko-kr/clojure-kr.html.markdown index 1d9e53cd..32a5baf3 100644 --- a/ko-kr/clojure-kr.html.markdown +++ b/ko-kr/clojure-kr.html.markdown @@ -377,7 +377,7 @@ Clojuredocs.org는 core 함수들에 대해 다양한 예제와 문서를 보유 [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure는 clojure/FP 스킬을 올릴 수 있는 좋은 길입니다: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org는 많고 많은 문서들을 보유하고 있습니다: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown index 958dd746..775907c2 100644 --- a/lambda-calculus.html.markdown +++ b/lambda-calculus.html.markdown @@ -41,7 +41,7 @@ Evaluation is done via which is essentially lexically-scoped substitution. When evaluating the -expression `(λx.x)a`, we replace all occurences of "x" in the function's body +expression `(λx.x)a`, we replace all occurrences of "x" in the function's body with "a". - `(λx.x)a` evaluates to: `a` diff --git a/latex.html.markdown b/latex.html.markdown index 34c4b78d..9edc057e 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -320,3 +320,5 @@ That's all for now! * The amazing LaTeX Wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) * An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) * A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes) +* An interactive platform to learn LaTeX (installationfree) [learnlatex.org/](https://www.learnlatex.org/) +* Stack Exchange's question and answer site about TeX, LaTeX, ConTeXt, etc. [tex.stackexchange.com](https://tex.stackexchange.com/) diff --git a/lbstanza.html.markdown b/lbstanza.html.markdown index 19dc7db7..90e7b7e5 100644 --- a/lbstanza.html.markdown +++ b/lbstanza.html.markdown @@ -8,7 +8,7 @@ contributors: LB Stanza (or Stanza for short) is a new optionally-typed general purpose programming language from the University of California, Berkeley. Stanza was designed to help programmers tackle the complexity of architecting large programs and significantly increase the productivity of application programmers across the entire software development life cycle. -```stanza +``` ; this is a comment ;<A> This is a block comment @@ -193,7 +193,7 @@ while condition[0]: for i in 0 to 10 do: vector[i] = i -; stanza also supports named labels which can functin as break or return +; stanza also supports named labels which can function as break or return ; statements defn another-fn (): label<False> return: @@ -218,7 +218,7 @@ for (x in xs, y in ys, z in zs) do : println("x:%_, y:%_, z:%_" % [x, y, z]) -;xs, ys, and zs are all "Seqable" meaing they are Seq types (sequences). +;xs, ys, and zs are all "Seqable" meaning they are Seq types (sequences). ; the `do` identifier is a special function that just applies the body of ; the for loop to each element of the sequence. ; @@ -268,7 +268,7 @@ is-there = any?({_ == 2.0}, numbers) doc: \<doc> # Document Strings - ```stanza + ``` val you-can = "include code snippets, too" ``` @@ -279,4 +279,4 @@ doc: \<doc> ``` \<doc> defn docfn () : false -```
\ No newline at end of file +``` diff --git a/ldpl.html.markdown b/ldpl.html.markdown index 86603d94..449c8670 100644 --- a/ldpl.html.markdown +++ b/ldpl.html.markdown @@ -3,6 +3,7 @@ language: LDPL filename: learnLDPL.ldpl contributors: - ["Martín del Río", "https://github.com/lartu"] + - ["John Paul Wohlscheid", "https://github.com/JohnBlood"] --- **LDPL** is a powerful, C++ transpiled, open-source programming language designed @@ -68,7 +69,7 @@ else if myMap:"someIndex" is not equal to 45 then else display "Else!" crlf end if -# Valid LDPL comparisson operators are +# Valid LDPL comparison operators are # - IS EQUAL TO # - IS NOT EQUAL TO # - IS LESS THAN @@ -123,8 +124,8 @@ get random in myNumber # get a random number between 0 and 1 # files, are divided in sections. The sections found in sub-procedures are # the PARAMETERS section, the LOCAL DATA section and the PROCEDURE section. # All sections except the PROCEDURE section can be skipped if they aren't -# used. If no PARAMTERS nor LOCAL DATA sections are used, the PROCEDURE -# keyword may be omited. +# used. If no PARAMETERS nor LOCAL DATA sections are used, the PROCEDURE +# keyword may be omitted. sub myFunction parameters: a is number # LDPL is pass by reference diff --git a/lua.html.markdown b/lua.html.markdown index ac7883b2..de71ccd4 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -58,7 +58,7 @@ foo = anUnknownVariable -- Now foo = nil. aBoolValue = false -- Only nil and false are falsy; 0 and '' are true! -if not aBoolValue then print('twas false') end +if not aBoolValue then print('it was false') end -- 'or' and 'and' are short-circuited. -- This is similar to the a?b:c operator in C/js: @@ -193,7 +193,7 @@ end -- A table can have a metatable that gives the table -- operator-overloadish behavior. Later we'll see --- how metatables support js-prototypey behavior. +-- how metatables support js-prototype behavior. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} @@ -364,7 +364,7 @@ end)() -- locals inside mod.lua are invisible outside it. -- This works because mod here = M in mod.lua: -mod.sayHello() -- Says hello to Hrunkner. +mod.sayHello() -- Prints: Why hello there Hrunkner -- This is wrong; sayMyName only exists in mod.lua: mod.sayMyName() -- error @@ -406,7 +406,7 @@ I started with <a href="https://ebens.me/post/lua-for-programmers-part-1/">Black Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book. That's the how. -It might be helpful to check out the <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short +It might be helpful to check out the <a href="http://lua-users.org/wiki/LuaShortReference">Lua short reference</a> on lua-users.org. The main topics not covered are standard libraries: diff --git a/m.html.markdown b/m.html.markdown index 96828ae5..87e0875e 100644 --- a/m.html.markdown +++ b/m.html.markdown @@ -198,7 +198,7 @@ M has an execution stack. When all levels of the stack have returned, the progra With an argument: execute a block of code & add a level to the stack. ``` -d ^routine ;run a routine from the begining. +d ^routine ;run a routine from the beginning. ; ;routines are identified by a caret. d tag ;run a tag in the current routine d tag^routine ;run a tag in different routine diff --git a/markdown.html.markdown b/markdown.html.markdown index 60ca1323..fefb60f6 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -40,9 +40,9 @@ specific to a certain parser. Markdown is a superset of HTML, so any HTML file is valid Markdown. ```md -<!--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 in your markdown file, you cannot use markdown syntax +<!--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 in your markdown file, you cannot use markdown syntax within that element's contents.--> ``` @@ -169,9 +169,9 @@ render the numbers in order, but this may not be a good idea. 1. Item three ``` -(This renders the same as the above example) +(This renders the same as the example above.) -You can also use sublists +You can also use sublists. ```md 1. Item one @@ -203,7 +203,7 @@ a line with four spaces or a tab. ``` You can also re-tab (or add an additional four spaces) for indentation -inside your code +inside your code. ```md my_array.each do |item| @@ -211,13 +211,13 @@ inside your code end ``` -Inline code can be created using the backtick character `` ` `` +Inline code can be created using the backtick character `` ` ``. ```md John didn't even know what the `go_to()` function did! ``` -In GitHub Flavored Markdown, you can use a special syntax for code +In GitHub Flavored Markdown, you can use a special syntax for code. <pre> <code class="highlight">```ruby @@ -227,7 +227,7 @@ end ```</code></pre> The above text doesn't require indenting, plus GitHub will use syntax -highlighting of the language you specify after the \`\`\` +highlighting of the language you specify after the opening <code>```</code>. ## Horizontal rule @@ -278,7 +278,7 @@ There is also "implicit naming" which lets you use the link text as the id. <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> +[<span class="nv">This</span>]: <span class="sx">http://thisisalink.com/</span></code></pre> But it's not that commonly used. @@ -298,7 +298,7 @@ omitted though.) - [Subchapter <h3 />](#subchapter-h3-) ``` -Nontheless, this is a feature that might not be working in all Markdown +Nonetheless, this is a feature that might not be working in all Markdown implementations the same way. ## Images @@ -370,9 +370,10 @@ Ugh this is so ugly | make it | stop ## Markdownlint In order to simplify work with Markdown and to unify its coding style, -`Markdownlint` has been created. This tool is available also as a plugin for -some IDEs and can be used as an utility to ensure validity and readability of -Markdown. +`Markdownlint` has been created. Available as a +[separate tool](https://github.com/markdownlint/markdownlint) +as well as a plugin for some IDEs, it can be used to ensure validity and +readability of Markdown. --- diff --git a/matlab.html.markdown b/matlab.html.markdown index ecf2fc96..b0482d0b 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -1,5 +1,5 @@ --- -language: Matlab +language: MATLAB filename: learnmatlab.mat contributors: - ["mendozao", "http://github.com/mendozao"] @@ -134,7 +134,7 @@ A.d.e = false; % Vectors x = [4 32 53 7 1] -x(2) % ans = 32, indices in Matlab start 1, not 0 +x(2) % ans = 32, indices in MATLAB start 1, not 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -502,7 +502,7 @@ find(x) % Finds all non-zero elements of x and returns their indexes, can use co % Classes -% Matlab can support object-oriented programming. +% MATLAB can support object-oriented programming. % Classes must be put in a file of the class name with a .m extension. % To begin, we create a simple class to store GPS waypoints. % Begin WaypointClass.m @@ -524,7 +524,7 @@ classdef WaypointClass % The class name. end % If we want to add two Waypoint objects together without calling - % a special function we can overload Matlab's arithmetic like so: + % a special function we can overload MATLAB's arithmetic like so: function r = plus(o1,o2) r = WaypointClass([o1.latitude] +[o2.latitude], ... [o1.longitude]+[o2.longitude]); @@ -536,7 +536,7 @@ end % We can create an object of the class using the constructor a = WaypointClass(45.0, 45.0) -% Class properties behave exactly like Matlab Structures. +% Class properties behave exactly like MATLAB Structures. a.latitude = 70.0 a.longitude = 25.0 @@ -547,15 +547,15 @@ ans = multiplyLatBy(a,3) % does not need to be passed to the method. ans = a.multiplyLatBy(1/3) -% Matlab functions can be overloaded to handle objects. -% In the method above, we have overloaded how Matlab handles +% MATLAB functions can be overloaded to handle objects. +% In the method above, we have overloaded how MATLAB handles % the addition of two Waypoint objects. b = WaypointClass(15.0, 32.0) c = a + b ``` -## More on Matlab +## More on MATLAB * [The official website](http://www.mathworks.com/products/matlab/) * [The official MATLAB Answers forum](http://www.mathworks.com/matlabcentral/answers/) diff --git a/mercurial.html.markdown b/mercurial.html.markdown index 98658f83..2c06ca77 100644 --- a/mercurial.html.markdown +++ b/mercurial.html.markdown @@ -22,13 +22,13 @@ and/or directorie(s) over time. * Distributed Architecture - Traditionally version control systems such as CVS and Subversion are a client server architecture with a central server to -store the revsion history of a project. Mercurial however is a truly -distributed architecture, giving each devloper a full local copy of the +store the revision history of a project. Mercurial however is a truly +distributed architecture, giving each developer a full local copy of the entire development history. It works independently of a central server. * Fast - Traditionally version control systems such as CVS and Subversion are a -client server architecture with a central server to store the revsion history +client server architecture with a central server to store the revision history of a project. Mercurial however is a truly distributed architecture, giving -each devloper a full local copy of the entire development history. It works +each developer a full local copy of the entire development history. It works independently of a central server. * Platform Independent - Mercurial was written to be highly platform independent. Much of Mercurial is written in Python, with small performance @@ -56,7 +56,7 @@ any later version. | changeset | Set of changes saved as diffs | | diff | Changes between file(s) | | tag | A named named revision | -| parent(s) | Immediate ancestor(s) of a revison | +| parent(s) | Immediate ancestor(s) of a revision | | branch | A child of a revision | | head | A head is a changeset with no child changesets | | merge | The process of merging two HEADS | @@ -184,7 +184,7 @@ Commit changes to the given files into the repository. # Commit with a message $ hg commit -m 'This is a commit message' -# Commit all added / removed files in the currrent tree +# Commit all added / removed files in the current tree $ hg commit -A 'Adding and removing all existing files in the tree' # amend the parent of the working directory with a new commit that contains the @@ -341,7 +341,7 @@ $ hg revert -a Remove the specified files on the next commit. ```bash -# Remove a spcific file +# Remove a specific file $ hg remove go_away.txt # Remove a group of files by pattern diff --git a/mips.html.markdown b/mips.html.markdown index 0e7a7d0c..3add0c5b 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -111,7 +111,7 @@ gateways and routers. sub $t2, $t0, $t1 # $t2 = $t0 - $t1 mul $t2, $t0, $t1 # $t2 = $t0 * $t1 div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be - # supported in some versons of MARS) + # supported in some versions of MARS) div $t0, $t1 # Performs $t0 / $t1. Get the # quotient using 'mflo' and # remainder using 'mfhi' @@ -162,7 +162,7 @@ gateways and routers. blt $t0, $t1, t0_gt_t1 # Branches when $t0 < $t1 ble $t0, $t1, t0_gte_t1 # Branches when $t0 <= $t1 bltz $t0, t0_lt0 # Branches when $t0 < 0 - slt $s0, $t0, $t1 # Instruction that sends a signal + slt $s0, $t0, $t1 # "Set on Less Than" # when $t0 < $t1 with result in $s0 # (1 for true) @@ -186,6 +186,7 @@ gateways and routers. # else # max = c; # else + # if (b > c) # max = b; # else # max = c; @@ -212,8 +213,9 @@ gateways and routers. # instruction to continue its execution li $t0, 0 while: - bgt $t0, 10, end_while # While $t0 is less than 10, + bgt $t0, 9, end_while # While $t0 is less than 10, # keep iterating + #actual loop content would go here addi $t0, $t0, 1 # Increment the value j while # Jump back to the beginning of # the loop diff --git a/mongodb.html.markdown b/mongodb.html.markdown index 959b57d0..306f361c 100644 --- a/mongodb.html.markdown +++ b/mongodb.html.markdown @@ -256,7 +256,7 @@ db.engineers.find({ $gt: { age: 25 }}) db.engineers.find({ $gte: { age: 25 }}) // Find all less than or less than equal to some condition -db.engineers.find({ $lte: { age: 25 }}) +db.engineers.find({ $lt: { age: 25 }}) db.engineers.find({ $lte: { age: 25 }}) // Find all equal or not equal to @@ -293,7 +293,7 @@ db.engineers.find({ $not: { // Must match none of the query conditions db.engineers.find({ $nor [ - gender: 'Female, + gender: 'Female', age: { $gte: 18 } @@ -400,6 +400,6 @@ features, I would look at - Aggregation - useful for creating advanced queries to be executed by the database -- Idexing allows for caching, which allows for much faster execution of queries +- Indexing allows for caching, which allows for much faster execution of queries - Sharding allows for horizontal data scaling and distribution between multiple machines. diff --git a/montilang.html.markdown b/montilang.html.markdown index cceb7aa1..483dc5a5 100644 --- a/montilang.html.markdown +++ b/montilang.html.markdown @@ -170,7 +170,7 @@ printseven /# currently, preprocessor statements can be used to make c++-style constants #/ &DEFINE LOOPSTR 20& -/# must have & on either side with no spaces, 'DEFINE' is case sensative. #/ +/# must have & on either side with no spaces, 'DEFINE' is case sensitive. #/ /# All statements are scanned and replaced before the program is run, regardless of where the statements are placed #/ FOR LOOPSTR 7 PRINT . ENDFOR /# Prints '7' 20 times. At run, 'LOOPSTR' in source code is replaced with '20' #/ diff --git a/ms-my/clojure-my.html.markdown b/ms-my/clojure-my.html.markdown index e199c8f4..cfcdeb40 100644 --- a/ms-my/clojure-my.html.markdown +++ b/ms-my/clojure-my.html.markdown @@ -413,7 +413,7 @@ Clojuredocs.org mempunyai dokumentasi berserta contoh untuk menggunakan kebanyak [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure ialah cara yang baik untuk mengasah skill Clojure dan functional programming: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org (yup, serius) juga mengandungi beberapa artikel sebagai permulaan: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/nim.html.markdown b/nim.html.markdown index 9730e579..b10bd75a 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -142,7 +142,7 @@ when compileBadCode: # Arrays type - RollCounter = array[DieFaces, int] # Array's are fixed length and + RollCounter = array[DieFaces, int] # Arrays are fixed length and DirNames = array[Direction, string] # indexed by any ordinal type. Truths = array[42..44, bool] var diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 70668611..fcd12951 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -3,26 +3,29 @@ language: OCaml filename: learnocaml.ml contributors: - ["Daniil Baturin", "http://baturin.org/"] + - ["Stanislav Modrak", "https://stanislav.gq/"] --- OCaml is a strictly evaluated functional language with some imperative features. -Along with StandardML and its dialects it belongs to ML language family. +Along with Standard ML and its dialects it belongs to ML language family. F# is also heavily influenced by OCaml. -Just like StandardML, OCaml features both an interpreter, that can be +Just like Standard ML, OCaml features both an interpreter, that can be used interactively, and a compiler. -The interpreter binary is normally called "ocaml" and the compiler is "ocamlopt". -There is also a bytecode compiler, "ocamlc", but there are few reasons to use it. +The interpreter binary is normally called `ocaml` and the compiler is `ocamlopt`. +There is also a bytecode compiler, `ocamlc`, but there are few reasons to use it. It is strongly and statically typed, but instead of using manually written -type annotations, it infers types of expressions using Hindley-Milner algorithm. +type annotations, it infers types of expressions using the +[Hindley-Milner](https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system) +algorithm. It makes type annotations unnecessary in most cases, but can be a major source of confusion for beginners. When you are in the top level loop, OCaml will print the inferred type -after you enter an expression. +after you enter an expression ``` # let inc x = x + 1 ;; @@ -31,8 +34,8 @@ val inc : int -> int = <fun> val a : int = 99 ``` -For a source file you can use "ocamlc -i /path/to/file.ml" command -to print all names and type signatures. +For a source file you can use the `ocamlc -i /path/to/file.ml` command +to print all names and type signatures ``` $ cat sigtest.ml @@ -48,11 +51,12 @@ val a : int ``` Note that type signatures of functions of multiple arguments are -written in curried form. A function that takes multiple arguments can be +written in [curried](https://en.wikipedia.org/wiki/Currying) form. +A function that takes multiple arguments can be represented as a composition of functions that take only one argument. -The "f(x,y) = x + y" function from the example above applied to -arguments 2 and 3 is equivalent to the "f0(y) = 2 + y" function applied to 3. -Hence the "int -> int -> int" signature. +The `f(x,y) = x + y` function from the example above applied to +arguments 2 and 3 is equivalent to the `f0(y) = 2 + y` function applied to 3. +Hence the `int -> int -> int` signature. ```ocaml @@ -65,13 +69,13 @@ Hence the "int -> int -> int" signature. (*** Variables and functions ***) -(* Expressions can be separated by a double semicolon symbol, ";;". +(* Expressions can be separated by a double semicolon ";;". In many cases it's redundant, but in this tutorial we use it after every expression for easy pasting into the interpreter shell. Unnecessary use of expression separators in source code files is often considered to be a bad style. *) -(* Variable and function declarations use "let" keyword. *) +(* Variable and function declarations use the "let" keyword. *) let x = 10 ;; (* OCaml allows single quote characters in identifiers. @@ -109,42 +113,42 @@ let sqr2 = sqr (-2) ;; "unit" type for it that has the only one value written as "()" *) let print_hello () = print_endline "hello world" ;; -(* Note that you must specify "()" as argument when calling it. *) +(* Note that you must specify "()" as the argument when calling it. *) print_hello () ;; -(* Calling a function with insufficient number of arguments +(* Calling a function with an insufficient number of arguments does not cause an error, it produces a new function. *) let make_inc x y = x + y ;; (* make_inc is int -> int -> int *) let inc_2 = make_inc 2 ;; (* inc_2 is int -> int *) inc_2 3 ;; (* Evaluates to 5 *) -(* You can use multiple expressions in function body. +(* You can use multiple expressions in the function body. The last expression becomes the return value. All other expressions must be of the "unit" type. This is useful when writing in imperative style, the simplest - form of it is inserting a debug print. *) + form of which is inserting a debug print. *) let print_and_return x = print_endline (string_of_int x); x ;; (* Since OCaml is a functional language, it lacks "procedures". - Every function must return something. So functions that - do not really return anything and are called solely for their - side effects, like print_endline, return value of "unit" type. *) + Every function must return something. So functions that do not + really return anything and are called solely for their side + effects, like print_endline, return a value of "unit" type. *) -(* Definitions can be chained with "let ... in" construct. - This is roughly the same to assigning values to multiple +(* Definitions can be chained with the "let ... in" construct. + This is roughly the same as assigning values to multiple variables before using them in expressions in imperative languages. *) let x = 10 in let y = 20 in x + y ;; -(* Alternatively you can use "let ... and ... in" construct. +(* Alternatively you can use the "let ... and ... in" construct. This is especially useful for mutually recursive functions, - with ordinary "let .. in" the compiler will complain about + with ordinary "let ... in" the compiler will complain about unbound values. *) let rec is_even = function @@ -186,9 +190,9 @@ let my_lambda = fun x -> x * x ;; ~-. 3.4 (* Float only *) (* You can define your own operators or redefine existing ones. - Unlike SML or Haskell, only selected symbols can be used - for operator names and first symbol defines associativity - and precedence rules. *) + Unlike Standard ML or Haskell, only certain symbols can be + used for operator names and the operator's first symbol determines + its associativity and precedence rules. *) let (+) a b = a - b ;; (* Surprise maintenance programmers. *) (* More useful: a reciprocal operator for floats. @@ -258,7 +262,7 @@ let ocaml = (String.make 1 'O') ^ "Caml" ;; (* There is a printf function. *) Printf.printf "%d %s" 99 "bottles of beer" ;; -(* Unformatted read and write functions are there too. *) +(* There's also unformatted read and write functions. *) print_string "hello world\n" ;; print_endline "hello world" ;; let line = read_line () ;; @@ -292,14 +296,14 @@ type 'a list_of_lists = 'a list list ;; type int_list_list = int list_of_lists ;; (* Types can also be recursive. Like in this type analogous to - built-in list of integers. *) + a built-in list of integers. *) type my_int_list = EmptyList | IntList of int * my_int_list ;; let l = IntList (1, EmptyList) ;; (*** Pattern matching ***) -(* Pattern matching is somewhat similar to switch statement in imperative +(* Pattern matching is somewhat similar to the switch statement in imperative languages, but offers a lot more expressive power. Even though it may look complicated, it really boils down to matching @@ -311,7 +315,7 @@ let l = IntList (1, EmptyList) ;; let is_zero x = match x with | 0 -> true - | _ -> false (* The "_" pattern means "anything else". *) + | _ -> false (* The "_" means "anything else". *) ;; (* Alternatively, you can use the "function" keyword. *) @@ -368,10 +372,13 @@ let rec sum_int_list l = let t = Cons (1, Cons (2, Cons (3, Nil))) ;; sum_int_list t ;; - ``` ## Further reading * Visit the official website to get the compiler and read the docs: <http://ocaml.org/> +* Quick tutorial on OCaml: <https://ocaml.org/docs/up-and-running> +* Complete online OCaml v5 playground: <https://ocaml.org/play> +* An up-to-date (2022) book (with free online version) "Real World OCaml": <https://www.cambridge.org/core/books/real-world-ocaml-functional-programming-for-the-masses/052E4BCCB09D56A0FE875DD81B1ED571> +* Online interactive textbook "OCaml Programming: Correct + Efficient + Beautiful" from Cornell University: <https://cs3110.github.io/textbook/cover.html> * Try interactive tutorials and a web-based interpreter by OCaml Pro: <http://try.ocamlpro.com/> diff --git a/opengl.html.markdown b/opengl.html.markdown index 83ace3e8..993402f7 100644 --- a/opengl.html.markdown +++ b/opengl.html.markdown @@ -35,7 +35,7 @@ int main() { context };
window.setVerticalSyncEnabled(true);
window.setActive(true);
- // After that we initialise GLEW and check if an error occured.
+ // After that we initialise GLEW and check if an error occurred.
GLenum error;
glewExperimental = GL_TRUE;
if ((err = glewInit()) != GLEW_OK)
@@ -140,7 +140,7 @@ if (logSize > 0) { }
```
-The same is possibile after <code>glLinkProgram()</code>, just replace <code>glGetShaderiv()</code> with <code>glGetProgramiv()</code>
+The same is possible after <code>glLinkProgram()</code>, just replace <code>glGetShaderiv()</code> with <code>glGetProgramiv()</code>
and <code>glGetShaderInfoLog()</code> with <code>glGetProgramInfoLog()</code>.
```cpp
@@ -194,7 +194,7 @@ void main() { out vec4 outColor;
void main() {
- // We simply set the ouput color to red.
+ // We simply set the output color to red.
// The parameters are red, green, blue and alpha.
outColor = vec4(1.0, 0.0, 0.0, 1.0);
}
@@ -233,7 +233,7 @@ glBufferData(GL_ARRAY_BUFFER, // target buffer // After filling the VBO link it to the location 0 in our vertex shader,
// which holds the vertex position.
// ...
-// To ask for the attibute location, if you haven't set it:
+// To ask for the attribute location, if you haven't set it:
GLint posLocation = glGetAttribLocation(program, "position");
// ..
glEnableVertexAttribArray(0);
@@ -463,7 +463,7 @@ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(),
iboData.data(), GL_STATIC_DRAW);
// Next in our render loop, we replace glDrawArrays() with:
-glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSINGED_INT, nullptr);
+glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
// Remember to delete the allocated memory for the IBO.
```
@@ -535,7 +535,7 @@ glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // ...
glBindVertexArray(vao);
glBindTexture(GL_TEXTURE_2D, texture);
-glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSINGED_INT, nullptr);
+glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
// ...
```
@@ -673,7 +673,7 @@ glUniformMatrix4fv(modelLocation, 1, GL_FALSE, ## Geometry Shader
-Gemoetry shaders were introduced in OpenGL 3.2, they can produce vertices
+Geometry shaders were introduced in OpenGL 3.2, they can produce vertices
that are send to the rasterizer. They can also change the primitive type e.g.
they can take a point as an input and output other primitives.
Geometry shaders are inbetween the vertex and the fragment shader.
diff --git a/openscad.html.markdown b/openscad.html.markdown new file mode 100644 index 00000000..63570cbe --- /dev/null +++ b/openscad.html.markdown @@ -0,0 +1,117 @@ +--- +language: openscad +filename: learnopenscad.scad +contributors: + - ["Tom Preston", "https://github.com/tompreston/"] +--- + +Draw 3D models with code using [OpenSCAD](https://openscad.org/). + +``` +// Comments look like this + +// 3D Primitives +cube(10); +cube([5, 10, 20]); +sphere(10); + +// Transformations +translate([20, 0, 0]) cube(10); +rotate([0, 20, 30]) cube(10); + +translate([20, 0, 0]) rotate([0, 20, 30]) cube(10); +rotate([0, 20, 30]) translate([20, 0, 0]) cube(10); + +// Modifiers +// +// * disable +// ! show only +// # highlight / debug +// % transparent / background +// +// For example, show only the rotated cube at the origin, before we translate it. +translate([20, 0, 0]) !rotate([0, 20, 30]) cube(10); + +// Formatting +// The following models are the same. The official docs prefer the second. +rotate([0, 20, 30]) translate([20, 0, 0]) cube(10); + +rotate([0, 20, 30]) + translate([20, 0, 0]) + cube(10); + +rotate([0, 20, 30]) { + translate([20, 0, 0]) { + cube(10); + } +} + +// Loops +num_cubes = 5; +r = 20; +cube_len = 5; + +for (i = [0:num_cubes]) { + echo(str("Plot cube ", i)); + rotate([0, i * 360 / num_cubes, 0]) + translate([r, 0, 0]) + cube(cube_len, center=true); +} + +// Boolean operations +// +// union() - the sum of both shapes +// difference() - the first shape, minus the second shape +// intersection() - only parts of both shapes which intersect +// +cube_l = 20; +cube_w = 10; +cube_h = 10; + +hole_pos_l = 10; +hole_pos_h = 5; +hole_r = 3; + +difference() { + cube([cube_l, cube_w, cube_h]); + translate([hole_pos_l, 0, hole_pos_h]) + rotate([-90, 0, 0]) + cylinder(cube_w, r=hole_r); +} + +// Functions calculate values +function inch2mm(i) = i * 25.4; + +cube(inch2mm(2)); + +// Modules create objects you want to use later +module house(roof="flat", paint=[1,0,0]) { + color(paint) + if (roof=="flat") { + translate([0,-1,0]) cube(); + } else if (roof=="pitched") { + rotate([90,0,0]) + linear_extrude(height=1) + polygon(points=[[0,0],[0,1],[0.5,1.5],[1,1],[1,0]]); + } + else if (roof=="domical") { + translate([0,-1,0]) { + translate([0.5,0.5,1]) + sphere(r=0.5,$fn=20); + cube(); + } + } +} + +house("pitched"); +translate([2, 0, 0]) house("domical"); + +// Import modules and function from other files +include <filename> // Import the content of the file as if they were written in this file +use <filename> // Import modules and functions, but do not execute any commands +``` + +## Further Reading +* Official docs https://openscad.org/documentation.html +* Cheat sheet https://openscad.org/cheatsheet/index.html +* Vim bindings https://github.com/sirtaj/vim-openscad diff --git a/p5.html.markdown b/p5.html.markdown index f6084b98..d36d417f 100644 --- a/p5.html.markdown +++ b/p5.html.markdown @@ -29,11 +29,11 @@ function setup() { } function draw() { - ellipse(10, 10, 50, 50); // creates a ellipse at the 10px from the left and 10px from the top with width adn height as 50 each, so its basically a circle. + ellipse(10, 10, 50, 50); // creates a ellipse at the 10px from the left and 10px from the top with width and height as 50 each, so its basically a circle. //remember in p5.js the origin is at the top-left corner of the canvas if (mouseIsPressed) { - // mouseIsPressed is a boolean variable that changes to true if the mouse buttton is pressed down at that instant + // mouseIsPressed is a boolean variable that changes to true if the mouse button is pressed down at that instant fill(0); // fill refers to the innner color or filling color of whatever shape you are going to draw next } else { diff --git a/pascal.html.markdown b/pascal.html.markdown index 9c73c456..fe00791a 100644 --- a/pascal.html.markdown +++ b/pascal.html.markdown @@ -131,7 +131,7 @@ Begin str := 'apple'; bool := true; //pascal is not a case-sensitive language - //arithmethic operation + //arithmetic operation int := 1 + 1; // int = 2 overwriting the previous assignment int := int + 1; // int = 2 + 1 = 3; int := 4 div 2; //int = 2 division operation where result will be floored diff --git a/php.html.markdown b/php.html.markdown index 821bde8f..61f1c00c 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -443,7 +443,7 @@ $bar('C'); // Prints "A - B - C" // You can call named functions using strings $function_name = 'add'; echo $function_name(1, 2); // => 3 -// Useful for programatically determining which function to run. +// Useful for programmatically determining which function to run. // Or, use call_user_func(callable $callback [, $parameter [, ... ]]); diff --git a/powershell.html.markdown b/powershell.html.markdown index 318bf043..033d6c25 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -802,6 +802,6 @@ Interesting Projects * [Oh-My-Posh](https://github.com/JanDeDobbeleer/oh-my-posh) Shell customization similar to the popular Oh-My-Zsh on Mac * [PSake](https://github.com/psake/psake) Build automation tool * [Pester](https://github.com/pester/Pester) BDD Testing Framework -* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind +* [ZLocation](https://github.com/vors/ZLocation) Powershell `cd` that reads your mind * [PowerShell Community Extensions](https://github.com/Pscx/Pscx) * [More on the Powershell Pipeline Issue](https://github.com/PowerShell/PowerShell/issues/1908) diff --git a/processing.html.markdown b/processing.html.markdown index 777c6981..63f10e88 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -2,7 +2,7 @@ language: processing filename: learnprocessing.pde contributors: - - ["Phone Thant Ko", "http://github.com/phonethantko"] + - ["Phone Than Ko", "http://github.com/phonethantko"] - ["Divay Prakash", "https://github.com/divayprakash"] --- @@ -256,7 +256,7 @@ line(x1, y1, z1, x2, y2, z2); // In 3D space // Triangle triangle(x1, y1, x2, y2, x3, y3); -// Draws a triangle connecting three points defined by coordinate paramters. +// Draws a triangle connecting three points defined by coordinate parameters. // Rectangle rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners @@ -375,7 +375,7 @@ texture(image); // PImage can be passed into arguments for texture-mapping the s If you want to take things further, there are more things Processing is powered for. Rendering models, shaders and whatnot. There's too much to cover in a -short documentation, so I will leave them out here. Shoud you be interested, +short documentation, so I will leave them out here. Should you be interested, please check out the references. ``` diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown index 70d0a01c..597b0e7a 100644 --- a/pt-br/awk-pt.html.markdown +++ b/pt-br/awk-pt.html.markdown @@ -202,7 +202,7 @@ function string_functions( localvar, arr) { # Ambas retornam o número de instâncias substituídas localvar = "fooooobar" sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" - gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + gsub("e", ".", localvar) # localvar => "m..t m. at th. bar" # Localiza um texto que casa com uma expressão regular # index() faz a mesma coisa, mas não permite uma expressão regular @@ -370,8 +370,10 @@ END { } ``` + Leituras adicionais (em inglês): * [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) * [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux. +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) + GNU AWK é encontrado na maioria dos sistemas GNU/Linux. diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 42a29991..7d8b75f1 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-pt.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 4e55f068..c3f62bc6 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -1,6 +1,6 @@ --- -language: c -filename: learnc.c +language: C +filename: learnc-pt.c contributors: - ["Adam Bard", "http://adambard.com/"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] @@ -10,7 +10,6 @@ translators: - ["Cássio Böck", "https://github.com/cassiobsilva"] - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] lang: pt-br -filename: c-pt.el --- Ah, C. Ainda é **a** linguagem de computação de alta performance. diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown index e40b8fe7..15ad930a 100644 --- a/pt-br/clojure-pt.html.markdown +++ b/pt-br/clojure-pt.html.markdown @@ -561,7 +561,7 @@ Caso queira aprender mais: [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) * 4clojure possui alguns problemas e desafios interessantes para quem quiser treinar clojure ou programação funcional: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) * clojure-doc.org tem um bom número de artigos para iniciantes: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 384ca325..87e5b3a4 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: c# +language: C# filename: csharp-pt.cs contributors: - ["Robson Alves", "http://robsonalves.net/"] @@ -153,7 +153,7 @@ on a new line! ""Wow!"", the masses cried"; intArray[1] = 1; // Listas - // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis + // Listas são usadas frequentemente tanto quanto matriz por serem mais flexíveis // O formato de declarar uma lista é o seguinte: // List<tipodado> <var nome> = new List<tipodado>(); List<int> intList = new List<int>(); diff --git a/pt-br/dart-pt.html.markdown b/pt-br/dart-pt.html.markdown index e9d72850..6aff1ac3 100644 --- a/pt-br/dart-pt.html.markdown +++ b/pt-br/dart-pt.html.markdown @@ -3,15 +3,16 @@ language: dart filename: learndart-pt.dart contributors: - ["Joao Pedrosa", "https://github.com/jpedrosa/"] + - ["Hélio Oliveira", "https://github.com/insign/"] translators: - ["Junior Damacena", "https://github.com/jdamacena/"] lang: pt-br --- Dart é uma novata no reino das linguagens de programação. -Ela empresta muito de outras linguagens mais conhecidas, e tem a meta de não se diferenciar muito de seu irmão, JavaScript. Assim como JavaScript, Dart foi pensada para oferecer grande integração com o Browser. +Ela absorve muitas teorias de outras linguagens mais conhecidas, e tem a meta de não se diferenciar muito de seu irmão, JavaScript. Assim como JavaScript, Dart foi pensada para oferecer grande integração com o navegador. -A característica mais controversa da Dart é a sua Tipagem Opcional, ou seja, não é obrigatório declarar tipos. +As variáveis em Dart tem tipos, mas não é obrigatório declarar devido à função de [detecção automática](https://dart.dev/guides/language/type-system#type-inference). ```dart import "dart:collection"; diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index e59ba901..2cc1c337 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -11,6 +11,7 @@ contributors: translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] - ["Bruno Volcov", "http://github.com/volcov"] + - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"] --- Git é um sistema distribuido de gestão para código fonte e controle de versões. @@ -67,7 +68,8 @@ referências e outros. ### *Working Tree* (componente do repositório) -A *Working Tree* é basicamente a listagem dos diretórios e arquivos do repositório. É chamada também de diretório do projeto. +A *Working Tree* é basicamente a listagem dos diretórios e arquivos do +repositório. É chamada também de diretório do projeto. ### *Index* (componente do diretório .git) @@ -77,28 +79,37 @@ maior controle sobre o que é registado no repositório git. ### *Commit* -Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos arquivos do projeto. -Por exemplo, ao adicionar cinco arquivos e remover outros 2, estas alterações -serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado -para outros repositórios ou não! +Um *commit** de git é um registo de um conjunto de alterações ou manipulações +nos arquivos do projeto. Por exemplo, ao adicionar cinco arquivos e remover +outros 2, estas alterações serão gravadas em um *commit* (ou registro). Este +*commit* pode então ser enviado para outros repositórios, caso você queira. ### *Branch* -Um *branch* é essencialmente uma referência que aponta para o último *commit* +Uma *branch* é essencialmente uma referência que aponta para o último *commit* efetuado. Na medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. ### *Tag* Uma tag é uma marcação em um ponto específico da história. Geralmente as -pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí vai) +pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí +vai) ### *HEAD* e *head* (componentes do diretório .git) -*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem -uma *HEAD* activa. -*head* é uma referência que aponta para qualquer *commit*. Um repositório pode -ter um número indefinido de *heads* +*HEAD* é a referência que aponta para a *branch* em uso. Um repositório só tem +uma *HEAD* activa. *head* é uma referência que aponta para qualquer *commit*. Um +repositório pode ter um número indefinido de *heads*. + +### Estados no Git + +* Modificado (Modified): Ocorreram mudanças em ao menos um arquivo mas essas +mudanças ainda não foram registradas na base de dados do Git +* Preparado (Staged): Marca o arquivo como preparado para ser adicionado ao +próximo commit +* Consolidado (Committed): As mudanças foram registradas na base de dados do +Git ### Recursos conceituais (EN) @@ -109,8 +120,8 @@ ter um número indefinido de *heads* ### *init* -Cria um repositório Git vazio. As definições, informação guardada e outros do -repositório git são guardados em uma pasta chamada ".git". +Cria um repositório Git vazio. As configurações do repositório, e outras +informações são guardadas em uma pasta dentro do repositório com o nome ".git". ```bash $ git init @@ -118,23 +129,24 @@ $ git init ### *config* -Permite configurar as definições, sejam as definições do repositório, sistema -ou configurações globais. +Permite configurar o git, seja com respeito a definições deste repositório, +do sistema ou configurações globais para todos os repositórios. ```bash -# Imprime e define algumas variáveis de configuração básicas (global) -$ git config --global user.email -$ git config --global user.name - +# Define e imprime algumas variáveis de configuração básicas (global) $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" + +$ git config --global user.email +$ git config --global user.name ``` [Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config) ### help -Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da semântica. +Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da +semântica. ```bash # Ver rapidamente os comandos disponiveis @@ -148,16 +160,32 @@ $ git help -a $ git help add $ git help commit $ git help init +# ou git <comando_aqui> --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### Ignorando arquivos + +É possível intencionalmente ignorar arquivos e pastas. Costuma-se utilizar o +arquivo .gitignore para fazer o git ignorar a existência de arquivos e pastas +geralmente utilizados para arquivos privados ou temporários que, de outro modo, +seriam compartilhados com todos que tem acesso ao repositório. + +```bash +$ echo "temp/" >> .gitignore +$ echo "chave_privada" >> .gitignore ``` ### status -Apresenta as diferenças entre o arquivo *index* (a versão corrente -do repositório) e o *commit* da *HEAD* atual. +Apresenta as diferenças entre o arquivo *index* (a versão corrente do +repositório) e o *commit* da *HEAD* atual. ```bash -# Apresenta o *branch*, arquivos não monitorados, alterações e outras +# Apresenta a *branch*, arquivos não monitorados, alterações e outras # diferenças $ git status @@ -173,35 +201,42 @@ incluidos nos commits! ```bash # adiciona um arquivo no diretório do projeto atual -$ git add HelloWorld.java +$ git add OlaMundo.java -# adiciona um arquivo num sub-diretório -$ git add /path/to/file/HelloWorld.c +# adiciona um arquivo em um sub-diretório +$ git add /caminho/para/arquivo/OlaMundo.java # permite usar expressões regulares! $ git add ./*.java + +# Você também pode adicionar tudo no seu diretório de trabalho como alterações +prontas para o próximo commit. +$ git add -A ``` +Esse comando apenas adiciona os arquivos no estado de preparados para o próximo +commit, mas não realiza o commit de fato. + ### branch -Gerencia os *branches*. É possível ver, editar, criar e apagar branches com este +Gerencia as *branches*. É possível ver, editar, criar e apagar branches com este comando. ```bash # listar *branches* existentes e remotos $ git branch -a -# criar um novo *branch* +# criar uma nova *branch* $ git branch myNewBranch -# apagar um *branch* +# apagar uma *branch* $ git branch -d myBranch -# alterar o nome de um *branch* +# alterar o nome de uma *branch* # git branch -m <oldname> <newname> $ git branch -m myBranchName myNewBranchName -# editar a descrição de um *branch* +# editar a descrição de uma *branch* $ git branch myBranchName --edit-description ``` @@ -212,18 +247,22 @@ Gerencia as *tags* ```bash # Listar tags $ git tag + # Criar uma tag anotada. # O parâmetro -m define uma mensagem, que é armazenada com a tag. # Se você não especificar uma mensagem para uma tag anotada, # o Git vai rodar seu editor de texto para você digitar alguma coisa. $ git tag -a v2.0 -m 'minha versão 2.0' + # Mostrar informações sobre a tag # O comando mostra a informação da pessoa que criou a tag, # a data de quando o commit foi taggeado, # e a mensagem antes de mostrar a informação do commit. $ git show v2.0 + # Enviar uma tag para o repositório remoto $ git push origin v2.0 + # Enviar várias tags para o repositório remoto $ git push origin --tags ``` @@ -231,14 +270,16 @@ $ git push origin --tags ### checkout Atualiza todos os arquivos no diretório do projeto para que fiquem iguais -à versão do index ou do *branch* especificado. +à versão do index ou da *branch* especificado. ```bash -# Checkout de um repositório - por padrão para o branch master +# Checkout de um repositório - por padrão para a branch master $ git checkout -# Checkout de um branch especifico + +# Checkout de uma branch especifica $ git checkout branchName -# Cria um novo branch e faz checkout para ele. + +# Cria uma nova branch e faz checkout para ela. # Equivalente a: "git branch <name>; git checkout <name>" $ git checkout -b newBranch ``` @@ -246,22 +287,41 @@ $ git checkout -b newBranch ### clone Clona ou copia um repositório existente para um novo diretório. Também -adiciona *branches* de monitoramento remoto para cada *branch* no repositório -clonado o que permite enviar alterações para um *branch* remoto. +adiciona *branches* no repositório clonado para cada *branch* no repositório +remoto o que permite enviar alterações para uma *branch* no repositório remoto. ```bash # Clona learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# Clone superficial - É mais rápido, mas puxa apenas o último commit +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# Clona apenas uma branch em específica +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch ``` ### commit -Guarda o conteudo atual do index num novo *commit*. Este *commit* contém +Guarda o conteúdo atual do index em um novo *commit*. Este *commit* contém as alterações feitas e a mensagem criada pelo usuário. ```bash -# commit com uma mensagem -$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +# Realiza um commit com uma mensagem +$ git commit -m "Adicione a função multipliqueNumeros() em OlaMundo.c" + +# Assine um commit com sua chave GPG. Antes disso, você precisa ter +# configurado a opção user.signkey do git com o comando: +# git config --global user.signinkey ID_CHAVE_AQUI +$ git commit -S -m "mensagem do commit aqui" + +# Automaticamente adicione como preparados arquivos modificados ou apagados e +# então realize um commit: +$ git commit -a -m "Modified foo.php and removed bar.php" + +# Altere o último commit (Esse comando cria um novo commit com o conteúdo do +# commit anterior mais suas novas alterações e sobrescreve o último commit) +$ git commit --amend -m "Correct message" ``` ### diff @@ -282,7 +342,7 @@ $ git diff HEAD ### grep -Permite procurar facilmente num repositório +Permite procurar facilmente em um repositório. Configurações opcionais: @@ -313,74 +373,158 @@ Apresenta commits do repositório. # Apresenta todos os commits $ git log -# Apresenta X commits -$ git log -n 10 +# Apresenta apenas mensagem do commit e referência +$ git log --oneline # Apresenta apenas commits de merge $ git log --merges + +# Apresenta todos os commits representados por um gráfico em ASCII +$ git log --graph ``` ### merge -"Merge" junta as alterações de commits externos com o *branch* atual. +"Merge" junta as alterações de commits externos com a *branch* atual. ```bash -# Junta o branch especificado com o atual +# Junta a branch especificada com o atual $ git merge branchName -# Para gerar sempre um commit ao juntar os branches +# Para gerar sempre um commit ao juntar as branches $ git merge --no-ff branchName ``` ### mv -Alterar o nome ou mover um arquivo. +Altera o nome ou move um arquivo. ```bash # Alterar o nome de um arquivo -$ git mv HelloWorld.c HelloNewWorld.c +$ git mv OlaMundo.c OlaNovoMundo.c # Mover um arquivo -$ git mv HelloWorld.c ./new/path/HelloWorld.c +$ git mv OlaMundo.c ./novo/caminho/OlaMundo.c -# Forçar a alteração de nome ou mudança local -# "existingFile" já existe no directório, será sobrescrito. +# Forçar a alteração de nome ou mudança de local +# Se o arquivo já existir no diretório, será sobrescrito. $ git mv -f myFile existingFile ``` ### pull -Puxa alterações de um repositório e as junta com outro branch +Puxa alterações de um repositório e as junta com outra branch ```bash # Atualiza o repositório local, juntando as novas alterações # do repositório remoto 'origin' e branch 'master' # git pull <remote> <branch> -# git pull => aplica a predefinição => git pull origin master $ git pull origin master -# Juntar alterações do branch remote e fazer rebase commits do branch +# Por padrão, o git irá realizar o pull na branch atual fazendo um merge +# com as alterações novas na branch remota +$ git pull + +# Juntar alterações da branch remote e fazer rebase commits da branch # no repositório local, como: "git pull <remote> <branch>, git rebase <branch>" $ git pull origin master --rebase ``` ### push -Enviar e juntar alterações de um branch para o seu branch correspondente -num repositório remoto. +Enviar e juntar alterações de uma branch para a sua branch correspondente +em um repositório remoto. ```bash # Envia e junta as alterações de um repositório local -# para um remoto denominado "origin" no branch "master". +# para um remoto denominado "origin" na branch "master". # git push <remote> <branch> -# git push => aplica a predefinição => git push origin master $ git push origin master + +# Por padrão, o git push irá enviar e realizar merge das mudanças da sua branch +# local com a branch remota +$ git push + +# Para associar a branch local com uma branch específica remota, adicione a +# flag -u +$ git push -u origin master + +# Agora, sempre que você realizar um push daquela branch local, use o atalho: +$ git push ``` +### stash + +O objetivo desse comando do git é pegar o estado "sujo" do seu diretório de +trabalho, que não está pronto (staged), e salvá-lo em um outro lugar para que +você possa trabalhar no seu repositório do zero, mas sem perder as mudanças que +fez. Em qualquer outro momento que você quiser, você pode trazer de volta as +alterações que você tirou dali com o comando stash. + +Digamos que você tem feito algumas alterações no seu repositório, mas agora +você quer realizar um pull do repositório remoto. Como você tem alterações não +commitadas no seu diretório (ele está "sujo"), você não irá conseguir realizar +o `git pull` com sucesso. Mas você pode executar o `git stash` para salvar +essas alterações e conseguir realizar o pull. Depois, você traz de volta. + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Agora você irá conseguir realizar o pull! + +```bash +git pull +``` +`...changes apply...` + +Verifique se está tudo OK com o `git status` + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +É possível verificar as alterações que você guardou com cada uso do comando +`git stash` com o `git stash list`. Como os usos desse comando são guardados +como em uma pilha, os usos mais recentes estarão no topo. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 added the index file +stash@{1}: WIP on master: c264051 Revert "added file_size" +stash@{2}: WIP on master: 21d80a5 added number to log +``` + +Agora vamos trazer o que havíamos salvado com o `git stash` de volta para o +diretório de trabalho. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add <file>..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` faz a mesma coisa + +Agora podemos voltar a trabalhar no que havíamos deixado de lado! + +[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) + ### rebase (cautela!) -Pega em todas as alterações que foram registadas num branch e volta a -aplicá-las em outro branch. +Pega em todas as alterações que foram registadas em uma branch e volta a +aplicá-las em outra branch. *Não deve ser feito rebase de commits que foram enviados para um repositório público* @@ -407,31 +551,79 @@ $ git reset # sobrescreve o projeto atual $ git reset --hard -# Move a head do branch atual para o commit especificado, sem alterar o projeto. +# Move a head da branch atual para o commit especificado, sem alterar o projeto. # todas as alterações ainda existem no projeto $ git reset 31f2bb1 -# Inverte a head do branch atual para o commit especificado +# Inverte a head da branch atual para o commit especificado # fazendo com que este esteja em sintonia com o diretório do projeto -# Remove alterações não registadas e todos os commits após o commit especificado +# Remove alterações não registradas e todos os commits após o commit +# especificado $ git reset --hard 31f2bb1 ``` +### reflog (cuidado!) + +O reflog irá listar a maior parte dos comandos que você realizou no git em um +determinado intervalo de tempo. O intervalo padrão é de 90 dias. + +Isso te dá a oportunidade de reverter qualquer comando que você realizou no git +e que tenha tido consequências indesejadas (por exemplo, se um rebase quebrou +sua aplicação). + +Você pode fazer assim: + +1. `git reflog` para listar todos os comandos utilizados no git para o rebase + +``` +38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog +38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators +4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown +34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) +ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) +2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d +``` +2. Selecione para onde você quer resetar. No nosso exemplo, seria o commit +`2e6c386`, ou `HEAD@{5}` +3. 'git reset --hard HEAD@{5}' esse comando irá resetar o seu repositório para +aquele ponto (5 commits atrás). +4. Agora você pode recomeçar o rebase ou apenas deixar como está. + +[Leitura complementar](https://git-scm.com/docs/git-reflog) + +### revert + +O comando revert pode ser utilizado para desfazer um commit. Não deve ser +confundido com o comando reset que restabelece o estado do repositório para um +momento anterior. O revert irá criar um novo commit com alterações inversas a +de um outro commit especificado, portanto revertendo aquelas alterações. + +```bash +# Revertendo um commit específico +$ git revert <commit> +``` + ### rm -O oposto de git add, git rm remove arquivos do branch atual. +O oposto de git add, git rm remove arquivos da branch atual. ```bash -# remove HelloWorld.c -$ git rm HelloWorld.c +# remove OlaMundo.c +$ git rm OlaMundo.c -# Remove um arquivo de um sub-directório -$ git rm /pather/to/the/file/HelloWorld.c +# Remove um arquivo de um sub-diretório +$ git rm /caminho/para/o/arquivo/OlaMundo.c ``` -## Informação complementar (EN) +## Leitura complementar + +* [Configurar o Git (GitHub Docs)](https://docs.github.com/pt/get-started/quickstart/set-up-git) + +* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/) -* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) * [git-scm - Video Tutorials](http://git-scm.com/videos) @@ -441,4 +633,10 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git (em Português)](https://www.git-scm.com/book/pt-br/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + +* [The New Boston tutorial to Git covering basic commands and workflow](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx) diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index 31473ee1..f68d63eb 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -28,7 +28,7 @@ Go vem com uma biblioteca padrão exaustiva e uma comunidade entusiasta. várias linhas */ // A cláusula package aparece no início de cada arquivo. -// Main é um nome especial declarando um executável ao invés de uma biblioteca. +// main é um nome especial declarando um executável ao invés de uma biblioteca. package main // A cláusula Import declara os pacotes referenciados neste arquivo. diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown index 3acfce21..dff3f2e1 100644 --- a/pt-br/groovy-pt.html.markdown +++ b/pt-br/groovy-pt.html.markdown @@ -5,7 +5,8 @@ filename: learngroovy-pt.groovy contributors: - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] translators: - - ["João Farias", "https://github.com/JoaoGFarias"] + - ["João Farias", "https://github.com/joaogfarias"] + - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"] lang: pt-br --- @@ -201,8 +202,16 @@ if(x==1) { //Groovy também suporta o operador ternário def y = 10 -def x = (y > 1) ? "functionou" : "falhou" -assert x == "functionou" +def x = (y > 1) ? "funcionou" : "falhou" +assert x == "funcionou" + +//E suporta o 'The Elvis Operator' também! +//Em vez de usar o operador ternário: + +displayName = nome.name ? nome.name : 'Anonimo' + +//Podemos escrever: +displayName = nome.name ?: 'Anonimo' //Loop 'for' //Itera sobre um intervalo (range) diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown index 58586522..919c0f4f 100644 --- a/pt-br/latex-pt.html.markdown +++ b/pt-br/latex-pt.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Svetlana Golubeva", "https://attillax.github.io/"] translators: - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] + - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"] lang: pt-br filename: learn-latex-pt.tex --- @@ -16,10 +17,10 @@ filename: learn-latex-pt.tex % Todas as linhas de comentários começam com % % Não existem comentários multilinhas -$ LaTeX não é um programa processador de textos "Visual" como +% LaTeX não é um programa processador de textos "Visual" como % MS Word ou OpenOffice Writer -$ Todo comando LaTeX começa com uma barra invertida (\) +% Todo comando LaTeX começa com uma barra invertida (\) % Documentos LaTeX começam com a definição do tipo que será % compilado % Os tipos de documento podem ser livro, relatório, apresentação, etc. @@ -37,14 +38,11 @@ $ Todo comando LaTeX começa com uma barra invertida (\) \usepackage{float} \usepackage{hyperref} -% Para poder usar caracteres acentuados, use o seguinte pacote: -\usepackage[utf8]{inputenc} - % Podemos definir algumas outras propriedades do documento também! \author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\ Svetlana Golubeva} \date{\today} -\title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!} +\title{Aprenda \LaTeX{} em Y Minutos!} % Agora estamos prontos para começar o documento % Tudo antes dessa linha é chamado "preâmbulo". @@ -52,6 +50,7 @@ Svetlana Golubeva} % Se informarmos os campos author (autores), date (data), "title" (título), % LaTeX poderá cria uma página inicial para nós. \maketitle + % Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso, % o documento deve ser compilado duas vezes, para que tudo apareça na ordem % correta. @@ -69,7 +68,7 @@ Svetlana Golubeva} % Esse comando está disponível para os documentos do tipo artigo (article) % e relatório (report). \begin{abstract} - Documentação do \LaTeX \hspace{1pt} escrita em \LaTeX! Nada original! + Documentação do \LaTeX{} escrita em \LaTeX! Nada original! \end{abstract} % Comandos para seções são intuitivos. @@ -93,11 +92,17 @@ Muito melhor agora. Afinal nem todas as seções precisam ser numeradas! \section{Algumas notas sobre texto} -%\section{Espaçamento % É necessário mais informação sobre intervalos de espaço. -\LaTeX \hspace{1pt} geralmente é muito bom sobre colocar texto onde ele deve +%\section{Espaçamento} % É necessário mais informação sobre intervalos de espaço. +\LaTeX{} geralmente é muito bom sobre colocar texto onde ele deve ser posto. Se uma linha \\ deve \\ ser \\ quebrada \\ adicione \textbackslash\textbackslash -\hspace{1pt} ao código de seu documento. \\ +\hspace{1pt} ao código de seu documento. + +Separe parágrafos por linhas vazias. + +Você precisa adicionar um til após abreviações (se não forem seguidas de vírgula) +para um espaço sem quebra, senão o espaçamento após o ponto será muito largo: +E.g., i.e., etc.~são exemplos de abreviações. \section{Listas} Listas são uma das coisas mais fáceis de criar no \LaTeX! Preciso fazer compras @@ -112,21 +117,21 @@ amanhã, então façamos uma lista de compras. Não é um item da lista, mas faz parte do bloco enumerate. - \end{enumerate} % Todos os blocos devem ter um final (end{}). +\end{enumerate} % Todos os blocos devem ter um final (end{}). \section{Matemática} -Um dos usos iniciais para \LaTeX \hspace{1pt} foi a produção de artigos +Um dos usos iniciais para \LaTeX{} foi a produção de artigos acadêmicos e técnicos. Usualmente nos campos da matemática e ciência. Assim, é -necessários que consigamos incluir alguns símbolos especiais em nosso texto! \\ +necessários que consigamos incluir alguns símbolos especiais em nosso texto! A matemática tem muitos símbolos, além dos quais se pode encontrar no teclado; símbolos para relações e conjuntos, setas, operadores, e letras gregas, apenas -para mencionar alguns.\\ +para mencionar alguns. Conjuntos e relações são essenciais em muitos textos de pesquisa em matemática. Aqui está como você pode indicar como todo x que pertence -a X, $\forall$ x $\in$ X. \\ +a X, $\forall$ x $\in$ X. % Perceba que é necessário adicionar os sinais $ antes e depois dos símbolos. % Isso é porque quando escrevendo, estamos em modo texto. % Mas os símbolos de matemática só existem no modo matemática. @@ -138,15 +143,14 @@ a X, $\forall$ x $\in$ X. \\ \[a^2 + b^2 = c^2 \] Minha letra grega favorita é $\xi$. Eu também gosto da $\beta$, $\gamma$ e $\sigma$. -Eu ainda não encontrei uma letra grega que o \LaTeX \hspace{1pt} não tenha!\\ +Eu ainda não encontrei uma letra grega que o \LaTeX{} não tenha!\\ Operadores são parte essencial de um documento sobre matemática: funções trigonométricas ($\sin$, $\cos$, $\tan$), logaritmo e exponencial ($\log$, $\exp$), -limites ($\lim$), etc. -possuem comandos pré-definidos em LaTex. +limites ($\lim$), etc.~possuem comandos pré-definidos em LaTex. Vamos escrever uma equação para ver como se faz: -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ Frações (numerador/denominador) podem ser escritas dessa forma: @@ -183,8 +187,10 @@ Somatórios e Integrais são escritas com os comandos sum e int: \section{Figuras} -Insiramos uma Figura. O local para colocar a figura pode ser difícil -de determinar. Eu tenho sempre que verificar as opções toda vez. +Insiramos uma Figura. O local para colocar a figura pode ser difícil de determinar. +Operações básicas são [t] para o topo, [b] para base, [h] para aqui (aproximadamente). +Eu tenho sempre que verificar as opções toda vez. +% Veja https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions para mais detalhes \begin{figure}[H] % H aqui é uma opção para o local da figura. \centering % centra a figura na página @@ -201,36 +207,45 @@ Também podemos incluir tabelas da mesma forma que figuras. \begin{table}[H] \caption{Título para a Tabela.} % os argumentos {} abaixo descrevem como cada linha da tabela é desenhada. - % Aqui também, Preciso ver isso. Toda. E. Cada. Vez. + % O básico é simples: uma letra para cada coluna, para controlar o alinhamento: + % Operações básicas são: c, l, r e p para centro, esquerda, direita e parágrafo + % opcionalmente, você pode adicionar um | para linha vertical + % Veja https://en.wikibooks.org/wiki/LaTeX/Tables para mais detalhes \begin{tabular}{c|cc} - Número & Sobrenome & Primeiro Nome \\ % Colunas são separadas por & + Número & Primeiro Nome & Sobrenome \\ % Colunas são separadas por & \hline % uma linha horizontal 1 & Biggus & Dickus \\ 2 & Monty & Python \end{tabular} + % Vai ficar mais ou menos assim: + % Número | Primeiro Nome Sobrenome + % -------|--------------------------- % por causa do \hline + % 1 | Biggus Dickus + % 2 | Monty Python \end{table} -\section{Fazendo o \LaTeX \hspace{1pt} não compilar algo (o código fonte)} +\section{Fazendo o \LaTeX{} não compilar algo (o código fonte)} Digamos que precisamos incluir algum código dentro do nosso -documento \LaTeX \hspace{1pt}, para isso precisamos com o \LaTeX \hspace{1pt} +documento \LaTeX{}, para isso precisamos com o \LaTeX{} não tente interpretar esse texto e que apenas inclua ele no documento. Fazemos isso com o bloco verbatim. % Existem outros pacotes (por exemplo, minty, lstlisting, etc.) % mas verbatim é o básico \begin{verbatim} - print("Hello World!") + print("Olá mundo!") a%b; % olha só! Podemos usar os sinais % no bloco verbatim. - random = 4; #decided by fair random dice roll + random = 4; #decidido por um lançamento honesto de dado + Veja https://www.explainxkcd.com/wiki/index.php/221:_Random_Number \end{verbatim} \section{Compilando} Imagino que agora você esteja pensando como compilar esse fantástico documento -e visualizar a gloriosa glória que é um pdf gerado por \LaTeX \hspace{1pt} pdf. +e visualizar a gloriosa glória que é um pdf gerado por \LaTeX{} pdf. (sim, esse documento é compilável). \\ -Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos: +Finalizando o documento usando \LaTeX{} consiste nos seguintes passos: \begin{enumerate} \item Escrever o documento em texto puro (o ``código fonte''). \item Compilar o código fonte para gerar um pdf. @@ -240,7 +255,7 @@ Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos \end{verbatim} \end{enumerate} -Existem editores de \LaTeX \hspace{1pt} que combinam os passos 1 e 2 no mesmo +Existem editores de \LaTeX{} que combinam os passos 1 e 2 no mesmo sistema de software. Assim, você pode ver o passo 1, mas não o passo 2 por completo. Passo 2 estará acontecendo escondido\footnote{Por exemplo, quando usar referências (como Equação~\ref{eq:pythagoras}), pode ser necessário executar o @@ -267,6 +282,27 @@ Existem dois tipos principais de links: URL visíveis \\ Esse pacote também produz uma lista de thumbnails no documento pdf gerado e ativa os links na tabela de conteúdo. +\section{Escrevendo em ASCII ou outras codificações} + +Por padrão, historicamente LaTeX aceita entradas que são puro ASCII (128), +mas não ASCII extendido, o que significa sem acentos (à, è etc.) e símbolos não latinos. + +É fácil inserir acentos e símbolos latinos básicos através de atalhos de barra invertida +como \,c, \'e, \`A, \ae e \oe etc. % Para ç, é, À, etc +% Veja https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Escaped_codes para mais detalhes + +Para escrever diretamente em UTF-8 quando compilando com pdflatex, use +\begin{verbatim} + \usepackage[utf8]{inputenc} +\end{verbatim} +A fonte selecionada precisa suportar os glifos usados em seu documento. Você precisa adicionar +\begin{verbatim} + \usepackage[T1]{fontenc} +\end{verbatim} + +Desde LuaTeX e XeLaTeX, suporte para UTF-8 vem embutido por padrão, tornando a vida muito +mais fácil para escrever em alfabetos não latinos. + \section{End} Por enquanto é isso! @@ -276,7 +312,7 @@ Por enquanto é isso! \begin{thebibliography}{1} % como em outras listas, o comando \bibitem pode ser usado para itens da lista % cada entrada pode ser citada diretamente no corpo do texto - \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em + \bibitem{latexwiki} The amazing \LaTeX{} wikibook: {\em https://en.wikibooks.org/wiki/LaTeX} \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} \end{thebibliography} @@ -289,3 +325,6 @@ https://en.wikibooks.org/wiki/LaTeX} * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) * An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) +* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes) +* An interactive platform to learn LaTeX (installationfree) [learnlatex.org/](https://www.learnlatex.org/) +* Stack Exchange's question and answer site about TeX, LaTeX, ConTeXt, etc. [tex.stackexchange.com](https://tex.stackexchange.com/) diff --git a/pt-br/lua-pt.html.markdown b/pt-br/lua-pt.html.markdown index 0c75da26..4aaf3a1e 100644 --- a/pt-br/lua-pt.html.markdown +++ b/pt-br/lua-pt.html.markdown @@ -2,7 +2,7 @@ language: Lua contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] -filename: learnlua.lua +filename: learnlua-pt.lua translators: - ["Iaan Mesquita", "https://github.com/ianitow"] lang: pt-br diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown index cbdebde7..40ac733a 100644 --- a/pt-br/make-pt.html.markdown +++ b/pt-br/make-pt.html.markdown @@ -4,7 +4,9 @@ tool: make contributors:
- ["Robert Steed", "https://github.com/robochat"]
- ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
-filename: Makefile
+translators:
+ - ["Rogério Gomes Rio", "https://github.com/rogerlista"]
+filename: Makefile-pt
lang: pt-br
---
diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown index dc50cac1..7960a59a 100644 --- a/pt-br/markdown-pt.html.markdown +++ b/pt-br/markdown-pt.html.markdown @@ -6,36 +6,56 @@ translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] - ["Gabriele Luz", "https://github.com/gabrieleluz"] - ["Monique Baptista", "https://github.com/bfmonique"] + - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"] lang: pt-br filename: learnmarkdown-pt.md --- -Markdown foi criado por John Gruber in 2004. Originado para ser fácil de ler e -escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos também). - -Dê-me feedback tanto quanto você quiser! / Sinta-se livre para fazer uma bifurcação (fork) e -puxar o projeto (pull request) +O Markdown foi lançado por John Gruber em 2004. Criado para ser uma sintaxe +fácil de ler e escrever e que é facilmente convertida em HTML (hoje, suporta +outros formatos também). + +O Markdown varia em termos de implementação de um parser para outro. Esse guia +irá tentar deixar explícito quando os recursos são universais ou quando são +específicos para um parser em específico. + +- [Elementos HTML](#elementos-html) +- [Cabeçalhos](#cabeçalhos) +- [Estilos de texto simples](#estilos-de-texto-simples) +- [Parágrafos](#parágrafos) +- [Listas](#listas) +- [Blocos de código](#blocos-de-código) +- [Linha Horizontal](#linha-horizontal) +- [Links](#links) + - [Tabela de conteúdo](#tabela-de-conteúdo) +- [Imagens](#imagens) +- [Miscelânea](#miscelânea) + - [Auto-links](#auto-links) + - [Auto-links para e-mails](#auto-links-com-e-mails) + - [Escapando caracteres](#escapando-caracteres) + - [Teclas do teclado](#teclas-do-teclado) + - [Tabelas](#tabelas) +- [Markdownlint](#markdownlint) +- [Leitura complementar](#leitura-complementar) ## Elementos HTML -Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é +O Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é um arquivo Markdown válido. -```md -<!-- Markdown é um superconjunto do HTML, de modo que qualquer arquivo HTML é -um arquivo Markdown válido. Isso significa que nós podemos usar elementos HTML -em Markdown, como o elemento de comentário, e eles não serão afetados pelo analisador -de remarcação. No entanto, se você criar um elemento HTML em seu arquivo Markdown, você -não pode usar sintaxe de remarcação dentro desse conteúdo do elemento.--> - -<!--A maneira como o Markdown é analisado varia de software para software. -Este guia vai tentar esclarecer quando as características são universais, ou quando eles são específicos para um determinado interpretador --> +```md +<!--Isso significa que nós podemos usar elementos HTML em Markdown, como o +elemento de comentário, e eles não serão afetados pelo analisador de +remarcação. No entanto, se você criar um elemento HTML em seu arquivo Markdown, +você não pode usar sintaxe de remarcação dentro do conteúdo desse elemento.--> +``` ## Cabeçalhos Você pode criar elementos HTML `<h1>` até `<h6>` facilmente antecedendo o texto -que deseja estar nesse elemento por um número de hashes (#) +que deseja estar nesse elemento por um número de cerquilhas (#). +```md # Isto é um cabeçalho <h1> ## Isto é um cabeçalho <h2> ### Isto é um cabeçalho <h3> @@ -44,7 +64,7 @@ que deseja estar nesse elemento por um número de hashes (#) ###### Isto é um cabeçalho <h6> ``` -Markdown também nos fornece duas maneiras alternativas de indicar h1 e h2 +Markdown também nos fornece duas maneiras alternativas de indicar h1 e h2. ```md Isto é um cabeçalho h1 @@ -55,21 +75,22 @@ Isto é um cabeçalho h2 ``` ## Estilos de texto simples -O texto pode ser facilmente denominado como marcação itálico, negrito ou tachado usando: + +O texto pode ser facilmente estilizado como itálico ou negrito usando Markdown. ```md *Este texto está em itálico* _E este também está._ **Este texto está em negrito** -__E este também está._ +__E este também está.__ ***Este texto está em negrito e itálico.*** **_E este também está_** -*--Danouse! Este também__* +*__Danou-se! Este também__* ``` -Em GitHub Flavored Markdown, que é usado para processar arquivos Markdown +No GitHub Flavored Markdown, que é usado para processar arquivos Markdown GitHub, nós também temos: ```md @@ -77,43 +98,46 @@ GitHub, nós também temos: ``` ## Parágrafos -Os parágrafos estão uma ou várias linhas adjacentes de texto separadas por +Os parágrafos estão em uma ou várias linhas adjacentes de texto separadas por uma ou múltiplas linhas em branco. ```md Este é um parágrafo. Eu estou digitando em um parágrafo, não é legal? Agora, eu estou no parágrafo 2. -... Ainda continuo no parágrafo 2! :) +Ainda continuo no parágrafo 2! -Eu estou no parágrafo três. + +Eu estou no parágrafo três! ``` Se você quiser inserir uma tag HTML `<br />`, você pode acabar com um parágrafo -com dois ou mais espaços e, em seguida, começar um novo parágrafo +com dois ou mais espaços e, em seguida, começar um novo parágrafo. ```md -Termino com dois espaços (destacar-me para vê-los). +Termino com dois espaços (selecione essa linha para vê-los). Há um <br /> acima de mim! ``` - -Bloco de citações são fáceis e feito com o caractere >. +Blocos de citações são fáceis e feitos com o caractere >. ```md > Este é um bloco de citação. Você pode -> Quebrar manualmente suas linhas e colocar um `>` antes de cada linha ou você pode -> deixar suas linhas ficarem muito longas e quebrarem por conta própria. Não faz diferença, -> desde que eles começam com um `>`. - +> Quebrar manualmente suas linhas e colocar um `>` antes de cada linha ou você +> pode deixar suas linhas ficarem muito longas e quebrarem por conta própria. +> Não faz diferença, desde que elas comecem com um `>`. > Você também pode usar mais de um nível >> De recuo? +> O quão legal é isso? + ``` ## Listas -As listas não ordenadas podem ser feitas usando asteriscos, positivos ou hífens + +As listas não ordenadas podem ser feitas usando asteriscos, sinais de positivo +ou hífens. ```md * Item @@ -141,18 +165,18 @@ Listas ordenadas são feitas com um número seguido por um ponto. 3. Item três ``` -<!-- Você não tem poder para rotular os itens corretamente e a remarcação ainda deixará os -itens em ordem, mas isso pode não ser uma boa idéia --> - +Você não precisa sequer rotular os itens corretamente e o Markdown ainda +assim deixará os itens em ordem, mas isso pode não ser uma boa idéia. ```md 1. Item um 1. Item dois 1. Item três ``` + (Isto é processado da mesma forma que o exemplo acima) -Você também pode usar sublistas +Você também pode usar sublistas. ```md 1. Item um @@ -163,63 +187,59 @@ Você também pode usar sublistas 4. Item quatro ``` -Existem também listas de tarefas. Isso cria checkboxes (caixas de seleção) de HTML +Existem também listas de tarefas. Isso cria checkboxes (caixas de seleção) do +HTML. ```md -As caixas abaixo sem o 'x' são checkboxes HTML desmarcadas -- [ ] Primeira tarefa a completar +As caixas abaixo sem o 'x' são checkboxes HTML desmarcadas. +- [ ] Primeira tarefa a completar. - [ ] Segunda tarefa a completar -A caixa de seleção abaixo será exibida como uma checkbox HTML marcada +A caixa de seleção abaixo será exibida como uma checkbox HTML marcada. - [x] Essa tarefa foi completa - ``` - ## Blocos de código -Você pode indicar um bloco de código (que utiliza o elemento `<code>`) pelo recuo -uma linha com quatro espaços ou uma guia + +Você pode indicar um bloco de código (que utiliza o elemento `<code>`) através +de indentação com quatro espaços ou uma tabulação. + ```md - Isto é código - É assim, sacou? - + Isto é código + É assim, sacou? ``` -Você pode também re-guia (ou adicionar mais quatro espaços adicionais) para o recuo -dentro do seu código +Você pode também adicionar mais tabulações (ou adicionar mais quatro espaços +adicionais) para indentação no seu código. ```md - my_array.each do |item| + my_array.each do |item| puts item end - ``` +``` -Código embutido pode ser criada usando o caractere de crase `` ` `` +Código embutido pode ser criado usando o caractere de crase `` ` ``. ```md -John não sabia nem o que o função `goto()` fazia! +John não sabia nem o que a função `go_to()` fazia! ``` -Em GitHub Flavored Markdown, você pode usar uma sintaxe especial para o código -```md - ``` ruby - def foobar - puts "Hello world!" - end - ``` -``` -======= -\`\`\`ruby <!-- exceto remover essas barras invertidas quando você faz isso, apenas ``` -ruby! --> +No GitHub Flavored Markdown, você pode usar uma sintaxe especial para código. + +<pre> +<code class="highlight">```ruby def foobar - puts "Hello world!" + puts "Olá mundo!" end -\`\`\` <!-- Aqui também, não use barras invertidas, apenas ``` --> +```</code></pre> + -O texto acima não requer recuo, além disso o GitHub vai usar a sintaxe highlight da linguagem que você especificar após a \`\`\`. +O texto acima não requer indentação, além disso o GitHub vai usar o destaque +de sintaxe da linguagem qeu você especificar após a tag <code>```</code>. ## Linha Horizontal -Linhas horizontais são facilmente adicionados com três ou mais asteriscos ou hífens, -com ou sem espaços. + +Linhas horizontais são facilmente adicionadas com três ou mais asteriscos ou +hífens, com ou sem espaços. ```md *** @@ -229,17 +249,19 @@ com ou sem espaços. ``` ## Links -Uma das melhores coisas sobre a marcação é o quão fácil é fazer ligações. Colocar -o texto a ser exibido entre parênteses rígidos [] seguido pela url em parênteses () + +Uma das melhores coisas sobre o Mardkwon é o quão fácil é criar links. +Coloque o texto a ser exibido entre colchetes [] seguido pela url entre +parênteses () ```md -[Click aqui!](http://test.com/) +[Clique aqui!](http://test.com/) ``` -Você também pode adicionar um título link usando aspas dentro dos parênteses +Você também pode adicionar um título ao link usando aspas dentro dos parênteses. ```md -[Click aqui!](http://test.com/ "Link para Test.com") +[Cliqueaqui!](http://test.com/ "Link para Test.com") ``` Caminhos relativos funcionam também. @@ -248,46 +270,64 @@ Caminhos relativos funcionam também. [Ir para música](/música/). ``` -Markdown também suporta ligações de estilo de referência +O Markdown também suporta links para referências no texto. -```md -[Clique neste link] [link1] para mais informações sobre isso! -[Além disso, verifique este link] [foobar] se você quiser. +<pre><code class="highlight">[<span class="nv">Clique nesse link</span>][<span class="ss">link1</span>] para mais informações! +[<span class="nv">Também cheque esse link</span>][<span class="ss">foobar</span>] se você quiser. -[link1]: http://test.com/ "Legal!" -[foobar]: http://foobar.biz/ "OK!" -``` +[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Legal!"</span> +[<span class="nv">link2r</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Certo!"</span></code></pre> O título também pode estar entre aspas simples ou entre parênteses, ou omitido -inteiramente. As referências podem estar em qualquer lugar no documento e os IDs de referência -pode ser qualquer um, desde que eles são únicos. +inteiramente. As referências podem estar em qualquer lugar no documento e os +IDs de referência podem ser qualquer um, desde que eles sejam únicos. -Existe também a "nomeação implicita", que permite que você use o texto do link como o id +Existe também a "nomeação implícita", que permite que você use o texto do link +como o id: -```md -[Este] [] é um link. +<pre><code class="highlight">[<span class="nv">Isso</span>][] é um link. + +[<span class="nv">Isso</span>]: <span class="sx">http://thisisalink.com/</span></code></pre> + + +Mas geralmente não são usados. + +### Tabela de conteúdo + +Alguns sabores de Markdown fazem inclusive uso de combinação de listas, links e +cabeçalhos de modo a criar uma tabela de conteúdo. Nesse caso, títulos em +cabeçalhos são precedidos de (`#`) e são usados como ids para links. Se o +cabeçalho consistir de várias palavras, elas serão conectadas por hífens (`-`), +que também substitui alguns caracteres especiais. (Embora alguns outros +carácteres especiais sejam omitidos.) -[este]: http://thisisalink.com/ +```md +- [Cabeçalho](#cabecalho) +- [Um outro cabeçalho](#outro-cabecalho) +- [Capítulo](#capitulo) + - [Subcapítulo <h3 />](#subcapitulo-h3-) ``` -Mas não são usados normalmente +De qualquer modo, esse é um recurso que talvez não funcione em todas as +implementações do Markdown da mesma forma. ## Imagens -As imagens são feitas da mesma forma que as ligações, mas com um ponto de exclamação na frente! + +As imagens são feitas da mesma forma que os links, mas com um ponto de +exclamação na frente! ```md -![Este é pairar-texto (texto alternativo) para minha imagem](http://imgur.com/myimage.jpg "Um título opcional") +![Este é alt-text (texto alternativo) para minha imagem](http://imgur.com/myimage.jpg "Um título opcional") ``` E estilo de referência funciona como esperado -```md -![Este é o pairar-texto.][Myimage] +<pre><code class="highlight">![<span class="nv">Esse é o alt-attribute.</span>][<span class="ss">myimage</span>] -[myimage]: relative/urls/legal/image.jpg "se você precisa de um título, é aqui" -``` +[<span class="nv">Minha imagem</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"se precisar de um título, está aqui"</span></code></pre> ## Miscelânea + ### Auto-links ```md @@ -303,14 +343,25 @@ E estilo de referência funciona como esperado ### Escapando caracteres -Quero digitar * Este texto entre asteriscos *, mas eu não quero que ele seja +Quero digitar *Este texto entre asteriscos*, mas eu não quero que ele seja em itálico, então eu faço o seguinte: \*Este texto entre asteriscos \*. +### Teclas do teclado + +No GitHub Flavored Markdown, você pode usar a tag `<kbd>` para representar uma +tecla do teclado. + +```md +Seu computador travou? Tente apertar +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> +``` + ### Tabelas + Tabelas estão disponíveis apenas no GitHub Flavored Markdown e são ligeiramente complicadas, mas se você realmente quer: -```md +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | esquerda-alin| Centrado | direita-alinh | @@ -325,8 +376,22 @@ Col 1 | Col2 | Col3 Ugh isso é tão feio | faça isto | parar ``` -Fim! +## Markdownlint + +De modo a simplificar o trabalho com Markdown e padronizar estilo de código, o +`Markdownlint` foi criado. Essa ferramenta está disponível como plugin para +algumas interfaces de desenvolvimento (IDEs) e pode ser utilizada como um +utilitário para garantir validade e legibilidade do Markdown. --- -Para mais informações, confira o post oficial de John Gruber de sintaxe [aqui](http://daringfireball.net/projects/markdown/syntax) -e de Adam Pritchard grande cheatsheet [aqui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). + +## Leitura complementar + +Para mais informações, confira o post oficial de John Gruber sobre sintaxe [aqui](http://daringfireball.net/projects/markdown/syntax) +e o do cheatsheet do Adam Pritchard [aqui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). + +Se você quiser aprender mais sobre recursos de alguns sabores específicos de +Markdown, veja: + +- [GitHub flavored Markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) +- [GitLab flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html) diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown index fae17bca..947e0699 100644 --- a/pt-br/matlab-pt.html.markdown +++ b/pt-br/matlab-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: Matlab +language: MATLAB contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] @@ -120,7 +120,7 @@ A.d.e = false; % Vetores x = [4 32 53 7 1] -x(2) % Resposta = 32, índices no Matlab começam por 1, não 0 +x(2) % Resposta = 32, índices no MATLAB começam por 1, não 0 x(2:3) % Resposta = 32 53 x(2:end) % Resposta = 32 53 7 1 @@ -479,7 +479,7 @@ perms(x) % Lista todas as permutações de elementos de x % Classes -% Matlab pode suportar programação orientada a objetos. +% MATLAB pode suportar programação orientada a objetos. % Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m % Para começar, criamos uma simples classe que armazena posições de GPS % Início ClassePosicoesGPS.m @@ -501,7 +501,7 @@ classdef ClassePosicoesGPS % O nome da classe. end % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar - % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira: + % uma função especial nós podemos sobrepor a aritmética do MATLAB, desta maneira: function r = plus(o1,o2) r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ... [o1.longitude]+[o2.longitude]); @@ -513,7 +513,7 @@ end % Podemos criar um objeto da classe usando o construtor a = ClassePosicoesGPS(45.0, 45.0) -% Propriedades da classe se comportam exatamente como estruturas Matlab +% Propriedades da classe se comportam exatamente como estruturas MATLAB a.latitude = 70.0 a.longitude = 25.0 @@ -524,15 +524,15 @@ ans = multiplicarLatPor(a,3) % o objeto não precisa ser passado para o método. ans = a.multiplicarLatPor(a,1/3) -% Funções do Matlab podem ser sobrepostas para lidar com objetos. -% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de +% Funções do MATLAB podem ser sobrepostas para lidar com objetos. +% No método abaixo, nós sobrepomos a forma como o MATLAB lida com a soma de % dois objetos PosicoesGPS. b = ClassePosicoesGPS(15.0, 32.0) c = a + b ``` -## Mais sobre Matlab +## Mais sobre MATLAB * O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) * O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index e55f1100..7db6a671 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -7,7 +7,7 @@ translators: - ["Abdala Cerqueira", "http://abda.la"] - ["Raquel Diniz", "http://twitter.com/raquelrdiniz"] lang: pt-br -filename: php-pt.html.markdown +filename: learnphp-pt.php --- Este documento descreve PHP 5+. diff --git a/pt-br/processing-pt.html.markdown b/pt-br/processing-pt.html.markdown new file mode 100644 index 00000000..5ed2950a --- /dev/null +++ b/pt-br/processing-pt.html.markdown @@ -0,0 +1,480 @@ +--- +language: processing +filename: learnprocessing.pde +contributors: + - ["Phone Thant Ko", "http://github.com/phonethantko"] + - ["Divay Prakash", "https://github.com/divayprakash"] +translators: + - ["Kemel Zaidan", "https://github.com/kemelzaidan"] +lang: pt-br +--- + +## Introdução + +Processing é uma linguagem de programação para criação de artes digitais e +conteúdo multimídia, permitindo que não programadores aprendam os fundamentos +da programação computacional em um contexto visual. + +Embora a linguagem seja baseada na linguagem Java, sua sintaxe foi amplamente +influenciado por ambas as sintaxes Java e Javascript. +[Veja mais aqui](https://processing.org/reference/) + +A linguagem é tipada estaticamente e também vem com o seu Ambiente de Desenvolvimento +Integrado (do inglês Integrated Development Environment - IDE) oficial para +compilar e executar os scripts. + +``` +/* --------- + Comentários + --------- +*/ + +// Comentário de linha única começa com // + +/* + Como o Processing é baseado em Java, + a sintaxe para seus comentários é a mesma do Java (como você deve ter notado + acima)! + Comentários de várias linhas são agrupados como visto aqui. +*/ + +/* --------------------------------------- + Escrevendo e executando programas em Processing + --------------------------------------- +*/ + +// No Processing, o ponto de entrada do programa é uma função chamada setup() +// com um tipo de retorno void. +// Observação! A sintaxe é muito semelhante à do C++. +void setup() { + // Isso imprime a saída clássica "Hello World!" no console quando executado. + println("Olá Mundo!"); // Mais uma linguagem com esse maldito ponto e vírgula, não é? +} + +// Normalmente, colocamos todos os códigos estáticos dentro do método setup() +// como o próprio nome sugere, uma vez que é executado apenas uma vez. +// Pode variar da definição das cores de fundo, ou o tamanho da tela. +background(color); //define a cor do fundo +size(largura,altura,[renderizador]); // define o tamanho da tela com parâmetro +// opcional para definir o renderizador +// Você verá mais sobre isso ao longo deste documento. + +// Se você deseja executar os códigos indefinidamente, eles devem ser colocados +// dentro do método draw() +// draw() deve existir caso você queira que o código seja executado +// continuamente e, obviamente, só pode haver um método draw(). +int = 0; +void draw(){ + // Este bloco de código faz um loop para sempre até parar + imprima(i); + i++; // Operador de incremento! +} + +// Agora que sabemos como escrever o script de trabalho e como executá-lo, +// continuaremos a explorar quais tipos de dados e coleções são suportados no +// Processing. + +/* ------------------------ + Tipos de dados e coleções + ------------------------ +*/ + +// De acordo com as Referências do Processing, ele suporta 8 tipos primitivos +// de dados da seguinte forma. + +boolean valorBoleano = true; // Boleano +byte valorByteDeA = 23; // Byte +char valorCharDeA = 'A'; // Caractere +color valorDeCorBrancoM = color(255, 255, 255); // Cor (especificada usando +// método color()) +color valorDeCorBrancoH = #FFFFFF; // Cor (especificada usando valor de hash) +int valor = 5; // Inteiro (Número sem decimais) +long valorLongo = 2147483648L; // "L" é adicionado ao número para marcá-lo como um longo +float valorFloat = 1,12345; // Float (números de ponto flutuante de 32 bits) +double valorDouble = 1,12345D; // Double (números de ponto flutuante de 64 bits) + +// NOTA! +// Embora os tipos de dados "long" e "double" funcionem na linguagem, +// funções do Processing não usam esses tipos de dados, portanto +// eles precisam ser convertidos em tipos de dados "int" e "float", +// respectivamente, usando a sintaxe (int) e (float) antes de passar para uma +// função. + +// Existem vários tipos de dados compostos que estão disponíveis por padrão para +// uso no Processing. +// Primeiramente, farei um resumo dos mais usados para economizar tempo. + +// String +// Enquanto o tipo de dados char usa '', o tipo de dados String usa "" - aspas +// duplas. +string stringExemplo = "Olá, Processing!"; +// String também pode ser criada a partir de um array de tipos de dados char. +// Nós vamos discutir array muito em breve. +char fonte = {'H', 'E', 'L', 'L', 'O'}; +String stringDeFonte = new String(source); // HELLO +// Como em Java, strings podem ser concatenadas usando o operador "+". +print("Olá " + "Mundo!"); // Olá Mundo! + +// Array +// Arrays em Processing podem conter quaisquer tipos de dados, incluindo os +// próprios objetos. Como os arrays são semelhantes aos objetos, eles devem +// ser criados com a palavra-chave "new". +int[] arrayInt = new int[5]; +int[] arrayIntComValores = {1, 2, 3}; // Você também pode preencher com dados. + +// Lista de Arrays +// As funções são semelhantes às do array; arraylists podem conter qualquer +// tipo de dados. A única diferença é que as listas de matrizes são +// redimensionadas dinamicamente, pois é uma forma de implementação de matriz +// redimensionável da interface "List" do Java . +ArrayList<Integer> intArrayList = new ArrayList<Integer>(); + +// Objeto +// Como é baseado em Java, o Processing suporta programação orientada a objetos. +// Isso significa que você pode basicamente definir quaisquer tipos de dados de +// sua preferência e manipulá-los para suas necessidades. +// Claro, uma classe tem que ser definida antes para o objeto que você quer. +// Formato --> NomeClasse NameInstancia +UmaClasseQualquer meuObjeto // então instancia mais tarde +//ou +UmaClasseQualquer meuObjetoInstanciado = new UmaClasseQualquer(); + +// O Processing surge com mais coleções (ex. - Dicionários e Listas) por +// padrão, por uma questão de simplicidade, vou deixá-los fora da discussão aqui. + +/* ------------ + Matemática + ------------ +*/ + +// Aritmética +1 + 1 // 2 +2 - 1 // 1 +2 * 3 // 6 +3/2 // 1 +3.0 / 2 // 1.5 +3.0% 2 // 1.0 + +// O Processing também vem com um conjunto de funções que simplificam operações +// matemáticas. +float f = sq(3); // f = 9.0 +float p = pow(3, 3); // p = 27.0 +int a = abs(-13); // a = 13 +int r1 = round(3.1); // r1 = 3 +int r2 = round(3.7); // r2 = 4 +float sr = sqrt(25); // sr = 5.0 + +// Vetores +// O Processing fornece uma maneira fácil de implementar vetores em seu ambiente +// usando a classe PVector. Ela pode descrever um vetor bi ou tridimensional e +// vem com um conjunto de métodos que são úteis para operações com matrizes. +// Você pode encontrar mais informações sobre a classe PVector e suas funções +// aqui. (https://processing.org/reference/PVector.html) + +// Trigonometria +// O Processing também suporta operações trigonométricas fornecendo um +// conjunto de funções. sin(), cos(), tan(), asin(), acos(), atan() e também +// degrees() e radians() para conversão conveniente. +// No entanto, essas funções usam o ângulo em radianos como parâmetro, então é +// necessário converter previamente. +float um = sin(PI/2); // um = 1.0 +// Como você deve ter notado, existe um conjunto de constantes para usos +// trigonométricos; PI, HALF_PI, QUARTER_PI e assim por diante... + +/* ------------- + Controle de fluxo + ------------- +*/ + +// Declarações Condicionais +// Instruções If - A mesma sintaxe das instruções if em Java. +if (author.getAppearance().equals("quente")) { + print("Narcisismo no máximo!"); +} else { + // Você pode verificar outras condições aqui. + print("Algo está realmente errado aqui!"); +} +// Um atalho para instruções if-else também pode ser usado. +int = 3; +String valor = (i > 5) ? "Grande" : "Pequena"; // "Pequena" + +// A estrutura switch-case pode ser usada para verificar várias condições de +// forma concisa. É importante usar a instrução break. Se a instrução `break` +// não existe o programa executa todos os casos a seguir após um caso ser +// verdadeiro. +int valor = 2; +switch(valor) { + case 0: + print("Nada!"); // Isso não é executado. + break; // Salta para a próxima instrução + case 1: + print("Chegando lá..."); // Isso novamente não é executado. + break; + case 2: + print("Bravo!"); // Esta linha é executada. + break; + default: + print("Não encontrado!"); // Esta linha é executada se nosso valor for algum outro valor. + break; +} + +// Declarações iterativas +// Declarações For - Novamente, a mesma sintaxe que em Java +for(int i = 0; i < 5; i++){ + print(i); // imprime de 0 a 4 +} + +// Declarações While - Novamente, nada de novo se você estiver familiarizado com +// a sintaxe Java. +int j = 3; +while(j > 0) { + print(j); + j--; // Isso é importante para evitar que o código seja executado indefinidamente. +} + +// loop()| noLoop() | redraw() | exit() +// Estas são mais funções específicas do Processing para configurar o fluxo do +// programa. +loop(); // permite que o método draw() seja executado para sempre enquanto +noLoop(); // só permite que ele seja executado uma vez. +redraw(); // executa o método draw() mais uma vez. +exit(); // Isso para o programa. É útil para programas com draw() +// rodando continuamente. +``` + +## Desenho com Processing + +Como você já deve ter entendido o básico da linguagem, vamos agora +ver a melhor parte do Processing - DESENHAR. + +``` +/* ------ + Formas + ------ +*/ + +// Formas 2D + +// Ponto +point(x, y); // No espaço 2D +point(x, y, z); // No espaço 3D +// Desenha um ponto no espaço de coordenadas. + +// Linha +line(x1, y1, x2, y2); // No espaço 2D +line(x1, y1, z1, x2, y2, z2); // No espaço 3D +// Desenha uma linha conectando dois pontos definidos por (x1, y1) e (x2, y2). + +// Triângulo +triangle(x1, y1, x2, y2, x3, y3); +// Desenha um triângulo conectando três pontos definidos por parâmetros de coordenadas. + +// Retângulo +rect(a, b, c, d, [r]); // Com parâmetro opcional definindo o raio de todos os cantos +rect(a, b, c, d, [te, td, bd, be]); // Com conjunto opcional de parâmetros definindo +// raio de cada canto +// Desenha um retângulo com {a, b} como coordenada superior esquerda e c e d como largura +// e altura respectivamente. + +// Quad +quad(x, y, x2, y2, x3, y3, x4, y4); +// Desenha um quadrilátero com parâmetros que definem as coordenadas de cada canto +// ponto. + +// Elipse +ellipse(x, y, largura, altura); +// Desenha um eclipse no ponto {x, y} com largura e altura especificadas. + +// Arco +arc(x, y, largura, altura, inicio, fim, [modo]); +// Enquanto os primeiros quatro parâmetros são autoexplicativos, +// início e fim definem os ângulos que o arco começa e termina (em radianos). +// O parâmetro opcional [mode] define o preenchimento; +// PIE dá o contorno de torta, CHORD dá o contorno reto e OPEN é como +// CHORD porém sem contorno + +// Curvas +// O Processing fornece duas implementações de curvas; usando curve() e +// bezier(). Como pretendo manter isso simples, não vou discutir mais detalhes. +// No entanto, se você quiser implementá-lo em seu sketch, aqui estão as +// referências: (https://processing.org/reference/curve_.html) +// (https://processing.org/reference/bezier_.html) + +// Formas 3D + +// espaço 3D +pode ser configurado definindo "P3D" para o parâmetro do renderizador no +// método size(). +size(largura, altura, P3D); +// No espaço 3D, você terá que traduzir para a coordenada específica para +// renderiza as formas 3D. + +// Caixa +box(tamanho); // Cubo com o mesmo comprimento definido pelo tamanho +box(w, h, d); // Caixa com largura, altura e profundidade definidas separadamente + +// Esfera +sphere(raio); // Seu tamanho é definido usando o parâmetro raio +// O mecanismo por trás da renderização das esferas é implementado por +// triângulos em mosaico. Dito isso, o nível de detalhe sendo renderizado é +// controlado pela função sphereDetail(res) +// Mais informações aqui: (https://processing.org/reference/sphereDetail_.html) + +// Formas irregulares +// E se você quiser desenhar algo que não foi disponibilizado pelo Processing +// funções? +// Você pode usar beginShape(), endShape(), vertex(x,y) para definir formas por +// especificando cada ponto. Mais informações aqui: +// (https://processing.org/reference/beginShape_.html) +// Você também pode usar formas personalizadas usando a classe PShape: +// (https://processing.org/reference/PShape.html) + +/* --------------- + Transformações + --------------- +*/ + +// As transformações são particularmente úteis para acompanhar o espaço de +// coordenadas e os vértices das formas que você desenhou. Particularmente; +// métodos de pilha de matrizes; pushMatrix(), popMatrix() e translate(x,y) +pushMatriz(); // Salva o sistema de coordenadas atual na pilha +// ... aplique todas as transformações aqui ... +popMatriz(); // Restaura o sistema de coordenadas salvo +// Usando-os, o sistema de coordenadas pode ser preservado e visualizado sem +// causar qualquer conflito. + +// Traduzir +translate(x,y); // Traduz para o ponto{x, y} ou seja - configurando a origem para esse ponto +translate(x, y, z); // Contraparte 3D da função + +// Rotacionar +rotate(ângulo); // Gira a quantidade especificada pelo parâmetro ângulo +// Possui 3 contrapartes 3D para realizar a rotação, uma para cada dimensão: +// rotateX(ângulo), rotateY(ângulo), rotateZ(ângulo) + +// Escala +scale(s); // Dimensiona o sistema de coordenadas expandindo ou contraindo-o. + +/* -------------------- + Estilo e texturas + -------------------- +*/ + +// Cores +// Como discuti anteriormente, a cor de fundo pode ser configurada usando a +// função background(). Você pode definir a cor de um objeto de antemão e depois +// passar para a função como um argumento. +color c = cor(255, 255, 255); // BRANCO! +// Por padrão, o Processing usa o esquema de cores RGB, mas pode ser configurado +// para HSB usando colorMode(). Leia mais aqui: +// (https://processing.org/reference/colorMode_.html) +background(c); // Até agora, a cor de fundo deve ser branca. +// Você pode usar a função fill() para selecionar a cor para preencher as formas. +// Tem que ser configurado antes de você começar a desenhar formas para que as +// cores fiquem aplicadas. +fill(color(0, 0, 0)); +// Se você quiser apenas colorir os contornos das formas, você pode usar +// função stroke(). +stroke(255, 255, 0, 200); // cor do traço definida para amarelo com transparência +// definido para um valor menor. + +// Imagens +// O Processing pode renderizar imagens e usá-las de várias maneiras. +// Principalmente armazenado como Tipo de dados PImage. +filter(sombreador); // O Processing suporta várias funções de filtro para manipulação de imagens. +texture(imagem); // PImage pode ser passado em argumentos para mapeamento de textura das formas. +``` + +Se você quiser levar as coisas adiante, há mais coisas que o Processing tem o poder de fazer. Renderizar modelos, shaders e outros efeitos. Há muito para se cobrir em uma +documentação curta, então vou deixá-los aqui. Se você se interessar, por favor verifique as referências. + +``` +// Antes de prosseguirmos, vou falar um pouco mais sobre como importar bibliotecas +// para que você possa estender a funcionalidade do Processing para outros horizontes. + +/* ------- + Importações + ------- +*/ + +// As possibilidades do Processing pode ser estendidas ainda mais quando +// importamos bibliotecas e pacotes em nossos esboços. +// A instrução de importação pode ser escrita como abaixo na parte superior +// do código-fonte. +import processing.algumacoisa.*; +``` + +## VAC? + +Vamos ao código? Vamos sujar as mãos! + +Vamos ver um exemplo do openprocessing para visualizar o quanto o Processing é +capaz de fazer com poucas linhas de código. + +Copie o código abaixo em seu IDE do Processing e veja a mágica. + +``` +// Isenção de responsabilidade: eu não escrevi este programa porque atualmente +// estou ocupado com meu estágio e este sketch é adaptado do openprocessing pois +// mostra algo legal com um código simples. +// Recuperado de: (https://www.openprocessing.org/sketch/559769) + +float theta; +float a; +float col; +float num; + +void setup() { + size(600,600); +} + +void draw() { + background(#F2F2F2); + translate(width/2, height/2); + theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6); + + float num=6; + for (int i=0; i<num; i++) { + a =350; + rotate(TWO_PI/num); + branch(a); + } + +} + +void branch(float len) { + col=map(len, 0, 90, 150, 255); + fill(col, 0, 74); + stroke (col, 0, 74); + line(0, 0, 0, -len); + ellipse(0, -len, 3, 3); + len *= 0.7; + + if (len>30) { + pushMatrix(); + translate(0, -30); + rotate(theta); + branch(len); + popMatrix(); + + pushMatrix(); + translate(0, -30); + rotate(-theta); + branch(len); + popMatrix(); + + } +} +``` + +A linguagem Processing é fácil de aprender e é particularmente útil para criar +conteúdo (mesmo em 3D) sem ter que digitar muitos códigos. É tão simples +que você pode ler o código e ter uma ideia aproximada do fluxo do programa. + +No entanto, isso não se aplica quando você introduz bibliotecas externas, pacotes +e até mesmo suas próprias aulas. (Confie em mim! Projetos em processing podem ficar realmente monstruosos...) + +## Alguns recursos úteis + + - [Site do Processing](http://processing.org) + - [Sketches em Processing](http://openprocessing.org) diff --git a/pt-br/pythonstatcomp-pt.html.markdown b/pt-br/pythonstatcomp-pt.html.markdown new file mode 100644 index 00000000..aa532eb4 --- /dev/null +++ b/pt-br/pythonstatcomp-pt.html.markdown @@ -0,0 +1,249 @@ +--- +category: tool +tool: Statistical Computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +translators: + - ["waltercjunior", "https://github.com/waltercjunior"] +filename: pythonstatcomp-pt.py +lang: pt-br +--- + +Este é um tutorial sobre como fazer algumas tarefas típicas de programação estatística usando Python. +É destinado basicamente à pessoas familizarizadas com Python e experientes com programação estatística em linguagens como R, +Stata, SAS, SPSS ou MATLAB. + +```python + + + +# 0. Preparando-se ==== + +""" Para começar, instale o seguinte : jupyther, numpy, scipy, pandas, + matplotlib, seaborn, requests. + Certifique-se de executar este tutorial utilizando o Jupyther notebook para + que você utilize os gráficos embarcados e ter uma fácil consulta à + documentação. + O comando para abrir é simplesmente '`jupyter notebook`, quando abrir então + clique em 'New -> Python'. +""" + +# 1. Aquisição de dados ==== + +""" A única razão das pessoas optarem por Python no lugar de R é que pretendem + interagir com o ambiente web, copiando páginas diretamente ou solicitando + dados utilizando uma API. Você pode fazer estas coisas em R, mas no + contexto de um projeto já usando Python, há uma vantagem em se ater uma + linguágem única. +""" + +import requests # para requisições HTTP (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # se retornou código 200, a requisição foi bem sucedida +r.text # código fonte bruto da página +print(r.text) # formatado bonitinho +# salve a o código fonte d apágina em um arquivo: +os.getcwd() # verifique qual é o diretório de trabalho +with open("learnxinyminutes.html", "wb") as f: + f.write(r.text.encode("UTF-8")) + +# Baixar um arquivo csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +with open(fn, "wb") as f: + f.write(r.text.encode("UTF-8")) + +""" para mais informações sobre o módulo de solicitações, incluindo API's, veja em + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Lendo um arquivo formato CSV ==== + +""" Um pacote de pandas da Wes McKinney lhe dá um objeto 'DataFrame' em Python. + Se você já usou R, já deve estar familiarizado com a ideia de "data.frame". +""" + +import pandas as pd +import numpy as np +import scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" Usuários R: observe que o Python, como a maioria das linguagens de programação + influenciada pelo C, a indexação começa de 0. Em R, começa a indexar em 1 + devido à influência do Fortran. +""" + +# duas maneiras diferentes de imprimir uma coluna +pets.age +pets["age"] + +pets.head(2) # imprima as 2 primeiras linhas +pets.tail(1) # imprima a última linha + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# Em R, você esperaria obter 3 linhas fazendo isso, mas aqui você obtem 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age) * 2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" Se você está fazendo alguma álgebra linear séria e processamento de + números você pode desejar apenas arrays, não DataFrames. DataFrames são + ideais para combinar colunas de diferentes tipos de dados. +""" + +# 3. Gráficos ==== + +import matplotlib as mpl +import matplotlib.pyplot as plt +%matplotlib inline + +# Para fazer a visualiação de dados em Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); + +# seaborn utiliza a biblioteca do matplotlib e torna os enredos mais bonitos + +import seaborn as sns + +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); + +# também existem algumas funções de plotagem específicas do seaborn +# observe como o seaborn automaticamenteo o eixto x neste gráfico de barras +sns.barplot(pets["age"]) + +# Veteranos em R ainda podem usar o ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# fonte: https://pypi.python.org/pypi/ggplot + +# há até um d3.js veja em: https://github.com/mikedewar/d3py + +# 4. Limpeza de dados simples e análise exploratória ==== + +""" Aqui está um exemplo mais complicado que demonstra dados básicos + fluxo de trabalho de limpeza levando à criação de algumas parcelas + e a execução de uma regressão linear. + O conjunto de dados foi transcrito da Wikipedia à mão. Contém + todos os sagrados imperadores romanos e os marcos importantes em suas vidas + (birth, death, coronation, etc.). + O objetivo da análise será explorar se um relacionamento existe + entre o ano de nascimento (birth year) e a expectativa de vida (lifespam) + do imperador. + Fonte de dados: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# carregue alguns dados dos sagrados imperadores romanos +url = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/hre.csv" +r = requests.get(url) +fp = "hre.csv" +with open(fp, "wb") as f: + f.write(r.text.encode("UTF-8")) + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death +0 NaN Carolingian Charles I 2 April 742 28 January 814 +1 NaN Carolingian Louis I 778 20 June 840 +2 NaN Carolingian Lothair I 795 29 September 855 +3 NaN Carolingian Louis II 825 12 August 875 +4 NaN Carolingian Charles II 13 June 823 6 October 877 + + Coronation 1 Coronation 2 Ceased to be Emperor +0 25 December 800 NaN 28 January 814 +1 11 September 813 5 October 816 20 June 840 +2 5 April 823 NaN 29 September 855 +3 Easter 850 18 May 872 12 August 875 +4 29 December 875 NaN 6 October 877 +""" + +# limpar as colunas Birth e Death + +import re # módulo para expressões regulares + +rx = re.compile(r'\d+$') # conincidir com os códigos finais + +""" Esta função aplia a expressão reguar a uma coluna de entrada (here Birth, + Death), nivela a lista resultante, converte-a em uma lista de objetos, e + finalmente converte o tipo do objeto da lista de String para inteiro. para + mais informações sobre o que as diferentes partes do código fazer, veja em: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" + +from functools import reduce + +def extractYear(v): + 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) + +# faça uma coluna infomrnado a idade estimada ("EstAge") +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# gráfico de dispersão simples, sem linha de tendência, cor representa dinastia +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False) + +# use o scipy para executar uma regrassão linear +from scipy import stats +(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge) +# código fonte: http://wiki.scipy.org/Cookbook/LinearRegression + +# varifique o declive (slope) +slope # 0.0057672618839073328 + +# varifique o valor R^2: +rval**2 # 0.020363950027333586 + +# varifique o valor p-value +pval # 0.34971812581498452 + +# use o seaborn para fazer um gráfico de dispersão e traçar a linha de tendência de regrassão linear +sns.lmplot("BirthY", "EstAge", data=hre) + +""" Para mais informações sobre o seaborn, veja + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + Para mais informações sobre o SciPy, veja + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + Para ver uma versão da análise dos sagrados imperadores romanos usando R, consulte + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" + +``` + +Se você quiser saber mais, obtenha o Python para análise de dados de Wes McKinney. É um excelente recurso e usei-o como referência ao escrever este tutorial. + +Você também pode encontrar muitos tutoriais interativos de IPython sobre assuntos específicos de seus interesses, como Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Programação Probabilística e Métodos Bayesianos para Hackers">Programação Probabilística e Métodos Bayesianos para Hackers</a>. + +Mais alguns módulos para pesquisar: + - análise de texto e processamento de linguagem natural: nltk, http://www.nltk.org + - análise de rede social: igraph, http://igraph.org/python/ diff --git a/pt-br/qt-pt.html.markdown b/pt-br/qt-pt.html.markdown index 99579c35..f4211e09 100644 --- a/pt-br/qt-pt.html.markdown +++ b/pt-br/qt-pt.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: Qt Framework -language: c++ +language: C++ filename: learnqt-pt.cpp contributors: - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] diff --git a/pt-br/r-pt.html.markdown b/pt-br/r-pt.html.markdown new file mode 100644 index 00000000..5c9304ec --- /dev/null +++ b/pt-br/r-pt.html.markdown @@ -0,0 +1,786 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["kalinn", "http://github.com/kalinn"] +translators: + - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"] +lang: pt-br +filename: learnr-pt.r +--- + +R é uma linguagem de programação estatística. Ela tem muitas bibliotecas para carregar e limpar conjuntos de dados, executar análises estatísticas e produzir gráficos. Você também pode executar comandos do `R` dentro de um documento LaTeX. + +```r + +# Comentários começam com o símbolo de Cerquilha, também conhecido como +# jogo da velha + +# Não existe um símbolo especial para comentários em várias linhas +# mas você pode escrever várias linhas de comentários adicionando a +# cerquilha (#) ao início de cada uma delas. + +# No Windows e Linux, você pode usar CTRL-ENTER para executar uma linha. +# No MacOS, o equivalente é COMMAND-ENTER + + + +############################################################################# +# Coisas que você pode fazer sem entender nada sobre programação +############################################################################# + +# Nesta seção, mostramos algumas das coisas legais que você pode fazer em +# R sem entender nada de programação. Não se preocupe em entender tudo o +# que o código faz. Apenas aproveite! + +data() # navegue pelos conjuntos de dados pré-carregados +data(rivers) # carregue este: "Comprimentos dos principais rios norte-americanos" +ls() # observe que "rivers" apareceu na área de trabalho (workspace) +head(rivers) # dê uma espiada no conjunto de dados +# 735 320 325 392 524 450 + +length(rivers) # quantos rios foram medidos? +# 141 +summary(rivers) # consulte um sumário de estatísticas básicas +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# faça um diagrama de ramos e folhas (uma visualização de dados semelhante a um histograma) +stem(rivers) + +# A vírgula está 2 dígito(s) à direita do símbolo | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) # Observe que os dados não são normais nem log-normais! +# Tome isso, fundamentalistas da curva normal! + +# O ponto decimal está 1 dígito(s) à esquerda do símbolo | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + +# faça um histograma: +hist(rivers, col="#333333", border="white", breaks=25) # brinque com estes parâmetros +hist(log(rivers), col="#333333", border="white", breaks=25) # você fará mais gráficos mais tarde + +# Aqui está outro conjunto de dados que vem pré-carregado. O R tem toneladas deles. +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Ano", + main="Número de descobertas importantes por ano") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Ano", + main="Número de descobertas importantes por ano") + +# Em vez de deixar a ordenação padrão (por ano), +# também podemos ordenar para ver o que é mais comum: +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# O ponto decimal está no símbolo | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + +# Role um dado algumas vezes +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Seus números serão diferentes dos meus, a menos que definamos a mesma semente aleatória com o set.seed + +# Obtenha 9 números de forma aleatória a partir de uma distribuição normal +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +################################################## +# Tipos de dados e aritmética básica +################################################## + +# Agora para a parte orientada a programação do tutorial. +# Nesta seção você conhecerá os tipos de dados importantes do R: +# integers, numerics, characters, logicals, e factors. +# Existem outros, mas estes são o mínimo que você precisa para +# iniciar. + +# INTEGERS +# Os inteiros de armazenamento longo são escritos com L +5L # 5 +class(5L) # "integer" +# (Experimente ?class para obter mais informações sobre a função class().) +# Em R, todo e qualquer valor, como 5L, é considerado um vetor de comprimento 1 +length(5L) # 1 +# Você pode ter um vetor inteiro com comprimento > 1 também: +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# NUMERICS +# Um "numeric" é um número de ponto flutuante de precisão dupla +5 # 5 +class(5) # "numeric" +# De novo, tudo em R é um vetor; +# você pode fazer um vetor numérico com mais de um elemento +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# Você também pode usar a notação científica +5e4 # 50000 +6.02e23 # Número de Avogadro +1.6e-35 # Comprimento de Planck +# Você também pode ter números infinitamente grandes ou pequenos +class(Inf) # "numeric" +class(-Inf) # "numeric" +# Você pode usar "Inf", por exemplo, em integrate(dnorm, 3, Inf) +# isso evita as tabelas de escores-Z. + +# ARITMÉTICA BÁSICA +# Você pode fazer aritmética com números +# Fazer aritmética com uma mistura de números inteiros (integers) e com +# ponto flutuante (numeric) resulta em um numeric +10L + 66L # 76 # integer mais integer resulta em integer +53.2 - 4 # 49.2 # numeric menos numeric resulta em numeric +2.0 * 2L # 4 # numeric vezes integer resulta em numeric +3L / 4 # 0.75 # integer dividido por numeric resulta em numeric +3 %% 2 # 1 # o resto de dois numeric é um outro numeric +# Aritmética ilegal produz um "não-é-um-número" (do inglês Not-a-Number): +0 / 0 # NaN +class(NaN) # "numeric" +# Você pode fazer aritmética em dois vetores com comprimento maior que 1, +# desde que o comprimento do vetor maior seja um múltiplo inteiro do menor +c(1,2,3) + c(1,2,3) # 2 4 6 +# Como um único número é um vetor de comprimento um, escalares são aplicados +# elemento a elemento com relação a vetores +(4 * c(1,2,3) - 2) / 2 # 1 3 5 +# Exceto para escalares, tenha cuidado ao realizar aritmética em vetores com +# comprimentos diferentes. Embora possa ser feito, +c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 +# ter comprimentos iguais é uma prática melhor e mais fácil de ler +c(1,2,3,1,2,3) * c(1,2,1,2,1,2) + +# CHARACTERS +# Não há diferença entre strings e caracteres em R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# São ambos vetores de caracteres de comprimento 1 +# Aqui está um mais longo: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# Você pode utilizar expressões regulares (regex) em vetores de caracteres: +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R tem vários vetores de caracteres embutidos: +letters +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + +# LOGICALS +# Em R, um "logical" é um booleano +class(TRUE) # "logical" +class(FALSE) # "logical" +# O comportamento deles é normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Dados ausentes (NA) são logical, também +class(NA) # "logical" +# Use | e & para operações lógicas. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Aplicar | e & a vetores retorna operações lógicas elemento a elemento +c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE +c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE +# Você pode testar se x é TRUE +isTRUE(TRUE) # TRUE +# Aqui obtemos um vetor logical com muitos elementos: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# FACTORS +# A classe factor é para dados categóricos +# Os fatores podem ser ordenados (como as avaliações de crianças) ou +# não ordenados (como as cores) +factor(c("azul", "azul", "verde", NA, "azul")) +# azul azul verde <NA> azul +# Levels: azul verde +# Os "levels" são os valores que os dados categóricos podem assumir +# Observe que os dados ausentes não entram nos levels +levels(factor(c("verde", "verde", "azul", NA, "azul"))) # "azul" "verde" +# Se um vetor de factor tem comprimento 1, seus levels também terão comprimento 1 +length(factor("green")) # 1 +length(levels(factor("green"))) # 1 +# Os fatores são comumente vistos em data frames, uma estrutura de dados que abordaremos +# mais tarde +data(infert) # "Infertilidade após aborto espontâneo e induzido" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" é um valor estranho; use-o para "apagar" um vetor +class(NULL) # NULL +parakeet = c("bico", "penas", "asas", "olhos") +parakeet +# [1] "bico" "penas" "asas" "olhos" +parakeet <- NULL +parakeet +# NULL + +# COERÇÃO DE TIPO +# Coerção de tipo é quando você força um valor a assumir um tipo diferente +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# Se você colocar elementos de diferentes tipos em um vetor, coerções estranhas acontecem: +c(TRUE, 4) # 1 4 +c("cachorro", TRUE, 4) # "cachorro" "TRUE" "4" +as.numeric("Bilbo") +# [1] NA +# Warning message: +# NAs introduced by coercion + +# Observe também: esses são apenas os tipos de dados básicos +# Existem muitos outros tipos de dados, como datas, séries temporais, etc. + + + +################################################## +# Variáveis, laços, expressões condicionais +################################################## + +# Uma variável é como uma caixa na qual você armazena um valor para uso posterior. +# Chamamos isso de "atribuir" o valor à variável. +# Ter variáveis nos permite escrever laços, funções e instruções com condição + +# VARIÁVEIS +# Existem muitas maneiras de atribuir valores: +x = 5 # é possível fazer assim +y <- "1" # mas é preferível fazer assim +TRUE -> z # isso funciona, mas é estranho + +# LAÇOS +# Nós temos laços com for +for (i in 1:4) { + print(i) +} +# [1] 1 +# [1] 2 +# [1] 3 +# [1] 4 +# Nós temos laços com while +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# 10...9...8...7...6...5... +# Tenha em mente que os laços for e while são executados lentamente em R +# Operações em vetores inteiros (por exemplo, uma linha inteira, uma coluna inteira) +# ou funções do tipo apply() (discutiremos mais tarde) são mais indicadas + +# IF/ELSE +# Novamente, bastante padrão +if (4 > 3) { + print("4 é maior que 3") +} else { + print("4 não é maior que 3") +} +# [1] "4 é maior que 3" + +# FUNÇÕES +# Definidas assim: +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) # adicione um pouco de ruído (controlado) + return(x) +} +# Chamada como qualquer outra função R: +jiggle(5) # 5±ε. Após set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################### +# Estruturas de dados: Vetores, matrizes, data frames e arranjos (arrays) +########################################################################### + +# UNIDIMENSIONAL + +# Vamos começar do início, e com algo que você já sabe: vetores. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# Consultamos elementos específicos utilizando colchetes +# (Observe que R começa a contar a partir de 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# Também podemos pesquisar os índices de componentes específicos, +which(vec %% 2 == 0) # 1 3 +# pegue apenas as primeiras ou últimas entradas no vetor, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# ou descubra se um determinado valor está no vetor +any(vec == 10) # TRUE +# Se um índice for além do comprimento de um vetor, você obterá NA: +vec[6] # NA +# Você pode encontrar o comprimento do seu vetor com length() +length(vec) # 4 +# Você pode realizar operações em vetores inteiros ou subconjuntos de vetores +vec * 4 # 32 36 40 44 +vec[2:3] * 5 # 45 50 +any(vec[2:3] == 8) # FALSE +# e R tem muitas funções internas para sumarizar vetores +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Mais alguns recursos embutidos: +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +# BIDIMENSIONAL (ELEMENTOS DA MESMA CLASSE) + +# Você pode fazer uma matriz com entradas do mesmo tipo assim: +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Ao contrário de um vetor, a classe de uma matriz é "matrix" independente do que ela contém +class(mat) # "matrix" +# Consulte a primeira linha +mat[1,] # 1 4 +# Execute uma operação na primeira coluna +3 * mat[,1] # 3 6 9 +# Consulte uma célula específica +mat[3,2] # 6 + +# Transponha toda a matriz +t(mat) +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# Multiplicação de matrizes +mat %*% t(mat) +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() une vetores em colunas para formar uma matriz +mat2 <- cbind(1:4, c("cachorro", "gato", "passaro", "cachorro")) +mat2 +# [,1] [,2] +# [1,] "1" "cachorro" +# [2,] "2" "gato" +# [3,] "3" "passaro" +# [4,] "4" "cachorro" +class(mat2) # matrix +# Mais uma vez, observe o que aconteceu! +# Como as matrizes devem conter todas as entradas da mesma classe, +# tudo foi convertido para a classe character +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() une vetores linha a linha para fazer uma matriz +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, tudo da mesma classe. Sem coerções. Muito melhor. + +# BIDIMENSIONAL (CLASSES DIFERENTES) + +# Para colunas de tipos diferentes, use um data frame +# Esta estrutura de dados é tão útil para programação estatística, +# que uma versão dela foi adicionada ao Python através do pacote "pandas". + +estudantes <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(estudantes) <- c("nome", "ano", "casa") # nomeie as colunas +class(estudantes) # "data.frame" +estudantes +# nome ano casa +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(estudantes$ano) # "numeric" +class(estudantes[,3]) # "factor" +# encontre as dimensões +nrow(estudantes) # 6 +ncol(estudantes) # 3 +dim(estudantes) # 6 3 +# A função data.frame() converte vetores de caracteres em vetores de fator +# por padrão; desligue isso definindo stringsAsFactors = FALSE quando +# você criar um data frame +?data.frame + +# Existem muitas maneiras particulares de consultar partes de um data frame, +# todas sutilmente diferentes +estudantes$ano # 3 2 2 1 0 -1 +estudantes[,2] # 3 2 2 1 0 -1 +estudantes[,"ano"] # 3 2 2 1 0 -1 + +# Uma versão extendida da estrutura data.frame é a data.table +# Se você estiver trabalhando com dados enormes ou em painel, ou precisar mesclar +# alguns conjuntos de dados, data.table pode ser uma boa escolha. Aqui está um tour +# relâmpago: +install.packages("data.table") # baixe o pacote a partir do CRAN +require(data.table) # carregue ele +estudantes <- as.data.table(estudantes) +estudantes # observe a saída ligeiramente diferente +# nome ano casa +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +estudantes[nome=="Ginny"] # Consulte estudantes com o nome == "Ginny" +# nome ano casa +# 1: Ginny -1 G +estudantes[ano==2] # Consulte estudantes com o ano == 2 +# nome ano casa +# 1: Fred 2 G +# 2: George 2 G +# data.table facilita a fusão de dois conjuntos de dados +# vamos fazer outro data.table para mesclar com os alunos +fundadores <- data.table(casa=c("G","H","R","S"), + fundador=c("Godric","Helga","Rowena","Salazar")) +fundadores +# casa fundador +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(estudantes, casa) +setkey(fundadores, casa) +estudantes <- fundadores[estudantes] # mescle os dois conjuntos de dados com base na "casa" +setnames(estudantes, c("casa","nomeFundadorCasa","nomeEstudante","ano")) +estudantes[,order(c("nome","ano","casa","nomeFundadorCasa")), with=F] +# nomeEstudante ano casa nomeFundadorCasa +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + +# O data.table torna as tabelas de sumário fáceis +estudantes[,sum(ano),by=casa] +# casa V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# Para remover uma coluna de um data.frame ou data.table, +# atribua a ela o valor NULL +estudantes$nomeFundadorCasa <- NULL +estudantes +# nomeEstudante ano casa +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Remova uma linha consultando parte dos dados +# Usando data.table: +estudantes[nomeEstudante != "Draco"] +# casa estudanteNome ano +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# Usando data.frame: +estudantes <- as.data.frame(estudantes) +estudantes[estudantes$casa != "G",] +# casa nomeFundadorCasa nomeEstudante ano +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTIDIMENSIONAL (TODOS OS ELEMENTOS DE UM TIPO) + +# Arranjos (arrays) criam tabelas n-dimensionais +# Todos os elementos devem ser do mesmo tipo +# Você pode fazer uma tabela bidimensional (como uma matriz) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# Você pode usar array para fazer matrizes tridimensionais também +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LISTAS (MULTIDIMENSIONAIS, POSSIVELMENTE IMPERFEITAS, DE DIFERENTES TIPOS) + +# Finalmente, R tem listas (de vetores) +lista1 <- list(tempo = 1:40) +lista1$preco = c(rnorm(40,.5*lista1$tempo,4)) # aleatória +lista1 +# Você pode obter itens na lista assim +lista1$tempo # um modo +lista1[["tempo"]] # um outro modo +lista1[[1]] # e ainda um outro modo +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# Você pode obter itens de uma lista como qualquer outro vetor +lista1$preco[4] + +# Listas não são a estrutura de dados mais eficiente para se trabalhar em R; +# a menos que você tenha um bom motivo, você deve se ater a data.frames +# As listas geralmente são retornadas por funções que realizam regressões lineares + +################################################## +# A família de funções apply() +################################################## + +# Lembra de mat? +mat +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Use apply(X, MARGIN, FUN) para aplicar a função FUN a uma matriz X +# sobre linhas (MARGIN = 1) ou colunas (MARGIN = 2) +# Ou seja, R faz FUN para cada linha (ou coluna) de X, muito mais rápido que um +# laço for ou while faria +apply(mat, MAR = 2, jiggle) +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Outras funções: ?lappy, ?sapply + +# Não as deixe te intimidar; todos concordam que essas funções são bem confusas + +# O pacote plyr visa substituir (e melhorar!) a família *apply(). +install.packages("plyr") +require(plyr) +?plyr + + + +######################### +# Carregando dados +######################### + +# "pets.csv" é um arquivo hospedado na internet +# (mas também poderia tranquilamente ser um arquivo no seu computador) +require(RCurl) +pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/docs/pets.csv"))) +pets +head(pets, 2) # primeiras duas linhas +tail(pets, 1) # última linha + +# Para salvar um data frame ou matriz como um arquivo .csv: +write.csv(pets, "pets2.csv") # para criar um novo arquivo .csv +# Define o diretório de trabalho com setwd(), confirme em qual você está com getwd() + +# Experimente ?read.csv e ?write.csv para obter mais informações + + + +######################### +# Análise estatística +######################### + +# Regressão linear! +modeloLinear <- lm(preco ~ tempo, data = lista1) +modeloLinear # imprime na tela o resultado da regressão +# Call: +# lm(formula = preco ~ tempo, data = lista1) +# +# Coefficients: +# (Intercept) tempo +# 0.1453 0.4943 +summary(modeloLinear) # saída mais detalhada da regressão +# Call: +# lm(formula = preco ~ tempo, data = lista1) +# +# Residuals: +# Min 1Q Median 3Q Max +# -8.3134 -3.0131 -0.3606 2.8016 10.3992 +# +# Coefficients: +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.14527 1.50084 0.097 0.923 +# tempo 0.49435 0.06379 7.749 2.44e-09 *** +# --- +# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 +# +# Residual standard error: 4.657 on 38 degrees of freedom +# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 +# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 +coef(modeloLinear) # extrai os parâmetros estimados +# (Intercept) tempo +# 0.1452662 0.4943490 +summary(modeloLinear)$coefficients # um outro meio de extrair os resultados +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 +# tempo 0.4943490 0.06379348 7.74920901 2.440008e-09 +summary(modeloLinear)$coefficients[,4] # the p-values +# (Intercept) tempo +# 9.234021e-01 2.440008e-09 + +# MODELOS LINEARES GERAIS +# Regressão logística +set.seed(1) +lista1$sucesso = rbinom(length(lista1$tempo), 1, .5) # binário aleatório +modeloLg <- glm(sucesso ~ tempo, data = lista1, + family=binomial(link="logit")) +modeloLg # imprime na tela o resultado da regressão logística +# Call: glm(formula = sucesso ~ tempo, +# family = binomial(link = "logit"), data = lista1) +# +# Coefficients: +# (Intercept) tempo +# 0.17018 -0.01321 +# +# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual +# Null Deviance: 55.35 +# Residual Deviance: 55.12 AIC: 59.12 +summary(modeloLg) # saída mais detalhada da regressão +# Call: +# glm(formula = sucesso ~ tempo, +# family = binomial(link = "logit"), data = lista1) + +# Deviance Residuals: +# Min 1Q Median 3Q Max +# -1.245 -1.118 -1.035 1.202 1.327 +# +# Coefficients: +# Estimate Std. Error z value Pr(>|z|) +# (Intercept) 0.17018 0.64621 0.263 0.792 +# tempo -0.01321 0.02757 -0.479 0.632 +# +# (Dispersion parameter for binomial family taken to be 1) +# +# Null deviance: 55.352 on 39 degrees of freedom +# Residual deviance: 55.121 on 38 degrees of freedom +# AIC: 59.121 +# +# Number of Fisher Scoring iterations: 3 + + +######################### +# Gráficos +######################### + +# FUNÇÕES DE PLOTAGEM INTEGRADAS +# Gráficos de dispersão! +plot(lista1$tempo, lista1$preco, main = "dados falsos") +# Trace a linha de regressão em um gráfico existente! +abline(modeloLinear, col = "red") +# Obtenha uma variedade de diagnósticos legais +plot(modeloLinear) +# Histogramas! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Gráficos de barras! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# Mas estes não são nem os mais bonitos dos gráficos no R +# Experimente o pacote ggplot2 para gráficos diferentes e mais bonitos +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(estudantes, aes(x=casa)) +pp + geom_bar() +ll <- as.data.table(lista1) +pp <- ggplot(ll, aes(x=tempo,preco)) +pp + geom_point() +# ggplot2 tem uma excelente documentação (disponível em http://docs.ggplot2.org/current/) + + + +``` + +## Como faço para obter R? + +* Obtenha o R e uma interface gráfica para o R em [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) é uma outra interface gráfica diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown index 3dd4a8d5..1080baa4 100644 --- a/pt-br/rust-pt.html.markdown +++ b/pt-br/rust-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust filename: rust-pt.rs contributors: - ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"] diff --git a/pt-br/sql-pt.html.markdown b/pt-br/sql-pt.html.markdown new file mode 100644 index 00000000..0e4631a6 --- /dev/null +++ b/pt-br/sql-pt.html.markdown @@ -0,0 +1,119 @@ +--- +language: SQL +filename: learnsql-pt.sql +contributors: + - ["Bob DuCharme", "http://bobdc.com/"] +translators: + - ["jovinoguerrero", "https://github.com/jovinoguerrero"] +lang: pt-br +--- + +A linguagem de consulta estruturada (SQL em inglês) é uma linguagem padrão ISO para criar e trabalhar com bancos de dados armazenados num conjunto de tabelas. As implementações geralmente adicionam suas próprias extensões à linguagem; [Comparação entre diferentes implementações de SQL](http://troels.arvin.dk/db/rdbms/) é uma boa referência sobre as diferenças entre os diferentes produtos. + +As implementações normalmente fornecem uma linha de comando onde se pode digitar os comandos mostrados aqui de forma interativa, e também oferecem uma maneira de executar uma série desses comandos armazenados em um arquivo de script (mostrar que é feito com o prompt interativo é um bom exemplo de algo que não é padronizado - a maioria das implementações SQL suporta as palavras-chave QUIT, EXIT ou ambas). + +Vários desses comandos de exemplo assumem que o [banco de dados de funcionários de exemplo MySQL](https://dev.mysql.com/doc/employee/en/) disponível em [github](https://github.com/datacharmer/test_db) já foi carregado. Os arquivos do GitHub são scripts de comandos, semelhantes aos comandos abaixo, que criam e carregam tabelas de dados sobre os funcionários de uma empresa fictícia. A sintaxe para executar esses scripts dependerá da implementação SQL que você está usando. Um aplicativo executado a partir do prompt do sistema operacional geralmente é o normal. + + +```sql +-- Os comentários começam com dois hífens. Cada comando é encerrado com um +-- ponto e vírgula. + +-- SQL não diferencia maiúsculas de minúsculas em palavras-chave. Os +-- comandos de exemplo mostrados aqui seguem a convenção de serem escritos +-- em maiúsculas porque torna mais fácil distingui-los dos nomes dos bancos +-- de dados, tabelas e colunas. + +-- Em seguida, um banco de dados é criado e excluído. Os nomes do banco de +-- dados e da tabela são sensíveis a maiúsculas de minúsculas. +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Mostra numa lista todos os bancos de dados disponíveis. +SHOW DATABASES; + +-- Usa um determinado banco de dados existente. +USE employees; + +-- Seleciona todas as filas e colunas da tabela de departamentos no banco +-- de dados atual. A atividade padrão é o intérprete rolar os resultados +-- na tela. +SELECT * FROM departments; + +-- Recupera todas as filas da tabela de departamentos, mas apenas as colunas +-- dept_no e dept_name. +-- A separação de comandos em várias linhas é permitida. +SELECT dept_no, + dept_name FROM departments; + +-- Obtém todas as colunas de departments, mas é limitado a 5 filas. +SELECT * FROM departments LIMIT 5; + +-- Obtém os valores da coluna dept_name da tabela de departments quando +-- dept_name tem como valor a substring 'en'. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Recupera todas as colunas da tabela de departments onde a coluna +-- dept_name começa com um 'S' e tem exatamente 4 caracteres depois dele. +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Seleciona os valores dos títulos da tabela de titles, mas não mostra +-- duplicatas. +SELECT DISTINCT title FROM titles; + +-- Igual ao anterior, mas ordenado por valores de da coluna title (diferencia +-- maiúsculas de minúsculas). +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Mostra o número de filas da tabela departments. +SELECT COUNT(*) FROM departments; + +-- Mostra o número de filas da tabela departments que contém 'en' como +-- substring na coluna dept_name. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- Uma união (JOIN) de informações de várias tabelas: a tabela titles mostra +-- quem tem quais cargos laborais, de acordo com seu número de funcionários, +-- e desde que data até que data. Esta informação é obtida, mas em vez do +-- número do funcionário é usada como referência cruzada a tabela employee +-- para obter o nome e sobrenome de cada funcionário (e limita os resultados +-- a 10 filas). +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +-- São listadas todas as tabelas de todas os bancos de dados. As implementações +-- normalmente fornecem seus próprios comandos para fazer isso com o banco de +-- dados atualmente em uso. +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Cria uma tabela chamada tablename1, com as duas colunas mostradas, a partir +-- do banco de dados em uso. Há muitas outras opções dísponiveis para a forma +-- em que se especificam as colunas, por ex. seus tipos de dados. +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Insere uma fila de dados na tabela tablename1. É assumido que a tabela foi +-- definida para aceitar esses valores como adequados. +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- Em tablename1, se altera o valor de fname para 'John' em todas as filas que +-- contenham um valor em lname igual a 'Mutt'. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Se excluem as filas da tabela tablename1 em que o valor de lname começa +-- com 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Se excluem as filas da tabela tablename1, deixando a tabla vazia. +DELETE FROM tablename1; + +-- A tabela tablename1, é excluída completamente. +DROP TABLE tablename1; +``` + +# Leitura adicional + +* [Codecademy - SQL](https://www.codecademy.com/learn/learn-sql) A good introduction to SQL in a “learn by doing it” format. +* [Database System Concepts](https://www.db-book.com/) book’s Chapter 3 - Introduction to SQL has an in depth explanation of SQL concepts. diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown index ce3be407..e2130e0a 100644 --- a/pt-br/tmux-pt.html.markdown +++ b/pt-br/tmux-pt.html.markdown @@ -59,47 +59,49 @@ As seções tmux acopladas são controladas através de teclas de atalho. (prefi ---------------------------------------------------------------------- (C-b) = Ctrl + b # Abre a opção de receber comandos(atalhos). - (M-1) = Meta + 1 -or- Alt + 1 + (M-1) = Meta + 1 -ou- Alt + 1 ---------------------------------------------------------------------- - ? # Lista todos os comandos. - : # Acessa o prompt command do tmux - r # Força a reinicialização do cliente acoplado. - c # Cria uma nova janela. + ? # Lista todos os comandos. + : # Acessa o prompt command do tmux + r # Força a reinicialização do cliente acoplado. + c # Cria uma nova janela. - ! # Retira o painel atual da janela. - % # Divide o painel atual em dois. Esquerda e direita. - " # Divide o painel atual em dois. Para cima e para baixo. + ! # Retira o painel atual da janela. + % # Divide o painel atual em dois. Esquerda e direita. + " # Divide o painel atual em dois. Para cima e para baixo. - n # Muda para a próxima janela. - p # Muda para a janela anterior. - { # Troca o painel atual pelo anterior. - } # Troca o painel corrent pelo posterior. + n # Muda para a próxima janela. + p # Muda para a janela anterior. + { # Troca o painel atual pelo anterior. + } # Troca o painel corrent pelo posterior. + [ # Entra no modo cópia (Copy Mode) para copiar texto ou ver o histórico. - s # Seleciona uma nova seção para o cliente acoplado iterativamente. - w # Seleciona a janela atual iterativamente. - 0 to 9 # Seleciona a janela de 0 à 9. - d # Separa o cliente atual. - D # Seleciona um cliente a ser separado. + s # Seleciona uma nova seção para o cliente acoplado iterativamente. + w # Seleciona a janela atual iterativamente. + 0 to 9 # Seleciona a janela de 0 à 9. - & # Encerra a janela atual. - x # Encerra o painel atual. + d # Separa o cliente atual. + D # Seleciona um cliente a ser separado. - Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita. + & # Encerra a janela atual. + x # Encerra o painel atual. + + Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita. Left, Right - M-1 to M-5 # Organiza os paines: + M-1 to M-5 # Organiza os paines: # 1) Horizontalmente de maneira igual # 2) Verticalmente de maineira igual. # 3) Principal horizontalmente # 4) Principal verticamente. # 5) Mosaico - C-Up, C-Down # Altera o tamanho do painel atual em uma célula. + C-Up, C-Down # Altera o tamanho do painel atual em uma célula. C-Left, C-Right - M-Up, M-Down # Altera o tamanho do painel atual em cinco células. + M-Up, M-Down # Altera o tamanho do painel atual em cinco células. M-Left, M-Right ``` diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown index 2a7205cd..81292798 100644 --- a/pt-br/visualbasic-pt.html.markdown +++ b/pt-br/visualbasic-pt.html.markdown @@ -28,12 +28,12 @@ module Module1 Console.WriteLine ("2. Entrada Olá Mundo" ) Console.WriteLine ("3. Cálculando números inteiros " ) Console.WriteLine ("4. Calculando números decimais " ) - Console.WriteLine ("5 . Calculadora de Trabalho " ) + Console.WriteLine ("5. Calculadora de Trabalho " ) Console.WriteLine ("6. Usando Do While Loops " ) Console.WriteLine ("7. Usando Para While Loops " ) - Console.WriteLine ("8 . Declarações condicionais " ) + Console.WriteLine ("8. Declarações condicionais " ) Console.WriteLine ("9. Selecione uma bebida" ) - Console.WriteLine ("50 . About" ) + Console.WriteLine ("50. About" ) Console.WriteLine ("Por favor, escolha um número da lista acima " ) Seleção Dim As String = Console.ReadLine Select A seleção dos casos @@ -76,7 +76,7 @@ module Module1 End Sub ' Um - Eu estou usando números para ajudar com a navegação acima quando eu voltar - ' depois de construí-lo . + ' depois de construí-lo. " Nós usamos subs privadas para separar diferentes seções do programa. Private Sub HelloWorldOutput () @@ -94,12 +94,12 @@ module Module1 Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes" ' Variáveis 'Os dados inseridos por um usuário precisam ser armazenados. - ' As variáveis também começar com um Dim e terminar com um Como VariableType . + ' As variáveis também começar com um Dim e terminar com um Como VariableType. ' Neste tutorial, nós queremos saber qual é o seu nome, e faça o programa ' Responder ao que é dito. Nome de usuário Dim As String - " Nós usamos string como string é uma variável de texto baseado . + " Nós usamos string como string é uma variável de texto baseado. Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome. username = Console.ReadLine () ' armazena o nome do usuário. Console.WriteLine (" Olá " + username) ' A saída é "Olá < seu nome >". @@ -124,10 +124,10 @@ module Module1 'Quatro Sub CalculatingDecimalNumbers particulares () Console.Title = " Calculando com duplo | Saiba X em Y Minutes" - ' Claro que gostaria de ser capaz de somar decimais . + ' Claro que gostaria de ser capaz de somar decimais. " Por isso, poderia mudar o acima de Integer para Double. - " Digite um número inteiro , 1,2 , 2,4 , 50,1 , 104,9 ect + " Digite um número inteiro como 1, 2, 50, 104, etc Console.Write ("Primeiro número:") Dim a As Double = Console.ReadLine Console.Write ("Segundo número:") 'Enter segundo número inteiro. @@ -141,9 +141,9 @@ module Module1 ' Cinco Private Sub WorkingCalculator () Console.Title = " A Calculadora de Trabalho | Saiba X em Y Minutes" - " No entanto, se você gostaria que a calculadora para subtrair, dividir , múltiplos e + " No entanto, se você gostaria que a calculadora para subtrair, dividir, múltiplos e ' somar. - ' Copie e cole o código acima novamente . + ' Copie e cole o código acima novamente. Console.Write ("Primeiro número:") Dim a As Double = Console.ReadLine Console.Write ("Segundo número:") 'Enter segundo número inteiro. @@ -153,7 +153,7 @@ module Module1 Dim e As Integer = a - b Dim f As Integer = a / b - " Ao adicionar as linhas abaixo , somos capazes de calcular a subtração , + " Ao adicionar as linhas abaixo, somos capazes de calcular a subtração, ' multply bem como dividir os valores de a e b Console.Gravar ( a.ToString ( ) + " + " + b.ToString ( ) ) 'Queremos pad as respostas para a esquerda por três espaços. @@ -172,8 +172,8 @@ module Module1 Sub UsingDoWhileLoops particulares () ' Assim como o sub privado anterior ' Desta vez, perguntar se o usuário deseja continuar ( Sim ou Não ? ) - ' Estamos usando Do While Loop , como não temos certeza se o usuário quer usar o - 'programa mais de uma vez . + ' Estamos usando Do While Loop, como não temos certeza se o usuário quer usar o + 'programa mais de uma vez. Console.Title = " UsingDoWhileLoops | Saiba X em Y Minutes" Dim resposta As String ' Nós usamos a variável " String" como a resposta é um texto Do ' Começamos o programa com @@ -195,12 +195,12 @@ module Module1 Console.Write ( a.ToString () + "/" + b.ToString ()) Console.WriteLine (" =" + e.ToString.PadLeft (3) ) Console.ReadLine () - ' Faça a pergunta , se o usuário deseja continuar? Infelizmente, + ' Faça a pergunta, se o usuário deseja continuar? Infelizmente, "é sensível a maiúsculas. Console.Write ( "Deseja continuar? (Sim / não )") " O programa pega a variável e imprime e começa de novo. answer = Console.ReadLine - " O comando para a variável para trabalhar seria , neste caso, " sim " + " O comando para a variável para trabalhar seria, neste caso, " sim " Loop While resposta = "yes" End Sub @@ -233,7 +233,7 @@ module Module1 outro Console.WriteLine (" Olá " + nome do usuário) Console.WriteLine (" Você check-out www.learnxinyminutes.com " ) - Console.ReadLine () ' Fins e imprime a declaração acima . + Console.ReadLine () ' Fins e imprime a declaração acima. End If End Sub @@ -242,15 +242,15 @@ module Module1 Console.Title = "Se Declaração / Else | Saiba X em Y Minutes" 'Às vezes é importante ter em conta mais de duas alternativas. 'Às vezes, há um bom número de outros. - 'Quando este for o caso , mais do que uma if seria necessária . - 'Uma instrução if é ótimo para máquinas de venda automática . Quando o usuário digita um código. - ' A1 , A2, A3 , ect para selecionar um item. + 'Quando este for o caso, mais do que uma if seria necessária. + 'Uma instrução if é ótimo para máquinas de venda automática. Quando o usuário digita um código. + ' A1, A2, A3, etc para selecionar um item. 'Todas as opções podem ser combinadas em uma única if. Seleção Dim Valor String = Console.ReadLine ' para a seleção Console.WriteLine (" A1. Para Soda " ) Console.WriteLine (" A2. Para Fanta " ) - Console.WriteLine (" A3 . Para Guaraná" ) + Console.WriteLine (" A3. Para Guaraná" ) Console.WriteLine (" A4. Para Coca Diet" ) Console.ReadLine () Se a seleção = "A1" Então diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 21e9b4bb..b2fb2a7d 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -2,6 +2,7 @@ language: yaml contributors: - ["Leigh Brenecki", "https://github.com/adambrenecki"] + - [Suhas SG, 'https://github.com/jargnar'] translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] filename: learnyaml-pt.yaml @@ -14,6 +15,8 @@ legível por seres humanos. É um superconjunto de JSON, com a adição de identação e quebras de linhas sintaticamente significativas, como Python. Ao contrário de Python, entretanto, YAML não permite o caracter literal tab para identação. ```yaml +--- # início do documento + # Comentários em YAML são como este. ################### @@ -30,28 +33,32 @@ boleano: true valor_nulo: null chave com espaco: valor # Observe que strings não precisam de aspas. Porém, elas podem ter. -porem: "Uma string, entre aspas." -"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave." +porem: 'Uma string, entre aspas.' +'Chaves podem estar entre aspas tambem.': "É útil se você quiser colocar um ':' na sua chave." +aspas simples: 'possuem ''um'' padrão de escape' +aspas duplas: "possuem vários: \", \0, \t, \u263A, \x0d\x0a == \r\n, e mais." +# Caracteres UTF-8/16/32 precisam ser codificados +Superscript dois: \u00B2 # Seqüências de várias linhas podem ser escritas como um 'bloco literal' (utilizando |), # ou em um 'bloco compacto' (utilizando '>'). bloco_literal: | - Todo esse bloco de texto será o valor da chave 'bloco_literal', - preservando a quebra de com linhas. + Todo esse bloco de texto será o valor da chave 'bloco_literal', + preservando a quebra de com linhas. - O literal continua até de-dented, e a primeira identação é - removida. + O literal continua até 'des-indentar', e a primeira identação é + removida. - Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações - - estas linhas serão identadas com 4 espaços. + Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações - + estas linhas serão identadas com 4 espaços. estilo_compacto: > - Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta - vez, todas as novas linhas serão substituídas com espaço simples. + Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta + vez, todas as novas linhas serão substituídas com espaço simples. - Linhas em branco, como acima, são convertidas em um carater de nova linha. + Linhas em branco, como acima, são convertidas em um carater de nova linha. - Linhas 'mais-indentadas' mantém suas novas linhas também - - este texto irá aparecer em duas linhas. + Linhas 'mais-indentadas' mantém suas novas linhas também - + este texto irá aparecer em duas linhas. #################### # TIPOS DE COLEÇÃO # @@ -59,54 +66,85 @@ estilo_compacto: > # Texto aninhado é conseguido através de identação. um_mapa_aninhado: - chave: valor - outra_chave: Outro valor - outro_mapa_aninhado: - ola: ola + chave: valor + outra_chave: Outro valor + outro_mapa_aninhado: + ola: ola # Mapas não tem que ter chaves com string. 0.25: uma chave com valor flutuante -# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave. +# As chaves podem ser complexas, como sequência de várias linhas +# Utilizando ? seguido por espaço para indicar o começo de uma chave complexa. ? | - Esta é uma chave - que tem várias linhas + Esta é uma chave + que tem várias linhas : e este é o seu valor -# também permite tipos de coleção de chaves, mas muitas linguagens de programação -# vão reclamar. +# YAML também permite o mapeamento entre sequências com a sintaxe chave complexa +# Alguns analisadores de linguagem de programação podem reclamar +# Um exemplo +? - Manchester United + - Real Madrid +: [2001-01-01, 2002-02-02] # Sequências (equivalente a listas ou arrays) semelhante a isso: uma_sequencia: - - Item 1 - - Item 2 - - 0.5 # sequencias podem conter tipos diferentes. - - Item 4 - - chave: valor - outra_chave: outro_valor - - - - Esta é uma sequencia - - dentro de outra sequencia + - Item 1 + - Item 2 + - 0.5 # sequências podem conter tipos diferentes. + - Item 4 + - chave: valor + outra_chave: outro_valor + - + - Esta é uma sequência + - dentro de outra sequência + - - - Indicadores de sequência aninhadas + - podem ser recolhidas # Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e -# sequencias: +# sequências: mapa_json: {"chave": "valor"} json_seq: [3, 2, 1, "decolar"] +e aspas são opcionais: {chave: [3, 2, 1, decolar]} -########################## -# RECURSOS EXTRA DO YAML # -########################## +########################### +# RECURSOS EXTRAS DO YAML # +########################### # YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique # conteúdo em seu documento. Ambas estas chaves terão o mesmo valor: -conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves. -outra_ancora: * nome_ancora +conteudo_ancora: &nome_ancora Essa string irá aparecer como o valor de duas chaves. +outra_ancora: *nome_ancora + +# Âncoras podem ser usadas para dubplicar/herdar propriedades +base: &base + name: Todos possuem o mesmo nome + +# O regexp << é chamado Mesclar o Tipo Chave Independente-de-Idioma. É usado para +# indicar que todas as chaves de um ou mais mapas específicos devam ser inseridos +# no mapa atual. + +foo: + <<: *base + idade: 10 + +bar: + <<: *base + idade: 20 + +# foo e bar terão o mesmo nome: Todos possuem o mesmo nome # YAML também tem tags, que você pode usar para declarar explicitamente os tipos. -string_explicita: !! str 0,5 +string_explicita: !!str 0.5 # Alguns analisadores implementam tags específicas de linguagem, como este para Python de # Tipo de número complexo. -numero_complexo_em_python: !! python / complex 1 + 2j +numero_complexo_em_python: !!python/complex 1+2j + +# Podemos utilizar chaves YAML complexas com tags específicas de linguagem +? !!python/tuple [5, 7] +: Fifty Seven +# Seria {(5, 7): 'Fifty Seven'} em Python #################### # YAML TIPOS EXTRA # @@ -114,27 +152,34 @@ numero_complexo_em_python: !! python / complex 1 + 2j # Strings e números não são os únicos que escalares YAML pode entender. # Data e 'data e hora' literais no formato ISO também são analisados. -datetime: 2001-12-15T02: 59: 43.1Z -datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5 -Data: 2002/12/14 +datetime: 2001-12-15T02:59:43.1Z +datetime_com_espaços: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 # A tag !!binary indica que a string é na verdade um base64-encoded (codificado) # representação de um blob binário. 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= + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= # YAML também tem um tipo de conjunto, o que se parece com isso: -set: - ? item1 - ? item2 - ? item3 - -# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: -set2: - item1: nulo - item2: nulo - item3: nulo +conjunto: + ? item1 + ? item2 + ? item3 +ou: {item1, item2, item3} + +# Como Python, são apenas conjuntos de mapas com valores nulos; o acima é equivalente a: +conjunto2: + item1: null + item2: null + item3: null + +... # fim do documento ``` +### Mais Recursos + ++ [Site Oficial do YAML](https://yaml.org/) ++ [Validador YAML Online](http://www.yamllint.com/) diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown index bd0f0fc5..86710a13 100644 --- a/pt-pt/git-pt.html.markdown +++ b/pt-pt/git-pt.html.markdown @@ -411,5 +411,3 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) - -* [GitGuys](http://www.gitguys.com/) diff --git a/purescript.html.markdown b/purescript.html.markdown index 8cf1c1dd..1ceaecf9 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -59,9 +59,9 @@ compare 3 2 -- GT true && (9 >= 19 || 1 < 2) -- true -- Strings -"Hellow" :: String -- "Hellow" +"Hello" :: String -- "Hello" -- Multiline string without newlines, to run in PSCi use "paste" mode. -"Hellow\ +"Hello\ \orld" -- "Helloworld" -- Multiline string with newlines """Hello diff --git a/python.html.markdown b/python.html.markdown index 0bd16a80..d9eda60c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -9,14 +9,18 @@ contributors: - ["Rommel Martinez", "https://ebzzry.io"] - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - ["caminsha", "https://github.com/caminsha"] + - ["Stanislav Modrak", "https://stanislav.gq"] + - ["John Paul Wohlscheid", "https://gitpi.us"] filename: learnpython.py --- -Python was created by Guido van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. +Python was created by Guido van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its +syntactic clarity. It's basically executable pseudocode. -Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the old Python 2.7 +Note: This article applies to Python 3 specifically. Check out +[here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the +old Python 2.7 ```python @@ -81,16 +85,29 @@ False - 5 # => -5 # Comparison operators look at the numerical value of True and False 0 == False # => True -1 == True # => True +2 > True # => True 2 == True # => False -5 != False # => True -# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned -# Don't mix up with bool(ints) and bitwise and/or (&,|) +# None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False. +# All other values are True bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False +bool(set()) # => False bool(4) # => True bool(-6) # => True + +# Using boolean logical operators on ints casts them to booleans for evaluation, +# but their non-cast value is returned. Don't mix up with bool(ints) and bitwise +# and/or (&,|) +bool(0) # => False +bool(2) # => True 0 and 2 # => 0 +bool(-5) # => True +bool(2) # => True -5 or 0 # => -5 # Equality is == @@ -139,10 +156,10 @@ b == a # => True, a's and b's objects are equal # You can find the length of a string len("This is a string") # => 16 -# You can also format using f-strings or formatted string literals (in Python 3.6+) +# Since Python 3.6, you can use f-strings or formatted string literals. name = "Reiko" f"She said her name is {name}." # => "She said her name is Reiko" -# You can basically put any Python expression inside the braces and it will be output in the string. +# Any valid Python expression inside these braces is returned to the string. f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." # None is an object @@ -153,14 +170,6 @@ None # => None "etc" is None # => False None is None # => True -# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. -# All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - #################################################### ## 2. Variables and Collections #################################################### @@ -289,7 +298,7 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Note keys for dictionaries have to be immutable types. This is to ensure that # the key can be converted to a constant hash value for quick look-ups. # Immutable types include ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +invalid_dict = {[1,2,3]: "123"} # => Yield a TypeError: unhashable type: 'list' valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. # Look up values with [] @@ -343,7 +352,7 @@ del filled_dict["one"] # Removes the key "one" from filled dict # Sets store ... well sets empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +# Initialize a set with a bunch of values. some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} # Similar to keys of a dictionary, elements of a set have to be immutable. @@ -415,7 +424,7 @@ for animal in ["dog", "cat", "mouse"]: """ "range(number)" returns an iterable of numbers -from zero to the given number +from zero up to (but excluding) the given number prints: 0 1 @@ -449,8 +458,7 @@ for i in range(4, 8, 2): print(i) """ -To loop over a list, and retrieve both the index and the value of each item in the list -prints: +Loop over a list to retrieve both the index and the value of each list item: 0 dog 1 cat 2 mouse @@ -477,10 +485,11 @@ try: # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # Refrain from this, provide a recovery (next example). except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks + pass # Multiple exceptions can be processed jointly. +else: # Optional clause to the try/except block. Must follow + # all except blocks. print("All good!") # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances print("We can clean up resources here") @@ -495,6 +504,7 @@ contents = {"aa": 12, "bb": 21} with open("myfile1.txt", "w+") as file: file.write(str(contents)) # writes a string to a file +import json with open("myfile2.txt", "w+") as file: file.write(json.dumps(contents)) # writes an object to a file @@ -516,7 +526,8 @@ print(contents) filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. +print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object + # that implements our Iterable interface. # We can loop over it. for i in our_iterable: @@ -528,15 +539,16 @@ our_iterable[1] # Raises a TypeError # An iterable is an object that knows how to create an iterator. our_iterator = iter(our_iterable) -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object with "next()". +# Our iterator is an object that can remember the state as we traverse through +# it. We get the next object with "next()". next(our_iterator) # => "one" # It maintains state as we iterate. next(our_iterator) # => "two" next(our_iterator) # => "three" -# After the iterator has returned all of its data, it raises a StopIteration exception +# After the iterator has returned all of its data, it raises a +# StopIteration exception next(our_iterator) # Raises StopIteration # We can also loop over it, in fact, "for" does this implicitly! @@ -544,7 +556,7 @@ our_iterator = iter(our_iterable) for i in our_iterator: print(i) # Prints one, two, three -# You can grab all the elements of an iterable or iterator by calling list() on it. +# You can grab all the elements of an iterable or iterator by call of list(). list(our_iterable) # => Returns ["one", "two", "three"] list(our_iterator) # => Returns [] because state is saved @@ -594,9 +606,9 @@ all_the_args(1, 2, a=3, b=4) prints: # Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # equivalent: all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent: all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent: all_the_args(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): @@ -606,17 +618,19 @@ def swap(x, y): x = 1 y = 2 x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. +# (x, y) = swap(x,y) # Again the use of parenthesis is optional. -# Function Scope +# global scope x = 5 def set_x(num): - # Local var x not the same as global variable x + # local scope begins here + # local var x not the same as global var x x = num # => 43 print(x) # => 43 def set_global_x(num): + # global indicates that particular var lives in the global scope global x print(x) # => 5 x = num # global var x is now set to 6 @@ -624,6 +638,12 @@ def set_global_x(num): set_x(43) set_global_x(6) +""" +prints: + 43 + 5 + 6 +""" # Python has first class functions @@ -646,7 +666,7 @@ list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] # We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list +# List comprehension stores the output as a list (which itself may be nested). [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] @@ -706,8 +726,8 @@ class Human: # Note that the double leading and trailing underscores denote objects # or attributes that are used by Python but that live in user-controlled # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called special methods (or sometimes called dunder methods) - # You should not invent such names on your own. + # __repr__ etc. are called special methods (or sometimes called dunder + # methods). You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name @@ -761,7 +781,7 @@ if __name__ == '__main__': i.say("hi") # "Ian: hi" j = Human("Joel") j.say("hello") # "Joel: hello" - # i and j are instances of type Human, or in other words: they are Human objects + # i and j are instances of type Human; i.e., they are Human objects. # Call our class method i.say(i.get_species()) # "Ian: H. sapiens" @@ -798,8 +818,8 @@ if __name__ == '__main__': # "species", "name", and "age", as well as methods, like "sing" and "grunt" # from the Human class, but can also have its own unique properties. -# To take advantage of modularization by file you could place the classes above in their own files, -# say, human.py +# To take advantage of modularization by file you could place the classes above +# in their own files, say, human.py # To import functions from other files use the following format # from "filename-without-extension" import "function-or-class" @@ -923,8 +943,8 @@ class Batman(Superhero, Bat): # However we are dealing with multiple inheritance here, and super() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. - # The use of *args and **kwargs allows for a clean way to pass arguments, - # with each parent "peeling a layer of the onion". + # The use of *args and **kwargs allows for a clean way to pass + # arguments, with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) @@ -1023,12 +1043,9 @@ print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` -## Ready For More? - ### Free Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) * [The Official Docs](https://docs.python.org/3/) * [Hitchhiker's Guide to Python](https://docs.python-guide.org/en/latest/) * [Python Course](https://www.python-course.eu) diff --git a/r.html.markdown b/r.html.markdown index e90d5a97..a063cc2f 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -4,6 +4,7 @@ contributors: - ["e99n09", "http://github.com/e99n09"] - ["isomorphismes", "http://twitter.com/isomorphisms"] - ["kalinn", "http://github.com/kalinn"] + - ["mribeirodantas", "http://github.com/mribeirodantas"] filename: learnr.r --- @@ -11,7 +12,7 @@ R is a statistical computing language. It has lots of libraries for uploading an ```r -# Comments start with number symbols. +# Comments start with hash signs, also known as number symbols (#). # You can't make multi-line comments, # but you can stack multiple comments like so. @@ -29,13 +30,13 @@ R is a statistical computing language. It has lots of libraries for uploading an # R without understanding anything about programming. Do not worry # about understanding everything the code does. Just enjoy! -data() # browse pre-loaded data sets -data(rivers) # get this one: "Lengths of Major North American Rivers" -ls() # notice that "rivers" now appears in the workspace -head(rivers) # peek at the data set +data() # browse pre-loaded data sets +data(rivers) # get this one: "Lengths of Major North American Rivers" +ls() # notice that "rivers" now appears in the workspace +head(rivers) # peek at the data set # 735 320 325 392 524 450 -length(rivers) # how many rivers were measured? +length(rivers) # how many rivers were measured? # 141 summary(rivers) # what are some summary statistics? # Min. 1st Qu. Median Mean 3rd Qu. Max. @@ -91,14 +92,15 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # 82 | 2 # make a histogram: -hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters -hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later +hist(rivers, col = "#333333", border = "white", breaks = 25) +hist(log(rivers), col = "#333333", border = "white", breaks = 25) +# play around with these parameters, you'll do more plotting later # Here's another neat data set that comes pre-loaded. R has tons of these. data(discoveries) -plot(discoveries, col="#333333", lwd=3, xlab="Year", +plot(discoveries, col = "#333333", lwd = 3, xlab = "Year", main="Number of important discoveries per year") -plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", +plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year", main="Number of important discoveries per year") # Rather than leaving the default ordering (by year), @@ -109,7 +111,7 @@ sort(discoveries) # [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 -stem(discoveries, scale=2) +stem(discoveries, scale = 2) # # The decimal point is at the | # @@ -134,7 +136,7 @@ summary(discoveries) # 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times -round(runif(7, min=.5, max=6.5)) +round(runif(7, min = .5, max = 6.5)) # 1 4 6 1 4 6 4 # Your numbers will differ from mine unless we set the same random.seed(31337) @@ -157,69 +159,68 @@ rnorm(9) # INTEGERS # Long-storage integers are written with L -5L # 5 -class(5L) # "integer" +5L # 5 +class(5L) # "integer" # (Try ?class for more information on the class() function.) # In R, every single value, like 5L, is considered a vector of length 1 -length(5L) # 1 +length(5L) # 1 # You can have an integer vector with length > 1 too: -c(4L, 5L, 8L, 3L) # 4 5 8 3 -length(c(4L, 5L, 8L, 3L)) # 4 -class(c(4L, 5L, 8L, 3L)) # "integer" +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" # NUMERICS # A "numeric" is a double-precision floating-point number -5 # 5 -class(5) # "numeric" +5 # 5 +class(5) # "numeric" # Again, everything in R is a vector; # you can make a numeric vector with more than one element -c(3,3,3,2,2,1) # 3 3 3 2 2 1 +c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1 # You can use scientific notation too -5e4 # 50000 -6.02e23 # Avogadro's number -1.6e-35 # Planck length +5e4 # 50000 +6.02e23 # Avogadro's number +1.6e-35 # Planck length # You can also have infinitely large or small numbers -class(Inf) # "numeric" -class(-Inf) # "numeric" +class(Inf) # "numeric" +class(-Inf) # "numeric" # You might use "Inf", for example, in integrate(dnorm, 3, Inf); # this obviates Z-score tables. # BASIC ARITHMETIC # You can do arithmetic with numbers # Doing arithmetic on a mix of integers and numerics gives you another numeric -10L + 66L # 76 # integer plus integer gives integer -53.2 - 4 # 49.2 # numeric minus numeric gives numeric -2.0 * 2L # 4 # numeric times integer gives numeric -3L / 4 # 0.75 # integer over numeric gives numeric -3 %% 2 # 1 # the remainder of two numerics is another numeric +10L + 66L # 76 # integer plus integer gives integer +53.2 - 4 # 49.2 # numeric minus numeric gives numeric +2.0 * 2L # 4 # numeric times integer gives numeric +3L / 4 # 0.75 # integer over numeric gives numeric +3 %% 2 # 1 # the remainder of two numerics is another numeric # Illegal arithmetic yields you a "not-a-number": -0 / 0 # NaN -class(NaN) # "numeric" +0 / 0 # NaN +class(NaN) # "numeric" # You can do arithmetic on two vectors with length greater than 1, # so long as the larger vector's length is an integer multiple of the smaller -c(1,2,3) + c(1,2,3) # 2 4 6 +c(1, 2, 3) + c(1, 2, 3) # 2 4 6 # Since a single number is a vector of length one, scalars are applied # elementwise to vectors -(4 * c(1,2,3) - 2) / 2 # 1 3 5 +(4 * c(1, 2, 3) - 2) / 2 # 1 3 5 # Except for scalars, use caution when performing arithmetic on vectors with # different lengths. Although it can be done, -c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 -# Matching lengths is better practice and easier to read -c(1,2,3,1,2,3) * c(1,2,1,2,1,2) +c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6 +# Matching lengths is better practice and easier to read most times +c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6 # CHARACTERS # There's no difference between strings and characters in R -"Horatio" # "Horatio" -class("Horatio") # "character" -class('H') # "character" +"Horatio" # "Horatio" +class("Horatio") # "character" +class("H") # "character" # Those were both character vectors of length 1 # Here is a longer one: -c('alef', 'bet', 'gimmel', 'dalet', 'he') -# => -# "alef" "bet" "gimmel" "dalet" "he" +c("alef", "bet", "gimmel", "dalet", "he") +# => "alef" "bet" "gimmel" "dalet" "he" length(c("Call","me","Ishmael")) # 3 # You can do regex operations on character vectors: -substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." # R has several built-in character vectors: letters @@ -230,32 +231,33 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D # LOGICALS # In R, a "logical" is a boolean -class(TRUE) # "logical" -class(FALSE) # "logical" + +class(TRUE) # "logical" +class(FALSE) # "logical" # Their behavior is normal -TRUE == TRUE # TRUE -TRUE == FALSE # FALSE -FALSE != FALSE # FALSE -FALSE != TRUE # TRUE +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE # Missing data (NA) is logical, too -class(NA) # "logical" +class(NA) # "logical" # Use | and & for logic operations. # OR -TRUE | FALSE # TRUE +TRUE | FALSE # TRUE # AND -TRUE & FALSE # FALSE +TRUE & FALSE # FALSE # Applying | and & to vectors returns elementwise logic operations -c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE -c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE +c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE +c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE # You can test if x is TRUE -isTRUE(TRUE) # TRUE +isTRUE(TRUE) # TRUE # Here we get a logical vector with many elements: -c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE -c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE +c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE # FACTORS # The factor class is for categorical data -# Factors can be ordered (like childrens' grade levels) or unordered (like colors) +# Factors can be ordered (like grade levels) or unordered (like colors) factor(c("blue", "blue", "green", NA, "blue")) # blue blue green <NA> blue # Levels: blue green @@ -263,31 +265,27 @@ factor(c("blue", "blue", "green", NA, "blue")) # Note that missing data does not enter the levels levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green" # If a factor vector has length 1, its levels will have length 1, too -length(factor("green")) # 1 +length(factor("green")) # 1 length(levels(factor("green"))) # 1 # Factors are commonly seen in data frames, a data structure we will cover later -data(infert) # "Infertility after Spontaneous and Induced Abortion" +data(infert) # "Infertility after Spontaneous and Induced Abortion" levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" # NULL # "NULL" is a weird one; use it to "blank out" a vector -class(NULL) # NULL +class(NULL) # NULL parakeet = c("beak", "feathers", "wings", "eyes") -parakeet -# => -# [1] "beak" "feathers" "wings" "eyes" +parakeet # "beak" "feathers" "wings" "eyes" parakeet <- NULL -parakeet -# => -# NULL +parakeet # NULL # TYPE COERCION # Type-coercion is when you force a value to take on a different type -as.character(c(6, 8)) # "6" "8" -as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE # If you put elements of different types into a vector, weird coercions happen: -c(TRUE, 4) # 1 4 -c("dog", TRUE, 4) # "dog" "TRUE" "4" +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" as.numeric("Bilbo") # => # [1] NA @@ -309,14 +307,15 @@ as.numeric("Bilbo") # VARIABLES # Lots of way to assign stuff: -x = 5 # this is possible -y <- "1" # this is preferred -TRUE -> z # this works but is weird +x = 5 # this is possible +y <- "1" # this is preferred traditionally +TRUE -> z # this works but is weird +# Refer to the Internet for the behaviors and preferences about them. # LOOPS # We've got for loops for (i in 1:4) { - print(i) + print(i) } # We've got while loops a <- 10 @@ -341,11 +340,11 @@ if (4 > 3) { # FUNCTIONS # Defined like so: jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise return(x) } # Called like any other R function: -jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 @@ -357,39 +356,39 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 # Let's start from the very beginning, and with something you already know: vectors. vec <- c(8, 9, 10, 11) -vec # 8 9 10 11 +vec # 8 9 10 11 # We ask for specific elements by subsetting with square brackets # (Note that R starts counting from 1) -vec[1] # 8 -letters[18] # "r" -LETTERS[13] # "M" -month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 # We can also search for the indices of specific components, -which(vec %% 2 == 0) # 1 3 +which(vec %% 2 == 0) # 1 3 # grab just the first or last few entries in the vector, -head(vec, 1) # 8 -tail(vec, 2) # 10 11 +head(vec, 1) # 8 +tail(vec, 2) # 10 11 # or figure out if a certain value is in the vector -any(vec == 10) # TRUE +any(vec == 10) # TRUE # If an index "goes over" you'll get NA: -vec[6] # NA +vec[6] # NA # You can find the length of your vector with length() -length(vec) # 4 +length(vec) # 4 # You can perform operations on entire vectors or subsets of vectors -vec * 4 # 32 36 40 44 -vec[2:3] * 5 # 45 50 -any(vec[2:3] == 8) # FALSE +vec * 4 # 32 36 40 44 +vec[2:3] * 5 # 45 50 +any(vec[2:3] == 8) # FALSE # and R has many built-in functions to summarize vectors -mean(vec) # 9.5 -var(vec) # 1.666667 -sd(vec) # 1.290994 -max(vec) # 11 -min(vec) # 8 -sum(vec) # 38 +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 # Some more nice built-ins: -5:15 # 5 6 7 8 9 10 11 12 13 14 15 -seq(from=0, to=31337, by=1337) +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from = 0, to = 31337, by = 1337) # => # [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 # [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 @@ -397,7 +396,7 @@ seq(from=0, to=31337, by=1337) # TWO-DIMENSIONAL (ALL ONE CLASS) # You can make a matrix out of entries all of the same type like so: -mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6)) mat # => # [,1] [,2] @@ -405,13 +404,13 @@ mat # [2,] 2 5 # [3,] 3 6 # Unlike a vector, the class of a matrix is "matrix", no matter what's in it -class(mat) # => "matrix" +class(mat) # "matrix" "array" # Ask for the first row -mat[1,] # 1 4 +mat[1, ] # 1 4 # Perform operation on the first column -3 * mat[,1] # 3 6 9 +3 * mat[, 1] # 3 6 9 # Ask for a specific cell -mat[3,2] # 6 +mat[3, 2] # 6 # Transpose the whole matrix t(mat) @@ -437,14 +436,14 @@ mat2 # [2,] "2" "cat" # [3,] "3" "bird" # [4,] "4" "dog" -class(mat2) # matrix +class(mat2) # matrix # Again, note what happened! # Because matrices must contain entries all of the same class, # everything got converted to the character class -c(class(mat2[,1]), class(mat2[,2])) +c(class(mat2[, 1]), class(mat2[, 2])) # rbind() sticks vectors together row-wise to make a matrix -mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4)) mat3 # => # [,1] [,2] [,3] [,4] @@ -458,11 +457,11 @@ mat3 # This data structure is so useful for statistical programming, # a version of it was added to Python in the package "pandas". -students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), - c(3,2,2,1,0,-1), - c("H", "G", "G", "R", "S", "G")) +students <- data.frame(c("Cedric", "Fred", "George", "Cho", "Draco", "Ginny"), + c( 3, 2, 2, 1, 0, -1), + c( "H", "G", "G", "R", "S", "G")) names(students) <- c("name", "year", "house") # name the columns -class(students) # "data.frame" +class(students) # "data.frame" students # => # name year house @@ -472,21 +471,22 @@ students # 4 Cho 1 R # 5 Draco 0 S # 6 Ginny -1 G -class(students$year) # "numeric" -class(students[,3]) # "factor" +class(students$year) # "numeric" +class(students[,3]) # "factor" # find the dimensions -nrow(students) # 6 -ncol(students) # 3 -dim(students) # 6 3 -# The data.frame() function converts character vectors to factor vectors -# by default; turn this off by setting stringsAsFactors = FALSE when -# you create the data.frame +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# The data.frame() function used to convert character vectors to factor +# vectors by default; This has changed in R 4.0.0. If your R version is +# older, turn this off by setting stringsAsFactors = FALSE when you +# create the data.frame ?data.frame # There are many twisty ways to subset data frames, all subtly unalike -students$year # 3 2 2 1 0 -1 -students[,2] # 3 2 2 1 0 -1 -students[,"year"] # 3 2 2 1 0 -1 +students$year # 3 2 2 1 0 -1 +students[, 2] # 3 2 2 1 0 -1 +students[, "year"] # 3 2 2 1 0 -1 # An augmented version of the data.frame structure is the data.table # If you're working with huge or panel data, or need to merge a few data @@ -503,19 +503,19 @@ students # note the slightly different print-out # 4: Cho 1 R # 5: Draco 0 S # 6: Ginny -1 G -students[name=="Ginny"] # get rows with name == "Ginny" +students[name == "Ginny"] # get rows with name == "Ginny" # => # name year house # 1: Ginny -1 G -students[year==2] # get rows with year == 2 +students[year == 2] # get rows with year == 2 # => # name year house # 1: Fred 2 G # 2: George 2 G # data.table makes merging two data sets easy # let's make another data.table to merge with students -founders <- data.table(house=c("G","H","R","S"), - founder=c("Godric","Helga","Rowena","Salazar")) +founders <- data.table(house = c("G" , "H" , "R" , "S"), + founder = c("Godric", "Helga", "Rowena", "Salazar")) founders # => # house founder @@ -526,8 +526,8 @@ founders setkey(students, house) setkey(founders, house) students <- founders[students] # merge the two data sets by matching "house" -setnames(students, c("house","houseFounderName","studentName","year")) -students[,order(c("name","year","house","houseFounderName")), with=F] +setnames(students, c("house", "houseFounderName", "studentName", "year")) +students[, order(c("name", "year", "house", "houseFounderName")), with = F] # => # studentName year house houseFounderName # 1: Fred 2 G Godric @@ -538,7 +538,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F] # 6: Draco 0 S Salazar # data.table makes summary tables easy -students[,sum(year),by=house] +students[, sum(year), by = house] # => # house V1 # 1: G 3 @@ -571,7 +571,7 @@ students[studentName != "Draco"] # 5: R Cho 1 # Using data.frame: students <- as.data.frame(students) -students[students$house != "G",] +students[students$house != "G", ] # => # house houseFounderName studentName year # 4 H Helga Cedric 3 @@ -583,13 +583,13 @@ students[students$house != "G",] # Arrays creates n-dimensional tables # All elements must be of the same type # You can make a two-dimensional table (sort of like a matrix) -array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +array(c(c(1, 2, 4, 5), c(8, 9, 3, 6)), dim = c(2, 4)) # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 # [2,] 2 5 9 6 # You can use array to make three-dimensional matrices too -array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +array(c(c(c(2, 300, 4), c(8, 9, 0)), c(c(5, 60, 0), c(66, 7, 847))), dim = c(3, 2, 2)) # => # , , 1 # @@ -609,7 +609,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # Finally, R has lists (of vectors) list1 <- list(time = 1:40) -list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1$price = c(rnorm(40, .5*list1$time, 4)) # random list1 # You can get items in the list like so list1$time # one way @@ -682,7 +682,7 @@ write.csv(pets, "pets2.csv") # to make a new .csv file ######################### # Linear regression! -linearModel <- lm(price ~ time, data = list1) +linearModel <- lm(price ~ time, data = list1) linearModel # outputs result of regression # => # Call: @@ -719,7 +719,7 @@ summary(linearModel)$coefficients # another way to extract results # Estimate Std. Error t value Pr(>|t|) # (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 # time 0.4943490 0.06379348 7.74920901 2.440008e-09 -summary(linearModel)$coefficients[,4] # the p-values +summary(linearModel)$coefficients[, 4] # the p-values # => # (Intercept) time # 9.234021e-01 2.440008e-09 @@ -728,8 +728,7 @@ summary(linearModel)$coefficients[,4] # the p-values # Logistic regression set.seed(1) list1$success = rbinom(length(list1$time), 1, .5) # random binary -glModel <- glm(success ~ time, data = list1, - family=binomial(link="logit")) +glModel <- glm(success ~ time, data = list1, family=binomial(link="logit")) glModel # outputs result of logistic regression # => # Call: glm(formula = success ~ time, @@ -745,8 +744,10 @@ glModel # outputs result of logistic regression summary(glModel) # more verbose output from the regression # => # Call: -# glm(formula = success ~ time, -# family = binomial(link = "logit"), data = list1) +# glm( +# formula = success ~ time, +# family = binomial(link = "logit"), +# data = list1) # Deviance Residuals: # Min 1Q Median 3Q Max @@ -780,7 +781,7 @@ plot(linearModel) # Histograms! hist(rpois(n = 10000, lambda = 5), col = "thistle") # Barplots! -barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) +barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow")) # GGPLOT2 # But these are not even the prettiest of R's plots @@ -788,10 +789,10 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) install.packages("ggplot2") require(ggplot2) ?ggplot2 -pp <- ggplot(students, aes(x=house)) +pp <- ggplot(students, aes(x = house)) pp + geom_bar() ll <- as.data.table(list1) -pp <- ggplot(ll, aes(x=time,price)) +pp <- ggplot(ll, aes(x = time, price)) pp + geom_point() # ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) diff --git a/raku-pod.html.markdown b/raku-pod.html.markdown index 7e9b6fc3..b008beab 100644 --- a/raku-pod.html.markdown +++ b/raku-pod.html.markdown @@ -193,7 +193,7 @@ are C<print>, C<put> and C<say>. ### Comments Although Pod blocks are ignored by the Rakudo Raku compiler, everything -indentified as a Pod block will be read and interpreted by Pod renderers. In +identified as a Pod block will be read and interpreted by Pod renderers. In order to prevent Pod blocks from being rendered by any renderer, use the `=comment` directive. diff --git a/raku.html.markdown b/raku.html.markdown index a8059791..39bc0e51 100644 --- a/raku.html.markdown +++ b/raku.html.markdown @@ -122,7 +122,7 @@ say @array; # OUTPUT: «a 6 b» # context, and any duplicated keys are deduplicated. my %hash = 'a' => 1, 'b' => 2; -# Keys get auto-quoted when the fat comman (`=>`) is used. Trailing commas are +# Keys get auto-quoted when the fat comma (`=>`) is used. Trailing commas are # okay. %hash = a => 1, b => 2, ; @@ -688,7 +688,7 @@ say (0 or False); # OUTPUT: «False». my ($a, $b, $c, $d, $e) = 1, 0, False, True, 'pi'; say $a && $b && $c; # OUTPUT: «0», the first falsey value say $a && $b && $c; # OUTPUT: «False», the first falsey value -say $a && $d && $e; # OUTPUT: «pi», last operand since everthing before is truthy +say $a && $d && $e; # OUTPUT: «pi», last operand since everything before is truthy # `||` returns the first argument that evaluates to `True`. say $b || $a || $d; # OUTPUT: «1» @@ -1965,7 +1965,7 @@ say so 'abbbbc' ~~ / a b* c /; # OUTPUT: «True» say so 'aec' ~~ / a b* c /; # OUTPUT: «False», "b"(s) are optional, not replaceable. # `**` - (Unbound) Quantifier -# If you squint hard enough, you might understand why exponentation is used +# If you squint hard enough, you might understand why exponentiation is used # for quantity. say so 'abc' ~~ / a b**1 c /; # OUTPUT: «True», exactly one time say so 'abc' ~~ / a b**1..3 c /; # OUTPUT: «True», one to three times diff --git a/rdf.html.markdown b/rdf.html.markdown new file mode 100644 index 00000000..5b2105b8 --- /dev/null +++ b/rdf.html.markdown @@ -0,0 +1,160 @@ +--- +language: RDF +filename: learnrdf.ttl +contributors: +- ["Bob DuCharme", "http://bobdc.com/"] +--- + +RDF (Resource Description Framework) is a [W3C +standard](https://www.w3.org/TR/2014/REC-rdf11-concepts-20140225/) data +model. The W3C has standardized several RDF syntaxes; examples below use the +most popular one, [Turtle](https://www.w3.org/TR/turtle/). + +One nice advantage of Turtle files is that if you concatenate any two +syntactically valid Turtle files, you will have another syntactically valid +Turtle file. This is one of many things about RDF that ease data integration. + +The W3C standard query language for RDF datasets is +[SPARQL](https://www.w3.org/TR/sparql11-query/). + +RDF expresses all facts as three-part {subject, predicate, object} statements +known as triples. Because the same entity can be the subject of some triples +and the object of others, a set of triples can represent a graph data +structure. A large-scale storage system for triples is called a triplestore, +and falls into the graph database category of NoSQL databases. + +RDF subjects and predicates must be URIs (Uniform Resource Identifiers), which +usually look like URLs but function as identifiers, not locators. The use of +URIs provides context for resource identifiers to make them unambiguous—for +example, to tell a book title from a job title. + +``` +# The hash symbol is the comment delimiter. + +# Turtle triple statements end with periods like natural language sentences. + +# These two triples tell us that the mythical Example Company's +# employee 134 has a hire date of 2022-11-12 and a family name of Smith: + +<http://example.com/emp134> <http://example.com/hireDate> "2022-11-12" . +<http://example.com/emp134> <http://example.com/familyName> "Smith" . + +# Declaring prefixes to stand in for namespaces reduces verbosity. These +# declarations typically go at the beginning of the file, but the only +# requirement is that they come before the first use of the prefix they declare. + +@prefix ex: <http://example.com/> . +ex:emp134 ex:hireDate "2022-11-12" . +ex:emp134 ex:familyName "Smith" . + +# A semicolon means that the next triple uses the same subject as the last +# one. This is handy for listing data about a single resource. The following +# example means the same thing as the previous one. + +@prefix ex: <http://example.com/> . +ex:emp134 ex:hireDate "2022-11-12" ; + ex:familyName "Smith" . + +# A comma means that the next triple has the same subject and predicate as +# the previous one. + +ex:emp134 ex:nickname "Smithy", "Skipper", "Big J". + +# Three single or double quote marks at the beginning and end of a value let +# you define a multi-line string value. + +ex:emp134 ex:description """ +Skipper joined the company in November. + +He always has a joke for everyone.""" . + +# Using URIs from existing standard vocabulary namespaces eases both data +# integration and interoperability with the large amount of RDF that already +# exists. Mixing and matching of standard and local custom namespaces is +# common. + +@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . +ex:emp134 ex:hireDate "2022-11-12" ; + vcard:family-name "Smith" . + +# Related RDF standards provide vocabularies that are popular for basic +# facts. The rdfs:label predicate from the RDF Schema standard is a common +# way to indicate a human-readable name. + +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +ex:hireDate rdfs:label "hire date" . + +# String object values can include language codes, making +# multi-lingual representation of entities easier for applications +# reading the data (for example, when generating a user interface). + +ex:hireDate rdfs:label "hire date"@en, "date d'embauche"@fr . + +# Representing a triple's object with a URI (or prefixed name) is not required +# but lets you connect up triples into a graph. + +ex:emp134 vcard:family-name "Smith" . +ex:emp113 vcard:family-name "Jones" ; + ex:reportsTo ex:emp134 . + +# Objects can be datatypes from the XML Schema part 2 standard or your own +# custom datatypes. + +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . +ex:emp134 vcard:family-name "Smith"^^xsd:string ; # default data type + ex:hireDate "2022-11-12"^^xsd:date ; + ex:rating "3.5"^^ex:someCustomType . + +# The use of schemas with RDF is optional. Schemas may describe all or a +# subset of a dataset. They use a vocabulary described by the W3C RDF Schema +# (RDFS) standard, usually with a prefix of rdfs. + +# These schemas are descriptive, to ease the accommodation of new +# datasets, not proscriptive rules about how new data should be +# created. The following declares a class. (Note that RDFS is itself +# expressed in triples.) + +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +ex:Person rdf:type rdfs:Class . + +# The following triple means the same as the preceding one but +# uses a Turtle shortcut for terseness and more readability. + +ex:Person a rdfs:Class . + +# That last triple declares that ex:Person is an instance of a class, and the +# following declares that employee 113 is an instance of the class Employee. + +ex:emp113 a ex:Employee . + +# The first triple below is actually unnecessary because a typical +# RDFS processor will infer from the second one that ex:Employee is a +# class. (Only a subset of RDF parsers perform RDFS inferencing.) + +ex:Employee a rdfs:Class . +ex:Employee rdfs:subClassOf ex:Person . + +# An RDF parser that reads the last four triples shown and understands +# RDFS will infer that ex:emp113 is an instance of ex:Person, because +# it's an instance of ex:Employee, a subclass of ex:Person. + +# RDFS lets you declare properties and associate them with classes. +# Properties are first class resources and don't "belong" to classes +# in the object-oriented sense. rdfs:domain means "the following object +# class uses the property named by this triple's subject". rdfs:range +# means "the property named by this triple's subject will have a value of +# the following class or type". + +ex:birthday rdf:type rdf:Property ; + rdfs:domain ex:Person ; + rdfs:range xsd:date . + +``` + +## Further Reading + +* [RDF Primer — Turtle version](https://www.w3.org/2007/02/turtle/primer/) from the W3C +* [What is RDF?](https://www.bobdc.com/blog/whatisrdf/) on bobdc.com +* [What is RDFS?](https://www.bobdc.com/blog/whatisrdfs/) on bobdc.com +* [Introduction to RDF and SPARQL](https://data.europa.eu/sites/default/files/d2.1.2_training_module_1.3_introduction_to_rdf_sparql_en_edp.pdf) at data.europa.eu + diff --git a/ro-ro/clojure-ro.html.markdown b/ro-ro/clojure-ro.html.markdown index 32ba9620..77052379 100644 --- a/ro-ro/clojure-ro.html.markdown +++ b/ro-ro/clojure-ro.html.markdown @@ -380,7 +380,7 @@ Clojuredocs.org contine documentatie cu exemple pentru majoritatea functiilor de [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure este o metoda excelenta pentru a exersa Clojure/FP (Programarea Functionala): -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org are un numar de article pentru incepatori: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/rst.html.markdown b/rst.html.markdown index 56d54501..c177fdb4 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -33,7 +33,7 @@ $ pip install docutils A simple example of the file syntax: ``` -.. Lines starting with two dots are special commands. But if no command can be found, the line is considered as a comment +.. Lines starting with two dots are special commands. But if no command can be found, the line is considered as a comment. ========================================================= Main titles are written using equals signs over and under @@ -80,12 +80,12 @@ France Paris Japan Tokyo =========== ======== -More complex tables can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) +More complex tables can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this. :) There are multiple ways to make links: - By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text). -- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link) +- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link). - By making a more Markdown-like link: `Github <https://github.com/>`_ . .. _Github: https://github.com/ diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 3acfafa3..fad1b434 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-ru.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index cc68d620..eb5de011 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: c +language: C filename: learnc-ru.c contributors: - ["Adam Bard", "http://adambard.com/"] diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 19233d23..66986fa0 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -421,7 +421,7 @@ Clojuredocs.org — сайт документации языка с пример [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure — отличный способ закрепить навыки программирования на clojure, решая задачи вместе с коллегами со всего мира: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org (да, именно) неплохой перечень статей для начинающих: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 37592258..8d2eac90 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -29,7 +29,7 @@ Go - это язык общего назначения, целью которо комментарий */ // Ключевое слово package присутствует в начале каждого файла. -// Main это специальное имя, обозначающее исполняемый файл, нежели библиотеку. +// main это специальное имя, обозначающее исполняемый файл, нежели библиотеку. package main // Import предназначен для указания зависимостей этого файла. diff --git a/ru-ru/qt-ru.html.markdown b/ru-ru/qt-ru.html.markdown index d0a70c9d..5fbcc3b4 100644 --- a/ru-ru/qt-ru.html.markdown +++ b/ru-ru/qt-ru.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: Qt Framework -language: c++ +language: C++ filename: learnqt-ru.cpp contributors: - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown index d46d301c..a568ac37 100644 --- a/ru-ru/rust-ru.html.markdown +++ b/ru-ru/rust-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust filename: learnrust-ru.rs contributors: diff --git a/rust.html.markdown b/rust.html.markdown index 9e07e005..c677ed96 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -223,7 +223,7 @@ fn main() { type FunctionPointer = fn(u32) -> u32; let fib : FunctionPointer = fibonacci; - println!("Fib: {}", fib(4)); + println!("Fib: {}", fib(4)); // 5 ///////////////////////// // 3. Pattern matching // diff --git a/scala.html.markdown b/scala.html.markdown index d2d45dc9..bb20f624 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -302,7 +302,7 @@ do { // 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, which is analagous to a `void` return type in Java +// Here it's Unit, which is analogous to a `void` return type in Java def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) diff --git a/set-theory.html.markdown b/set-theory.html.markdown index d55ab7d5..f89345c0 100644 --- a/set-theory.html.markdown +++ b/set-theory.html.markdown @@ -17,7 +17,7 @@ Set theory is a branch of mathematics that studies sets, their operations, and t * the cross operator, `×`, means "the Cartesian product of". ### Qualifiers -* the colon qualifier, `:`, means "such that"; +* the colon, `:`, or the vertical bar `|` qualifiers are interchangeable and mean "such that"; * the membership qualifier, `∈`, means "belongs to"; * the subset qualifier, `⊆`, means "is a subset of"; * the proper subset qualifier, `⊂`, means "is a subset of but is not equal to". diff --git a/sing.html.markdown b/sing.html.markdown index 2e439800..50b52390 100644 --- a/sing.html.markdown +++ b/sing.html.markdown @@ -154,7 +154,7 @@ fn learnTypes() void sys.validate(dyna_array.size() == 1); // a map that associates a number to a string. - // "map(x)..." reads "map with key of type x and vaue of type..." + // "map(x)..." reads "map with key of type x and value of type..." var a_map map(string)i32; a_map.insert("one", 1); diff --git a/sk-sk/git-sk.html.markdown b/sk-sk/git-sk.html.markdown index 21741406..ddcd9658 100644 --- a/sk-sk/git-sk.html.markdown +++ b/sk-sk/git-sk.html.markdown @@ -514,8 +514,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) - * [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index aaa592dc..d4016ecf 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -60,7 +60,7 @@ doSomethingWith: argumentObject Everything here except the `^` involves sending more messages. Event the `ifTrue:` that you might think is a language control structure is just Smalltalk code. -We start by sending `size` to `self`. `self` is the object currently running the code - so in this case it is the myObject we started with. `size` is a very common message that we might anticipate tells us something about how big an object is; you could look it up with the Smalltalk tools very simply. The result we get is then sent the message `>` with the plain old integer 4 (which is an object too; no strange primitive types to pollute the system here) and nobody should be surprised the `>` is a comparison that answers true or false. That boolean (which is actually a Boolean object in Smalltalk) is sent the message `ifTrue:` with the block of code between the `[]` as its argument; obvioulsy a true boolean might be expected to run that block of code and a false to ignore it. +We start by sending `size` to `self`. `self` is the object currently running the code - so in this case it is the myObject we started with. `size` is a very common message that we might anticipate tells us something about how big an object is; you could look it up with the Smalltalk tools very simply. The result we get is then sent the message `>` with the plain old integer 4 (which is an object too; no strange primitive types to pollute the system here) and nobody should be surprised the `>` is a comparison that answers true or false. That boolean (which is actually a Boolean object in Smalltalk) is sent the message `ifTrue:` with the block of code between the `[]` as its argument; obviously a true boolean might be expected to run that block of code and a false to ignore it. If the block is run then we do some more message sending to the argument object and noting the `^` we return the answer back to our starting point and it gets assigned to `result`. If the block is ignored we seem to run out of code and so `self` is returned and assigned to `result`. diff --git a/solidity.html.markdown b/solidity.html.markdown index 5f8ef407..d40536b4 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -214,7 +214,7 @@ assert(c >= a); // assert tests for internal invariants; require is used for use // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol -// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truely random number using something like Chainlink VRF. +// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truly random number using something like Chainlink VRF. // https://docs.chain.link/docs/get-a-random-number // Type casting @@ -278,7 +278,7 @@ f(22); // call // Delete can be called on most types // (does NOT destroy value, but sets value to 0, the initial value) -uint x = 5; +delete x; // Destructuring/Tuples @@ -388,7 +388,7 @@ block.gasLimit(); storage['abc'] = 'def'; // maps 256 bit words to 256 bit words -// 4. FUNCTIONS AND MORE +// 5. FUNCTIONS AND MORE // A. Functions // Simple function function increment(uint x) returns (uint) { @@ -396,13 +396,13 @@ function increment(uint x) returns (uint) { return x; } -// Functions can return many arguments, and by specifying returned arguments -// name don't need to explicitly return +// Functions can return many arguments, +// and by specifying returned arguments name explicit return is not needed function increment(uint x, uint y) returns (uint x, uint y) { x += 1; y += 1; } -// Call previous functon +// Call previous function uint (a,b) = increment(1,1); // 'view' (alias for 'constant') @@ -435,7 +435,7 @@ function increment(uint x) view returns (uint x) { // Functions hoisted - and can assign a function to a variable function a() { var z = b; - b(); + z(); } function b() { @@ -494,9 +494,9 @@ Coin.LogSent().watch({}, '', function(error, result) { // '_' (underscore) often included as last line in body, and indicates // function being called should be placed there modifier onlyAfter(uint _time) { require (now >= _time); _; } -modifier onlyOwner { require(msg.sender == owner) _; } +modifier onlyOwner { require(msg.sender == owner); _; } // commonly used with state machines -modifier onlyIfStateA (State currState) { require(currState == State.A) _; } +modifier onlyIfStateA (State currState) { require(currState == State.A); _; } // Append right after function declaration function changeOwner(newOwner) @@ -646,7 +646,7 @@ reveal(100, "mySecret"); // All data to start of time is stored in blockchain, so // anyone can observe all previous data and changes -// E. Oracles and External Data +// D. Oracles and External Data // Oracles are ways to interact with your smart contracts outside the blockchain. // They are used to get data from the real world, send post requests, to the real world // or vise versa. @@ -654,7 +654,7 @@ reveal(100, "mySecret"); // Time-based implementations of contracts are also done through oracles, as // contracts need to be directly called and can not "subscribe" to a time. // Due to smart contracts being decentralized, you also want to get your data -// in a decentralized manner, other your run into the centralized risk that +// in a decentralized manner, otherwise you run into the centralized risk that // smart contract design matter prevents. // To easiest way get and use pre-boxed decentralized data is with Chainlink Data Feeds @@ -671,12 +671,12 @@ reveal(100, "mySecret"); // Setting up oracle networks yourself -// D. Cron Job +// E. 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 +// F. 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) @@ -714,7 +714,7 @@ contract SomeOracle { // Now, your client contract can addSubscriber by importing SomeOracleCallback // and registering with Some Oracle -// F. State machines +// G. State machines // see example below for State enum and inState modifier ``` diff --git a/sql.html.markdown b/sql.html.markdown index 685e522d..834cf00b 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -95,7 +95,7 @@ UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; -- Delete rows from the tablename1 table -- where the lname value begins with 'M'. -DELETE FROM tablename1 WHERE lname like 'M%'; +DELETE FROM tablename1 WHERE lname LIKE 'M%'; -- Delete all rows from the tablename1 table, leaving the empty table. DELETE FROM tablename1; diff --git a/tcsh.html.markdown b/tcsh.html.markdown index e38b7a27..05954442 100644 --- a/tcsh.html.markdown +++ b/tcsh.html.markdown @@ -713,7 +713,7 @@ end #### About [T]CSH: # * CSH is notorious about its bugs; # * It was also famous about its advanced interactive mode. -# * TCSH is famous that have the most advanced completition subsystem. +# * TCSH is famous that have the most advanced completion subsystem. # * TCSH is famous that have the most advanced aliases subsystem; aliases # can take parameters and often used as functions! # * TCSH is well known that preferred by people (me too) because of better diff --git a/textile.html.markdown b/textile.html.markdown index 2b81674a..293e647d 100644 --- a/textile.html.markdown +++ b/textile.html.markdown @@ -165,11 +165,11 @@ but again, they use different HTML markup and thus the distinction. ###. Superscripts and Subscripts use carats and tildes: -Superscripts are 2 ^nd^ to none, but subscripts are CO ~2~ L too. +Superscripts are 2 ^and^ to none, but subscripts are CO ~2~ L too. Note the spaces around the superscripts and subscripts. To avoid the spaces, add square brackets around them: -2[^nd^] and CO[~2~]L +2[^and^] and CO[~2~]L ###. Insertions and deletions are indicated using -/+ symbols: This is -deleted- text and this is +inserted+ text. @@ -375,7 +375,7 @@ table(tableclass). |a|classy|table| |a|classy|table| -###. Spanning rows and colums: +###. Spanning rows and columns: A backslash \ is used for a column span: |\2. spans two cols | diff --git a/tmux.html.markdown b/tmux.html.markdown index 1c2c2da3..095e24fb 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -183,7 +183,7 @@ bind a send-prefix ### Theme ########################################################################### -# Statusbar Color Palatte +# Statusbar Color Palette set-option -g status-justify left set-option -g status-bg black set-option -g status-fg white diff --git a/tr-tr/bf-tr.html.markdown b/tr-tr/bf-tr.html.markdown index e7015cd0..ef46f362 100644 --- a/tr-tr/bf-tr.html.markdown +++ b/tr-tr/bf-tr.html.markdown @@ -1,6 +1,6 @@ --- language: bf -filename: brainfuck-tr +filename: brainfuck-tr.bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io"] translators: diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index 9d65cf9c..c944f245 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ lang: tr-tr filename: learncpp-tr.cpp contributors: diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 4ef12527..05531d64 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -1,7 +1,7 @@ --- -name: c +name: C category: language -language: c +language: C filename: learnc-tr.c contributors: - ["Adam Bard", "http://adambard.com/"] diff --git a/tr-tr/clojure-tr.html.markdown b/tr-tr/clojure-tr.html.markdown index 5ebe5ce6..d21947ee 100644 --- a/tr-tr/clojure-tr.html.markdown +++ b/tr-tr/clojure-tr.html.markdown @@ -482,7 +482,7 @@ Clojuredocs.org, örneklerle bezenmiş Clojure dökümantasyonu: [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure, interaktif bir şekilde FP ve Clojure yeteneklerinizi geliştirmenize olanak veriyor: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org, Başlangıç için bir içeriklere sahip: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 91c7c269..9834be20 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: c# +language: C# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown index 87c1820c..c6979468 100644 --- a/tr-tr/git-tr.html.markdown +++ b/tr-tr/git-tr.html.markdown @@ -587,8 +587,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Kopya Kağıdı](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) - * [Git - Basit bir kılavuz](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) diff --git a/typescript.html.markdown b/typescript.html.markdown index 74cd15c6..64f5ca5b 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -2,6 +2,7 @@ language: TypeScript contributors: - ["Philippe Vlérick", "https://github.com/pvlerick"] + - ["Kiwimoe", "https://github.com/kiwimoe"] filename: learntypescript.ts --- @@ -291,7 +292,6 @@ foo.baz = 'hello world' ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) - * [TypeScript language specifications] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) - * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [TypeScript language specifications] (https://github.com/microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md) + * [Learn TypeScript] (https://learntypescript.dev/) * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) - * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) diff --git a/uk-ua/c-ua.html.markdown b/uk-ua/c-ua.html.markdown index c4dac75f..56a2b2ad 100644 --- a/uk-ua/c-ua.html.markdown +++ b/uk-ua/c-ua.html.markdown @@ -1,5 +1,5 @@ --- -language: c +language: C filename: learnc-ua.c contributors: - ["Adam Bard", "http://adambard.com/"] diff --git a/uk-ua/rust-ua.html.markdown b/uk-ua/rust-ua.html.markdown index 422de371..4aad0cbb 100644 --- a/uk-ua/rust-ua.html.markdown +++ b/uk-ua/rust-ua.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/vala.html.markdown b/vala.html.markdown index 06d6dedc..739e0fda 100755 --- a/vala.html.markdown +++ b/vala.html.markdown @@ -486,7 +486,7 @@ int more = 57; int* more_pointer = &more; // & = address-of int indirection_demo = more_pointer*; // indirection -// Profiles: affect which Vala features are avaliable and which libraries the +// Profiles: affect which Vala features are available and which libraries the // C-code will use. // - gobject (default) // posix diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown index 1bcc94a0..f5454ebf 100644 --- a/vi-vn/git-vi.html.markdown +++ b/vi-vn/git-vi.html.markdown @@ -396,8 +396,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/) - * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) diff --git a/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown index 257216ff..f709b838 100644 --- a/vi-vn/json-vi.html.markdown +++ b/vi-vn/json-vi.html.markdown @@ -37,7 +37,7 @@ kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD "các khóa": "phải luôn được đặt trong dấu ngoặc kép", "số": 0, - "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\"." + "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\".", "có đúng không?": true, "không có gì": null, diff --git a/vim.html.markdown b/vim.html.markdown index 00a44807..fb2fc81f 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -3,6 +3,7 @@ category: tool tool: vim contributors: - ["RadhikaG", "https://github.com/RadhikaG"] + - ["kaymmm", "https://github.com/kaymmm"] filename: LearnVim.txt --- @@ -19,70 +20,71 @@ specific points in the file, and for fast editing. ## Basics of navigating Vim ``` - vim <filename> # Open <filename> in vim - :help <topic> # Open up built-in help docs about <topic> if any exists - :q # Quit vim - :w # Save current file - :wq # Save file and quit vim - ZZ # Save file and quit vim - :q! # Quit vim without saving file - # ! *forces* :q to execute, hence quiting vim without saving - ZQ # Quit vim without saving file - :x # Save file and quit vim, shorter version of :wq - - u # Undo - CTRL+R # Redo - - h # Move left one character - j # Move down one line - k # Move up one line - l # Move right one character - - Ctrl+B # Move back one full screen - Ctrl+F # Move forward one full screen - Ctrl+D # Move forward 1/2 a screen - Ctrl+U # Move back 1/2 a screen + vim <filename> # Open <filename> in vim + :help <topic> # Open up built-in help docs about <topic> if any exists + :q # Quit vim + :w # Save current file + :wq # Save file and quit vim + ZZ # Save file and quit vim + :q! # Quit vim without saving file + # ! *forces* :q to execute, hence quitting vim without saving + ZQ # Quit vim without saving file + :x # Save file(only when the file is modified) and quit vim + + u # Undo + CTRL+R # Redo + + h # Move left one character + j # Move down one line + k # Move up one line + l # Move right one character + + Ctrl+B # Move back one full screen + Ctrl+F # Move forward one full screen + Ctrl+D # Move forward 1/2 a screen + Ctrl+U # Move back 1/2 a screen # Moving within the line - 0 # Move to beginning of line - $ # Move to end of line - ^ # Move to first non-blank character in line + 0 # Move to beginning of line + $ # Move to end of line + ^ # Move to first non-blank character in line # Searching in the text - /word # Highlights all occurrences of word after cursor - ?word # Highlights all occurrences of word before cursor - n # Moves cursor to next occurrence of word after search - N # Moves cursor to previous occerence of word + /word # Highlights all occurrences of word after cursor + ?word # Highlights all occurrences of word before cursor + n # Moves cursor to next occurrence of word after search + N # Moves cursor to previous occurrence of word - :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file - :s/foo/bar/g # Change 'foo' to 'bar' on the current line - :%s/\n/\r/g # Replace new line characters with new line characters + :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file + :s/foo/bar/g # Change 'foo' to 'bar' on the current line + :%s/\n/\r/g # Replace new line characters with new line characters + :'<,'>s/foo/bar/g # Change 'foo' to 'bar on every line in the current visual selection # Jumping to characters - f<character> # Jump forward and land on <character> - t<character> # Jump forward and land right before <character> + f<character> # Jump forward and land on <character> + t<character> # Jump forward and land right before <character> # For example, - f< # Jump forward and land on < - t< # Jump forward and land right before < + f< # Jump forward and land on < + t< # Jump forward and land right before < # Moving by word - w # Move forward by one word - b # Move back by one word - e # Move to end of current word + w # Move forward by one word + b # Move back by one word + e # Move to end of current word # Other characters for moving around - gg # Go to the top of the file - G # Go to the bottom of the file - :NUM # Go to line number NUM (NUM is any number) - H # Move to the top of the screen - M # Move to the middle of the screen - L # Move to the bottom of the screen + gg # Go to the top of the file + G # Go to the bottom of the file + :NUM # Go to line number NUM (NUM is any number) + H # Move to the top of the screen + M # Move to the middle of the screen + L # Move to the bottom of the screen ``` ## Help docs: @@ -104,28 +106,28 @@ Vim is based on the concept on **modes**. - Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` - i # Puts vim into insert mode, before the cursor position - a # Puts vim into insert mode, after the cursor position - v # Puts vim into visual mode - : # Puts vim into ex mode - <esc> # 'Escapes' from whichever mode you're in, into Command mode + i # Puts vim into insert mode, before the cursor position + a # Puts vim into insert mode, after the cursor position + v # Puts vim into visual mode + : # Puts vim into ex mode + <esc> # 'Escapes' from whichever mode you're in, into Command mode # Copying and pasting text - # Operations use the vim register by default - # Think of it as vim's private clipboard + # Operations use the vim register by default + # Think of it as vim's private clipboard - # Yank ~ copy text into vim register - y # Yank whatever is selected - yy # Yank the current line + # Yank ~ copy text into vim register + y # Yank whatever is selected + yy # Yank the current line - # Delete ~ yank text and delete from file - d # Delete whatever is selected - dd # Delete the current line + # Delete ~ yank text and delete from file + d # Delete whatever is selected + dd # Delete the current line - p # Paste text in vim register after the current cursor position - P # Paste text in vim register before the current cursor position + p # Paste text in vim register after the current cursor position + P # Paste text in vim register before the current cursor position - x # Delete character under current cursor position + x # Delete character under current cursor position ``` ## The 'Grammar' of vim @@ -142,64 +144,75 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ``` # 'Verbs' - d # Delete - c # Change - y # Yank (copy) - v # Visually select + d # Delete + c # Change + y # Yank (copy) + v # Visually select # 'Modifiers' - i # Inside - a # Around - NUM # Number (NUM is any number) - f # Searches for something and lands on it - t # Searches for something and stops before it - / # Finds a string from cursor onwards - ? # Finds a string before cursor + i # Inside + a # Around + NUM # Number (NUM is any number) + f # Searches for something and lands on it + t # Searches for something and stops before it + / # Finds a string from cursor onwards + ? # Finds a string before cursor # 'Nouns' - w # Word - s # Sentence - p # Paragraph - b # Block + w # Word + s # Sentence + p # Paragraph + b # Block # Sample 'sentences' or commands - d2w # Delete 2 words - cis # Change inside sentence - yip # Yank inside paragraph (copy the para you're in) - ct< # Change to open bracket - # Change the text from where you are to the next open bracket - d$ # Delete till end of line + d2w # Delete 2 words + cis # Change inside sentence + yip # Yank inside paragraph (copy the para you're in) + ct< # Change to open bracket + # Change the text from where you are to the next open bracket + d$ # Delete till end of line ``` ## Some shortcuts and tricks <!--TODO: Add more!--> ``` - > # Indent selection by one block - < # Dedent selection by one block - :earlier 15m # Reverts the document back to how it was 15 minutes ago - :later 15m # Reverse above command - ddp # Swap position of consecutive lines, dd then p - . # Repeat previous action - :w !sudo tee % # Save the current file as root - :set syntax=c # Set syntax highlighting to 'c' - :sort # Sort all lines - :sort! # Sort all lines in reverse - :sort u # Sort all lines and remove duplicates - ~ # Toggle letter case of selected text - u # Selected text to lower case - U # Selected text to upper case - J # Join the current line with the next line + > # Indent selection by one block + < # Dedent selection by one block + :earlier 15m # Reverts the document back to how it was 15 minutes ago + :later 15m # Reverse above command + ddp # Swap position of consecutive lines, dd then p + . # Repeat previous action + :w !sudo tee % # Save the current file as root + :set syntax=c # Set syntax highlighting to 'c' + :sort # Sort all lines + :sort! # Sort all lines in reverse + :sort u # Sort all lines and remove duplicates + ~ # Toggle letter case of selected text + u # Selected text to lower case + U # Selected text to upper case + J # Join the current line with the next line # Fold text - zf # Create fold from selected text - zo # Open current fold - zc # Close current fold - zR # Open all folds - zM # Close all folds + zf # Create fold from selected text + zd # Delete fold on the current line + zD # Recursively delete nested or visually selected folds + zE # Eliminate all folds in the window + zo # Open current fold + zO # Recursively open nested or visually selected folds + zc # Close current fold + zC # Recursively close nested or visually selected folds + zR # Open all folds + zM # Close all folds + za # Toggle open/close current fold + zA # Recursively toggle open/close nested fold + [z # Move to the start of the current fold + ]z # Move to the end of the current fold + zj # Move to the start of the next fold + zk # Move to the end of the previous fold ``` ## Macros @@ -210,9 +223,9 @@ you use, until you stop recording. On invoking a macro, it applies the exact same sequence of actions and commands again on the text selection. ``` - qa # Start recording a macro named 'a' - q # Stop recording - @a # Play back the macro + qa # Start recording a macro named 'a' + q # Stop recording + @a # Play back the macro ``` ### Configuring ~/.vimrc diff --git a/vimscript.html.markdown b/vimscript.html.markdown index c2934af8..04fee6fa 100644 --- a/vimscript.html.markdown +++ b/vimscript.html.markdown @@ -11,7 +11,7 @@ contributors: " ############## " " Vim script (also called VimL) is the subset of Vim's ex-commands which -" supplies a number of features one one would expect from a scripting language, +" supplies a number of features one would expect from a scripting language, " such as values, variables, functions or loops. Always keep in the back of " your mind that a Vim script file is just a sequence of ex-commands. It is " very common for a script to mix programming-language features and raw @@ -38,11 +38,11 @@ echo 'Hello' | echo 'world!' " Putting a comment after a command usually works pwd " Displays the current working directory -" Except for some commands it does not; use the command delemiter before the +" Except for some commands it does not; use the command delimiter before the " comment (echo assumes that the quotation mark begins a string) echo 'Hello world!' | " Displays a message -" Line breaks can be escaped by pacing a backslash as the first non-whitespace +" Line breaks can be escaped by placing a backslash as the first non-whitespace " character on the *following* line. Only works in script files, not on the " command line echo " Hello @@ -98,7 +98,7 @@ echo v:false | " Evaluates to 0 or the string 'v:false' " Boolean values can result from comparison of two objects. echo x == y | " Equality by value -echo x != y | " Unequality +echo x != y | " Inequality echo x > y | " Greater than echo x >= y | " Greater than or equal echo x < y | " Smaller than @@ -110,7 +110,7 @@ echo x isnot y | " Instance non-identity (lists and dictionaries) " echo 'a' < 'b'. Case sensitivity depends on the setting of 'ignorecase' " " Explicit case-sensitivity is specified by appending '#' (match case) or '?' -" (ignore case) to the operator. Prefer explicity case sensitivity when writing +" (ignore case) to the operator. Prefer explicitly case sensitivity when writing " portable scripts. echo 'a' < 'B' | " True or false depending on 'ignorecase' @@ -315,7 +315,7 @@ let s:isNumber = {x -> type(x) == type(0)} | " Local: any name allowed " Assign values of list to multiple variables (number of items must match) let [x, y] = [1, 2] -" Assign the remainer to a rest variable (note the semicolon) +" Assign the remainder to a rest variable (note the semicolon) let [mother, father; children] = ['Alice', 'Bob', 'Carol', 'Dennis', 'Emily'] @@ -610,7 +610,7 @@ echo exists(':Make') | " Command echo exists("#CursorHold") | " Auto-command defined for event echo exists("#BufReadPre#*.gz") | " Event and pattern echo exists("#filetypeindent") | " Auto-command group -echo exists("##ColorScheme") | " Auto-commnand supported for event +echo exists("##ColorScheme") | " Auto-command supported for event " Various dynamic values (see |expand()|) echo expand('%') | " Current file name diff --git a/vyper.html.markdown b/vyper.html.markdown index fec1a79f..bad0c31e 100644 --- a/vyper.html.markdown +++ b/vyper.html.markdown @@ -181,7 +181,7 @@ def _changeTaskStatus( \ _status: uint256, \ ): # backslashes (\) allow for multi-line code - # Natspec comments are particularly helpful for documentation and readibility + # Natspec comments are particularly helpful for documentation and readability # Natspec can be included using familiar Pythonic docstring syntax """ @notice @@ -429,16 +429,16 @@ struct Struct: owner: address _balance: uint256 # balance is a reserved keyword, is a member for addresses -exampleStuct: Struct +exampleStruct: Struct @public def foo() -> uint256: - self.exampleStuct = Struct({owner: msg.sender, _balance: 5}) - self.exampleStuct._balance = 10 - self.exampleStuct._balance = 5 # set to new value - clear(self.exampleStuct._balance) - clear(self.exampleStuct) - return self.exampleStuct._balance + self.exampleStruct = Struct({owner: msg.sender, _balance: 5}) + self.exampleStruct._balance = 10 + self.exampleStruct._balance = 5 # set to new value + clear(self.exampleStruct._balance) + clear(self.exampleStruct) + return self.exampleStruct._balance # Data locations: Memory vs. storage vs. calldata - all complex types (arrays, @@ -510,7 +510,7 @@ def increment(x: uint256, y: uint256) -> (uint256, uint256): y += 1 return (x, y) -# Call previous functon +# Call previous function @public @constant def willCall() -> (uint256, uint256): @@ -679,7 +679,7 @@ sha3(concat("ab", "cd")) # returns bytes32 # Step 1. Commit # Place a commitment by sending output of `sha3()` -sha3("a secret"); # btyes32 commit +sha3("a secret"); # bytes32 commit sha3(concat("secret", "other secret", "salt")); # commit multiple things # The `sha3()` calculation should occur off-chain, only the bytes32 # output should be inputted into some `commit()` function diff --git a/yaml.html.markdown b/yaml.html.markdown index 6dc5905e..135213d2 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -2,8 +2,10 @@ language: yaml filename: learnyaml.yaml contributors: + - [Leigh Brenecki, 'https://leigh.net.au'] - [Suhas SG, 'https://github.com/jargnar'] + --- YAML is a data serialisation language designed to be directly writable and @@ -17,6 +19,7 @@ YAML doesn't allow literal tab characters for indentation. --- # document start # Comments in YAML look like this. +# YAML supports single-line comments. ################ # SCALAR TYPES # @@ -28,11 +31,24 @@ key: value another_key: Another value goes here. a_number_value: 100 scientific_notation: 1e+12 -# The number 1 will be interpreted as a number, not a boolean. if you want -# it to be interpreted as a boolean, use true +hex_notation: 0x123 # evaluates to 291 +octal_notation: 0123 # evaluates to 83 + +# The number 1 will be interpreted as a number, not a boolean. +# If you want it to be interpreted as a boolean, use true. boolean: true null_value: null +another_null_value: ~ key with spaces: value + +# Yes and No (doesn't matter the case) will be evaluated to boolean +# true and false values respectively. +# To use the actual value use single or double quotes. +no: no # evaluates to "false": false +yes: No # evaluates to "true": false +not_enclosed: yes # evaluates to "not_enclosed": true +enclosed: "yes" # evaluates to "enclosed": yes + # Notice that strings don't need to be quoted. However, they can be. however: 'A string, enclosed in quotes.' 'Keys can be quoted too.': "Useful if you want to put a ':' in your key." @@ -41,25 +57,49 @@ double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more." # UTF-8/16/32 characters need to be encoded Superscript two: \u00B2 -# Multiple-line strings can be written either as a 'literal block' (using |), +# Special characters must be enclosed in single or double quotes +special_characters: "[ John ] & { Jane } - <Doe>" + +# Multiple-line strings can be written either as a 'literal block' (using |), # or a 'folded block' (using '>'). +# Literal block turn every newline within the string into a literal newline (\n). +# Folded block removes newlines within the string. literal_block: | - This entire block of text will be the value of the 'literal_block' key, - with line breaks being preserved. + This entire block of text will be the value of the 'literal_block' key, + with line breaks being preserved. - The literal continues until de-dented, and the leading indentation is - stripped. + The literal continues until de-dented, and the leading indentation is + stripped. - Any lines that are 'more-indented' keep the rest of their indentation - - these lines will be indented by 4 spaces. + Any lines that are 'more-indented' keep the rest of their indentation - + these lines will be indented by 4 spaces. folded_style: > - This entire block of text will be the value of 'folded_style', but this - time, all newlines will be replaced with a single space. + This entire block of text will be the value of 'folded_style', but this + time, all newlines will be replaced with a single space. - Blank lines, like above, are converted to a newline character. + Blank lines, like above, are converted to a newline character. - 'More-indented' lines keep their newlines, too - - this text will appear over two lines. + 'More-indented' lines keep their newlines, too - + this text will appear over two lines. + +# |- and >- removes the trailing blank lines (also called literal/block "strip") +literal_strip: |- + This entire block of text will be the value of the 'literal_block' key, + with trailing blank line being stripped. +block_strip: >- + This entire block of text will be the value of 'folded_style', but this + time, all newlines will be replaced with a single space and + trailing blank line being stripped. + +# |+ and >+ keeps trailing blank lines (also called literal/block "keep") +literal_keep: |+ + This entire block of text will be the value of the 'literal_block' key, + with trailing blank line being kept. + +block_keep: >+ + This entire block of text will be the value of 'folded_style', but this + time, all newlines will be replaced with a single space and + trailing blank line being kept. #################### # COLLECTION TYPES # @@ -87,7 +127,7 @@ a_nested_map: # An example ? - Manchester United - Real Madrid -: [2001-01-01, 2002-02-02] +: [ 2001-01-01, 2002-02-02 ] # Sequences (equivalent to lists or arrays) look like this # (note that the '-' counts as indentation): @@ -98,24 +138,26 @@ a_sequence: - Item 4 - key: value another_key: another_value - - - - This is a sequence + - - This is a sequence - inside another sequence - - - Nested sequence indicators - can be collapsed # Since YAML is a superset of JSON, you can also write JSON-style maps and # sequences: -json_map: {"key": "value"} -json_seq: [3, 2, 1, "takeoff"] -and quotes are optional: {key: [3, 2, 1, takeoff]} +json_map: { "key": "value" } +json_seq: [ 3, 2, 1, "takeoff" ] +and quotes are optional: { key: [ 3, 2, 1, takeoff ] } ####################### # EXTRA YAML FEATURES # ####################### # YAML also has a handy feature called 'anchors', which let you easily duplicate -# content across your document. Both of these keys will have the same value: +# content across your document. +# Anchors identified by & character which define the value. +# Aliases identified by * character which acts as "see above" command. +# Both of these keys will have the same value: anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name @@ -123,28 +165,35 @@ other_anchor: *anchor_name base: &base name: Everyone has same name -# The regexp << is called Merge Key Language-Independent Type. It is used to +# The regexp << is called 'Merge Key Language-Independent Type'. It is used to # indicate that all the keys of one or more specified maps should be inserted # into the current map. - +# NOTE: If key already exists alias will not be merged foo: - <<: *base + <<: *base # doesn't merge the anchor age: 10 - + name: John bar: - <<: *base + <<: *base # base anchor will be merged age: 20 # foo and bar would also have name: Everyone has same name # YAML also has tags, which you can use to explicitly declare types. +# Syntax: !![typeName] [value] +explicit_boolean: !!bool true +explicit_integer: !!int 42 +explicit_float: !!float -42.24 explicit_string: !!str 0.5 +explicit_datetime: !!timestamp 2022-11-17 12:34:56.78 +9 +explicit_null: !!null null + # Some parsers implement language specific tags, like this one for Python's # complex number type. python_complex_number: !!python/complex 1+2j # We can also use yaml complex keys with language specific tags -? !!python/tuple [5, 7] +? !!python/tuple [ 5, 7 ] : Fifty Seven # Would be {(5, 7): 'Fifty Seven'} in Python @@ -154,9 +203,10 @@ python_complex_number: !!python/complex 1+2j # Strings and numbers aren't the only scalars that YAML can understand. # ISO-formatted date and datetime literals are also parsed. -datetime: 2001-12-15T02:59:43.1Z -datetime_with_spaces: 2001-12-14 21:59:43.10 -5 -date: 2002-12-14 +datetime_canonical: 2001-12-15T02:59:43.1Z +datetime_space_separated_with_time_zone: 2001-12-14 21:59:43.10 -5 +date_implicit: 2002-12-14 +date_explicit: !!timestamp 2002-12-14 # The !!binary tag indicates that a string is actually a base64-encoded # representation of a binary blob. @@ -171,7 +221,7 @@ set: ? item1 ? item2 ? item3 -or: {item1, item2, item3} +or: { item1, item2, item3 } # Sets are just maps with null values; the above is equivalent to: set2: @@ -186,3 +236,4 @@ set2: + [YAML official website](https://yaml.org/) + [Online YAML Validator](http://www.yamllint.com/) ++ [JSON ⇆ YAML](https://www.json2yaml.com/) diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown index 8ee2db2c..bac833a6 100644 --- a/zh-cn/awk-cn.html.markdown +++ b/zh-cn/awk-cn.html.markdown @@ -179,7 +179,7 @@ function string_functions( localvar, arr) { # 都是返回替换的个数 localvar = "fooooobar" sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" - gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + gsub("e", ".", localvar) # localvar => "m..t m. at th. bar" # 搜索匹配正则的字符串 # index() 也是搜索, 不支持正则 diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index e0d6b6fe..a6a61949 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -1,5 +1,5 @@ ---
-language: c++
+language: C++
filename: learncpp-cn.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index dbad5030..dd4445f7 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: c +language: C filename: learnc-cn.c contributors: - ["Adam Bard", "http://adambard.com/"] diff --git a/zh-cn/clojure-cn.html.markdown b/zh-cn/clojure-cn.html.markdown index fa241384..e98eac2a 100644 --- a/zh-cn/clojure-cn.html.markdown +++ b/zh-cn/clojure-cn.html.markdown @@ -362,7 +362,7 @@ Clojuredocs.org有大多数核心函数的文档,还带了示例哦: [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) 4Clojure是个很赞的用来练习clojure/FP技能的地方: -[http://www.4clojure.com/](http://www.4clojure.com/) +[https://4clojure.oxal.org/](https://4clojure.oxal.org/) Clojure-doc.org (你没看错)有很多入门级的文章: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/zh-cn/clojure-macro-cn.html.markdown b/zh-cn/clojure-macro-cn.html.markdown index 23b2f203..85b966e9 100644 --- a/zh-cn/clojure-macro-cn.html.markdown +++ b/zh-cn/clojure-macro-cn.html.markdown @@ -131,7 +131,7 @@ lang: zh-cn ; 然而,如果我们希望它在编译期执行,就需要创建宏 (defmacro inline-2 [form] - (inline-2-helper form))) + (inline-2-helper form)) (macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) ; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown index 971c1be9..0bad34ce 100644 --- a/zh-cn/csharp-cn.html.markdown +++ b/zh-cn/csharp-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: c# +language: C# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] diff --git a/zh-cn/docker-cn.html.markdown b/zh-cn/docker-cn.html.markdown index f55e805a..ff793ae0 100644 --- a/zh-cn/docker-cn.html.markdown +++ b/zh-cn/docker-cn.html.markdown @@ -1,5 +1,6 @@ --- -language: docker +category: tool +tool: docker lang: zh-cn filename: docker-cn.bat contributors: diff --git a/zh-cn/gdscript-cn.html.markdown b/zh-cn/gdscript-cn.html.markdown new file mode 100644 index 00000000..7c731533 --- /dev/null +++ b/zh-cn/gdscript-cn.html.markdown @@ -0,0 +1,317 @@ +--- +language: GDScript +contributors: + - ["Wichamir", "https://github.com/Wichamir/"] +translators: + - ["ShiftWatchOut", "https://github.com/ShiftWatchOut"] +filename: learngdscript-cn.gd +lang: zh-cn +--- + +GDScript 是一种动态类型的脚本语言,专门为免费开源游戏引擎 Godot 制作。 GDScript 的语法类似 Python。 +它的主要优点是易于使用和与引擎深度集成。 它非常适合游戏开发。 + +## 基础 + +```nim +# 单行注释使用 # 号书写。 +""" + 多行 + 注释 + 是 + 使用 + 文档字符串(docstring) + 书写。 +""" + +# 脚本文件本身默认是一个类,文件名为类名,您也可以为其定义其他名称。 +class_name MyClass + +# 继承 +extends Node2D + +# 成员变量 +var x = 8 # 整型 +var y = 1.2 # 浮点型 +var b = true # 布尔型 +var s = "Hello World!" # 字符串 +var a = [1, false, "brown fox"] # 数组(Array) - 类似于 Python 的列表(list), + # 它可以同时保存不同类型的变量。 +var d = { + "key" : "value", + 42 : true +} # 字典包含键值对。 +var p_arr = PoolStringArray(["Hi", "there", "!"]) # 池数组只能包含单一类型。 + # 放入其他类型会被转换为目标类型 + +# 内置向量类型: +var v2 = Vector2(1, 2) +var v3 = Vector3(1, 2, 3) + +# 常量 +const ANSWER_TO_EVERYTHING = 42 +const BREAKFAST = "Spam and eggs!" + +# 枚举 +enum { ZERO, ONE , TWO, THREE } +enum NamedEnum { ONE = 1, TWO, THREE } + +# 导出的变量将在检查器中可见。 +export(int) var age +export(float) var height +export var person_name = "Bob" # 如果设置了默认值,则不需要类型注解。 + +# 函数 +func foo(): + pass # pass 关键字是未书写的代码的占位符 + +func add(first, second): + return first + second + +# 打印值 +func printing(): + print("GDScript ", "简直", "棒呆了") + prints("这", "些", "字", "被", "空", "格", "分", "割") + printt("这", "些", "字", "被", "制", "表", "符", "分", "割") + printraw("这句话将被打印到系统控制台。") + +# 数学 +func doing_math(): + var first = 8 + var second = 4 + print(first + second) # 12 + print(first - second) # 4 + print(first * second) # 32 + print(first / second) # 2 + print(first % second) # 0 + # 还有 +=, -=, *=, /=, %= 等操作符,但并没有 ++ 和 -- . + print(pow(first, 2)) # 64 + print(sqrt(second)) # 2 + printt(PI, TAU, INF, NAN) # 内置常量 + +# 控制流 +func control_flow(): + x = 8 + y = 2 # y 最初被设为一个浮点数, + # 但我们可以利用语言提供的动态类型能力将它的类型变为整型! + + if x < y: + print("x 小于 y") + elif x > y: + print("x 大于 y") + else: + print("x 等于 y") + + var a = true + var b = false + var c = false + if a and b or not c: # 你也可以用 &&, || 和 ! + print("看到这句说明上面的条件判断为真!") + + for i in range(20): # GDScript 有类似 Python 的 range 函数 + print(i) # 所以这句将打印从 0 到 19 的数字 + + for i in 20: # 与 Python 略有不同的是,你可以直接用一个整型数开始循环 + print(i) # 所以这行代码也将打印从 0 到 19 的数字 + + for i in ["two", 3, 1.0]: # 遍历数组 + print(i) + + while x > y: + printt(x, y) + y += 1 + + x = 2 + y = 10 + while x < y: + x += 1 + if x == 6: + continue # continue 语句使 x 等于 6 时,程序跳过这次循环后面的代码,不会打印 6。 + prints("x 等于:", x) + if x == 7: + break # 循环将在 x 等于 7 处跳出,后续所有循环不再执行,因此不会打印 8、9 和 10 + + match x: + 1: + print("match 很像其他语言中的 switch.") + 2: + print("但是,您不需要在每个值之前写一个 case 关键字。") + 3: + print("此外,每种情况都会默认跳出。") + break # 错误!不要在 match 里用 break 语句! + 4: + print("如果您需要跳过后续代码,这里也使用 continue 关键字。") + continue + _: + print("下划线分支,在其他分支都不满足时,在这里书写默认的逻辑。") + + # 三元运算符 (写在一行的 if-else 语句) + prints("x 是", "正值" if x >= 0 else "负值") + +# 类型转换 +func casting_examples(): + var i = 42 + var f = float(42) # 使用变量构造函数强制转换 + var b = i as bool # 或使用 as 关键字 + +# 重载函数 +# 通常,我们只会重载以下划线开头的内置函数, +# 但实际上您可以重载几乎任何函数。 + +# _init 在对象初始化时被调用。 +# 这是对象的构造函数。 +func _init(): + # 在此处初始化对象的内部属性。 + pass + +# _ready 在脚本节点及其子节点进入场景树时被调用。 +func _ready(): + pass + +# _process 在每一帧上都被调用。 +func _process(delta): + # 传递给此函数的 delta 参数是时间,即从上一帧到当前帧经过的秒数。 + print("Delta 时间为:", delta) + +# _physics_process 在每个物理帧上都被调用。 +# 这意味着 delta 应该是恒定的。 +func _physics_process(delta): + # 使用向量加法和乘法进行简单移动。 + var direction = Vector2(1, 0) # 或使用 Vector2.RIGHT + var speed = 100.0 + self.global_position += direction * speed * delta + # self 指向当前类的实例 + +# 重载函数时,您可以使用 . 运算符调用父函数 +# like here: +func get_children(): + # 在这里做一些额外的事情。 + var r = .get_children() # 调用父函数的实现 + return r + +# 内部类 +class InnerClass: + extends Object + + func hello(): + print("来自内部类的 Hello!") + +func use_inner_class(): + var ic = InnerClass.new() + ic.hello() + ic.free() # 可以自行释放内存 +``` + +## 访问场景树中其他节点 + +```nim +extends Node2D + +var sprite # 该变量将用来保存引用。 + +# 您可以在 _ready 中获取对其他节点的引用。 +func _ready() -> void: + # NodePath 对于访问节点很有用。 + # 将 String 传递给其构造函数来创建 NodePath: + var path1 = NodePath("path/to/something") + # 或者使用 NodePath 字面量: + var path2 = @"path/to/something" + # NodePath 示例: + var path3 = @"Sprite" # 相对路径,当前节点的直接子节点 + var path4 = @"Timers/Firerate" # 相对路径,子节点的子节点 + var path5 = @".." # 当前节点的父节点 + var path6 = @"../Enemy" # 当前节点的兄弟节点 + var path7 = @"/root" # 绝对路径,等价于 get_tree().get_root() + var path8 = @"/root/Main/Player/Sprite" # Player 的 Sprite 的绝对路径 + var path9 = @"Timers/Firerate:wait_time" # 访问属性 + var path10 = @"Player:position:x" # 访问子属性 + + # 最后,获取节点引用可以使用以下方法: + sprite = get_node(@"Sprite") as Sprite # 始终转换为您期望的类型 + sprite = get_node("Sprite") as Sprite # 这里 String 被隐式转换为 NodePath + sprite = get_node(path3) as Sprite + sprite = get_node_or_null("Sprite") as Sprite + sprite = $Sprite as Sprite + +func _process(delta): + # 现在我们就可以在别处使用 sprite 里保存的引用了。 + prints("Sprite 有一个全局位置 ", sprite.global_position) + +# 在 _ready 执行之前,使用 onready 关键字为变量赋值。 +# 这是一种常用的语法糖。 +onready var tween = $Tween as Tween + +# 您可以导出这个 NodePath,以便在检查器中给它赋值。 +export var nodepath = @"" +onready var reference = get_node(nodepath) as Node +``` + +## 信号(Signals) + +信号系统是 Godot 对观察者编程模式的实现。例子如下: + +```nim +class_name Player extends Node2D + +var hp = 10 + +signal died() # 定义一个信号 +signal hurt(hp_old, hp_new) # 信号可以带参数 + +func apply_damage(dmg): + var hp_old = hp + hp -= dmg + emit_signal("hurt", hp_old, hp) # 发出信号并传递参数 + if hp <= 0: + emit_signal("died") + +func _ready(): + # 将信号 "died" 连接到 self 中定义的 _on_death 函数 + self.connect("died", self, "_on_death") + +func _on_death(): + self.queue_free() # 死亡时销毁 Player +``` + +## 类型注解 + +GDScript 可以选择性地使用静态类型。 + +```nim +extends Node + +var x: int # 定义带有类型的变量 +var y: float = 4.2 +var z := 1.0 # 使用 := 运算符根据默认值推断类型 + +onready var node_ref_typed := $Child as Node + +export var speed := 50.0 + +const CONSTANT := "Typed constant." + +func _ready() -> void: + # 此函数不返回任何东西 + x = "string" # 错误!不要更改类型! + return + +func join(arg1: String, arg2: String) -> String: + # 此函数接受两个 String 并返回一个 String。 + return arg1 + arg2 + +func get_child_at(index: int) -> Node: + # 此函数接受一个 int 并返回一个 Node + return get_children()[index] + +signal example(arg: int) # 错误!信号不能接受类型参数! +``` + +## 延展阅读 + +* [Godot's Website](https://godotengine.org/) +* [Godot Docs](https://docs.godotengine.org/en/stable/) +* [Getting started with GDScript](https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/index.html) +* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html) +* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html) +* [GDQuest](https://www.gdquest.com/) +* [GDScript.com](https://gdscript.com/)
\ No newline at end of file diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown index 63d740a1..9dfbbb93 100644 --- a/zh-cn/git-cn.html.markdown +++ b/zh-cn/git-cn.html.markdown @@ -370,5 +370,3 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Atlassian Git - 教程与工作流程](https://www.atlassian.com/git/) * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) - -* [GitGuys](http://www.gitguys.com/) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index dd52d187..0123c0a6 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -22,7 +22,7 @@ Go语言有非常棒的标准库,还有一个充满热情的社区。 注释 */ // 导入包的子句在每个源文件的开头。 -// Main比较特殊,它用来声明可执行文件,而不是一个库。 +// main比较特殊,它用来声明可执行文件,而不是一个库。 package main // Import语句声明了当前文件引用的包。 diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index 1de7f3e6..53a423a8 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -190,7 +190,7 @@ public class LearnJava { { //System.out.println(fooWhile); //增加计数器 - //遍历99次, fooWhile 0->99 + //遍历100次, fooWhile 0->99 fooWhile++; } System.out.println("fooWhile Value: " + fooWhile); @@ -201,7 +201,7 @@ public class LearnJava { { //System.out.println(fooDoWhile); //增加计数器 - //遍历99次, fooDoWhile 0->99 + //遍历100次, fooDoWhile 0->99 fooDoWhile++; }while(fooDoWhile < 100); System.out.println("fooDoWhile Value: " + fooDoWhile); diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 6736dc2a..6fd10a32 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -391,7 +391,8 @@ dofile('mod2') --> Hi! (再次运行,与require不同) f = loadfile('mod2') -- Calling f() runs mod2.lua. -- loadstring是loadfile的字符串版本。 -g = loadstring('print(343)') --返回一个函数。 +-- (loadstring已弃用, 使用load代替) +g = load('print(343)') --返回一个函数。 g() -- 打印343; 在此之前什么也不打印。 --]] diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index d215755c..ca08b36b 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -1,5 +1,5 @@ ---
-language: Matlab
+language: MATLAB
filename: matlab-cn.m
contributors:
- ["mendozao", "http://github.com/mendozao"]
diff --git a/zh-cn/powershell-cn.html.markdown b/zh-cn/powershell-cn.html.markdown index 6ab34e9f..875d2e33 100644 --- a/zh-cn/powershell-cn.html.markdown +++ b/zh-cn/powershell-cn.html.markdown @@ -13,7 +13,7 @@ PowerShell 是 Windows 平台下的脚本语言同时也是配置管理框架, 与 Bash 最大的不同是你大部分操作的东西是对象而不是普通的文本。 -[延伸阅读](https://technet.microsoft.com/en-us/library/bb978526.aspx) +[延伸阅读](https://docs.microsoft.com/zh-cn/powershell/scripting/overview) 如果你不确定你的环境,执行如下操作: @@ -263,7 +263,7 @@ Get-Command ConvertTo-*,ConvertFrom-* ### 有用的东西 # 更新 PATH -$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + +$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") # 找到 Python 的 PATH @@ -319,7 +319,7 @@ if (-not (Test-Path $Profile)) { 尚未涉及 -* WMI: Windows 管理规范 (Get-CimInstance) +* WMI: Windows 管理规范 (Get-CimInstance) * 多任务: Start-Job -scriptBlock {...}, * 代码签名 * 远程 (Enter-PSSession/Exit-PSSession; Invoke-Command) diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index a4e53c1b..127f7ad5 100644 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -552,7 +552,7 @@ next(our_iterator) # => "three" # 当迭代器所有元素都取出后,会抛出 StopIteration next(our_iterator) # 抛出 StopIteration -# 我们可以通过遍历还访问所有的值,实际上,for 内部实现了迭代 +# 我们还可以通过遍历访问所有的值,实际上,for 内部实现了迭代 our_iterator = iter(our_iterable) for i in our_iterator: print(i) # 依次打印 one, two, three @@ -697,7 +697,7 @@ import math dir(math) # 当你的脚本文件所在的文件夹也包含了一个名为 math.py 的 Python 文件 -# 这个 math.p 文件会被代替引入,而不是引入 Python 內建模块中的 math +# 这个 math.py 文件会被代替引入,而不是引入 Python 內建模块中的 math # 出现这个情况的原因是本地文件夹的引入优先级要比 Python 內建库引入优先级要高 @@ -760,7 +760,7 @@ class Human: del self._age # 当 Python 解释器在读取源文件的时候,就会执行文件中所有的代码 -# 对 __name__ 的检查可以保证这块代码只会在执行这个模块是住程序情况下被运行(而不是在引用时运行) +# 对 __name__ 的检查可以保证这块代码只会在这个模块是主程序的情况下被运行(而不是在引用时运行) if __name__ == '__main__': # i = Human(name="Ian") diff --git a/zh-cn/qt-cn.html.markdown b/zh-cn/qt-cn.html.markdown index 8681c85b..1d24f200 100644 --- a/zh-cn/qt-cn.html.markdown +++ b/zh-cn/qt-cn.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: Qt Framework -language: c++ +language: C++ filename: learnqt-cn.cpp contributors: - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 63adab64..b0b8b58c 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -430,7 +430,7 @@ def guests(*array) array.each { |guest| puts guest } end -# 结构 +# 解构 # 如果函数返回一个数组,在赋值时可以进行拆分: def foods @@ -449,7 +449,7 @@ end best *ranked_competitors.first(3) #=> Winners are John, Sally, and Dingus. -# 结构操作符也可放在参数里面 +# 解构操作符也可放在参数里面 def best(first, second, third, *others) puts "Winners are #{first}, #{second}, and #{third}." puts "There were #{others.count} other participants." diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown index b77c9c38..6bed1650 100644 --- a/zh-cn/rust-cn.html.markdown +++ b/zh-cn/rust-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/zig.html.markdown b/zig.html.markdown new file mode 100644 index 00000000..f8c866e5 --- /dev/null +++ b/zig.html.markdown @@ -0,0 +1,980 @@ +--- +language: zig +filename: learnzig.zig +contributors: + - ["Philippe Pittoli", "https://karchnu.fr/"] +--- + + +[Zig][ziglang] aims to be a replacement for the C programming language. + +**WARNING**: this document expects you to understand a few basic concepts in computer science, such as pointers, stack and heap memory, etc. + +**WARNING**: Zig isn't considered as ready for production. Bugs are expected. +DO NOT TRY ZIG AS YOUR FIRST PROGRAMMING EXPERIENCE. +The compiler, even the language and its libraries aren't ready, yet. +You've been warned. + +Prior knowledge of C is recommended. + + +## Quick overview: Zig compared to C + +- Syntax is mostly the same, with some improvements (less ambiguity). +- Zig introduces namespaces. +- Try and catch mechanism, which is both convenient, efficient and optional. +- Most of the C undefined behaviors (UBs) are fixed. +- Compared to C, raw pointers are safer to use and less likely to be needed. + * The type system distinguishes between a pointer to a single value, or multiple values, etc. + * Slices are preferred, which is a structure with a pointer and a runtime known size, which characterizes most uses of pointers in the first place. +- Some arbitrary language limitations are removed. For example, enumerations, structures and unions can have functions. +- Simple access to SIMD operations (basic maths on vectors). +- Zig provides both low-level features of C and the one provided through compiler extensions. + For example: packed structures. +- An extensive standard library, including data structures and algorithms. +- Cross-compilation capability is provided by default, without any dependency. + Different libc are provided to ease the process. + Cross-compilation works from, and to, any operating system and architecture. + +## Zig language + + +``` +//! Top-level documentation. + +/// Documentation comment. + +// Simple comment. +``` + + +### Hello world. +``` +// Import standard library, reachable through the "std" constant. +const std = @import("std"); + +// "info" now refers to the "std.log.info" function. +const info = std.log.info; + +// Usual hello world. +// syntax: [pub] fn <function-name>(<arguments>) <return-type> { <body> } +pub fn main() void { + // Contrary to C functions, Zig functions have a fixed number of arguments. + // In C: "printf" takes any number of arguments. + // In Zig: std.log.info takes a format and a list of elements to print. + info("hello world", .{}); // .{} is an empty anonymous tuple. +} +``` + +### Booleans, integers and float. +``` +// Booleans. +// Keywords are preferred to operators for boolean operations. +print("{}\n{}\n{}\n", .{ + true and false, + true or false, + !true, +}); + +// Integers. +const one_plus_one: i32 = 1 + 1; +print("1 + 1 = {}\n", .{one_plus_one}); // 2 + +// Floats. +const seven_div_three: f32 = 7.0 / 3.0; +print("7.0 / 3.0 = {}\n", .{seven_div_three}); // 2.33333325e+00 + +// Integers have arbitrary value lengths. +var myvar: u10 = 5; // 10-bit unsigned integer +// Useful for example to read network packets, or complex binary formats. + +// Number representation is greatly improved compared to C. +const one_billion = 1_000_000_000; // Decimal. +const binary_mask = 0b1_1111_1111; // Binary. Ex: network mask. +const permissions = 0o7_5_5; // Octal. Ex: Unix permissions. +const big_address = 0xFF80_0000_0000_0000; // Hexa. Ex: IPv6 address. + + +// Overflow operators: tell the compiler when it's okay to overflow. +var i: u8 = 0; // "i" is an unsigned 8-bit integer +i -= 1; // runtime overflow error (unsigned value always are positive) +i -%= 1; // okay (wrapping operator), i == 255 + +// Saturation operators: values will stick to their lower and upper bounds. +var i: u8 = 200; // "i" is an unsigned 8-bit integer (values: from 0 to 255) +i +| 100 == 255 // u8: won't go higher than 255 +i -| 300 == 0 // unsigned, won't go lower than 0 +i *| 2 == 255 // u8: won't go higher than 255 +i <<| 8 == 255 // u8: won't go higher than 255 +``` + +### Arrays. +``` +// An array is a well-defined structure with a length attribute (len). + +// 5-byte array with undefined content (stack garbage). +var array1: [5]u8 = undefined; + +// 5-byte array with defined content. +var array2 = [_]u8{ 1, 2, 3, 4, 5 }; +// [_] means the compiler knows the length at compile-time. + +// 1000-byte array with defined content (0). +var array3 = [_]u8{0} ** 1000; + +// Another 1000-byte array with defined content. +// The content is provided by the "foo" function, called at compile-time and +// allows complex initializations. +var array4 = [_]u8{foo()} ** 1000; + +// In any case, array.len gives the length of the array, +// array1.len and array2.len produce 5, array3.len and array4.len produce 1000. + + +// Modifying and accessing arrays content. + +// Array of 10 32-bit undefined integers. +var some_integers: [10]i32 = undefined; + +some_integers[0] = 30; // first element of the array is now 30 + +var x = some_integers[0]; // "x" now equals to 30, its type is inferred. +var y = some_integers[1]; // Second element of the array isn't defined. + // "y" got a stack garbage value (no runtime error). + +// Array of 10 32-bit undefined integers. +var some_integers: [10]i32 = undefined; + +var z = some_integers[20]; // index > array size, compilation error. + +// At runtime, we loop over the elements of "some_integers" with an index. +// Index i = 20, then we try: +try some_integers[i]; // Runtime error 'index out of bounds'. + // "try" keyword is necessary when accessing an array with + // an index, since there is a potential runtime error. + // More on that later. +``` + +### Multidimensional arrays. +``` + +const mat4x4 = [4][4]f32{ + [_]f32{ 1.0, 0.0, 0.0, 0.0 }, + [_]f32{ 0.0, 1.0, 0.0, 1.0 }, + [_]f32{ 0.0, 0.0, 1.0, 0.0 }, + [_]f32{ 0.0, 0.0, 0.0, 1.0 }, +}; + +// Access the 2D array then the inner array through indexes. +try expect(mat4x4[1][1] == 1.0); + +// Here we iterate with for loops. +for (mat4x4) |row, row_index| { + for (row) |cell, column_index| { + // ... + } +} +``` + +### Strings. +``` + +// Simple string constant. +const greetings = "hello"; +// ... which is equivalent to: +const greetings: *const [5:0]u8 = "hello"; +// In words: "greetings" is a constant value, a pointer on a constant array of 5 +// elements (8-bit unsigned integers), with an extra '0' at the end. +// The extra "0" is called a "sentinel value". + +print("string: {s}\n", .{greetings}); + +// This represents rather faithfully C strings. Although, Zig strings are +// structures, no need for "strlen" to compute their size. +// greetings.len == 5 +``` + +### Slices. +``` + +// A slice is a pointer and a size, an array without compile-time known size. +// Slices have runtime out-of-band verifications. + +const array = [_]u8{1,2,3,4,5}; // [_] = array with compile-time known size. +const slice = array[0..array.len]; // "slice" represents the whole array. + // slice[10] gives a runtime error. +``` + +### Pointers. +``` + +// Pointer on a value can be created with "&". +const x: i32 = 1; +const pointer: *i32 = &x; // "pointer" is a pointer on the i32 var "x". +print("1 = {}, {}\n", .{x, pointer}); + +// Pointer values are accessed and modified with ".*". +if (pointer.* == 1) { + print("x value == {}\n", .{pointer.*}); +} + +// ".?" is a shortcut for "orelse unreachable". +const foo = pointer.?; // Get the pointed value, otherwise crash. +``` + +### Optional values (?<type>). +``` +// An optional is a value than can be of any type or null. + +// Example: "optional_value" can either be "null" or an unsigned 32-bit integer. +var optional_value: ?u32 = null; // optional_value == null +optional_value = 42; // optional_value != null + +// "some_function" returns ?u32 +var x = some_function(); +if (x) |value| { + // In case "some_function" returned a value. + // Do something with 'value'. +} +``` + +### Errors. +``` +// Zig provides an unified way to express errors. + +// Errors are defined in error enumerations, example: +const Error = error { + WatchingAnyNetflixTVShow, + BeOnTwitter, +}; + +// Normal enumerations are expressed the same way, but with "enum" keyword. +const SuccessStory = enum { + DoingSport, + ReadABook, +}; + + +// Error union (!). +// Either the value "mylife" is an an error or a normal value. +var mylife: Error!SuccessStory = Error.BeOnTwitter; +// mylife is an error. Sad. + +mylife = SuccessStory.ReadABook; +// Now mylife is an enum. + + +// Zig ships with many pre-defined errors. Example: +const value: anyerror!u32 = error.Broken; + + +// Handling errors. + +// Some error examples. +const Error = error { + UnExpected, + Authentication, +}; + +// "some_function" can either return an "Error" or an integer. +fn some_function() Error!u8 { + return Error.UnExpected; // It returns an error. +} + +// Errors can be "catch" without intermediate variable. +var value = some_function() catch |err| switch(err) { + Error.UnExpected => return err, // Returns the error. + Error.Authentication => unreachable, // Not expected. Crashes the program. + else => unreachable, +}; + +// An error can be "catch" without giving it a name. +const unwrapped = some_function() catch 1234; // "unwrapped" = 1234 + +// "try" is a very handy shortcut for "catch |err| return err". +var value = try some_function(); +// If "some_function" fails, the current function stops and returns the error. +// "value" can only have a valid value, the error already is handled with "try". +``` + +### Control flow. + +``` +// Conditional branching. + +if (condition) { + ... +} +else { + ... +} + +// Ternary. +var value = if (condition) x else y; + +// Shortcut for "if (x) x else 0" +var value = x orelse 0; + +// If "a" is an optional, which may contain a value. +if (a) |value| { + print("value: {}\n", .{value}); +} +else { + print("'a' is null\n", .{}); +} + +// Get a pointer on the value (if it exists). +if (a) |*value| { value.* += 1; } + + +// Loops. + +// Syntax examples: +// while (condition) statement +// while (condition) : (end-of-iteration-statement) statement +// +// for (iterable) statement +// for (iterable) |capture| statement +// for (iterable) statement else statement + +// Note: loops work the same way over arrays or slices. + +// Simple "while" loop. +while (i < 10) { i += 1; } + +// While loop with a "continue expression" +// (expression executed as the last expression of the loop). +while (i < 10) : (i += 1) { ... } +// Same, with a more complex continue expression (block of code). +while (i * j < 2000) : ({ i *= 2; j *= 3; }) { ... } + +// To iterate over a portion of a slice, reslice. +for (items[0..1]) |value| { sum += value; } + +// Loop over every item of an array (or slice). +for (items) |value| { sum += value; } + +// Iterate and get pointers on values instead of copies. +for (items) |*value| { value.* += 1; } + +// Iterate with an index. +for (items) |value, i| { print("val[{}] = {}\n", .{i, value}); } + +// Iterate with pointer and index. +for (items) |*value, i| { print("val[{}] = {}\n", .{i, value}); value.* += 1; } + + +// Break and continue are supported. +for (items) |value| { + if (value == 0) { continue; } + if (value >= 10) { break; } + // ... +} + +// For loops can also be used as expressions. +// Similar to while loops, when you break from a for loop, +// the else branch is not evaluated. +var sum: i32 = 0; +// The "for" loop has to provide a value, which will be the "else" value. +const result = for (items) |value| { + if (value != null) { + sum += value.?; // "result" will be the last "sum" value. + } +} else 0; // Last value. +``` + +### Labels. +``` + +// Labels are a way to name an instruction, a location in the code. +// Labels can be used to "continue" or "break" in a nested loop. +outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| { + for ([_]i32{ 1, 2, 3, 4, 5 }) |_| { + count += 1; + continue :outer; // "continue" for the first loop. + } +} // count = 8 +outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| { + for ([_]i32{ 1, 2, 3, 4, 5 }) |_| { + count += 1; + break :outer; // "break" for the first loop. + } +} // count = 1 + + +// Labels can also be used to return a value from a block. +var y: i32 = 5; +const x = blk: { + y += 1; + break :blk y; // Now "x" equals 6. +}; +// Relevant in cases like "for else" expression (explained in the following). + +// For loops can be used as expressions. +// When you break from a for loop, the else branch is not evaluated. +// WARNING: counter-intuitive. +// The "for" loop will run, then the "else" block will run. +// The "else" keyword has to be followed by the value to give to "result". +// See later for another form. +var sum: u8 = 0; +const result = for (items) |value| { + sum += value; +} else 8; // result = 8 + +// In this case, the "else" keyword is followed by a value, too. +// However, the syntax is different: it is labeled. +// Instead of a value, there is a label followed by a block of code, which +// allows to do stuff before returning the value (see the "break" invocation). +const result = for (items) |value| { // First: loop. + sum += value; +} else blk: { // Second: "else" block. + std.log.info("executed AFTER the loop!", .{}); + break :blk sum; // The "sum" value will replace the label "blk". +}; +``` + +### Switch. +``` + +// As a switch in C, but slightly more advanced. +// Syntax: +// switch (value) { +// pattern => expression, +// pattern => expression, +// else => expression +// }; + +// A switch only checking for simple values. +var x = switch(value) { + Error.UnExpected => return err, + Error.Authentication => unreachable, + else => unreachable, +}; + +// A slightly more advanced switch, accepting a range of values: +const foo: i32 = 0; +const bar = switch (foo) { + 0 => "zero", + 1...std.math.maxInt(i32) => "positive", + else => "negative", +}; +``` + +### Structures. +``` + +// Structure containing a single value. +const Full = struct { + number: u16, +}; + +// Packed structure, with guaranteed in-memory layout. +const Divided = packed struct { + half1: u8, + quarter3: u4, + quarter4: u4, +}; + +// Point is a constant representing a structure containing two u32, "x" and "y". +// "x" has a default value, which wasn't possible in C. +const Point = struct { + x: u32 = 1, // default value + y: u32, +}; + +// Variable "p" is a new Point, with x = 1 (default value) and y = 2. +var p = Point{ .y = 2 }; + +// Fields are accessed as usual with the dot notation: variable.field. +print("p.x: {}\n", .{p.x}); // 1 +print("p.y: {}\n", .{p.y}); // 2 + + +// A structure can also contain public constants and functions. +const Point = struct { + pub const some_constant = 30; + + x: u32, + y: u32, + + // This function "init" creates a Point and returns it. + pub fn init() Point { + return Point{ .x = 0, .y = 0 }; + } +}; + + +// How to access a structure public constant. +// The value isn't accessed from an "instance" of the structure, but from the +// constant representing the structure definition (Point). +print("constant: {}\n", .{Point.some_constant}); + +// Having an "init" function is rather idiomatic in the standard library. +// More on that later. +var p = Point.init(); +print("p.x: {}\n", .{p.x}); // p.x = 0 +print("p.y: {}\n", .{p.y}); // p.y = 0 + + +// Structures often have functions to modify their state, similar to +// object-oriented programming. +const Point = struct { + const Self = @This(); // Refers to its own type (later called "Point"). + + x: u32, + y: u32, + + // Take a look at the signature. First argument is of type *Self: "self" is + // a pointer on the instance of the structure. + // This allows the same "dot" notation as in OOP, like "instance.set(x,y)". + // See the following example. + pub fn set(self: *Self, x: u32, y: u32) void { + self.x = x; + self.y = y; + } + + // Again, look at the signature. First argument is of type Self (not *Self), + // this isn't a pointer. In this case, "self" refers to the instance of the + // structure, but can't be modified. + pub fn getx(self: Self) u32 { + return self.x; + } + + // PS: two previous functions may be somewhat useless. + // Attributes can be changed directly, no need for accessor functions. + // It was just an example. +}; + +// Let's use the previous structure. +var p = Point{ .x = 0, .y = 0 }; // "p" variable is a Point. + +p.set(10, 30); // x and y attributes of "p" are modified via the "set" function. +print("p.x: {}\n", .{p.x}); // 10 +print("p.y: {}\n", .{p.y}); // 30 + +// In C: +// 1. We would have written something like: point_set(p, 10, 30). +// 2. Since all functions are in the same namespace, it would have been +// very cumbersome to create functions with different names for different +// structures. Many long names, painful to read. +// +// In Zig, structures provide namespaces for their own functions. +// Different structures can have the same names for their functions, +// which brings clarity. +``` + +### Tuples. +``` +// A tuple is a list of elements, possibly of different types. + +const foo = .{ "hello", true, 42 }; +// foo.len == 3 +``` + +### Enumerations. +``` + +const Type = enum { ok, not_ok }; + +const CardinalDirections = enum { North, South, East, West }; +const direction: CardinalDirections = .North; +const x = switch (direction) { + // shorthand for CardinalDirections.North + .North => true, + else => false +}; + +// Switch statements need exhaustiveness. +// WARNING: won't compile. East and West are missing. +const x = switch (direction) { + .North => true, + .South => true, +}; + + +// Switch statements need exhaustiveness. +// Won't compile: East and West are missing. +const x = switch (direction) { + .North => true, + .South => true, + .East, // Its value is the same as the following pattern: false. + .West => false, +}; + + +// Enumerations are like structures: they can have functions. +``` + +### Unions. +``` + +const Bar = union { + boolean: bool, + int: i16, + float: f32, +}; + +// Both syntaxes are equivalent. +const foo = Bar{ .int = 42 }; +const foo: Bar = .{ .int = 42 }; + +// Unions, like enumerations and structures, can have functions. +``` + +### Tagged unions. +``` + +// Unions can be declared with an enum tag type, allowing them to be used in +// switch expressions. + +const MaybeEnum = enum { + success, + failure, +}; + +const Maybe = union(MaybeEnum) { + success: u8, + failure: []const u8, +}; + +// First value: success! +const yay = Maybe{ .success = 42 }; +switch (yay) { + .success => |value| std.log.info("success: {}", .{value}), + .failure => |err_msg| std.log.info("failure: {}", .{err_msg}), +} + +// Second value: failure! :( +const nay = Maybe{ .failure = "I was too lazy" }; +switch (nay) { + .success => |value| std.log.info("success: {}", .{value}), + .failure => |err_msg| std.log.info("failure: {}", .{err_msg}), +} +``` + +### Defer and errdefer. +``` + +// Make sure that an action (single instruction or block of code) is executed +// before the end of the scope (function, block of code). +// Even on error, that action will be executed. +// Useful for memory allocations, and resource management in general. + +pub fn main() void { + // Should be executed at the end of the function. + defer print("third!\n", .{}); + + { + // Last element of its scope: will be executed right away. + defer print("first!\n", .{}); + } + + print("second!\n", .{}); +} + +fn hello_world() void { + defer print("end of function\n", .{}); // after "hello world!" + + print("hello world!\n", .{}); +} + +// errdefer executes the instruction (or block of code) only on error. +fn second_hello_world() !void { + errdefer print("2. something went wrong!\n", .{}); // if "foo" fails. + defer print("1. second hello world\n", .{}); // executed after "foo" + + try foo(); +} +// Defer statements can be seen as stacked: first one is executed last. +``` + +### Memory allocators. +Memory isn't managed directly in the standard library, instead an "allocator" is asked every time an operation on memory is required. +Thus, the standard library lets developers handle memory as they need, through structures called "allocators", handling all memory operations. + +**NOTE**: the choice of the allocator isn't in the scope of this document. +A whole book could be written about it. +However, here are some examples, to get an idea of what you can expect: +- page_allocator. + Allocate a whole page of memory each time we ask for some memory. + Very simple, very dumb, very wasteful. +- GeneralPurposeAllocator. + Get some memory first and manage some buckets of memory in order to + reduce the number of allocations. + A bit complex. Can be combined with other allocators. + Can detect leaks and provide useful information to find them. +- FixedBufferAllocator. + Use a fixed buffer to get its memory, don't ask memory to the kernel. + Very simple, limited and wasteful (can't deallocate), but very fast. +- ArenaAllocator. + Allow to free all allocated memory at once. + To use in combinations with another allocator. + Very simple way of avoiding leaks. + +A first example. +``` +// "!void" means the function doesn't return any value except for errors. +// In this case we try to allocate memory, and this may fail. +fn foo() !void { + // In this example we use a page allocator. + var allocator = std.heap.page_allocator; + + // "list" is an ArrayList of 8-bit unsigned integers. + // An ArrayList is a contiguous, growable list of elements in memory. + var list = try ArrayList(u8).initAllocated(allocator); + defer list.deinit(); // Free the memory at the end of the scope. Can't leak. + // "defer" allows to express memory release right after its allocation, + // regardless of the complexity of the function (loops, conditions, etc.). + + list.add(5); // Some memory is allocated here, with the provided allocator. + + for (list.items) |item| { + std.debug.print("item: {}\n", .{item}); + } +} +``` + +### Memory allocation combined with error management and defer. +``` + +fn some_memory_allocation_example() !void { + // Memory allocation may fail, so we "try" to allocate the memory and + // in case there is an error, the current function returns it. + var buf = try page_allocator.alloc(u8, 10); + // Defer memory release right after the allocation. + // Will happen even if an error occurs. + defer page_allocator.free(buf); + + // Second allocation. + // In case of a failure, the first allocation is correctly released. + var buf2 = try page_allocator.alloc(u8, 10); + defer page_allocator.free(buf2); + + // In case of failure, both previous allocations are correctly deallocated. + try foo(); + try bar(); + + // ... +} +``` + +### Memory allocators: a taste of the standard library. +``` + +// Allocators: 4 main functions to know +// single_value = create (type) +// destroy (single_value) +// slice = alloc (type, size) +// free (slice) + +// Page Allocator +fn page_allocator_fn() !void { + var slice = try std.heap.page_allocator.alloc(u8, 3); + defer std.heap.page_allocator.free(slice); + + // playing_with_a_slice(slice); +} + +// GeneralPurposeAllocator +fn general_purpose_allocator_fn() !void { + // GeneralPurposeAllocator has to be configured. + // In this case, we want to track down memory leaks. + const config = .{.safety = true}; + var gpa = std.heap.GeneralPurposeAllocator(config){}; + defer _ = gpa.deinit(); + + const allocator = gpa.allocator(); + + var slice = try allocator.alloc(u8, 3); + defer allocator.free(slice); + + // playing_with_a_slice(slice); +} + +// FixedBufferAllocator +fn fixed_buffer_allocator_fn() !void { + var buffer = [_]u8{0} ** 1000; // array of 1000 u8, all initialized at zero. + var fba = std.heap.FixedBufferAllocator.init(buffer[0..]); + // Side note: buffer[0..] is a way to create a slice from an array. + // Since the function takes a slice and not an array, this makes + // the type system happy. + + var allocator = fba.allocator(); + + var slice = try allocator.alloc(u8, 3); + // No need for "free", memory cannot be freed with a fixed buffer allocator. + // defer allocator.free(slice); + + // playing_with_a_slice(slice); +} + +// ArenaAllocator +fn arena_allocator_fn() !void { + // Reminder: arena doesn't allocate memory, it uses an inner allocator. + // In this case, we combine the arena allocator with the page allocator. + var arena = std.heap.arena_allocator.init(std.heap.page_allocator); + defer arena.deinit(); // end of function = all allocations are freed. + + var allocator = arena.allocator(); + + const slice = try allocator.alloc(u8, 3); + // No need for "free", memory will be freed anyway. + + // playing_with_a_slice(slice); +} + + +// Combining the general purpose and arena allocators. Both are very useful, +// and their combinations should be in everyone's favorite cookbook. +fn gpa_arena_allocator_fn() !void { + const config = .{.safety = true}; + var gpa = std.heap.GeneralPurposeAllocator(config){}; + defer _ = gpa.deinit(); + + const gpa_allocator = gpa.allocator(); + + var arena = arena_allocator.init(gpa_allocator); + defer arena.deinit(); + + const allocator = arena.allocator(); + + var slice = try allocator.alloc(u8, 3); + defer allocator.free(slice); + + // playing_with_a_slice(slice); +} +``` + +### Comptime. +``` + +// Comptime is a way to avoid the pre-processor. +// The idea is simple: run code at compilation. + +inline fn max(comptime T: type, a: T, b: T) T { + return if (a > b) a else b; +} + +var res = max(u64, 1, 2); +var res = max(f32, 10.50, 32.19); + + +// Comptime: creating generic structures. + +fn List(comptime T: type) type { + return struct { + items: []T, + + fn init() ... { ... } + fn deinit() ... { ... } + fn do() ... { ... } + }; +} + +const MyList = List(u8); + + +// use +var list = MyList{ + .items = ... // memory allocation +}; + +list.items[0] = 10; +``` + +### Conditional compilation. +``` +const available_os = enum { OpenBSD, Linux }; +const myos = available_os.OpenBSD; + + +// The following switch is based on a constant value. +// This means that the only possible outcome is known at compile-time. +// Thus, there is no need to build the rest of the possibilities. +// Similar to the "#ifdef" in C, but without requiring a pre-processor. +const string = switch (myos) { + .OpenBSD => "OpenBSD is awesome!", + .Linux => "Linux rocks!", +}; + +// Also works in this case. +const myprint = switch(myos) { + .OpenBSD => std.debug.print, + .Linux => std.log.info, +} +``` + +### Testing our functions. +``` +const std = @import("std"); +const expect = std.testing.expect; + +// Function to test. +pub fn some_function() bool { + return true; +} + +// This "test" block can be run with "zig test". +// It will test the function at compile-time. +test "returns true" { + expect(false == some_function()); +} +``` + +### Compiler built-ins. +The compiler has special functions called "built-ins", starting with an "@". +There are more than a hundred built-ins, allowing very low-level stuff: +- compile-time errors, logging, verifications +- type coercion and conversion, even in an unsafe way +- alignment management +- memory tricks (such as getting the byte offset of a field in a struct) +- calling functions at compile-time +- including C headers to transparently call C functions +- atomic operations +- embed files into the executable (@embedFile) +- frame manipulations (for async functions, for example) +- etc. + +Example: enums aren't integers, they have to be converted with a built-in. +``` +const Value = enum { zero, stuff, blah }; +if (@enumToInt(Value.zero) == 0) { ... } +if (@enumToInt(Value.stuff) == 1) { ... } +if (@enumToInt(Value.blah) == 2) { ... } +``` + + +### A few "not yourself in the foot" measures in the Zig language. + +- Namespaces: names conflicts are easily avoided. + In practice, that means an unified API between different structures (data types). +- Enumerations aren't integers. Comparing an enumeration to an integer requires a conversion. +- Explicit casts, coercion exists but is limited. + Types are slightly more enforced than in C, just a taste: + Pointers aren't integers, explicit conversion is necessary. + You won't lose precision by accident, implicit coercions are only authorized in case no precision can be lost. + Unions cannot be reinterpreted (in an union with an integer and a float, one cannot take a value for another by accident). + Etc. +- Removing most of the C undefined behaviors (UBs), and when the compiler encounters one, it stops. +- Slice and Array structures are preferred to pointers. + Types enforced by the compiler are less prone to errors than pointer manipulations. +- Numerical overflows produce an error, unless explicitly accepted using wrapping operators. +- Try and catch mechanism. + It's both handy, trivially implemented (simple error enumeration), and it takes almost no space nor computation time. +- Unused variables are considered as errors by the compiler. +- Many pointer types exist in order to represent what is pointed. + Example: is this a single value or an array, is the length known, etc. +- Structures need a value for their attributes, and it still is possible to give an undefined value (stack garbage), but at least it is explicitly undefined. + + +## Further Reading + +For a start, some concepts are presented on the [Zig learn website][ziglearn]. + +The [official website][zigdoc] provides a reference documentation to the language. + +For now, documentation for standard library is WIP. + +[ziglang]: https://ziglang.org +[ziglearn]: https://ziglearn.org/ +[zigdoc]: https://ziglang.org/documentation/ |