summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown13
-rw-r--r--c.html.markdown9
-rw-r--r--cs-cz/python3.html.markdown6
-rw-r--r--csharp.html.markdown8
-rw-r--r--d.html.markdown50
-rw-r--r--git.html.markdown28
-rw-r--r--go.html.markdown2
-rw-r--r--json.html.markdown2
-rw-r--r--pt-br/c-pt.html.markdown19
-rw-r--r--python.html.markdown14
-rw-r--r--python3.html.markdown245
-rw-r--r--ruby.html.markdown3
-rw-r--r--sass.html.markdown215
-rw-r--r--xml.html.markdown4
14 files changed, 453 insertions, 165 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index 191f916a..211d2944 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -90,17 +90,26 @@ else
echo "Your name is your username"
fi
+# NOTE: if $Name is empty, bash sees the above condition as:
+if [ -ne $USER ]
+# which is invalid syntax
+# so the "safe" way to use potentially empty variables in bash is:
+if [ "$Name" -ne $USER ] ...
+# which, when $Name is empty, is seen by bash as:
+if [ "" -ne $USER ] ...
+# which works as expected
+
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail"
# To use && and || with if statements, you need multiple pairs of square brackets:
-if [ $Name == "Steve" ] && [ $Age -eq 15 ]
+if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
echo "This will run if $Name is Steve AND $Age is 15."
fi
-if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "This will run if $Name is Daniya OR Zach."
fi
diff --git a/c.html.markdown b/c.html.markdown
index 3339032f..bfdf276c 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -54,6 +54,8 @@ int function_2(void);
// Must declare a 'function prototype' before main() when functions occur after
// your main() function.
int add_two_ints(int x1, int x2); // function prototype
+// although `int add_two_ints(int, int);` is also valid (no need to name the args),
+// it is recommended to name arguments in the prototype as well for easier inspection
// Your program's entry point is a function called
// main with an integer return type.
@@ -74,6 +76,9 @@ 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
// ints are usually 4 bytes
int x_int = 0;
@@ -232,7 +237,7 @@ int main (int argc, char** argv)
0 || 1; // => 1 (Logical or)
0 || 0; // => 0
- // Conditional expression ( ? : )
+ // Conditional ternary expression ( ? : )
int e = 5;
int f = 10;
int z;
@@ -302,6 +307,8 @@ int main (int argc, char** argv)
for (i = 0; i <= 5; i++) {
; // use semicolon to act as the body (null statement)
}
+ // Or
+ for (i = 0; i <= 5; i++);
// branching with multiple choices: switch()
switch (a) {
diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown
index 11c8a654..6d2fd1eb 100644
--- a/cs-cz/python3.html.markdown
+++ b/cs-cz/python3.html.markdown
@@ -48,7 +48,7 @@ Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit sta
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
-# Pokud použiteje desetinné číslo, výsledek je jím také
+# Pokud použijete desetinné číslo, výsledek je jím také
3 * 2.0 # => 6.0
# Modulo
@@ -420,7 +420,7 @@ next(iterator) # Vyhodí StopIteration
## 4. Funkce
####################################################
-# Pro vytvoření nové funkce použijte def
+# Pro vytvoření nové funkce použijte klíčové slovo def
def secist(x, y):
print("x je {} a y je {}".format(x, y))
return x + y # Hodnoty se vrací pomocí return
@@ -520,7 +520,7 @@ class Clovek(object):
# podtržítka na začátku a na konci značí, že se jedná o atribut nebo
# objekt využívaný Pythonem ke speciálním účelům, ale můžete sami
# definovat jeho chování. Metody jako __init__, __str__, __repr__
- # a další se nazývají "magické metody". Nikdy nepoužívejte toto
+ # a další se nazývají "magické metody". Nikdy nepoužívejte toto
# speciální pojmenování pro běžné metody.
def __init__(self, jmeno):
# Přiřazení parametru do atributu instance jmeno
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 28da9fe5..7aca2c6f 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -160,7 +160,7 @@ on a new line! ""Wow!"", the masses cried";
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
- List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize
+ List<int> z = new List<int> { 9000, 1000, 1337 }; // initialize
// The <> are for generics - Check out the cool stuff section
// Lists don't default to a value;
@@ -460,7 +460,7 @@ on a new line! ""Wow!"", the masses cried";
{
// OPTIONAL PARAMETERS
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
- MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
+ MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones
// BY REF AND OUT PARAMETERS
int maxCount = 0, count; // ref params must have value
@@ -481,7 +481,7 @@ on a new line! ""Wow!"", the masses cried";
// in case variable is null
int notNullable = nullable ?? 0; // 0
- // ?. is an operator for null-propogation - a shorthand way of checking for null
+ // ?. is an operator for null-propagation - a shorthand way of checking for null
nullable?.Print(); // Use the Print() extension method if nullable isn't null
// IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is:
@@ -650,7 +650,7 @@ on a new line! ""Wow!"", the masses cried";
{
return _cadence;
}
- set // set - define a method to set a proprety
+ set // set - define a method to set a property
{
_cadence = value; // Value is the value passed in to the setter
}
diff --git a/d.html.markdown b/d.html.markdown
index 88a83e41..80c1dc65 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -74,16 +74,18 @@ are passed to functions by value (i.e. copied) and classes are passed by referen
we can use templates to parameterize all of these on both types and values!
```c
-// Here, T is a type parameter. Think <T> from C++/C#/Java
+// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java.
struct LinkedList(T) {
T data = null;
- LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T>
+
+ // Use '!' to instantiate a parameterized type. Again, think '<T>'.
+ LinkedList!(T)* next;
}
class BinTree(T) {
T data = null;
- // If there is only one template parameter, we can omit the parentheses
+ // If there is only one template parameter, we can omit the parentheses.
BinTree!T left;
BinTree!T right;
}
@@ -98,13 +100,11 @@ enum Day {
Saturday,
}
-// Use alias to create abbreviations for types
-
+// Use alias to create abbreviations for types.
alias IntList = LinkedList!int;
alias NumTree = BinTree!double;
// We can create function templates as well!
-
T max(T)(T a, T b) {
if(a < b)
return b;
@@ -112,9 +112,8 @@ T max(T)(T a, T b) {
return a;
}
-// Use the ref keyword to ensure pass by referece.
-// That is, even if a and b are value types, they
-// will always be passed by reference to swap
+// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b'
+// are value types, they will always be passed by reference to 'swap()'.
void swap(T)(ref T a, ref T b) {
auto temp = a;
@@ -122,13 +121,13 @@ void swap(T)(ref T a, ref T b) {
b = temp;
}
-// With templates, we can also parameterize on values, not just types
+// With templates, we can also parameterize on values, not just types.
class Matrix(uint m, uint n, T = int) {
T[m] rows;
T[n] columns;
}
-auto mat = new Matrix!(3, 3); // We've defaulted type T to int
+auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'.
```
@@ -138,21 +137,20 @@ have the syntax of POD structures (`structure.x = 7`) with the semantics of
getter and setter methods (`object.setX(7)`)!
```c
-// Consider a class parameterized on a types T, U
-
+// Consider a class parameterized on types 'T' & 'U'.
class MyClass(T, U) {
T _data;
U _other;
-
}
-// And "getter" and "setter" methods like so
+// And "getter" and "setter" methods like so:
class MyClass(T, U) {
T _data;
U _other;
- // Constructors are always named `this`
+ // Constructors are always named 'this'.
this(T t, U u) {
+ // This will call the setter methods below.
data = t;
other = u;
}
@@ -175,16 +173,24 @@ class MyClass(T, U) {
_other = u;
}
}
-// And we use them in this manner
+// And we use them in this manner:
void main() {
- auto mc = MyClass!(int, string);
+ auto mc = new MyClass!(int, string)(7, "seven");
+
+ // Import the 'stdio' module from the standard library for writing to
+ // console (imports can be local to a scope).
+ import std.stdio;
+
+ // Call the getters to fetch the values.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
- mc.data = 7;
- mc.other = "seven";
+ // Call the setters to assign new values.
+ mc.data = 8;
+ mc.other = "eight";
- writeln(mc.data);
- writeln(mc.other);
+ // Call the getters again to fetch the new values.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
}
```
diff --git a/git.html.markdown b/git.html.markdown
index 72079f6c..971d53e4 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Leo Rudberg" , "http://github.com/LOZORD"]
- ["Betsy Lorton" , "http://github.com/schbetsy"]
+ - ["Bruno Volcov", "http://github.com/volcov"]
filename: LearnGit.txt
---
@@ -76,6 +77,11 @@ other repositories, or not!
A branch is essentially a pointer to the last commit you made. As you go on
committing, this pointer will automatically update to point the latest commit.
+### Tag
+
+A tag is a mark on specific point in history. Typically people use this
+functionality to mark release points (v1.0, and so on)
+
### HEAD and head (component of .git dir)
HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD.
@@ -206,6 +212,28 @@ $ git branch -m myBranchName myNewBranchName
$ git branch myBranchName --edit-description
```
+### tag
+
+Manage your tags
+
+```bash
+# List tags
+$ git tag
+# Create a annotated tag
+# The -m specifies a tagging message,which is stored with the tag.
+# If you don’t specify a message for an annotated tag,
+# Git launches your editor so you can type it in.
+$ git tag -a v2.0 -m 'my version 2.0'
+# Show info about tag
+# That shows the tagger information, the date the commit was tagged,
+# and the annotation message before showing the commit information.
+$ git show v2.0
+# Push a single tag to remote
+$ git push origin v2.0
+# Push a lot of tags to remote
+$ git push origin --tags
+```
+
### checkout
Updates all files in the working tree to match the version in the index, or specified tree.
diff --git a/go.html.markdown b/go.html.markdown
index 646a5650..a857a76c 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -423,3 +423,5 @@ idioms. Or you can click on a function name in [the
documentation](http://golang.org/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
+
+Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.
diff --git a/json.html.markdown b/json.html.markdown
index b5e36090..060e9c3d 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -58,7 +58,7 @@ Drawbacks of JSON include lack of type definition and some sort of DTD.
"alternative style": {
"comment": "check this out!"
- , "comma position": "doesn't matter - as long as it's before the value, then it's valid"
+ , "comma position": "doesn't matter - as long as it's before the next key, then it's valid"
, "another comment": "how nice"
},
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 451df4f3..43688724 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
translators:
- ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["Elton Viana", "https://github.com/eltonvs"]
lang: pt-br
filename: c-pt.el
---
@@ -139,13 +140,13 @@ int main() {
int var_length_array[size]; // declara o VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- //Uma possível saída para esse programa seria:
- // > Entre o tamanho do array:: 10
+ // Uma possível saída para esse programa seria:
+ // > Entre o tamanho do array: 10
// > sizeof array = 40
// String são apenas arrays de caracteres terminados por um
- // byte NUL (0x00), representado em string pelo caracter especial '\0'.
- // (Não precisamos incluir o byte NUL em literais de string; o compilador
+ // byte nulo (0x00), representado em string pelo caracter especial '\0'.
+ // (Não precisamos incluir o byte nulo em literais de string; o compilador
// o insere ao final do array para nós.)
char uma_string[20] = "Isto é uma string";
// Observe que 'é' não está na tabela ASCII
@@ -153,8 +154,8 @@ int main() {
// Porém, comentários podem conter acentos
printf("%s\n", uma_string); // %s formata a string
- printf("%d\n", uma_string[16]); // => 0
- // i.e., byte #17 é 0 (assim como 18, 19, e 20)
+ printf("%d\n", uma_string[17]); // => 0
+ // i.e., byte #18 é 0 (assim como o 19°, 20°, 21°...)
// Se temos caracteres entre aspas simples, temos um caracter literal.
// Seu tipo é `int`, *não* `char` (por razões históricas).
@@ -220,11 +221,11 @@ int main() {
0 || 1; // => 1 (Ou lógico)
0 || 0; // => 0
- //Expressão condicional ( ? : )
+ //Expressão condicional ternária ( ? : )
int a = 5;
int b = 10;
int z;
- z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b."
+ z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b."
//Operadores de incremento e decremento:
char *s = "iLoveC";
@@ -290,6 +291,8 @@ int main() {
for (i = 0; i <= 5; i++) {
; // Use ponto e vírgula para agir como um corpo (declaração nula)
}
+ // Ou
+ for (i = 0; i <= 5; i++);
// Criando branchs com escolhas múltiplas: switch()
switch (alguma_expressao_integral) {
diff --git a/python.html.markdown b/python.html.markdown
index 5b36083d..b939ebbe 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -14,7 +14,13 @@ executable pseudocode.
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020,
+it is though recommended to start learnign Python with Python 3.
+For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+
+It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
+using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
+allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial.
```python
@@ -144,6 +150,12 @@ bool("") # => False
# Python has a print statement
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+# Simple way to get input data from console
+input_string_var = raw_input("Enter some data: ") # Returns the data as a string
+input_var = input("Enter some data: ") # Evaluates the data as python code
+# Warning: Caution is recommended for input() method usage
+# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
+
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
some_var # => 5
diff --git a/python3.html.markdown b/python3.html.markdown
index 87fa0b70..a1125c73 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -33,27 +33,27 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
3 # => 3
# Math is what you would expect
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
# Except division which returns floats, real numbers, by default
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
# When you use a float, results are floats
-3 * 2.0 # => 6.0
+3 * 2.0 # => 6.0
# Modulo operation
-7 % 3 # => 1
+7 % 3 # => 1
# Exponentiation (x**y, x to the yth power)
-2**4 # => 16
+2**4 # => 16
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@@ -63,20 +63,20 @@ True
False
# negate with not
-not True # => False
+not True # => False
not False # => True
# Boolean Operators
# Note "and" and "or" are case-sensitive
-True and False #=> False
-False or True #=> True
+True and False # => False
+False or True # => True
# Note using Bool operators with ints
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
# Equality is ==
1 == 1 # => True
@@ -98,13 +98,13 @@ False or True #=> True
# (is vs. ==) is checks if two variable refer to the same object, but == checks
# if the objects pointed to have the same values.
-a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
-b = a # Point b at what a is pointing to
-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 is a # => False, a and b do not refer to the same object
-b == a # => True, a's and b's objects are equal
+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 is a # => False, a and b do not refer to the same object
+b == a # => True, a's and b's objects are equal
# Strings are created with " or '
"This is a string."
@@ -113,24 +113,24 @@ b == a # => True, a's and b's objects are equal
# Strings can be added too! But try not to do this.
"Hello " + "world!" # => "Hello world!"
# Strings can be added without using '+'
-"Hello " "world!" # => "Hello world!"
+"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
# .format can be used to format strings, like this:
-"{} can be {}".format("strings", "interpolated")
+"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated"
# You can repeat the formatting arguments to save some typing.
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
-#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
# You can use keywords if you don't want to count.
-"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna"
# If your Python 3 code also needs to run on Python 2.5 and below, you can also
# still use the old style of formatting:
-"%s can be %s the %s way" % ("strings", "interpolated", "old")
+"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way"
# None is an object
@@ -139,14 +139,14 @@ None # => None
# Don't use the equality "==" symbol to compare objects to None
# Use "is" instead. This checks for equality of object identity.
"etc" is None # => False
-None is None # => True
+None is None # => True
# None, 0, and empty strings/lists/dicts all evaluate to False.
# All other values are True
-bool(0) # => False
+bool(0) # => False
bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
+bool([]) # => False
+bool({}) # => False
####################################################
@@ -154,11 +154,15 @@ bool({}) #=> False
####################################################
# Python has a print function
-print("I'm Python. Nice to meet you!")
+print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end character.
-print("Hello, World", end="!") # => Hello, World!
+print("Hello, World", end="!") # => Hello, World!
+
+# Simple way to get input data from console
+input_string_var = input("Enter some data: ") # Returns the data as a string
+# Note: In earlier versions of Python, input() method was named as raw_input()
# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
@@ -185,7 +189,7 @@ li.pop() # => 3 and li is now [1, 2, 4]
li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array
-li[0] # => 1
+li[0] # => 1
# Look at the last element
li[-1] # => 3
@@ -194,61 +198,61 @@ li[4] # Raises an IndexError
# You can look at ranges with slice syntax.
# (It's a closed/open range for you mathy types.)
-li[1:3] # => [2, 4]
+li[1:3] # => [2, 4]
# Omit the beginning
-li[2:] # => [4, 3]
+li[2:] # => [4, 3]
# Omit the end
-li[:3] # => [1, 2, 4]
+li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
# Return a reversed copy of the list
-li[::-1] # => [3, 4, 2, 1]
+li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
# Make a one layer deep copy using slices
-li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
+li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
# Remove arbitrary elements from a list with "del"
-del li[2] # li is now [1, 2, 3]
+del li[2] # li is now [1, 2, 3]
# You can add lists
# Note: values for li and for other_li are not modified.
-li + other_li # => [1, 2, 3, 4, 5, 6]
+li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
-li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Check for existence in a list with "in"
-1 in li # => True
+1 in li # => True
# Examine the length with "len()"
-len(li) # => 6
+len(li) # => 6
# Tuples are like lists but are immutable.
tup = (1, 2, 3)
-tup[0] # => 1
+tup[0] # => 1
tup[0] = 3 # Raises a TypeError
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
# You can do most of the list operations on tuples too
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
# You can unpack tuples (or lists) into variables
-a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
-e, d = d, e # d is now 5 and e is now 4
+e, d = d, e # d is now 5 and e is now 4
# Dictionaries store mappings
@@ -259,45 +263,45 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Note keys for dictionaries have to be immutable types. This is to ensure that
# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
-invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
+invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
# Look up values with []
-filled_dict["one"] # => 1
+filled_dict["one"] # => 1
# Get all keys as an iterable with "keys()". We need to wrap the call in list()
# to turn it into a list. We'll talk about those later. Note - Dictionary key
# ordering is not guaranteed. Your results might not match this exactly.
-list(filled_dict.keys()) # => ["three", "two", "one"]
+list(filled_dict.keys()) # => ["three", "two", "one"]
# Get all values as an iterable with "values()". Once again we need to wrap it
# in list() to get it out of the iterable. Note - Same as above regarding key
# ordering.
-list(filled_dict.values()) # => [3, 2, 1]
+list(filled_dict.values()) # => [3, 2, 1]
# Check for existence of keys in a dictionary with "in"
-"one" in filled_dict # => True
-1 in filled_dict # => False
+"one" in filled_dict # => True
+1 in filled_dict # => False
# Looking up a non-existing key is a KeyError
-filled_dict["four"] # KeyError
+filled_dict["four"] # KeyError
# Use "get()" method to avoid the KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
+filled_dict.get("four", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Adding to a dictionary
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 #another way to add to dict
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 #another way to add to dict
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
@@ -306,31 +310,31 @@ del filled_dict["one"] # Removes the key "one" from filled dict
# Sets store ... well sets
empty_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
-some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
+some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Similar to keys of a dictionary, elements of a set have to be immutable.
-invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
# Can set new variables to a set
filled_set = some_set
# Add one more item to the set
-filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with &
other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
# Do set union with |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Check for existence in a set with in
2 in filled_set # => True
-10 in filled_set # => False
+10 in filled_set # => False
@@ -416,12 +420,12 @@ try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
+ pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
- pass # Multiple exceptions can be handled together, if required.
-else: # Optional clause to the try/except block. Must follow all except blocks
+ pass # Multiple exceptions can be handled together, if required.
+else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
-finally: # Execute under all circumstances
+finally: # Execute under all circumstances
print("We can clean up resources here")
# Instead of try/finally to cleanup resources you can use a with statement
@@ -435,11 +439,11 @@ with open("myfile.txt") as f:
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface
+print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface
# We can loop over it.
for i in our_iterable:
- print(i) # Prints one, two, three
+ print(i) # Prints one, two, three
# However we cannot address elements by index.
our_iterable[1] # Raises a TypeError
@@ -449,17 +453,17 @@ our_iterator = iter(our_iterable)
# Our iterator is an object that can remember the state as we traverse through it.
# We get the next object with "next()".
-next(our_iterator) #=> "one"
+next(our_iterator) # => "one"
# It maintains state as we iterate.
-next(our_iterator) #=> "two"
-next(our_iterator) #=> "three"
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
# After the iterator has returned all of its data, it gives you a StopIterator Exception
-next(our_iterator) # Raises StopIteration
+next(our_iterator) # Raises StopIteration
# You can grab all the elements of an iterator by calling list() on it.
-list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+list(filled_dict.keys()) # => Returns ["one", "two", "three"]
####################################################
@@ -469,20 +473,20 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
# Use "def" to create new functions
def add(x, y):
print("x is {} and y is {}".format(x, y))
- return x + y # Return values with a return statement
+ return x + y # Return values with a return statement
# Calling functions with parameters
-add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
+add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
# Another way to call functions is with keyword arguments
-add(y=6, x=5) # Keyword arguments can arrive in any order.
+add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
# positional arguments
def varargs(*args):
return args
-varargs(1, 2, 3) # => (1, 2, 3)
+varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
# keyword arguments, as well
@@ -490,7 +494,7 @@ def keyword_args(**kwargs):
return kwargs
# Let's call it to see what happens
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can do both at once, if you like
@@ -507,33 +511,33 @@ all_the_args(1, 2, a=3, b=4) prints:
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
- return y, x # Return multiple values as a tuple without the parenthesis.
- # (Note: parenthesis have been excluded but can be included)
+ return y, x # Return multiple values as a tuple without the parenthesis.
+ # (Note: parenthesis have been excluded but can be included)
x = 1
y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x = 5
def setX(num):
# Local var x not the same as global variable x
- x = num # => 43
- print (x) # => 43
+ x = num # => 43
+ print (x) # => 43
def setGlobalX(num):
global x
- print (x) # => 5
- x = num # global var x is now set to 6
- print (x) # => 6
+ print (x) # => 5
+ x = num # global var x is now set to 6
+ print (x) # => 6
setX(43)
setGlobalX(6)
@@ -549,20 +553,20 @@ add_10 = create_adder(10)
add_10(3) # => 13
# There are also anonymous functions
-(lambda x: x > 2)(3) # => True
-(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# TODO - Fix for iterables
# There are built-in higher order functions
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+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]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
# List comprehension stores the output as a list which can itself be a nested list
-[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]
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Classes
@@ -609,15 +613,15 @@ j = Human("Joel")
print(j.say("hello")) # prints out "Joel: hello"
# Call our class method
-i.get_species() # => "H. sapiens"
+i.get_species() # => "H. sapiens"
# Change the shared attribute
Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
# Call the static method
-Human.grunt() # => "*grunt*"
+Human.grunt() # => "*grunt*"
####################################################
@@ -630,8 +634,8 @@ print(math.sqrt(16)) # => 4
# You can get specific functions from a module
from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
# You can import all functions from a module.
# Warning: this is not recommended
@@ -639,7 +643,7 @@ from math import *
# You can shorten module names
import math as m
-math.sqrt(16) == m.sqrt(16) # => True
+math.sqrt(16) == m.sqrt(16) # => True
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the
@@ -698,7 +702,7 @@ def say(say_please=False):
return msg, say_please
-print(say()) # Can you buy me a beer?
+print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
@@ -715,6 +719,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
### Dead Tree
diff --git a/ruby.html.markdown b/ruby.html.markdown
index c10255d8..0e798706 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -12,8 +12,7 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Rahil Momin", "https://github.com/iamrahil"]
- - ["Gabriel Halley", https://github.com/ghalley]
-
+ - ["Gabriel Halley", https://github.com/ghalley"]
---
```ruby
diff --git a/sass.html.markdown b/sass.html.markdown
index 509aee9b..02bec47f 100644
--- a/sass.html.markdown
+++ b/sass.html.markdown
@@ -3,6 +3,7 @@ language: sass
filename: learnsass.scss
contributors:
- ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
---
Sass is a CSS extension language that adds features such as variables, nesting, mixins and more.
@@ -11,6 +12,7 @@ Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help develop
Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons.
This tutorial is written using SCSS.
+If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier.
```scss
@@ -121,6 +123,69 @@ div {
+/*Functions
+==============================*/
+
+
+
+/* Sass provides functions that can be used to accomplish a variety of
+ tasks. Consider the following */
+
+/* Functions can be invoked by using their name and passing in the
+ required arguments */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to
+ mixins. When trying to choose between a function or a mixin, remember
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Sass code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
+ function. */
+
+/* This function will take a target size and the parent size and calculate
+ and return the percentage */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compiles to: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
/*Extend (Inheritance)
==============================*/
@@ -150,6 +215,12 @@ div {
border-color: #22df56;
}
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way it groups together the classes that all share
+ the same base styling. If this was done with a mixin, the width,
+ height, and border would be duplicated for each statement that
+ called the mixin. While it won't affect your workflow, it will
+ add unnecessary bloat to the files created by the Sass compiler. */
@@ -172,6 +243,7 @@ ul {
/* '&' will be replaced by the parent selector. */
/* You can also nest pseudo-classes. */
/* Keep in mind that over-nesting will make your code less maintainable.
+Best practices recommend going no more than 3 levels deep when nesting.
For example: */
ul {
@@ -212,6 +284,140 @@ ul li a {
+/*Partials and Imports
+==============================*/
+
+
+
+/* Sass allows you to create partial files. This can help keep your Sass
+ code modularized. Partial files should begin with an '_', e.g. _reset.css.
+ Partials are not generated into CSS. */
+
+/* Consider the following CSS which we'll put in a file called _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass offers @import which can be used to import partials into a file.
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Sass takes the
+ imported file and combines it with the compiled code. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/*Placeholder Selectors
+==============================*/
+
+
+
+/* Placeholders are useful when creating a CSS statement to extend. If you
+ wanted to create a CSS statement that was exclusively used with @extend,
+ you can do so using a placeholder. Placeholders begin with a '%' instead
+ of '.' or '#'. Placeholders will not appear in the compiled CSS. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compiles to: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/*Math Operations
+==============================*/
+
+
+
+/* Sass provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Sass files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
```
@@ -226,6 +432,15 @@ Because people were constantly writing it as "SASS", the creator of the language
If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/).
You can use either syntax, just go into the settings and select either Sass or SCSS.
+
+## Compatibility
+
+Sass can be used in any project as long as you have a program to compile it
+into CSS. You'll want to verify that the CSS you're using is compatible
+with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
+
## Further reading
* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
diff --git a/xml.html.markdown b/xml.html.markdown
index 4d33e614..547deb08 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -83,7 +83,7 @@ With this tool, you can check the XML data outside the application logic.
<!DOCTYPE note SYSTEM "Bookstore.dtd">
<bookstore>
<book category="COOKING">
- <title >Everyday Italian</title>
+ <title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>
@@ -121,7 +121,7 @@ With this tool, you can check the XML data outside the application logic.
<bookstore>
<book category="COOKING">
- <title >Everyday Italian</title>
+ <title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>