From a3818d119ea677e1992fa05d5ab130a012086a56 Mon Sep 17 00:00:00 2001 From: Chaitanya Krishna Ande Date: Thu, 23 Apr 2015 13:54:52 +0200 Subject: initial version for latex --- latex.html.markdown | 133 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 latex.html.markdown diff --git a/latex.html.markdown b/latex.html.markdown new file mode 100644 index 00000000..cc1d99cb --- /dev/null +++ b/latex.html.markdown @@ -0,0 +1,133 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] +filename: learn-latex.tex +--- + +LaTeX is known to create aesthetically pleasing documents without you worrying +about the formatting. It is also great if one wants to create documents +containing a lot of mathematics. Getting a good document is very easy, but +getting it to behave exactly the way you want can be a bit hairy. + + +```latex +% 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 + +% Getting to the final document using LaTeX consists of the following steps: +% 1. Write the document in plain text +% 2. Compile plain text document to produce a pdf +% The compilation step looks something like this: +% $ pdflatex your-tex-file.tex your-tex-file.pdf +% 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. + +% For Step 1, it is best if you get a good text editor +% On Windows, probably Notepad++ +% For Step 2, you will need to get a TeX distribution +% Windows: MikTeX +% MacOS: MacTeX +% Linux: Should be available from your package manager + +% Let's get to the final pdf document as soon as possible + +% Choose the kind of document you want to write. +% You can replace article with book, report, etc. +\documentclass{article} +% begin the document +\begin{document} +% end the document +\end{document} +% Compile to pdf +% Now, you already have a final document which of course it is empty. +% Everything that you write is between the +% \begin{document} +% \end{document} + +% Start a new document from here. +% Let's do a decent document +\documentclass{article} +% required for inserting images +\usepackage{graphicx} +% begin the document +\begin{document} +% set the title (optional) +\title{Title of the document} +% set the author (optional) +\author{Chaitanya Krishna Ande} + +% make the title (optional) +\maketitle + +% start the first section +\section{Introduction} + +% write your text +This is the introduction. + +% start another section +\section{Another section} +This is the text for another section. + +% another section with subsection +\section{Section with sub-section} +Text for the section. +\subsection{Sub-section} +Let's discuss the Pythagoras theorem. +\subsubsection{Pythagoras Theorm} +% for cross-reference +\label{subsec:pythagoras} + +% notice how the sections and sub-sections are automatically numbered + +% Some math +% Inline math within $ $ +For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, $b$ and $c$, where $c$ is the +hypotenuse, the following holds: +% Display math with the equation 'environment' +\begin{equation} + c^2 = a^2 + b^2. + % for cross-reference + \label{eq:pythagoras} +\end{equation} + +% Let's cross-reference the equation +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. + +\subsubsection{Figure} +Let's insert a Figure. + +\begin{figure} + \centering + \includegraphics[width=0.8\linewidth]{right-triangle.png} + \caption{Right triangle with sides a, b, c} + \label{fig:right-triangle} +\end{figure} + + +\subsubsection{Table} +Let's insert a Table. + +\begin{table} +\caption{Caption for the Table.} +\begin{tabular}{ccc} +Number & Last Name & First Name \\ +\hline +1 & Biggus & Dickus \\ +2 & Monty & Python +\end{tabular} +\end{table} + +% end the document +\end{document} +``` -- cgit v1.2.3 From 1d43bd50c3e9305abfe95eade590ef5828f9ad5c Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 12:29:08 -0400 Subject: Initial placeholder --- coldfusion.html.markdown | 1 + 1 file changed, 1 insertion(+) create mode 100644 coldfusion.html.markdown diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown new file mode 100644 index 00000000..3c0b0b06 --- /dev/null +++ b/coldfusion.html.markdown @@ -0,0 +1 @@ +Coming soon -- cgit v1.2.3 From 9d33f091701013236055b553d7eb7a8dba3df65e Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 16:52:07 -0400 Subject: Update coldfusion.html.markdown Adds variable declaration, comparison operators, and if/else control structures --- coldfusion.html.markdown | 395 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 394 insertions(+), 1 deletion(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 3c0b0b06..4c734920 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -1 +1,394 @@ -Coming soon +--- +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 +" ---> + + + + + + + + + + +#myVariable# +#myNumber# + + + + + + + + + + + + + +#1 + 1# = 2 +#10 - 8# = 2 +#1 * 2# = 2 +#10 / 5# = 2 +#12 % 5# = 0 + + +#1 eq 1# +#15 neq 1# +#10 gt 8# +#1 lt 2# +#10 gte 5# +#1 lte 5# + + + + + #myCondition# + + #myCondition#. Proceed Carefully!!! + + myCondition is unknown + +``` + + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. -- cgit v1.2.3 From 1e7f639755042211ce0f10953153d6d341dbecab Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 16:52:47 -0400 Subject: Update coldfusion.html.markdown Fixes a typo --- coldfusion.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 4c734920..be08733e 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -26,7 +26,7 @@ ColdFusion is a scripting language for web development. #myVariable# -#myNumber# +#myNumber# -- cgit v1.2.3 From b8ad751cc020c07796832c1689cca7b84970b4e9 Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 21:07:13 -0400 Subject: Update coldfusion.html.markdown Adds a few more examples --- coldfusion.html.markdown | 87 ++++++++++++++++++++---------------------------- 1 file changed, 37 insertions(+), 50 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index be08733e..b8fe9359 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -10,9 +10,9 @@ ColdFusion is a scripting language for web development. ```ColdFusion " ---> - @@ -25,8 +25,10 @@ ColdFusion is a scripting language for web development. -#myVariable# -#myNumber# +#myVariable#
+#myNumber#
+ +
@@ -40,19 +42,23 @@ ColdFusion is a scripting language for web development. -#1 + 1# = 2 -#10 - 8# = 2 -#1 * 2# = 2 -#10 / 5# = 2 -#12 % 5# = 0 +#1 + 1#
= 2 +#10 - 8#
= 2 +#1 * 2#
= 2 +#10 / 5#
= 2 +#12 % 5#
= 0 + +
-#1 eq 1# -#15 neq 1# -#10 gt 8# -#1 lt 2# -#10 gte 5# -#1 lte 5# +#1 eq 1#
+#15 neq 1#
+#10 gt 8#
+#1 lt 2#
+#10 gte 5#
+#1 lte 5#
+ +
@@ -63,36 +69,17 @@ ColdFusion is a scripting language for web development. myCondition is unknown -``` - + + #i#
+
+ +
+``` +" ---> - +

Simple Variables

+

Set myVariable to "myValue"

+

Set myNumber to 3.14

-#myVariable#
-#myNumber#
+

Display myVariable: #myVariable#

+

Display myNumber: #myNumber#


+

Complex Variables

+

Set myArray1 to an array of 1 dimension using literal or bracket notation

+

Set myArray2 to an array of 1 dimension using function notation

+

Contents of myArray1

- +

Contents of myArray2

+ -#1 + 1#
= 2 -#10 - 8#
= 2 -#1 * 2#
= 2 -#10 / 5#
= 2 -#12 % 5#
= 0 +

Operators

+

Arithmetic

+

1 + 1 = #1 + 1#

+

10 - 7 = #10 - 7#

+

15 * 10 = #15 * 10#

+

100 / 5 = #100 / 5#

+

120 % 5 = #120 % 5#

+

120 mod 5 = #120 mod 5#


-#1 eq 1#
-#15 neq 1#
-#10 gt 8#
-#1 lt 2#
-#10 gte 5#
-#1 lte 5#
+

Comparison

+

Standard Notation

+

Is 1 eq 1? #1 eq 1#

+

Is 15 neq 1? #15 neq 1#

+

Is 10 gt 8? #10 gt 8#

+

Is 1 lt 2? #1 lt 2#

+

Is 10 gte 5? #10 gte 5#

+

Is 1 lte 5? #1 lte 5#

+ +

Alternative Notation

+

Is 1 == 1? #1 eq 1#

+

Is 15 != 1? #15 neq 1#

+

Is 10 > 8? #10 gt 8#

+

Is 1 < 2? #1 lt 2#

+

Is 10 >= 5? #10 gte 5#

+

Is 1 <= 5? #1 lte 5#


+

Control Structures

+ + +

Condition to test for: "#myCondition#"

+ - #myCondition# + #myCondition#. We're testing. #myCondition#. Proceed Carefully!!! @@ -73,54 +101,53 @@ ColdFusion is a scripting language for web development.
+

Loops

+

For Loop

- #i#
+

Index equals #i#

+
+ +

For Each Loop (Complex Variables)

+ +

Set myArray3 to [5, 15, 99, 45, 100]

+ + + + +

Index equals #i#

+
+ +

Set myArray4 to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]

