summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown7
-rw-r--r--c.html.markdown140
-rw-r--r--csharp.html.markdown2
-rw-r--r--es-es/git-es.html.markdown411
-rw-r--r--java.html.markdown34
-rw-r--r--julia.html.markdown34
-rw-r--r--ko-kr/brainfuck-kr.html.markdown3
-rw-r--r--pt-br/java-pt.html.markdown435
-rw-r--r--pt-br/php-pt.html.markdown700
-rw-r--r--python.html.markdown4
-rw-r--r--ru-ru/c-ru.html.markdown483
-rw-r--r--ru-ru/go-ru.html.markdown2
-rw-r--r--ru-ru/objective-c-ru.html.markdown317
-rw-r--r--ruby.html.markdown4
-rw-r--r--zh-cn/bash-cn.html.markdown148
-rw-r--r--zh-cn/brainfuck-cn.html.markdown70
16 files changed, 2745 insertions, 49 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index d208b957..afc46eb0 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -115,6 +115,13 @@ do
echo "$VARIABLE"
done
+# while loop:
+while [true]
+do
+ echo "loop body here..."
+ break
+done
+
# You can also define functions
# Definition:
function foo ()
diff --git a/c.html.markdown b/c.html.markdown
index c67f8b21..84856b32 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -20,6 +20,13 @@ memory management and C will take you as far as you need to go.
Multi-line comments look like this. They work in C89 as well.
*/
+// Constants: #define <keyword>
+#define DAYS_IN_YEAR 365
+
+//enumeration constants are also ways to declare constants.
+enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
+// MON gets 2 automatically, TUE gets 3, etc.
+
// Import headers with #include
#include <stdlib.h>
#include <stdio.h>
@@ -31,8 +38,12 @@ Multi-line comments look like this. They work in C89 as well.
// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
-void function_1();
-void function_2();
+void function_1(char c);
+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
// Your program's entry point is a function called
// main with an integer return type.
@@ -72,6 +83,10 @@ int main() {
unsigned int ux_int;
unsigned long long ux_long_long;
+ // chars inside single quotes are integers in machine's character set.
+ '0' // => 48 in the ASCII character set.
+ 'A' // => 65 in the ASCII character set.
+
// sizeof(T) gives you the size of a variable with type T in bytes
// sizeof(obj) yields the size of the expression (variable, literal, etc.).
printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)
@@ -135,13 +150,25 @@ int main() {
int cha = 'a'; // fine
char chb = 'a'; // fine too (implicit conversion from int to char)
+ //Multi-dimensional arrays:
+ int multi_array[2][5] = {
+ {1, 2, 3, 4, 5},
+ {6, 7, 8, 9, 0}
+ }
+ //access elements:
+ int array_int = multi_array[0][2]; // => 3
+
///////////////////////////////////////
// Operators
///////////////////////////////////////
- int i1 = 1, i2 = 2; // Shorthand for multiple declaration
+ // Shorthands for multiple declarations:
+ int i1 = 1, i2 = 2;
float f1 = 1.0, f2 = 2.0;
+ int a, b, c;
+ a = b = c = 0;
+
// Arithmetic is straightforward
i1 + i2; // => 3
i2 - i1; // => 1
@@ -181,6 +208,20 @@ int main() {
0 || 1; // => 1 (Logical or)
0 || 0; // => 0
+ //Conditional expression ( ? : )
+ int a = 5;
+ int b = 10;
+ int z;
+ z = (a > b) ? a : b; // => 10 "if a > b return a, else return b."
+
+ //Increment and decrement operators:
+ char *s = "iLoveC"
+ int j = 0;
+ s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
+ j = 0;
+ s[++j]; // => "L". Increments value of j THEN returns j-th value of s.
+ // same with j-- and --j
+
// Bitwise operators!
~0x0F; // => 0xF0 (bitwise negation, "1's complement")
0x0F & 0xF0; // => 0x00 (bitwise AND)
@@ -209,9 +250,8 @@ int main() {
// While loops exist
int ii = 0;
- while (ii < 10) {
- printf("%d, ", ii++); // ii++ increments ii in-place
- // after yielding its value ("postincrement").
+ while (ii < 10) { //ANY value not zero is true.
+ printf("%d, ", ii++); // ii++ increments ii AFTER using it's current value.
} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
printf("\n");
@@ -219,8 +259,7 @@ int main() {
int kk = 0;
do {
printf("%d, ", kk);
- } while (++kk < 10); // ++kk increments kk in-place, and yields
- // the already incremented value ("preincrement")
+ } while (++kk < 10); // ++kk increments kk BEFORE using it's current value.
// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
printf("\n");
@@ -233,6 +272,13 @@ int main() {
printf("\n");
+ // *****NOTES*****:
+ // Loops and Functions MUST have a body. If no body is needed:
+ int i;
+ for (i = 0; i <= 5; i++) {
+ ; // use semicolon to act as the body (null statement)
+ }
+
// branching with multiple choices: switch()
switch (some_integral_expression) {
case 0: // labels need to be integral *constant* epxressions
@@ -309,7 +355,7 @@ int main() {
printf("%d\n", x); // => Prints 1
// Arrays are a good way to allocate a contiguous block of memory
- int x_array[20];
+ int x_array[20]; //declares array of size 20 (cannot change size)
int xx;
for (xx = 0; xx < 20; xx++) {
x_array[xx] = 20 - xx;
@@ -385,8 +431,12 @@ int add_two_ints(int x1, int x2)
}
/*
-Functions are pass-by-value, but you can make your own references
-with pointers so functions can mutate their values.
+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
+do to the arguments in the function do not change the value of the original
+argument where the function was called.
+
+Use pointers if you need to edit the original argument values.
Example: in-place string reversal
*/
@@ -404,6 +454,19 @@ void str_reverse(char *str_in)
}
}
+//if referring to external variables outside function, must use extern keyword.
+int i = 0;
+void testFunc() {
+ extern int i; //i here is now using external variable i
+}
+
+//make external variables private to source file with static:
+static int i = 0; //other files using testFunc() cannot access variable i
+void testFunc() {
+ extern int i;
+}
+//**You may also declare functions as static to make them private**
+
/*
char c[] = "This is a test.";
str_reverse(c);
@@ -494,6 +557,61 @@ typedef void (*my_fnp_type)(char *);
// ...
// my_fnp_type f;
+//Special characters:
+'\a' // alert (bell) character
+'\n' // newline character
+'\t' // tab character (left justifies text)
+'\v' // vertical tab
+'\f' // new page (formfeed)
+'\r' // carriage return
+'\b' // backspace character
+'\0' // null character. Usually put at end of strings in C lang.
+ // hello\n\0. \0 used by convention to mark end of string.
+'\\' // backspace
+'\?' // question mark
+'\'' // single quote
+'\"' // double quote
+'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character
+'\ooo' // octal number. Example: '\013' = vertical tab character
+
+//print formatting:
+"%d" // integer
+"%3d" // integer with minimum of length 3 digits (right justifies text)
+"%s" // string
+"%f" // float
+"%ld" // long
+"%3.2f" // minimum 3 digits left and 2 digits right decimal float
+"%7.4s" // (can do with strings too)
+"%c" // char
+"%p" // pointer
+"%x" // hexidecimal
+"%o" // octal
+"%%" // prints %
+
+///////////////////////////////////////
+// Order of Evaluation
+///////////////////////////////////////
+
+//---------------------------------------------------//
+// Operators | Associativity //
+//---------------------------------------------------//
+// () [] -> . | left to right //
+// ! ~ ++ -- + = *(type)sizeof | right to left //
+// * / % | left to right //
+// + - | left to right //
+// << >> | left to right //
+// < <= > >= | left to right //
+// == != | left to right //
+// & | left to right //
+// ^ | left to right //
+// | | left to right //
+// && | left to right //
+// || | left to right //
+// ?: | right to left //
+// = += -= *= /= %= &= ^= |= <<= >>= | right to left //
+// , | left to right //
+//---------------------------------------------------//
+
```
## Further Reading
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 87c2f704..dad0c26b 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -233,7 +233,7 @@ on a new line! ""Wow!"", the masses cried";
int fooWhile = 0;
while (fooWhile < 100)
{
- //Iterated 99 times, fooWhile 0->99
+ //Iterated 100 times, fooWhile 0->99
fooWhile++;
}
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
new file mode 100644
index 00000000..0623b29b
--- /dev/null
+++ b/es-es/git-es.html.markdown
@@ -0,0 +1,411 @@
+---
+category: tool
+tool: git
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+translator:
+ - ["Raúl Ascencio", "http://rscnt.github.io"]
+filename: LearnGit.txt
+language: es-es
+
+---
+
+Git es un sistema de control de versiones distribuido diseñado para manejar
+cualquier tipo de proyecto ya sea largos o pequeños, con velocidad y eficiencia.
+
+Git realiza esto haciendo "snapshots" del proyecto, con ello permite
+versionar y administrar nuestro código fuente.
+
+## Versionamiento, conceptos.
+
+### Que es el control de versiones?
+El control de versiones es un sistema que guarda todos los cambios realizados a
+uno o varios archivos, a lo largo del tiempo.
+
+### Versionamiento centralizado vs Versionamiento Distribuido.
+
++ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar
+ archivos.
++ El versionamiento distribuido se enfoca en compartir los cambios realizados.
+ Cada cambio tiene un único identificador.
++ El versionamiento distribuido no tiene una estructura definida, incluso se
+ puede mantener el estilo de los repositorios SVN con git.
+
+[Informacion adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
+
+### Por que usar Git?
+
+* Se puede trabajar sin conexion.
+* Colaborar con otros es sencillo!.
+* Derivar, Crear ramas del proyecto (aka: Branching) es facil!.
+* Combinar (aka: Marging)
+* Git es rapido.
+* Git es flexible.
+
+## Arquitectura de Git.
+
+### Repositorio
+
+Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
+comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
+y que sus atributos otorgan acceso al historial del elemento, ademas de otras
+cosas.
+
+Un repositorio esta compuesto por la carpeta .git y un "arbol de trabajo".
+
+### Directorio .git (componentes del repositorio)
+
+El directorio .git contiene todas las configuraciones, registros, branches, HEAD
+y mas.
+
+[Lista detallada.](http://es.gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Directorio de trabajo (componentes del repositorio)
+
+Es basicamente los directorios y archivos dentro del repositorio. La mayorioa de
+las veces se le llama "directorio de trabajo".
+
+### Inidice (componentes del directorio .git)
+
+El inidice es la area de inicio en git. Es basicamente la capa que separa el
+directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores
+mas poder sobre lo que envia y recibe en el repositorio.
+
+### Commit (aka: cambios)
+
+Un commit es una captura de un conjunto de cambios, o modificaciones hechas en
+el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2,
+estos cambios se almacenaran en un commit (aka: captura). Este commit puede ser o
+no ser enviado (aka: "pusheado") hacia un repositorio.
+
+### Branch (rama)
+
+Un "branch", es escencialmente un apuntador hacia el ultimo commit (cambio
+registrado) que se ha realizado. A medida que se realizan mas commits, este
+apuntador se actualizara automaticamente hacia el ultimo commit.
+
+### "HEAD" y "head" (component of .git dir)
+
+"HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un
+repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a
+cualquier commit realizado, un repositorio puede tener cualquier numero de
+"heads".
+
+### conceptos - recursos.
+
+* [Git para informaticos](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git para diseñadores](http://hoth.entp.com/output/git_for_designers.html)
+
+
+## Comandos.
+
+
+### init
+
+Crear un repositorio de git vacio. Las configuraciones, informacion almacenada y
+demas son almacenadas en el directorio ".git".
+
+```bash
+$ git init
+```
+
+### config
+
+Se utiliza para configurar las opciones ya sea globalmente, o solamente en el
+repositorio.
+
+```bash
+# Imprime y guarda algunas variables de configuracion basicas. (Globalmente)
+$ git config --global user.email
+$ git config --global user.name
+
+$ git config --global user.email "corre@gmail.com"
+$ git config --global user.name "nombre"
+```
+
+[Mas sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git)
+
+### help
+
+Otorga un accceso rapido a una guia extremadamente detallada de cada comando en
+git. O puede ser usada simplemente como un recordatorio de estos.
+
+```bash
+# Una vista rapido de los comandos disponibles.
+$ git help
+
+# Chequear todos los comandos disponibles
+$ git help -a
+
+# Obtener ayuda especifica de un comando - manual de usuario
+# git help <comando>
+$ git help add
+$ git help commit
+$ git help init
+```
+
+### status
+
+Muestra las diferencias entre el archivo indice y el commit al cual apunta el
+HEAD actualmente.
+
+
+```bash
+# Mostrara el "branch", archivos sin añadir a la repo, cambios y otras
+# diferencias
+$ git status
+
+# Devuelve ayuda sobre el comando status.
+$ git help status
+```
+
+### add
+
+Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se
+utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por
+lo que no se incluiran en los commits (cambios).
+
+```bash
+# Añade un archivo en el directorio de trabajo actual.
+$ git add FooBar.java
+
+# Añade un archivo que se encuentra bajo un directorio.
+$ git add /directorio/del/archivo/Foo.c
+
+# Soporte para expresiones regulares!
+$ git add ./*.py
+```
+
+### branch
+
+Administra las ramas del repositorios ("branches"). Puedes ver, editar, crear y
+borrar ramas ("branches"), usando este comando.
+
+```bash
+# lista todas las ramas (remotas y locales)
+$ git branch -a
+
+# Añada una nueva rama ("branch").
+$ git branch branchNueva
+
+# Eliminar una rama.
+$ git branch -d branchFoo
+
+# Renombra una rama.
+# git branch -m <anterior> <nuevo>
+$ git branch -m youngling padawan
+
+# Edita la descripcion de la rama.
+$ git branch master --edit-description
+```
+
+### checkout
+
+Actualiza todos los archivos en el directorio de trabajo para que sean igual que
+las versiones almacenadas en el indice, o en un arbol de trabajo especificado.
+
+```bash
+# Despachar un repositorio. - Por defecto la master branch. (la rama principal llamada 'master')
+$ git checkout
+# Despacha una rama especifica.
+$ git checkout padawan
+# Crea una nueva rama y cambia hacia ella, es igual a utilizar: "git brach jedi; git checkout jedi"
+$ git checkout -b jdei
+```
+
+### clone
+
+Clona, o copia, una repo existente en un nuevo directorio. Tambien añada el
+seguimiento hacia las ramas existentes del repo que ha sido clonada, lo que
+permite subir (push) los archivos hacia una rama remota.
+
+```bash
+# Clonar la repo de jquery.
+$ git clone https://github.com/jquery/jquery.git
+```
+
+### commit
+
+Almacena los cambios que almacenados en el indice en un nuevo "commit". Este
+commit contiene los cambios hechos mas un resumen hecho por el desarrollador.
+
+```bash
+# commit with a message
+# realizar un commit y añadirle un mensaje.
+$ git commit -m "jedi anakin wil be - jedis.list"
+```
+
+### diff
+
+Muestra las diferencias entre un archivo en el directorio de trabajo, el indice
+y commits.
+
+```bash
+# Muestra la diferencia entre un directorio de trabajo y el indice.
+$ git diff
+
+# Muestra la diferencia entre el indice y los commits mas recientes.
+$ git diff --cached
+
+# Muestra la diferencia entre el directorio de trabajo y el commit mas reciente.
+$ git diff HEAD
+```
+
+### grep
+
+Permite realizar una busqueda rapida en un repositorio.
+
+Configuracion opcionales:
+
+```bash
+# Gracias a Travis Jeffery por compartir lo siguiente.
+# Permite mostrar numeros de lineas en la salida de grep.
+$ git config --global grep.lineNumber true
+
+# Realiza una busqueda mas lejible, incluyendo agrupacion.
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+```bash
+# Busca por "unaVariable" en todos los archivos ,java
+$ git grep 'unaVariable' -- '*.java'
+
+# Busca por una linea que contenga "nombreArreglo" y , "agregar" o "remover"
+$ git grep -e 'nombreArreglo' --and \( -e agregar -e remover \)
+```
+
+Mas ejemplos:
+[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+
+### log
+
+Muestra los commits (cambios) registrados en el repositotrio.
+
+```bash
+# Muestra todos los commits.
+$ git log
+
+# Muestra un numero x de commits.
+$ git log -n 10
+
+# Muestra solo los commits que se han combinado en el hisotrial
+$ git log --merges
+```
+
+### merge
+
+Combina los cambios de commits realizados externamente dentro de la rama en la
+que se trabaja.
+
+```bash
+# Combina la rama especificada en la rama actual.
+$ git merge jediMaster
+
+# Siempre genere un solo merge commit cuando se utilizar merge.
+$ git merge --no-ff jediMaster
+```
+
+### mv
+
+Renombra o mueve un archivo
+
+```bash
+# Renombrando un archivo
+$ git mv HolaMundo.c AdiosMundo.c
+
+# Moviendo un archivo.
+$ git mv HolaOtraVezMundo.c ./nuevo/directorio/NuevoArchivo.c
+
+# Sustituye un archivo.
+$ git mv -f archivoA archivoB
+```
+
+### pull
+
+Sube (Empuja) de un repositorio y lo combina en otro en una rama diferente.
+
+```bash
+# Actualiza el repositorio local, combinando los nuevos cambios.
+# de las ramas remotas "origin" y "master".
+# from the remote "origin" and "master" branch.
+# git pull <remota> <rama>
+$ git pull origin master
+```
+
+### push
+
+Push and merge changes from a branch to a remote & branch.
+
+```bash
+# Push and merge changes from a local repo to a
+# Empuja y combina cambios de un repositorio local hacian un repositorio remoto
+# llamados "origin" y "master", respectivamente.
+# git push <remota> <rama>
+# git push => por defecto es lo mismo que poner => git push origin master
+$ git push origin master
+```
+
+
+Toma todos los cambios que fueron registrados en una rama, y los repite dentro
+de otra rama.
+*No reescribe los commits que se han empujado antes a un repositorio publico*
+
+```bash
+# Integrar ramaExperimento dentro de la rama "master"
+# git rebase <basebranch> <topicbranch>
+$ git rebase master experimentBranch
+```
+
+[Informacion adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar)
+
+### reset (precaucion)
+
+Reinicia el cabezal actual hacia un estado especificado. Esto permite desacer
+combinaciones (merges), pulls, commits, adds y mas. Es un comando util, pero
+tambien peligrosa si no se sabe lo que se hace.
+
+```bash
+# Reinica el area principal, con el ultimo cambio registrado. (deja los
+# directorios sin cambios)
+$ git reset
+
+# Reinica el area principal, con el ultimo cambio registrado, y reescribe el
+# directorio de trabajo.
+$ git reset --hard
+
+# Mueve la rama actual hacia el commit especificado (no realiza cambios a los
+# directorios), todos los cambios aun existen el directorio.
+$ git reset 31f2bb1
+
+# Mueve la rama actual devuelta a un commit especificado asi como el
+# directorios (borra todos los cambios que no fueron registros y todos los
+# cambios realizados despues del commit especificado).
+$ git reset --hard 31f2bb1
+```
+
+### rm
+
+Lo contrario de git add, git rm remueve los archivos del directorio de trabajo
+actual.
+
+```bash
+# Remueve FooBar.c
+$ git rm FooBar.c
+
+# Remueve un archivo de un directorio.
+$ git rm /directorio/del/archivo/FooBar.c
+```
+
+## Informacion Adicional
+
+* [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1)
+
+* [git-scm - Video-tutoriales](http://git-scm.com/videos)
+
+* [git-scm - Documentacion](http://git-scm.com/book/es)
+
+* [Atlassian Git - Tutoriales y Flujos de trabajo](https://www.atlassian.com/git/)
+
+* [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+
+* [GitGuys](http://www.gitguys.com/)
diff --git a/java.html.markdown b/java.html.markdown
index 3d0cb1d7..b4624d5e 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -26,7 +26,8 @@ import java.util.ArrayList;
// Import all classes inside of java.security package
import java.security.*;
-// Each .java file contains one public class, with the same name as the file.
+// Each .java file contains one outer-level public class, with the same name as
+// the file.
public class LearnJava {
// A program must have a main method as an entry point
@@ -84,7 +85,7 @@ public class LearnJava {
// Char - A single 16-bit Unicode character
char fooChar = 'A';
- // Use final to make a variable immutable
+ // final variables can't be reassigned to another object
final int HOURS_I_WORK_PER_WEEK = 9001;
// Strings
@@ -99,7 +100,7 @@ public class LearnJava {
System.out.println(bazString);
// Arrays
- //The array size must be decided upon declaration
+ //The array size must be decided upon instantiation
//The format for declaring an array is follows:
//<datatype> [] <var name> = new <datatype>[<array size>];
int [] intArray = new int[10];
@@ -161,10 +162,13 @@ public class LearnJava {
// Incrementations
int i = 0;
System.out.println("\n->Inc/Dec-rementation");
- System.out.println(i++); //i = 1. Post-Incrementation
- System.out.println(++i); //i = 2. Pre-Incrementation
- System.out.println(i--); //i = 1. Post-Decrementation
- System.out.println(--i); //i = 0. Pre-Decrementation
+ // The ++ and -- operators increment and decrement by 1 respectively.
+ // If they are placed before the variable, they increment then return;
+ // after the variable they return then increment.
+ System.out.println(i++); //i = 1, prints 0 (post-increment)
+ System.out.println(++i); //i = 2, prints 2 (pre-increment)
+ System.out.println(i--); //i = 1, prints 2 (post-decrement)
+ System.out.println(--i); //i = 0, prints 0 (pre-decrement)
///////////////////////////////////////
// Control Structures
@@ -211,19 +215,19 @@ public class LearnJava {
//Iterated 10 times, fooFor 0->9
}
System.out.println("fooFor Value: " + fooFor);
-
+
// For Each Loop
// An automatic iteration through an array or list of objects.
int[] fooList = {1,2,3,4,5,6,7,8,9};
//for each loop structure => for(<object> : <array_object>)
//reads as: for each object in the array
//note: the object type must match the array.
-
+
for( int bar : fooList ){
//System.out.println(bar);
//Iterates 9 times and prints 1-9 on new lines
}
-
+
// Switch Case
// A switch works with the byte, short, char, and int data types.
// It also works with enumerated types (discussed in Enum Types),
@@ -246,7 +250,7 @@ public class LearnJava {
break;
}
System.out.println("Switch Case Result: " + monthString);
-
+
// Conditional Shorthand
// You can use the '?' operator for quick assignments or logic forks.
// Reads as "If (statement) is true, use <first value>, otherwise, use <second value>"
@@ -294,14 +298,14 @@ public class LearnJava {
trek.speedUp(3); // You should always use setter and getter methods
trek.setCadence(100);
- // toString is a convention to display the value of this Object.
+ // toString returns this Object's string representation.
System.out.println("trek info: " + trek.toString());
} // End main method
} // End LearnJava class
-// You can include other, non-public classes in a .java file
+// You can include other, non-public outer-level classes in a .java file
// Class Declaration Syntax:
@@ -319,7 +323,7 @@ class Bicycle {
String name; // default: Only accessible from within this package
// Constructors are a way of creating classes
- // This is a default constructor
+ // This is a constructor
public Bicycle() {
gear = 1;
cadence = 50;
@@ -327,7 +331,7 @@ class Bicycle {
name = "Bontrager";
}
- // This is a specified constructor (it contains arguments)
+ // This is a constructor that takes arguments
public Bicycle(int startCadence, int startSpeed, int startGear, String name) {
this.gear = startGear;
this.cadence = startCadence;
diff --git a/julia.html.markdown b/julia.html.markdown
index 4ebd50ff..c3d2195b 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -100,7 +100,7 @@ false
println("I'm Julia. Nice to meet you!")
# You don't declare variables before assigning to them.
-some_var = 5 #=> 5
+some_var = 5 #=> 5
some_var #=> 5
# Accessing a previously unassigned variable is an error
@@ -201,7 +201,7 @@ b = [1,2,3]
append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3]
# Check for existence in a list with in
-in(a,1) #=> true
+in(1, a) #=> true
# Examine the length with length
length(a) #=> 8
@@ -218,7 +218,7 @@ end
# Many list functions also work on tuples
length(tup) #=> 3
tup[1:2] #=> (1,2)
-in(tup,2) #=> true
+in(2, tup) #=> true
# You can unpack tuples into variables
a, b, c = (1, 2, 3) #=> (1,2,3) # a is now 1, b is now 2 and c is now 3
@@ -249,14 +249,14 @@ keys(filled_dict)
#=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2])
# Note - dictionary keys are not sorted or in the order you inserted them.
-# Get all values
+# Get all values
values(filled_dict)
#=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2])
# Note - Same as above regarding key ordering.
# Check for existence of keys in a dictionary with in, haskey
-in(filled_dict, ("one", 1)) #=> true
-in(filled_dict, ("two", 3)) #=> false
+in(("one", 1), filled_dict) #=> true
+in(("two", 3), filled_dict) #=> false
haskey(filled_dict, "one") #=> true
haskey(filled_dict, 1) #=> false
@@ -281,8 +281,8 @@ filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4)
push!(filled_set,5) #=> Set{Int64}(5,4,2,3,1)
# Check if the values are in the set
-in(filled_set,2) #=> true
-in(filled_set,10) #=> false
+in(2, filled_set) #=> true
+in(10, filled_set) #=> false
# There are functions for set intersection, union, and difference.
other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3)
@@ -396,7 +396,7 @@ varargs(1,2,3) #=> (1,2,3)
# The ... is called a splat.
# We just used it in a function definition.
# It can also be used in a fuction call,
-# where it will splat an Array or Tuple's contents into the argument list.
+# where it will splat an Array or Tuple's contents into the argument list.
Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays
Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3)
@@ -423,7 +423,7 @@ end
# You can define functions that take keyword arguments
function keyword_args(;k1=4,name2="hello") # note the ;
return ["k1"=>k1,"name2"=>name2]
-end
+end
keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4]
keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"]
@@ -511,7 +511,7 @@ end
# The default constructor's arguments are the properties
# of the tyep, in order the order they are listed in the definition
tigger = Tiger(3.5,"orange") #=> Tiger(3.5,"orange")
-
+
# The type doubles as the constructor function for values of that type
sherekhan = typeof(tigger)(5.6,"fire") #=> Tiger(5.6,"fire")
@@ -529,8 +529,8 @@ subtypes(Number) #=> 6-element Array{Any,1}:
# Complex{Float32}
# Complex{Float64}
# Complex{T<:Real}
- # ImaginaryUnit
- # Real
+ # ImaginaryUnit
+ # Real
subtypes(Cat) #=> 0-element Array{Any,1}
# Every type has a super type; use the `super` function to get it.
@@ -565,7 +565,7 @@ end
# When possible, you should use outer constructors rather than inner ones.
####################################################
-## 6. Multiple-Dispatch
+## 6. Multiple-Dispatch
####################################################
# In Julia, all named functions are generic functions
@@ -641,11 +641,11 @@ end
# Also let the cat go first
fight(c::Cat,l::Lion) = println("The cat beats the Lion")
-#=> Warning: New definition
+#=> Warning: New definition
# fight(Cat,Lion) at none:1
-# is ambiguous with
+# is ambiguous with
# fight(Lion,Cat) at none:2.
-# Make sure
+# Make sure
# fight(Lion,Lion)
# is defined first.
#fight (generic function with 4 methods)
diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/brainfuck-kr.html.markdown
index 661fcfea..c2e4341f 100644
--- a/ko-kr/brainfuck-kr.html.markdown
+++ b/ko-kr/brainfuck-kr.html.markdown
@@ -5,10 +5,11 @@ contributors:
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["JongChan Choi", "http://0xABCDEF.com/"]
+ - ["Peter Lee", "http://peterjlee.com/"]
lang: ko-kr
---
-Brainfuck(f는 대문자로 적지 않습니다)은
+Brainfuck(문장을 시작하는 단어가 아닌이상 첫글자는 대문자를 사용하지 않습니다)은
여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다.
```
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
new file mode 100644
index 00000000..e8d5a538
--- /dev/null
+++ b/pt-br/java-pt.html.markdown
@@ -0,0 +1,435 @@
+---
+
+language: java
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Madison Dickson", "http://github.com/mix3d"]
+translators:
+ - ["Victor Kléber Santos L. Melo", "http://victormelo.com.br/blog"]
+ - ["Renê Douglas N. de Morais", "mailto:rene.douglas.bsi@gmail.com"]
+lang: pt-br
+filename: LearnJava.java
+
+---
+
+Java é uma linguagem de programação de propósito geral, concorrente, baseada em classes e orientada a objetos.
+[Leia mais aqui](http://docs.oracle.com/javase/tutorial/java/index.html)
+
+```java
+// Comentários de uma linha começam com //
+/*
+Comentários de várias linhas são feitos dessa forma.
+*/
+/**
+Comentários JavaDoc são feitos assim. São usados para descrever a Classe ou os atributos da Classe.
+*/
+
+// Importa a classe ArrayList que está dentro do pacote java.util
+import java.util.ArrayList;
+// Importa todas as classes que estão dentro do pacote java.security
+import java.security.*;
+
+// Cada arquivo .java contém uma classe pública, com o mesmo nome do arquivo.
+public class LearnJava {
+
+ // Um programa precisa ter um método main como um ponto de entrada.
+ public static void main (String[] args) {
+
+ // O System.out.println é usado para imprimir no console
+ System.out.println("Olá Mundo!");
+ System.out.println(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Para imprimir sem inserir uma nova lina, use o System.out.print
+ System.out.print("Olá ");
+ System.out.print("Mundo");
+
+
+ ///////////////////////////////////////
+ // Tipos & Variáveis
+ ///////////////////////////////////////
+
+ // Declara-se variáveis usando <tipo> <nome> [
+ // Byte - inteiro de 8 bits com sinal complementado a dois
+ // (-128 <= byte <= 127)
+ byte fooByte = 100;
+
+ // Short - inteiro de 16 bits com sinal complementado a dois
+ // (-32,768 <= short <= 32,767)
+ short fooShort = 10000;
+
+ // Integer - inteiro de 32 bits com sinal complementado a dois
+ // (-2,147,483,648 <= int <= 2,147,483,647)
+ int fooInt = 1;
+
+ // Long - inteiro de 64 bits com sinal complementado a dois
+ // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ long fooLong = 100000L;
+ // L é usado para indicar que o valor da variável é do tipo Long;
+ // sem o L, tudo é tratado como inteiro por padrão.
+
+ // Nota: Java não tem tipos sem sinal
+
+ // Float - Ponto Flutuante 32-bits, de precisão simples no padrão IEEE 754
+ float fooFloat = 234.5f;
+ // f é usado para indicar que o valor da variável é do tipo float;
+ // caso contrário, ela é tratada como double.
+
+ // Double - Ponto Flutuante 64-bits, de precisão dupla no padrão IEEE 754
+ double fooDouble = 123.4;
+
+ // Boolean - true & false
+ boolean fooBoolean = true;
+ boolean barBoolean = false;
+
+ // Char - Um caractere Unicode de 16 bits
+ char fooChar = 'A';
+
+ // Usa-se o final para fazer com que a variável seja imutável.
+ final int HORAS_QUE_TRABALHEI_POR_SEMANA = 9001;
+
+ // Strings
+ String fooString = "Aqui está minha String!";
+
+ // \n é um caractere de escape que inicia uma nova linha
+ String barString = "Imprimir em uma nova linha?\nSem problemas!";
+ // \t é um caractere de escape que adiciona um caractere de tabulação
+ String bazString = "Você quer adicionar tabulação?\tSem problemas!";
+ System.out.println(fooString);
+ System.out.println(barString);
+ System.out.println(bazString);
+
+ // Arrays
+ //O tamanho do array precisa ser determinado na sua declaração
+ //O formato para declarar um array é:
+ //<tipo de dado> [] <nome da variável> = new <tipo de dado>[<tamanho do array>];
+ int [] intArray = new int[10];
+ String [] stringArray = new String[1];
+ boolean [] booleanArray = new boolean[100];
+
+ // Outra maneira de declarar e inicializar um array
+ int [] y = {9000, 1000, 1337};
+
+ // Indexando um array - Acessando um elemento
+ System.out.println("intArray no índice 0: " + intArray[0]);
+
+ // O primeiro termo de um array é o 0 e eles são mutáveis.
+ intArray[1] = 1;
+ System.out.println("intArray no índice 1: " + intArray[1]); // => 1
+
+ // Outras estruturas que devem ser vistas
+ // ArrayLists - São parecidos com os arrays, porém oferecem mais funcionalidades
+ // e o tamanho é mutável.
+ // LinkedLists
+ // Maps
+ // HashMaps
+
+ ///////////////////////////////////////
+ // Operadores
+ ///////////////////////////////////////
+ System.out.println("\n->Operadores");
+
+ int i1 = 1, i2 = 2; // Forma abreviada de escrever múltiplas declarações.
+
+ // Aritmética é feita da forma convencional
+ System.out.println("1+2 = " + (i1 + i2)); // => 3
+ System.out.println("2-1 = " + (i2 - i1)); // => 1
+ System.out.println("2*1 = " + (i2 * i1)); // => 2
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 arredondado para baixo)
+
+ // Módulo
+ System.out.println("11%3 = "+(11 % 3)); // => 2
+
+ // Operadores de comparação
+ System.out.println("3 == 2? " + (3 == 2)); // => false
+ System.out.println("3 != 2? " + (3 != 2)); // => true
+ System.out.println("3 > 2? " + (3 > 2)); // => true
+ System.out.println("3 < 2? " + (3 < 2)); // => false
+ System.out.println("2 <= 2? " + (2 <= 2)); // => true
+ System.out.println("2 >= 2? " + (2 >= 2)); // => true
+
+ // Operadores bit-a-bit!
+ /*
+ ~ Complemento de um
+ << Deslocamento a esquerda com sinal
+ >> Deslocamento a direita com sinal
+ >>> Deslocamento a direita sem sinal
+ & E bit-a-bit
+ | OU bit-a-bit
+ ^ OU exclusivo bit-a-bit
+ */
+
+ // Incrementações
+ int i = 0;
+ System.out.println("\n->Inc/Dec-rementação");
+ System.out.println(i++); //i = 1. Pós-Incrementação
+ System.out.println(++i); //i = 2. Pre-Incrementação
+ System.out.println(i--); //i = 1. Pós-Decrementação
+ System.out.println(--i); //i = 0. Pre-Decrementação
+
+ ///////////////////////////////////////
+ // Estruturas de Controle
+ ///////////////////////////////////////
+ System.out.println("\n->Estruturas de Controle");
+
+ // Os comandos If são parecidos com o da linguagem C
+ int j = 10;
+ if (j == 10){
+ System.out.println("Eu serei impresso");
+ } else if (j > 10) {
+ System.out.println("Eu não");
+ } else {
+ System.out.println("Eu também não");
+ }
+
+ // O Loop While
+ int fooWhile = 0;
+ while(fooWhile < 100)
+ {
+ //System.out.println(fooWhile);
+ //Incrementando o contador
+ //Iteração feita 99 vezes, fooWhile 0->99
+ fooWhile++;
+ }
+ System.out.println("Valor do fooWhile: " + fooWhile);
+
+ // O Loop Do While
+ int fooDoWhile = 0;
+ do
+ {
+ //System.out.println(fooDoWhile);
+ //Incrementando o contador
+ //Iteração feita 99 vezes, fooDoWhile 0->99
+ fooDoWhile++;
+ }while(fooDoWhile < 100);
+ System.out.println("Valor do fooDoWhile: " + fooDoWhile);
+
+ // O Loop For
+ int fooFor;
+ //estrutura do loop for => for(<operação_de_início>; <condição>; <passo>)
+ for(fooFor=0; fooFor<10; fooFor++){
+ //System.out.println(fooFor);
+ //Iteração feita 10 vezes, fooFor 0->9
+ }
+ System.out.println("Valor do fooFor: " + fooFor);
+
+ // O Loop For Each
+ // Itera automaticamente por um array ou lista de objetos.
+ int[] fooList = {1,2,3,4,5,6,7,8,9};
+ //estrutura do loop for each => for(<objeto> : <array_de_objeto>)
+ //lê-se: para cada objeto no array
+ //nota: o tipo do objeto deve ser o mesmo do array.
+
+ for( int bar : fooList ){
+ //System.out.println(bar);
+ //Itera 9 vezes e imprime 1-9 em novas linhas
+ }
+
+ // Switch
+ // Um switch funciona com os tipos de dados: byte, short, char e int
+ // Ele também funciona com tipos enumerados (vistos em tipos Enum)
+ // como também a classe String e algumas outras classes especiais
+ // tipos primitivos: Character, Byte, Short e Integer
+ int mes = 3;
+ String mesString;
+ switch (mes){
+ case 1:
+ mesString = "Janeiro";
+ break;
+ case 2:
+ mesString = "Fevereiro";
+ break;
+ case 3:
+ mesString = "Março";
+ break;
+ default:
+ mesString = "Algum outro mês";
+ break;
+ }
+ System.out.println("Resultado do Switch: " + mesString);
+
+ // Condição de forma abreviada.
+ // Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas.
+ // Lê-se "Se (declaração) é verdadeira, use <primeiro valor>
+ // caso contrário, use <segundo valor>".
+ int foo = 5;
+ String bar = (foo < 10) ? "A" : "B";
+ System.out.println(bar); //Imprime A, pois a condição é verdadeira.
+
+
+ ///////////////////////////////////////
+ // Convertendo tipos de dados e Casting
+ ///////////////////////////////////////
+
+ //Conversão de Dados
+
+ //Convertendo String para Inteiro.
+ Integer.parseInt("123");//retorna uma versão inteira de "123".
+
+ //Convertendo Inteiro para String
+ Integer.toString(123);//retorna uma versão String de 123.
+
+ // Para outras conversões confira as seguintes classes
+ // Double
+ // Long
+ // String
+
+ // Casting
+ // Você pode também converter objetos java, há vários detalhes e
+ // lida com alguns conceitos intermediários
+ // Dê uma olhada no link:
+ // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+
+
+ ///////////////////////////////////////
+ // Classes e Métodos
+ ///////////////////////////////////////
+
+ System.out.println("\n->Classes e Métodos");
+
+ // (segue a definição da classe Bicicleta)
+
+ // Use o new para instanciar uma classe
+ Bicicleta caloi = new Bicicleta(); // Objeto caloi criado.
+
+ // Chame os métodos do objeto
+ caloi.aumentarVelocidade(3); // Você deve sempre usar métodos para modificar variáveis
+ caloi.setRitmo(100);
+
+ // toString é uma convenção para mostrar o valor deste objeto.
+ System.out.println("informações de caloi: " + caloi.toString());
+
+ } // Fim do método main
+} // Fim da classe LearnJava
+
+
+// Você pode incluir outras classes que não são públicas num arquivo .java
+
+
+// Sintaxe de declaração de Classe.
+// <public/private/protected> class <nome da classe>{
+// // atributos, construtores e todos os métodos.
+// // funções são chamadas de métodos em Java.
+// }
+
+class Bicicleta {
+
+ // Atributos/Variáveis da classe Bicicleta.
+ public int ritmo; // Public: Pode ser acessada em qualquer lugar.
+ private int velocidade; // Private: Apenas acessível a classe.
+ protected int catraca; // Protected: Acessível a classe e suas subclasses.
+ String nome; // default: Apenas acessível ao pacote.
+
+ // Construtores são uma forma de criação de classes
+ // Este é o construtor padrão.
+ public Bicicleta() {
+ catraca = 1;
+ ritmo = 50;
+ velocidade = 5;
+ nome = "Bontrager";
+ }
+
+ // Este é um construtor específico (ele contém argumentos).
+ public Bicicleta (int ritmoInicial, int velocidadeInicial, int catracaInicial, String nome) {
+ this.catraca = catracaInicial;
+ this.ritmo = ritmoInicial;
+ this.velocidade = velocidadeInicial;
+ this.nome = nome;
+ }
+
+ // Sintaxe de um método:
+ // <public/private/protected> <tipo de retorno> <nome do método>(<args>) //
+
+ // Classes em Java costumam implementar métodos getters e setters para seus campos.
+
+ // Sintaxe de declaração de métodos
+ // <escopo> <tipo de retorno> <nome do método>(<args>) //
+ public int getRitmo() {
+ return ritmo;
+ }
+
+ // Métodos do tipo void não requerem declaração de retorno.
+ public void setRitmo(int novoValor) {
+ ritmo = novoValor;
+ }
+
+ public void setEquipamento(int novoValor) {
+ catraca = novoValor;
+ }
+
+ public void aumentarVelocidade(int incremento) {
+ velocidade += incremento;
+ }
+
+ public void diminuirVelocidade(int decremento) {
+ velocidade -= decremento;
+ }
+
+ public void setNome(String novoNome) {
+ nome = novoNome;
+ }
+
+ public String getNome() {
+ return nome; // retorna um dado do tipo String.
+ }
+
+ //Método para mostrar os valores dos atributos deste objeto.
+ @Override
+ public String toString() {
+ return "catraca: " + catraca +
+ " ritmo: " + ritmo +
+ " velocidade: " + velocidade +
+ " nome: " + nome;
+ }
+} // fim classe Bicicleta
+
+// Velocipede é uma subclasse de bicicleta.
+class Velocipede extends Bicicleta {
+ // (Velocípedes são bicicletas com rodas dianteiras grandes
+ // Elas não possuem catraca.)
+
+ public Velocipede(int ritmoInicial, int velocidadeInicial){
+ // Chame o construtor do pai (construtor de Bicicleta) com o comando super.
+ super(ritmoInicial, velocidadeInicial, 0, "PennyFarthing");
+ }
+
+ // Você pode marcar um método que você está substituindo com uma @annotation
+ // Para aprender mais sobre o que são as annotations e sua finalidade
+ // dê uma olhada em: http://docs.oracle.com/javase/tutorial/java/annotations/
+ @Override
+ public void setEquipamento(int catraca) {
+ catraca = 0;
+ }
+
+}
+
+```
+
+## Leitura Recomendada
+
+Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, use o Google e encontre exemplos específicos.
+
+Outros tópicos para pesquisar:
+
+* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+
+* [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+
+* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+
+* [Exceções](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+
+* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+
+* [Tipos Genéricos](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
+
+* [Conversões de código Java](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+
+Livros:
+
+* [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/)
diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown
new file mode 100644
index 00000000..344df43a
--- /dev/null
+++ b/pt-br/php-pt.html.markdown
@@ -0,0 +1,700 @@
+---
+language: php
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+translators:
+ - ["Abdala Cerqueira", "http://abda.la"]
+ - ["Raquel Diniz", "http://twitter.com/raquelrdiniz"]
+lang: pt-br
+filename: learnphp-pt.php
+---
+
+Este documento descreve PHP 5+.
+
+```php
+<?php // O código PHP deve estar incluso na tag <?php
+
+// Se o arquivo PHP só contém código PHP, a melhor prática
+// é omitir a tag de fechamento PHP.
+
+// Duas barras iniciam o comentário de uma linha.
+
+# O hash (aka pound symbol) também inicia, mas // é mais comum
+
+/*
+ O texto envolto por barra-asterisco e asterisco-barra
+ faz um comentário de múltiplas linhas
+*/
+
+// Utilize "echo" ou "print" para imprimir a saída
+print('Olá '); // Imprime "Olá " sem quebra de linha
+
+// () são opcionais para print e echo
+echo "Mundo\n"; // Imprime "Mundo" com quebra de linha
+// (Todas as declarações devem terminar com um ponto e vírgula)
+
+// Qualquer coisa fora da tag <?php é impresso automaticamente
+?>
+Olá mundo novamente!
+<?php
+
+
+/************************************
+ * Tipos e variáveis
+ */
+
+// Variáveis começam com o símbolo $.
+// Um nome de variável válido se inicia com uma letra ou sublinhado,
+// seguido por qualquer quantidade de letras, números ou sublinhados.
+
+// Valores booleanos não diferenciam maiúsculo de minúsculo (case-insensitive)
+$boolean = true; // ou TRUE ou True
+$boolean = false; // ou FALSE ou False
+
+// Inteiros
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (um 0 denota um número octal)
+$int4 = 0x0F; // => 15 (um 0x denota um literal hex)
+
+// Flutuantes - Floats (aka doubles)
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// Excluir variável
+unset($int1)
+
+// Aritmética
+$soma = 1 + 1; // 2
+$diferenca = 2 - 1; // 1
+$produto = 2 * 2; // 4
+$quociente = 2 / 1; // 2
+
+// Taquigrafia aritmética
+$numero = 0;
+$numero += 1; // Incrementa $number em 1
+echo $numero++; // Imprime 1 (incrementa após a avaliação)
+echo ++$numero; // Imprime 3 (incrementa antes da avaliação)
+$numero /= $float; // Divide e atribui o quociente de $numero
+
+// Strings podem ser colocadas entre aspas simples
+$sgl_quotes = '$String'; // => '$String'
+
+// Evite o uso de aspas duplas, exceto para incorporar outras variáveis
+$dbl_quotes = "Esta é uma $sgl_quotes."; // => 'Esta é uma $String.'
+
+// Os caracteres especiais só são escapados entre aspas duplas
+$escapado = "Este contém um \t caractere tab.";
+$naoescapado = 'Este contém somente a barra e o t: \t';
+
+// Coloque uma variável entre chaves se necessário
+$dinheiro = "Eu tenho $${numero} no banco.";
+
+// Desde o PHP 5.3, nowdocs podem ser usados para múltiplas linhas sem análise
+$nowdoc = <<<'FIM'
+múltiplas linhas
+string
+FIM;
+
+// Heredocs farão a análise
+$heredoc = <<<FIM
+múltiplas linhas
+$sgl_quotes
+FIM;
+
+// Concatenação de string é feita com .
+echo 'Esta string ' . 'é concatenada';
+
+
+/********************************
+ * Constantes
+ */
+
+// Uma constante é definida usando define()
+// e nunca pode ser mudada durante a execução!
+
+// Um nome de constante válida começa com uma letra ou sublinhado,
+// seguido por qualquer quantidade de letras, números ou sublinhados.
+define("FOO", "alguma coisa");
+
+// Acesso a uma constante é possível usando diretamente o nome escolhido
+echo 'Isto sairá '.FOO;
+
+
+/********************************
+ * Arrays
+ */
+
+// Todos os arrays em PHP são arrays associativos (hashmaps),
+
+// Funciona com todas as versões do PHP
+$associativo = array('Um' => 1, 'Dois' => 2, 'Tres' => 3);
+
+// PHP 5.4 introduziu uma nova sintaxe
+$associativo = ['Um' => 1, 'Dois' => 2, 'Tres' => 3];
+
+echo $associativo['Um']; // imprime 1
+
+// Uma lista de literais atribui chaves inteiras implicitamente
+$array = ['Um', 'Dois', 'Tres'];
+echo $array[0]; // => "Um"
+
+// Adiciona um elemento no final do array
+$array[] = 'Quatro';
+
+// Remove um elemento do array
+unset($array[3]);
+
+/********************************
+ * Saída
+ */
+
+echo('Olá Mundo!');
+// Imprime Olá Mundo! para stdout.
+// Stdout é uma página web se executado em um navegador.
+
+print('Olá Mundo!'); // O mesmo que o echo
+
+// echo é atualmente um construtor de linguagem, então você pode
+// remover os parênteses.
+echo 'Olá Mundo!';
+print 'Olá Mundo!'; // O print também é
+
+$paragrafo = 'parágrafo';
+
+echo 100; // Imprime valores escalares diretamente
+echo $paragrafo; // ou variáveis
+
+// Se a abertura de tags curtas está configurada, ou sua versão do PHP é
+// 5.4.0 ou maior, você pode usar a sintaxe de echo curto
+?>
+<p><?= $paragrafo ?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // $x agora contém o mesmo valor de $y
+$z = &$y;
+// $z agora contém uma referência para $y. Mudando o valor de
+// $z irá mudar o valor de $y também, e vice-versa.
+// $x irá permanecer inalterado com o valor original de $y
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+// Despeja tipos e valores de variável para o stdout
+var_dump($z); // imprime int(0)
+
+// Imprime variáveis para stdout em formato legível para humanos
+print_r($array); // imprime: Array ( [0] => Um [1] => Dois [2] => Tres )
+
+/********************************
+ * Lógica
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// assert lança um aviso se o seu argumento não é verdadeiro
+
+// Estas comparações serão sempre verdadeiras, mesmo que os tipos
+// não sejam os mesmos.
+assert($a == $b); // igualdade
+assert($c != $a); // desigualdade
+assert($c <> $a); // alternativa para desigualdade
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// A seguir, só serão verdadeiras se os valores correspondem e são do mesmo tipo.
+assert($c === $d);
+assert($a !== $d);
+assert(1 == '1');
+assert(1 !== '1');
+
+// As variáveis podem ser convertidas entre tipos, dependendo da sua utilização.
+
+$inteiro = 1;
+echo $inteiro + $inteiro; // => 2
+
+$string = '1';
+echo $string + $string; // => 2 (strings são coagidas para inteiros)
+
+$string = 'one';
+echo $string + $string; // => 0
+// Imprime 0 porque o operador + não pode fundir a string 'um' para um número
+
+// Tipo de fundição pode ser utilizado para tratar uma variável
+// como um outro tipo
+
+$booleano = (boolean) 1; // => true
+
+$zero = 0;
+$booleano = (boolean) $zero; // => false
+
+// Há também funções dedicadas para fundir a maioria dos tipos
+$inteiro = 5;
+$string = strval($inteiro);
+
+$var = null; // valor Null
+
+
+/********************************
+ * Estruturas de controle
+ */
+
+if (true) {
+ print 'Eu fico impresso';
+}
+
+if (false) {
+ print 'Eu não\'t';
+} else {
+ print 'Eu fico impresso';
+}
+
+if (false) {
+ print 'Não fica impresso';
+} elseif(true) {
+ print 'Fica';
+}
+
+// operadores ternários
+print (false ? 'Não fica impresso' : 'Fica');
+
+$x = 0;
+if ($x === '0') {
+ print 'Não imprime';
+} elseif($x == '1') {
+ print 'Não imprime';
+} else {
+ print 'Imprime';
+}
+
+
+
+// Esta sintaxe alternativa é útil para modelos (templates)
+?>
+
+<?php if ($x): ?>
+Isto é exibido se o teste for verdadeiro.
+<?php else: ?>
+Isto é apresentado caso contrário.
+<?php endif; ?>
+
+<?php
+
+// Use switch para salvar alguma lógica.
+switch ($x) {
+ case '0':
+ print 'Switch faz coerção de tipo';
+ break; // Você deve incluir uma pausa, ou você vai cair
+ // no caso 'dois' e 'tres'
+ case 'dois':
+ case 'tres':
+ // Faz alguma coisa, se a variável é 'dois' ou 'tres'
+ break;
+ default:
+ // Faz algo por padrão
+}
+
+// While, do...while e for são repetições provavelmente 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";
+
+$rodas = ['bicicleta' => 2, 'carro' => 4];
+
+// Repetições foreach podem iterar sobre arrays
+foreach ($rodas as $contador_rodas) {
+ echo $contador_rodas;
+} // Imprime "24"
+
+echo "\n";
+
+// Você pode iterar sobre as chaves, bem como os valores
+foreach ($rodas as $veiculo => $contador_rodas) {
+ echo "O $veiculo tem $contador_rodas rodas";
+}
+
+echo "\n";
+
+$i = 0;
+while ($i < 5) {
+ if ($i === 3) {
+ break; // Sai da repetição
+ }
+ echo $i++;
+} // Imprime "012"
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // Ignora esta iteração da repetição
+ }
+ echo $i;
+} // Imprime "0124"
+
+
+/********************************
+ * Functions
+ */
+
+// Define a função com "function":
+function minha_funcao () {
+ return 'Olá';
+}
+
+echo minha_funcao(); // => "Olá"
+
+// Um nome de função válido começa com uma letra ou sublinhado,
+// seguido por qualquer quantidade de letras, números ou sublinhados.
+
+function adicionar($x, $y = 1) { // $y é opcional e o valor padrão é 1
+ $resultado = $x + $y;
+ return $resultado;
+}
+
+echo adicionar(4); // => 5
+echo adicionar(4, 2); // => 6
+
+// $resultado não é acessível fora da função
+// print $resultado; // Dá uma aviso.
+
+// Desde o PHP 5.3 você pode declarar funções anônimas
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// Funções podem retornar funções
+function bar ($x, $y) {
+ // Utilize 'use' para trazer variáveis de fora
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // Imprime "A - B - C"
+
+// Você pode chamar funções nomeadas usando strings
+$nome_funcao = 'add';
+echo $nome_funcao(1, 2); // => 3
+// Útil para dinamicamente determinar qual função será executada.
+// Ou utilize call_user_func(callable $callback [, $parameter [, ... ]]);
+
+/********************************
+ * Includes (Incluir)
+ */
+
+<?php
+// PHP dentro de arquivos incluídos também deve começar com uma tag
+// de abertura do PHP.
+
+include 'meu-arquivo.php';
+// O código meu-arquivo.php já está disponível no escopo atual.
+// Se o arquivo não pode ser incluído (por exemplo, arquivo não encontrado),
+//um aviso é emitido.
+
+include_once 'meu-arquivo.php';
+// Se o código no meu-arquivo.php foi incluído em outro lugar, ele não vai
+// ser incluído novamente. Isso evita vários erros de declaração de classe
+
+require 'meu-arquivo.php';
+require_once 'meu-arquivo.php';
+// Faz o mesmo que o include(), exceto que o require() irá causar um erro fatal
+// se o arquivo não puder ser incluído
+
+// Conteúdo de meu-include.php:
+<?php
+
+return 'Qualquer coisa que você quiser.';
+// Fim do arquivo
+
+// Includes e requires também podem retornar um valor.
+$valor = include 'meu-include.php';
+
+// Arquivos são incluídos com base no caminho determinado ou,
+// se este não for passado, com base na diretiva de configuração include_path.
+// Se o arquivo não é encontrado no include_path, o include vai finalmente
+// verificar no próprio diretório do script chamado e no diretório
+// de trabalho atual antes de falhar.
+/* */
+
+/********************************
+ * Classes
+ */
+
+// As classes são definidas com a palavra-chave class
+
+class MinhaClasse
+{
+ const MINHA_CONST = 'valor'; // Uma constante
+
+ static $valorEstatico = 'estatico';
+
+ // Variáveis estáticas e sua visibilidade
+ public static $valorEstaticoPublico = 'estaticoPublico';
+ // Acessível somente dentro da classe
+ private static $valorEstaticoPrivado = 'estaticoPrivado';
+ // Acessível a partir da classe e subclasses
+ protected static $valorEstaticoProtegido = 'estaticoProtegido';
+
+ // Propriedades devem declarar a sua visibilidade
+ public $propriedade = 'publica';
+ public $propInstancia;
+ protected $prot = 'protegida'; // Acessível a partir da classe e subclasses
+ private $priv = 'privada'; // Acessível somente dentro da classe
+
+ // Criar um construtor com o __construct
+ public function __construct($propInstancia) {
+ // Acesse variável de instância utilizando $this
+ $this->propInstancia = $propInstancia;
+ }
+
+ // Métodos são declarados como funções dentro de uma classe
+ public function meuMetodo()
+ {
+ print 'MinhaClasse';
+ }
+
+ //palavra-chave final faz uma função não poder ser sobrescrita
+ final function voceNaoPodeMeSobrescrever()
+ {
+ }
+
+/*
+ * Declarando propriedades ou métodos de classe como estáticos faz deles
+ * acessíveis sem precisar instanciar a classe. A propriedade declarada
+ * como estática não pode ser acessada com um objeto
+ * instanciado da classe (embora métodos estáticos possam).
+*/
+
+ public static function meuMetodoEstatico()
+ {
+ print 'Eu sou estatico';
+ }
+}
+
+echo MinhaClasse::MINHA_CONST; // Imprime 'valor';
+echo MinhaClasse::$valorEstatico; // Imprime 'estatico';
+MinhaClasse::meuMetodoEstatico(); // Imprime 'Eu sou estatico';
+
+// Instantiate classes using new
+$minha_classe = new MinhaClasse('Uma propriedade de instância');
+// Os parênteses são opcionais, se não passar algum argumento.
+
+// Acesse membros da classe utilizando ->
+echo $minha_classe->propriedade; // => "publica"
+echo $minha_classe->instanceProp; // => "Uma propriedade de instância"
+$minha_classe->meuMetodo(); // => "MinhaClasse"
+
+
+// Estender classes usando "extends"
+class MinhaOutraClasse extends MinhaClasse
+{
+ function imprimePropriedadeProtegida()
+ {
+ echo $this->prot;
+ }
+
+ // Sobrescrever um método
+ function meuMetodo()
+ {
+ parent::meuMetodo();
+ print ' > MinhaOutraClasse';
+ }
+}
+
+$minha_outra_classe = new MinhaOutraClasse('Propriedade de instância');
+$minha_outra_classe->imprimePropriedadeProtegida(); // => Prints "protegida"
+$minha_outra_classe->myMethod(); // Prints "MinhaClasse > MinhaOutraClasse"
+
+final class VoceNaoPodeMeEstender
+{
+}
+
+// Você pode usar "métodos mágicos" para criar getters e setters
+class MinhaClasseMapa
+{
+ private $propriedade;
+
+ public function __get($chave)
+ {
+ return $this->$chave;
+ }
+
+ public function __set($chave, $valor)
+ {
+ $this->$chave = $valor;
+ }
+}
+
+$x = new MinhaClasseMapa();
+echo $x->propriedade; // Irá usar o método __get()
+$x->propriedade = 'Algo'; // Irá usar o método __set()
+
+// Classes podem ser abstratas (usando a palavra-chave abstract) ou
+// implementar interfaces (usando a palavra-chave implements).
+// Uma interface é declarada com a palavra-chave interface.
+
+interface InterfaceUm
+{
+ public function fazAlgo();
+}
+
+interface InterfaceDois
+{
+ public function fazOutraCoisa();
+}
+
+// interfaces podem ser estendidas
+interface InterfaceTres extends InterfaceDois
+{
+ public function fazOutroContrato();
+}
+
+abstract class MinhaClasseAbstrata implements InterfaceUm
+{
+ public $x = 'fazAlgo';
+}
+
+class MinhaClasseConcreta extends MinhaClasseAbstrata implements InterfaceDois
+{
+ public function fazAlgo()
+ {
+ echo $x;
+ }
+
+ public function fazOutraCoisa()
+ {
+ echo 'fazOutraCoisa';
+ }
+}
+
+
+// Classes podem implementar mais de uma interface
+class UmaOutraClasse implements InterfaceUm, InterfaceDois
+{
+ public function fazAlgo()
+ {
+ echo 'fazAlgo';
+ }
+
+ public function fazOutraCoisa()
+ {
+ echo 'fazOutraCoisa';
+ }
+}
+
+
+/********************************
+ * Traits (Traços)
+ */
+
+// Traits estão disponíveis a partir de PHP 5.4.0 e
+// são declarados usando "trait"
+
+trait MeuTraco
+{
+ public function meuMetodoDeTraco()
+ {
+ print 'Eu tenho MeuTraco';
+ }
+}
+
+class MinhaClasseTracada
+{
+ use MeuTraco;
+}
+
+$cls = new MinhaClasseTracada();
+$cls->meuMetodoDeTraco(); // Imprime "Eu tenho MeuTraco"
+
+
+/********************************
+ * Namespaces (Espaço nominal)
+ */
+
+// Esta seção é separada porque a declaração de espaços nominais
+// deve ser a primeira instrução em um arquivo. Vamos fingir, aqui não é o caso
+
+<?php
+
+// Por padrão, as classes existem no espaço nominal global e podem
+// ser explicitamente chamadas com uma barra invertida.
+
+$cls = new \MinhaClasse();
+
+
+
+// Definir o espaço nominal para o arquivo
+namespace Meu\Espaconominal;
+
+class MinhaClasse
+{
+}
+
+// (de outro arquivo)
+$cls = new Meu\Espaconominal\MinhaClasse;
+
+//Ou de dentro de outro espaço nominal.
+namespace Meu\Outro\Espaconominal;
+
+use My\Espaconominal\MinhaClasse;
+
+$cls = new MinhaClasse();
+
+//Ou você pode usar como apelido de espaço nominal;
+
+namespace Meu\Outro\Espaconominal;
+
+use Meu\Espaconominal as OutroEspaconominal;
+
+$cls = new OutroEspaconominal\MinhaClasse();
+
+*/
+
+```
+
+## Mais informações
+
+Visite a [documentação oficial do PHP](http://www.php.net/manual/)
+para referência e participação da comunidade.
+
+Se você estiver interessado em melhores práticas atualizadas, visite
+[PHP The Right Way](http://www.phptherightway.com/).
+
+Se você está vindo de uma linguagem com bom gerenciamento de pacotes, confira
+[Composer](http://getcomposer.org/).
+
+Para os padrões comuns, visite o Grupo de Interoperabilidade de Framework PHP
+[PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/python.html.markdown b/python.html.markdown
index 08e68407..22d236ac 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -2,6 +2,7 @@
language: python
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "http://aminbandali.com"]
filename: learnpython.py
---
@@ -159,6 +160,8 @@ li[1:3] #=> [2, 4]
li[2:] #=> [4, 3]
# Omit the end
li[:3] #=> [1, 2, 4]
+# Revert the list
+li[::-1] #=> [3, 4, 2, 1]
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
@@ -481,6 +484,7 @@ dir(math)
* [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)
### Dead Tree
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
new file mode 100644
index 00000000..874e0821
--- /dev/null
+++ b/ru-ru/c-ru.html.markdown
@@ -0,0 +1,483 @@
+---
+language: c
+filename: learnc.c
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+ - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
+translators:
+ - ["Evlogy Sutormin", "http://evlogii.com"]
+lang: ru-ru
+---
+
+Что ж, Си всё ещё является лидером среди современных высокопроизводительных языков.
+
+Для большинствоа программистов, Си – это самый низкоуровневый язык на котором они когда-либо писали,
+но этот язык даёт больше, чем просто повышение производительности.
+Держите это руководство в памяти и вы сможете использовать Си максимально эффективно.
+
+```c
+// Однострочный комментарий начинается с // - доступен только после С99.
+
+/*
+Многострочный комментарий выглядит так. Работает начиная с С89.
+*/
+
+// Импорт файлов происходит с помощью **#include**
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+// Файлы <в угловых скобочках> будут подключаться из стандартной библиотеки.
+// Свои файлы необходимо подключать с помощью "двойных кавычек".
+#include "my_header.h"
+
+// Объявление функций должно происходить в .h файлах или вверху .c файла.
+void function_1();
+void function_2();
+
+// Точка входа в программу – это функция main.
+int main() {
+ // для форматированного вывода в консоль используется printf
+ // %d – означает, что будем выводить целое число, \n переводит указатель вывода
+ // на новую строчку
+ printf("%d\n", 0); // => напечатает "0"
+ // Каждый оператор заканчивается точкой с запятой.
+
+ ///////////////////////////////////////
+ // Типы
+ ///////////////////////////////////////
+
+ // int обычно имеет длину 4 байта
+ int x_int = 0;
+
+ // short обычно имеет длину 2 байта
+ short x_short = 0;
+
+ // char гарантированно имеет длину 1 байта
+ char x_char = 0;
+ char y_char = 'y'; // Символьные литералы заключаются в кавычки ''
+
+ // long как правило занимает от 4 до 8 байт
+ // long long занимает как минимум 64 бита
+ long x_long = 0;
+ long long x_long_long = 0;
+
+ // float это 32-битное число с плавающей точкой
+ float x_float = 0.0;
+
+ // double это 64-битное число с плавающей точкой
+ double x_double = 0.0;
+
+ // Целые типы могут быть беззнаковыми.
+ unsigned short ux_short;
+ unsigned int ux_int;
+ unsigned long long ux_long_long;
+
+ // sizeof(T) возвращает размер переменной типа Т в байтах.
+ // sizeof(obj) возвращает размер объекта obj в байтах.
+ printf("%zu\n", sizeof(int)); // => 4 (на большинстве машин int занимает 4 байта)
+
+ // Если аргуметом sizeof будет выражение, то этот аргумент вычисляется
+ // ещё во время компиляции кода (кроме динамических массивов).
+ int a = 1;
+ // size_t это беззнаковый целый тип который использует как минимум 2 байта
+ // для записи размера объекта
+ size_t size = sizeof(a++); // a++ не выполнится
+ printf("sizeof(a++) = %zu, где a = %d\n", size, a);
+ // выведет строку "sizeof(a++) = 4, где a = 1" (на 32-битной архитектуре)
+
+ // Можно задать размер массива при объявлении.
+ char my_char_array[20]; // Этот массив занимает 1 * 20 = 20 байт
+ int my_int_array[20]; // Этот массив занимает 4 * 20 = 80 байт (сумма 4-битных слов)
+
+ // Можно обнулить массив при объявлении.
+ char my_array[20] = {0};
+
+ // Индексация массива происходит также как и в других Си-подобных языках.
+ my_array[0]; // => 0
+
+ // Массивы изменяемы. Это просто память как и другие переменные.
+ my_array[1] = 2;
+ printf("%d\n", my_array[1]); // => 2
+
+ // В C99 (а также опционально в C11), массив может быть объявлен динамически.
+ // Размер массива не обязательно должен быть рассчитан на этапе компиляции.
+ printf("Enter the array size: "); // спрашиваем юзера размер массива
+ char buf[0x100];
+ fgets(buf, sizeof buf, stdin);
+ size_t size = strtoul(buf, NULL, 10); // strtoul парсит строку в беззнаковое целое
+ int var_length_array[size]; // объявление динамического массива
+ printf("sizeof array = %zu\n", sizeof var_length_array);
+ // Вывод программы (в зависимости от архитектуры) будет таким:
+ // > Enter the array size: 10
+ // > sizeof array = 40
+
+ // Строка – это просто массив символов, оканчивающийся нулевым (NUL (0x00)) байтом
+ // представляемым в строке специальным символом '\0'.
+ // Нам не нужно вставлять нулевой байт в строковой литерал,
+ // компилятор всё сделает за нас.
+ char a_string[20] = "This is a string";
+ printf("%s\n", a_string); // %s обозначает вывод строки
+
+ printf("%d\n", a_string[16]); // => 0
+ // байт #17 тоже равен 0 (а также 18, 19, и 20)
+
+ // Если между одинарными кавычками есть символ – это символьный литерал,
+ // но это тип int, а не char (по историческим причинам).
+
+ int cha = 'a'; // хорошо
+ char chb = 'a'; // тоже хорошо (подразумевается преобразование int в char)
+
+ ///////////////////////////////////////
+ // Операторы
+ ///////////////////////////////////////
+
+ // Можно использовать множественное объявление.
+ int i1 = 1, i2 = 2;
+ float f1 = 1.0, f2 = 2.0;
+
+ // Арифметика обычная
+ i1 + i2; // => 3
+ i2 - i1; // => 1
+ i2 * i1; // => 2
+ i1 / i2; // => 0 (0.5, но обрезается до 0)
+
+ f1 / f2; // => 0.5, плюс-минус погрешность потому что,
+ // цифры с плавающей точкой вычисляются неточно!
+
+ // Модуль
+ 11 % 3; // => 2
+
+ // Операции сравнения вам уже знакомы, но в Си нет булевого типа.
+ // Вместо него используется int. 0 это false, всё остальное это true.
+ // Операции сравнения всегда возвращают 1 или 0.
+ 3 == 2; // => 0 (false)
+ 3 != 2; // => 1 (true)
+ 3 > 2; // => 1
+ 3 < 2; // => 0
+ 2 <= 2; // => 1
+ 2 >= 2; // => 1
+
+ // Си это не Питон – операции сравнения могут быть только парными.
+ int a = 1;
+ // ОШИБКА:
+ int between_0_and_2 = 0 < a < 2;
+ // Правильно:
+ int between_0_and_2 = 0 < a && a < 2;
+
+ // Логика
+ !3; // => 0 (логическое НЕ)
+ !0; // => 1
+ 1 && 1; // => 1 (логическое И)
+ 0 && 1; // => 0
+ 0 || 1; // => 1 (лигическое ИЛИ)
+ 0 || 0; // => 0
+
+ // Битовые операторы
+ ~0x0F; // => 0xF0 (побитовое отрицание)
+ 0x0F & 0xF0; // => 0x00 (побитовое И)
+ 0x0F | 0xF0; // => 0xFF (побитовое ИЛИ)
+ 0x04 ^ 0x0F; // => 0x0B (исключающее ИЛИ (XOR))
+ 0x01 << 1; // => 0x02 (побитовый сдвиг влево (на 1))
+ 0x02 >> 1; // => 0x01 (побитовый сдвиг вправо (на 1))
+
+ // Будьте осторожны при сдвиге беззнакового int, эти операции не определены:
+ // - сдвиг в знаковый бит у целого числа (int a = 1 << 32)
+ // - сдвиг влево отрицательных чисел (int a = -1 << 2)
+
+ ///////////////////////////////////////
+ // Структуры ветвления
+ ///////////////////////////////////////
+
+ // Условный оператор
+ if (0) {
+ printf("I am never run\n");
+ } else if (0) {
+ printf("I am also never run\n");
+ } else {
+ printf("I print\n");
+ }
+
+ // Цикл с предусловием
+ int ii = 0;
+ while (ii < 10) {
+ printf("%d, ", ii++); // инкрементация происходит после того как
+ // знаечние ii передано ("postincrement")
+ } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ //Цикл с постусловием
+ int kk = 0;
+ do {
+ printf("%d, ", kk);
+ } while (++kk < 10); // инкрементация происходит перед тем как
+ // передаётся знаечние kk ("preincrement")
+ // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // Цикл со счётчиком
+ int jj;
+ for (jj=0; jj < 10; jj++) {
+ printf("%d, ", jj);
+ } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // Ветвление с множественным выбором
+ switch (some_integral_expression) {
+ case 0: // значения должны быть целыми константами (и могут быть выражениями)
+ do_stuff();
+ break; // если не написать break; то управление будет передено следующему блоку
+ case 1:
+ do_something_else();
+ break;
+ default:
+ // если не было совпадения, то выполняется блок default:
+ fputs("ошибка!\n", stderr);
+ exit(-1);
+ break;
+ }
+
+ ///////////////////////////////////////
+ // Форматирование вывода
+ ///////////////////////////////////////
+
+ // Каждое выражение в Си имеет тип, но вы можете привести один тип к другому,
+ // если хотите (с некоторыми искажениями).
+
+ int x_hex = 0x01; // Вы можете назначать переменные с помощью шеснадцатеричного кода.
+
+ // Приведение типов будет пытаться сохранять цифровые значения.
+ printf("%d\n", x_hex); // => Prints 1
+ printf("%d\n", (short) x_hex); // => Prints 1
+ printf("%d\n", (char) x_hex); // => Prints 1
+
+ // Типы могут переполняться без вызова предупреждения.
+ printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
+
+ // Для определения максимального значения типов `char`, `signed char` и `unisigned char`,
+ // соответственно используйте CHAR_MAX, SCHAR_MAX и UCHAR_MAX макросы из <limits.h>
+
+ // Целые типы могут быть приведены к вещественным и наоборот.
+ printf("%f\n", (float)100); // %f formats a float
+ printf("%lf\n", (double)100); // %lf formats a double
+ printf("%d\n", (char)100.0);
+
+ ///////////////////////////////////////
+ // Указатели
+ ///////////////////////////////////////
+
+ // Указатель – это переменная которая хранит адрес в памяти.
+ // При объявлении указателя указывается тип данных переменной на которую он будет ссылаться.
+ // Вы можете получить адрес любой переменной, а потом работать с ним.
+
+ // Используйте & для получения адреса переменной.
+ int x = 0;
+ printf("%p\n", (void *)&x); // => Напечатает адрес в памяти, где лежит переменная x
+ // (%p выводит указатель на void *)
+
+ // Для объявления указателя нужно поставить * перед именем.
+ int *px, not_a_pointer; // px это указатель на int
+ px = &x; // сохранит адрес x в px
+ printf("%p\n", (void *)px); // => Напечатает адрес в памяти, где лежит переменная px
+ printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
+ // => Напечатает "8, 4" в 64 битной системе
+
+ // Для того, чтобы получить знаечние по адресу, напечатайте * перед именем.
+ // Да, использование * при объявлении указателя и получении значения по адресу
+ // немного запутано, но вы привыкнете.
+ printf("%d\n", *px); // => Напечаатет 0, значение перемененной x
+
+ // Вы также можете изменять значение, на которое указывает указатель.
+ (*px)++; // Инкрементирует значение на которое указывает px на единицу
+ printf("%d\n", *px); // => Напечатает 1
+ printf("%d\n", x); // => Напечатает 1
+
+ // Массивы удобно использовать для болшого количества однотипных данных.
+ int x_array[20];
+ int xx;
+ for (xx = 0; xx < 20; xx++) {
+ x_array[xx] = 20 - xx;
+ } // Объявление x_array с значениями 20, 19, 18,... 2, 1
+
+ // Объявление указателя на int с адресом массива.
+ int* x_ptr = x_array;
+ // x_ptr сейчас указывает на первый элемент массива (со значением 20).
+ // Это рабоатет, потому что имя массива возвращает указатель на первый элемент.
+ // Например, когда массив передаётся в функцию или назначается указателю, он
+ // невявно преобразуется в указатель.
+ // Исключения: когда массив является аргументом для оператор '&':
+ int arr[10];
+ int (*ptr_to_arr)[10] = &arr; // &arr не является 'int *'!
+ // он является "указателем на массив" (из десяти 'int'ов).
+ // или когда массив это строчный литерал, используемый при объявлении массива символов:
+ char arr[] = "foobarbazquirk";
+ // или когда массив является аргументом `sizeof` или `alignof` операторов:
+ int arr[10];
+ int *ptr = arr; // то же самое что и "int *ptr = &arr[0];"
+ printf("%zu %zu\n", sizeof arr, sizeof ptr); // напечатает "40, 4" или "40, 8"
+
+ // Декрементация и инкрементация указателей зависит от их типа
+ // (это называется арифметика указателей)
+ printf("%d\n", *(x_ptr + 1)); // => Напечатает 19
+ printf("%d\n", x_array[1]); // => Напечатает 19
+
+ // Вы также можете динамически выделять несколько блоков памяти с помощью
+ // функции malloc из стандартной библиотеки, которая принимает один
+ // аргумент типа size_t – количество байт необходимых для выделения.
+ int *my_ptr = malloc(sizeof(*my_ptr) * 20);
+ for (xx = 0; xx < 20; xx++) {
+ *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
+ } // Выделяет память для 20, 19, 18, 17... 2, 1 (как int'ы)
+
+ // Работа с памятью с помощью указателей может давать неожиданные и
+ // непредсказуемые результаты.
+ printf("%d\n", *(my_ptr + 21)); // => Напечатает кто-нибудь-знает-что?
+ // Скорей всего программа вылетит.
+
+ // Когда вы закончили работать с памятью, которую ранее выделили, вам необходимо
+ // освободить её, иначе это может вызвать утечку памяти или ошибки.
+ free(my_ptr);
+
+ // Строки это массивы символов, но обычно они представляются как
+ // указатели на символ (как указатели на первый элемент массива).
+ // Хорошей практикой считается использование `const char *' при объявлении
+ // строчного литерала. При таком подходе литерал не может быть изменён.
+ // (например "foo"[0] = 'a' вызовет ошибку!)
+
+ const char *my_str = "This is my very own string literal";
+ printf("%c\n", *my_str); // => 'T'
+
+ // Это не работает, если строка является массивом
+ // (потенциально задаваемой с помощью строкового литерала)
+ // который находиться в перезаписываемой части памяти:
+
+ char foo[] = "foo";
+ foo[0] = 'a'; // это выполнится и строка теперь "aoo"
+
+ void function_1()
+} // конец функции main()
+
+///////////////////////////////////////
+// Функции
+///////////////////////////////////////
+
+// Синтаксис объявления функции:
+// <возвращаемый тип> <имя функции>(аргументы)
+
+int add_two_ints(int x1, int x2) {
+ return x1 + x2; // Используйте return для возврата значения
+}
+
+/*
+Данные в функцию передаются "по значению", но никто не мешает
+вам передавать в функцию указатели и менять данные по указателям.
+
+Например: инвертировать строку прямо в функции
+*/
+
+// void означает, что функция ничего не возвращает
+void str_reverse(char *str_in) {
+ char tmp;
+ int ii = 0;
+ size_t len = strlen(str_in); // `strlen()` является частью стандартной библиотеки
+ for (ii = 0; ii < len / 2; ii++) {
+ tmp = str_in[ii];
+ str_in[ii] = str_in[len - ii - 1]; // ii-тый символ с конца
+ str_in[len - ii - 1] = tmp;
+ }
+}
+
+char c[] = "This is a test.";
+str_reverse(c);
+printf("%s\n", c); // => Выведет ".tset a si sihT"
+
+///////////////////////////////////////
+// Типы и структуры определяемые пользователем
+///////////////////////////////////////
+
+// typedef используется для задания стандартным типам своих названий
+typedef int my_type;
+my_type my_type_var = 0;
+
+// Структуры это просто коллекция данных, память выделяется последовательно,
+// в том порядке в котором записаны данные.
+struct rectangle {
+ int width;
+ int height;
+};
+
+// sizeof(struct rectangle) == sizeof(int) + sizeof(int) – не всегда верно
+// из-за особенностей компиляции (необычное поведение при отступах)[1].
+
+void function_1() {
+ struct rectangle my_rec;
+
+ // Доступ к структурам через точку
+ my_rec.width = 10;
+ my_rec.height = 20;
+
+ // Вы можете объявить указатель на структуру
+ struct rectangle *my_rec_ptr = &my_rec;
+
+ // Можно доступаться к структуре и через указатель
+ (*my_rec_ptr).width = 30;
+
+ // ... или ещё лучше: используйте оператор -> для лучшей читабельночти
+ my_rec_ptr->height = 10; // то же что и "(*my_rec_ptr).height = 10;"
+}
+
+// Вы можете применить typedef к структуре, для удобства.
+typedef struct rectangle rect;
+
+int area(rect r) {
+ return r.width * r.height;
+}
+
+// Если вы имеете большую структуру, можно доступаться к ней "по указателю",
+// чтобы избежать копирования всей структуры.
+int area(const rect *r) {
+ return r->width * r->height;
+}
+
+///////////////////////////////////////
+// Указатели на функции
+///////////////////////////////////////
+
+/*
+Во время исполнения функции находятся по известным адресам в памяти.
+Указатель на функцию может быть использован для непосредственного вызова функции.
+Однако синтаксис может сбивать с толку.
+
+Пример: использование str_reverse по указателю
+*/
+
+void str_reverse_through_pointer(char *str_in) {
+ // Определение функции через указатель.
+ void (*f)(char *); // Сигнатура должна полность совпадать с целевой функцией.
+ f = &str_reverse; // Присвоить фактический адрес (во время исполнения)
+ // "f = str_reverse;" тоже будет работать.
+ //Имя функции (как и массива) возвращает указатель на начало.
+ (*f)(str_in); // Просто вызываем функцию через указатель.
+ // "f(str_in);" или вот так
+}
+```
+
+## На почитать
+
+Лучше всего найдите копию [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
+Это **книга** написанная создателями Си. Но будьте осторожны, она содержит идеи которые больше не считаются хорошими.
+
+Другой хороший ресурс: [Learn C the hard way](http://c.learncodethehardway.org/book/).
+
+Если у вас появился вопрос, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com).
+
+Очень важно использовать правильные отступы и ставить пробелы в нужных местах.
+Читаемый код лучше чем красивый или быстрый код.
+Чтобы научиться писать хороший код, почитайте [Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
+
+Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья.
+
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown
index 8098f601..27b5d894 100644
--- a/ru-ru/go-ru.html.markdown
+++ b/ru-ru/go-ru.html.markdown
@@ -1,6 +1,4 @@
---
-name: Go
-category: language
language: Go
filename: learngo-ru.go
contributors:
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
new file mode 100644
index 00000000..72e3b9e0
--- /dev/null
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -0,0 +1,317 @@
+---
+language: Objective-C
+filename: LearnObjectiveC.m
+contributors:
+ - ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
+ - ["Yannick Loriot", "https://github.com/YannickL"]
+translators:
+ - ["Evlogy Sutormin", "http://evlogii.com"]
+lang: ru-ru
+---
+
+Objective-C — компилируемый объектно-ориентированный язык программирования, используемый корпорацией Apple,
+построенный на основе языка Си и парадигм Smalltalk.
+В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения.
+
+```cpp
+// Однострочный комментарий
+
+/*
+Многострочный
+комментарий
+*/
+
+// Импорт файлов фреймворка Foundation с помощью #import
+#import <Foundation/Foundation.h>
+#import "MyClass.h"
+
+// Точка входа в программу это функция main,
+// которая возвращает целый тип integer
+int main (int argc, const char * argv[])
+{
+ // Создание autorelease pool для управления памятью
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ // Используйте NSLog для печати в консоль
+ NSLog(@"Hello World!"); // Напечатает строку "Hello World!"
+
+ ///////////////////////////////////////
+ // Типы и переменные
+ ///////////////////////////////////////
+
+ // Простое объявление
+ int myPrimitive1 = 1;
+ long myPrimitive2 = 234554664565;
+
+ // Помещайте * в начало названия объекта для строго типизированного объявления
+ MyClass *myObject1 = nil; // Строгая типизация
+ id myObject2 = nil; // Слабая типизация
+
+ NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)"
+ // %@ – это объект
+ // 'description' это общий для всех объектов метод вывода данных
+
+ // Строка
+ NSString *worldString = @"World";
+ NSLog(@"Hello %@!", worldString); // напечатает "Hello World!"
+
+ // Символьные литералы
+ NSNumber *theLetterZNumber = @'Z';
+ char theLetterZ = [theLetterZNumber charValue];
+ NSLog(@"%c", theLetterZ);
+
+ // Целочисленный литералы
+ NSNumber *fortyTwoNumber = @42;
+ int fortyTwo = [fortyTwoNumber intValue];
+ NSLog(@"%i", fortyTwo);
+
+ // Беззнаковый целочисленный литерал
+ NSNumber *fortyTwoUnsignedNumber = @42U;
+ unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue];
+ NSLog(@"%u", fortyTwoUnsigned);
+
+ NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
+ short fortyTwoShort = [fortyTwoShortNumber shortValue];
+ NSLog(@"%hi", fortyTwoShort);
+
+ NSNumber *fortyTwoLongNumber = @42L;
+ long fortyTwoLong = [fortyTwoLongNumber longValue];
+ NSLog(@"%li", fortyTwoLong);
+
+ // Вещественный литерал
+ NSNumber *piFloatNumber = @3.141592654F;
+ float piFloat = [piFloatNumber floatValue];
+ NSLog(@"%f", piFloat);
+
+ NSNumber *piDoubleNumber = @3.1415926535;
+ double piDouble = [piDoubleNumber doubleValue];
+ NSLog(@"%f", piDouble);
+
+ // BOOL (булевый) литерал
+ NSNumber *yesNumber = @YES;
+ NSNumber *noNumber = @NO;
+
+ // Массив
+ NSArray *anArray = @[@1, @2, @3, @4];
+ NSNumber *thirdNumber = anArray[2];
+ NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3"
+
+ // Словарь
+ NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
+ NSObject *valueObject = aDictionary[@"A Key"];
+ NSLog(@"Object = %@", valueObject); // Напечатает "Object = (null)"
+
+ ///////////////////////////////////////
+ // Операторы
+ ///////////////////////////////////////
+
+ // Операторы работают также как в Си.
+ // Например:
+ 2 + 5; // => 7
+ 4.2f + 5.1f; // => 9.3f
+ 3 == 2; // => 0 (НЕТ)
+ 3 != 2; // => 1 (ДА)
+ 1 && 1; // => 1 (логическое И)
+ 0 || 1; // => 1 (логическое ИЛИ)
+ ~0x0F; // => 0xF0 (побитовое отрицание)
+ 0x0F & 0xF0; // => 0x00 (побитовое И)
+ 0x01 << 1; // => 0x02 (побитовый сдвиг влево (на 1))
+
+ ///////////////////////////////////////
+ // Структуры ветвления
+ ///////////////////////////////////////
+
+ // Условный оператор
+ if (NO)
+ {
+ NSLog(@"I am never run");
+ } else if (0)
+ {
+ NSLog(@"I am also never run");
+ } else
+ {
+ NSLog(@"I print");
+ }
+
+ // Ветвление с множественным выбором
+ switch (2)
+ {
+ case 0:
+ {
+ NSLog(@"I am never run");
+ } break;
+ case 1:
+ {
+ NSLog(@"I am also never run");
+ } break;
+ default:
+ {
+ NSLog(@"I print");
+ } break;
+ }
+
+ // Цикл с предусловием
+ int ii = 0;
+ while (ii < 4)
+ {
+ NSLog(@"%d,", ii++); // ii++ инкрементирует ii после передачи значения
+ } // => напечатает "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Цикл со счётчиком
+ int jj;
+ for (jj=0; jj < 4; jj++)
+ {
+ NSLog(@"%d,", jj);
+ } // => напечатает "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // // Цикл просмотра
+ NSArray *values = @[@0, @1, @2, @3];
+ for (NSNumber *value in values)
+ {
+ NSLog(@"%@,", value);
+ } // => напечатает "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Обработка исключений
+ @try
+ {
+ // Ваше исключение здесь
+ @throw [NSException exceptionWithName:@"FileNotFoundException"
+ reason:@"File Not Found on System" userInfo:nil];
+ } @catch (NSException * e)
+ {
+ NSLog(@"Exception: %@", e);
+ } @finally
+ {
+ NSLog(@"Finally");
+ } // => напечатает "Exception: File Not Found on System"
+ // "Finally"
+
+ ///////////////////////////////////////
+ // Объекты
+ ///////////////////////////////////////
+
+ // Создание объектов через выделение памяти и инициализацию.
+ // Объект не является полнофункциональным пока обе части не выполнятся.
+ MyClass *myObject = [[MyClass alloc] init];
+
+ // В Objective-C можель ООП базируется на передаче сообщений.
+ // В Objective-C Вы не просто вызваете метод; вы посылаете сообщение.
+ [myObject instanceMethodWithParameter:@"Steve Jobs"];
+
+ // Очищайте память, перед завершением работы программы.
+ [pool drain];
+
+ // Конец программы.
+ return 0;
+}
+
+///////////////////////////////////////
+// Классы и функции
+///////////////////////////////////////
+
+// Объявляйте свой класс в файле МойКласс.h
+// Синтаксис объявления:
+// @interface ИмяКласса : ИмяКлассаРодителя <ИмплементируемыеПротоколы>
+// {
+// Объявление переменных;
+// }
+// -/+ (тип) Объявление метода(ов).
+// @end
+
+
+@interface MyClass : NSObject <MyProtocol>
+{
+ int count;
+ id data;
+ NSString *name;
+}
+// При объявлении свойств сразу генерируются геттер и сеттер
+@property int count;
+@property (copy) NSString *name; // Скопировать объект в ходе присвоения.
+@property (readonly) id data; // Генерация только геттера
+
+// Методы
++/- (return type)methodSignature:(Parameter Type *)parameterName;
+
+// + для методов класса
++ (NSString *)classMethod;
+
+// - для метода объекта
+- (NSString *)instanceMethodWithParameter:(NSString *)string;
+- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number;
+
+@end
+
+// Имплементируйте методы в файле МойКласс.m:
+
+@implementation MyClass
+
+// Вызывается при высвобождении памяти под объектом
+- (void)dealloc
+{
+}
+
+// Конструкторы – это способ осздания объектов класса.
+// Это обычный конструктор вызываемый при создании объекта клсааа.
+- (id)init
+{
+ if ((self = [super init]))
+ {
+ self.count = 1;
+ }
+ return self;
+}
+
++ (NSString *)classMethod
+{
+ return [[self alloc] init];
+}
+
+- (NSString *)instanceMethodWithParameter:(NSString *)string
+{
+ return @"New string";
+}
+
+- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number
+{
+ return @42;
+}
+
+// Методы объявленные в МyProtocol (см. далее)
+- (void)myProtocolMethod
+{
+ // имплементация
+}
+
+@end
+
+/*
+ * Протокол объявляет методы которые должны быть имплементированы
+ * Протокол не является классом. Он просто определяет интерфейс,
+ * который должен быть имплементирован.
+ */
+
+@protocol MyProtocol
+ - (void)myProtocolMethod;
+@end
+```
+## На почитать
+
+[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C)
+
+[Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/)
+
+[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)
+
+[iOS разработчик: Обзор книг для новичка](http://habrahabr.ru/post/166213/)
+
+[Хочешь быть iOS разработчиком? Будь им!](http://www.pvsm.ru/ios/12662/print/)
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 8723e18f..bf4cb229 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -139,8 +139,8 @@ array.[] 12 #=> nil
# From the end
array[-1] #=> 5
-# With a start and end index
-array[2, 4] #=> [3, 4, 5]
+# With a start index and length
+array[2, 3] #=> [3, 4, 5]
# Or with a range
array[1..3] #=> [2, 3, 4]
diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown
new file mode 100644
index 00000000..e3eed3a6
--- /dev/null
+++ b/zh-cn/bash-cn.html.markdown
@@ -0,0 +1,148 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+translators:
+ - ["Chunyang Xu", "https://github.com/XuChunyang"]
+filename: LearnBash-cn.sh
+lang: zh-cn
+---
+
+Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的默认 shell。
+以下大多数例子可以作为脚本的一部分运行也可直接在 shell 下交互执行。
+
+[更多信息](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/sh
+# 脚本的第一行叫 shebang,用来告知系统如何执行该脚本:
+# 参见: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# 如你所见,注释以 # 开头,shebang 也是注释。
+
+# 显示 “Hello world!”
+echo Hello, world!
+
+# 每一句指令以换行或分号隔开:
+echo 'This is the first line'; echo 'This is the second line'
+
+# 声明一个变量:
+VARIABLE="Some string"
+
+# 下面是错误的做法:
+VARIABLE = "Some string"
+# Bash 会把 VARIABLE 当做一个指令,由于找不到该指令,因此这里会报错。
+
+
+# 使用变量:
+echo $VARIABLE
+echo "$VARIABLE"
+echo '$VARIABLE'
+# 当你分配 (assign) 、导出 (export),或者以其他方式使用变量时,变量名前不加 $。
+# 如果要使用变量的值, 则要加 $。
+# 注意: ' (单引号) 不会展开变量(即会屏蔽掉变量)。
+
+
+# 在变量内部进行字符串代换
+echo ${VARIABLE/Some/A}
+# 会把 VARIABLE 中首次出现的 "some" 替换成 “A”。
+
+# 内置变量:
+# 下面的内置变量很有用
+echo "Last program return value: $?"
+echo "Script's PID: $$"
+echo "Number of arguments: $#"
+echo "Scripts arguments: $@"
+echo "Scripts arguments separeted in different variables: $1 $2..."
+
+# 读取输入:
+echo "What's your name?"
+read NAME # 这里不需要声明新变量
+echo Hello, $NAME!
+
+# 通常的 if 结构看起来像这样:
+# 'man test' 可查看更多的信息
+if [ $NAME -ne $USER ]
+then
+ echo "Your name is you username"
+else
+ echo "Your name isn't you username"
+fi
+
+# 根据上一个指令执行结果决定是否执行下一个指令
+echo "Always executed" || echo "Only executed if first command fail"
+echo "Always executed" && echo "Only executed if first command does NOT fail"
+
+# 表达式的格式如下:
+echo $(( 10 + 5 ))
+
+# 与其他编程语言不同的是,bash 运行时依赖上下文。比如,使用 ls 时,列出当前目录。
+ls
+
+# 指令可以带有选项:
+ls -l # 列出文件和目录的详细信息
+
+# 前一个指令的输出可以当作后一个指令的输入。grep 用来匹配字符串。
+# 用下面的指令列出当前目录下所有的 txt 文件:
+ls -l | grep "\.txt"
+
+# 重定向可以到输出,输入和错误输出。
+python2 hello.py < "input.in"
+python2 hello.py > "output.out"
+python2 hello.py 2> "error.err"
+# > 会覆盖已存在的文件, >> 会以累加的方式输出文件中。
+
+# 一个指令可用 $( ) 嵌套在另一个指令内部:
+# 以下的指令会打印当前目录下的目录和文件总数
+echo "There are $(ls | wc -l) items here."
+
+# Bash 的 case 语句与 Java 和 C++ 中的 switch 语句类似:
+case "$VARIABLE" in
+ # 列出需要匹配的字符串
+ 0) echo "There is a zero.";;
+ 1) echo "There is a one.";;
+ *) echo "It is not null.";;
+esac
+
+# 循环遍历给定的参数序列:
+# 变量$VARIABLE 的值会被打印 3 次。
+# 注意 ` ` 和 $( ) 等价。seq 返回长度为 3 的数组。
+for VARIABLE in `seq 3`
+do
+ echo "$VARIABLE"
+done
+
+# 你也可以使用函数
+# 定义函数:
+function foo ()
+{
+ echo "Arguments work just like script arguments: $@"
+ echo "And: $1 $2..."
+ echo "This is a function"
+ return 0
+}
+
+# 更简单的方法
+bar ()
+{
+ echo "Another way to declare functions!"
+ return 0
+}
+
+# 调用函数
+foo "My name is" $NAME
+
+# 有很多有用的指令需要学习:
+tail -n 10 file.txt
+# 打印 file.txt 的最后 10 行
+head -n 10 file.txt
+# 打印 file.txt 的前 10 行
+sort file.txt
+# 将 file.txt 按行排序
+uniq -d file.txt
+# 报告或忽略重复的行,用选项 -d 打印重复的行
+cut -d ',' -f 1 file.txt
+# 打印每行中 ',' 之前内容
+```
diff --git a/zh-cn/brainfuck-cn.html.markdown b/zh-cn/brainfuck-cn.html.markdown
new file mode 100644
index 00000000..a6f3fa09
--- /dev/null
+++ b/zh-cn/brainfuck-cn.html.markdown
@@ -0,0 +1,70 @@
+---
+language: brainfuck
+lang: zh-cn
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["lyuehh", "https://github.com/lyuehh"]
+---
+
+Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。
+
+```
+除"><+-.,[]"之外的的任何字符都会被忽略 (不包含双引号)。
+
+Brainfuck 包含一个有30,000个单元为0的数组,和
+一个数据指针指向当前的单元。
+
+8个指令如下:
++ : 指针指向的单元的值加1
+- : 指针指向的单元的值减1
+> : 将指针移动到下一个单元(右边的元素)
+< : 将指针移动到上一个单元(左边的元素)
+. : 打印当前单元的内容的ASCII值 (比如 65 = 'A').
+, : 读取一个字符到当前的单元
+[ : 如果当前单元的值是0,则向后调转到对应的]处
+] : 如果当前单元的值不是0,则向前跳转到对应的[处
+
+[ 和 ] 组成了一个while循环。很明显,它们必须配对。
+
+让我们看一些基本的brainfuck 程序。
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+这个程序打印字母'A'。首先,它把 #1 增加到6,使用它来作为循环条件,
+然后,进入循环,将指针移动到 #2 ,将 #2 的值增加到10,然后
+移动回 #1,将单元 #1 的值减1,然后继续。循环共进行了6次。
+
+这时,我们在 #1,它的值为0,#2 的值为60,我们移动到
+#2,将 #2 的内容加上5,然后将 #2 的内容打印出来,65在
+ASCII中表示'A', 所以'A'就会被打印出来。
+
+
+, [ > + < - ] > .
+
+这个程序从用户的输入中读取一个字符,然后把它复制到 #1。
+然后我们开始一个循环,移动到 #2,将 #2 的值加1,再移动回 #1,将 #1
+的值减1,直到 #1的值为0,这样 #2 里就保存了 #1 的旧值,循环结束时我们
+在 #1,这时我们移动到 #2,然后把字符以ASCII打印出来。
+
+而且要记住的一点就是,空格在这里只是为了可读性,你可以将他们写成这样:
+
+,[>+<-]>.
+
+试着思考一下这段程序是干什么的:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+这段程序从输入接收2个参数,然后将他们相乘。
+
+先读取2个输入,然后开始外层循环,以 #1 作为终止条件,然后将指针移动到
+#2,然后开始 #2 的内层循环,将 #3 加1。但是这里有一个小问题,在内层
+循环结束的时候,#2 的值是0了,那么下次执行外层循环的时候,就有问题了。
+为了解决这个问题,我们可以增加 #4 的值,然后把 #4 的值复制到 #2,
+最后结果就保存在 #3 中了。
+```
+好了这就是brainfuck了。也没那么难,是吧?为了好玩,你可以写你自己的
+brainfuck程序,或者用其他语言写一个brainfuck的解释器,解释器非常容易
+实现,但是如果你是一个自虐狂的话,你可以尝试用brainfuck写一个brainfuk的
+解释器。