diff options
-rw-r--r-- | README.markdown | 2 | ||||
-rw-r--r-- | c.html.markdown | 54 | ||||
-rw-r--r-- | coldfusion.html.markdown | 321 | ||||
-rw-r--r-- | csharp.html.markdown | 49 | ||||
-rw-r--r-- | css.html.markdown | 258 | ||||
-rw-r--r-- | fr-fr/objective-c-fr.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/python3-fr.html.markdown | 723 | ||||
-rw-r--r-- | haml.html.markdown | 25 | ||||
-rw-r--r-- | java.html.markdown | 48 | ||||
-rw-r--r-- | json.html.markdown | 6 | ||||
-rw-r--r-- | latex.html.markdown | 231 | ||||
-rw-r--r-- | objective-c.html.markdown | 2 | ||||
-rw-r--r-- | python.html.markdown | 2 | ||||
-rw-r--r-- | python3.html.markdown | 6 | ||||
-rw-r--r-- | ru-ru/objective-c-ru.html.markdown | 2 | ||||
-rw-r--r-- | ru-ru/php-ru.html.markdown | 61 | ||||
-rw-r--r-- | ruby.html.markdown | 10 | ||||
-rw-r--r-- | rust.html.markdown | 4 | ||||
-rw-r--r-- | sass.html.markdown | 232 | ||||
-rw-r--r-- | tr-tr/objective-c-tr.html.markdown | 2 | ||||
-rw-r--r-- | vi-vn/objective-c-vi.html.markdown | 2 | ||||
-rw-r--r-- | vi-vn/ruby-vi.html.markdown | 549 |
22 files changed, 2407 insertions, 184 deletions
diff --git a/README.markdown b/README.markdown index 774797d5..28fa5093 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ commented code and explained as they go. ... to write more inline code tutorials. Just grab an existing file from this repo and copy the formatting (don't worry, it's all very simple). -Make a new file, send a pull request, and if it passes muster I'll get it up pronto. +Make a new file, send a pull request, and if it passes master I'll get it up pronto. Remember to fill in the "contributors" fields so you get credited properly! diff --git a/c.html.markdown b/c.html.markdown index db2ac930..3339032f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - ["Marco Scannadinari", "https://marcoms.github.io"] + - ["himanshu", "https://github.com/himanshu81494"] --- @@ -27,6 +28,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line... */ // ...not this one! // Constants: #define <keyword> +// Constants are written in all-caps out of convention, not requirement #define DAYS_IN_YEAR 365 // Enumeration constants are also ways to declare constants. @@ -56,6 +58,15 @@ int add_two_ints(int x1, int x2); // function prototype // Your program's entry point is a function called // main with an integer return type. int main(void) { + // your program +} + +// The command line arguments used to run your program are also passed to main +// argc being the number of arguments - your program's name counts as 1 +// argv is an array of character arrays - containing the arguments themselves +// argv[0] = name of your program, argv[1] = first argument, etc. +int main (int argc, char** argv) +{ // print output using printf, for "print formatted" // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 @@ -306,7 +317,29 @@ int main(void) { exit(-1); break; } - + /* + using "goto" in C + */ + typedef enum { false, true } bool; + // for C don't have bool as data type :( + bool disaster = false; + int i, j; + for(i=0;i<100;++i) + for(j=0;j<100;++j) + { + if((i + j) >= 150) + disaster = true; + if(disaster) + goto error; + } + error : + printf("Error occured at i = %d & j = %d.\n", i, j); + /* + https://ideone.com/GuPhd6 + this will print out "Error occured at i = 52 & j = 99." + */ + + /////////////////////////////////////// // Typecasting /////////////////////////////////////// @@ -472,7 +505,24 @@ char c[] = "This is a test."; str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ - +/* +as we can return only one variable +to change values of more than one variables we use call by reference +*/ +void swapTwoNumbers(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} +/* +int first = 10; +int second = 20; +printf("first: %d\nsecond: %d\n", first, second); +swapTwoNumbers(&first, &second); +printf("first: %d\nsecond: %d\n", first, second); +// values will be swapped +*/ // if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown new file mode 100644 index 00000000..e2f0737d --- /dev/null +++ b/coldfusion.html.markdown @@ -0,0 +1,321 @@ +--- +language: ColdFusion +contributors: + - ["Wayne Boka", "http://wboka.github.io"] +filename: LearnColdFusion.cfm +--- + +ColdFusion is a scripting language for web development. +[Read more here.](http://www.adobe.com/products/coldfusion-family.html) + +```ColdFusion + +<em>HTML tags have been provided for output readability</em> + +<!--- Comments start with "<!---" and end with "--->" ---> +<!--- + Comments can + also + span + multiple lines +---> + +<!--- CFML tags have a similar format to HTML tags. ---> +<h1>Simple Variables</h1> +<!--- Variable Declaration: Variables are loosely typed, similar to javascript ---> +<p>Set <b>myVariable</b> to "myValue"</p> +<cfset myVariable = "myValue" /> +<p>Set <b>myNumber</b> to 3.14</p> +<cfset myNumber = 3.14 /> + +<!--- Displaying simple data ---> +<!--- Use <cfoutput> for simple values such as strings, numbers, and expressions ---> +<p>Display <b>myVariable</b>: <cfoutput>#myVariable#</cfoutput></p><!--- myValue ---> +<p>Display <b>myNumber</b>: <cfoutput>#myNumber#</cfoutput></p><!--- 3.14 ---> + +<hr /> + +<h1>Complex Variables</h1> +<!--- Declaring complex variables ---> +<!--- Declaring an array of 1 dimension: literal or bracket notation ---> +<p>Set <b>myArray1</b> to an array of 1 dimension using literal or bracket notation</p> +<cfset myArray1 = [] /> +<!--- Declaring an array of 1 dimension: function notation ---> +<p>Set <b>myArray2</b> to an array of 1 dimension using function notation</p> +<cfset myArray2 = ArrayNew(1) /> + +<!--- Outputting complex variables ---> +<p>Contents of <b>myArray1</b></p> +<cfdump var="#myArray1#" /> <!--- An empty array object ---> +<p>Contents of <b>myArray2</b></p> +<cfdump var="#myArray2#" /> <!--- An empty array object ---> + +<!--- Operators ---> +<!--- Arithmetic ---> +<h1>Operators</h1> +<h2>Arithmetic</h2> +<p>1 + 1 = <cfoutput>#1 + 1#</cfoutput></p> +<p>10 - 7 = <cfoutput>#10 - 7#<br /></cfoutput></p> +<p>15 * 10 = <cfoutput>#15 * 10#<br /></cfoutput></p> +<p>100 / 5 = <cfoutput>#100 / 5#<br /></cfoutput></p> +<p>120 % 5 = <cfoutput>#120 % 5#<br /></cfoutput></p> +<p>120 mod 5 = <cfoutput>#120 mod 5#<br /></cfoutput></p> + +<hr /> + +<!--- Comparison ---> +<h2>Comparison</h2> +<h3>Standard Notation</h3> +<p>Is 1 eq 1? <cfoutput>#1 eq 1#</cfoutput></p> +<p>Is 15 neq 1? <cfoutput>#15 neq 1#</cfoutput></p> +<p>Is 10 gt 8? <cfoutput>#10 gt 8#</cfoutput></p> +<p>Is 1 lt 2? <cfoutput>#1 lt 2#</cfoutput></p> +<p>Is 10 gte 5? <cfoutput>#10 gte 5#</cfoutput></p> +<p>Is 1 lte 5? <cfoutput>#1 lte 5#</cfoutput></p> + +<h3>Alternative Notation</h3> +<p>Is 1 == 1? <cfoutput>#1 eq 1#</cfoutput></p> +<p>Is 15 != 1? <cfoutput>#15 neq 1#</cfoutput></p> +<p>Is 10 > 8? <cfoutput>#10 gt 8#</cfoutput></p> +<p>Is 1 < 2? <cfoutput>#1 lt 2#</cfoutput></p> +<p>Is 10 >= 5? <cfoutput>#10 gte 5#</cfoutput></p> +<p>Is 1 <= 5? <cfoutput>#1 lte 5#</cfoutput></p> + +<hr /> + +<!--- Control Structures ---> +<h1>Control Structures</h1> + +<cfset myCondition = "Test" /> + +<p>Condition to test for: "<cfoutput>#myCondition#</cfoutput>"</p> + +<cfif myCondition eq "Test"> + <cfoutput>#myCondition#. We're testing.</cfoutput> +<cfelseif myCondition eq "Production"> + <cfoutput>#myCondition#. Proceed Carefully!!!</cfoutput> +<cfelse> + myCondition is unknown +</cfif> + +<hr /> + +<!--- Loops ---> +<h1>Loops</h1> +<h2>For Loop</h2> +<cfloop from="0" to="10" index="i"> + <p>Index equals <cfoutput>#i#</cfoutput></p> +</cfloop> + +<h2>For Each Loop (Complex Variables)</h2> + +<p>Set <b>myArray3</b> to [5, 15, 99, 45, 100]</p> + +<cfset myArray3 = [5, 15, 99, 45, 100] /> + +<cfloop array="#myArray3#" index="i"> + <p>Index equals <cfoutput>#i#</cfoutput></p> +</cfloop> + +<p>Set <b>myArray4</b> to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]</p> + +<cfset myArray4 = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"] /> + +<cfloop array="#myArray4#" index="s"> + <p>Index equals <cfoutput>#s#</cfoutput></p> +</cfloop> + +<h2>Switch Statement</h2> + +<p>Set <b>myArray5</b> to [5, 15, 99, 45, 100]</p> + +<cfset myArray5 = [5, 15, 99, 45, 100] /> + +<cfloop array="#myArray5#" index="i"> + <cfswitch expression="#i#"> + <cfcase value="5,15,45" delimiters=","> + <p><cfoutput>#i#</cfoutput> is a multiple of 5.</p> + </cfcase> + <cfcase value="99"> + <p><cfoutput>#i#</cfoutput> is ninety-nine.</p> + </cfcase> + <cfdefaultcase> + <p><cfoutput>#i#</cfoutput> is not 5, 15, 45, or 99.</p> + </cfdefaultcase> + </cfswitch> +</cfloop> + +<hr /> + +<h1>Converting types</h1> + +<style> + table.table th, table.table td { + border: 1px solid #000000; + padding: 2px; + } + + table.table th { + background-color: #CCCCCC; + } +</style> + +<table class="table" cellspacing="0"> + <thead> + <tr> + <th>Value</th> + <th>As Boolean</th> + <th>As number</th> + <th>As date-time</th> + <th>As string</th> + </tr> + </thead> + <tbody> + <tr> + <th>"Yes"</th> + <td>TRUE</td> + <td>1</td> + <td>Error</td> + <td>"Yes"</td> + </tr> + <tr> + <th>"No"</th> + <td>FALSE</td> + <td>0</td> + <td>Error</td> + <td>"No"</td> + </tr> + <tr> + <th>TRUE</th> + <td>TRUE</td> + <td>1</td> + <td>Error</td> + <td>"Yes"</td> + </tr> + <tr> + <th>FALSE</th> + <td>FALSE</td> + <td>0</td> + <td>Error</td> + <td>"No"</td> + </tr> + <tr> + <th>Number</th> + <td>True if Number is not 0; False otherwise.</td> + <td>Number</td> + <td>See "Date-time values" earlier in this chapter.</td> + <td>String representation of the number (for example, "8").</td> + </tr> + <tr> + <th>String</th> + <td>If "Yes", True <br>If "No", False <br>If it can be converted to 0, False <br>If it can be converted to any other number, True</td> + <td>If it represents a number (for example, "1,000" or "12.36E-12"), it is converted to the corresponding number.</td> + <td>If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. <br>If it is an ODBC date, time, or timestamp (for example "{ts '2001-06-14 11:30:13'}", or if it is expressed in a standard U.S. date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value. <br>Days of the week or unusual punctuation result in an error. <br>Dashes, forward-slashes, and spaces are generally allowed.</td> + <td>String</td> + </tr> + <tr> + <th>Date</th> + <td>Error</td> + <td>The numeric value of the date-time object.</td> + <td>Date</td> + <td>An ODBC timestamp.</td> + </tr> + </tbody> +</table> + +<hr /> + +<h1>Components</h1> + +<em>Code for reference (Functions must return something to support IE)</em> + +<pre> +<cfcomponent> + <cfset this.hello = "Hello" /> + <cfset this.world = "world" /> + + <cffunction name="sayHello"> + <cfreturn this.hello & ", " & this.world & "!" /> + </cffunction> + + <cffunction name="setHello"> + <cfargument name="newHello" type="string" required="true" /> + + <cfset this.hello = arguments.newHello /> + + <cfreturn true /> + </cffunction> + + <cffunction name="setWorld"> + <cfargument name="newWorld" type="string" required="true" /> + + <cfset this.world = arguments.newWorld /> + + <cfreturn true /> + </cffunction> + + <cffunction name="getHello"> + <cfreturn this.hello /> + </cffunction> + + <cffunction name="getWorld"> + <cfreturn this.world /> + </cffunction> +</cfcomponent> +</pre> + +<cfset this.hello = "Hello" /> +<cfset this.world = "world" /> + +<cffunction name="sayHello"> + <cfreturn this.hello & ", " & this.world & "!" /> +</cffunction> + +<cffunction name="setHello"> + <cfargument name="newHello" type="string" required="true" /> + + <cfset this.hello = arguments.newHello /> + + <cfreturn true /> +</cffunction> + +<cffunction name="setWorld"> + <cfargument name="newWorld" type="string" required="true" /> + + <cfset this.world = arguments.newWorld /> + + <cfreturn true /> +</cffunction> + +<cffunction name="getHello"> + <cfreturn this.hello /> +</cffunction> + +<cffunction name="getWorld"> + <cfreturn this.world /> +</cffunction> + + +<b>sayHello()</b> +<cfoutput><p>#sayHello()#</p></cfoutput> +<b>getHello()</b> +<cfoutput><p>#getHello()#</p></cfoutput> +<b>getWorld()</b> +<cfoutput><p>#getWorld()#</p></cfoutput> +<b>setHello("Hola")</b> +<cfoutput><p>#setHello("Hola")#</p></cfoutput> +<b>setWorld("mundo")</b> +<cfoutput><p>#setWorld("mundo")#</p></cfoutput> +<b>sayHello()</b> +<cfoutput><p>#sayHello()#</p></cfoutput> +<b>getHello()</b> +<cfoutput><p>#getHello()#</p></cfoutput> +<b>getWorld()</b> +<cfoutput><p>#getWorld()#</p></cfoutput> +``` + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) diff --git a/csharp.html.markdown b/csharp.html.markdown index 02650038..28da9fe5 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] - ["Wouter Van Schandevijl", "http://github.com/laoujin"] + - ["Jo Pearce", "http://github.com/jdpearce"] filename: LearnCSharp.cs --- @@ -418,6 +419,42 @@ on a new line! ""Wow!"", the masses cried"; // Item is an int Console.WriteLine(item.ToString()); } + + // YIELD + // Usage of the "yield" keyword indicates that the method it appears in is an Iterator + // (this means you can use it in a foreach loop) + public static IEnumerable<int> YieldCounter(int limit = 10) + { + for (var i = 0; i < limit; i++) + yield return i; + } + + // which you would call like this : + public static void PrintYieldCounterToConsole() + { + foreach (var counter in YieldCounter()) + Console.WriteLine(counter); + } + + // you can use more than one "yield return" in a method + public static IEnumerable<int> ManyYieldCounter() + { + yield return 0; + yield return 1; + yield return 2; + yield return 3; + } + + // you can also use "yield break" to stop the Iterator + // this method would only return half of the values from 0 to limit. + public static IEnumerable<int> YieldCounterWithBreak(int limit = 10) + { + for (var i = 0; i < limit; i++) + { + if (i > limit/2) yield break; + yield return i; + } + } public static void OtherInterestingFeatures() { @@ -443,6 +480,9 @@ on a new line! ""Wow!"", the masses cried"; // ?? is syntactic sugar for specifying default value (coalesce) // in case variable is null int notNullable = nullable ?? 0; // 0 + + // ?. is an operator for null-propogation - a shorthand way of checking for null + nullable?.Print(); // Use the Print() extension method if nullable isn't null // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: var magic = "magic is a string, at compile time, so you still get type safety"; @@ -750,7 +790,7 @@ on a new line! ""Wow!"", the masses cried"; // It's also possible to define custom Indexers on objects. // All though this is not entirely useful in this example, you - // could do bicycle[0] which yields "chris" to get the first passenger or + // could do bicycle[0] which returns "chris" to get the first passenger or // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) private string[] passengers = { "chris", "phil", "darren", "regina" }; @@ -761,7 +801,7 @@ on a new line! ""Wow!"", the masses cried"; } set { - return passengers[i] = value; + passengers[i] = value; } } @@ -837,7 +877,8 @@ on a new line! ""Wow!"", the masses cried"; bool Broken { get; } // interfaces can contain properties as well as methods & events } - // Class can inherit only one other class, but can implement any amount of interfaces + // Class can inherit only one other class, but can implement any amount of interfaces, however + // the base class name must be the first in the list and all interfaces follow class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; @@ -876,7 +917,7 @@ on a new line! ""Wow!"", the masses cried"; ## Topics Not Covered * Attributes - * async/await, yield, pragma directives + * async/await, pragma directives * Web Development * ASP.NET MVC & WebApi (new) * ASP.NET Web Forms (old) diff --git a/css.html.markdown b/css.html.markdown index 811767e6..e3ca94d9 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -5,25 +5,20 @@ contributors: - ["Marco Scannadinari", "https://github.com/marcoms"] - ["Geoffrey Liu", "https://github.com/g-liu"] - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] filename: learncss.css --- -In the early days of the web there were no visual elements, just pure text. But with the -further development of browsers, fully visual web pages also became common. -CSS is the standard language that exists to keep the separation between -the content (HTML) and the look-and-feel of web pages. +In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common. -In short, what CSS does is to provide a syntax that enables you to target -different elements on an HTML page and assign different visual properties to them. +CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page. -Like any other languages, CSS has many versions. Here we focus on CSS2.0, -which is not the most recent version, but is the most widely supported and compatible version. +CSS lets you target different elements on an HTML page and assign different visual properties to them. -**NOTE:** Because the outcome of CSS consists of visual effects, in order to -learn it, you need try everything in a -CSS playground like [dabblet](http://dabblet.com/). -The main focus of this article is on the syntax and some general tips. +This guide has been written for CSS 2, though CSS 3 is fast becoming popular. +**NOTE:** Because CSS produces visual results, in order to learn it, you need try everything in a CSS playground like [dabblet](http://dabblet.com/). +The main focus of this article is on the syntax and some general tips. ```css /* comments appear inside slash-asterisk, just like this line! @@ -33,219 +28,212 @@ The main focus of this article is on the syntax and some general tips. ## SELECTORS #################### */ -/* Generally, the primary statement in CSS is very simple */ +/* the selector is used to target an element on a page. selector { property: value; /* more properties...*/ } -/* the selector is used to target an element on page. - -You can target all elements on the page using asterisk! */ -* { color:red; } - /* -Given an element like this on the page: +Here is an example element: -<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' /> +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> */ -/* you can target it by its name */ -.some-class { } +/* You can target it using one of its CSS classes */ +.class1 { } -/* or by both classes! */ -.some-class.class2 { } +/* or both classes! */ +.class1.class2 { } -/* or by its element name */ +/* or its name */ div { } /* or its id */ -#someId { } +#anID { } -/* or by the fact that it has an attribute! */ +/* or using the fact that it has an attribute! */ [attr] { font-size:smaller; } /* or that the attribute has a specific value */ [attr='value'] { font-size:smaller; } -/* start with a value (CSS3) */ +/* starts with a value (CSS 3) */ [attr^='val'] { font-size:smaller; } -/* or ends with (CSS3) */ +/* or ends with a value (CSS 3) */ [attr$='ue'] { font-size:smaller; } -/* or select by one of the values from the whitespace separated list (CSS3) */ -[otherAttr~='foo'] { font-size:smaller; } +/* or contains a value in a space-separated list */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } -/* or value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D) */ +/* or contains a value in a dash-separated list, ie, "-" (U+002D) */ [otherAttr|='en'] { font-size:smaller; } -/* and more importantly you can combine these together -- there shouldn't be -any space between different parts because that makes it to have another -meaning. */ +/* You can concatenate different selectors to create a narrower selector. Don't + put spaces between them. */ div.some-class[attr$='ue'] { } -/* you can also select an element based on its parent. */ - -/* an element which is direct child of an element (selected the same way) */ -div.some-parent > .class-name {} +/* You can select an element which is a child of another element */ +div.some-parent > .class-name { } -/* or any of its parents in the tree - the following basically means any element that has class "class-name" - and is child of a div with class name "some-parent" IN ANY DEPTH */ -div.some-parent .class-name {} +/* or a descendant of another element. Children are the direct descendants of + their parent element, only one level down the tree. Descendants can be any + level down the tree. */ +div.some-parent .class-name { } -/* warning: the same selector without space has another meaning. - can you say what? */ -div.some-parent.class-name {} +/* Warning: the same selector without a space has another meaning. + Can you guess what? */ +div.some-parent.class-name { } -/* you also might choose to select an element based on its direct - previous sibling */ -.i-am-before + .this-element { } +/* You may also select an element based on its adjacent sibling */ +.i-am-just-before + .this-element { } -/* or any sibling before this */ -.i-am-any-before ~ .this-element {} +/* or any sibling preceding it */ +.i-am-any-element-before ~ .this-element { } -/* There are some pseudo classes that allows you to select an element - based on its page behaviour (rather than page structure) */ +/* There are some selectors called pseudo classes that can be used to select an + element when it is in a particular state */ -/* for example for when an element is hovered */ -selector:hover {} +/* for example, when the cursor hovers over an element */ +selector:hover { } -/* or a visited link */ -selected:visited {} +/* or a link has been visited */ +selector:visited { } -/* or not visited link */ -selected:link {} +/* or hasn't been visited */ +selected:link { } -/* or an input element which is focused */ -selected:focus {} +/* or an element in focus */ +selected:focus { } +/* At appropriate places, an asterisk may be used as a wildcard to select every + element */ +* { } /* all elements */ +.parent * { } /* all descendants */ +.parent > * { } /* all children */ /* #################### ## PROPERTIES #################### */ selector { - - /* Units */ - width: 50%; /* in percent */ - font-size: 2em; /* times current font-size */ - width: 200px; /* in pixels */ - font-size: 20pt; /* in points */ - width: 5cm; /* in centimeters */ - min-width: 50mm; /* in millimeters */ - max-width: 5in; /* in inches. max-(width|height) */ - height: 0.2vh; /* times vertical height of browser viewport (CSS3) */ - width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */ - min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */ - max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */ - + + /* Units of length can be absolute or relative. */ + + /* Relative units */ + width: 50%; /* percentage of parent element width */ + font-size: 2em; /* multiples of element's original font-size */ + font-size: 2rem; /* or the root element's font-size */ + font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ + font-size: 2vh; /* or its height */ + font-size: 2vmin; /* whichever of a vh or a vw is smaller */ + font-size: 2vmax; /* or greater */ + + /* Absolute units */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimeters */ + min-width: 50mm; /* millimeters */ + max-width: 5in; /* inches */ + /* Colors */ - background-color: #F6E; /* in short hex */ - background-color: #F262E2; /* in long hex format */ - background-color: tomato; /* can be a named color */ - background-color: rgb(255, 255, 255); /* in rgb */ - background-color: rgb(10%, 20%, 50%); /* in rgb percent */ - background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb (CSS3) */ - background-color: transparent; /* see thru */ - background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */ - background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */ - - - /* Images */ - background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */ - + color: #F6E; /* short hex format */ + color: #FF66EE; /* long hex format */ + color: tomato; /* a named color */ + color: rgb(255, 255, 255); /* as rgb values */ + color: rgb(10%, 20%, 50%); /* as rgb percentages */ + color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */ + color: transparent; /* equivalent to setting the alpha to 0 */ + color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */ + + /* Images as backgrounds of elements */ + background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ + /* Fonts */ font-family: Arial; - font-family: "Courier New"; /* if name has space it appears in single or double quotes */ - font-family: "Courier New", Trebuchet, Arial, sans-serif; /* if first one was not found - browser uses the second font, and so forth */ + /* if the font family name has a space, it must be quoted */ + font-family: "Courier New"; + /* if the first one is not found, the browser uses the next, and so on */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; } - ``` ## Usage -Save any CSS you want in a file with extension `.css`. +Save a CSS stylesheet with the extension `.css`. ```xml -<!-- you need to include the css file in your page's <head>: --> +<!-- You need to include the css file in your page's <head>. This is the + recommended method. Refer to http://stackoverflow.com/questions/8284365 --> <link rel='stylesheet' type='text/css' href='path/to/style.css' /> -<!-- you can also include some CSS inline in your markup. However it is highly -recommended to avoid this. --> +<!-- You can also include some CSS inline in your markup. --> <style> a { color: purple; } </style> -<!-- or directly set CSS properties on the element. -This has to be avoided as much as you can. --> +<!-- Or directly set CSS properties on the element. --> <div style="border: 1px solid red;"> </div> - ``` -## Precedence +## Precedence or Cascade -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. -In these cases, one of the rules takes precedence over others. +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. + +This process is called cascading, hence the name Cascading Style Sheets. Given the following CSS: ```css -/*A*/ +/* A */ p.class1[attr='value'] -/*B*/ -p.class1 {} +/* B */ +p.class1 { } -/*C*/ -p.class2 {} +/* C */ +p.class2 { } -/*D*/ -p {} +/* D */ +p { } -/*E*/ +/* E */ p { property: value !important; } - ``` and the following markup: ```xml -<p style='/*F*/ property:value;' class='class1 class2' attr='value'> -</p> +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> ``` -The precedence of style is as followed: -Remember, the precedence is for each **property**, not for the entire block. +The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. -* `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. -* `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` - but it appears last. -* Then is `B` -* and lastly is `D`. +* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage. +* `F` is next, because it is an inline style. +* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`. +* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`. +* `B` is next. +* `D` is the last one. ## Compatibility -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatibility -of what you use in CSS with your target browsers. +Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature. -[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. +## Resources -To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource. +* To run a quick compatibility check, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) ## Further Reading -* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) -* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) * [QuirksMode CSS](http://www.quirksmode.org/css/) * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 69f4d8f9..4e31c4bf 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -14,7 +14,7 @@ lang: fr-fr L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. -```objective_c +```objective-c // Les commentaires sur une seule ligne commencent par // /* diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown new file mode 100644 index 00000000..04d0a55d --- /dev/null +++ b/fr-fr/python3-fr.html.markdown @@ -0,0 +1,723 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Gnomino", "https://github.com/Gnomino"] +filename: learnpython3-fr.py +lang: fr-fr +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des +langages les populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. +C'est tout simplement du pseudo-code exécutable. + +L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] + +Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 + +```python + +# Un commentaire d'une ligne commence par un dièse + +""" Les chaînes de caractères peuvent être écrites + avec 3 guillemets doubles ("), et sont souvent + utilisées comme des commentaires. +""" + +#################################################### +## 1. Types de données primaires et opérateurs +#################################################### + +# On a des nombres +3 # => 3 + +# Les calculs sont ce à quoi on s'attend +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Sauf pour la division qui retourne un float (nombre à virgule flottante) +35 / 5 # => 7.0 + +# Résultats de divisions entières tronqués pour les nombres positifs et négatifs +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quand on utilise un float, le résultat est un float +3 * 2.0 # => 6.0 + +# Modulo (reste de la division) +7 % 3 # => 1 + +# Exponentiation (x**y, x élevé à la puissance y) +2**4 # => 16 + +# Forcer la priorité de calcul avec des parenthèses +(1 + 3) * 2 # => 8 + +# Les valeurs booléennes sont primitives +True +False + +# Négation avec not +not True # => False +not False # => True + +# Opérateurs booléens +# On note que "and" et "or" sont sensibles à la casse +True and False #=> False +False or True #=> True + +# Utilisation des opérations booléennes avec des entiers : +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# On vérifie une égalité avec == +1 == 1 # => True +2 == 1 # => False + +# On vérifie une inégalité avec != +1 != 1 # => False +2 != 1 # => True + +# Autres opérateurs de comparaison +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# On peut enchaîner les comparaisons +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie +# si les objets ont la même valeur. +a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] +b = a # b pointe sur a +b is a # => True, a et b pointent sur le même objet +b == a # => True, les objets a et b sont égaux +b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] +b is a # => False, a et b ne pointent pas sur le même objet +b == a # => True, les objets a et b ne pointent pas sur le même objet + +# Les chaînes (ou strings) sont créées avec " ou ' +"Ceci est une chaine" +'Ceci est une chaine aussi.' + +# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. +"Hello " + "world!" # => "Hello world!" +# On peut aussi le faire sans utiliser '+' +"Hello " "world!" # => "Hello world!" + +# On peut traîter une chaîne comme une liste de caractères +"This is a string"[0] # => 'T' + +# .format peut être utilisé pour formatter des chaînes, comme ceci: +"{} peuvent etre {}".format("Les chaînes", "interpolées") + +# On peut aussi réutiliser le même argument pour gagner du temps. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# On peut aussi utiliser des mots clés pour éviter de devoir compter. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# Si votre code doit aussi être compatible avec Python 2.5 et moins, +# vous pouvez encore utiliser l'ancienne syntaxe : +"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") + + +# None est un objet +None # => None + +# N'utilisez pas "==" pour comparer des objets à None +# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. +"etc" is None # => False +None is None # => True + +# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. +# Toutes les autres valeurs valent True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Python a une fonction print pour afficher du texte +print("I'm Python. Nice to meet you!") + +# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. +# Utilisez l'argument optionnel end pour changer ce caractère de fin. +print("Hello, World", end="!") # => Hello, World! + +# Pas besoin de déclarer des variables avant de les définir. +# La convention est de nommer ses variables avec des minuscules_et_underscores +some_var = 5 +some_var # => 5 + +# Tenter d'accéder à une variable non définie lève une exception. +# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. +une_variable_inconnue # Lève une NameError + +# Les listes permettent de stocker des séquences +li = [] +# On peut initialiser une liste pré-remplie +other_li = [4, 5, 6] + +# On ajoute des objets à la fin d'une liste avec .append +li.append(1) # li vaut maintenant [1] +li.append(2) # li vaut maintenant [1, 2] +li.append(4) # li vaut maintenant [1, 2, 4] +li.append(3) # li vaut maintenant [1, 2, 4, 3] +# On enlève le dernier élément avec .pop +li.pop() # => 3 et li vaut maintenant [1, 2, 4] +# Et on le remet +li.append(3) # li vaut de nouveau [1, 2, 4, 3] + +# Accès à un élément d'une liste : +li[0] # => 1 +# Accès au dernier élément : +li[-1] # => 3 + +# Accéder à un élément en dehors des limites lève une IndexError +li[4] # Lève une IndexError + +# On peut accéder à une intervalle avec la syntaxe "slice" +# (c'est un rang du type "fermé/ouvert") +li[1:3] # => [2, 4] +# Omettre les deux premiers éléments +li[2:] # => [4, 3] +# Prendre les trois premiers +li[:3] # => [1, 2, 4] +# Sélectionner un élément sur deux +li[::2] # =>[1, 4] +# Avoir une copie de la liste à l'envers +li[::-1] # => [3, 4, 2, 1] +# Pour des "slices" plus élaborées : +# li[debut:fin:pas] + +# Faire une copie d'une profondeur de un avec les "slices" +li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. + +# Enlever des éléments arbitrairement d'une liste +del li[2] # li is now [1, 2, 3] + +# On peut additionner des listes +# Note: les valeurs de li et other_li ne sont pas modifiées. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concaténer des listes avec "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Vérifier la présence d'un objet dans une liste avec "in" +1 in li # => True + +# Examiner la longueur avec "len()" +len(li) # => 6 + + +# Les tuples sont comme des listes mais sont immuables. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Lève une TypeError + +# Note : un tuple de taille un doit avoir une virgule après le dernier élément, +# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> + +# On peut utiliser la plupart des opérations des listes sur des tuples. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Vous pouvez décomposer des tuples (ou des listes) dans des variables +a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 +# Les tuples sont créés par défaut sans parenthèses +d, e, f = 4, 5, 6 +# Voyez comme il est facile d'intervertir deux valeurs : +e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 + + +# Créer un dictionnaire : +empty_dict = {} +# Un dictionnaire pré-rempli : +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note : les clés des dictionnaires doivent être de types immuables. +# Elles doivent être convertibles en une valeur constante pour une recherche rapide. +# Les types immuables incluent les ints, floats, strings et tuples. +invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. + +# On trouve une valeur avec [] +filled_dict["one"] # => 1 + +# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer +# de list() pour avoir une liste Note: l'ordre n'est pas garanti. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# On obtient toutes les valeurs sous forme d'un itérable avec "values()". +# Là aussi, il faut utiliser list() pour avoir une liste. +# Note : l'ordre n'est toujours pas garanti. +list(filled_dict.values()) # => [3, 2, 1] + + +# On vérifie la présence d'une clé dans un dictionnaire avec "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# L'accès à une clé non-existente lève une KeyError +filled_dict["four"] # KeyError + +# On utilise "get()" pour éviter la KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. +filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 + +# Ajouter à un dictionnaire +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # une autre méthode + +# Enlever des clés d'un dictionnaire avec del +del filled_dict["one"] # Enlever la clé "one" de filled_dict. + + +# Les sets stockent des ensembles +empty_set = set() +# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. +some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} + +# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. +invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# On peut changer un set : +filled_set = some_set + +# Ajouter un objet au set : +filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} + +# Chercher les intersections de deux sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# On fait l'union de sets avec | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# On fait la différence de deux sets avec - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# On vérifie la présence d'un objet dans un set avec in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Structures de contrôle et Itérables +#################################################### + +# On crée juste une variable +some_var = 5 + +# Voici une condition "si". L'indentation est significative en Python! +# Affiche: "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # La clause elif ("sinon si") est optionelle + print("some_var is smaller than 10.") +else: # La clause else ("sinon") l'est aussi. + print("some_var is indeed 10.") + + +""" +Les boucles "for" itèrent sur une liste +Affiche: + chien est un mammifère + chat est un mammifère + souris est un mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser format() pour interpoler des chaînes formattées + print("{} est un mammifère".format(animal)) + +""" +"range(nombre)" retourne un itérable de nombres +de zéro au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(debut, fin)" retourne un itérable de nombre +de debut à fin. +Affiche: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(debut, fin, pas)" retourne un itérable de nombres +de début à fin en incrémentant de pas. +Si le pas n'est pas indiqué, la valeur par défaut est 1. +Affiche: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + +Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Raccourci pour x = x + 1 + +# On gère les exceptions avec un bloc try/except +try: + # On utilise "raise" pour lever une erreur + raise IndexError("Ceci est une erreur d'index") +except IndexError as e: + pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. +except (TypeError, NameError): + pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. +else: # Clause optionelle des blocs try/except. Doit être après tous les except. + print("Tout va bien!") # Uniquement si aucune exception n'est levée. +finally: # Éxécuté dans toutes les circonstances. + print("On nettoie les ressources ici") + +# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python offre une abstraction fondamentale : l'Iterable. +# Un itérable est un objet pouvant être traîté comme une séquence. +# L'objet retourné par la fonction range() est un itérable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable + +# On peut boucler dessus +for i in our_iterable: + print(i) # Affiche one, two, three + +# Cependant, on ne peut pas accéder aux éléments par leur adresse. +our_iterable[1] # Lève une TypeError + +# Un itérable est un objet qui sait créer un itérateur. +our_iterator = iter(our_iterable) + +# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. +# On passe à l'élément suivant avec "next()". +next(our_iterator) #=> "one" + +# Il garde son état quand on itère. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator +next(our_iterator) # Lève une StopIteration + +# On peut mettre tous les éléments d'un itérateur dans une liste avec list() +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Fonctions +#################################################### + +# On utilise "def" pour créer des fonctions +def add(x, y): + print("x est {} et y est {}".format(x, y)) + return x + y # On retourne une valeur avec return + +# Appel d'une fonction avec des paramètres : +add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 + +# Une autre manière d'appeller une fonction : avec des arguments +add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. + +# Définir une fonction qui prend un nombre variable d'arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# On peut aussi définir une fonction qui prend un nombre variable de paramètres. +def keyword_args(**kwargs): + return kwargs + +# Appelons la pour voir ce qu'il se passe : +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# On peut aussi faire les deux à la fois : +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appelant des fonctions, on peut aussi faire l'inverse : +# utiliser * pour étendre un tuple de paramètres +# et ** pour étendre un dictionnaire d'arguments. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # équivalent à foo(1, 2, 3, 4) +all_the_args(**kwargs) # équivalent à foo(a=3, b=4) +all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) + +# Retourne plusieurs valeurs (avec un tuple) +def swap(x, y): + return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. + # (Note: on peut aussi utiliser des parenthèses) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses + +# Portée des fonctions : +x = 5 + +def setX(num): + # La variable locale x n'est pas la même que la variable globale x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # la variable globale x est maintenant 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Mais aussi des fonctions anonymes +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Il y a aussi des fonctions de base +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. +# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# On utilise l'opérateur "classe" pour définir une classe +class Human: + + # Un attribut de la classe. Il est partagé par toutes les instances de la classe. + species = "H. sapiens" + + # L'initialiseur de base. Il est appelé quand la classe est instanciée. + # Note : les doubles underscores au début et à la fin sont utilisés pour + # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. + # Les méthodes (ou objets ou attributs) comme: __init__, __str__, + # __repr__ etc. sont appelés méthodes magiques. + # Vous ne devriez pas inventer de noms de ce style. + def __init__(self, name): + # Assigner l'argument à l'attribut de l'instance + self.name = name + + # Une méthode de l'instance. Toutes prennent "self" comme premier argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Une méthode de classe est partagée avec entre les instances + # Ils sont appelés avec la classe comme premier argument + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appelée sans référence à une instance ni à une classe. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantier une classe +i = Human(name="Ian") +print(i.say("hi")) # affiche "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() # => "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print(math.sqrt(16)) # => 4 + +# On peut importer des fonctions spécifiques d'un module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# On peut importer toutes les fonctions d'un module +# Attention: ce n'est pas recommandé. +from math import * + +# On peut raccourcir un nom de module +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Les modules Python sont juste des fichiers Python. +# Vous pouvez écrire les vôtres et les importer. Le nom du module +# est le nom du fichier. + +# On peut voir quels fonctions et objets un module définit +import math +dir(math) + + +#################################################### +## 7. Avancé +#################################################### + +# Les générateurs aident à faire du code paresseux (lazy) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un générateur crée des valeurs à la volée. +# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque +# itération. Cela signifie que les valeurs supérieures à 15 ne seront pas traîtées par +# double_numbers. +# Note : range est un générateur aussi. +# Créer une liste 1-900000000 prendrait beaucoup de temps +# On met un underscore à la fin d'un nom de variable normalement réservé par Python. +range_ = range(1, 900000000) +# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorateurs +# Dans cet exemple, beg enveloppe say +# Beg appellera say. Si say_please vaut True le message retourné sera changé +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # affiche Can you buy me a beer? +print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( +``` + +## Prêt pour encore plus ? + +### En ligne et gratuit (en anglais) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Livres (en anglais) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/haml.html.markdown b/haml.html.markdown index 847714e6..0948e9ef 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -122,11 +122,36 @@ $ haml input_file.haml output_file.html if book do %p This is a book + +/ Adding ordered / unordered list +%ul + %li + =item1 + =item2 / Again, no need to add the closing tags to the block, even for the Ruby. Indentation will take care of that for you. +/ ------------------------------------------- +/ Inserting Table with bootstrap classes +/ ------------------------------------------- + +%table.table.table-hover + %thead + %tr + %th Header 1 + %th Header 2 + + %tr + %td Value1 + %td value2 + + %tfoot + %tr + %td + Foot value + / ------------------------------------------- / Inline Ruby / Ruby interpolation diff --git a/java.html.markdown b/java.html.markdown index 67e5494e..35ec57d8 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] - ["Simon Morgan", "http://sjm.io/"] - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] filename: LearnJava.java --- @@ -95,11 +96,13 @@ public class LearnJava { // Note: Java has no unsigned types. // Float - Single-precision 32-bit IEEE 754 Floating Point + // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; // f or F is used to denote that this variable value is of type float; // otherwise it is treated as double. // Double - Double-precision 64-bit IEEE 754 Floating Point + // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; // Boolean - true & false @@ -115,6 +118,34 @@ public class LearnJava { final double E; E = 2.71828; + + // BigInteger - Immutable arbitrary-precision integers + // + // BigInteger is a data type that allows programmers to manipulate + // integers longer than 64-bits. Integers are stored as an array of + // of bytes and are manipulated using functions built into BigInteger + // + // BigInteger can be initialized using an array of bytes or a string. + + BigInteger fooBigInteger = new BigDecimal(fooByteArray); + + + // BigDecimal - Immutable, arbitrary-precision signed decimal number + // + // A BigDecimal takes two parts: an arbitrary precision integer + // unscaled value and a 32-bit integer scale + // + // BigDecimal allows the programmer complete control over decimal + // rounding. It is recommended to use BigDecimal with currency values + // and where exact decimal percision is required. + // + // BigDecimal can be initialized with an int, long, double or String + // or by initializing the unscaled value (BigInteger) and scale (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + + // Strings String fooString = "My String Is Here!"; @@ -286,6 +317,23 @@ public class LearnJava { break; } System.out.println("Switch Case Result: " + monthString); + + // Starting in Java 7 and above, switching Strings works like this: + String myAnswer = "maybe"; + switch(myAnswer){ + case "yes": + System.out.println("You answered yes."); + break; + case "no": + System.out.println("You answered no."); + break; + case "maybe": + System.out.println("You answered maybe."); + break; + default: + System.out.println("You answered " + myAnswer); + break; + } // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. diff --git a/json.html.markdown b/json.html.markdown index a1629137..b5e36090 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -4,6 +4,7 @@ filename: learnjson.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] --- As JSON is an extremely simple data-interchange format, this is most likely going @@ -16,6 +17,11 @@ but they should be avoided for better compatibility. For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. +Data types supported by JSON includes: numbers, string, boolean, array, object and null. +Supporting browsers are: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. +JSON file type for JSON files is ".json". The MIME type for JSON text is "application/json" +Drawbacks of JSON include lack of type definition and some sort of DTD. + ```json { "key": "value", diff --git a/latex.html.markdown b/latex.html.markdown new file mode 100644 index 00000000..146e8d45 --- /dev/null +++ b/latex.html.markdown @@ -0,0 +1,231 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +filename: learn-latex.tex +--- +% All comment lines start with % +% There are no multi-line comments + +% LaTeX is NOT a "What You See Is What You Get" word processing software like +% MS Word, or OpenOffice Writer + +% Every Latex command starts with a backslash (\) + +% LaTeX documents start with a defining the type of document it's compiling +% Other document types include book, report, presentations, etc. +% The options for the document appear in the [] brackets. In this case +% it specifies we want to use 12pt font. +\documentclass[12pt]{article} + +% Next we define the packages the document uses. +% If you want to include graphics, colored text, or +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% I'm going to include the float and caption packages for figures. +\usepackage{caption} +\usepackage{float} + +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Now we're ready to begin the document +% Everything before this line is called "The Preamble" +\begin{document} +% if we set the author, date, title fields, we can have LaTeX +% create a title page for us. +\maketitle + +% Most research papers have abstract, you can use the predefined commands for this. +% This should appear in its logical order, therefore, after the top matter, +% but before the main sections of the body. +% This command is available in the document classes article and report. +\begin{abstract} + LaTex documentation written as LaTex! How novel and totally not my idea! +\end{abstract} + +% Section commands are intuitive. +% All the titles of the sections are added automatically to the table of contents. +\section{Introduction} +Hello, my name is Colton and together we're going to explore LaTeX! + +\section{Another section} +This is the text for another section. I think it needs a subsection. + +\subsection{This is a subsection} % Subsections are also intuitive. +I think we need another one + +\subsubsection{Pythagoras} +Much better now. +\label{subsec:pythagoras} + +% By using the asterisk we can suppress Latex's inbuilt numbering. +% This works for other Latex commands as well. +\section*{This is an unnumbered section} +However not all sections have to be numbered! + +\section{Some Text notes} +LaTeX is generally pretty good about placing text where it should go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to +the source code. \\ + +\section{Lists} +Lists are one of the easiest things to create in Latex! I need to go shopping +tomorrow, so let's make a grocery list. +\begin{enumerate} % This creates an "enumerate" environment. + % \item tells the enumerate to increment + \item Salad. + \item 27 watermelon. + \item A single jackrabbit. + % we can even override the item number by using [] + \item[how many?] Medium sized squirt guns. + + Not a list item, but still part of the enumerate. + +\end{enumerate} % All environments must have an end. + +\section{Math} + +One of the primary uses for LaTeX is to produce academic articles or +technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! \\ + +Math has many symbols, far beyond what you can find on a keyboard; +Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ + +Sets and relations play a vital role in many mathematical research papers. +Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. +% We can enter math-mode from text mode with the $ signs. +% The opposite also holds true. Variable can also be rendered in math-mode. + +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +I haven't found a Greek letter that yet that Latex doesn't know about! + +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc. +have per-defined LaTeX commands. +Let's write an equation to see how it's done: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fractions(Numerator-denominators) can be written in these forms: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatively complex fractions can be written as +% \frac{numerator}{denominator} +$\frac{n!}{k!(n - k)!}$ \\ + +We can also insert equations in an "equation environment." + +% Display math with the equation 'environment' +\begin{equation} % enters math-mode + c^2 = a^2 + b^2. + \label{eq:pythagoras} % for referencing +\end{equation} % all \begin statements must have an end statement + +We can then reference our new equation! +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +figures, equations, sections, etc. + +Summations and Integrals are written with sum and int commands: + +% Some latex compilers will complain if there are blank lines +% In an equation environment. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figures} + +Let's insert a Figure. Figure placement can get a little tricky. +I definitely have to lookup the placement options each time. + +\begin{figure}[H] % H here denoted the placement option. + \centering % centers the figure on the page + % Inserts a figure scaled to 0.8 the width of the page. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Commented out for compilation purposes. Please use your imagination. + \caption{Right triangle with sides $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Table} +We can also insert Tables in the same way as figures. + +\begin{table}[H] + \caption{Caption for the Table.} + % the {} arguments below describe how each row of the table is drawn. + % Again, I have to look these up. Each. And. Every. Time. + \begin{tabular}{c|cc} + Number & Last Name & First Name \\ % Column rows are separated by $ + \hline % a horizontal line + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Coming soon + +\section{Getting Latex to not compile something (i,e, Source Code)} +Let's say we want to include some code into our Latex document, +we would then need Latex to not try and interpret that text and +instead just print it to the document. We do this we a verbatim +environment. + +% There are other packages that exist (i.e. minty, lstlisting, etc.) +% but verbatim is the bare-bones basic one. +\begin{verbatim} + print("Hello World!") + a%b; % look! We can use % signs in verbatim. + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Compiling} + +By now you're probably wondering how to compile this fabulous document +and look at the glorious glory that is a Latex pdf. +(yes, this document actually does compiles). \\ +Getting to the final document using LaTeX consists of the following steps: + \begin{enumerate} + \item Write the document in plain text (the "source code"). + \item Compile source code to produce a pdf. + The compilation step looks something like this (in Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +software. So, you get to see Step 1, but not Step 2 completely. +Step 2 is still happening behind the scenes. + +You write all your formatting information in plain text in Step 1. +The compilation part in Step 2 takes care of producing the document in the +format you defined in Step 1. + +\section{End} + +That's all for now! + +% end the document +\end{document} +``` +## More on 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/) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 89901308..cf6bf780 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -13,7 +13,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```objective_c +```objective-c // Single-line comments start with // /* diff --git a/python.html.markdown b/python.html.markdown index 6cfb5dca..5b36083d 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -142,7 +142,7 @@ bool("") # => False #################################################### # Python has a print statement -print "I'm Python. Nice to meet you!" +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores diff --git a/python3.html.markdown b/python3.html.markdown index cd1a83cc..87fa0b70 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -569,8 +569,8 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] #################################################### -# We subclass from object to get a class. -class Human(object): +# We use the "class" operator to get a class +class Human: # A class attribute. It is shared by all instances of this class species = "H. sapiens" @@ -664,8 +664,6 @@ def double_numbers(iterable): # Instead of generating and returning all values at once it creates one in each # iteration. This means values bigger than 15 wont be processed in # double_numbers. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made # We use a trailing underscore in variable names when we want to use a name that # would normally collide with a python keyword range_ = range(1, 900000000) diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index ddff2e5c..8eac4ddb 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -17,7 +17,7 @@ Cocoa Touch. Он является объектно-ориентированным языком программирования общего назначения, который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C. -```objective_c +```objective-c // Однострочные комментарии начинаются с // /* diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 53b2f916..5672aa90 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["SlaF", "https://github.com/SlaF"] + - ["Corpsee", "https://github.com/corpsee"] lang: ru-ru filename: learnphp-ru.php --- @@ -14,8 +15,8 @@ filename: learnphp-ru.php ```php <?php // PHP код должен быть заключен в теги <?php -// Если ваш файл содержит только PHP код, то можно -// пропустить закрывающийся ?> +// Если ваш файл содержит только PHP-код, то можно +пропустить закрывающий ?> // А так начинаются комментарии @@ -30,10 +31,10 @@ filename: learnphp-ru.php print('Hello '); // Напечатать "Hello " без перевода строки // () необязательно применять для print и echo -echo "World\n"; // Печатать "World" и перейти на новую строку. +echo "World\n"; // Напечатать "World" и перейти на новую строку. // (все утверждения должны заканчиваться ;) -// Любые символы за пределами закрывающегося тега выводятся автоматически: +// Любые символы за пределами закрывающего тега выводятся автоматически: ?> Hello World Again! <?php @@ -46,7 +47,7 @@ Hello World Again! // Переменные начинаются с символа $. // Правильное имя переменной начинается с буквы или знака подчеркивания, // и может содержать любые цифры, буквы, или знаки подчеркивания. -// Не рекомендуется использовать кирилические символы в именах (прим. пер.) +// Не рекомендуется использовать кириллические символы в именах (прим. пер.) // Логические значения нечувствительны к регистру $boolean = true; // или TRUE или True @@ -56,7 +57,7 @@ $boolean = false; // или FALSE или False $int1 = 12; // => 12 $int2 = -12; // => -12- $int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) -$int4 = 0x0F; // => 15 (ведущие символы 0x означает шестнадцатеричное число) +$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число) // Дробные числа $float = 1.234; @@ -126,7 +127,7 @@ echo 'This outputs '.FOO; // Все массивы в PHP - это ассоциативные массивы или хеши, -// Ассоциативные массивы, известные в других языках как хеш-карты. +// Ассоциативные массивы, известные в других языках как HashMap. // Работает во всех версиях РHP $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); @@ -199,13 +200,13 @@ assert($c > $b); // больше assert($a <= $b); // меньше или равно assert($c >= $d); // больше или равно -// Следующие утверждения истинны если переменные имеют одинаковый тип. +// Следующие утверждения истинны, если переменные имеют одинаковый тип. assert($c === $d); assert($a !== $d); assert(1 == '1'); assert(1 !== '1'); -// Переменные могут изменять тип, в зависимости от их использования. +// Переменные могут изменять тип в зависимости от их использования. $integer = 1; echo $integer + $integer; // => 2 @@ -235,7 +236,7 @@ $var = null; // Null $integer = 10; $boolen = settype($integer, "string") // теперь $integer имеет строковый тип -// settype возвращает true - если преобразование удалось и false в противном случае +// settype возвращает true, если преобразование удалось и false в противном случае /******************************** * Управляющие структуры @@ -311,7 +312,7 @@ echo "\n"; for ($x = 0; $x < 10; $x++) { echo $x; -} // Prints "0123456789" +} // Напечатает "0123456789" echo "\n"; @@ -320,7 +321,7 @@ $wheels = ['bicycle' => 2, 'car' => 4]; // Циклы foreach могут обходить массивы foreach ($wheels as $wheel_count) { echo $wheel_count; -} // Prints "24" +} // Напечатает "24" echo "\n"; @@ -337,14 +338,14 @@ while ($i < 5) { break; // Exit out of the while loop } echo $i++; -} // Prints "012" +} // Напечатает "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { continue; // Skip this iteration of the loop } echo $i; -} // Prints "0124" +} // Напечатает "0124" /******************************** @@ -369,7 +370,7 @@ function add ($x, $y = 1) { // $y по умолчанию равно 1 echo add(4); // => 5 echo add(4, 2); // => 6 -// $result недоступна за пределами функции +// $result недоступен за пределами функции // print $result; // Выдает предупреждение // Начиная с PHP 5.3 вы можете объявлять анонимные функции: @@ -402,19 +403,19 @@ echo $function_name(1, 2); // => 3 /******************************** - * Includes + * Включения */ <?php // PHP код внутри включаемого файла должен начинаться с тега PHP. include 'my-file.php'; -// Код в файле my-file.php теперь доступен в текущем в текущем пространстве имен. -// Если файл не удалось включить, будет выдано предупреждение. +// Код в файле my-file.php теперь доступен в текущем пространстве имен. +// Если файл не удалось подключить, то будет выдано предупреждение. include_once 'my-file.php'; -// Если код в файле my-file.php уже был включен, он не будет включен повторно. -// Это предотвращает ошибку повторного включения файла. +// Если код в файле my-file.php уже был подключен, он не будет подключен повторно. +// Это предотвращает ошибку повторного подключения файла. require 'my-file.php'; require_once 'my-file.php'; @@ -422,7 +423,7 @@ require_once 'my-file.php'; // Same as include(), except require() will cause a fatal error if the // file cannot be included. // Действует также как и include(), но если файл не удалось подключить, -// функция выдает неисправимую ошибку +// функция выдает фатальную ошибку // Содержимое файла my-include.php: <?php @@ -452,19 +453,19 @@ class MyClass static $staticVar = 'static'; - // Properties must declare their visibility + // Свойства объявляются с указанием их видимости public $property = 'public'; public $instanceProp; - protected $prot = 'protected'; // Accessible from the class and subclasses - private $priv = 'private'; // Accessible within the class only + protected $prot = 'protected'; // Свойство доступно только потомкам и самому классу + private $priv = 'private'; // Свойство доступно только самому классу - // Create a constructor with __construct + // Конструктор описывается с помощью __construct public function __construct($instanceProp) { - // Access instance variables with $this + // Доступ к эземпляру класса с помощью $this $this->instanceProp = $instanceProp; } - // Methods are declared as functions inside a class + // Методы объявляются как функции принадлежащие классу public function myMethod() { print 'MyClass'; @@ -502,7 +503,7 @@ class MyOtherClass extends MyClass echo $this->prot; } - // Override a method + // Переопределение родительского метода function myMethod() { parent::myMethod(); @@ -595,7 +596,7 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Трейты */ -// Трейты появились в PHP 5.4.0 и объявляются при помощи ключевого слова trait +// Трейты появились в PHP 5.4 и объявляются при помощи ключевого слова trait trait MyTrait { @@ -611,7 +612,7 @@ class MyTraitfulClass } $cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$cls->myTraitMethod(); // Напечатает "I have MyTrait" /******************************** diff --git a/ruby.html.markdown b/ruby.html.markdown index fe142365..c10255d8 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,6 +12,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", https://github.com/ghalley] --- @@ -39,6 +40,7 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 2**5 #=> 32 +5 % 3 #=> 2 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -160,6 +162,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can be indexed # From the front array[0] #=> 1 +array.first #=> 1 array[12] #=> nil # Like arithmetic, [var] access @@ -170,6 +173,7 @@ array.[] 12 #=> nil # From the end array[-1] #=> 5 +array.last #=> 5 # With a start index and length array[2, 3] #=> [3, 4, 5] @@ -264,6 +268,12 @@ hash.each do |key, value| puts "#{key} is #{value}" end +# If you still need and index you can use "each_with_index" and define an index +# variable +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" diff --git a/rust.html.markdown b/rust.html.markdown index b2854b0c..d0c56b4a 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -287,9 +287,9 @@ fn main() { // While a value is mutably borrowed, it cannot be accessed at all. let mut var2 = 4; let ref_var2: &mut i32 = &mut var2; - *ref_var2 += 2; + *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2 - println!("{}", *ref_var2); // 6 + println!("{}", *ref_var2); // 6 , //var2 would not compile. //ref_var2 is of type &mut i32, so //stores a reference to an i32 not the value. // var2 = 2; // this would not compile because `var2` is borrowed } ``` diff --git a/sass.html.markdown b/sass.html.markdown new file mode 100644 index 00000000..509aee9b --- /dev/null +++ b/sass.html.markdown @@ -0,0 +1,232 @@ +--- +language: sass +filename: learnsass.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] +--- + +Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. +Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code. + +Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. +This tutorial is written using SCSS. + + +```scss + + +//Single line comments are removed when Sass is compiled to CSS. + +/*Multi line comments are preserved. */ + + + +/*Variables +==============================*/ + + + +/* You can store a CSS value (such as a color) in a variable. +Use the '$' symbol to create a variable. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. +Now if you want to change a color, you only have to make the change once.*/ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* This would compile to: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* This is much more maintainable than having to change the color +each time it appears throughout your stylesheet. */ + + + +/*Mixins +==============================*/ + + + +/* If you find you are writing the same code for more than one +element, you might want to store that code in a mixin. + +Use the '@mixin' directive, plus a name for your mixin.*/ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* You can use the mixin with '@include' and the mixin name. */ + +div { + @include center; + background-color: $primary-color; +} + +/*Which would compile to: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* You can use mixins to create a shorthand property. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/*Which you can invoke by passing width and height arguments. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* This compiles to: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + + +/*Extend (Inheritance) +==============================*/ + + + +/*Extend is a way to share the properties of one selector with another. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Compiles to: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + + + + +/*Nesting +==============================*/ + + + +/*Sass allows you to nest selectors within selectors */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' will be replaced by the parent selector. */ +/* You can also nest pseudo-classes. */ +/* Keep in mind that over-nesting will make your code less maintainable. +For example: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compiles to: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + + +``` + + + +## SASS or Sass? +Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym. +Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets". + + +## Practice Sass +If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/). +You can use either syntax, just go into the settings and select either Sass or SCSS. + + +## Further reading +* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles. diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown index f27cbf08..727f973e 100644 --- a/tr-tr/objective-c-tr.html.markdown +++ b/tr-tr/objective-c-tr.html.markdown @@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C programlama diline Smalltalk stilinde mesajlaşma ekler. -```objective_c +```objective-c // Tek satır yorum // işaretleri ile başlar /* diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index c97bb560..38e418e9 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```objective_c
+```objective-c
// Chú thích dòng đơn bắt đầu với //
/*
diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown new file mode 100644 index 00000000..73382100 --- /dev/null +++ b/vi-vn/ruby-vi.html.markdown @@ -0,0 +1,549 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Vinh Nguyen", "http://rubydaily.net"] +lang: vi-vn + +--- + +```ruby +# Đây là một comment + +=begin +Đây là một comment nhiều dòng +Không ai dùng cách này +Bạn không nên dùng +=end + +# Đầu tiên và quan trọng nhất: Mọi thứ là đối tượng. + +# Các con số là các đối tượng. + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Một vài bài toán số học căn bản +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# Số học vừa là các cú pháp thân thiện cho việc gọi +# một hàm trên một đối tượng +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Các giá trị đặc biệt là các đối tượng +nil # Ở đây không có gì để xem +true # luôn đúng +false # luôn sai + +nil.class #=> Lớp Nil +true.class #=> Lớp True +false.class #=> Lớp False + +# So sánh bằng +1 == 1 #=> true +2 == 1 #=> false + +# So sánh không bằng +1 != 1 #=> false +2 != 1 #=> true + +# Ngoài chính false, thì nil là một giá trị khác của false + +!nil #=> true +!false #=> true +!0 #=> false + +# Các loại so sánh khác +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Các toán tử logic +true && false #=> false +true || false #=> true +!true #=> false + + +# Có các cách khác của các toán tử logic với mức thấp hơn +# Chúng được sử dụng như các cấu trúc điều khiển luồng nối các mệnh đề +# với nhau cho đến khi một trong số chúng trả về đúng hoặc sai. + +# `do_something_else` chỉ được gọi nếu như hàm `do_something` thành công. +do_something() and do_something_else() +# `log_error` chỉ được gọi nếu hàm `do_something` không thành công. +do_something() or log_error() + + +# Các chuỗi là các đối tượng + +'I am a string'.class #=> String +"I am a string too".class #=> String + +placeholder = 'use string interpolation' +"I can #{placeholder} when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" + +# Nên đưa các chuỗi vào trong dấu nháy đơn +# Ngoài ra dấu nháy kép được sử dụng trong tính toán. + +# Nối các chuỗi, nhưng không nối với các số. +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Xuất ra ngoài màn hình +puts "I'm printing!" + +# Các biến +x = 25 #=> 25 +x #=> 25 + +# Chú ý về việc gán các giá trị được trả về vào biến. +# Điều này có nghĩa là bạn có thể gán nhiều biến. + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Theo quy ước, dùng snake_case cho các tên của biến. +snake_case = true + +# Dùng để mô tả tên các biến +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Ký tự (là các đối tượng) +# Các ký tự là bất biến, như các biến hằng số chỉ đến các số nguyên. +# Chúng thường xuyên được sử dụng thay cho các chuỗi để chuyển đổi các giá +# trị hiệu quả. + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Các mảng + +# Đây là một mảng +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Các mảng có thể chứa nhiều phần tử khác nhau + +[1, 'hello', false] #=> [1, "hello", false] + +# Có thể truy cập các giá trị của mảng thông qua các chỉ mục +array[0] #=> 1 +array[12] #=> nil + +# Giống như số học, sử dụng [biến] là một cú pháp thông dụng +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Lấy phần tử cuối cùng +array[-1] #=> 5 + +# Bắt đầu từ chỉ mục và số phần tử cần lấy +array[2, 3] #=> [3, 4, 5] + +# Đảo ngược một mảng +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Lấy một khoảng +array[1..3] #=> [2, 3, 4] + +# Thêm phần tử vào mảng bằng cách này +array << 6 #=> [1, 2, 3, 4, 5, 6] +# Hoặc cách này +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Kiểm tra phần tử có tồn tại trong mảng +array.include?(1) #=> true + +# Băm là phần chính của Ruby với các cặp khoá/giá trị +# Băm được biểu thị bằng dấu ngoặc nhọn: +hash = { 'color' => 'green', 'number' => 5 } + +hash.keys #=> ['color', 'number'] + +# Băm có thể được truy cập nhanh chóng thông qua khoá +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Khoá không tồn tại sẽ trả về nil +hash['nothing here'] #=> nil + +# Kể từ Ruby bản 1.9, đây là một cú pháp đặc biệt, sử dụng symbol như khoá + +new_hash = { defcon: 3, action: true } + +new_hash.keys #=> [:defcon, :action] + +# Kiểm tra khoá hoặc giá trị có tồn tại hay không +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + +# Mẹo: Cả Mảng và Băm đều là Enumberable +# Chúng cùng chia sẻ rất nhiều phương thức hữu ích như each, map, count... + +# Cấu trúc điều khiển + +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# TUY NHIÊN, không ai sử dụng vòng lặp for. +# Thay vào đó, ban nên dùng phương thức "each" và truyền vào đó một khối. +# Một khối là một loạt các mã mà bạn có thể truyền +# cho một phương thức giống như each. +# Nó tương tự với lambda, các hàm ẩn danh hoặc closures trong các ngôn ngữ +# lập trình khác. +# +# Phương thức "each" cho một khoản sẽ chạy qua từng phần tử của khoảng đó. +# Khối được truyền vào là một số đếm như là tham số. +# Gọi một method "each" với một khối sẽ trông như thế này: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Bạn cũng có thể bao khối trong các dấu ngoặc nhọn. +(1..5).each { |counter| puts "iteration #{counter}" } + +# Các nội dung của cấu trúc dữ liệu cũng có thể được lặp bằng each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# Cases cũng được dùng cho các dãy +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Xử lý ngoại lệ: +begin + # Code ở đây có thể sẽ đưa ra một ngoại lệ. + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end + +# Hàm + +def double(x) + x * 2 +end + +# Hàm (và tất cả các khối) được mặc định giá trị trả về ở mệnh đề cuối. +double(2) #=> 4 + +# Dấu ngoặc là một tuỳ chọn cho một kết quả rõ ràng. +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Các đối số được chia cắt bởi dấu phẩy. +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Tất cả các hàm có thể có một tham số tuỳ chọn. +# Nó có thể được gọi với từ khóa "yield". +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# Bạn có thể truyền một khối đến một hàm +# Dấu "&" được đánh dấu đến một khối +def guests(&block) + block.call 'some_argument' +end + +# Bạn có thể truyền một danh sách các tham số, nó sẽ được chuyển thành mảng. +# Thông qua việc sử dụng dấu *. +def guests(*array) + array.each { |guest| puts guest } +end + +# Định nghĩ một lớp thông qua từ khoá class. +class Human + + # Một biến class. Nó được chia sẽ cho tất cả các instance của lớp này. + @@species = 'H. sapiens' + + # Các khởi tạo căn bản + def initialize(name, age = 0) + # Gán đối số đến biến instance "name" + @name = name + # Nếu không có age, sẽ lấy giá trị mặc định trong danh sách đối số. + @age = age + end + + # Hàm nhập giá trị căn bản + def name=(name) + @name = name + end + + # Hàm lấy giá trị căn bản + def name + @name + end + + # Các hàm trên có thể được gọn lại bằng cách dùng hàm attr_accessor + attr_accessor :name + + # Các hàm nhận/lấy cũng có thể được tạo riêng như sau: + attr_reader :name + attr_writer :name + + # Một hàm lớp dùng self để phân biệt với hàm instance. + # Nó chỉ có thể được gọi trên lớp. + def self.say(msg) + puts msg + end + + def species + @@species + end +end + + +# Khởi tạo một lớp +jim = Human.new('Jim Halpert') + +dwight = Human.new('Dwight K. Schrute') + +# Hãy gọi một cặp các hàm. +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Gọi một hàm lớp +Human.say('Hi') #=> "Hi" + +# Phạm vi của biến được định nghĩa bởi cách chúng ta đặt tên cho chúng. +# Các biến bắt đầu với dấu $ là biến toàn cục. +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# Các biến bắt đầu với dấu @ là biến phạm vi. +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# Các biến bắt đầu với dấu @@ có pham vi là trong một lớp. +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Các biến bắt đầu với ký tự viết hoa là biến hằng. +Var = "I'm a constant" +defined? Var #=> "constant" + +# Lớp cũng là một đối tượng trong Ruby. Bởi vậy lớp có các biến instance. +# Biến lớp được chia sẽ trong lớp và các lớp kế thừa nó. + +# Lớp cơ sở +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Lớp kế thừa +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Các biến lớp instance không được chia sẽ trong lớp kế thừa. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# Include một module sẽ đưa các hàm của module thành instances của lớp. +# Extend một module sẽ đưa các hàm của module thành các biến của lớp. + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Hàm hồi quy được thực hiện khi include và extend một module. + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Các nguồn tham khảo thêm. + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. |