+ + + + +

Index equals #s#

+
+ +

Switch Statement

+ +

Set myArray5 to [5, 15, 99, 45, 100]

+ + + + + + +

#i# is a multiple of 5.

+
+ +

#i# is ninety-nine.

+
+ +

#i# is not 5, 15, 45, or 99.

+
+

``` +

Components

+ +Code for reference (Functions must return something to support IE) + +
+<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>
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +sayHello() +

#sayHello()#

+getHello() +

#getHello()#

+getWorld() +

#getWorld()#

+setHello("Hola") +

#setHello("Hola")#

+setWorld("mundo") +

#setWorld("mundo")#

+sayHello() +

#sayHello()#

+getHello() +

#getHello()#

+getWorld() +

#getWorld()#

+``` ## 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) -- cgit v1.2.3 From c1c7a96378d79d379e68084780eecd91731fa4bb Mon Sep 17 00:00:00 2001 From: Himanshu81494 Date: Fri, 9 Oct 2015 19:57:06 +0530 Subject: typo in readme --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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! -- cgit v1.2.3 From 1e90e7da1d042dfc46a5be11117a4e45e460bcf8 Mon Sep 17 00:00:00 2001 From: Andy B Date: Fri, 9 Oct 2015 15:32:05 +0100 Subject: [objective-c/en-fr-ru-tr-vn] Enable syntax highlighting --- fr-fr/objective-c-fr.html.markdown | 2 +- objective-c.html.markdown | 2 +- ru-ru/objective-c-ru.html.markdown | 2 +- tr-tr/objective-c-tr.html.markdown | 2 +- vi-vn/objective-c-vi.html.markdown | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) 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/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/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/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 // /* -- cgit v1.2.3 From e8e8b9c76fb578d3f8e90b90b3c8a1c59cf0e901 Mon Sep 17 00:00:00 2001 From: Andy B Date: Fri, 9 Oct 2015 15:48:21 +0100 Subject: [C/en] Accessing command line arguments in main --- c.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index db2ac930..345dca7f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -27,6 +27,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line... */ // ...not this one! // Constants: #define +// 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 +57,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 -- cgit v1.2.3 From 53a0264029dbaaf5909110c0a390753b276ac324 Mon Sep 17 00:00:00 2001 From: Sricharan Chiruvolu Date: Fri, 9 Oct 2015 20:30:57 +0530 Subject: Update latex.html.markdown --- latex.html.markdown | 53 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/latex.html.markdown b/latex.html.markdown index c8f21a83..f0646941 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -3,6 +3,7 @@ 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 --- @@ -25,12 +26,15 @@ getting it to behave exactly the way you want can be a bit hairy. \documentclass[12pt]{article} % Next we define the packages the document uses. +% If you want to include graphics, colored text or +% source code from a 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} +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} \date{\today} \title{Learn LaTeX in Y Minutes!} @@ -41,6 +45,16 @@ getting it to behave exactly the way you want can be a bit hairy. % create a title page fo 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 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 ! @@ -69,15 +83,34 @@ One of the primary uses for LaTeX is to produce academic article 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! \\ -My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +Math has many symbols, far beyond what you can find on a keyboard. +Set and relation symbols, arrows, operators, 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. \\ -% We can also add references -For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, - $b$ and $c$, where $c$ is the hypotenuse, the following holds: +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. + +Operators are essential parts of a mathematical document: trigonometric functions +(sin, cos, tan), logarithms and exponentials (log, exp), limits (lim) e.t.c. have +pre-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)!}$ + % Display math with the equation 'environment' \begin{equation} % enters math-mode c^2 = a^2 + b^2. @@ -88,11 +121,17 @@ For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also the subject of Sec.~\ref{subsec:pythagoras}. +Summations and Integrals are written with sum and int commands: +\begin{equation} % enters math-mode +\sum_{i=0}^{5} f_i + +\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 definately have to lookup the placement options each time. +I definitely have to lookup the placement options each time. \begin{figure}[H] \centering @@ -115,6 +154,8 @@ Let's insert a Table. \end{tabular} \end{table} +% \section{Hyperlinks} + \section{Compiling} -- cgit v1.2.3 From c899b6605ef9667cb214c2163e7182ad41783be4 Mon Sep 17 00:00:00 2001 From: himanshu81494 Date: Fri, 9 Oct 2015 20:59:05 +0530 Subject: Update c.html.markdown --- c.html.markdown | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 29bc5a5b..f35a2098 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -307,8 +307,9 @@ int main(void) { exit(-1); break; } - - // using "goto" + /* + using "goto" in C + */ typedef enum { false, true } bool; // for C don't have bool as data type :( bool disaster = false; @@ -323,7 +324,10 @@ int main(void) { } error : printf("Error occured at i = %d & j = %d.\n", i, j); - // this will print out "Error occured at i = 52 & j = 99." + /* + https://ideone.com/GuPhd6 + this will print out "Error occured at i = 52 & j = 99." + */ /////////////////////////////////////// @@ -491,13 +495,15 @@ char c[] = "This is a test."; str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ -//as we can return return only one variable -//to change values of more than one variables we use call by reference +/* +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 temp = *a; + *a = *b; + *b = temp; } /* int first = 10; -- cgit v1.2.3 From 7b4d529c5e0dd4b62cf91a90ec72fe40ecca86ec Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Fri, 9 Oct 2015 11:47:13 -0400 Subject: Fix puts typo --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index bd1497ce..88efe322 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -265,7 +265,7 @@ 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| - pust "#{element} is number #{index} in the array" + puts "#{element} is number #{index} in the array" end counter = 1 -- cgit v1.2.3 From b433595a272d7d48281a8ea831c81c460c26a009 Mon Sep 17 00:00:00 2001 From: Laura Date: Fri, 9 Oct 2015 13:15:04 -0400 Subject: [sass/en] Add Sass tutorial --- learnsass.scss | 231 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 learnsass.scss diff --git a/learnsass.scss b/learnsass.scss new file mode 100644 index 00000000..9ab4eba7 --- /dev/null +++ b/learnsass.scss @@ -0,0 +1,231 @@ +--- +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. */ +/* 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. -- cgit v1.2.3 From 35e89f86fe21eb2a1246357184628595f8edca5d Mon Sep 17 00:00:00 2001 From: Cameron Schermerhorn Date: Fri, 9 Oct 2015 13:31:48 -0400 Subject: Resolve merge conflict with master + added name back to contributor list --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 58c19f11..3b289a6d 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -6,7 +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"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] filename: LearnJava.java --- -- cgit v1.2.3 From f3de591fc522f41bdfb92893fc623f48fb18d1d4 Mon Sep 17 00:00:00 2001 From: Colton Kohnke Date: Fri, 9 Oct 2015 21:29:01 +0200 Subject: merge patch-1, restructure, fix grammar --- latex.html.markdown | 154 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 95 insertions(+), 59 deletions(-) diff --git a/latex.html.markdown b/latex.html.markdown index f0646941..146e8d45 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,28 +6,23 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] filename: learn-latex.tex --- - -LaTeX is known to create aesthetically pleasing documents without you worrying -about the formatting. It is also great if one wants to create documents -containing a lot of mathematics. Getting a good document is very easy, but -getting it to behave exactly the way you want can be a bit hairy. - - -```latex - % 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 +% 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. +% 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 a file into your document, +% 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} @@ -42,13 +37,13 @@ getting it to behave exactly the way you want can be a bit hairy. % 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 fo us. +% 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 document classes article and report. +% 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} @@ -56,76 +51,103 @@ getting it to behave exactly the way you want can be a bit hairy. % 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 ! +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} +\subsection{This is a subsection} % Subsections are also intuitive. I think we need another one \subsubsection{Pythagoras} Much better now. \label{subsec:pythagoras} -\section*{This is an unnumbered section} +% 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 text. In case you haven't noticed the \textbackslash is the character -the tells the LaTeX compiler it should pay attention to what's next. +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 article or +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, Greek letters to name a few. \\ - +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. \\ +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) e.t.c. have -pre-defined LaTeX commands. Let's write an equation to see how it's done: \\ +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$ +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ Fractions(Numerator-denominators) can be written in these forms: % 10 / 7 -^10/_7 +$^{10}/_{7}$ % Relatively complex fractions can be written as % \frac{numerator}{denominator} -$\frac{n!}{k!(n - k)!}$ +$\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. - % for cross-reference - \label{eq:pythagoras} -\end{equation} % all \begin statments must have an end statement + \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}. +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: -\begin{equation} % enters math-mode -\sum_{i=0}^{5} f_i -\int_0^\infty \mathrm{e}^{-x}\,\mathrm{d}x +% 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} @@ -133,40 +155,56 @@ Summations and Integrals are written with sum and int commands: 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] - \centering - %\includegraphics[width=0.8\linewidth]{right-triangle.png} - % Commented out for compilation purposes. Use your imagination. +\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} -Let's insert a Table. +We can also insert Tables in the same way as figures. \begin{table}[H] \caption{Caption for the Table.} - \begin{tabular}{ccc} - Number & Last Name & First Name \\ - \hline + % 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} +% \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 -(yes, it actually compiles). \\ +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} % we can also created numbered lists! - \item Write the document in plain text - \item Compile plain text document to produce a pdf. - The compilation step looks something like this: \\ - % Verbatim tells the compiler to not interpret. + \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} @@ -191,5 +229,3 @@ That's all for now! * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) * An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) - - -- cgit v1.2.3 From 7d8bab656f154d4a58905fa4f0063b3e3824d4cf Mon Sep 17 00:00:00 2001 From: Aayush Ranaut Date: Fri, 9 Oct 2015 18:48:40 -0400 Subject: Range is not a generator --- python3.html.markdown | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 971ca0a4..c77f644e 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -96,7 +96,7 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variable refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to @@ -256,8 +256,8 @@ empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} -# Note keys for dictionaries have to be immutable types. This is to ensure that -# the key can be converted to a constant hash value for quick look-ups. +# Note keys for dictionaries have to be immutable types. This is to ensure that +# the key can be converted to a constant hash value for quick look-ups. # Immutable types include ints, floats, strings, tuples. invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. @@ -423,7 +423,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances print("We can clean up resources here") - + # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: @@ -661,8 +661,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) -- cgit v1.2.3 From bb68e9483d8be6b7ba76f93e2fcfc07fabe03293 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Sat, 10 Oct 2015 14:38:50 +0530 Subject: Adding unordered/ordered list --- haml.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/haml.html.markdown b/haml.html.markdown index 847714e6..dbc0a439 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -122,6 +122,12 @@ $ 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. -- cgit v1.2.3 From 091356a8da5b7dfca13075bec5089d700a1d9782 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Sat, 10 Oct 2015 14:42:30 +0530 Subject: Added table implementation in ruby --- haml.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/haml.html.markdown b/haml.html.markdown index 847714e6..d44a4728 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -127,6 +127,25 @@ $ haml input_file.haml output_file.html 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 -- cgit v1.2.3 From 689bb106f5e0a4da882e84a30633c6cab370d771 Mon Sep 17 00:00:00 2001 From: duci9y Date: Sat, 10 Oct 2015 14:59:30 +0530 Subject: [css/en] Fixed grammar, increased clarity. Also fixed extraneous whitespace, code mistakes, made sure line width was <80 characters. --- css.html.markdown | 258 ++++++++++++++++++++++++++---------------------------- 1 file changed, 123 insertions(+), 135 deletions(-) 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: -
+
*/ -/* 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 - + - + - +
- ``` -## 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 -

-

+

``` -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) -- cgit v1.2.3 From e13909c73719203deb83881c7d70ed7b1ef5a64f Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sat, 10 Oct 2015 19:51:04 +0200 Subject: Added french translation for Python3 --- fr-fr/python3-fr.html.markdown | 724 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 724 insertions(+) create mode 100644 fr-fr/python3-fr.html.markdown diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown new file mode 100644 index 00000000..2963a03f --- /dev/null +++ b/fr-fr/python3-fr.html.markdown @@ -0,0 +1,724 @@ +--- +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"] +filename: learnpython3-fr.py +lang: fr-fr +--- + +Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular +languages in existence. I fell in love with Python for its syntactic clarity. It's basically +executable pseudocode. +Python 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 éxé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ère 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 string ) 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" +# (Pour les matheux, 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)) # => +type((1,)) # => +type(()) # => + +# 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é-packager" 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 sets +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 hérite de object pour créer une classe +class Human(object): + + # 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éé 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) -- cgit v1.2.3 From 7f07379cfb8aeeffae49b857dda272d646ae5e48 Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sat, 10 Oct 2015 19:58:16 +0200 Subject: Removed leftovers, added Gnomino to the translators of Python3-FR --- fr-fr/python3-fr.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index 2963a03f..21aa5be5 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -5,13 +5,12 @@ contributors: - ["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 was created by Guido Van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. Python 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 éxécutable. -- cgit v1.2.3 From 7a3babacd7f52dd82f9b443bc6e371fbc96e4835 Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sat, 10 Oct 2015 20:05:33 +0200 Subject: Removed spaces in parenthesis --- fr-fr/python3-fr.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index 21aa5be5..f826c4f6 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -15,7 +15,7 @@ Python a été créé par Guido Van Rossum au début des années 90. C'est maint langages les populaires.Je suis tombé amoureux de Python pour la clarté de sa syntaxe. C'est tout simplement du pseudo-code éxé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] +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 @@ -40,7 +40,7 @@ Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil 8 - 1 # => 7 10 * 2 # => 20 -# Sauf pour la division qui retourne un float ( nombre à virgule flottante ) +# 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 @@ -52,7 +52,7 @@ Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil # Quand on utilise un float, le résultat est un float 3 * 2.0 # => 6.0 -# Modulo ( reste de la division ) +# Modulo (reste de la division) 7 % 3 # => 1 # Exponentiation (x**y, x élevé à la puissance y) @@ -109,7 +109,7 @@ 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 string ) sont créées avec " ou ' +# Les chaînes (ou strings) sont créées avec " ou ' "Ceci est une chaine" 'Ceci est une chaine aussi.' @@ -144,7 +144,7 @@ None # => None "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. +# 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 @@ -512,7 +512,7 @@ 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 ) +# 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) @@ -704,7 +704,7 @@ 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 ) +### En ligne et gratuit (en anglais) * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) @@ -716,7 +716,7 @@ print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor * [Python Course](http://www.python-course.eu/index.php) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -### Livres ( en anglais ) +### 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) -- cgit v1.2.3 From 0a599281c3f35e8987e488f6ace6aab789617aa7 Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sat, 10 Oct 2015 20:11:50 +0200 Subject: Corrected spelling mistakes --- fr-fr/python3-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index f826c4f6..13e453f4 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -340,7 +340,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} ## 3. Structures de contrôle et Itérables #################################################### -# On créée juste une variable +# On crée juste une variable some_var = 5 # Voici une condition "si". L'indentation est significative en Python! @@ -660,7 +660,7 @@ def double_numbers(iterable): for i in iterable: yield i + i -# Un générateur créé des valeurs à la volée. +# 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. -- cgit v1.2.3 From 1b0740ef8ecdcc01b74edd9669934d4f600a0491 Mon Sep 17 00:00:00 2001 From: Vinh Nguyen Date: Sun, 11 Oct 2015 09:28:59 +0700 Subject: Translate Ruby to vietnamese --- vi-vn/ruby-vi.html.markdown | 548 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 548 insertions(+) create mode 100644 vi-vn/ruby-vi.html.markdown diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown new file mode 100644 index 00000000..a50fe878 --- /dev/null +++ b/vi-vn/ruby-vi.html.markdown @@ -0,0 +1,548 @@ +--- +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"] + +--- + +```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. -- cgit v1.2.3 From d97eaa51d279f24dddbc820aab10ec3cb2e90e69 Mon Sep 17 00:00:00 2001 From: Chris Date: Sat, 10 Oct 2015 20:52:59 -0700 Subject: Added detail on C# single inheritance Clarified that the base class name must be the first thing listed --- csharp.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 02650038..a4dff948 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -837,7 +837,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; -- cgit v1.2.3 From 2b8fe51af6d03cbae2f5139b368006c80c9ff544 Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Sun, 11 Oct 2015 09:39:39 +0530 Subject: Mention meaning of asterisk. Explain *ref_var2 Issue #1398 --- rust.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 } ``` -- cgit v1.2.3 From 5bbd8419b232bff0baae40506351f733e0e30462 Mon Sep 17 00:00:00 2001 From: Chris Date: Sat, 10 Oct 2015 22:25:39 -0700 Subject: Added info C# null-propagation Another tool I found useful when learning C# --- csharp.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 02650038..14ffe4e0 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -443,6 +443,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"; -- cgit v1.2.3 From aad7eb82dd34c53dcdf15a8ea34dbee0df066bcc Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sun, 11 Oct 2015 10:34:18 +0200 Subject: Corrected french mistakes --- fr-fr/python3-fr.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index 13e453f4..b687143c 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -12,7 +12,7 @@ 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. +langages les populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. C'est tout simplement du pseudo-code éxé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] @@ -23,7 +23,7 @@ Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil # Un commentaire d'une ligne commence par un dièse -""" Les chaînes de caractère peuvent être écrites +""" Les chaînes de caractères peuvent être écrites avec 3 guillemets doubles ("), et sont souvent utilisées comme des commentaires. """ @@ -196,7 +196,7 @@ li[-1] # => 3 li[4] # Lève une IndexError # On peut accéder à une intervalle avec la syntaxe "slice" -# (Pour les matheux, c'est un rang du type "fermé/ouvert") +# (c'est un rang du type "fermé/ouvert") li[1:3] # => [2, 4] # Omettre les deux premiers éléments li[2:] # => [4, 3] @@ -246,7 +246,7 @@ tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True -# Vous pouvez "dé-packager" des tuples (ou des listes) dans des variables +# 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 @@ -305,7 +305,7 @@ filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} del filled_dict["one"] # Enlever la clé "one" de filled_dict. -# Les sets stockent ... des sets +# 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} -- cgit v1.2.3 From a1eabd5187d10865e901bc5b89b6eb84104fd553 Mon Sep 17 00:00:00 2001 From: Vinh Nguyen Date: Sun, 11 Oct 2015 16:05:07 +0700 Subject: Add language --- vi-vn/ruby-vi.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown index a50fe878..73382100 100644 --- a/vi-vn/ruby-vi.html.markdown +++ b/vi-vn/ruby-vi.html.markdown @@ -13,6 +13,7 @@ contributors: - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Vinh Nguyen", "http://rubydaily.net"] +lang: vi-vn --- -- cgit v1.2.3 From 097c839b7bbf03dd2ee50c9ccabde147e6bf285e Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sun, 11 Oct 2015 13:47:44 +0200 Subject: Changed way of creating classes --- fr-fr/python3-fr.html.markdown | 4 ++-- python3.html.markdown | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index b687143c..22256efc 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -570,8 +570,8 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] #################################################### -# On hérite de object pour créer une classe -class Human(object): +# 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" diff --git a/python3.html.markdown b/python3.html.markdown index cd1a83cc..5a992b54 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" -- cgit v1.2.3 From cc982fdbd1234b1a9ea29d93e3b997889a150577 Mon Sep 17 00:00:00 2001 From: Laura Date: Sun, 11 Oct 2015 09:52:30 -0400 Subject: Corrected extension --- learnsass.scss | 231 ---------------------------------------------------- sass.html.markdown | 232 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 232 insertions(+), 231 deletions(-) delete mode 100644 learnsass.scss create mode 100644 sass.html.markdown diff --git a/learnsass.scss b/learnsass.scss deleted file mode 100644 index 9ab4eba7..00000000 --- a/learnsass.scss +++ /dev/null @@ -1,231 +0,0 @@ ---- -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. */ -/* 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/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. -- cgit v1.2.3 From e6aa293c3afca8ff429a9f676d0807829e88106c Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sun, 11 Oct 2015 19:10:40 +0200 Subject: Corrected a spelling mistake --- fr-fr/python3-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index 22256efc..04d0a55d 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -13,7 +13,7 @@ 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 éxécutable. +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] -- cgit v1.2.3 From 51f7c4f6a015666794dc46ec080c80813d4ac57e Mon Sep 17 00:00:00 2001 From: Jo Pearce Date: Mon, 12 Oct 2015 14:07:56 +0100 Subject: Fixed the custom indexer example (setter return type is void) --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 479b7f01..72ee3731 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -749,7 +749,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" }; @@ -760,7 +760,7 @@ on a new line! ""Wow!"", the masses cried"; } set { - return passengers[i] = value; + passengers[i] = value; } } -- cgit v1.2.3 From 0cea1d25d5d103eb9774cf3f3e1362a11b2e684d Mon Sep 17 00:00:00 2001 From: Jo Pearce Date: Mon, 12 Oct 2015 15:15:06 +0100 Subject: Added some simple yield examples --- csharp.html.markdown | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 72ee3731..8babb90a 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 --- @@ -417,6 +418,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 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 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 YieldCounterWithBreak(int limit = 10) + { + for (var i = 0; i < limit; i++) + { + if (i > limit/2) yield break; + yield return i; + } + } public static void OtherInterestingFeatures() { @@ -875,7 +912,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) -- cgit v1.2.3 From ba06e9af37fda3dd363ab5a39bf03cd65bbe2ddd Mon Sep 17 00:00:00 2001 From: Ananya W Cleetus Date: Mon, 12 Oct 2015 11:56:37 -0400 Subject: Update python.html.markdown --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 -- cgit v1.2.3 From 6525590e7c24b5e46006a0b85a3f718cd47ed4f6 Mon Sep 17 00:00:00 2001 From: corpsee Date: Mon, 12 Oct 2015 22:25:15 +0600 Subject: Improved PHP ru-ru translation --- ru-ru/php-ru.html.markdown | 61 +++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 30 deletions(-) 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-код, то можно +пропустить закрывающий ?> // А так начинаются комментарии @@ -30,10 +31,10 @@ filename: learnphp-ru.php print('Hello '); // Напечатать "Hello " без перевода строки // () необязательно применять для print и echo -echo "World\n"; // Печатать "World" и перейти на новую строку. +echo "World\n"; // Напечатать "World" и перейти на новую строку. // (все утверждения должны заканчиваться ;) -// Любые символы за пределами закрывающегося тега выводятся автоматически: +// Любые символы за пределами закрывающего тега выводятся автоматически: ?> Hello World Again! 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 + * Включения */ 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" /******************************** -- cgit v1.2.3 From 8cb9e5395b2a21fe8e86455f5a5729a60435524c Mon Sep 17 00:00:00 2001 From: Robert Rose Date: Mon, 12 Oct 2015 17:19:35 -0400 Subject: Updated Java tutorial with BigInteger and BigDecimal. --- java.html.markdown | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 67e5494e..55daa5bb 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -95,11 +95,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 +117,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!"; -- cgit v1.2.3 From 4010f3727b377f1aa012c5f4195e58e11cae3be4 Mon Sep 17 00:00:00 2001 From: Robert Rose Date: Mon, 12 Oct 2015 17:48:08 -0400 Subject: Added contributor credit. --- java.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/java.html.markdown b/java.html.markdown index 55daa5bb..b43c3a72 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"] + - ["Rob Rose", "https://github.com/RobRoseKnows"] filename: LearnJava.java --- -- cgit v1.2.3 From a811ee38e44ca5d25eaa385cd7a2de93a9d67056 Mon Sep 17 00:00:00 2001 From: Robert Rose Date: Mon, 12 Oct 2015 17:49:47 -0400 Subject: Removed credit --- java.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index b43c3a72..55daa5bb 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] - ["Simon Morgan", "http://sjm.io/"] - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["Rob Rose", "https://github.com/RobRoseKnows"] filename: LearnJava.java --- -- cgit v1.2.3 From 26696b764b83ae34bb809405ecf5cfba615aad6a Mon Sep 17 00:00:00 2001 From: Robert Rose Date: Mon, 12 Oct 2015 17:52:09 -0400 Subject: Revert "Updated Java tutorial with BigInteger and BigDecimal." This reverts commit 8cb9e5395b2a21fe8e86455f5a5729a60435524c. --- java.html.markdown | 30 ------------------------------ 1 file changed, 30 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 55daa5bb..67e5494e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -95,13 +95,11 @@ 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 @@ -117,34 +115,6 @@ 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!"; -- cgit v1.2.3 From a504713d000567919196fed9f2be44e91ba722fe Mon Sep 17 00:00:00 2001 From: Robert Rose Date: Mon, 12 Oct 2015 17:52:21 -0400 Subject: Updated Java tutorial with BigInteger and BigDecimal --- java.html.markdown | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 67e5494e..55daa5bb 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -95,11 +95,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 +117,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!"; -- cgit v1.2.3