Merge remote-tracking branch 'refs/remotes/adambard/master'

This commit is contained in:
Mark Green 2016-01-22 00:54:49 +00:00
commit 57053bc95d
37 changed files with 3343 additions and 227 deletions

View File

@ -51,7 +51,7 @@ Long version:
### Header configuration
The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least
the custom scripts underpinning the site, required that some key information be defined in the header.
the custom scripts underpinning the site, requires that some key information be defined in the header.
The following fields are necessary for English articles about programming languages:

View File

@ -83,7 +83,7 @@ echo Hello, $Name!
# We have the usual if structure:
# use 'man test' for more info about conditionals
if [ $Name -ne $USER ]
if [ $Name != $USER ]
then
echo "Your name isn't your username"
else
@ -91,12 +91,12 @@ else
fi
# NOTE: if $Name is empty, bash sees the above condition as:
if [ -ne $USER ]
if [ != $USER ]
# which is invalid syntax
# so the "safe" way to use potentially empty variables in bash is:
if [ "$Name" -ne $USER ] ...
if [ "$Name" != $USER ] ...
# which, when $Name is empty, is seen by bash as:
if [ "" -ne $USER ] ...
if [ "" != $USER ] ...
# which works as expected
# There is also conditional execution

View File

@ -820,6 +820,76 @@ std::map<Foo, int, compareFunction> fooMap;
fooMap[Foo(1)] = 1;
fooMap.find(Foo(1)); //true
///////////////////////////////////////
// Lambda Expressions (C++11 and above)
///////////////////////////////////////
// lambdas are a convenient way of defining an anonymous function
// object right at the location where it is invoked or passed as
// an argument to a function.
// For example, consider sorting a vector of pairs using the second
// value of the pair
vector<pair<int, int> > tester;
tester.push_back(make_pair(3, 6));
tester.push_back(make_pair(1, 9));
tester.push_back(make_pair(5, 0));
// Pass a lambda expression as third argument to the sort function
// sort is from the <algorithm> header
sort(tester.begin(), tester.end(), [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second < rhs.second;
});
// Notice the syntax of the lambda expression,
// [] in the lambda is used to "capture" variables
// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how.
// It can be either:
// 1. a value : [x]
// 2. a reference : [&x]
// 3. any variable currently in scope by reference [&]
// 4. same as 3, but by value [=]
// Example:
vector<int> dog_ids;
// number_of_dogs = 3;
for(int i = 0; i < 3; i++) {
dog_ids.push_back(i);
}
int weight[3] = {30, 50, 10};
// Say you want to sort dog_ids according to the dogs' weights
// So dog_ids should in the end become: [2, 0, 1]
// Here's where lambda expressions come in handy
sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) {
return weight[lhs] < weight[rhs];
});
// Note we captured "weight" by reference in the above example.
// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
///////////////////////////////
// Range For (C++11 and above)
///////////////////////////////
// You can use a range for loop to iterate over a container
int arr[] = {1, 10, 3};
for(int elem: arr){
cout << elem << endl;
}
// You can use "auto" and not worry about the type of the elements of the container
// For example:
for(auto elem: arr) {
// Do something with each element of arr
}
/////////////////////
// Fun stuff
/////////////////////

View File

@ -76,7 +76,7 @@ int main (int argc, char** argv)
///////////////////////////////////////
// Types
///////////////////////////////////////
// All variables MUST be declared at the top of the current block scope
// we declare them dynamically along the code for the sake of the tutorial
@ -239,7 +239,7 @@ int main (int argc, char** argv)
z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
// Increment and decrement operators:
char *s = "iLoveC";
char *s = "ILoveC";
int j = 0;
s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
j = 0;
@ -313,9 +313,15 @@ int main (int argc, char** argv)
case 1:
printf("Huh, 'a' equals 1!\n");
break;
// Be careful - without a "break", execution continues until the
// next "break" is reached.
case 3:
case 4:
printf("Look at that.. 'a' is either 3, or 4\n");
break;
default:
// if `some_integral_expression` didn't match any of the labels
fputs("error!\n", stderr);
fputs("Error!\n", stderr);
exit(-1);
break;
}
@ -340,8 +346,8 @@ int main (int argc, char** argv)
https://ideone.com/GuPhd6
this will print out "Error occured at i = 52 & j = 99."
*/
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
@ -440,7 +446,7 @@ int main (int argc, char** argv)
for (xx = 0; xx < 20; xx++) {
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
// Note that there is no standard way to get the length of a
// dynamically allocated array in C. Because of this, if your arrays are
// going to be passed around your program a lot, you need another variable
@ -491,7 +497,7 @@ int add_two_ints(int x1, int x2)
/*
Functions are call by value. When a function is called, the arguments passed to
the function are copies of the original arguments (except arrays). Anything you
the function are copies of the original arguments (except arrays). Anything you
do to the arguments in the function do not change the value of the original
argument where the function was called.
@ -716,13 +722,13 @@ typedef void (*my_fnp_type)(char *);
/******************************* Header Files **********************************
Header files are an important part of c as they allow for the connection of c
source files and can simplify code and definitions by seperating them into
Header files are an important part of c as they allow for the connection of c
source files and can simplify code and definitions by seperating them into
seperate files.
Header files are syntaxtically similar to c source files but reside in ".h"
files. They can be included in your c source file by using the precompiler
command #include "example.h", given that example.h exists in the same directory
Header files are syntactically similar to c source files but reside in ".h"
files. They can be included in your c source file by using the precompiler
command #include "example.h", given that example.h exists in the same directory
as the c file.
*/

View File

@ -233,40 +233,38 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl
<em>Code for reference (Functions must return something to support IE)</em>
<pre>
&lt;cfcomponent&gt;
&lt;cfset this.hello = "Hello" /&gt;
&lt;cfset this.world = "world" /&gt;
<cfcomponent>
<cfset this.hello = "Hello" />
<cfset this.world = "world" />
&lt;cffunction name="sayHello"&gt;
&lt;cfreturn this.hello & ", " & this.world & "!" /&gt;
&lt;/cffunction&gt;
<cffunction name="sayHello">
<cfreturn this.hello & ", " & this.world & "!" />
</cffunction>
&lt;cffunction name="setHello"&gt;
&lt;cfargument name="newHello" type="string" required="true" /&gt;
<cffunction name="setHello">
<cfargument name="newHello" type="string" required="true" />
&lt;cfset this.hello = arguments.newHello /&gt;
<cfset this.hello = arguments.newHello />
&lt;cfreturn true /&gt;
&lt;/cffunction&gt;
<cfreturn true />
</cffunction>
&lt;cffunction name="setWorld"&gt;
&lt;cfargument name="newWorld" type="string" required="true" /&gt;
<cffunction name="setWorld">
<cfargument name="newWorld" type="string" required="true" />
&lt;cfset this.world = arguments.newWorld /&gt;
<cfset this.world = arguments.newWorld />
&lt;cfreturn true /&gt;
&lt;/cffunction&gt;
<cfreturn true />
</cffunction>
&lt;cffunction name="getHello"&gt;
&lt;cfreturn this.hello /&gt;
&lt;/cffunction&gt;
<cffunction name="getHello">
<cfreturn this.hello />
</cffunction>
&lt;cffunction name="getWorld"&gt;
&lt;cfreturn this.world /&gt;
&lt;/cffunction&gt;
&lt;/cfcomponent&gt;
</pre>
<cffunction name="getWorld">
<cfreturn this.world />
</cffunction>
</cfcomponent>
<cfset this.hello = "Hello" />
<cfset this.world = "world" />

View File

@ -339,7 +339,7 @@ nil ; for false - and the empty list
;; The () in the above is the list of arguments for the function
(defun hello (name)
(format nil "Hello, ~a " name))
(format nil "Hello, ~a" name))
(hello "Steve") ; => "Hello, Steve"
@ -430,7 +430,7 @@ nil ; for false - and the empty list
(defun walker (n)
(if (zerop n)
:walked
(walker (1- n))))
(walker (- n 1))))
(walker 5) ; => :walked

View File

@ -1,10 +1,12 @@
---
language: markdown
lang: cs-cz
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
translators:
- ["Michal Martinek", "https://github.com/MichalMartinek"]
filename: markdown.md
lang: cs-cz
---
Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná

View File

@ -630,7 +630,7 @@ on a new line! ""Wow!"", the masses cried";
public static class Extensions
{
// EXTENSION FUNCTIONS
// EXTENSION METHODS
public static void Print(this object obj)
{
Console.WriteLine(obj.ToString());

View File

@ -254,7 +254,7 @@ void main() {
// Use an index, access every array element by reference (because we're
// going to change each element) and just call parallel on the array!
foreach(i, ref elem; parallel(arr)) {
ref = sqrt(i + 1.0);
elem = sqrt(i + 1.0);
}
}
```

View File

@ -6,19 +6,19 @@ contributors:
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
translators:
- ["Moritz Kammerer", "https://github.com/phxql"]
- ["Jerome Meinke", "https://github.com/jmeinke"]
lang: de-de
filename: latex-de.tex
---
```
% Alle Kommentare starten fangen mit % an
% Es gibt keine Kommentare über mehrere Zeilen
% Alle Kommentare starten mit einem Prozentzeichen %
% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B.
% LaTeX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B.
% MS Word oder OpenOffice Writer
% Jedes LateX-Kommando startet mit einem Backslash (\)
% Jedes LaTeX-Kommando startet mit einem Backslash (\)
% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen
% LaTeX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen
% Weitere Dokumententypen sind z.B. book, report, presentations, etc.
% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall
% wollen wir einen 12 Punkte-Font verwenden.
@ -26,7 +26,7 @@ filename: latex-de.tex
% Als nächstes definieren wir die Pakete, die wir verwenden wollen.
% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest,
% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern.
% musst du die Fähigkeiten von LaTeX durch Hinzufügen von Paketen erweitern.
% Wir verwenden die Pakete float und caption für Bilder.
\usepackage{caption}
\usepackage{float}
@ -34,30 +34,41 @@ filename: latex-de.tex
% Mit diesem Paket können leichter Umlaute getippt werden
\usepackage[utf8]{inputenc}
% Es gibt eigentlich keine Kommentare über mehrere Zeilen, solche kann man
% aber selbst durch die Angabe eigener Kommandos definieren.
% Dieses Kommando kann man später benutzen.
\newcommand{\comment}[1]{}
% Es können durchaus noch weitere Optione für das Dokument gesetzt werden!
\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
\date{\today}
\title{Learn LaTeX in Y Minutes!}
\title{Learn \LaTeX\ in Y Minutes!}
% Nun kann's losgehen mit unserem Dokument.
% Alles vor dieser Zeile wird die Preamble genannt.
\begin{document}
\begin{document}
\comment{
Dies ist unser selbst-definierter Befehl
für mehrzeilige Kommentare.
}
% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann
% LateX für uns eine Titelseite generieren
% LaTeX für uns eine Titelseite generieren
\maketitle
% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an.
% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an.
% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem
% Inhalt erscheinen.
% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar.
\begin{abstract}
LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee!
\LaTeX -Documentation geschrieben in \LaTeX ! Wie ungewöhnlich und garantiert nicht meine Idee!
\end{abstract}
% Section Befehle sind intuitiv.
% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen.
\section{Einleitung}
Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen!
Hi, mein Name ist Moritz und zusammen werden wir \LaTeX\ erforschen!
\section{Noch eine section}
Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection.
@ -71,16 +82,16 @@ So ist's schon viel besser.
% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung.
% Das funktioniert auch bei anderen Befehlen.
\section*{Das ist eine unnummerierte section}
Es müssen nicht alle sections nummeriert sein!
\section*{Das ist eine unnummerierte section}
Es müssen nicht alle Sections nummeriert sein!
\section{Ein paar Notizen}
LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht.
\LaTeX\ ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht.
Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge
\textbackslash\textbackslash in den Code ein.\\
\section{Listen}
Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen,
Listen sind eine der einfachsten Dinge in \LaTeX. Ich muss morgen einkaufen gehen,
also lass uns eine Einkaufsliste schreiben:
\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung.
% \item bringt enumerate dazu, eins weiterzuzählen.
@ -96,7 +107,7 @@ also lass uns eine Einkaufsliste schreiben:
\section{Mathe}
Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen
Einer der Haupteinsatzzwecke von \LaTeX\ ist das Schreiben von akademischen
Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder
anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle
Symbole zu unserem Paper hinzuzufügen! \\
@ -106,18 +117,18 @@ Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstabe
um nur ein paar zu nennen.\\
Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen
Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\
Papern. So schreibt man in \LaTeX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\
% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben,
% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LaTeX schreiben,
% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings
% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und
% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden.
Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$.
Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt!
Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den \LaTeX nicht kennt!
Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten:
Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
Logarithmus und Exponenten ($\log$, $\exp$),
Grenzwerte ($\lim$), etc. haben vordefinierte Befehle.
Lass uns eine Gleichung schreiben: \\
@ -127,7 +138,7 @@ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\
Brüche (Zähler / Nenner) können so geschrieben werden:
% 10 / 7
$^{10}/_{7}$
$^{10}/_{7}$
% Komplexere Brüche können so geschrieben werden:
% \frac{Zähler}{Nenner}
@ -142,19 +153,19 @@ Wir können Gleichungen auch in einer equation Umgebung verwenden.
\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen
Wir können nun unsere Gleichung referenzieren!
Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in
Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in
Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden:
Grafiken, Gleichungen, Sections, etc.
Summen und Integrale können mit den sum und int Befehlen dargestellt werden:
% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen
\begin{equation}
% Manche LaTeX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen
\begin{equation}
\sum_{i=0}^{5} f_{i}
\end{equation}
\begin{equation}
\end{equation}
\begin{equation}
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
\end{equation}
\end{equation}
\section{Grafiken}
@ -164,7 +175,7 @@ Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt.
\begin{figure}[H] % H ist die Platzierungsoption
\centering % Zentriert die Grafik auf der Seite
% Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt.
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
% Auskommentiert, damit es nicht im Dokument auftaucht.
\caption{Dreieck mit den Seiten $a$, $b$, $c$}
\label{fig:right-triangle}
@ -177,7 +188,7 @@ Wir können Tabellen genauso wie Grafiken einfügen.
\caption{Überschrift der Tabelle.}
% Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll.
% Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal.
\begin{tabular}{c|cc}
\begin{tabular}{c|cc}
Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt
\hline % Eine horizontale Linie
1 & Biggus & Dickus \\
@ -187,36 +198,36 @@ Wir können Tabellen genauso wie Grafiken einfügen.
% \section{Links} % Kommen bald!
\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)}
Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll
in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren,
\section{Verhindern, dass \LaTeX\ etwas kompiliert (z.B. Quelltext)}
Angenommen, wir wollen Quelltext in unserem \LaTeX-Dokument. \LaTeX\ soll
in diesem Fall nicht den Quelltext als \LaTeX-Kommandos interpretieren,
sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden
wir eine verbatim Umgebung.
% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.)
% aber verbatim ist das simpelste.
\begin{verbatim}
\begin{verbatim}
print("Hello World!")
a%b; % Schau dir das an! Wir können % im verbatim verwenden!
random = 4; #decided by fair random dice roll
\end{verbatim}
\section{Kompilieren}
\section{Kompilieren}
Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF
verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\
Dafür musst du folgende Schritte durchführen:
\begin{enumerate}
\item Schreibe das Dokument. (den LateX-Quelltext).
\item Kompiliere den Quelltext in ein PDF.
\item Schreibe das Dokument. (den \LaTeX -Quelltext).
\item Kompiliere den Quelltext in ein PDF.
Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\
\begin{verbatim}
$pdflatex learn-latex.tex learn-latex.pdf
\begin{verbatim}
$pdflatex learn-latex.tex learn-latex.pdf
\end{verbatim}
\end{enumerate}
Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt
Manche \LaTeX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt
2 wird unsichtbar im Hintergrund ausgeführt.
Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet

View File

@ -38,11 +38,10 @@ not False -- True
1 < 10 -- True
-- Strings and characters
"This is a string."
'a' -- character
'You cant use single quotes for strings.' -- error!
"This is a string because it uses double quotes."
'a' -- characters in single quotes
-- Strings can be appended
-- Strings can be appended.
"Hello " ++ "world!" -- "Hello world!"
{-- Lists, Tuples, and Records --}
@ -53,10 +52,10 @@ not False -- True
-- The second example can also be written with two dots.
[1..5]
-- Append lists just like strings
-- Append lists just like strings.
[1..5] ++ [6..10] == [1..10] -- True
-- To add one item, use "cons"
-- To add one item, use "cons".
0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
-- The head and tail of a list are returned as a Maybe. Instead of checking
@ -64,6 +63,7 @@ not False -- True
List.head [1..5] -- Just 1
List.tail [1..5] -- Just [2, 3, 4, 5]
List.head [] -- Nothing
-- List.functionName means the function lives in the List module.
-- Every element in a tuple can be a different type, but a tuple has a
-- fixed length.
@ -74,23 +74,28 @@ List.head [] -- Nothing
fst ("elm", 42) -- "elm"
snd ("elm", 42) -- 42
-- Records are like tuples but the fields have names.
-- Notice that equals signs, not colons, are used.
{ x = 3, y = 7}
-- The empty tuple, or "unit", is sometimes used as a placeholder.
-- It is the only value of its type, also called "Unit".
()
-- Records are like tuples but the fields have names. The order of fields
-- doesn't matter. Notice that record values use equals signs, not colons.
{ x = 3, y = 7 }
-- Access a field with a dot and the field name.
{ x = 3, y = 7}.x -- 3
{ x = 3, y = 7 }.x -- 3
-- Or with an accessor fuction, a dot and then the field name.
.y { x = 3, y = 7} -- 7
-- Or with an accessor fuction, which is a dot and the field name on its own.
.y { x = 3, y = 7 } -- 7
-- Update the fields of a record. (It must have the fields already.)
{ person |
name = "George" }
{ physics |
position = physics.position + physics.velocity,
velocity = physics.velocity + physics.acceleration }
-- Update multiple fields at once, using the current values.
{ particle |
position = particle.position + particle.velocity,
velocity = particle.velocity + particle.acceleration }
{-- Control Flow --}
@ -111,11 +116,16 @@ else
-- Use case statements to pattern match on different possibilities.
case aList of
[] -> "matches the empty list"
[x]-> "matches a list of exactly one item, " ++ toString x
x::xs -> "matches a list of at least one item whose head is " ++ toString x
-- Pattern matches go in order. If we put [x] last, it would never match because
-- x::xs also matches (xs would be the empty list). Matches do not "fall through".
-- The compiler will alert you to missing or extra cases.
-- Pattern match on a Maybe.
case List.head aList of
Just x -> "The head is " ++ toString x
Nothing -> "The list was empty"
Nothing -> "The list was empty."
{-- Functions --}
@ -126,7 +136,7 @@ case List.head aList of
multiply a b =
a * b
-- Apply (call) a function by passing it arguments (no commas necessay).
-- Apply (call) a function by passing it arguments (no commas necessary).
multiply 7 6 -- 42
-- Partially apply a function by passing only some of its arguments.
@ -151,8 +161,8 @@ area (width, height) =
area (6, 7) -- 42
-- Use curly brackets to pattern match record field names
-- Use let to define intermediate values
-- Use curly brackets to pattern match record field names.
-- Use let to define intermediate values.
volume {width, height, depth} =
let
area = width * height
@ -161,21 +171,22 @@ volume {width, height, depth} =
volume { width = 3, height = 2, depth = 7 } -- 42
-- Functions can be recursive
-- Functions can be recursive.
fib n =
if n < 2 then
1
else
fib (n - 1) + fib (n - 2)
List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34]
List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
-- Another recursive function (use List.length in real code).
listLength aList =
case aList of
[] -> 0
x::xs -> 1 + listLength xs
-- Function application happens before any infix operation
-- Function calls happen before any infix operator. Parens indicate precedence.
cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
-- First degrees is applied to 30, then the result is passed to the trig
-- functions, which is then squared, and the addition happens last.
@ -191,7 +202,7 @@ cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
True : Bool
-- Functions have types too. Read -> as "goes to". Think of the rightmost type
-- as the type of the return value.
-- as the type of the return value, and the others as arguments.
not : Bool -> Bool
round : Float -> Int
@ -220,34 +231,41 @@ origin =
{ x = 0, y = 0, z = 0 }
-- You can give existing types a nice name with a type alias.
type alias Point3D = { x : Float, y : Float, z : Float }
type alias Point3D =
{ x : Float, y : Float, z : Float }
-- If you alias a record, you can use the name as a constructor function.
otherOrigin : Point3D
otherOrigin = Point3D 0 0 0
otherOrigin =
Point3D 0 0 0
-- But it's still the same type, you can equate them
-- But it's still the same type, so you can equate them.
origin == otherOrigin -- True
-- By contrast, defining a union type creates a type that didn't exist before.
-- A union type is so called because it can be one of many possibilities.
-- Each of the possibilities is represented as a "tag".
type Direction = North | South | East | West
type Direction =
North | South | East | West
-- Tags can carry other values of known type. This can work recursively.
type IntTree = Leaf | Node Int IntTree IntTree
type IntTree =
Leaf | Node Int IntTree IntTree
-- "Leaf" and "Node" are the tags. Everything following a tag is a type.
-- Tags can be used as values or functions.
root : IntTree
root = Node 7 Leaf Leaf
root =
Node 7 Leaf Leaf
-- Union types (and type aliases) can use type variables.
type Tree a = Leaf | Node a (Tree a) (Tree a)
type Tree a =
Leaf | Node a (Tree a) (Tree a)
-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a."
-- You can pattern match union tags. The uppercase tags must be matched exactly.
-- The lowercase variables will match anything. Underscore also matches
-- anything, but signifies that you aren't using it.
-- Pattern match union tags. The uppercase tags will be matched exactly. The
-- lowercase variables will match anything. Underscore also matches anything,
-- but signifies that you aren't using it.
leftmostElement : Tree a -> Maybe a
leftmostElement tree =
case tree of
@ -260,21 +278,20 @@ leftmostElement tree =
{-- Modules and Imports --}
-- The core libraries are organized into modulues, as are any third-party
-- libraries you may use. For large projects, you can define your own modulues.
-- The core libraries are organized into modules, as are any third-party
-- libraries you may use. For large projects, you can define your own modules.
-- Put this at the top of the file. If omitted, you're in Main.
module Name where
-- By default, everything is exported.
-- Limit what values and types are exported
module Name (Type, value) where
-- By default, everything is exported. You can specify exports explicity.
module Name (MyType, myValue) where
-- One common pattern is to export a union type but not its tags. This is known
-- as an "opaque type", and is frequently used in libraries.
-- Import code from other modules to use it in this one
-- Places Dict in scope, so you can call Dict.insert
-- Import code from other modules to use it in this one.
-- Places Dict in scope, so you can call Dict.insert.
import Dict
-- Imports the Dict module and the Dict type, so your annotations don't have to
@ -318,6 +335,8 @@ $ elm repl
-- Install a new package, and record it in elm-package.json.
$ elm package install evancz/elm-html
-- See what changed between versions of a package.
$ elm package diff evancz/elm-html 3.0.0 4.0.2
-- Elm's package manager enforces semantic versioning, so minor version bumps
-- will never break your build!
```
@ -335,12 +354,14 @@ Here are some useful resources.
* Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of:
* [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default
* Data structures like [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
* [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) and its cousin [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), commonly used for missing values or error handling
* Data structures like [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
* JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay with examples on how to organize code into components.
* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay by Elm's creator with examples on how to organize code into components.
* The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful.
* [Scope in Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) and [How to Read a Type Annotation](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). More community guides on the basics of Elm, written for JavaScript developers.
Go out and write some Elm!

View File

@ -0,0 +1,213 @@
---
language: latex
lang: es-es
contributors:
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
- ["Colton Kohnke", "http://github.com/voltnor"]
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
translators:
- ["Mario Pérez", "https://github.com/MarioPerezEsteso"]
filename: learn-latex-es.tex
---
```tex
% Todas las líneas comentadas comienzan con %
% No existen los comentarios multilínea
% LaTeX NO es un software de procesamiento de texto que cumple con
% "Lo que ves es lo que tienes" como MS Word u OpenOffice
% Todos los comandos de LaTeX comienzan con una contrabarra (\)
% Los documentos LaTeX comienzan definiendo el tipo de documento que se va a
% compilar. Algunos tipos de documentos son libros, informes, presentaciones,
% etc. Las opciones para el documento comienzan en los corchetes []. En este
% caso, se especifica que queremos utilizar una fuente de tamaño 12pt.
\documentclass[12pt]{article}
% A continuación, definimos los paquetes que utilizará el documento.
% Si quieres incluir gráficos, texto coloreado o código fuente de otro lenguaje,
% debes extender las funciones de LaTeX. Esto se consigue añadiendo paquetes.
% A continuación se incluirán los paquetes float y caption para figuras.
\usepackage{caption}
\usepackage{float}
% También podemos definir otras propiedades en el documento
\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
\date{\today}
\title{Learn LaTeX in Y Minutes!}
% Ahora estamos preparados para comenzar el documento
% Todo lo que se encuentre antes de esta línea se llama "El Preámbulo"
\begin{document}
% Si especificamos el autor, fecha y título, LaTeX creará una página como título
% por nosotros
\maketitle
% La mayoría de los artículos de investigación tienen un abstract. Es posible
% utilizar comandos predefinidos para ello.
% Esto debería aparecer en su orden lógico. Tras el título pero antes de las
% secciones principales del cuerpo.
% Este comando está disponible en los tipos de documentos article y report.
\begin{abstract}
Documentación de LaTex escrita en LaTex.
\end{abstract}
% Los comandos de sección son intuitivos.
% Todos los títulos de secciones son añadidos automáticamente a la tabla de contenidos.
\section{Introducción}
Hola, mi nombre es Mario Pérez y estoy traduciendo este documento para aprender LaTex.
\section{Otra sección}
Este es el texto de otra sección. Creo que necesitará una subsección.
\subsection{Esto es una subsección} % Las subsecciones también son fáciles.
Creo que necesitamos otra más.
\subsubsection{Pitágoras}
Mejor ahora.
\label{subsec:pitagoras}
% Utilizando el asterisco podemos decirle a LaTeX que no ponga los números de secciones y subsecciones.
% Esto también funciona con otros comandos de LaTeX.
\section*{Esto es una sección no numerada}
¡No todas las secciones tienen que estar numeradas!
\section{Algunas notas}
LaTeX es generalmente bastante bueno situando el texto donde debe ir. Si una lína \\ necesita \\ ser \\ rota \\ puedes poner \textbackslash\textbackslash en el código fuente. \\
\section{Listas}
Las listas son de las cosas más fáciles de crear en LaTeX. Necesito ir a comprar mañana, así que vamos a crear una lista de la compra.
\begin{enumerate} % Esto crea una lista numerada.
% \item crea un elemento
\item Ensalada.
\item 27 sandías.
\item Pescado.
% podemos incluso sobreescribir el número del ítem usando []
\item[cuántos?] Plátanos.
No es un ítem de la lista, pero sigue siendo parte de la enumeración.
\end{enumerate} % Todos los contextos deben tener un final.
\section{Matemáticas}
Uno de los usos principales de LaTeX es la producción de artículos académicos o técnicos. Normalmente relacionados con la ciencia y las matemáticas. Debido a esto, necesitamos poder añadir símbolos especiales a nuestro artículo.\\
En matemáticas hay muchos símbolos. Más de los que podemos encontrar en un teclado. Flechas o letras por nombrar un par.\\
Algunos símbolos juegan un papel fundamental en muchos artículos de investigación matemática. Así es como se establece que todo Y pertenece a X: $\forall$ x $\in$ X. \\
He necesitado añadir el signo $ antes de los símbolos. Esto se debe a que cuando escribimos, estamos en modo texto. Sin embargo, los símbolos solo pueden utilizarse en modo matemático, al cual se entra con el signo $.
% Lo opuesto también se cumple. Una variable también puede ser mostrada en modo matemático, al que también se puede entrar con \[\]
\[a^2 + b^2 = c^2 \]
Mi letra griega favorita es $\xi$. También me gustan $\beta$, $\gamma$ y $\sigma$.
Todavía no he encontrado una letra griega que LaTeX no conozca.
Los operadores son también una parte esencial de un documento matemático:
funciones trigonométricas ($\sin$, $\cos$, $\tan$), logaritmos y exponenciales ($\log$, $\exp$), límites ($\lim$), etc. tienen comandos predefinidos en LaTeX.
Vamos a escribir una ecuación para ver cómo se hace: \\
$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
Las fracciones (numeradores-denominadores) pueden escribirse de la siguiente forma:
% 10 / 7
$^{10}/_{7}$
% Las fracciones relativamente complejas pueden escribirse como
% \frac{numerador}{denominador}
$\frac{n!}{k!(n - k)!}$ \\
También podemos insertar ecuaciones en un contexto de ecuación.
% Mostrar matemáticas en el contexto de ecuaciones
\begin{equation} % entra en modo matemático
c^2 = a^2 + b^2.
\label{eq:pitagoras} % para referencias
\end{equation} % Todos los contextos deben tener un final.
Podemos referenciar nuestra nueva ecuación.
Ecuación ~\ref{eq:pythagoras} también se conoce como el Teorema de Pitágoras, el cual también se encuentra en la sección ~\ref{subsec:pythagoras}. Muchas cosas pueden ser etiquetadas: figures, equations, sections, etc.
Los sumatorios e integrales son escritor son los comandos sum e int:
% Algunos compiladores de LaTeX se quejarán si hay líneas en blanco
% En un contexto de ecuación.
\begin{equation}
\sum_{i=0}^{5} f_{i}
\end{equation}
\begin{equation}
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
\end{equation}
\section{Figuras}
Vamos a insertar una figura. Situarla puede ser algo complicado.
\begin{figure}[H] % H aquí establece la situación de la figura.
\centering % centra la figura en la página
% Inserta una figura escalada por 0.8 el ancho de la página.
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
% La línea anterior ha sido comentada para poder compilar este archivo. Por favor, usa tu imaginación.
\caption{Triángulo con lados $a$, $b$, $c$}
\label{fig:right-triangle}
\end{figure}
\subsection{Tablas}
También podemos insertar tablas de la misma manera que las figuras.
\begin{table}[H]
\caption{Título para la tabla.}
% los argumentos en {} describen cómo cada fila va a ser representada.
\begin{tabular}{c|cc}
Número & Nombre & Apellido \\
\hline % una línea horizontal
1 & Biggus & Dickus \\
2 & Monty & Python
\end{tabular}
\end{table}
% \section{Hyperlinks} % En construcción
\section{Haciendo que LaTeX no compile algo (por ejemplo, código fuente)}
Digamos que queremos incluir código fuente dentro de nuestro documento LaTex. En ese caso, debemos indicarle a LaTeX que no trate de compilarlo y simplemente lo muestre en el documento. Esto lo realizamos en el contexto verbatim.
% Hay otros paquetes para esta misma tarea, pero verbatim es el más básico.
\begin{verbatim}
print("Hola Mundo!")
a%b; % Podemos usar los signos % en verbatim.
aleatorio = 4; # Número aleatorio
\end{verbatim}
\section{Compilación}
Ahora mismo te estarás preguntando cómo compilar este fabuloso documento y obtener un documento PDF.\\
Para obtener el documento final utilizando LaTeX hay que seguir los siguientes pasos:
\begin{enumerate}
\item Escribe el documento en texto plano.
\item Compila el código para producir un PDF.
Los pasos de compilación serán algo parecido a esto (en Linux): \\
\begin{verbatim}
$pdflatex learn-latex.tex learn-latex.pdf
\end{verbatim}
\end{enumerate}
Un gran número de editores LaTeX combinan ambos pasos para que sea más sencillo obtener el documento.
Escribe toda la información de formato en el paso 1 y con el paso 2 obtendrás el documento que has definido en el paso anterior.
\section{End}
Esto es todo por ahora.
% fin del documento
\end{document}
```
## Más información sobre LaTeX
* El wikilibro LaTeX: [https://es.wikibooks.org/wiki/Manual_de_LaTeX](https://es.wikibooks.org/wiki/Manual_de_LaTeX)
* Un tutorial real: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)

825
es-es/php-es.html.markdown Normal file
View File

@ -0,0 +1,825 @@
---
language: PHP
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
translators:
- ["Mario Pérez", "https://github.com/MarioPerezEsteso"]
lang: es-es
filename: learnphp-es.php
---
Este documento explica el funcionamiento de PHP 5+.
```php
<?php // El código PHP debe estar dentro de etiquetas <?php
// Si tu fichero php solo contiene código php, es una buena práctica
// omitir la etiqueta de cierre php para prevenir salidas acidentales.
// Dos barras comienzan un comentario de una línea.
# También lo hará una almohadilla, pero // es más común
/*
Escribir texto entre una barra-asterisco y asterisco-barra
crea un comentario multilínea.
*/
// Utiliza "echo" o "print" para imprimir por pantalla
print('Hola '); // Imprime "Hola " sin salto de línea
// () son opcionales para print y echo
echo "Mundo\n"; // Imprime "Mundo" con un salto de línea
// (todas las sentencias deben finalizar con un punto y coma)
// Cualquier cosa fuera de las etiquetas <?php se imprime automáticamente
?>
¡Hola Mundo de nuevo!
<?php
/************************************
* Tipos y variables
*/
// Las variables comienzan con el símbolo $.
// Una variable válida comienza con una letra o guión bajo,
// seguida de cualquier cantidad de letras, números o guiones bajos.
// Las variables booleanas no distinguen entre mayúsculas o minúsculas
$boolean = true; // o TRUE o True
$boolean = false; // o FALSE o False
// Enteros
$int1 = 12; // => 12
$int2 = -12; // => -12
$int3 = 012; // => 10 (un 0 al comienzo declara un número octal)
$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal)
// Floats (también conocidos como doubles)
$float = 1.234;
$float = 1.2e3;
$float = 7E-10;
// Eliminar variable
unset($int1);
// Operaciones aritméticas
$suma = 1 + 1; // 2
$diferencia = 2 - 1; // 1
$producto = 2 * 2; // 4
$cociente = 2 / 1; // 2
// Operaciones aritméticas de escritura rápida
$numero = 0;
$numero += 1; // Incrementa $numero en 1
echo $numero++; // Imprime 1 (incremento después la evaluación)
echo ++$numero; // Imprime 3 (incremento antes de la evaluación)
$numero /= $float; // Divide y asigna el cociente a $numero
// Las cadenas de caracteres deben declararse entre comillas simples
$sgl_quotes = '$String'; // => '$String'
// Evita utilizar comillas dobles excepto para embeber otras variables
$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
// Los caracteres especiales solo son válidos entre comillas dobles
$escaped = "Esto contiene \t un caracter tabulador.";
$unescaped = 'Esto solo contiene una barra y una t: \t';
// Rodea una variable entre corchetes si es necesario
$dinero = "Tengo $${numero} en el banco.";
// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas
$nowdoc = <<<'END'
Multi line
string
END;
// Heredocs interpola cadenas de caracteres
$heredoc = <<<END
Multi line
$sgl_quotes
END;
// La concatenación de cadenas de caracteres se realiza con .
echo 'Esta cadena de caracteres ' . 'está concatenada';
// Las cadenas de caracteres pueden ser pasadas como parámetros en un echo
echo 'Multiples', 'Parametros', 'Validos'; // Devuelve 'MultiplesParametrosValidos'
/********************************
* Constantes
*/
// Una constante se define utilizando define()
// y nunca puede ser cambiada en tiempo de ejecución
// un nombre válido para una constante debe comenzar con una letra o guión bajo,
// seguido por cualquier número de letras, números o guiones bajos.
define("FOO", "algo");
// el acceso a una constante se puede realizar llamando a la variable elegida sin un símbolo de $
echo FOO; // Devuelve 'algo'
echo 'Esto imprime '.FOO; // Devuelve 'Esto imprime algo'
/********************************
* Arrays
*/
// Todos los arrays en PHP son asociativos (hashmaps),
// Los arrays asociativos son conocidos como hashmaps en algunos lenguajes.
// Funciona con todas las versiones de php
$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3);
// PHP 5.4 introdujo una nueva sintaxis
$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3];
echo $asociativo['Uno']; // imprime 1
// Lista literales implícitamente asignados con claves enteras
$array = ['Uno', 'Dos', 'Tres'];
echo $array[0]; // => "Uno"
// Añadir un elemento al final de un array
$array[] = 'Cuatro';
// o
array_push($array, 'Cinco');
// Eliminar un elemento de un array
unset($array[3]);
/********************************
* Salidas por pantalla
*/
echo('¡Hola Mundo!');
// Imprime ¡Hola Mundo! en stdout.
// Stdout es la página web si se está ejecutando en un navegador.
print('!Hola Mundo!'); // Es lo mismo que echo
// No es necesario el paréntesis en echo y print
echo '¡Hola Mundo!';
print '¡Hola Mundo!';
$parrafo = 'parrafo';
echo 100; // Haz echo de escalares directamente
echo $parrafo; // o de variables
// Si las etiquetas cortas estás configuradas y tu versión de PHP es
// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo
?>
<p><?= $parrafo?></p>
<?php
$x = 1;
$y = 2;
$x = $y; // $x ahora contiene el mismo valor que $y
$z = &$y;
// $z contiene ahora una referencia a $y. Un cambio en el valor de
// $z cambiará también el valor de $y, y viceversa.
// $x sin embargo, tendrá el valor original de $y
echo $x; // => 2
echo $z; // => 2
$y = 0;
echo $x; // => 2
echo $z; // => 0
// Dump muestra el tipo y valor de una variable en stdout
var_dump($z); // imprime int(0)
// Para mostrar el valor de una variable en un formato legible para humanos
print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres )
/********************************
* Lógica
*/
$a = 0;
$b = '0';
$c = '1';
$d = '1';
// assert lanza una advertencia si su argumento no es verdadero
// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos.
assert($a == $b); // igualdad
assert($c != $a); // desigualdad
assert($c <> $a); // desigualdad alternativa
assert($a < $c);
assert($c > $b);
assert($a <= $b);
assert($c >= $d);
// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo.
assert($c === $d);
assert($a !== $d);
assert(1 === '1');
assert(1 !== '1');
// Operador 'Spaceship' (desde PHP 7)
// Devuelve 0 si ambos valores son iguales
// Devuelve 1 si el valor de la izquierda es mayor
// Devuelve -1 si el valor de la derecha es mayor
$a = 100;
$b = 1000;
echo $a <=> $a; // 0 porque son iguales
echo $a <=> $b; // -1 porque $a < $b
echo $b <=> $a; // 1 porque $b > $a
// Las variables pueden ser convertidas entre tipos, dependiendo de su uso.
$entero = 1;
echo $entero + $entero; // => 2
$string = '1';
echo $string + $string; // => 2 (los strings son convertidos a enteros)
$string = 'uno';
echo $string + $string; // => 0
// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número
// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo
$boolean = (boolean) 1; // => true
$cero = 0;
$boolean = (boolean) $cero; // => false
// También hay funciones dedicadas a la conversión de tipos
$entero = 5;
$string = strval($entero);
$var = null; // Valor nulo
/********************************
* Estructuras de control
*/
if (true) {
print 'He sido imprimido';
}
if (false) {
print 'Yo no';
} else {
print 'He sido imprimido';
}
if (false) {
print 'No se imprime';
} elseif(true) {
print 'Sí se imprime';
}
// operador ternario
print (false ? 'No se imprime' : 'Sí se imprime');
// atajo para el operador ternario desde PHP 5.3
// equivalente de "$x ? $x : 'Sí'""
$x = false;
print($x ?: 'Sí');
// operador 'no definido' desde php 7
$a = null;
$b = 'Imprime';
echo $a ?? 'a no está definido'; // imprime 'a no está definido'
echo $b ?? 'b no está definido'; // imprime 'Imprime'
$x = 0;
if ($x === '0') {
print 'No imprime';
} elseif($x == '1') {
print 'No imprime';
} else {
print 'Imprime';
}
// Esta sintaxis alternativa se utiliza para plantillas:
?>
<?php if ($x): ?>
Esto se muestra si la evaluación es verdadera.
<?php else: ?>
En otro caso, se muestra esto.
<?php endif; ?>
<?php
// Utiliza el switch para tener algo más de lógica.
switch ($x) {
case '0':
print 'Switch does type coercion';
break; // Debes incluir un break para no seguir con los casos 'Dos' y 'Tres'
case 'Dos':
case 'Tres':
// Hacer algo si la variables es 'Dos' o 'Tres'
break;
default:
// Hacer algo por defecto
}
// Los bucles While, do...while y for te serán familiares
$i = 0;
while ($i < 5) {
echo $i++;
}; // Imprime "01234"
echo "\n";
$i = 0;
do {
echo $i++;
} while ($i < 5); // Imprime "01234"
echo "\n";
for ($x = 0; $x < 10; $x++) {
echo $x;
} // Imprime "0123456789"
echo "\n";
$ruedas = ['bicicleta' => 2, 'coche' => 4];
// Los bucles foreach pueden iterar por arrays
foreach ($ruedas as $numero_ruedas) {
echo $numero_ruedas;
} // Imprime "24"
echo "\n";
// También se puede iterar sobre las claves, así como sobre los valores
foreach ($ruedas as $vehiculo => $numero_ruedas) {
echo "Un $vehiculo tiene $numero_ruedas ruedas";
}
echo "\n";
$i = 0;
while ($i < 5) {
if ($i === 3) {
break; // Sale fuera del bucle while
}
echo $i++;
} // Imprime "012"
for ($i = 0; $i < 5; $i++) {
if ($i === 3) {
continue; // Se salta esta iteración del bucle
}
echo $i;
} // Imprime "0124"
/********************************
* Funciones
*/
// Define una función con "function":
function mi_funcion () {
return 'Hola';
}
echo mi_funcion(); // => "Hola"
// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier
// número de letras, números o guiones bajos.
function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1
$resultado = $x + $y;
return $resultado;
}
echo anadir(4); // => 5
echo anadir(4, 2); // => 6
// $resultado no es accesible fuera de la función
// print $resultado; // Devuelve una advertencia.
// Desde PHP 5.3 se pueden declarar funciones anónimas
$inc = function ($x) {
return $x + 1;
};
echo $inc(2); // => 3
function foo ($x, $y, $z) {
echo "$x - $y - $z";
}
// Las funciones pueden devolver funciones
function bar ($x, $y) {
// Utiliza 'use' para meter variables de fuera de la función
return function ($z) use ($x, $y) {
foo($x, $y, $z);
};
}
$bar = bar('A', 'B');
$bar('C'); // Imprime "A - B - C"
// Puedes llamar a funciones utilizando cadenas de caracteres
$nombre_funcion = 'add';
echo $nombre_funcion(1, 2); // => 3
// Es útil para determinarl qué función ejecutar.
// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]);
// Puedes obtener todos los parámetros pasados a una función
function parametros() {
$numero_argumentos = func_num_args();
if ($numero_argumentos > 0) {
echo func_get_arg(0) . ' | ';
}
$args_array = func_get_args();
foreach ($args_array as $key => $arg) {
echo $key . ' - ' . $arg . ' | ';
}
}
parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo |
// Desde PHP 5.6 se puede obtener un número variable de argumentos
function variable($palabra, ...$lista) {
echo $palabra . " || ";
foreach ($lista as $item) {
echo $item . ' | ';
}
}
variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo |
/********************************
* Includes
*/
<?php
// Los ficheros PHP incluidos deben comenzar también con la etiqueta de <?php
include 'mi-fichero.php';
// El código de mi-fichero.php ya está disponible en el entorno actual.
// Si el fichero no puede ser incluido (por ejemplo porque no se ha encontrado),
// se muestra una advertencia.
include_once 'mi-fichero.php';
// Si el código del fichero mi-fichero.php ya ha sido incluido, ya no se
// incluirá de nuevo. Este previene errores por múltiples declaraciones.
require 'mi-fichero.php';
require_once 'mi-fichero.php';
// Es lo mismo que el include(), pero require() causará un error fatal si el archivo
// no ha podido ser incluido.
// Contenido de mi-include.php:
<?php
return 'Cualquier cosa.';
// acabar archivo
// Los include y require también pueden devolver un valor.
$valor = include 'mi-include.php';
// Los archivos son incluidos en función de la ruta data o, si ninguna ruta es
// especificada se utilizará la directiva de configuración de include_path. Si el
// fichero no se encuentra en el include_path, include comprobará la ruta del código
// que lo llama antes de fallar.
/* */
/********************************
* Clases
*/
// Las clases son definidas con la palabra clave class
class MiClase
{
const MI_CONSTANTE = 'valor'; // Una constante
static $staticVar = 'static';
// Las variables estáticas y su visibilidad
public static $publicStaticVar = 'publicStatic';
// Accesible solo dentro de su clase
private static $privateStaticVar = 'privateStatic';
// Accesible desde la clase y las subclases
protected static $protectedStaticVar = 'protectedStatic';
// Las propiedades deben declarar su visibilidad
public $propiedad = 'public';
public $instanceProp;
protected $prot = 'protected'; // Accesible desde la clase y las subclases
private $priv = 'private'; // Accesible solo desde la clase
// Crear un constructor con __construct
public function __construct($instanceProp) {
// Accede a las variables de la instancia con $this
$this->instanceProp = $instanceProp;
}
// Los métodos son declarados como funciones dentro de una clase
public function miMetodo()
{
print 'MiClase';
}
// la palabra clave final hará una función no sobreescribible
final function noMePuedesSobreEscribir()
{
}
/*
* Declarar propiedades de clase o métodos como estáticos los hace accesibles sin
* necesidad de instanciar la clase. Una propiedad declarada como estática no
* puede ser accedida mediante una instancia de la clase, pero sí mediante un
* método estático.
*/
public static function miMetodoEstatico()
{
print 'Soy estático';
}
}
// Las constantes de una clase siempre pueden ser accedidas estáticamente
echo MiClase::MI_CONSTANTE; // Muestra 'valor';
echo MiClase::$staticVar; // Muestra 'static';
MiClase::miMetodoEstatico(); // Muestra 'Soy estático';
// Instancia una clase usando new
$mi_clase = new MiClase('Una instancia');
// Los paréntesis son opcionales si no se pasa ningún argumento.
// Accede a los miembros de una clase utilizando ->
echo $mi_clase->propiedad; // => "public"
echo $mi_clase->instanceProp; // => "Una instancia"
$mi_clase->miMetodo(); // => "MiClase"
// Extender clases utilizando "extends"
class MiOtraClase extends MiClase
{
function imprimePropiedadProtegida()
{
echo $this->prot;
}
// Sobreescribe un método
function miMetodo()
{
parent::miMetodo();
print ' > MiOtraClase';
}
}
$mi_otra_clase = new MiOtraClase('Propiedad de instancia');
$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected"
$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase"
final class NoMePuedesExtender
{
}
// Puedes utilizar "métodos mágicos" para crear los getters y setters
class MiClaseMapeada
{
private $propiedad;
public function __get($key)
{
return $this->$key;
}
public function __set($key, $value)
{
$this->$key = $value;
}
}
$x = new MiClaseMapeada();
echo $x->propiedad; // Utilizará el método __get()
$x->propiedad = 'Algo'; // Utilizará el método __set()
// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o
// implementando interfaces (utilizando la palabra clave implements).
// Una interfaz puede ser declarada con la palabra clave interface.
interface InterfazUno
{
public function hazAlgo();
}
interface InterfazDos
{
public function hazOtraCosa();
}
// las interfaces pueden ser extendidas
interface InterfazTres extends InterfazDos
{
public function hazCualquierOtraCosa();
}
abstract class MiClaseAbstracta implements InterfazUno
{
public $x = 'hazAlgo';
}
class MiOtraClase extends MiClaseAbstracta implements InterfazDos
{
public function hazAlgo()
{
echo $x;
}
public function hazOtraCosa()
{
echo 'hazOtraCosa';
}
}
// Las clases pueden implementar más de una interfaz
class CualquierOtraClase implements InterfazUno, InterfazDos
{
public function hazAlgo()
{
echo 'hazAlgo';
}
public function hazOtraCosa()
{
echo 'hazOtraCosa';
}
}
/********************************
* Traits
*/
// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait"
trait MiTrait
{
public function miMetodoTrait()
{
print 'Tengo trait';
}
}
class MiClaseTrait
{
use MiTrait;
}
$cls = new MiClaseTrait();
$cls->miMetodoTrait(); // Imprime "Tengo trait"
/********************************
* Namespaces
*/
// Esta sección está separada porque una declaración de namespace debe
// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso
<?php
// Por defecto, las clases existen en el namespace global y pueden ser llamadas
// explícitamente con una contrabarra.
$cls = new \MiClase();
// Estableder el namespace para un archivo
namespace Mi\Namespace;
class MiClase
{
}
// (de otro archivo)
$cls = new Mi\Namespace\MiClase;
// O de otro namespace.
namespace Mi\Otro\Namespace;
use Mi\Namespace\MiClase;
$cls = new MiClase();
// O se puede asignar un ales al namespace
namespace Mi\Otro\Namespace;
use Mi\Namespace as OtroNamespace;
$cls = new OtroNamespace\MiClase();
/**********************
* Late Static Binding
*
*/
class ClasePadre {
public static function quien() {
echo "Soy una " . __CLASS__ . "\n";
}
public static function test() {
// Auto referencia a la clase en la que el método está definido
self::quien();
// Referencia estáticamente a la clase donde el método ha sido llamado
static::quien();
}
}
ClasePadre::test();
/*
Soy una ClasePadre
Soy una ClasePadre
*/
class ClaseHija extends ClasePadre {
public static function quien() {
echo "Pero soy una " . __CLASS__ . "\n";
}
}
ClaseHija::test();
/*
Soy una ClasePadre
Pero soy una ClaseHija
*/
/**********************
* Manejo de errores
*
*/
// Una simple gestión de errores puede ser realizada con un bloque try catch
try {
// Haz algo
} catch (Exception $e) {
// Maneja la excepción
}
// Cuando se utilicen bloques try catch en un entorno con namespaces hay que
// usar lo siguiente
try {
// Haz algo
} catch (\Exception $e) {
// Maneja la excepción
}
// Excepciones personalizadas
class MiExcepcion extends Exception {}
try {
$condicion = true;
if ($condicion) {
throw new MiExcepcion('Ha pasado algo');
}
} catch (MiExcepcion $e) {
// Manejar la excepción
}
```
## Más información
Visita la [documentación oficial de PHP](http://www.php.net/manual/) para más referencias
y apoyo de la comunidad.
Si estás interesado en buenas prácticas, visita
[PHP The Right Way](http://www.phptherightway.com/).
Si vienes de un lenguaje con una buena gestión de paquetes, visita
[Composer](http://getcomposer.org/).
Para estándares comunes, visita el PHP Framework Interoperability Group
[PSR standards](https://github.com/php-fig/fig-standards).

View File

@ -3,7 +3,7 @@ name: Go
category: language
language: Go
lang: fr-fr
filename: learngo.go
filename: learngo-fr.go
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["Christopher Bess", "https://github.com/cbess"]

View File

@ -13,8 +13,8 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://www.g
/*
Set yourself up:
1) Install GVM - http://gvmtool.net/
2) Install Groovy: gvm install groovy
1) Install SDKMAN - http://sdkman.io/
2) Install Groovy: sdk install groovy
3) Start the groovy console by typing: groovyConsole
*/

147
hu-hu/yaml-hu.html.markdown Normal file
View File

@ -0,0 +1,147 @@
---
language: yaml
filename: learnyaml-hu.yaml
contributors:
- ["Adam Brenecki", "https://github.com/adambrenecki"]
translators:
- ["Tamás Diószegi", "https://github.com/ditam"]
lang: hu-hu
---
A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is
olvasható és írható legyen emberi szemmel.
A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt
szintaktikai jelentéssel bíró sortörésekkel és indentációval,
a Pythonhoz hasonlóan. A Pythonnal ellentétben azonban a YAML nem engedélyezi
a közvetlen tab karakterek jelenlétét.
Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő,
a kódolást a tartalomban explicit nem kell (és nem is lehet) feltüntetni.
```yaml
# A kommentek YAML-ban így néznek ki.
##################
# Skalár típusok #
##################
# A gyökér objektumunk (az egész dokumentumra értve) egy map,
# ami a más nyelvekből ismert dictionary, hash vagy object típusokkal egyenértékű.
kulcs: érték
masik_kulcs: Másik érték jön ide.
egy_szam: 100
tudomanyos_jelolessel: 1e+12
boolean: true
null_value: null
kulcs benne szóközökkel: érték
# Látható, hogy a sztringeket nem szükséges idézőjelek közé zárni, bár szabad.
Továbbá: "Idézőjelekkel megadott sztring."
"A kulcs is lehet idézőjeles.": "Hasznos lehet, ha ':'-ot akarsz a kulcsban."
# Többsoros sztringek írhatóak 'literal block'-ként ('|' jelet használva)
# vagy 'folded block'-ként is ('>' jelet használva).
literal_block: |
Ez az egész szöveg-blokk lesz az értéke a literal_block kulcsnak,
a sortöréseket megtartva.
Az ilyen sztringet az indentáció visszahúzása zárja le, a behúzás pedig
eltávolításra kerül.
A 'még jobban' behúzott részek megtartják a behúzásukat -
ezeknek a soroknak 4 szóköz behúzása lesz.
folded_style: >
Az az egész szöveg-blokk lesz az értéke a 'folded_style' kulcsnak, de
ezúttal minden sortörés egy szóközre lesz cserélve.
Az üres sorok, mint a fenti, új sor karakterre cserélődnek.
A 'még jobban' behúzott sorok megtartják a sortöréseiket, -
ez a szöveg két sorban jelenik meg.
######################
# Gyűjtemény típusok #
######################
# Egymásba ágyazás a behúzás változtatásával érhető el.
beagyazott_map:
key: value
another_key: Another Value
masik_beagyazott_map:
hello: hello
# A mapeknek nem csak sztring kulcsaik lehetnek.
0.25: lebegőpontos kulcs
# A kulcsok lehetnek többsoros objektumok is, ? jellel jelezve a kulcs kezdetét
? |
Ez itt egy
többsoros kulcs
: és ez az értéke
# Szintén engedélyezett a kollekció típusok használata kulcsként, de egyéb
# nyelvekben ez gyakran problémákat fog okozni.
# Szekvenciák (listákkal vagy tömbökkel egyenértékűek) így néznek ki:
egy_szekvencia:
- Item 1
- Item 2
- 0.5 # Többféle típust is tartalmazhat
- Item 4
- key: value
another_key: another_value
-
- Ez egy szekvencia
- egy másik szekvenciába ágyazva
# Mivel a YAML a JSON befoglaló halmazát alkotja, JSON szintaxisú
# mapek és szekvenciák is használhatóak:
json_map: {"key": "value"}
json_seq: [3, 2, 1, "takeoff"]
#########################
# EXTRA YAML KÉPESSÉGEK #
#########################
# A YAML-ben ún. 'anchor'-ök segítségével könnyen lehet duplikálni
# tartalmakat a dokumentumon belül. A következő kulcsok azonos értékkel bírnak:
anchored_tartalom: &anchor_neve Ez a sztring két kulcs értéke is lesz.
másik_anchor: *anchor_neve
# Vannak a YAML-ben tagek is, amivel explicit lehet típusokat jelölni.
explicit_string: !!str 0.5
# Bizonyos implementációk nyelv-specifikus tageket tartalmaznak, mint
# például ez a Python komplex szám típusának jelölésére:
python_complex_number: !!python/complex 1+2j
######################
# EXTRA YAML TÍPUSOK #
######################
# Nem a sztringek és a számok az egyedüli skalár típusok YAML-ben.
# ISO-formátumú dátumok és dátumot jelölő literal kifejezések is értelmezettek.
datetime: 2001-12-15T02:59:43.1Z
datetime_with_spaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
# A !!binary tag jelöli, hogy egy sztring valójában base64-kódolású
# reprezentációja egy bináris blob-nak
gif_file: !!binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
# Létezik a YAML-ban egy halmaz típus (set) is, ami így néz ki:
set:
? elem1
? elem2
? elem3
# Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti
# halmaz egyenértékű a következővel:
set2:
elem1: null
elem2: null
elem3: null
```

View File

@ -0,0 +1,647 @@
---
language: python
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
- ["Andre Polykanine", "https://github.com/Oire"]
filename: learnpython.py
translators:
- ["Ale46", "http://github.com/Ale46/"]
lang: it-it
---
Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari
linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente
pseudocodice eseguibile.
Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
Nota: Questo articolo è valido solamente per Python 2.7, ma dovrebbe andar bene anche per
Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
```python
# I commenti su una sola linea iniziano con un cancelletto
""" Più stringhe possono essere scritte
usando tre ", e sono spesso usate
come commenti
"""
####################################################
## 1. Tipi di dati primitivi ed Operatori
####################################################
# Hai i numeri
3 # => 3
# La matematica è quello che vi aspettereste
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7
# La divisione è un po' complicata. E' una divisione fra interi in cui viene
# restituito in automatico il risultato intero.
5 / 2 # => 2
# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats.
2.0 # Questo è un float
11.0 / 4.0 # => 2.75 ahhh...molto meglio
# Il risultato di una divisione fra interi troncati positivi e negativi
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # funziona anche per i floats
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# Operazione Modulo
7 % 3 # => 1
# Elevamento a potenza (x alla y-esima potenza)
2**4 # => 16
# Forzare le precedenze con le parentesi
(1 + 3) * 2 # => 8
# Operatori Booleani
# Nota "and" e "or" sono case-sensitive
True and False #=> False
False or True #=> True
# Note sull'uso di operatori Bool con interi
0 and 2 #=> 0
-5 or 0 #=> -5
0 == False #=> True
2 == True #=> False
1 == True #=> True
# nega con not
not True # => False
not False # => True
# Uguaglianza è ==
1 == 1 # => True
2 == 1 # => False
# Disuguaglianza è !=
1 != 1 # => False
2 != 1 # => True
# Altri confronti
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# I confronti possono essere concatenati!
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# Le stringhe sono create con " o '
"Questa è una stringa."
'Anche questa è una stringa.'
# Anche le stringhe possono essere sommate!
"Ciao " + "mondo!" # => Ciao mondo!"
# Le stringhe possono essere sommate anche senza '+'
"Ciao " "mondo!" # => Ciao mondo!"
# ... oppure moltiplicate
"Hello" * 3 # => "HelloHelloHello"
# Una stringa può essere considerata come una lista di caratteri
"Questa è una stringa"[0] # => 'Q'
# % può essere usato per formattare le stringhe, in questo modo:
"%s possono essere %s" % ("le stringhe", "interpolate")
# Un nuovo modo per fomattare le stringhe è il metodo format.
# Questo metodo è quello consigliato
"{0} possono essere {1}".format("le stringhe", "formattate")
# Puoi usare delle parole chiave se non vuoi contare
"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna")
# None è un oggetto
None # => None
# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None
# Usa "is" invece
"etc" is None # => False
None is None # => True
# L'operatore 'is' testa l'identità di un oggetto. Questo non è
# molto utile quando non hai a che fare con valori primitivi, ma lo è
# quando hai a che fare con oggetti.
# None, 0, e stringhe/liste vuote sono tutte considerate a False.
# Tutti gli altri valori sono True
bool(0) # => False
bool("") # => False
####################################################
## 2. Variabili e Collections
####################################################
# Python ha una funzione di stampa
print "Sono Python. Piacere di conoscerti!"
# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores
una_variabile # => 5
# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione.
# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni.
un_altra_variabile # Genera un errore di nome
# if può essere usato come un'espressione
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# Liste immagazzinano sequenze
li = []
# Puoi partire con una lista pre-riempita
altra_li = [4, 5, 6]
# Aggiungi cose alla fine di una lista con append
li.append(1) # li ora è [1]
li.append(2) # li ora è [1, 2]
li.append(4) # li ora è [1, 2, 4]
li.append(3) # li ora è [1, 2, 4, 3]
# Rimuovi dalla fine della lista con pop
li.pop() # => 3 e li ora è [1, 2, 4]
# Rimettiamolo a posto
li.append(3) # li ora è [1, 2, 4, 3] di nuovo.
# Accedi ad una lista come faresti con un array
li[0] # => 1
# Assegna nuovo valore agli indici che sono già stati inizializzati con =
li[0] = 42
li[0] # => 42
li[0] = 1 # Nota: è resettato al valore iniziale
# Guarda l'ultimo elemento
li[-1] # => 3
# Guardare al di fuori dei limiti è un IndexError
li[4] # Genera IndexError
# Puoi guardare gli intervalli con la sintassi slice (a fetta).
# (E' un intervallo chiuso/aperto per voi tipi matematici.)
li[1:3] # => [2, 4]
# Ometti l'inizio
li[2:] # => [4, 3]
# Ometti la fine
li[:3] # => [1, 2, 4]
# Seleziona ogni seconda voce
li[::2] # =>[1, 4]
# Copia al contrario della lista
li[::-1] # => [3, 4, 2, 1]
# Usa combinazioni per fare slices avanzate
# li[inizio:fine:passo]
# Rimuovi arbitrariamente elementi da una lista con "del"
del li[2] # li è ora [1, 2, 3]
# Puoi sommare le liste
li + altra_li # => [1, 2, 3, 4, 5, 6]
# Nota: i valori per li ed altra_li non sono modificati.
# Concatena liste con "extend()"
li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6]
# Controlla l'esistenza di un valore in una lista con "in"
1 in li # => True
# Esamina la lunghezza con "len()"
len(li) # => 6
# Tuple sono come le liste ma immutabili.
tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # Genera un TypeError
# Puoi fare tutte queste cose da lista anche sulle tuple
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# Puoi scompattare le tuple (o liste) in variabili
a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3
# Le tuple sono create di default se non usi le parentesi
d, e, f = 4, 5, 6
# Guarda come è facile scambiare due valori
e, d = d, e # d è ora 5 ed e è ora 4
# Dizionari immagazzinano mappature
empty_dict = {}
# Questo è un dizionario pre-riempito
filled_dict = {"uno": 1, "due": 2, "tre": 3}
# Accedi ai valori con []
filled_dict["uno"] # => 1
# Ottieni tutte le chiavi come una lista con "keys()"
filled_dict.keys() # => ["tre", "due", "uno"]
# Nota - Nei dizionari l'ordine delle chiavi non è garantito.
# Il tuo risultato potrebbe non essere uguale a questo.
# Ottieni tutt i valori come una lista con "values()"
filled_dict.values() # => [3, 2, 1]
# Nota - Come sopra riguardo l'ordinamento delle chiavi.
# Controlla l'esistenza delle chiavi in un dizionario con "in"
"uno" in filled_dict # => True
1 in filled_dict # => False
# Cercando una chiave non esistente è un KeyError
filled_dict["quattro"] # KeyError
# Usa il metodo "get()" per evitare KeyError
filled_dict.get("uno") # => 1
filled_dict.get("quattro") # => None
# Il metodo get supporta un argomento di default quando il valore è mancante
filled_dict.get("uno", 4) # => 1
filled_dict.get("quattro", 4) # => 4
# nota che filled_dict.get("quattro") è ancora => None
# (get non imposta il valore nel dizionario)
# imposta il valore di una chiave con una sintassi simile alle liste
filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4
# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente
filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5
filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5
# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni)
empty_set = set()
# Inizializza un "set()" con un po' di valori
some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4])
# l'ordine non è garantito, anche se a volta può sembrare ordinato
another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4])
# Da Python 2.7, {} può essere usato per dichiarare un set
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# Aggiungere elementi ad un set
filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5}
# Fai intersezioni su un set con &
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
# Fai unioni su set con |
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Fai differenze su set con -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Controlla l'esistenza in un set con in
2 in filled_set # => True
10 in filled_set # => False
####################################################
## 3. Control Flow
####################################################
# Dichiariamo una variabile
some_var = 5
# Questo è un controllo if. L'indentazione è molto importante in python!
# stampa "some_var è più piccola di 10"
if some_var > 10:
print "some_var è decisamente più grande di 10."
elif some_var < 10: # Questa clausola elif è opzionale.
print "some_var è più piccola di 10."
else: # Anche questo è opzionale.
print "some_var è precisamente 10."
"""
I cicli for iterano sulle liste
stampa:
cane è un mammifero
gatto è un mammifero
topo è un mammifero
"""
for animale in ["cane", "gatto", "topo"]:
# Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.)
print "{0} è un mammifero".format(animale)
"""
"range(numero)" restituisce una lista di numeri
da zero al numero dato
stampa:
0
1
2
3
"""
for i in range(4):
print i
"""
"range(lower, upper)" restituisce una lista di numeri
dal più piccolo (lower) al più grande (upper)
stampa:
4
5
6
7
"""
for i in range(4, 8):
print i
"""
I cicli while vengono eseguiti finchè una condizione viene a mancare
stampa:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 # Forma compatta per x = x + 1
# Gestisci le eccezioni con un blocco try/except
# Funziona da Python 2.6 in su:
try:
# Usa "raise" per generare un errore
raise IndexError("Questo è un errore di indice")
except IndexError as e:
pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero.
except (TypeError, NameError):
pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario.
else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except
print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni
finally: # Eseguito sempre
print "Possiamo liberare risorse qui"
# Invece di try/finally per liberare risorse puoi usare il metodo with
with open("myfile.txt") as f:
for line in f:
print line
####################################################
## 4. Funzioni
####################################################
# Usa "def" per creare nuove funzioni
def aggiungi(x, y):
print "x è {0} e y è {1}".format(x, y)
return x + y # Restituisce valori con il metodo return
# Chiamare funzioni con parametri
aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11
# Un altro modo per chiamare funzioni è con parole chiave come argomenti
aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine.
# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali
# che verranno interpretati come tuple se non usi il *
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
# Puoi definire funzioni che accettano un numero variabile di parole chiave
# come argomento, che saranno interpretati come un dizionario se non usi **
def keyword_args(**kwargs):
return kwargs
# Chiamiamola per vedere cosa succede
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# Puoi farle entrambi in una volta, se ti va
def all_the_args(*args, **kwargs):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) stampa:
(1, 2)
{"a": 3, "b": 4}
"""
# Quando chiami funzioni, puoi fare l'opposto di args/kwargs!
# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs
# sviluppandoli, rispettivamente, con * e **
def pass_all_the_args(*args, **kwargs):
all_the_args(*args, **kwargs)
print varargs(*args)
print keyword_args(**kwargs)
# Funzioni Scope
x = 5
def setX(num):
# La variabile locale x non è uguale alla variabile globale x
x = num # => 43
print x # => 43
def setGlobalX(num):
global x
print x # => 5
x = num # la variabile globable x è ora 6
print x # => 6
setX(43)
setGlobalX(6)
# Python ha funzioni di prima classe
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
# Ci sono anche funzioni anonime
(lambda x: x > 2)(3) # => True
# Esse sono incluse in funzioni di alto livello
map(add_10, [1, 2, 3]) # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# Possiamo usare la comprensione delle liste per mappe e filtri
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Classi
####################################################
# Usiamo una sottoclasse da un oggetto per avere una classe.
class Human(object):
# Un attributo della classe. E' condiviso da tutte le istanze delle classe
species = "H. sapiens"
# Costruttore base, richiamato quando la classe viene inizializzata.
# Si noti che il doppio leading e gli underscore finali denotano oggetti
# o attributi che sono usati da python ma che vivono nello spazio dei nome controllato
# dall'utente. Non dovresti usare nomi di questo genere.
def __init__(self, name):
# Assegna l'argomento all'attributo name dell'istanza
self.name = name
# Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
# Un metodo della classe è condiviso fra tutte le istanze
# Sono chiamate con la classe chiamante come primo argomento
@classmethod
def get_species(cls):
return cls.species
# Un metodo statico è chiamato senza una classe od una istanza di riferimento
@staticmethod
def grunt():
return "*grunt*"
# Instanziare una classe
i = Human(name="Ian")
print i.say("hi") # stampa "Ian: hi"
j = Human("Joel")
print j.say("hello") # stampa "Joel: hello"
# Chiamare metodi della classe
i.get_species() # => "H. sapiens"
# Cambiare l'attributo condiviso
Human.species = "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
# Chiamare il metodo condiviso
Human.grunt() # => "*grunt*"
####################################################
## 6. Moduli
####################################################
# Puoi importare moduli
import math
print math.sqrt(16) # => 4
# Puoi ottenere specifiche funzione da un modulo
from math import ceil, floor
print ceil(3.7) # => 4.0
print floor(3.7) # => 3.0
# Puoi importare tutte le funzioni da un modulo
# Attenzione: questo non è raccomandato
from math import *
# Puoi abbreviare i nomi dei moduli
import math as m
math.sqrt(16) == m.sqrt(16) # => True
# puoi anche verificare che le funzioni sono equivalenti
from math import sqrt
math.sqrt == m.sqrt == sqrt # => True
# I moduli di Python sono normali file python. Ne puoi
# scrivere di tuoi ed importarli. Il nome del modulo
# è lo stesso del nome del file.
# Potete scoprire quali funzioni e attributi
# definiscono un modulo
import math
dir(math)
####################################################
## 7. Avanzate
####################################################
# I generatori ti aiutano a fare codice pigro
def double_numbers(iterable):
for i in iterable:
yield i + i
# Un generatore crea valori al volo.
# Invece di generare e ritornare tutti i valori in una volta ne crea uno in ciascuna
# iterazione. Ciò significa che i valori più grandi di 15 non saranno considerati in
# double_numbers.
# Nota xrange è un generatore che fa la stessa cosa di range.
# Creare una lista 1-900000000 occuperebbe molto tempo e spazio.
# xrange crea un oggetto generatore xrange invece di creare l'intera lista
# come fa range.
# Usiamo un underscore finale nel nome delle variabile quando vogliamo usare un nome
# che normalmente colliderebbe con una parola chiave di python
xrange_ = xrange(1, 900000000)
# raddoppierà tutti i numeri fino a che result >=30 non sarà trovato
for i in double_numbers(xrange_):
print i
if i >= 30:
break
# Decoratori
# in questo esempio beg include say
# Beg chiamerà say. Se say_please è True allora cambierà il messaggio
# ritornato
from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Per favore! Sono povero :(")
return msg
return wrapper
@beg
def say(say_please=False):
msg = "Puoi comprarmi una birra?"
return msg, say_please
print say() # Puoi comprarmi una birra?
print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :(
```
## Pronto per qualcosa di più?
### Gratis Online
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
* [The Official Docs](http://docs.python.org/2.6/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
### Libri cartacei
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)

View File

@ -535,7 +535,7 @@ class PennyFarthing extends Bicycle {
// (Penny Farthings are those bicycles with the big front wheel.
// They have no gears.)
public PennyFarthing(int startCadence, int startSpeed){
public PennyFarthing(int startCadence, int startSpeed) {
// Call the parent constructor with super
super(startCadence, startSpeed, 0, "PennyFarthing");
}

View File

@ -151,12 +151,16 @@ a = Int64[] # => 0-element Int64 Array
# 1-dimensional array literals can be written with comma-separated values.
b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6]
b[1] # => 4
b[end] # => 6
# 2-dimentional arrays use space-separated values and semicolon-separated rows.
matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
# Arrays of a particular Type
b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6]
# Add stuff to the end of a list with push! and append!
push!(a,1) # => [1]
push!(a,2) # => [1,2]

View File

@ -26,6 +26,7 @@ specific to a certain parser.
## HTML Elements
Markdown is a superset of HTML, so any HTML file is valid Markdown.
```markdown
<!--This means we can use HTML elements in Markdown, such as the comment element,
and they won't be affected by a markdown parser. However, if you create an HTML element
@ -54,6 +55,7 @@ This is an h1
This is an h2
-------------
```
## Simple text styles
Text can be easily styled as italic or bold using markdown.
@ -133,6 +135,7 @@ or
- Item
- One last item
```
Ordered lists are done with a number followed by a period.
```markdown
@ -152,6 +155,7 @@ render the numbers in order, but this may not be a good idea.
(This renders the same as the above example)
You can also use sublists
```markdown
1. Item one
2. Item two
@ -197,13 +201,13 @@ John didn't even know what the `go_to()` function did!
```
In Github Flavored Markdown, you can use a special syntax for code
```markdown
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
<pre>
<code class="highlight">&#x60;&#x60;&#x60;ruby
def foobar
puts "Hello world!"
end
\`\`\` <!-- here too, no backslashes, just ``` -->
```
&#x60;&#x60;&#x60;</code></pre>
The above text doesn't require indenting, plus Github will use syntax
highlighting of the language you specify after the \`\`\`
@ -212,6 +216,7 @@ highlighting of the language you specify after the \`\`\`
Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
with or without spaces.
```markdown
***
---
@ -228,58 +233,64 @@ the text to display in hard brackets [] followed by the url in parentheses ()
[Click me!](http://test.com/)
```
You can also add a link title using quotes inside the parentheses.
```markdown
[Click me!](http://test.com/ "Link to Test.com")
```
Relative paths work too.
```markdown
[Go to music](/music/).
```
Markdown also supports reference style links.
```markdown
[Click this link][link1] for more info about it!
[Also check out this link][foobar] if you want to.
[link1]: http://test.com/ "Cool!"
[foobar]: http://foobar.biz/ "Alright!"
```
Markdown also supports reference style links.
<pre><code class="highlight">&#x5b;<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it!
&#x5b;<span class="nv">Also check out this link</span>][<span class="ss">foobar</span>] if you want to.
&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Alright!"</span></code></pre>
The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
can be anything so long as they are unique.
There is also "implicit naming" which lets you use the link text as the id.
```markdown
[This][] is a link.
[this]: http://thisisalink.com/
```
<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
But it's not that commonly used.
## Images
Images are done the same way as links but with an exclamation point in front!
```markdown
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
```
And reference style works as expected.
```markdown
![This is the alt-attribute.][myimage]
[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
```
<pre><code class="highlight">!&#x5b;<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
## Miscellany
### Auto-links
```markdown
<http://testwebsite.com/> is equivalent to
[http://testwebsite.com/](http://testwebsite.com/)
```
### Auto-links for emails
```markdown
<foo@bar.com>
```
### Escaping characters
```markdown
I want to type *this text surrounded by asterisks* but I don't want it to be
in italics, so I do this: \*this text surrounded by asterisks\*.
@ -288,6 +299,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*.
### Keyboard keys
In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
```markdown
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
@ -296,6 +308,7 @@ Your computer crashed? Try sending a
Tables are only available in Github Flavored Markdown and are slightly
cumbersome, but if you really want it:
```markdown
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
@ -309,5 +322,6 @@ Col 1 | Col2 | Col3
:-- | :-: | --:
Ugh this is so ugly | make it | stop
```
---
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).

102
ms-my/json-my.html.markdown Normal file
View File

@ -0,0 +1,102 @@
---
language: json
filename: learnjson-ms.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["himanshu", "https://github.com/himanshu81494"]
- ["Michael Neth", "https://github.com/infernocloud"]
translators:
- ["abdalim", "https://github.com/abdalim"]
lang: ms-my
---
Disebabkan JSON adalah format pertukaran-data yang sangat ringkas, panduan ini
kemungkinan besar adalah Learn X in Y Minutes yang paling mudah.
JSON dalam bentuk paling aslinya sebenarnya tidak mempunyai sebarang komentar,
tetapi kebanyakan pembaca menerima komen dalam bentuk C (`\\`,`/* */`). Beberapa
pembaca juga bertoleransi terhadap koma terakhir (iaitu koma selepas elemen
terakhir di dalam array atau selepas ciri terakhir sesuatu objek), tetapi semua
ini harus dielakkan dan dijauhkan untuk keserasian yang lebih baik.
Untuk tujuan ini bagaimanapun, semua di dalam panduan ini adalah 100% JSON yang
sah. Luckily, it kind of speaks for itself.
Sebuah nilai JSON harus terdiri dari salah satu, iaitu, nombor, string, array,
objek atau salah satu dari nama literal berikut: true, false, null.
Pelayar web yang menyokong adalah: Firefox 3.5+, Internet Explorer 8.0+, Chrome
1.0+, Opera 10.0+, dan Safari 4.0+.
Sambungan fail untuk fail - fail JSON adalah ".json" dan jenis MIME untuk teks
JSON adalah "application/json".
Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan
menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript
mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data.
Maklumat lebih lanjut boleh dijumpai di http://www.json.org/
JSON dibina pada dua struktur:
* Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini
direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table",
senarai berkunci, atau "associative array".
* Sebuah senarai nilai yang tersusun. Dalam kebanyakan bahasa aturcara, ini
direalisasikan sebagai array, vektor, senarai atau urutan.
Sebuah objek dengan pelbagai pasangan nama/nilai.
```json
{
"kunci": "nilai",
"kekunci": "harus sentiasa dibalut dengan 'double quotes'",
"nombor": 0,
"strings": "Hellø, wørld. Semua unicode dibenarkan, bersama \"escaping\".",
"ada bools?": true,
"tiada apa - apa": null,
"nombor besar": 1.2e+100,
"objek": {
"komen": "Sebahagian besar struktur akan terdiri daripada objek.",
"array": [0, 1, 2, 3, "Array boleh mempunyai sebarang jenis data di dalamnya.", 5],
"objek lain": {
"komen": "Objek boleh dibina dengan pelbagai lapisan, sangat berguna."
}
},
"kebendulan": [
{
"punca potassium": ["pisang"]
},
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, "neo"],
[0, 0, 0, 1]
]
],
"stail alternatif": {
"komen": "cuba lihat ini!"
, "posisi koma": "tidak mengapa - selagi ia adalah sebelum nama atau kunci seterusnya, maka ia sah"
, "komen lain": "sungguh bagus"
}
}
```
Sebuah array sahaja yang mengandungi nilai - nilai juga adalah JSON yang sah.
```json
[1, 2, 3, "text", true]
```
Objek - objek boleh menjadi sebahagian dari array juga.
```json
[{"nama": "Abe", "umur": 25}, {"nama": "Jemah", "umur": 29}, {"name": "Yob", "umur": 31}]
```

View File

@ -103,7 +103,7 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument
## It can also have optional arguments:
sub with-optional($arg?) { # the "?" marks the argument optional
say "I might return `(Any)` (Perl's "null"-like value) if I don't have
say "I might return `(Any)` (Perl's 'null'-like value) if I don't have
an argument passed, or I'll return my argument";
$arg;
}
@ -803,9 +803,8 @@ module Foo::Bar {
my sub unavailable { # `my sub` is the default
say "Can't access me from outside, I'm my !";
}
say ++$n; # increment the package variable and output its value
}
say ++$n; # lexically-scoped variables are still available
}
say $Foo::Bar::n; #=> 1
Foo::Bar::inc; #=> 2
@ -1330,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
### Extra: the MAIN subroutime
### Extra: the MAIN subroutine
# The `MAIN` subroutine is called when you run a Perl 6 file directly.
# It's very powerful, because Perl 6 actually parses the arguments
# and pass them as such to the sub. It also handles named argument (`--foo`)

View File

@ -53,6 +53,8 @@ $int1 = 12; // => 12
$int2 = -12; // => -12
$int3 = 012; // => 10 (a leading 0 denotes an octal number)
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
// Binary integer literals are available since PHP 5.4.0.
$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number)
// Floats (aka doubles)
$float = 1.234;
@ -116,11 +118,11 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
// a valid constant name starts with a letter or underscore,
// followed by any number of letters, numbers, or underscores.
define("FOO", "something");
define("FOO", "something");
// access to a constant is possible by calling the choosen name without a $
echo FOO; // Returns 'something'
echo 'This outputs '.FOO; // Returns 'This ouputs something'
echo 'This outputs ' . FOO; // Returns 'This ouputs something'
@ -765,6 +767,37 @@ I'm a ParentClass
But I'm ChildClass
*/
/**********************
* Magic constants
*
*/
// Get current class name. Must be used inside a class declaration.
echo "Current class name is " . __CLASS__;
// Get full path directory of a file
echo "Current directory is " . __DIR__;
// Typical usage
require __DIR__ . '/vendor/autoload.php';
// Get full path of a file
echo "Current file path is " . __FILE__;
// Get current function name
echo "Current function name is " . __FUNCTION__;
// Get current line number
echo "Current line number is " . __LINE__;
// Get the name of the current method. Only returns a value when used inside a trait or object declaration.
echo "Current method is " . __METHOD__;
// Get the name of the current namespace
echo "Current namespace is " . __NAMESPACE__;
// Get the name of the current trait. Only returns a value when used inside a trait or object declaration.
echo "Current namespace is " . __TRAIT__;
/**********************
* Error Handling

View File

@ -163,7 +163,7 @@ z repozytorium CPAN do zrealizowania konkretnego zadania.
#### Do doczytania
- [perl-tutorial](http://perl-tutorial.org/)
- [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- wbudowane w Perla: `perldoc perlintro`
- [perl-tutorial](http://perl-tutorial.org/)
- [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- wbudowane w Perla: `perldoc perlintro`

View File

@ -18,6 +18,7 @@ rather than plain text.
[Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx)
If you are uncertain about your environment:
```
Get-ExecutionPolicy -List
Set-ExecutionPolicy AllSigned
@ -33,6 +34,7 @@ $PSVersionTable
```
Getting help:
```
# Find commands
Get-Command about_* # alias: gcm
@ -49,6 +51,7 @@ Update-Help # Run as admin
```
The tutorial starts here:
```
# As you already figured, comments start with #
@ -244,10 +247,12 @@ function New-Website() {
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
# Note that .NET functions MUST be called with parentheses
# while PS functions CANNOT be called with parentheses
# while PS functions CANNOT be called with parentheses.
# If you do call a cmdlet/PS function with parentheses,
# it is the same as passing a single parameter list
$writer = New-Object System.IO.StreamWriter($path, $true)
$writer.Write([Environment]::NewLine)
$write.Dispose()
$writer.Dispose()
### IO
# Reading a value from input:
@ -265,12 +270,14 @@ Get-Command ConvertTo-*,ConvertFrom-*
# Refresh your PATH
$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
# Find Python in path
$env:PATH.Split(";") | Where-Object { $_ -like "*python*"}
# Change working directory without having to remember previous path
Push-Location c:\temp # change working directory to c:\temp
Pop-Location # change back to previous working directory
# Aliases are: pushd and popd
# Unblock a directory after download
Get-ChildItem -Recurse | Unblock-File
@ -292,6 +299,7 @@ $Shortcut.Save()
Configuring your shell
```
# $Profile is the full path for your `Microsoft.PowerShell_profile.ps1`
# All code there will be executed when the PS session starts
@ -304,6 +312,7 @@ if (-not (Test-Path $Profile)) {
```
Interesting Projects
* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
@ -314,6 +323,7 @@ Interesting Projects
* [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead)
Not covered
* WMI: Windows Management Intrumentation (Get-CimInstance)
* Multitasking: Start-Job -scriptBlock {...},
* Code Signing

View File

@ -726,6 +726,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
* [Fullstack Python](https://www.fullstackpython.com/)
### Dead Tree

View File

@ -97,13 +97,13 @@ False or True # => True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# (is vs. ==) is checks if two variable refer to the same object, but == checks
# (is vs. ==) is checks if two variables refer to the same object, but == checks
# if the objects pointed to have the same values.
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b = a # Point b at what a is pointing to
b is a # => True, a and b refer to the same object
b == a # => True, a's and b's objects are equal
b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
b is a # => False, a and b do not refer to the same object
b == a # => True, a's and b's objects are equal

View File

@ -9,6 +9,8 @@ This is a tutorial on how to do some typical statistical programming tasks using
```python
# 0. Getting set up ====
""" Get set up with IPython and pip install the following: numpy, scipy, pandas,
@ -25,17 +27,17 @@ This is a tutorial on how to do some typical statistical programming tasks using
already using Python, there's a benefit to sticking with one language.
"""
import requests # for HTTP requests (web scraping, APIs)
import requests # for HTTP requests (web scraping, APIs)
import os
# web scraping
r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
r.status_code # if 200, request was successful
r.text # raw page source
print(r.text) # prettily formatted
r.status_code # if 200, request was successful
r.text # raw page source
print(r.text) # prettily formatted
# save the page source in a file:
os.getcwd() # check what's the working directory
f = open("learnxinyminutes.html","wb")
os.getcwd() # check what's the working directory
f = open("learnxinyminutes.html", "wb")
f.write(r.text.encode("UTF-8"))
f.close()
@ -44,7 +46,7 @@ fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/"
fn = "pets.csv"
r = requests.get(fp + fn)
print(r.text)
f = open(fn,"wb")
f = open(fn, "wb")
f.write(r.text.encode("UTF-8"))
f.close()
@ -58,7 +60,9 @@ f.close()
you've used R, you will be familiar with the idea of the "data.frame" already.
"""
import pandas as pd, numpy as np, scipy as sp
import pandas as pd
import numpy as np
import scipy as sp
pets = pd.read_csv(fn)
pets
# name age weight species
@ -74,20 +78,20 @@ pets
pets.age
pets["age"]
pets.head(2) # prints first 2 rows
pets.tail(1) # prints last row
pets.head(2) # prints first 2 rows
pets.tail(1) # prints last row
pets.name[1] # 'vesuvius'
pets.species[0] # 'cat'
pets["weight"][2] # 34
pets.name[1] # 'vesuvius'
pets.species[0] # 'cat'
pets["weight"][2] # 34
# in R, you would expect to get 3 rows doing this, but here you get 2:
pets.age[0:2]
# 0 3
# 1 6
sum(pets.age)*2 # 28
max(pets.weight) - min(pets.weight) # 20
sum(pets.age) * 2 # 28
max(pets.weight) - min(pets.weight) # 20
""" If you are doing some serious linear algebra and number-crunching, you may
just want arrays, not DataFrames. DataFrames are ideal for combining columns
@ -96,7 +100,8 @@ max(pets.weight) - min(pets.weight) # 20
# 3. Charts ====
import matplotlib as mpl, matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
# To do data vizualization in Python, use matplotlib
@ -105,13 +110,17 @@ plt.hist(pets.age);
plt.boxplot(pets.weight);
plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
plt.scatter(pets.age, pets.weight)
plt.xlabel("age")
plt.ylabel("weight");
# seaborn sits atop matplotlib and makes plots prettier
import seaborn as sns
plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
plt.scatter(pets.age, pets.weight)
plt.xlabel("age")
plt.ylabel("weight");
# there are also some seaborn-specific plotting functions
# notice how seaborn automatically labels the x-axis on this barplot
@ -141,7 +150,7 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv"
r = requests.get(url)
fp = "hre.csv"
f = open(fp,"wb")
f = open(fp, "wb")
f.write(r.text.encode("UTF-8"))
f.close()
@ -149,33 +158,33 @@ hre = pd.read_csv(fp)
hre.head()
"""
Ix Dynasty Name Birth Death Election 1
0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN
1 NaN Carolingian Louis I 778 20 June 840 NaN
2 NaN Carolingian Lothair I 795 29 September 855 NaN
3 NaN Carolingian Louis II 825 12 August 875 NaN
4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN
Ix Dynasty Name Birth Death Election 1
0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN
1 NaN Carolingian Louis I 778 20 June 840 NaN
2 NaN Carolingian Lothair I 795 29 September 855 NaN
3 NaN Carolingian Louis II 825 12 August 875 NaN
4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN
Election 2 Coronation 1 Coronation 2 Ceased to be Emperor
0 NaN 25 December 800 NaN 28 January 814
1 NaN 11 September 813 5 October 816 20 June 840
2 NaN 5 April 823 NaN 29 September 855
3 NaN Easter 850 18 May 872 12 August 875
4 NaN 29 December 875 NaN 6 October 877
Election 2 Coronation 1 Coronation 2 Ceased to be Emperor
0 NaN 25 December 800 NaN 28 January 814
1 NaN 11 September 813 5 October 816 20 June 840
2 NaN 5 April 823 NaN 29 September 855
3 NaN Easter 850 18 May 872 12 August 875
4 NaN 29 December 875 NaN 6 October 877
Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2
0 NaN NaN NaN NaN
1 Charles I son NaN NaN
2 Louis I son NaN NaN
3 Lothair I son NaN NaN
4 Louis I son NaN NaN
Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2
0 NaN NaN NaN NaN
1 Charles I son NaN NaN
2 Louis I son NaN NaN
3 Lothair I son NaN NaN
4 Louis I son NaN NaN
"""
# clean the Birth and Death columns
import re # module for regular expressions
import re # module for regular expressions
rx = re.compile(r'\d+$') # match trailing digits
rx = re.compile(r'\d+$') # match trailing digits
""" This function applies the regular expression to an input column (here Birth,
Death), flattens the resulting list, converts it to a Series object, and
@ -185,8 +194,9 @@ rx = re.compile(r'\d+$') # match trailing digits
- http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list
- http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html
"""
def extractYear(v):
return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int))
return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int))
hre["BirthY"] = extractYear(hre.Birth)
hre["DeathY"] = extractYear(hre.Death)
@ -199,17 +209,17 @@ sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False);
# use scipy to run a linear regression
from scipy import stats
(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge)
(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge)
# code source: http://wiki.scipy.org/Cookbook/LinearRegression
# check the slope
slope # 0.0057672618839073328
slope # 0.0057672618839073328
# check the R^2 value:
rval**2 # 0.020363950027333586
rval**2 # 0.020363950027333586
# check the p-value
pval # 0.34971812581498452
pval # 0.34971812581498452
# use seaborn to make a scatterplot and plot the linear regression trend line
sns.lmplot("BirthY", "EstAge", data=hre);
@ -223,6 +233,7 @@ sns.lmplot("BirthY", "EstAge", data=hre);
To see a version of the Holy Roman Emperors analysis using R, see
- http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
"""
```
If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial.

View File

@ -594,3 +594,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.

View File

@ -327,9 +327,15 @@ divideInts(10, 3) // (Int, Int) = (3,1)
val d = divideInts(10, 3) // (Int, Int) = (3,1)
d._1 // Int = 3
d._2 // Int = 1
// Alternatively you can do multiple-variable assignment to tuple, which is more
// convenient and readable in many cases
val (div, mod) = divideInts(10, 3)
div // Int = 3
mod // Int = 1
/////////////////////////////////////////////////
// 5. Object Oriented Programming
@ -460,6 +466,9 @@ def matchEverything(obj: Any): String = obj match {
// You can nest patterns:
case List(List((1, 2, "YAY"))) => "Got a list of list of tuple"
// Match any case (default) if all previous haven't matched
case _ => "Got unknown object"
}
// In fact, you can pattern match any object with an "unapply" method. This
@ -612,6 +621,9 @@ import scala.collection.immutable.{List => ImmutableList}
// Import all classes, except some. The following excludes Map and Set:
import scala.collection.immutable.{Map => _, Set => _, _}
// Java classes can also be imported. Scala syntax can be used
import java.swing.{JFrame, JWindow}
// Your programs entry point is defined in an scala file using an object, with a
// single method, main:
object Application {

View File

@ -213,7 +213,7 @@ default: // required (in order to cover all possible input)
// Functions are a first-class type, meaning they can be nested
// in functions and can be passed around
// Function with Swift header docs (format as reStructedText)
// Function with Swift header docs (format as Swift-modified Markdown syntax)
/**
A greet operation
@ -221,9 +221,9 @@ A greet operation
- A bullet in docs
- Another bullet in the docs
:param: name A name
:param: day A day
:returns: A string containing the name and day value.
- Parameter name : A name
- Parameter day : A day
- Returns : A string containing the name and day value.
*/
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
@ -392,7 +392,7 @@ testTryStuff()
public class Shape {
public func getArea() -> Int {
return 0;
return 0
}
}

View File

@ -7,7 +7,7 @@ filename: LearnTmux.txt
---
[tmux](http://tmux.sourceforge.net)
[tmux](http://tmux.github.io)
is a terminal multiplexer: it enables a number of terminals
to be created, accessed, and controlled from a single screen. tmux
may be detached from a screen and continue running in the background
@ -240,7 +240,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] |
### References
[Tmux | Home](http://tmux.sourceforge.net)
[Tmux | Home](http://tmux.github.io)
[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux)

View File

@ -25,14 +25,14 @@ import UIKit
//XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot
listesinde gruplama yapmanıza olanak sağlıyor
//listesinde gruplama yapmanıza olanak sağlıyor
// MARK: Bölüm işareti
// TODO: Daha sonra yapılacak
// FIXME: Bu kodu düzelt
//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print
otomatik olarak yeni satır ekliyor.
//Swift 2 de, println ve print metotları print komutunda birleştirildi.
//Print otomatik olarak yeni satır ekliyor.
print("Merhaba dünya") // println print olarak kullanılıyor.
print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar.
@ -75,7 +75,7 @@ print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7
*/
var baziOptionalString: String? = "optional" // nil olabilir.
// yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay
okunabilir)
//okunabilir)
var someOptionalString2: Optional<String> = "optional"
@ -104,7 +104,8 @@ if let baziOpsiyonelSabitString = baziOptionalString {
// Swift değişkenlerde herhangi bir tip saklanabilir.
// AnyObject == id
// Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle
çalışabilir (Class, Int, struct, etc)
//çalışabilir
(Class, Int, struct, etc)
var herhangiBirObject: AnyObject = 7
herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün"
@ -234,7 +235,7 @@ func fiyatlariGetir() -> (Double, Double, Double) {
let fiyatTuple = fiyatlariGetir()
let fiyat = fiyatTuple.2 // 3.79
// _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden
gelir
//gelir
let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69
print(fiyat1 == fiyatTuple.1) // true
print("Benzin fiyatı: \(fiyat)")

View File

@ -159,6 +159,14 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"});
// Including references to a definition file:
/// <reference path="jquery.d.ts" />
// Template Strings (strings that use backticks)
// String Interpolation with Template Strings
var name = 'Tyrone';
var greeting = `Hi ${name}, how are you?`
// Multiline Strings with Template Strings
var multiline = `This is an example
of a multiline string`;
```
## Further Reading

View File

@ -210,7 +210,7 @@ f2 = {a = 2, b = 3}
metafraction = {}
function metafraction.__add(f1, f2)
sum = {}
local sum = {}
sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b
return sum
@ -273,7 +273,7 @@ eatenBy = myFavs.animal -- 可以工作!感谢元表
Dog = {} -- 1.
function Dog:new() -- 2.
newObj = {sound = 'woof'} -- 3.
local newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4.
return setmetatable(newObj, self) -- 5.
end
@ -307,7 +307,7 @@ mrDog:makeSound() -- 'I say woof' -- 8.
LoudDog = Dog:new() -- 1.
function LoudDog:makeSound()
s = self.sound .. ' ' -- 2.
local s = self.sound .. ' ' -- 2.
print(s .. s .. s)
end

253
zh-cn/tmux-cn.html.markdown Normal file
View File

@ -0,0 +1,253 @@
---
category: tool
tool: tmux
filename: LearnTmux-cn.txt
contributors:
- ["mdln", "https://github.com/mdln"]
translators:
- ["Arnie97", "https://github.com/Arnie97"]
lang: zh-cn
---
[tmux](http://tmux.github.io)是一款终端复用工具。
在它的帮助下,你可以在同一个控制台上建立、访问并控制多个终端。
你可以断开与一个 tmux 终端的连接,此时程序将在后台运行,
当你需要时,可以随时重新连接到这个终端。
```
tmux [command] # 运行一条命令
# 如果单独使用 'tmux' 而不指定某个命令,将会建立一个新的会话
new # 创建一个新的会话
-s "Session" # 创建一个会话并命名为“Session”
-n "Window" # 创建一个窗口并命名为“Window”
-c "/dir" # 在指定的工作目录中启动会话
attach # 连接到上一次的会话(如果可用)
-t "#" # 连接到指定的会话
-d # 断开其他客户端的会话
ls # 列出打开的会话
-a # 列出所有打开的会话
lsw # 列出窗口
-a # 列出所有窗口
-s # 列出会话中的所有窗口
lsp # 列出窗格
-a # 列出所有窗格
-s # 列出会话中的所有窗格
-t "#" # 列出指定窗口中的所有窗格
kill-window # 关闭当前窗口
-t "#" # 关闭指定的窗口
-a # 关闭所有窗口
-a -t "#" # 关闭除指定窗口以外的所有窗口
kill-session # 关闭当前会话
-t "#" # 关闭指定的会话
-a # 关闭所有会话
-a -t "#" # 关闭除指定会话以外的所有会话
```
### 快捷键
通过“前缀”快捷键,可以控制一个已经连入的 tmux 会话。
```
----------------------------------------------------------------------
(C-b) = Ctrl + b # 在使用下列快捷键之前,需要按这个“前缀”快捷键
(M-1) = Meta + 1 或 Alt + 1
----------------------------------------------------------------------
? # 列出所有快捷键
: # 进入 tmux 的命令提示符
r # 强制重绘当前客户端
c # 创建一个新窗口
! # 将当前窗格从窗口中移出,成为为一个新的窗口
% # 将当前窗格分为左右两半
" # 将当前窗格分为上下两半
n # 切换到下一个窗口
p # 切换到上一个窗口
{ # 将当前窗格与上一个窗格交换
} # 将当前窗格与下一个窗格交换
s # 在交互式界面中,选择并连接至另一个会话
w # 在交互式界面中,选择并激活一个窗口
0 至 9 # 选择 0 到 9 号窗口
d # 断开当前客户端
D # 选择并断开一个客户端
& # 关闭当前窗口
x # 关闭当前窗格
Up, Down # 将焦点移动至相邻的窗格
Left, Right
M-1 到 M-5 # 排列窗格:
# 1) 水平等分
# 2) 垂直等分
# 3) 将一个窗格作为主要窗格,其他窗格水平等分
# 4) 将一个窗格作为主要窗格,其他窗格垂直等分
# 5) 平铺
C-Up, C-Down # 改变当前窗格的大小,每按一次增减一个单位
C-Left, C-Right
M-Up, M-Down # 改变当前窗格的大小,每按一次增减五个单位
M-Left, M-Right
```
### 配置 ~/.tmux.conf
tmux.conf 可以在 tmux 启动时自动设置选项,类似于 .vimrc 或 init.el 的用法。
```
# tmux.conf 示例
# 2014.10
### 通用设置
###########################################################################
# 启用 UTF-8 编码
setw -g utf8 on
set-option -g status-utf8 on
# 命令回滚/历史数量限制
set -g history-limit 2048
# 从 1 开始编号,而不是从 0 开始
set -g base-index 1
# 启用鼠标
set-option -g mouse-select-pane on
# 重新加载配置文件
unbind r
bind r source-file ~/.tmux.conf
### 快捷键设置
###########################################################################
# 取消默认的前缀键 C-b
unbind C-b
# 设置新的前缀键 `
set-option -g prefix `
# 多次按下前缀键时,切换到上一个窗口
bind C-a last-window
bind ` last-window
# 按下F11/F12可以选择不同的前缀键
bind F11 set-option -g prefix C-a
bind F12 set-option -g prefix `
# Vim 风格的快捷键绑定
setw -g mode-keys vi
set-option -g status-keys vi
# 使用 Vim 风格的按键在窗格间移动
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
# 循环切换不同的窗口
bind e previous-window
bind f next-window
bind E swap-window -t -1
bind F swap-window -t +1
# 较易于使用的窗格分割快捷键
bind = split-window -h
bind - split-window -v
unbind '"'
unbind %
# 在嵌套使用 tmux 的情况下,激活最内层的会话,以便向其发送命令
bind a send-prefix
### 外观主题
###########################################################################
# 状态栏颜色
set-option -g status-justify left
set-option -g status-bg black
set-option -g status-fg white
set-option -g status-left-length 40
set-option -g status-right-length 80
# 窗格边框颜色
set-option -g pane-active-border-fg green
set-option -g pane-active-border-bg black
set-option -g pane-border-fg white
set-option -g pane-border-bg black
# 消息框颜色
set-option -g message-fg black
set-option -g message-bg green
# 窗口状态栏颜色
setw -g window-status-bg black
setw -g window-status-current-fg green
setw -g window-status-bell-attr default
setw -g window-status-bell-fg red
setw -g window-status-content-attr default
setw -g window-status-content-fg yellow
setw -g window-status-activity-attr default
setw -g window-status-activity-fg yellow
### 用户界面
###########################################################################
# 通知方式
setw -g monitor-activity on
set -g visual-activity on
set-option -g bell-action any
set-option -g visual-bell off
# 自动设置窗口标题
set-option -g set-titles on
set-option -g set-titles-string '#H:#S.#I.#P #W #T' # 窗口编号,程序名称,是否活动
# 调整状态栏
set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
# 在状态栏中显示性能计数器
# 需要用到 https://github.com/thewtex/tmux-mem-cpu-load
set -g status-interval 4
set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]"
```
### 参考资料
[Tmux 主页](http://tmux.github.io)
[Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux)
[FreeBSDChina Wiki](https://wiki.freebsdchina.org/software/t/tmux)
[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文))
[Tmux 快速教程](http://blog.jeswang.org/blog/2013/06/24/tmux-kuai-su-jiao-cheng)
[如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
[管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator)

View File

@ -0,0 +1,727 @@
---
language: python
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
- ["Andre Polykanine", "https://github.com/Oire"]
- ["evuez", "http://github.com/evuez"]
translators:
- ["Michael Yeh", "https://hinet60613.github.io/"]
filename: learnpython-tw.py
lang: zh-tw
---
Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法甚至可以說它就是可執行的虛擬碼。
非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。
註: 本篇文章適用的版本為Python 2.7但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護因此建議您可以從Python 3開始學Python。
Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/).
讓程式碼同時支援Python 2.7和3.X是可以做到的只要引入
[`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組.
`__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼詳細訊息請參考Python 3 教學。
```python
# 單行註解從井字號開始
""" 多行字串可以用三個雙引號
包住,不過通常這種寫法會
被拿來當作多行註解
"""
####################################################
## 1. 原始型別與運算元
####################################################
# 你可以使用數字
3 # => 3
# 還有四則運算
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7
# 除法比較麻煩,除以整數時會自動捨去小數位。
5 / 2 # => 2
# 要做精確的除法,我們需要浮點數
2.0 # 浮點數
11.0 / 4.0 # => 2.75 精確多了!
# 整數除法的無條件捨去對正數或負數都適用
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # 浮點數的整數也適用
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# 我們可以用除法模組(參考第六節:模組),讓
# 單一斜線代表普通除法,而非無條件捨去
from __future__ import division
11/4 # => 2.75 ...普通除法
11//4 # => 2 ...無條件捨去
# 取餘數
7 % 3 # => 1
# 指數 (x的y次方)
2**4 # => 16
# 用括號改變運算順序
(1 + 3) * 2 # => 8
# 布林運算
# 注意 "and" 和 "or" 要用小寫
True and False #=> False
False or True #=> True
# 用整數與布林值做運算
0 and 2 #=> 0
-5 or 0 #=> -5
0 == False #=> True
2 == True #=> False
1 == True #=> True
# 用not取反向
not True # => False
not False # => True
# 等於判斷是用 ==
1 == 1 # => True
2 == 1 # => False
# 不等於判斷是用 !=
1 != 1 # => False
2 != 1 # => True
# 更多比較
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# 比較是可以串接的
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# 字串用單引號 ' 或雙引號 " 建立
"This is a string."
'This is also a string.'
# 字串相加會被串接再一起
"Hello " + "world!" # => "Hello world!"
# 不用加號也可以做字串相加
"Hello " "world!" # => "Hello world!"
# ... 也可以做相乘
"Hello" * 3 # => "HelloHelloHello"
# 字串可以被視為字元的陣列
"This is a string"[0] # => 'T'
# 字串的格式化可以用百分之符號 %
# 儘管在Python 3.1後這個功能被廢棄了,並且在
# 之後的版本會被移除,但還是可以了解一下
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x,y)
# 新的格式化方式是使用format函式
# 這個方式也是較為推薦的
"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# 無(None) 是一個物件
None # => None
# 不要用等於符號 "==" 對 無(None)做比較
# 用 "is"
"etc" is None # => False
None is None # => True
# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用,
# 但對物件來說是很有用的。
# 任何物件都可以被當作布林值使用
# 以下的值會被視為是False :
# - 無(None)
# - 任何型別的零 (例如: 0, 0L, 0.0, 0j)
# - 空序列 (例如: '', (), [])
# - 空容器 (例如: {}, set())
# - 自定義型別的實體,且滿足某些條件
# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
#
# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值).
bool(0) # => False
bool("") # => False
####################################################
## 2. 變數與集合
####################################################
# Python的輸出很方便
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
# 從命令列獲得值也很方便
input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數
input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行
# 注意: 請謹慎使用input()函式
# 註: 在Python 3中input()已被棄用raw_input()已被更名為input()
# 使用變數前不需要先宣告
some_var = 5 # 方便好用
lower_case_with_underscores
some_var # => 5
# 對沒有被賦值的變數取值會造成例外
# 請參考錯誤流程部分做例外處理
some_other_var # 造成 NameError
# if可以當判斷式使用
# 相當於C語言中的二元判斷式
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# 串列型態可以儲存集合
li = []
# 你可以預先填好串列內容
other_li = [4, 5, 6]
# 用append()在串列後新增東西
li.append(1) # 此時 li 內容為 [1]
li.append(2) # 此時 li 內容為 [1, 2]
li.append(4) # 此時 li 內容為 [1, 2, 4]
li.append(3) # 此時 li 內容為 [1, 2, 4, 3]
# 用pop()移除串列尾端的元素
li.pop() # => 3 ,此時 li 內容為 [1, 2, 4]
# 然後再塞回去
li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3]
# 你可以像存取陣列一樣的存取串列
li[0] # => 1
# 用等號 = 給串列中特定索引的元素賦值
li[0] = 42
li[0] # => 42
li[0] = 1 # 註: 將其設定回原本的值
# 用 -1 索引值查看串列最後一個元素
li[-1] # => 3
# 存取超過範圍會產生IndexError
li[4] # Raises an IndexError
# 你可以用切片語法來存取特定範圍的值
# (相當於數學中的左閉右開區間,即包含最左邊界,但不包含右邊界)
li[1:3] # => [2, 4]
# 略過開頭元素
li[2:] # => [4, 3]
# 略過結尾元素
li[:3] # => [1, 2, 4]
# 每隔兩個元素取值
li[::2] # =>[1, 4]
# 串列反轉
li[::-1] # => [3, 4, 2, 1]
# 你可以任意組合來達到你想要的效果
# li[開始索引:結束索引:間隔]
# 用 "del" 從串列中移除任意元素
del li[2] # 現在 li 內容為 [1, 2, 3]
# 你可以做串列相加
li + other_li # => [1, 2, 3, 4, 5, 6]
# 註: li 及 other_li 沒有被更動
# 用 "extend()" 做串列串接
li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6]
# 移除特定值的第一次出現
li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6]
li.remove(2) # 2 不在串列中,造成 ValueError
# 在特定位置插入值
li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6]
# 取得特定值在串列中第一次出現的位置
li.index(2) # => 1
li.index(7) # 7 不在串列中,造成 ValueError
# 用 "in" 檢查特定值是否出現在串列中
1 in li # => True
# 用 "len()" 取得串列長度
len(li) # => 6
# 元組(Tuple以下仍用原文)類似於串列,但是它是不可改變的
tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # 產生TypeError
# 能對串列做的東西都可以對tuple做
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# 你可以把tuple拆開並分別將值存入不同變數
a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3
d, e, f = 4, 5, 6 # 也可以不寫括號
# 如果不加括號預設會產生tuple
g = 4, 5, 6 # => (4, 5, 6)
# 你看,交換兩個值很簡單吧
e, d = d, e # 此時 d 的值為 5 且 e 的值為 4
# 字典(Dictionary)用來儲存映射關係
empty_dict = {}
# 你可以對字典做初始化
filled_dict = {"one": 1, "two": 2, "three": 3}
# 用 [] 取值
filled_dict["one"] # => 1
# 用 "keys()" 將所有的Key輸出到一個List中
filled_dict.keys() # => ["three", "two", "one"]
# 註: 字典裡key的排序是不固定的
# 你的執行結果可能與上面不同
# 譯註: 只能保證所有的key都有出現但不保證順序
# 用 "values()" 將所有的Value輸出到一個List中
filled_dict.values() # => [3, 2, 1]
# 註: 同上,不保證順序
# 用 "in" 來檢查指定的Key是否在字典中
"one" in filled_dict # => True
1 in filled_dict # => False
# 查詢不存在的Key會造成KeyError
filled_dict["four"] # KeyError
# 用 "get()" 來避免KeyError
# 若指定的Key不存在的話會得到None
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
# 注意此時 filled_dict.get("four") 仍然為 None
# (get()此時並沒有產生出任何的值)
# 像操作list一樣對指定的Key賦值
filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4
# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary
filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5
filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5
# 集合(Set)被用來儲存...集合。
# 跟串列(List)有點像,但集合內不會有重複的元素
empty_set = set()
# 初始化 "set()" 並給定一些值
some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入
# 一樣,不保證順序,就算真的有照順序排也只是你運氣好
another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4])
# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# 加入更多元素進入Set
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# 用 & 來對兩個集合取交集
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
# 用 | 來對兩個集合取聯集
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# 用 - 來將第二個集合內有的元素移出第一個集合
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# 用 ^ 來對兩個集合取差集
{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
# 檢查左邊是否為右邊的母集
{1, 2} >= {1, 2, 3} # => False
# 檢查左邊是否為右邊的子集
{1, 2} <= {1, 2, 3} # => True
# 用 in 來檢查某元素是否存在於集合內
2 in filled_set # => True
10 in filled_set # => False
####################################################
## 3. 控制流程
####################################################
# 首先,先宣告一個變數
some_var = 5
# 這邊是 if 判斷式。注意縮排對Python是很重要的。
# 下面應該會印出 "some_var is smaller than 10"
if some_var > 10:
print "some_var is totally bigger than 10."
elif some_var < 10: # elif 可有可無
print "some_var is smaller than 10."
else: # else 也可有可無
print "some_var is indeed 10."
"""
For 迴圈會遞迴整的List
下面的程式碼會輸出:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
# 你可以用{0}來組合0出格式化字串 (見上面.)
print "{0} is a mammal".format(animal)
"""
"range(number)" 回傳一個包含從0到給定值的數字List
下面的程式碼會輸出:
0
1
2
3
"""
for i in range(4):
print i
"""
"range(lower, upper)" 回傳一個包含從給定的下限
到給定的上限的數字List
下面的程式碼會輸出:
4
5
6
7
"""
for i in range(4, 8):
print i
"""
While迴圈會執行到條件不成立為止
下面的程式碼會輸出:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 # x = x + 1 的簡寫
# 用try/except處理例外
# 適用Python 2.6及以上版本
try:
# 用 "raise" 來發起例外
raise IndexError("This is an index error")
except IndexError as e:
pass # 毫無反應就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理
except (TypeError, NameError):
pass # 有需要的話,多種例外可以一起處理
else: # else 可有可無但必須寫在所有的except後
print "All good!" # 只有在try的時候沒有產生任何except才會被執行
finally: # 不管什麼情況下一定會被執行
print "We can clean up resources here"
# 除了try/finally以外你可以用 with 來簡單的處理清理動作
with open("myfile.txt") as f:
for line in f:
print line
####################################################
## 4. 函式
####################################################
# 用 "def" 來建立新函式
def add(x, y):
print "x is {0} and y is {1}".format(x, y)
return x + y # 用 "return" 來回傳值
# 用參數來呼叫函式
add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11
# 你也可以寫上參數名稱來呼叫函式
add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行
# 你可以定義接受多個變數的函式,用*來表示參數tuple
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
# 你可以定義接受多個變數的函式,用**來表示參數dictionary
def keyword_args(**kwargs):
return kwargs
# 呼叫看看會發生什麼事吧
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# 如果你想要,你也可以兩個同時用
def all_the_args(*args, **kwargs):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
# 呼叫函式時,你可以做反向的操作
# 用 * 將變數展開為順序排序的變數
# 用 ** 將變數展開為Keyword排序的變數
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # 等同於 foo(1, 2, 3, 4)
all_the_args(**kwargs) # 等同於 foo(a=3, b=4)
all_the_args(*args, **kwargs) # 等同於 foo(1, 2, 3, 4, a=3, b=4)
# 你可以把args跟kwargs傳到下一個函式內
# 分別用 * 跟 ** 將它展開就可以了
def pass_all_the_args(*args, **kwargs):
all_the_args(*args, **kwargs)
print varargs(*args)
print keyword_args(**kwargs)
# 函式範圍
x = 5
def set_x(num):
# 區域變數 x 和全域變數 x 不是同一個東西
x = num # => 43
print x # => 43
def set_global_x(num):
global x
print x # => 5
x = num # 全域變數 x 在set_global_x(6)被設定為 6
print x # => 6
set_x(43)
set_global_x(6)
# Python有一級函式
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
# 也有匿名函式
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# 還有內建的高階函式
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]
# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用
[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. 類別
####################################################
# 我們可以由object繼承出一個新的類別
class Human(object):
# 類別的參數,被所有這個類別的實體所共用
species = "H. sapiens"
# 基礎建構函式當class被實體化的時候會被呼叫
# 注意前後的雙底線
# 代表此物件或屬性雖然在使用者控制的命名空間內但是被python使用
def __init__(self, name):
# 將函式引入的參數 name 指定給實體的 name 參數
self.name = name
# 初始化屬性
self.age = 0
# 一個實體的方法(method)。 所有的method都以self為第一個參數
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
# 一個類別方法會被所有的實體所共用
# 他們會以類別為第一參數的方式被呼叫
@classmethod
def get_species(cls):
return cls.species
# 靜態方法
@staticmethod
def grunt():
return "*grunt*"
# 屬性就像是用getter取值一樣
# 它將方法 age() 轉為同名的、只能讀取的屬性
@property
def age(self):
return self._age
# 這樣寫的話可以讓屬性被寫入新的值
@age.setter
def age(self, age):
self._age = age
# 這樣寫的話允許屬性被刪除
@age.deleter
def age(self):
del self._age
# 將類別實體化
i = Human(name="Ian")
print i.say("hi") # prints out "Ian: hi"
j = Human("Joel")
print j.say("hello") # prints out "Joel: hello"
# 呼叫類別方法
i.get_species() # => "H. sapiens"
# 更改共用的屬性
Human.species = "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
# 呼叫靜態方法
Human.grunt() # => "*grunt*"
# 更新屬性
i.age = 42
# 取得屬性
i.age # => 42
# 移除屬性
del i.age
i.age # => raises an AttributeError
####################################################
## 6. 模組
####################################################
# 你可以引入模組來做使用
import math
print math.sqrt(16) # => 4
# math.sqrt()為取根號
# 你可以只從模組取出特定幾個函式
from math import ceil, floor
print ceil(3.7) # => 4.0
print floor(3.7) # => 3.0
# 你可以將所有的函式從模組中引入
# 注意:不建議這麼做
from math import *
# 你可以用 as 簡寫模組名稱
import math as m
math.sqrt(16) == m.sqrt(16) # => True
# 你也可以測試函示是否相等
from math import sqrt
math.sqrt == m.sqrt == sqrt # => True
# Python的模組就只是一般的Python檔。
# 你可以自己的模組自己寫、自己的模組自己引入
# 模組的名稱和檔案名稱一樣
# 你可以用dir()來查看有哪些可用函式和屬性
import math
dir(math)
####################################################
## 7. 進階
####################################################
# 產生器(Generator)可以讓你寫更懶惰的程式碼
def double_numbers(iterable):
for i in iterable:
yield i + i
# 產生器可以讓你即時的產生值
# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時
# 產生值。 這也意味著大於15的值不會在double_numbers中產生。
# 這邊xrange()做的事情和range()一樣
# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間
# xrange() 建立一個產生器物件而不是如range()建立整個List
# 我們用底線來避免可能和python的關鍵字重複的名稱
xrange_ = xrange(1, 900000000)
# 下面的程式碼會把所有的值乘以兩倍直到出現大於30的值
for i in double_numbers(xrange_):
print i
if i >= 30:
break
# 裝飾子
# 在這個範例中beg會綁在say上
# Beg會呼叫say。 如果say_please為True的話它會更改回傳的訊息
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() # Can you buy me a beer?
print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
```
## 準備好學更多了嗎?
### 線上免費資源
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
* [The Official Docs](http://docs.python.org/2/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
### 或買本書?
* [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)