From 3c1e9a8bc06b654cd812306ed90ca61e9d8bb3eb Mon Sep 17 00:00:00 2001 From: davidsonmizael Date: Thu, 8 Oct 2015 00:33:55 -0300 Subject: Adding bash tutorial in pt-br --- pt-br/bash-pt.html.markdown | 282 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 pt-br/bash-pt.html.markdown (limited to 'pt-br') diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown new file mode 100644 index 00000000..a604e7b8 --- /dev/null +++ b/pt-br/bash-pt.html.markdown @@ -0,0 +1,282 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] +translators: + - ["Davidson Mizael", "https://github.com/davidsonmizael"] +filename: LearnBash-pt_br.sh +lang: pt-br +--- + +Tutorial de shell em português + +Bash é o nome do shell do Unix, que também é distribuido como shell do sistema +operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos +os exemplos abaixo podem fazer parte de um shell script e pode ser executados +diretamente no shell. + +[Leia mais sobre](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# A primeira linha do script é o shebang, que conta para o sistema como executar +# o script: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Como você já deve ter percebido, comentários começam com #. +# Shebang também é um comentário. + +# Exemplo simples de hello world: +echo Hello World! + +# Cada comando começa com uma nova linha, ou após um ponto virgula: +echo 'Essa é a primeira linha'; echo 'Essa é a segunda linha' + +# A declaração de variáveis é mais ou menos assim +Variavel="Alguma string" + +# Mas não assim: +Variavel = "Alguma string" +# Bash interpretará Variavel como um comando e tentará executar e lhe retornar +# um erro porque o comando não pode ser encontrado. + +# Ou assim: +Variavel= 'Alguma string' +# Bash interpretará 'Alguma string' como um comando e tentará executar e lhe retornar +# um erro porque o comando não pode ser encontrado. (Nesse caso a a parte 'Variavel=' +# é vista com uma declaração de variável valida apenas para o escopo do comando 'Uma string'). + +# Usando a variável: +echo $Variavel +echo "$Variavel" +echo '$Variavel' +# Quando você usa a variável em si — declarando valor, exportando, etc — você escreve +# seu nome sem o $. Se você quer usar o valor da variável você deve usar o $. +# Note que ' (aspas simples) não expandirão as variáveis! + +# Substituição de strings em variáveis +echo ${Variavel/Alguma/Uma} +# Isso substituirá a primeira ocorrência de "Alguma" por "Uma" + +# Substring de uma variável +Tamanho=7 +echo ${Variavel:0:Tamanho} +# Isso retornará apenas os 7 primeiros caractéres da variável + +# Valor padrão de uma variável +echo ${Foo:-"ValorPadraoSeFooNaoExistirOuEstiverVazia"} +# Isso funciona para nulo (Foo=) e (Foo=""); zero (Foo=0) retorna 0. +# Note que isso apenas retornar o valor padrão e não mudar o valor da variável. + +# Variáveis internas +# Tem algumas variáveis internas bem uteis, como +echo "O ultimo retorno do programa: $?" +echo "PID do script: $$" +echo "Numero de argumentos passados para o script $#" +echo "Todos os argumentos passados para o script $@" +echo "Os argumentos do script em variáveis diferentes: $1, $2..." + +# Lendo o valor do input: +echo "Qual o seu nome?" +read Nome # Note que nós não precisamos declarar a variável +echo Ola, $Nome + +# Nós temos a estrutura if normal: +# use 'man test' para mais infomações para as condicionais +if [ $Nome -ne $USER ] +then + echo "Seu nome não é o seu username" +else + echo "Seu nome é seu username" +fi + +# Tem também execução condicional +echo "Sempre executado" || echo "Somente executado se o primeiro falhar" +echo "Sempre executado" && "Só executado se o primeiro NÃO falhar" + +# Para usar && e || com o if, você precisa multiplicar os pares de colchetes +if [ $Nome == "Estevao"] && [ $Idade -eq 15] +then + echo "Isso vai rodar se $Nome é igual Estevao E $Idade é 15." +fi + +fi [ $Nome == "Daniela" ] || [ $Nome = "Jose" ] +then + echo "Isso vai rodar se $Nome é Daniela ou Jose." +fi + +# Expressões são denotadas com o seguinte formato +echo $(( 10 + 5)) + +# Diferentemente das outras linguagens de programação, bash é um shell, então ele +# funciona no diretório atual. Você pode listar os arquivos e diretórios no diretório +# atual com o comando ls: +ls + +#Esse comando tem opções que controlam sua execução +ls -l # Lista todo arquivo e diretorio em linhas separadas + +# Os resultados do comando anterior pode ser passado para outro comando como input. +# O comando grep filtra o input com o padrão passado. É assim que listamos apenas +# os arquivos .txt no diretório atual: +ls -l | grep "\.txt" + +# Você pode redirecionar o comando de input e output (stdin, stdout e stderr). +# Lê o stdin até ^EOF$ e sobrescreve hello.py com as linhas entre "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ imprt print_function +import sys +print("#stdout", file=sys.stdout) +print("stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Rode hello.py com várias instruções stdin, stdout e stderr: +python hello.py < "input.in" +python hello.py > "ouput.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# O erro no output sobrescreverá o arquivo se existir, +# se ao invés disso você quiser complementar, use ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Sobrescreve output.out, complemente para error.err e conta as linhas +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +#Roda um comando e imprime o desencriptador (e.g. /dev/fd/123) +# veja: man fd +echo <(echo "#helloworld") + +# Sobrescreve ouput.out com "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out > /dev/null + +# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão) +rm -v output.out error.err output-and-error.log + +# Comando podem ser substituidos por outros comandos usando $( ): +# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual +echo "Existem $(ls | wc -l) itens aqui." + +# O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se +# preferência ao uso do $( ) +echo "Existem `ls | wc -l` itens aqui." + +# Bash usa o comando case que funciona de uma maneira similar ao switch de Java e C++: +case "$Variavel" in + # Lista de parametros para condições que você quer encontrar + 0) echo "Isso é um Zero.";; + 1) echo "Isso é um Um.";; + *) echo "Isso não é null.";; +esac + +# loops for iteragem para quantos argumentos passados: +# O conteudo de $Variavel é exibido três vezes. +for Variavel in {1..3} +do + echo "$Variavel" +done + +# Ou use o loop da "maneira tradicional": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Eles também podem ser usados em arquivos... +# Isso irá rodar o comando 'cat' em arquivo1 e arquivo2 +for Variavel in arquivo1 arquivo2 +do + cat "$Variavel" +done + +# ...ou o output de um comando +# Isso irá usar cat no output do ls. +for Output in $(ls) +do + cat "$Output" +done + +# loop while: +while [ true ] +do + echo "corpo do loop aqui..." + break +done + +# Você também pode usar funções +# Definição: +function foo() { + echo "Argumentos funcionam bem assim como os dos scripts: $@" + echo "E: $1 $2..." + echo "Isso é uma função" + return 0 +} + +# ou simplesmente +bar () { + echo "Outro jeito de declarar funções!" + return 0 +} + +# Chamando sua função +foo "Meu nome é" $Nome + +# Existe um monte de comandos úteis que você deveria aprender: +# exibe as 10 ultimas linhas de arquivo.txt +tail -n 10 arquivo.txt +# exibe as primeiras 10 linhas de arquivo.txt +head -n 10 arquivo.txt +# ordena as linhas de arquivo.txt +sort arquivo.txt +# reporta ou omite as linhas repetidas, com -d você as reporta +uniq -d arquivo.txt +# exibe apenas a primeira coluna após o caráctere ',' +cut -d ',' -f 1 arquivo.txt +# substitui todas as ocorrencias de 'okay' por 'legal' em arquivo.txt (é compativel com regex) +sed -i 's/okay/legal/g' file.txt +# exibe para o stdout todas as linhas do arquivo.txt que encaixam com o regex +# O exemplo exibe linhas que começam com "foo" e terminam com "bar" +grep "^foo.*bar$" arquivo.txt +# passe a opção "-c" para ao invês de imprimir o numero da linha que bate com o regex +grep -c "^foo.*bar$" arquivo.txt +# se você quer literalmente procurar por uma string, +# e não pelo regex, use fgrep (ou grep -F) +fgrep "^foo.*bar$" arquivo.txt + + +# Leia a documentação interna do shell Bash com o comando interno 'help': +help +help help +help for +help return +help source +help . + +# Leia a página principal da documentação com man +apropos bash +man 1 bash +man bash + +# Leia a documentação de informação com info (? para ajuda) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +#Leia a documentação informativa do Bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 1ba31a4a46a34dacdc85780e5b76507336cf456c Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 06:36:53 -0300 Subject: Create a new translate for csharp to pt-br language I started the feature to translate csharp docs to portuguese from Brazil (pt-br). --- pt-br/csharp.html.markdown | 899 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 899 insertions(+) create mode 100644 pt-br/csharp.html.markdown (limited to 'pt-br') diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown new file mode 100644 index 00000000..1f6bea18 --- /dev/null +++ b/pt-br/csharp.html.markdown @@ -0,0 +1,899 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] +filename: LearnCSharp.cs +--- + +C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. + +[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) + +```c# +// Comentário de linha única começa com // +/* +Múltipas linhas é desta forma +*/ +/// +/// Esta é uma documentação comentário XML que pode ser usado para gerar externo +/// documentação ou fornecer ajuda de contexto dentro de um IDE +/// +//public void MethodOrClassOrOtherWithParsableHelp() {} + +// Especificar qual namespace seu código irá usar +// Os namespaces a seguir são padrões do .NET Framework Class Library +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Mas este aqui não é : +using System.Data.Entity; +// Para que consiga utiliza-lo, você precisa adicionar novas referências +// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` + +// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" +// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; +namespace Learning.CSharp +{ + // Cada .cs deve conter uma classe com o mesmo nome do arquivo + // você está autorizado a contrariar isto, mas evite por sua sanidade. + public class AprenderCsharp + { + // Sintaxe Básica - Pule para as CARACTERÍSTICAS INTERESSANTES se você ja usou Java ou C++ antes. + public static void Syntax() + { + // Use Console.WriteLine para apresentar uma linha + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Para apresentar sem incluir uma nova linha, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + /////////////////////////////////////////////////// + // Tpos e Variáveis + // + // Declare uma variável usando + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. + // L is used to denote that this variable value is of type long or ulong + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // or false + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings - ao contrário dos anteriores tipos base, que são todos os tipos de valor, +            // Uma string é um tipo de referência. Ou seja, você pode configurá-lo como nulo + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // Você pode acessar todos os caracteres de string com um indexador: + char charFromString = fooString[1]; // => 'e' + // Strings são imutáveis: você não pode fazer fooString[1] = 'X'; + + // Compare strings com sua atual cultura, ignorando maiúsculas e minúsculas + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatando, baseado no sprintf + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Datas e formatações + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Você pode juntar um string em mais de duas linhas com o símbolo @. Para escapar do " use "" + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Use const ou read-only para fazer uma variável imutável + // os valores da const são calculados durante o tempo de compilação + const int HoursWorkPerWeek = 9001; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + + // Arrays - zero indexado + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Arrays are mutable. + intArray[1] = 1; + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for generics - Check out the cool stuff section + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Others data structures to check out: + // Stack/Queue + // Dictionary (an implementation of a hash map) + // HashSet + // Read-only Collections + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Iterated 100 times, fooWhile 0->99 + fooWhile++; + } + + // Do While Loop + int fooDoWhile = 0; + do + { + // Start iteration 100 times, fooDoWhile 0->99 + if (false) + continue; // skip the current iteration + + fooDoWhile++; + + if (fooDoWhile == 50) + break; // breaks from the loop completely + + } while (fooDoWhile < 100); + + //for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterated 10 times, fooFor 0->9 + } + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. + // (The ToCharArray() could be removed, because a string also implements IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Iterated over all the characters in the string + } + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // Converting Data Types And Typecasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw a FormatException on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Function is boolean + Console.WriteLine(tryInt); // 123 + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + // or + tryInt.ToString(); + + // Casting + // Cast decimal 15 to a int + // and then implicitly cast to long + long x = (int) 15M; + } + + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.Info()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // End main method + + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + // A method that differs only in return type is not unique + public static void MethodSignatures( + ref int maxCount, // Pass by reference + out int count) + { + count = 15; // out param must be assigned before control leaves the method + } + + // GENERICS + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // BY REF AND OUT PARAMETERS + int maxCount = 0, count; // ref params must have value + MethodSignatures(ref maxCount, out count); + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // GENERICS + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a generic above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // ERROR HANDLING - coping with an uncertain world + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // will no longer execute because CreateWithGears throws an exception + string some = ""; + if (true) some = null; + some.ToLower(); // throws a NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // catch all other exceptions + { + throw new ApplicationException("It hit the fan", ex); + // throw; // A rethrow that preserves the callstack + } + // catch { } // catch-all without capturing the Exception + finally + { + // executes after try or catch + } + + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, resources will be released. + // Even if an exception is thrown. + } + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRepository(); + + // execution is delayed, which is great when querying a database + var filter = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + filter = filter.Where(b => b.IsBroken); // no query run + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword private + public string Name { get; set; } + + // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, //you can explicitly set a value to a name + Gitane // 43 + } + // We defined this type inside a Bicycle class, so it is a nested type + // Code outside of this class should reference this type as Bicycle.Brand + + public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + + // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on + [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // need to set the values manually! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } + + // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } + + // Static members belong to the type itself rather then specific object. + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + public static int BicyclesCreated { get; set; } + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool _hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + this.Gear = 1; // you can access members of the object with the keyword this + Cadence = 50; // but you don't always need it + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties (this is the preferred way in C#) + + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } + + // Properties can be auto-implemented + public int FrameSize + { + get; + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set; + } + + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" }; + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Method to display the attribute values of this Object. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Methods can also be static. It can be useful for helper methods + public static bool DidWeCreateEnoughBycles() + { + // Within a static method, we only can reference static class members + return BicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + + + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new InvalidOperationException("You can't change gears on a PennyFarthing"); + } + } + + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // Oops, can't do this! + return penny; + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return result; + } + } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRepository : DbContext + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace +``` + +## Topics Not Covered + + * Attributes + * async/await, yield, pragma directives + * Web Development + * ASP.NET MVC & WebApi (new) + * ASP.NET Web Forms (old) + * WebMatrix (tool) + * Desktop Development + * Windows Presentation Foundation (WPF) (new) + * Winforms (old) + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From da6fc10553b457ef0d8ceb4f8898dfb2c5ddbbdd Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:03:18 -0300 Subject: Include and correct csharp docs Correct the csharp doc en-us language which was written intialize to initialize and include new more translated words to pt-br language. --- pt-br/csharp.html.markdown | 92 +++++++++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 46 deletions(-) (limited to 'pt-br') diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 1f6bea18..deba2263 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -136,76 +136,76 @@ on a new line! ""Wow!"", the masses cried"; const int HoursWorkPerWeek = 9001; /////////////////////////////////////////////////// - // Data Structures + // Estrutura de Dados /////////////////////////////////////////////////// - // Arrays - zero indexado - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; + // Matrizes - zero indexado + // O tamanho do array pode ser decidido ainda na declaração + // O formato para declarar uma matriz é o seguinte: + // [] = new []; int[] intArray = new int[10]; - // Another way to declare & initialize an array + // Outra forma de declarar & inicializar uma matriz int[] y = { 9000, 1000, 1337 }; - // Indexing an array - Accessing an element + // Indexando uma matriz - Acessando um elemento Console.WriteLine("intArray @ 0: " + intArray[0]); - // Arrays are mutable. + // Matriz são alteráveis intArray[1] = 1; - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); + // Listas + // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis + // O formato de declarar uma lista é o seguinte: + // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for generics - Check out the cool stuff section + List z = new List { 9000, 1000, 1337 }; // inicializar + // O <> são para genéricos - Confira está interessante seção do material - // Lists don't default to a value; - // A value must be added before accessing the index + // Lista não possuem valores padrão. + // Um valor deve ser adicionado antes e depois acessado pelo indexador intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // Stack/Queue - // Dictionary (an implementation of a hash map) + // Outras estruturas de dados para conferir: + // Pilha/Fila + // Dicionário (uma implementação de map de hash) // HashSet - // Read-only Collections + // Read-only Coleção // Tuple (.Net 4+) /////////////////////////////////////// - // Operators + // Operadores /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // Shorthand for multiple declarations + int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis - // Arithmetic is straightforward + // Aritmética é clara Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - // Comparison operators - Console.WriteLine("3 == 2? " + (3 == 2)); // => false - Console.WriteLine("3 != 2? " + (3 != 2)); // => true - Console.WriteLine("3 > 2? " + (3 > 2)); // => true - Console.WriteLine("3 < 2? " + (3 < 2)); // => false - Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true - Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + // Comparações de operadores + Console.WriteLine("3 == 2? " + (3 == 2)); // => falso + Console.WriteLine("3 != 2? " + (3 != 2)); // => verdadeiro + Console.WriteLine("3 > 2? " + (3 > 2)); // => verdadeiro + Console.WriteLine("3 < 2? " + (3 < 2)); // => falso + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => verdadeiro + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => verdadeiro - // Bitwise operators! + // Operadores bit a bit (bitwise) /* - ~ Unary bitwise complement + ~ Unário bitwise complemento << Signed left shift >> Signed right shift & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ^ Bitwise exclusivo OR + | Bitwise inclusivo OR */ - // Incrementations + // Incrementações int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); Console.WriteLine(i++); //i = 1. Post-Incrementation @@ -214,11 +214,11 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(--i); //i = 0. Pre-Decrementation /////////////////////////////////////// - // Control Structures + // Estrutura de Controle /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // If statements are c-like + // Declaração if é como a linguagem C int j = 10; if (j == 10) { @@ -233,9 +233,9 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("I also don't"); } - // Ternary operators - // A simple if/else can be written as follows - // ? : + // Operador Ternário + // Um simples if/else pode ser escrito da seguinte forma + // ? : int toCompare = 17; string isTrue = toCompare == 17 ? "True" : "False"; @@ -251,25 +251,25 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - // Start iteration 100 times, fooDoWhile 0->99 + // Inicia a interação 100 vezes, fooDoWhile 0->99 if (false) - continue; // skip the current iteration + continue; // pule a intereção atual para apróxima fooDoWhile++; if (fooDoWhile == 50) - break; // breaks from the loop completely + break; // Interrompe o laço inteiro } while (fooDoWhile < 100); - //for loop structure => for(; ; ) + //estrutura de loop for => for(; ; ) for (int fooFor = 0; fooFor < 10; fooFor++) { - //Iterated 10 times, fooFor 0->9 + //Iterado 10 vezes, fooFor 0->9 } // For Each Loop - // foreach loop structure => foreach( in ) + // Estrutura do foreach => foreach( in ) // The foreach loop loops over any object implementing IEnumerable or IEnumerable // All the collection types (Array, List, Dictionary...) in the .Net framework // implement one or both of these interfaces. -- cgit v1.2.3 From 6a6ac5560f6ec2813bff60b660b21d24bd80d011 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:38:30 -0300 Subject: Included new more words to pt-br --- pt-br/csharp.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'pt-br') diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index deba2263..02098ca8 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -270,20 +270,20 @@ on a new line! ""Wow!"", the masses cried"; // For Each Loop // Estrutura do foreach => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework - // implement one or both of these interfaces. - // (The ToCharArray() could be removed, because a string also implements IEnumerable) + // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable + // Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework + // implementa uma ou mais destas interfaces. + // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable) foreach (char character in "Hello World".ToCharArray()) { //Iterated over all the characters in the string } // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // Um switch funciona com os tipos de dados byte, short, char, e int. + // Isto também funcional com tipos enumeradors (discutidos em Tipos Enum), + // A classe String, and a few special classes that wrap + // tipos primitívos: Character, Byte, Short, and Integer. int month = 3; string monthString; switch (month) -- cgit v1.2.3 From bf12497636d9bcb2e5bd15e88493f2c0f95ce4a7 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:59:41 -0300 Subject: Alter the header file to correct contributor --- pt-br/csharp.html.markdown | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'pt-br') diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 02098ca8..9934afd9 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -1,12 +1,9 @@ --- language: c# +filename: learnruby-ptbr.cs contributors: - - ["Irfan Charania", "https://github.com/irfancharania"] - - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] - - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] - - ["Wouter Van Schandevijl", "http://github.com/laoujin"] -filename: LearnCSharp.cs + - ["Robson Alves", "http://robsonalves.net/"] +lang: pt-br --- C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. -- cgit v1.2.3 From 7b0c8231822472a1e0cdf99149b02aed21a71df0 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 08:11:19 -0300 Subject: Correct the header file name --- pt-br/csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pt-br') diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 9934afd9..547f4817 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -1,6 +1,6 @@ --- language: c# -filename: learnruby-ptbr.cs +filename: csharp-pt.cs contributors: - ["Robson Alves", "http://robsonalves.net/"] lang: pt-br -- cgit v1.2.3 From ac4823b3871010d90604daecc5f06c09859bacc2 Mon Sep 17 00:00:00 2001 From: Bruno Volcov Date: Tue, 13 Oct 2015 11:39:54 -0300 Subject: add pt-br translation to git tags documentation --- pt-br/git-pt.html.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'pt-br') diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index 981da503..ea3570d6 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -5,8 +5,12 @@ lang: pt-br filename: LearnGit.txt 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"] translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Bruno Volcov", "http://github.com/volcov"] --- Git é um sistema distribuido de gestão para código fonte e controle de versões. @@ -84,6 +88,11 @@ Um *branch* é essencialmente uma referência que aponta para o último *commit* efetuado. Na medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. +### *Tag* + +Uma tag é uma marcação em um ponto específico da história. Geralmente as +pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí vai) + ### *HEAD* e *head* (componentes do diretório .git) *HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem @@ -196,6 +205,29 @@ $ git branch -m myBranchName myNewBranchName $ git branch myBranchName --edit-description ``` +### Tag + +Gerencia as *tags* + +```bash +# Listar tags +$ git tag +# Criar uma tag anotada. +# O parâmetro -m define uma mensagem, que é armazenada com a tag. +# Se você não especificar uma mensagem para uma tag anotada, +# o Git vai rodar seu editor de texto para você digitar alguma coisa. +$ git tag -a v2.0 -m 'minha versão 2.0' +# Mostrar informações sobre a tag +# O comando mostra a informação da pessoa que criou a tag, +# a data de quando o commit foi taggeado, +# e a mensagem antes de mostrar a informação do commit. +$ git show v2.0 +# Enviar uma tag para o repositório remoto +$ git push origin v2.0 +# Enviar várias tags para o repositório remoto +$ git push origin --tags +``` + ### checkout Atualiza todos os arquivos no diretório do projeto para que fiquem iguais -- cgit v1.2.3 From 3b5071b9d637de87dba9d3baa2a23ec367bb0f70 Mon Sep 17 00:00:00 2001 From: Felipe Tarijon Date: Wed, 14 Oct 2015 12:57:53 -0300 Subject: Traduzido o artigo de AMD. --- pt-br/amd.html.markdown | 217 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 pt-br/amd.html.markdown (limited to 'pt-br') diff --git a/pt-br/amd.html.markdown b/pt-br/amd.html.markdown new file mode 100644 index 00000000..626481ff --- /dev/null +++ b/pt-br/amd.html.markdown @@ -0,0 +1,217 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +translators: + - ["Felipe Tarijon", "http://nanoincub.com/"] +filename: learnamd.js +--- + +## Começando com AMD + +A API de Definição de Módulos Assíncrona **Asynchronous Module Definition** +especifica um mecanismo para definição de módulos em JavaScript para os quais o +módulo e suas dependências podem ser carregados de forma assíncrona. Isso é +particularmente bem adequado para o ambiente do browser onde o carregamento de +módulos de forma síncrona fica sujeito a problemas de performance, usabilidade, +debugging e problemas de acesso em requisições cross-domain. + +### Conceito básico +```javascript +// O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require` +// e isso é tudo sobre a definição de módulo e consumo: +// `define(id?, dependências?, factory)` define um módulo +// `require(dependências, callback)` importa uma série de dependências e +// consome elas no callback passado como parâmetro. + +// Vamos começar usando o define para definir um novo módulo +// que não tem dependências. Nós vamos fazer isso passando um nome +// e uma função factory para definir: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // O valor retornado da função de factory do módulo é + // o que os outros módulos ou chamadas de require irão + // receber quando requisitarem nosso módulo `awesomeAMD`. + // O valor exportado pode ser qualquer coisa, (construtor) funções, + // objetos, primitives, até mesmo undefined (apesar de que não irão ajudar muito). + return isAMDAwesome; +}); + +// Agora, vamos definir outro módulo que depende do nosso módulo `awesomeAMD`. +// Perceba que existe um argumento adicional definindo nossas dependências do +// módulo agora: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // dependências serão passadas como argumentos da factory + // na ordem que elas forem especificadas + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('Isso é tãaaao loko!'); + } else { + alert('Bem estúpido, né não?'); + } + }; + return tellEveryone; +}); + +// Agora que nós sabemos como usar o define, vamos usar o `require` para +// começar nosso programa. A assinatura do `require` é `(arrayDedependências, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// Para fazer esse tutorial executável, vamos implementar uma versão muito básica +// (não-assíncrona) de AMD bem aqui nesse lugar: +function define(nome, deps, factory){ + // perceba como os módulos sem dependências são manipulados + define[nome] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // primeiro vamos recuperar todas as dependências necessárias + // pela chamada requerida + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // corresponder todas as dependências da função de callback + return callback.apply(null, args); +} +// você pode ver esse código em ação aqui: http://jsfiddle.net/qap949pd/ +``` + +### Uso na vida real com require.js + +Em contraste com o exemplo introdutório, `require.js` (a biblioteca mais popular de AMD) na verdade implementa o **A** do **AMD**, permitindo que você carregue os módulos e suas +dependências via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/algumaClasse'], function(AlgumaClasse){ + // o callback é deferido até que a dependencia seja carregada + var coisa = new AlgumaClasse(); +}); +console.log('Então aqui estamos nós, esperando!'); // isso vai rodar primeiro +``` + +Por convenção, você geralmente guarda um módulo em um arquivo. `require.js` pode resolver nome de módulos baseado no caminho das pastas, então você não precisa nomear os seus módulos, mas sim simplesmente referenciar eles usando sua origem. No exemplo `algumaClasse` é adotado a pasta `modules`, relativa a configuração da sua `baseUrl`: + +* app/ + * main.js + * modules/ + * algumaClasse.js + * algunsHelpers.js + * ... + * daos/ + * coisas.js + * ... + +Isso significa que nós podemos definir `algumaClasse` sem especificar o id de um módulo: + +```javascript +/* arquivo: app/modules/algumaClasse.js */ +define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){ + // definição de módulo, claro, irá acontecer também de forma assíncrona + function AlgumaClasse(){ + this.metodo = function(){/**/}; + // ... + } + return AlgumaClasse; +}); +``` +Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize +`requirejs.config(configObj)` em seu `main.js`: + +```javascript +/* arquivo: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // você pode também carregar módulos de outros locais + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coolLib, helpers){ + // um arquivo `main` precisa chamar o require pelo menos uma vez, + // caso contrário, o código jamais rodará + coolLib.facaAlgoDoidoCom(helpers.transform($('#foo'))); +}); +``` +Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: + +```html + + + + Umas 100 tags de script? Nunca mais! + + + + + +``` + +### Otimizando um projeto inteiro utilizando r.js + +Muitas pessoas preferem usar AMD para sanar a organização do código durante o desenvolvimento, mas continuam querendo colocar um único arquivo de script em produção ao invés de realizarem centenas de requisições XHRs no carregamento da página. + +`require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos. + +Instale-o utilizando `npm`: +```shell +$ npm install requirejs -g +``` + +Agora você pode alimentá-lo com um arquivo de configuração: +```shell +$ r.js -o app.build.js +``` + +Para o nosso exemplo acima a configuração pode ser essa: +```javascript +/* file : app.build.js */ +({ + name : 'main', // nome do ponto de acesso + out : 'main-built.js', // nome o arquivo para gravar a saída + baseUrl : 'app', + paths : { + // `empty:` fala para o r.js que isso ainda deve ser baixado da CDN, usando + // o local especificado no `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`: +```html + +``` + +Uma incrível e detalhada visão geral [de build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponível no repositório do GitHub. + +### Tópicos não abordados nesse tutorial +* [Plugins de carregamento / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style carregamento e exportação](http://requirejs.org/docs/commonjs.html) +* [Configuração avançada](http://requirejs.org/docs/api.html#config) +* [Shim configuration (carregando módulos sem AMD)](http://requirejs.org/docs/api.html#config-shim) +* [Carregando e otimizando CSS com require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Usando almond.js para builds](https://github.com/jrburke/almond) + +### Outras leituras: + +* [Especificação oficial](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Por quê AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementações: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) \ No newline at end of file -- cgit v1.2.3 From adefaa5fdf1de01dc8318a69d440bfc71a7629c7 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 13:07:17 -0300 Subject: Ruby Ecosystem translation to portuguese The whole article has been translated. --- pt-br/ruby-ecosystem-pt.html.markdown | 147 ++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 pt-br/ruby-ecosystem-pt.html.markdown (limited to 'pt-br') diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown new file mode 100644 index 00000000..0298f8a1 --- /dev/null +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -0,0 +1,147 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Claudson Martins", "http://github.com/claudsonm"] +lang: pt-br + +--- + +Pessoas utilizando Ruby geralmente têm uma forma de instalar diferentes versões +do Ruby, gerenciar seus pacotes (ou gemas) e as dependências das gemas. + +## Gerenciadores Ruby + +Algumas plataformas possuem o Ruby pré-instalado ou disponível como um pacote. +A maioria dos "rubistas" não os usam, e se usam, é apenas para inicializar outro +instalador ou implementação do Ruby. Ao invés disso, rubistas tendêm a instalar +um gerenciador para instalar e alternar entre diversas versões do Ruby e seus +ambientes de projeto. + +Abaixo estão os gerenciadores Ruby mais populares: + +* [RVM](https://rvm.io/) - Instala e alterna entre os rubies. RVM também possui + o conceito de gemsets para isolar os ambientes dos projetos completamente. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Apenas instala os + rubies. Use este para um melhor controle sobre a instalação de seus rubies. +* [rbenv](https://github.com/sstephenson/rbenv) - Apenas alterna entre os rubies. + Usado com o ruby-build. Use este para um controle mais preciso sobre a forma + como os rubies são carregados. +* [chruby](https://github.com/postmodern/chruby) - Apenas alterna entre os rubies. + A concepção é bastante similar ao rbenv. Sem grandes opções sobre como os + rubies são instalados. + +## Versões do Ruby + +O Ruby foi criado por Yukihiro "Matz" Matsumoto, que continua a ser uma espécie +de [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), embora +isso esteja mudando recentemente. Como resultado, a implementação de referência +do Ruby é chamada de MRI (Matz' Reference Implementation), e quando você ver uma +versão do Ruby, ela está se referindo a versão de lançamento do MRI. + +As três principais versões do Ruby em uso são: + +* 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e + suporte a frameworks 2.0.0. +* 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas + atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - O Ruby 1.8.7 foi + [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +A diferença entre a versão 1.8.7 para 1.9.x é muito maior do que a da 1.9.3 para +a 2.0.0. Por exemplo, a série 1.9 introduziu encodes e uma VM bytecode. Ainda +existem projetos na versão 1.8.7, mas eles estão tornando-se uma pequena minoria +pois a maioria da comunidade migrou para a versão, pelo menos, 1.9.2 ou 1.9.3. + +## Implementações Ruby + +O ecossistema Ruby conta com várias diferentes implementações do Ruby, cada uma +com pontos fortes e estados de compatibilidade. Para ser claro, as diferentes +implementações são escritas em diferentes linguagens, mas *todas elas são Ruby*. +Cada implementação possui hooks especiais e recursos extra, mas todas elas +executam arquivos normais do Ruby tranquilamente. Por exemplo, JRuby é escrita +em Java, mas você não precisa saber Java para utilizá-la. + +Muito maduras/compatíveis: + +* [MRI](https://github.com/ruby/ruby) - Escrita em C, esta é a implementação de + referência do Ruby. Por definição, é 100% compatível (consigo mesma). Todos os + outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). +* [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação + robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a + interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projets, e + linguagens existentes. +* [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com + uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação + em Ruby, ela expõe muitos recursos da VM na rubyland. + +Medianamente maduras/compatíveis: + +* [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma + máquina virtual Smalltalk. Smalltalk possui algumas ferramentas impressionantes, + e este projeto tenta trazer isso para o desenvolvimento Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS. + +Pouco maduras/compatíveis: + +* [Topaz](http://topazruby.com/) - Escrita em RPython (usando o conjunto de + ferramentas PyPy), Topaz é bastante jovem e ainda não compatível. Parece ser + promissora como uma implementação Ruby de alta performance. +* [IronRuby](http://ironruby.net/) - Escrita em C# visando a plataforma .NET, + o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio. + +Implementações Ruby podem ter seus próprios números de lançamento, mas elas +sempre focam uma versão específica da MRI para compatibilidade. Diversas +implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por +exemplo) para especificar qual versão da MRI focar. + +## RubySpec + +A maioria das implementações Ruby dependem fortemente da [RubySpec](http://rubyspec.org/). +Ruby não tem uma especificação oficial, então a comunidade tem escrito +especificações executáveis em Ruby para testar a compatibilidade de suas +implementações com a MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) é um gerenciador de pacotes para Ruby mantido +pela comunidade. RubyGems vem com o Ruby, portanto não é preciso baixar separadamente. + +Os pacotes do Ruby são chamados de "gemas", e elas podem ser hospedadas pela +comunidade em RubyGems.org. Cada gema contém seu código-fonte e alguns metadados, +incluindo coisas como versão, dependências, autor(es) e licença(s). + +## Bundler + +[Bundler](http://bundler.io/) é um gerenciador de dependências para as gemas. +Ele usa a Gemfile de um projeto para encontrar dependências, e então busca as +dependências dessas dependências de forma recursiva. Ele faz isso até que todas +as dependências sejam resolvidas e baixadas, ou para se encontrar um conflito. + +O Bundler gerará um erro se encontrar um conflito entre dependências. Por exemplo, +se a gema A requer versão 3 ou maior que a gema Z, mas a gema B requer a versão +2, o Bundler irá notificá-lo que há um conflito. Isso se torna extremamente útil +quando diversas gemas começam a referenciar outras gemas (que referem-se a outras +gemas), o que pode formar uma grande cascata de dependências a serem resolvidas. + +# Testes + +Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio +framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x). +Existem diversas bibliotecas de teste com diferentes objetivos. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) + - Framework de testes "Unit-style" para o Ruby 1.8 (built-in) +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) + - Framework de testes para o Ruby 1.9/2.0 (built-in) +* [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade +* [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados + +## Seja Legal + +A comunidade Ruby orgulha-se de ser uma comunidade aberta, diversa, e receptiva. +O próprio Matz é extremamente amigável, e a generosidade dos rubistas em geral +é incrível. -- cgit v1.2.3 From 09ceb868bc045d81fc4cf91b77708bb1f9671e50 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 13:16:49 -0300 Subject: Test list fix and some other minor improvements --- pt-br/ruby-ecosystem-pt.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'pt-br') diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown index 0298f8a1..da4f6f37 100644 --- a/pt-br/ruby-ecosystem-pt.html.markdown +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -47,7 +47,7 @@ As três principais versões do Ruby em uso são: * 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e suporte a frameworks 2.0.0. * 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas - atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) + atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/). * 1.8.7 - O Ruby 1.8.7 foi [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). @@ -72,7 +72,7 @@ Muito maduras/compatíveis: outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). * [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a - interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projets, e + interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projetos, e linguagens existentes. * [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação @@ -81,7 +81,7 @@ Muito maduras/compatíveis: Medianamente maduras/compatíveis: * [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma - máquina virtual Smalltalk. Smalltalk possui algumas ferramentas impressionantes, + máquina virtual Smalltalk. O Smalltalk possui algumas ferramentas impressionantes, e este projeto tenta trazer isso para o desenvolvimento Ruby. * [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS. @@ -94,7 +94,7 @@ Pouco maduras/compatíveis: o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio. Implementações Ruby podem ter seus próprios números de lançamento, mas elas -sempre focam uma versão específica da MRI para compatibilidade. Diversas +sempre focam em uma versão específica da MRI para compatibilidade. Diversas implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por exemplo) para especificar qual versão da MRI focar. @@ -133,10 +133,10 @@ Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x). Existem diversas bibliotecas de teste com diferentes objetivos. -* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - - Framework de testes "Unit-style" para o Ruby 1.8 (built-in) -* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - - Framework de testes para o Ruby 1.9/2.0 (built-in) +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - + Framework de testes "Unit-style" para o Ruby 1.8 (built-in) +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - + Framework de testes para o Ruby 1.9/2.0 (built-in) * [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade * [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados -- cgit v1.2.3 From 2f7c68978bd42cc863985a451d018e20f9711fb8 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:45:03 +0200 Subject: [yaml/pt-br] YAML translation to Brazilian Portuguese --- pt-br/yaml-pt.html.markdown | 139 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 pt-br/yaml-pt.html.markdown (limited to 'pt-br') diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown new file mode 100644 index 00000000..a7414f2d --- /dev/null +++ b/pt-br/yaml-pt.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] +--- + +YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e +legível por seres humanos. + +É um estrito subconjunto de JSON, com a adição de sintaticamente +novas linhas e recuo significativos, como Python. Ao contrário de Python, no entanto, +YAML não permite caracteres de tabulação literais em tudo. + +```yaml +# Commentários em YAML são como este. + +################### +# TIPOS ESCALARES # +################### + +# Nosso objeto raiz (que continua por todo o documento) será um mapa, +# o que equivale a um dicionário, hash ou objeto em outras linguagens. +chave: valor +outra_chave: Outro valor vai aqui. +u_valor_numerico: 100 +notacao_cientifica: 1e+12 +boleano: true +valor_nulo: null +chave com espaco: valor +# Observe que strings não precisam de aspas. Porém, elas podem ter. +porem: "Uma string, entre aspas." +"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave." + +# Seqüências de várias linhas podem ser escritos como um 'bloco literal' (utilizando |), +# ou em um 'bloco compacto' (utilizando '>'). +bloco_literal: | + Todo esse bloco de texto será o valor da chave 'bloco_literal', + preservando a quebra de com linhas. + + O literal continua até de-dented, e a primeira identação é + removida. + + Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações - + estas linhas serão identadas com 4 espaços. +estilo_compacto: > + Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta + vez, todas as novas linhas serão substituídas com espaço simples. + + Linhas em branco, como acima, são convertidas em um carater de nova linha. + + Linhas 'mais-indentadas' mantém suas novas linhas também - + este texto irá aparecer em duas linhas. + +#################### +# TIPOS DE COLEÇÃO # +#################### + +# Texto aninhado é conseguido através de identação. +um_mapa_aninhado: + chave: valor + outra_chave: Outro valor + outro_mapa_aninhado: + ola: ola + +# Mapas não tem que ter chaves com string. +0.25: uma chave com valor flutuante + +# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave. +? | + Esta é uma chave + que tem várias linhas +: e este é o seu valor + +# também permite tipos de coleção de chaves, mas muitas linguagens de programação +# vão reclamar. + +# Sequências (equivalente a listas ou arrays) semelhante à isso: +uma_sequencia: + - Item 1 + - Item 2 + - 0.5 # sequencias podem conter tipos diferentes. + - Item 4 + - chave: valor + outra_chave: outro_valor + - + - Esta é uma sequencia + - dentro de outra sequencia + +# Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e +# sequencias: +mapa_json: {"chave": "valor"} +json_seq: [3, 2, 1, "decolar"] + +########################## +# RECURSOS EXTRA DO YAML # +########################## + +# YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique +# conteúdo em seu documento. Ambas estas chaves terão o mesmo valor: +conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves. +outra_ancora: * nome_ancora + +# YAML também tem tags, que você pode usar para declarar explicitamente os tipos. +string_explicita: !! str 0,5 +# Alguns analisadores implementam tags específicas de linguagem, como este para Python de +# Tipo de número complexo. +numero_complexo_em_python: !! python / complex 1 + 2j + +#################### +# YAML TIPOS EXTRA # +#################### + +# Strings e números não são os únicos que escalares YAML pode entender. +# Data e 'data e hora' literais no formato ISO também são analisados. +datetime: 2001-12-15T02: 59: 43.1Z +datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5 +Data: 2002/12/14 + +# A tag !!binary indica que a string é na verdade um base64-encoded (condificado) +# representação de um blob binário. +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML também tem um tipo de conjunto, o que se parece com isso: +set: + ? item1 + ? item2 + ? item3 + +# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: +set2: + item1: null + item2: null + item3: null +``` -- cgit v1.2.3 From 251ffdf894a697ec58a59d620956f4cca7172810 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:48:17 +0200 Subject: [yaml/pt-br] fixing contributors and add translators --- pt-br/yaml-pt.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'pt-br') diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index a7414f2d..93fca3f7 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -2,6 +2,8 @@ language: yaml filename: learnyaml.yaml contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] --- @@ -133,7 +135,7 @@ set: # Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: set2: - item1: null - item2: null - item3: null + item1: nulo + item2: nulo + item3: nulo ``` -- cgit v1.2.3 From 400b1a4b830b6d2cae677d916781dc88a45af027 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:58:47 +0200 Subject: [yaml/pt-br] fixing header --- pt-br/yaml-pt.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'pt-br') diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 93fca3f7..341ae675 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -1,10 +1,11 @@ --- language: yaml -filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] +filename: learnyaml-pt.yaml +lang: pt-br --- YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e -- cgit v1.2.3 From db8d8558809e7a6501f2f91ad3d6b12f16cf369f Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:17:44 -0300 Subject: Paren translation to brazillian portuguese --- pt-br/paren-pt.html.markdown | 196 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 pt-br/paren-pt.html.markdown (limited to 'pt-br') diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown new file mode 100644 index 00000000..bd0c95e7 --- /dev/null +++ b/pt-br/paren-pt.html.markdown @@ -0,0 +1,196 @@ +--- +language: Paren +filename: learnparen-pt.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br +--- + +[Paren](https://bitbucket.org/ktg/paren) é um dialeto do Lisp. É projetado para ser uma linguagem embutida. + +Alguns exemplos foram retirados de . + +```scheme +;;; Comentários +# Comentários + +;; Comentários de única linha começam com um ponto e vírgula ou cerquilha + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Tipos de Dados Primitivos e Operadores +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Números +123 ; inteiro +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : inteiro +(double 123) ; => 123 : double + +;; O uso de funções é feito da seguinte maneira (f x y z ...) +;; onde f é uma função e x, y, z, ... são os operandos +;; Se você quiser criar uma lista literal de dados, use (quote) para impedir +;; que sejam interpretados +(quote (+ 1 2)) ; => (+ 1 2) +;; Agora, algumas operações aritméticas +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Booleanos +true ; para verdadeiro +false ; para falso +(! true) ; => falso +(&& true false (prn "não chega aqui")) ; => falso +(|| false true (prn "não chega aqui")) ; => verdadeiro + +;;; Caracteres são inteiros. +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Strings são arrays de caracteres de tamanho fixo. +"Olá, mundo!" +"Sebastião \"Tim\" Maia" ; Contra-barra é um caractere de escape +"Foo\tbar\r\n" ; Inclui os escapes da linguagem C: \t \r \n + +;; Strings podem ser concatenadas também! +(strcat "Olá " "mundo!") ; => "Olá mundo!" + +;; Uma string pode ser tratada como uma lista de caracteres +(char-at "Abacaxi" 0) ; => 65 + +;; A impressão é muito fácil +(pr "Isso é" "Paren. ") (prn "Prazer em conhecê-lo!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variáveis +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Você pode criar ou definir uma variável usando (set) +;; o nome de uma variável pode user qualquer caracter, exceto: ();#" +(set alguma-variavel 5) ; => 5 +alguma-variavel ; => 5 + +;; Acessar uma variável ainda não atribuída gera uma exceção +; x ; => Unknown variable: x : nil + +;; Ligações locais: Utiliza cálculo lambda! +;; 'a' e 'b' estão ligados a '1' e '2' apenas dentro de (fn ...) +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Coleções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Listas + +;; Listas são estruturas de dados semelhantes a vetores. (A classe de comportamento é O(1).) +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; 'list' é uma variação conveniente para construir listas +(list 1 2 3) ; => (1 2 3) +;; Um quote também pode ser usado para uma lista de valores literais +(quote (+ 1 2)) ; => (+ 1 2) + +;; Você ainda pode utilizar 'cons' para adicionar um item ao início da lista +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Listas são um tipo muito básico, portanto existe *enorme* funcionalidade +;; para elas, veja alguns exemplos: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use 'fn' para criar funções. +;; Uma função sempre retorna o valor de sua última expressão +(fn () "Olá Mundo") ; => (fn () Olá Mundo) : fn + +;; Use parênteses para chamar todas as funções, incluindo uma expressão lambda +((fn () "Olá Mundo")) ; => "Olá Mundo" + +;; Atribuir uma função a uma variável +(set ola-mundo (fn () "Olá Mundo")) +(ola-mundo) ; => "Olá Mundo" + +;; Você pode encurtar isso utilizando a definição de função açúcar sintático: +(defn ola-mundo2 () "Olá Mundo") + +;; Os () acima é a lista de argumentos para a função +(set ola + (fn (nome) + (strcat "Olá " nome))) +(ola "Steve") ; => "Olá Steve" + +;; ... ou equivalente, usando a definição açucarada: +(defn ola2 (nome) + (strcat "Olá " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Igualdade +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Para números utilize '==' +(== 3 3.0) ; => verdadeiro +(== 2 1) ; => falso + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Controle de Fluxo +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Condicionais + +(if true ; Testa a expressão + "isso é verdade" ; Então expressão + "isso é falso") ; Senão expressão +; => "isso é verdade" + +;;; Laços de Repetição + +;; O laço for é para número +;; (for SÍMBOLO INÍCIO FIM SALTO EXPRESSÃO ..) +(for i 0 10 2 (pr i "")) ; => Imprime 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => Imprime 0 2.5 5 7.5 10 + +;; Laço while +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => Imprime 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutação +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use 'set' para atribuir um novo valor a uma variável ou local +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros lhe permitem estender a sintaxe da linguagem. +;; Os macros no Paren são fáceis. +;; Na verdade, (defn) é um macro. +(defmacro setfn (nome ...) (set nome (fn ...))) +(defmacro defn (nome ...) (def nome (fn ...))) + +;; Vamos adicionar uma notação infixa +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Macros não são higiênicos, você pode sobrescrever as variáveis já existentes! +;; Eles são transformações de códigos. +``` -- cgit v1.2.3 From de34d88d94864ecf77151a866b512045ce196d74 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:26:25 -0300 Subject: Translation revision improvements --- pt-br/paren-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pt-br') diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown index bd0c95e7..464a69d2 100644 --- a/pt-br/paren-pt.html.markdown +++ b/pt-br/paren-pt.html.markdown @@ -72,7 +72,7 @@ false ; para falso ;; 2. Variáveis ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Você pode criar ou definir uma variável usando (set) -;; o nome de uma variável pode user qualquer caracter, exceto: ();#" +;; o nome de uma variável pode conter qualquer caracter, exceto: ();#" (set alguma-variavel 5) ; => 5 alguma-variavel ; => 5 -- cgit v1.2.3 From 401093269d1a5b0db14c54f2e355ff3461b43325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Tue, 20 Oct 2015 23:53:25 -0200 Subject: Pogoscript to pt-br Partial translation to pt-br --- pt-br/pogo.html.markdown | 202 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 pt-br/pogo.html.markdown (limited to 'pt-br') diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown new file mode 100644 index 00000000..80972c98 --- /dev/null +++ b/pt-br/pogo.html.markdown @@ -0,0 +1,202 @@ +--- +language: pogoscript +contributors: + - ["Tim Macfarlane", "http://github.com/refractalize"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] +filename: learnPogo.pogo +--- + +Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents +e que compila para linguagem Javascript padrão. + +``` javascript +// definindo uma variável +water temperature = 24 + +// reatribuindo o valor de uma variável após a sua definição +water temperature := 26 + +// funções permitem que seus parâmetros sejam colocados em qualquer lugar +temperature at (a) altitude = 32 - a / 100 + +// funções longas são apenas indentadas +temperature at (a) altitude := + if (a < 0) + water temperature + else + 32 - a / 100 + +// chamada de uma função +current temperature = temperature at 3200 altitude + +// essa função cria um novo objeto com métodos +position (x, y) = { + x = x + y = y + + distance from position (p) = + dx = self.x - p.x + dy = self.y - p.y + Math.sqrt (dx * dx + dy * dy) +} + +// `self` é similiar ao `this` no Javascript, com exceção de que `self` não +// é redefinido em cada nova função + +// chamada de métodos +position (7, 2).distance from position (position (5, 1)) + +// assim como no Javascript, objetos também são hashes +position.'x' == position.x == position.('x') + +// arrays +positions = [ + position (1, 1) + position (1, 2) + position (1, 3) +] + +// indexando um array +positions.0.y + +n = 2 +positions.(n).y + +// strings +poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. + Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. + Put on my shirt and took it off in the sun walking the path to lunch. + A dandelion seed floats above the marsh grass with the mosquitos. + At 4 A.M. the two middleaged men sleeping together holding hands. + In the half-light of dawn a few birds warble under the Pleiades. + Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep + cheep cheep.' + +// texto de Allen Ginsburg + +// interpolação +outlook = 'amazing!' +console.log "the weather tomorrow is going to be #(outlook)" + +// expressões regulares +r/(\d+)m/i +r/(\d+) degrees/mg + +// operadores +true @and true +false @or true +@not false +2 < 4 +2 >= 2 +2 > 1 + +// todos do Javascript também são suportados + +// definindo seu próprio operador +(p1) plus (p2) = + position (p1.x + p2.x, p1.y + p2.y) + +// `plus` pode ser usado com um operador +position (1, 1) @plus position (0, 2) +// ou como uma função +(position (1, 1)) plus (position (0, 2)) + +// retorno explícito +(x) times (y) = return (x * y) + +// new +now = @new Date () + +// funções podem receber argumentos opcionais +spark (position, color: 'black', velocity: {x = 0, y = 0}) = { + color = color + position = position + velocity = velocity +} + +red = spark (position 1 1, color: 'red') +fast black = spark (position 1 1, velocity: {x = 10, y = 0}) + +// functions can unsplat arguments too +log (messages, ...) = + console.log (messages, ...) + +// blocks are functions passed to other functions. +// This block takes two parameters, `spark` and `c`, +// the body of the block is the indented code after the +// function call + +render each @(spark) into canvas context @(c) + ctx.begin path () + ctx.stroke style = spark.color + ctx.arc ( + spark.position.x + canvas.width / 2 + spark.position.y + 3 + 0 + Math.PI * 2 + ) + ctx.stroke () + +// asynchronous calls + +// JavaScript both in the browser and on the server (with Node.js) +// makes heavy use of asynchronous IO with callbacks. Async IO is +// amazing for performance and making concurrency simple but it +// quickly gets complicated. +// Pogoscript has a few things to make async IO much much easier + +// Node.js includes the `fs` module for accessing the file system. +// Let's list the contents of a directory + +fs = require 'fs' +directory listing = fs.readdir! '.' + +// `fs.readdir()` is an asynchronous function, so we can call it +// using the `!` operator. The `!` operator allows you to call +// async functions with the same syntax and largely the same +// semantics as normal synchronous functions. Pogoscript rewrites +// it so that all subsequent code is placed in the callback function +// to `fs.readdir()`. + +// to catch asynchronous errors while calling asynchronous functions + +try + another directory listing = fs.readdir! 'a-missing-dir' +catch (ex) + console.log (ex) + +// in fact, if you don't use `try catch`, it will raise the error up the +// stack to the outer-most `try catch` or to the event loop, as you'd expect +// with non-async exceptions + +// all the other control structures work with asynchronous calls too +// here's `if else` +config = + if (fs.stat! 'config.json'.is file ()) + JSON.parse (fs.read file! 'config.json' 'utf-8') + else + { + color: 'red' + } + +// to run two asynchronous calls concurrently, use the `?` operator. +// The `?` operator returns a *future* which can be executed to +// wait for and obtain the result, again using the `!` operator + +// we don't wait for either of these calls to finish +a = fs.stat? 'a.txt' +b = fs.stat? 'b.txt' + +// now we wait for the calls to finish and print the results +console.log "size of a.txt is #(a!.size)" +console.log "size of b.txt is #(b!.size)" + +// futures in Pogoscript are analogous to Promises +``` + +That's it. + +Download [Node.js](http://nodejs.org/) and `npm install pogo`. + +There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), including a [cheat sheet](http://pogoscript.org/cheatsheet.html), a [guide](http://pogoscript.org/guide/), and how [Pogoscript translates to Javascript](http://featurist.github.io/pogo-examples/). Get in touch on the [google group](http://groups.google.com/group/pogoscript) if you have questions! -- cgit v1.2.3 From f0daae643482918fce3c75b012087dc19f883d25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Wed, 21 Oct 2015 23:30:42 -0200 Subject: translation to pt-br translation to pt-br completed --- pt-br/pogo.html.markdown | 76 ++++++++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 38 deletions(-) (limited to 'pt-br') diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown index 80972c98..5dc81ec0 100644 --- a/pt-br/pogo.html.markdown +++ b/pt-br/pogo.html.markdown @@ -3,7 +3,8 @@ language: pogoscript contributors: - ["Tim Macfarlane", "http://github.com/refractalize"] - ["Cássio Böck", "https://github.com/cassiobsilva"] -filename: learnPogo.pogo +filename: learnPogo-pt-br.pogo +lang: pt-br --- Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents @@ -26,7 +27,7 @@ temperature at (a) altitude := else 32 - a / 100 -// chamada de uma função +// declarando uma função current temperature = temperature at 3200 altitude // essa função cria um novo objeto com métodos @@ -43,7 +44,7 @@ position (x, y) = { // `self` é similiar ao `this` no Javascript, com exceção de que `self` não // é redefinido em cada nova função -// chamada de métodos +// declaração de métodos position (7, 2).distance from position (position (5, 1)) // assim como no Javascript, objetos também são hashes @@ -117,14 +118,13 @@ spark (position, color: 'black', velocity: {x = 0, y = 0}) = { red = spark (position 1 1, color: 'red') fast black = spark (position 1 1, velocity: {x = 10, y = 0}) -// functions can unsplat arguments too +// funções também podem ser utilizadas para realizar o "unsplat" de argumentos log (messages, ...) = console.log (messages, ...) -// blocks are functions passed to other functions. -// This block takes two parameters, `spark` and `c`, -// the body of the block is the indented code after the -// function call +// blocos são funções passadas para outras funções. +// Este bloco recebe dois parâmetros, `spark` e `c`, +// o corpo do bloco é o código indentado após a declaração da função render each @(spark) into canvas context @(c) ctx.begin path () @@ -138,40 +138,40 @@ render each @(spark) into canvas context @(c) ) ctx.stroke () -// asynchronous calls +// chamadas assíncronas -// JavaScript both in the browser and on the server (with Node.js) -// makes heavy use of asynchronous IO with callbacks. Async IO is -// amazing for performance and making concurrency simple but it -// quickly gets complicated. -// Pogoscript has a few things to make async IO much much easier +// O Javascript, tanto no navegador quanto no servidor (através do Node.js) +// realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com +// chamadas de retorno. E/S assíncrona é maravilhosa para a performance e +// torna a concorrência simples, porém pode rapidamente se tornar algo complicado. +// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono mosquitos +// mais fácil -// Node.js includes the `fs` module for accessing the file system. -// Let's list the contents of a directory +// O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. +// Vamos listar o conteúdo de um diretório fs = require 'fs' directory listing = fs.readdir! '.' -// `fs.readdir()` is an asynchronous function, so we can call it -// using the `!` operator. The `!` operator allows you to call -// async functions with the same syntax and largely the same -// semantics as normal synchronous functions. Pogoscript rewrites -// it so that all subsequent code is placed in the callback function -// to `fs.readdir()`. +// `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o +// operador `!`. O operador `!` permite que você chame funções assíncronas +// com a mesma sintaxe e praticamente a mesma semântica do que as demais +// funções síncronas. O Pogoscript reescreve a função para que todo código +// inserido após o operador seja inserido em uma função de callback para o +// `fs.readdir()`. -// to catch asynchronous errors while calling asynchronous functions +// para se obter erros ao utilizar funções assíncronas try another directory listing = fs.readdir! 'a-missing-dir' catch (ex) console.log (ex) -// in fact, if you don't use `try catch`, it will raise the error up the -// stack to the outer-most `try catch` or to the event loop, as you'd expect -// with non-async exceptions +// na verdade, se você não usar o `try catch`, o erro será passado para o +// `try catch` mais externo do evento, assim como é feito nas exceções síncronas -// all the other control structures work with asynchronous calls too -// here's `if else` +// todo o controle de estrutura funciona com chamadas assíncronas também +// aqui um exemplo de `if else` config = if (fs.stat! 'config.json'.is file ()) JSON.parse (fs.read file! 'config.json' 'utf-8') @@ -180,23 +180,23 @@ config = color: 'red' } -// to run two asynchronous calls concurrently, use the `?` operator. -// The `?` operator returns a *future* which can be executed to -// wait for and obtain the result, again using the `!` operator +// para executar duas chamadas assíncronas de forma concorrente, use o +// operador `?`. +// O operador `?` retorna um *future* que pode ser executado aguardando +// o resultado, novamente utilizando o operador `o` -// we don't wait for either of these calls to finish +// nós não esperamos nenhuma dessas chamadas serem concluídas a = fs.stat? 'a.txt' b = fs.stat? 'b.txt' -// now we wait for the calls to finish and print the results +// agora nos aguardamos o término das chamadas e escrevemos os resultados console.log "size of a.txt is #(a!.size)" console.log "size of b.txt is #(b!.size)" -// futures in Pogoscript are analogous to Promises +// no Pogoscript, futures são semelhantes a Promises ``` +E encerramos por aqui. -That's it. +Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. -Download [Node.js](http://nodejs.org/) and `npm install pogo`. - -There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), including a [cheat sheet](http://pogoscript.org/cheatsheet.html), a [guide](http://pogoscript.org/guide/), and how [Pogoscript translates to Javascript](http://featurist.github.io/pogo-examples/). Get in touch on the [google group](http://groups.google.com/group/pogoscript) if you have questions! +Há bastante documentação em [http://pogoscript.org/](http://pogoscript.org/), incluindo um material para [consulta rápida](http://pogoscript.org/cheatsheet.html), um [guia](http://pogoscript.org/guide/), e como o [Pogoscript é traduzido para o Javascript](http://featurist.github.io/pogo-examples/). Entre em contato através do [grupo do Google](http://groups.google.com/group/pogoscript) se você possui dúvidas! -- cgit v1.2.3 From 4c9f38665d291e4abe2c7d57e633f5aed9eb72ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Thu, 22 Oct 2015 00:35:27 -0200 Subject: grammar fixes Portuguese changes to a better text understanding --- pt-br/pogo.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'pt-br') diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown index 5dc81ec0..124b32f7 100644 --- a/pt-br/pogo.html.markdown +++ b/pt-br/pogo.html.markdown @@ -41,7 +41,7 @@ position (x, y) = { Math.sqrt (dx * dx + dy * dy) } -// `self` é similiar ao `this` no Javascript, com exceção de que `self` não +// `self` é similiar ao `this` do Javascript, com exceção de que `self` não // é redefinido em cada nova função // declaração de métodos @@ -91,7 +91,7 @@ false @or true 2 >= 2 2 > 1 -// todos do Javascript também são suportados +// os operadores padrão do Javascript também são suportados // definindo seu próprio operador (p1) plus (p2) = @@ -142,9 +142,10 @@ render each @(spark) into canvas context @(c) // O Javascript, tanto no navegador quanto no servidor (através do Node.js) // realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com -// chamadas de retorno. E/S assíncrona é maravilhosa para a performance e -// torna a concorrência simples, porém pode rapidamente se tornar algo complicado. -// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono mosquitos +// chamadas de retorno (callbacks). A E/S assíncrona é ótima para a performance e +// torna a utilização da concorrência simples, porém pode rapidamente se tornar +// algo complicado. +// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono muito // mais fácil // O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. @@ -155,12 +156,11 @@ directory listing = fs.readdir! '.' // `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o // operador `!`. O operador `!` permite que você chame funções assíncronas -// com a mesma sintaxe e praticamente a mesma semântica do que as demais -// funções síncronas. O Pogoscript reescreve a função para que todo código -// inserido após o operador seja inserido em uma função de callback para o -// `fs.readdir()`. +// com a mesma sintaxe e a mesma semântica do que as demais funções síncronas. +// O Pogoscript reescreve a função para que todo código inserido após o +// operador seja inserido em uma função de callback para o `fs.readdir()`. -// para se obter erros ao utilizar funções assíncronas +// obtendo erros ao utilizar funções assíncronas try another directory listing = fs.readdir! 'a-missing-dir' @@ -168,9 +168,9 @@ catch (ex) console.log (ex) // na verdade, se você não usar o `try catch`, o erro será passado para o -// `try catch` mais externo do evento, assim como é feito nas exceções síncronas +// `try catch` mais externo do evento, assim como é feito em exceções síncronas -// todo o controle de estrutura funciona com chamadas assíncronas também +// todo o controle de estrutura também funciona com chamadas assíncronas // aqui um exemplo de `if else` config = if (fs.stat! 'config.json'.is file ()) @@ -182,8 +182,8 @@ config = // para executar duas chamadas assíncronas de forma concorrente, use o // operador `?`. -// O operador `?` retorna um *future* que pode ser executado aguardando -// o resultado, novamente utilizando o operador `o` +// O operador `?` retorna um *future*, que pode ser executado para +// aguardar o resultado, novamente utilizando o operador `!` // nós não esperamos nenhuma dessas chamadas serem concluídas a = fs.stat? 'a.txt' -- cgit v1.2.3 From 9fcfa2c91feb2af119e67c9d1897340e87f03daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Thu, 22 Oct 2015 00:37:46 -0200 Subject: File name changed --- pt-br/pogo-pt.html.markdown | 202 ++++++++++++++++++++++++++++++++++++++++++++ pt-br/pogo.html.markdown | 202 -------------------------------------------- 2 files changed, 202 insertions(+), 202 deletions(-) create mode 100644 pt-br/pogo-pt.html.markdown delete mode 100644 pt-br/pogo.html.markdown (limited to 'pt-br') diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown new file mode 100644 index 00000000..124b32f7 --- /dev/null +++ b/pt-br/pogo-pt.html.markdown @@ -0,0 +1,202 @@ +--- +language: pogoscript +contributors: + - ["Tim Macfarlane", "http://github.com/refractalize"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] +filename: learnPogo-pt-br.pogo +lang: pt-br +--- + +Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents +e que compila para linguagem Javascript padrão. + +``` javascript +// definindo uma variável +water temperature = 24 + +// reatribuindo o valor de uma variável após a sua definição +water temperature := 26 + +// funções permitem que seus parâmetros sejam colocados em qualquer lugar +temperature at (a) altitude = 32 - a / 100 + +// funções longas são apenas indentadas +temperature at (a) altitude := + if (a < 0) + water temperature + else + 32 - a / 100 + +// declarando uma função +current temperature = temperature at 3200 altitude + +// essa função cria um novo objeto com métodos +position (x, y) = { + x = x + y = y + + distance from position (p) = + dx = self.x - p.x + dy = self.y - p.y + Math.sqrt (dx * dx + dy * dy) +} + +// `self` é similiar ao `this` do Javascript, com exceção de que `self` não +// é redefinido em cada nova função + +// declaração de métodos +position (7, 2).distance from position (position (5, 1)) + +// assim como no Javascript, objetos também são hashes +position.'x' == position.x == position.('x') + +// arrays +positions = [ + position (1, 1) + position (1, 2) + position (1, 3) +] + +// indexando um array +positions.0.y + +n = 2 +positions.(n).y + +// strings +poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. + Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. + Put on my shirt and took it off in the sun walking the path to lunch. + A dandelion seed floats above the marsh grass with the mosquitos. + At 4 A.M. the two middleaged men sleeping together holding hands. + In the half-light of dawn a few birds warble under the Pleiades. + Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep + cheep cheep.' + +// texto de Allen Ginsburg + +// interpolação +outlook = 'amazing!' +console.log "the weather tomorrow is going to be #(outlook)" + +// expressões regulares +r/(\d+)m/i +r/(\d+) degrees/mg + +// operadores +true @and true +false @or true +@not false +2 < 4 +2 >= 2 +2 > 1 + +// os operadores padrão do Javascript também são suportados + +// definindo seu próprio operador +(p1) plus (p2) = + position (p1.x + p2.x, p1.y + p2.y) + +// `plus` pode ser usado com um operador +position (1, 1) @plus position (0, 2) +// ou como uma função +(position (1, 1)) plus (position (0, 2)) + +// retorno explícito +(x) times (y) = return (x * y) + +// new +now = @new Date () + +// funções podem receber argumentos opcionais +spark (position, color: 'black', velocity: {x = 0, y = 0}) = { + color = color + position = position + velocity = velocity +} + +red = spark (position 1 1, color: 'red') +fast black = spark (position 1 1, velocity: {x = 10, y = 0}) + +// funções também podem ser utilizadas para realizar o "unsplat" de argumentos +log (messages, ...) = + console.log (messages, ...) + +// blocos são funções passadas para outras funções. +// Este bloco recebe dois parâmetros, `spark` e `c`, +// o corpo do bloco é o código indentado após a declaração da função + +render each @(spark) into canvas context @(c) + ctx.begin path () + ctx.stroke style = spark.color + ctx.arc ( + spark.position.x + canvas.width / 2 + spark.position.y + 3 + 0 + Math.PI * 2 + ) + ctx.stroke () + +// chamadas assíncronas + +// O Javascript, tanto no navegador quanto no servidor (através do Node.js) +// realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com +// chamadas de retorno (callbacks). A E/S assíncrona é ótima para a performance e +// torna a utilização da concorrência simples, porém pode rapidamente se tornar +// algo complicado. +// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono muito +// mais fácil + +// O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. +// Vamos listar o conteúdo de um diretório + +fs = require 'fs' +directory listing = fs.readdir! '.' + +// `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o +// operador `!`. O operador `!` permite que você chame funções assíncronas +// com a mesma sintaxe e a mesma semântica do que as demais funções síncronas. +// O Pogoscript reescreve a função para que todo código inserido após o +// operador seja inserido em uma função de callback para o `fs.readdir()`. + +// obtendo erros ao utilizar funções assíncronas + +try + another directory listing = fs.readdir! 'a-missing-dir' +catch (ex) + console.log (ex) + +// na verdade, se você não usar o `try catch`, o erro será passado para o +// `try catch` mais externo do evento, assim como é feito em exceções síncronas + +// todo o controle de estrutura também funciona com chamadas assíncronas +// aqui um exemplo de `if else` +config = + if (fs.stat! 'config.json'.is file ()) + JSON.parse (fs.read file! 'config.json' 'utf-8') + else + { + color: 'red' + } + +// para executar duas chamadas assíncronas de forma concorrente, use o +// operador `?`. +// O operador `?` retorna um *future*, que pode ser executado para +// aguardar o resultado, novamente utilizando o operador `!` + +// nós não esperamos nenhuma dessas chamadas serem concluídas +a = fs.stat? 'a.txt' +b = fs.stat? 'b.txt' + +// agora nos aguardamos o término das chamadas e escrevemos os resultados +console.log "size of a.txt is #(a!.size)" +console.log "size of b.txt is #(b!.size)" + +// no Pogoscript, futures são semelhantes a Promises +``` +E encerramos por aqui. + +Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. + +Há bastante documentação em [http://pogoscript.org/](http://pogoscript.org/), incluindo um material para [consulta rápida](http://pogoscript.org/cheatsheet.html), um [guia](http://pogoscript.org/guide/), e como o [Pogoscript é traduzido para o Javascript](http://featurist.github.io/pogo-examples/). Entre em contato através do [grupo do Google](http://groups.google.com/group/pogoscript) se você possui dúvidas! diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown deleted file mode 100644 index 124b32f7..00000000 --- a/pt-br/pogo.html.markdown +++ /dev/null @@ -1,202 +0,0 @@ ---- -language: pogoscript -contributors: - - ["Tim Macfarlane", "http://github.com/refractalize"] - - ["Cássio Böck", "https://github.com/cassiobsilva"] -filename: learnPogo-pt-br.pogo -lang: pt-br ---- - -Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents -e que compila para linguagem Javascript padrão. - -``` javascript -// definindo uma variável -water temperature = 24 - -// reatribuindo o valor de uma variável após a sua definição -water temperature := 26 - -// funções permitem que seus parâmetros sejam colocados em qualquer lugar -temperature at (a) altitude = 32 - a / 100 - -// funções longas são apenas indentadas -temperature at (a) altitude := - if (a < 0) - water temperature - else - 32 - a / 100 - -// declarando uma função -current temperature = temperature at 3200 altitude - -// essa função cria um novo objeto com métodos -position (x, y) = { - x = x - y = y - - distance from position (p) = - dx = self.x - p.x - dy = self.y - p.y - Math.sqrt (dx * dx + dy * dy) -} - -// `self` é similiar ao `this` do Javascript, com exceção de que `self` não -// é redefinido em cada nova função - -// declaração de métodos -position (7, 2).distance from position (position (5, 1)) - -// assim como no Javascript, objetos também são hashes -position.'x' == position.x == position.('x') - -// arrays -positions = [ - position (1, 1) - position (1, 2) - position (1, 3) -] - -// indexando um array -positions.0.y - -n = 2 -positions.(n).y - -// strings -poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. - Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. - Put on my shirt and took it off in the sun walking the path to lunch. - A dandelion seed floats above the marsh grass with the mosquitos. - At 4 A.M. the two middleaged men sleeping together holding hands. - In the half-light of dawn a few birds warble under the Pleiades. - Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep - cheep cheep.' - -// texto de Allen Ginsburg - -// interpolação -outlook = 'amazing!' -console.log "the weather tomorrow is going to be #(outlook)" - -// expressões regulares -r/(\d+)m/i -r/(\d+) degrees/mg - -// operadores -true @and true -false @or true -@not false -2 < 4 -2 >= 2 -2 > 1 - -// os operadores padrão do Javascript também são suportados - -// definindo seu próprio operador -(p1) plus (p2) = - position (p1.x + p2.x, p1.y + p2.y) - -// `plus` pode ser usado com um operador -position (1, 1) @plus position (0, 2) -// ou como uma função -(position (1, 1)) plus (position (0, 2)) - -// retorno explícito -(x) times (y) = return (x * y) - -// new -now = @new Date () - -// funções podem receber argumentos opcionais -spark (position, color: 'black', velocity: {x = 0, y = 0}) = { - color = color - position = position - velocity = velocity -} - -red = spark (position 1 1, color: 'red') -fast black = spark (position 1 1, velocity: {x = 10, y = 0}) - -// funções também podem ser utilizadas para realizar o "unsplat" de argumentos -log (messages, ...) = - console.log (messages, ...) - -// blocos são funções passadas para outras funções. -// Este bloco recebe dois parâmetros, `spark` e `c`, -// o corpo do bloco é o código indentado após a declaração da função - -render each @(spark) into canvas context @(c) - ctx.begin path () - ctx.stroke style = spark.color - ctx.arc ( - spark.position.x + canvas.width / 2 - spark.position.y - 3 - 0 - Math.PI * 2 - ) - ctx.stroke () - -// chamadas assíncronas - -// O Javascript, tanto no navegador quanto no servidor (através do Node.js) -// realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com -// chamadas de retorno (callbacks). A E/S assíncrona é ótima para a performance e -// torna a utilização da concorrência simples, porém pode rapidamente se tornar -// algo complicado. -// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono muito -// mais fácil - -// O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. -// Vamos listar o conteúdo de um diretório - -fs = require 'fs' -directory listing = fs.readdir! '.' - -// `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o -// operador `!`. O operador `!` permite que você chame funções assíncronas -// com a mesma sintaxe e a mesma semântica do que as demais funções síncronas. -// O Pogoscript reescreve a função para que todo código inserido após o -// operador seja inserido em uma função de callback para o `fs.readdir()`. - -// obtendo erros ao utilizar funções assíncronas - -try - another directory listing = fs.readdir! 'a-missing-dir' -catch (ex) - console.log (ex) - -// na verdade, se você não usar o `try catch`, o erro será passado para o -// `try catch` mais externo do evento, assim como é feito em exceções síncronas - -// todo o controle de estrutura também funciona com chamadas assíncronas -// aqui um exemplo de `if else` -config = - if (fs.stat! 'config.json'.is file ()) - JSON.parse (fs.read file! 'config.json' 'utf-8') - else - { - color: 'red' - } - -// para executar duas chamadas assíncronas de forma concorrente, use o -// operador `?`. -// O operador `?` retorna um *future*, que pode ser executado para -// aguardar o resultado, novamente utilizando o operador `!` - -// nós não esperamos nenhuma dessas chamadas serem concluídas -a = fs.stat? 'a.txt' -b = fs.stat? 'b.txt' - -// agora nos aguardamos o término das chamadas e escrevemos os resultados -console.log "size of a.txt is #(a!.size)" -console.log "size of b.txt is #(b!.size)" - -// no Pogoscript, futures são semelhantes a Promises -``` -E encerramos por aqui. - -Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. - -Há bastante documentação em [http://pogoscript.org/](http://pogoscript.org/), incluindo um material para [consulta rápida](http://pogoscript.org/cheatsheet.html), um [guia](http://pogoscript.org/guide/), e como o [Pogoscript é traduzido para o Javascript](http://featurist.github.io/pogo-examples/). Entre em contato através do [grupo do Google](http://groups.google.com/group/pogoscript) se você possui dúvidas! -- cgit v1.2.3 From 3dec2d03a7c327dcf5049ef087d1dd395b04ffd8 Mon Sep 17 00:00:00 2001 From: Jean Matheus Souto Date: Sat, 24 Oct 2015 20:51:42 -0200 Subject: Add more resources, add me to contributors --- pt-br/ruby-pt.html.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'pt-br') diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 89a051d4..668cd25f 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -4,6 +4,7 @@ lang: pt-br filename: learnruby-pt.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] + - ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"] translators: - ["Katyanna Moura", "https://twitter.com/amelie_kn"] --- @@ -161,9 +162,6 @@ hash['numero'] #=> 5 hash['nada aqui'] #=> nil # Interar sobre hashes com o método #each: -hash.each do |k, v| - puts "#{k} is #{v}" -end hash.each do |k, v| puts "#{k} é #{v}" @@ -385,3 +383,11 @@ Humano.bar # 0 Doutor.bar # nil ``` + +## Mais sobre Ruby + +- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem. +- [Ruby a partir de outras linguagens](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide* -- cgit v1.2.3 From d9d8de0d229443534272e2a1976fb7f0e69631b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Sun, 25 Oct 2015 15:44:35 -0200 Subject: Translator section added Changed my name from contributor section to the translator section --- pt-br/pogo-pt.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'pt-br') diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown index 124b32f7..80dcfcd5 100644 --- a/pt-br/pogo-pt.html.markdown +++ b/pt-br/pogo-pt.html.markdown @@ -2,6 +2,7 @@ language: pogoscript contributors: - ["Tim Macfarlane", "http://github.com/refractalize"] +translators: - ["Cássio Böck", "https://github.com/cassiobsilva"] filename: learnPogo-pt-br.pogo lang: pt-br -- cgit v1.2.3 From 8cac01c1b01fcb065b95e7b382449c6d0314d1cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Sun, 25 Oct 2015 16:18:48 -0200 Subject: File created pt-br haml file created --- pt-br/haml-pt.html.markdown | 182 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 pt-br/haml-pt.html.markdown (limited to 'pt-br') diff --git a/pt-br/haml-pt.html.markdown b/pt-br/haml-pt.html.markdown new file mode 100644 index 00000000..bff4bdee --- /dev/null +++ b/pt-br/haml-pt.html.markdown @@ -0,0 +1,182 @@ +--- +language: haml +filename: learnhaml.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] +translators: + - ["Cássio Böck", "https://github.com/cassiobsilva"] +--- + +Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of inline code. It is a popular alternative to using Rails templating language (.erb) and allows you to embed Ruby code into your markup. + +It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. + +You can also use Haml on a project independent of Ruby, by installing the Haml gem on your machine and using the command line to convert it to html. + +$ haml input_file.haml output_file.html + + +```haml +/ ------------------------------------------- +/ Indenting +/ ------------------------------------------- + +/ + Because of the importance indentation has on how your code is rendered, the + indents should be consistent throughout the document. Any differences in + indentation will throw an error. It's common-practice to use two spaces, + but it's really up to you, as long as they're constant. + + +/ ------------------------------------------- +/ Comments +/ ------------------------------------------- + +/ This is what a comment looks like in Haml. + +/ + To write a multi line comment, indent your commented code to be + wrapped by the forward slash + +-# This is a silent comment, which means it wont be rendered into the doc at all + + +/ ------------------------------------------- +/ Html elements +/ ------------------------------------------- + +/ To write your tags, use the percent sign followed by the name of the tag +%body + %header + %nav + +/ Notice no closing tags. The above code would output + +
+ +
+ + +/ The div tag is the default element, so they can be written simply like this +.foo + +/ To add content to a tag, add the text directly after the declaration +%h1 Headline copy + +/ To write multiline content, nest it instead +%p + This is a lot of content that we could probably split onto two + separate lines. + +/ + You can escape html by using the ampersand and equals sign ( &= ). This + converts html-sensitive characters (&, /, :) into their html encoded + equivalents. For example + +%p + &= "Yes & yes" + +/ would output 'Yes & yes' + +/ You can unescape html by using the bang and equals sign ( != ) +%p + != "This is how you write a paragraph tag

" + +/ which would output 'This is how you write a paragraph tag

' + +/ CSS classes can be added to your tags either by chaining .classnames to the tag +%div.foo.bar + +/ or as part of a Ruby hash +%div{:class => 'foo bar'} + +/ Attributes for any tag can be added in the hash +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ For boolean attributes assign the value 'true' +%input{:selected => true} + +/ To write data-attributes, use the :data key with its value as another hash +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Inserting Ruby +/ ------------------------------------------- + +/ + To output a Ruby value as the contents of a tag, use an equals sign followed + by the Ruby code + +%h1= book.name + +%p + = book.author + = book.publisher + + +/ To run some Ruby code without rendering it to the html, use a hyphen instead +- books = ['book 1', 'book 2', 'book 3'] + +/ Allowing you to do all sorts of awesome, like Ruby blocks +- books.shuffle.each_with_index do |book, index| + %h1= book + + if book do + %p This is a book + +/ Adding ordered / unordered list +%ul + %li + =item1 + =item2 + +/ + Again, no need to add the closing tags to the block, even for the Ruby. + Indentation will take care of that for you. + +/ ------------------------------------------- +/ Inserting Table with bootstrap classes +/ ------------------------------------------- + +%table.table.table-hover + %thead + %tr + %th Header 1 + %th Header 2 + + %tr + %td Value1 + %td value2 + + %tfoot + %tr + %td + Foot value + + +/ ------------------------------------------- +/ Inline Ruby / Ruby interpolation +/ ------------------------------------------- + +/ Include a Ruby variable in a line of plain text using #{} +%p Your highest scoring game is #{best_game} + + +/ ------------------------------------------- +/ Filters +/ ------------------------------------------- + +/ + Use the colon to define Haml filters, one example of a filter you can + use is :javascript, which can be used for writing inline js + +:javascript + console.log('This is inline