From 898750902a9035830652ef367015b830525349f6 Mon Sep 17 00:00:00 2001 From: Nacho Date: Thu, 19 Feb 2015 07:35:22 -0600 Subject: Updated Spanish translation --- es-es/go-es.html.markdown | 618 ++++++++++++++++++++++++++++------------------ 1 file changed, 371 insertions(+), 247 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 86de33ec..90967727 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -1,326 +1,450 @@ --- +name: Go +category: language language: Go lang: es-es filename: learngo-es.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] translators: - ["Adrian Espinosa", "http://www.adrianespinosa.com"] - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Nacho Pacheco -- Feb/2015", "https://github.com/gitnacho"] --- -Go fue creado por la necesidad de hacer el trabajo rápidamente. No es -la última tendencia en informática, pero es la forma nueva y más -rápida de resolver problemas reales. +Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la +última tendencia en informática, pero es la forma nueva y más rápida de +resolver problemas reales. -Tiene conceptos familiares de lenguajes imperativos con tipado -estático. Es rápido compilando y rápido al ejecutar, añade una -concurrencia fácil de entender para las CPUs de varios núcleos de hoy -en día, y tiene características que ayudan con la programación a gran -escala. +Tiene conceptos familiares de lenguajes imperativos con tipado estático. +Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de +entender para las CPUs de varios núcleos de hoy día, y tiene +características que ayudan con la programación a gran escala. -Go viene con una librería estándar muy buena y una comunidad entusiasta. +Go viene con una biblioteca estándar muy buena y una entusiasta comunidad. ```go // Comentario de una sola línea -/* Comentario - multi línea */ +/* Comentario + multilínea */ -// La cláusula package aparece al comienzo de cada archivo fuente. -// Main es un nombre especial que declara un ejecutable en vez de una librería. +// La cláusula `package` aparece al comienzo de cada archivo fuente. +// `main` es un nombre especial que declara un ejecutable en vez de una +// biblioteca. package main -// La declaración Import declara los paquetes de librerías -// referenciados en este archivo. +// La instrucción `import` declara los paquetes de bibliotecas referidos +// en este archivo. import ( - "fmt" // Un paquete en la librería estándar de Go. - "net/http" // Sí, un servidor web! - "strconv" // Conversiones de cadenas. - m "math" // Librería matemáticas con alias local m. + "fmt" // Un paquete en la biblioteca estándar de Go. + "io/ioutil" // Implementa algunas útiles funciones de E/S. + m "math" // Biblioteca de matemáticas con alias local m. + "net/http" // Sí, ¡un servidor web! + "strconv" // Conversiones de cadenas. ) -// Definición de una función. Main es especial. Es el punto de -// entrada para el ejecutable. Te guste o no, Go utiliza llaves. +// Definición de una función. `main` es especial. Es el punto de entrada +// para el ejecutable. Te guste o no, Go utiliza llaves. func main() { - // Println imprime una línea a stdout. - // Cualificalo con el nombre del paquete, fmt. - fmt.Println("Hello world!") + // Println imprime una línea a stdout. + // Cualificalo con el nombre del paquete, fmt. + fmt.Println("¡Hola mundo!") - // Llama a otra función de este paquete. - beyondHello() + // Llama a otra función de este paquete. + másAlláDelHola() } // Las funciones llevan parámetros entre paréntesis. // Si no hay parámetros, los paréntesis siguen siendo obligatorios. -func beyondHello() { - var x int // Declaración de una variable. - // Las variables se deben declarar antes de utilizarlas. - x = 3 // Asignación de variables. - // Declaración "corta" con := para inferir el tipo, declarar y asignar. - y := 4 - sum, prod := learnMultiple(x, y) // Función devuelve dos valores. - fmt.Println("sum:", sum, "prod:", prod) // Simple salida. - learnTypes() // < y minutes, learn more! +func másAlláDelHola() { + var x int // Declaración de una variable. + // Las variables se deben declarar antes de utilizarlas. + x = 3 // Asignación de variable. + // Declaración "corta" con := para inferir el tipo, declarar y asignar. + y := 4 + suma, producto := aprendeMúltiple(x, y) // La función devuelve dos + // valores. + fmt.Println("suma:", suma, "producto:", producto) // Simple salida. + aprendeTipos() // < y minutes, ¡aprende más! } -// Las funciones pueden tener parámetros y (múltiples!) valores de retorno. -func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // Devolver dos valores. +// Las funciones pueden tener parámetros y (¡múltiples!) valores de +// retorno. +func aprendeMúltiple(x, y int) (suma, producto int) { + return x + y, x * y // Devuelve dos valores. } // Algunos tipos incorporados y literales. -func learnTypes() { - // La declaración corta suele darte lo que quieres. - s := "Learn Go!" // tipo cadena - - s2 := ` Un tipo cadena "puro" puede incluir +func aprendeTipos() { + // La declaración corta suele darte lo que quieres. + s := "¡Aprende Go!" // tipo cadena. + s2 := `Un tipo cadena "puro" puede incluir saltos de línea.` // mismo tipo cadena - // Literal no ASCII. Los fuentes de Go son UTF-8. - g := 'Σ' // Tipo rune, un alias de int32, alberga un punto unicode. - f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. - c := 3 + 4i // complex128, representado internamente por dos float64. - // Sintaxis Var con inicializadores. - var u uint = 7 // Sin signo, pero la implementación depende del - // tamaño como en int. - var pi float32 = 22. / 7 - - // Sintáxis de conversión con una declaración corta. - n := byte('\n') // byte es un alias de uint8. - - // Los Arrays tienen un tamaño fijo a la hora de compilar. - var a4 [4]int // Un array de 4 ints, inicializados a 0. - a3 := [...]int{3, 1, 5} // Un array de 3 ints, inicializados como se indica. - - // Los Slices tienen tamaño dinámico. Los arrays y slices tienen sus ventajas - // y desventajas pero los casos de uso para los slices son más comunes. - s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos. - s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0. - var d2 [][]float64 // Solo declaración, sin asignación. - bs := []byte("a slice") // Sintaxis de conversión de tipo. - - p, q := learnMemory() // Declara p, q para ser un tipo puntero a int. - fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints. - - // Los Maps son arrays asociativos dinámicos, como los hash o - // diccionarios de otros lenguajes. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 - - // Las variables no utilizadas en Go producen error. - // El guión bajo permite "utilizar" una variable, pero descartar su valor. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Esto cuenta como utilización de variables. - fmt.Println(s, c, a4, s3, d2, m) - - learnFlowControl() // Vuelta al flujo. + // Literal no ASCII. Los ficheros fuente de Go son UTF-8. + g := 'Σ' // Tipo rune, un alias de int32, alberga un carácter unicode. + f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. + c := 3 + 4i // complex128, representado internamente por dos float64. + // Sintaxis Var con iniciadores. + var u uint = 7 // Sin signo, pero la implementación depende del tamaño + // como en int. + var pi float32 = 22. / 7 + + // Sintáxis de conversión con una declaración corta. + n := byte('\n') // byte es un alias para uint8. + + // Los Arreglos tienen un tamaño fijo a la hora de compilar. + var a4 [4]int // Un arreglo de 4 ints, iniciados a 0. + a3 := [...]int{3, 1, 5} // Un arreglo iniciado con un tamaño fijo de tres + // elementos, con valores 3, 1 y 5. + // Los Sectores tienen tamaño dinámico. Los arreglos y sectores tienen + // sus ventajas y desventajas pero los casos de uso para los sectores + // son más comunes. + s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos. + s4 := make([]int, 4) // Asigna sectores de 4 ints, iniciados a 0. + var d2 [][]float64 // Solo declaración, sin asignación. + bs := []byte("a sector") // Sintaxis de conversión de tipo. + // Debido a que son dinámicos, los sectores pueden crecer bajo demanda. + // Para añadir elementos a un sector, se utiliza la función incorporada + // append(). + // El primer argumento es el sector al que se está anexando. Comúnmente, + // la variable del arreglo se actualiza en su lugar, como en el + // siguiente ejemplo. + sec := []int{1, 2 , 3} // El resultado es un sector de longitud 3. + sec = append(sec, 4, 5, 6) // Añade 3 elementos. El sector ahora tiene una + // longitud de 6. + fmt.Println(sec) // El sector actualizado ahora es [1 2 3 4 5 6] + // Para anexar otro sector, en lugar de la lista de elementos atómicos + // podemos pasar una referencia a un sector o un sector literal como + // este, con elipsis al final, lo que significa tomar un sector y + // desempacar sus elementos, añadiéndolos al sector sec. + sec = append(sec, []int{7, 8, 9} ...) // El segundo argumento es un + // sector literal. + fmt.Println(sec) // El sector actualizado ahora es [1 2 3 4 5 6 7 8 9] + p, q := aprendeMemoria() // Declara p, q para ser un tipo puntero a + // int. + fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints. + + // Los Mapas son arreglos asociativos dinámicos, como los hash o + // diccionarios de otros lenguajes. + m := map[string]int{"tres": 3, "cuatro": 4} + m["uno"] = 1 + + // Las variables no utilizadas en Go producen error. + // El guión bajo permite "utilizar" una variable, pero descartar su + // valor. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Esto cuenta como utilización de variables. + fmt.Println(s, c, a4, s3, d2, m) + + aprendeControlDeFlujo() // Vuelta al flujo. +} + +// Es posible, a diferencia de muchos otros lenguajes tener valores de +// retorno con nombre en las funciones. +// Asignar un nombre al tipo que se devuelve en la línea de declaración de +// la función nos permite volver fácilmente desde múltiples puntos en una +// función, así como sólo utilizar la palabra clave `return`, sin nada +// más. +func aprendeRetornosNombrados(x, y int) (z int) { + z = x * y + return // aquí z es implícito, porque lo nombramos antes. } -// Go posee recolector de basura. Tiene puntero pero no aritmética de -// punteros. Puedes cometer un errores con un puntero nil, pero no +// Go posee recolector de basura. Tiene punteros pero no aritmética de +// punteros. Puedes cometer errores con un puntero nil, pero no // incrementando un puntero. -func learnMemory() (p, q *int) { - // q y p tienen un tipo puntero a int. - p = new(int) // Función incorporada que asigna memoria. - // La asignación de int se inicializa a 0, p ya no es nil. - s := make([]int, 20) // Asigna 20 ints a un solo bloque de memoria. - s[3] = 7 // Asignar uno de ellos. - r := -2 // Declarar otra variable local. - return &s[3], &r // & toma la dirección de un objeto. +func aprendeMemoria() (p, q *int) { + // Los valores de retorno nombrados q y p tienen un tipo puntero + // a int. + p = new(int) // Función incorporada que reserva memoria. + // La asignación de int se inicia a 0, p ya no es nil. + s := make([]int, 20) // Reserva 20 ints en un solo bloque de memoria. + s[3] = 7 // Asigna uno de ellos. + r := -2 // Declara otra variable local. + return &s[3], &r // & toma la dirección de un objeto. } -func expensiveComputation() float64 { - return m.Exp(10) +func cálculoCaro() float64 { + return m.Exp(10) } -func learnFlowControl() { - // La declaración If requiere llaves, pero no paréntesis. - if true { - fmt.Println("told ya") - } - // El formato está estandarizado por el comando "go fmt." - if false { - // Pout. - } else { - // Gloat. - } - // Utiliza switch preferiblemente para if encadenados. - x := 42.0 - switch x { - case 0: - case 1: - case 42: - // Los cases no se mezclan, no requieren de "break". - case 43: - // No llega. +func aprendeControlDeFlujo() { + // La declaración If requiere llaves, pero no paréntesis. + if true { + fmt.Println("ya relatado") + } + // El formato está estandarizado por la orden "go fmt." + if false { + // Abadejo. + } else { + // Relamido. + } + // Utiliza switch preferentemente para if encadenados. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Los cases no se mezclan, no requieren de "break". + case 43: + // No llega. + } + // Como if, for no utiliza paréntesis tampoco. + // Variables declaradas en for e if son locales a su ámbito. + for x := 0; x < 3; x++ { // ++ es una instrucción. + fmt.Println("iteración", x) + } + // aquí x == 42. + + // For es la única instrucción de bucle en Go, pero tiene formas + // alternativas. + for { // Bucle infinito. + break // ¡Solo bromeaba! + continue // No llega. + } + + // Puedes usar `range` para iterar en un arreglo, un sector, una + // cadena, un mapa o un canal. + // `range` devuelve o bien, un canal o de uno a dos values (arreglo, + // sector, cadena y mapa). + for clave, valor := range map[string]int{"uno": 1, "dos": 2, "tres": 3} { + // por cada par en el mapa, imprime la clave y el valor + fmt.Printf("clave=%s, valor=%d\n", clave, valor) + } + + // Como en for, := en una instrucción if significa declarar y asignar + // primero, luego comprobar y > x. + if y := cálculoCaro(); y > x { + x = y } - // Como if, for no utiliza paréntesis tampoco. - // Variables declaradas en for y if son locales de su ámbito local. - for x := 0; x < 3; x++ { // ++ es una sentencia. - fmt.Println("iteration", x) - } - // x == 42 aqui. + // Las funciones literales son "cierres". + granX := func() bool { + return x > 100 // Referencia a x declarada encima de la instrucción + // switch. + } + fmt.Println("granX:", granX()) // cierto (la última vez asignamos + // 1e6 a x). + x /= 1.3e3 // Esto hace a x == 1300 + fmt.Println("granX:", granX()) // Ahora es falso. + + // Es más las funciones literales se pueden definir y llamar en línea, + // actuando como un argumento para la función, siempre y cuando: + // a) la función literal sea llamada inmediatamente (), + // b) el tipo del resultado sea del tipo esperado del argumento + fmt.Println("Suma dos números + doble: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Llamada con argumentos 10 y 2 + // => Suma dos números + doble: 24 + + // Cuando lo necesites, te encantará. + goto encanto +encanto: + + aprendeFunciónFábrica() // func devolviendo func es divertido(3)(3) + aprendeADiferir() // Un rápido desvío a una importante palabra clave. + aprendeInterfaces() // ¡Buen material dentro de poco! +} - // For es la única sentencia de bucle en Go, pero tiene formas alternativas. - for { // Bucle infinito. - break // Solo bromeaba! - continue // No llega. - } - // Como en for, := en una sentencia if significa declarar y asignar primero, - // luego comprobar y > x. - if y := expensiveComputation(); y > x { - x = y - } - // Los literales de funciones son "closures". - xBig := func() bool { - return x > 100 // Referencia a x declarada encima de la sentencia switch. - } - fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x). - x /= m.Exp(9) // Esto lo hace x == e. - fmt.Println("xBig:", xBig()) // Ahora es falso. +func aprendeFunciónFábrica() { + // Las dos siguientes son equivalentes, la segunda es más práctica + fmt.Println(instrucciónFábrica("día")("Un bello", "de verano")) + + d := instrucciónFábrica("atardecer") + fmt.Println(d("Un hermoso", "de verano")) + fmt.Println(d("Un maravilloso", "de verano")) +} - // Cuando lo necesites, te encantará. - goto love -love: +// Los decoradores son comunes en otros lenguajes. Lo mismo se puede hacer +// en Go con funciónes literales que aceptan argumentos. +func instrucciónFábrica(micadena string) func(antes, después string) string { + return func(antes, después string) string { + return fmt.Sprintf("¡%s %s %s!", antes, micadena, después) // nueva cadena + } +} - learnInterfaces() // Buen material dentro de poco! +func aprendeADiferir() (ok bool) { + // las instrucciones diferidas se ejecutan justo antes de que la + // función regrese. + defer fmt.Println("las instrucciones diferidas se ejecutan en orden inverso (PEPS).") + defer fmt.Println("\nEsta línea se imprime primero debido a que") + // Defer se usa comunmente para cerrar un fichero, por lo que la + // función que cierra el fichero se mantiene cerca de la función que lo + // abrió. + return true } // Define Stringer como un tipo interfaz con un método, String. type Stringer interface { - String() string + String() string } -// Define pair como un struct con dos campos int, x e y. -type pair struct { - x, y int +// Define par como una estructura con dos campos int, x e y. +type par struct { + x, y int } -// Define un método del tipo pair. Pair ahora implementa Stringer. -func (p pair) String() string { // p se llama "recibidor" - // Sprintf es otra función pública del paquete fmt. - // La sintaxis con punto referencia campos de p. - return fmt.Sprintf("(%d, %d)", p.x, p.y) +// Define un método en el tipo par. Par ahora implementa a Stringer. +func (p par) String() string { // p se conoce como el "receptor" + // Sprintf es otra función pública del paquete fmt. + // La sintaxis con punto se refiere a los campos de p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) } -func learnInterfaces() { - // La sintaxis de llaves es un "literal struct". Evalúa a un struct - // inicializado. La sintaxis := declara e inicializa p a este struct. - p := pair{3, 4} - fmt.Println(p.String()) // Llamar al método String de p, de tipo pair. - var i Stringer // Declarar i como interfaz tipo Stringer. - i = p // Válido porque pair implementa Stringer. - // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba. - fmt.Println(i.String()) - - // Las funciones en el paquete fmt llaman al método String para - // preguntar a un objeto por una versión imprimible de si mismo. - fmt.Println(p) // Salida igual que arriba. Println llama al método String. - fmt.Println(i) // Salida igual que arriba. - - learnVariadicParams("great", "learning", "here!") +func aprendeInterfaces() { + // La sintaxis de llaves es una "estructura literal". Evalúa a una + // estructura iniciada. La sintaxis := declara e inicia p a esta + // estructura. + p := par{3, 4} + fmt.Println(p.String()) // Llama al método String de p, de tipo par. + var i Stringer // Declara i como interfaz de tipo Stringer. + i = p // Válido porque par implementa Stringer. + // Llama al metodo String de i, de tipo Stringer. Misma salida que + // arriba. + fmt.Println(i.String()) + + // Las funciones en el paquete fmt llaman al método String para + // consultar un objeto por una representación imprimible de si + // mismo. + fmt.Println(p) // Salida igual que arriba. Println llama al método + // String. + fmt.Println(i) // Salida igual que arriba. + aprendeNúmeroVariableDeParámetros("¡gran", "aprendizaje", "aquí!") } // Las funciones pueden tener número variable de argumentos. -func learnVariadicParams(myStrings ...interface{}) { - // Iterar cada valor de la variadic. - for _, param := range myStrings { - fmt.Println("param:", param) - } - - // Pasar valor variadic como parámetro variadic. - fmt.Println("params:", fmt.Sprintln(myStrings...)) - - learnErrorHandling() +func aprendeNúmeroVariableDeParámetros(misCadenas ...interface{}) { + // Itera en cada valor de los argumentos variables. + // El espacio en blanco aquí omite el índice del argumento arreglo. + for _, parámetro := range misCadenas { + fmt.Println("parámetro:", parámetro) + } + + // Pasa el valor de múltiples variables como parámetro variadic. + fmt.Println("parámetros:", fmt.Sprintln(misCadenas...)) + aprendeManejoDeError() } -func learnErrorHandling() { - // ", ok" forma utilizada para saber si algo funcionó o no. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok será falso porque 1 no está en el map. - fmt.Println("no one there") - } else { - fmt.Print(x) // x sería el valor, si estuviera en el map. - } - // Un valor de error comunica más información sobre el problema aparte de "ok". - if _, err := strconv.Atoi("non-int"); err != nil { // _ descarta el valor - // Imprime "strconv.ParseInt: parsing "non-int": invalid syntax". - fmt.Println(err) - } - // Revisarmeos las interfaces más tarde. Mientras tanto, - learnConcurrency() +func aprendeManejoDeError() { + // ", ok" forma utilizada para saber si algo funcionó o no. + m := map[int]string{3: "tres", 4: "cuatro"} + if x, ok := m[1]; !ok { // ok será falso porque 1 no está en el mapa. + fmt.Println("nada allí") + } else { + fmt.Print(x) // x sería el valor, si estuviera en el mapa. + } + // Un valor de error comunica más información sobre el problema aparte + // de "ok". + if _, err := strconv.Atoi("no-int"); err != nil { // _ descarta el + // valor + // Imprime "strconv.ParseInt: parsing "no-int": invalid syntax". + fmt.Println(err) + } + // Revisaremos las interfaces más adelante. Mientras tanto... + aprendeConcurrencia() } -// c es un canal, un objeto de comunicación de concurrencia segura. +// c es un canal, un objeto de comunicación concurrente seguro. func inc(i int, c chan int) { - c <- i + 1 // <- es el operador "enviar" cuando un canal aparece a la izquierda. + c <- i + 1 // <- es el operador "enviar" cuando aparece un canal a la + // izquierda. } // Utilizaremos inc para incrementar algunos números concurrentemente. -func learnConcurrency() { - // Misma función make utilizada antes para crear un slice. Make asigna e - // inicializa slices, maps, y channels. - c := make(chan int) - // Iniciar tres goroutines concurrentes. Los números serán incrementados - // concurrentemente, quizás en paralelo si la máquina es capaz y - // está correctamente configurada. Las tres envían al mismo channel. - go inc(0, c) // go es una sentencia que inicia una nueva goroutine. - go inc(10, c) - go inc(-805, c) - // Leer los tres resultados del channel e imprimirlos. - // No se puede saber en que orden llegarán los resultados! - fmt.Println(<-c, <-c, <-c) // Channel a la derecha, <- es el operador "recibir". - - cs := make(chan string) // Otro channel, este gestiona cadenas. - ccs := make(chan chan string) // Un channel de cadenas de channels. - go func() { c <- 84 }() // Iniciar una nueva goroutine solo para - // enviar un valor. - go func() { cs <- "wordy" }() // Otra vez, para cs en esta ocasión. - // Select tiene una sintáxis parecida a la sentencia switch pero - // cada caso involucra una operacion de channels. Selecciona un caso - // de forma aleatoria de los casos que están listos para comunicarse. - select { - case i := <-c: // El valor recibido puede ser asignado a una variable, - fmt.Printf("it's a %T", i) - case <-cs: // o el valor puede ser descartado. - fmt.Println("it's a string") - case <-ccs: // Channel vacío, no está listo para la comunicación. - fmt.Println("didn't happen.") - } - - // En este punto un valor fue devuelvto de c o cs. Uno de las dos - // goroutines que se iniciaron se ha completado, la otrá permancerá - // bloqueada. - - learnWebProgramming() // Go lo hace. Tu también quieres hacerlo. +func aprendeConcurrencia() { + // Misma función make utilizada antes para crear un sector. Make asigna + // e inicia sectores, mapas y canales. + c := make(chan int) + // Inicia tres rutinasgo concurrentes. Los números serán incrementados + // concurrentemente, quizás en paralelo si la máquina es capaz y está + // correctamente configurada. Las tres envían al mismo canal. + go inc(0, c) // go es una instrucción que inicia una nueva rutinago. + go inc(10, c) + go inc(-805, c) + // Lee los tres resultados del canal y los imprime. + // ¡No se puede saber en que orden llegarán los resultados! + fmt.Println(<-c, <-c, <-c) // Canal a la derecha, <- es el operador + // "recibe". + + cs := make(chan string) // Otro canal, este gestiona cadenas. + ccs := make(chan chan string) // Un canal de canales cadena. + go func() { c <- 84 }() // Inicia una nueva rutinago solo para + // enviar un valor. + go func() { cs <- "verboso" }() // Otra vez, para cs en esta ocasión. + // Select tiene una sintáxis parecida a la instrucción switch pero cada + // caso involucra una operacion con un canal. Selecciona un caso de + // forma aleatoria de los casos que están listos para comunicarse. + select { + case i := <-c: // El valor recibido se puede asignar a una variable, + fmt.Printf("es un %T", i) + case <-cs: // o el valor se puede descartar. + fmt.Println("es una cadena") + case <-ccs: // Canal vacío, no está listo para la comunicación. + fmt.Println("no sucedió.") + } + + // En este punto un valor fue devuelto de c o cs. Una de las dos + // rutinasgo que se iniciaron se ha completado, la otrá permancerá + // bloqueada. + + aprendeProgramaciónWeb() // Go lo hace. Tú también quieres hacerlo. } // Una simple función del paquete http inicia un servidor web. -func learnWebProgramming() { - // El primer parámetro de la direccinón TCP a la que escuchar. - // El segundo parámetro es una interfaz, concretamente http.Handler. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // no ignorar errores +func aprendeProgramaciónWeb() { +// El primer parámetro es la direccinón TCP a la que escuchar. + // El segundo parámetro es una interfaz, concretamente http.Handler. + go func() { + err := http.ListenAndServe(":8080", par{}) + fmt.Println(err) // no ignora errores + }() + consultaAlServidor() } -// Haz pair un http.Handler implementando su único método, ServeHTTP. -func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Servir datos con un método de http.ResponseWriter. - w.Write([]byte("You learned Go in Y minutes!")) +// Hace un http.Handler de par implementando su único método, ServeHTTP. +func (p par) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Sirve datos con un método de http.ResponseWriter. + w.Write([]byte("¡Aprendiste Go en Y minutos!")) +} + +func consultaAlServidor() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + cuerpo, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nEl servidor web dijo: `%s`\n", string(cuerpo)) } ``` -## Para leer más +## Más información + +La raíz de todas las cosas sobre Go es el +[sitio web oficial de Go](http://golang.org/). +Allí puedes seguir el tutorial, jugar interactivamente y leer mucho más. -La raíz de todas las cosas de Go es la [web oficial de Go](http://golang.org/). -Ahí puedes seguir el tutorial, jugar interactivamente y leer mucho. +La definición del lenguaje es altamente recomendada. Es fácil de leer y +sorprendentemente corta (como la definición del lenguaje Go en estos +días). -La propia definición del lenguaje también está altamente -recomendada. Es fácil de leer e increíblemente corta (como otras -definiciones de lenguajes hoy en día) +Puedes jugar con el código en el +[parque de diversiones Go](https://play.golang.org/p/ncRC2Zevag). ¡Trata +de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes +utilizar [https://play.golang.org]( https://play.golang.org) como un +[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) para probar +cosas y el código en el navegador, sin ni siquiera instalar Go. -En la lista de lectura de estudiantes de Go está el código fuente de -la librería estándar. Muy bien documentada, demuestra lo mejor de Go -leíble, comprendible, estilo Go y formas Go. Pincha en el nombre de -una función en la documentación y te aparecerá el código fuente! +En la lista de lecturas para estudiantes de Go está el +[código fuente de la biblioteca estándar](http://golang.org/src/pkg/). +Ampliamente documentado, que demuestra lo mejor del legible y comprensible +Go, con su característico estilo y modismos. ¡O puedes hacer clic en un +nombre de función en [la documentación](http://golang.org/pkg/) y +aparecerá el código fuente! +Otro gran recurso para aprender Go está en +[Go con ejemplos](http://goconejemplos.com/). -- cgit v1.2.3 From b8ee0a0a525c4ff140b3f17fd3d75c8e123d5259 Mon Sep 17 00:00:00 2001 From: Nacho Date: Thu, 19 Feb 2015 14:56:58 -0600 Subject: Updated the Spanish translation, the translated and linked to Playground code was tested, changed the URLs for resources in Spanish. --- es-es/go-es.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 90967727..c41d693d 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -33,13 +33,13 @@ Go viene con una biblioteca estándar muy buena y una entusiasta comunidad. /* Comentario multilínea */ -// La cláusula `package` aparece al comienzo de cada archivo fuente. +// La cláusula `package` aparece al comienzo de cada fichero fuente. // `main` es un nombre especial que declara un ejecutable en vez de una // biblioteca. package main // La instrucción `import` declara los paquetes de bibliotecas referidos -// en este archivo. +// en este fichero. import ( "fmt" // Un paquete en la biblioteca estándar de Go. "io/ioutil" // Implementa algunas útiles funciones de E/S. @@ -70,7 +70,7 @@ func másAlláDelHola() { suma, producto := aprendeMúltiple(x, y) // La función devuelve dos // valores. fmt.Println("suma:", suma, "producto:", producto) // Simple salida. - aprendeTipos() // < y minutes, ¡aprende más! + aprendeTipos() // < y minutos, ¡aprende más! } // Las funciones pueden tener parámetros y (¡múltiples!) valores de @@ -211,7 +211,7 @@ func aprendeControlDeFlujo() { // Puedes usar `range` para iterar en un arreglo, un sector, una // cadena, un mapa o un canal. - // `range` devuelve o bien, un canal o de uno a dos values (arreglo, + // `range` devuelve o bien, un canal o de uno a dos valores (arreglo, // sector, cadena y mapa). for clave, valor := range map[string]int{"uno": 1, "dos": 2, "tres": 3} { // por cada par en el mapa, imprime la clave y el valor -- cgit v1.2.3 From 4196b7addd156b3b7f1621c0c0a1e38654897acf Mon Sep 17 00:00:00 2001 From: e99n09 Date: Sun, 8 Mar 2015 20:21:26 -0400 Subject: Create statcomppython This is a tutorial on how to use Python for the stuff people normally do in R, MATLAB, or Stata. It's designed for someone comfortable with programming, basically familiar with Python, and experienced with a statistical programming language. Scraping the web, reading CSV files, summarizing columns, basic charts and plotting options, plus an extended data cleaning and exploratory data analysis example using a table of Holy Roman Emperors. --- statcomppython | 234 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 statcomppython diff --git a/statcomppython b/statcomppython new file mode 100644 index 00000000..1f71bf6e --- /dev/null +++ b/statcomppython @@ -0,0 +1,234 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: statcomppython.py +--- + +This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Getting set up ==== + +""" Get set up with IPython and pip install the following: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Make sure to do this tutorial in the IPython notebook so that you get + the inline plots and easy documentation lookup. +""" + +# 1. Data acquisition ==== + +""" One reason people choose Python over R is that they intend to interact a lot + with the web, either by scraping pages directly or requesting data through + an API. You can do those things in R, but in the context of a project + already using Python, there's a benefit to sticking with one language. +""" + +import requests # for HTTP requests (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted +# save the page source in a file: +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# downloading a csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" for more on the requests module, including APIs, see + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Reading a CSV file ==== + +""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If + you've used R, you will be familiar with the idea of the "data.frame" already. +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" R users: note that Python, like most normal programming languages, starts + indexing from 0. R is the unusual one for starting from 1. +""" + +# two different ways to print out a column +pets.age +pets["age"] + +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# in R, you would expect to get 3 rows doing this, but here you get 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" If you are doing some serious linear algebra and number-crunching, you may + just want arrays, not DataFrames. DataFrames are ideal for combining columns + of different types. +""" + +# 3. Charts ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# To do data vizualization in Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn sits atop matplotlib and makes plots prettier + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# there are also some seaborn-specific plotting functions +# notice how seaborn automatically labels the x-axis on this barplot +sns.barplot(pets["age"]) + +# R veterans can still use ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# source: https://pypi.python.org/pypi/ggplot + +# there's even a d3.js port: https://github.com/mikedewar/d3py + +# 4. Simple data cleaning and exploratory analysis ==== + +""" Here's a more complicated example that demonstrates a basic data + cleaning workflow leading to the creation of some exploratory plots + and the running of a linear regression. + The data set was transcribed from Wikipedia by hand. It contains + all the Holy Roman Emperors and the important milestones in their lives + (birth, death, coronation, etc.). + The goal of the analysis will be to explore whether a relationship + exists between emperor birth year and emperor lifespan. + data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# load some data on Holy Roman Emperors +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# clean the Birth and Death columns + +import re # module for regular expressions + +rx = re.compile(r'\d+$') # match trailing digits + +""" This function applies the regular expression to an input column (here Birth, + Death), flattens the resulting list, converts it to a Series object, and + finally converts the type of the Series object from string to integer. For + more information into what different parts of the code do, see: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# make a column telling estimated age +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# simple scatterplot, no trend line, color represents dynasty +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# use scipy to run a linear regression +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# code source: http://wiki.scipy.org/Cookbook/LinearRegression + +# check the slope +slope # 0.0057672618839073328 + +# check the R^2 value: +rval**2 # 0.020363950027333586 + +# check the p-value +pval # 0.34971812581498452 + +# use seaborn to make a scatterplot and plot the linear regression trend line +sns.lmplot("BirthY", "EstAge", data=hre); + +""" For more information on seaborn, see + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + For more information on SciPy, see + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + To see a version of the Holy Roman Emperors analysis using R, see + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. + +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers. + +Some more modules to research: + - text analysis and natural language processing: nltk, http://www.nltk.org + - social network analysis: igraph, http://igraph.org/python/ -- cgit v1.2.3 From e65582d459e5770d1a3ac3c5e5826dc10b546344 Mon Sep 17 00:00:00 2001 From: e99n09 Date: Sun, 8 Mar 2015 22:34:12 -0400 Subject: Update and rename statcomppython to pythonstatcomp.markdown.html --- pythonstatcomp.markdown.html | 234 +++++++++++++++++++++++++++++++++++++++++++ statcomppython | 234 ------------------------------------------- 2 files changed, 234 insertions(+), 234 deletions(-) create mode 100644 pythonstatcomp.markdown.html delete mode 100644 statcomppython diff --git a/pythonstatcomp.markdown.html b/pythonstatcomp.markdown.html new file mode 100644 index 00000000..78b62e33 --- /dev/null +++ b/pythonstatcomp.markdown.html @@ -0,0 +1,234 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp.py +--- + +This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Getting set up ==== + +""" Get set up with IPython and pip install the following: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Make sure to do this tutorial in the IPython notebook so that you get + the inline plots and easy documentation lookup. +""" + +# 1. Data acquisition ==== + +""" One reason people choose Python over R is that they intend to interact a lot + with the web, either by scraping pages directly or requesting data through + an API. You can do those things in R, but in the context of a project + already using Python, there's a benefit to sticking with one language. +""" + +import requests # for HTTP requests (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted +# save the page source in a file: +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# downloading a csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" for more on the requests module, including APIs, see + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Reading a CSV file ==== + +""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If + you've used R, you will be familiar with the idea of the "data.frame" already. +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" R users: note that Python, like most normal programming languages, starts + indexing from 0. R is the unusual one for starting from 1. +""" + +# two different ways to print out a column +pets.age +pets["age"] + +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# in R, you would expect to get 3 rows doing this, but here you get 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" If you are doing some serious linear algebra and number-crunching, you may + just want arrays, not DataFrames. DataFrames are ideal for combining columns + of different types. +""" + +# 3. Charts ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# To do data vizualization in Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn sits atop matplotlib and makes plots prettier + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# there are also some seaborn-specific plotting functions +# notice how seaborn automatically labels the x-axis on this barplot +sns.barplot(pets["age"]) + +# R veterans can still use ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# source: https://pypi.python.org/pypi/ggplot + +# there's even a d3.js port: https://github.com/mikedewar/d3py + +# 4. Simple data cleaning and exploratory analysis ==== + +""" Here's a more complicated example that demonstrates a basic data + cleaning workflow leading to the creation of some exploratory plots + and the running of a linear regression. + The data set was transcribed from Wikipedia by hand. It contains + all the Holy Roman Emperors and the important milestones in their lives + (birth, death, coronation, etc.). + The goal of the analysis will be to explore whether a relationship + exists between emperor birth year and emperor lifespan. + data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# load some data on Holy Roman Emperors +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# clean the Birth and Death columns + +import re # module for regular expressions + +rx = re.compile(r'\d+$') # match trailing digits + +""" This function applies the regular expression to an input column (here Birth, + Death), flattens the resulting list, converts it to a Series object, and + finally converts the type of the Series object from string to integer. For + more information into what different parts of the code do, see: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# make a column telling estimated age +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# simple scatterplot, no trend line, color represents dynasty +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# use scipy to run a linear regression +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# code source: http://wiki.scipy.org/Cookbook/LinearRegression + +# check the slope +slope # 0.0057672618839073328 + +# check the R^2 value: +rval**2 # 0.020363950027333586 + +# check the p-value +pval # 0.34971812581498452 + +# use seaborn to make a scatterplot and plot the linear regression trend line +sns.lmplot("BirthY", "EstAge", data=hre); + +""" For more information on seaborn, see + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + For more information on SciPy, see + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + To see a version of the Holy Roman Emperors analysis using R, see + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. + +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers. + +Some more modules to research: + - text analysis and natural language processing: nltk, http://www.nltk.org + - social network analysis: igraph, http://igraph.org/python/ diff --git a/statcomppython b/statcomppython deleted file mode 100644 index 1f71bf6e..00000000 --- a/statcomppython +++ /dev/null @@ -1,234 +0,0 @@ ---- -language: Statistical computing with Python -contributors: - - ["e99n09", "https://github.com/e99n09"] -filename: statcomppython.py ---- - -This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. - -```python - -# 0. Getting set up ==== - -""" Get set up with IPython and pip install the following: numpy, scipy, pandas, - matplotlib, seaborn, requests. - Make sure to do this tutorial in the IPython notebook so that you get - the inline plots and easy documentation lookup. -""" - -# 1. Data acquisition ==== - -""" One reason people choose Python over R is that they intend to interact a lot - with the web, either by scraping pages directly or requesting data through - an API. You can do those things in R, but in the context of a project - already using Python, there's a benefit to sticking with one language. -""" - -import requests # for HTTP requests (web scraping, APIs) -import os - -# web scraping -r = requests.get("https://github.com/adambard/learnxinyminutes-docs") -r.status_code # if 200, request was successful -r.text # raw page source -print(r.text) # prettily formatted -# save the page source in a file: -os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html","wb") -f.write(r.text.encode("UTF-8")) -f.close() - -# downloading a csv -fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" -fn = "pets.csv" -r = requests.get(fp + fn) -print(r.text) -f = open(fn,"wb") -f.write(r.text.encode("UTF-8")) -f.close() - -""" for more on the requests module, including APIs, see - http://docs.python-requests.org/en/latest/user/quickstart/ -""" - -# 2. Reading a CSV file ==== - -""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If - you've used R, you will be familiar with the idea of the "data.frame" already. -""" - -import pandas as pd, numpy as np, scipy as sp -pets = pd.read_csv(fn) -pets -# name age weight species -# 0 fluffy 3 14 cat -# 1 vesuvius 6 23 fish -# 2 rex 5 34 dog - -""" R users: note that Python, like most normal programming languages, starts - indexing from 0. R is the unusual one for starting from 1. -""" - -# two different ways to print out a column -pets.age -pets["age"] - -pets.head(2) # prints first 2 rows -pets.tail(1) # prints last row - -pets.name[1] # 'vesuvius' -pets.species[0] # 'cat' -pets["weight"][2] # 34 - -# in R, you would expect to get 3 rows doing this, but here you get 2: -pets.age[0:2] -# 0 3 -# 1 6 - -sum(pets.age)*2 # 28 -max(pets.weight) - min(pets.weight) # 20 - -""" If you are doing some serious linear algebra and number-crunching, you may - just want arrays, not DataFrames. DataFrames are ideal for combining columns - of different types. -""" - -# 3. Charts ==== - -import matplotlib as mpl, matplotlib.pyplot as plt -%matplotlib inline - -# To do data vizualization in Python, use matplotlib - -plt.hist(pets.age); - -plt.boxplot(pets.weight); - -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); - -# seaborn sits atop matplotlib and makes plots prettier - -import seaborn as sns - -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); - -# there are also some seaborn-specific plotting functions -# notice how seaborn automatically labels the x-axis on this barplot -sns.barplot(pets["age"]) - -# R veterans can still use ggplot -from ggplot import * -ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") -# source: https://pypi.python.org/pypi/ggplot - -# there's even a d3.js port: https://github.com/mikedewar/d3py - -# 4. Simple data cleaning and exploratory analysis ==== - -""" Here's a more complicated example that demonstrates a basic data - cleaning workflow leading to the creation of some exploratory plots - and the running of a linear regression. - The data set was transcribed from Wikipedia by hand. It contains - all the Holy Roman Emperors and the important milestones in their lives - (birth, death, coronation, etc.). - The goal of the analysis will be to explore whether a relationship - exists between emperor birth year and emperor lifespan. - data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor -""" - -# load some data on Holy Roman Emperors -url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" -r = requests.get(url) -fp = "hre.csv" -f = open(fp,"wb") -f.write(r.text.encode("UTF-8")) -f.close() - -hre = pd.read_csv(fp) - -hre.head() -""" - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN -""" - -# clean the Birth and Death columns - -import re # module for regular expressions - -rx = re.compile(r'\d+$') # match trailing digits - -""" This function applies the regular expression to an input column (here Birth, - Death), flattens the resulting list, converts it to a Series object, and - finally converts the type of the Series object from string to integer. For - more information into what different parts of the code do, see: - - https://docs.python.org/2/howto/regex.html - - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list - - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html -""" -def extractYear(v): - return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) - -hre["BirthY"] = extractYear(hre.Birth) -hre["DeathY"] = extractYear(hre.Death) - -# make a column telling estimated age -hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) - -# simple scatterplot, no trend line, color represents dynasty -sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); - -# use scipy to run a linear regression -from scipy import stats -(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) -# code source: http://wiki.scipy.org/Cookbook/LinearRegression - -# check the slope -slope # 0.0057672618839073328 - -# check the R^2 value: -rval**2 # 0.020363950027333586 - -# check the p-value -pval # 0.34971812581498452 - -# use seaborn to make a scatterplot and plot the linear regression trend line -sns.lmplot("BirthY", "EstAge", data=hre); - -""" For more information on seaborn, see - - http://web.stanford.edu/~mwaskom/software/seaborn/ - - https://github.com/mwaskom/seaborn - For more information on SciPy, see - - http://wiki.scipy.org/SciPy - - http://wiki.scipy.org/Cookbook/ - To see a version of the Holy Roman Emperors analysis using R, see - - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R -""" -``` - -If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. - -You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers. - -Some more modules to research: - - text analysis and natural language processing: nltk, http://www.nltk.org - - social network analysis: igraph, http://igraph.org/python/ -- cgit v1.2.3 From 4e530b27b0a9d0373e117397429118fd14f152ff Mon Sep 17 00:00:00 2001 From: dokato Date: Mon, 9 Mar 2015 20:28:26 +0100 Subject: First version of python script translation --- pl-pl/python-pl.html.markdown | 629 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 629 insertions(+) create mode 100644 pl-pl/python-pl.html.markdown diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown new file mode 100644 index 00000000..1f4cfd0b --- /dev/null +++ b/pl-pl/python-pl.html.markdown @@ -0,0 +1,629 @@ + +--- +name: python +category: language +language: python +filename: learnpython-pl.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Dominik Krzemiński", "https://github.com/dokato"] +lang: pl-pl +--- +Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. +Obecnie jest jednym z najbardziej popularnych języków programowania. +Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. +To po prostu wykonywalny pseudokod. + +Zapraszam do kontaktu. Złapiecie mnie na [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] + +Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien +działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. + +```python + +# Pojedyncze komentarze oznaczamy takim symbolem. + +""" Wielolinijkowe napisy zapisywane są przy użyciu + trzech znaków cudzysłowiu i często + wykorzystywane są jako komentarze +""" + +#################################################### +## 1. Podstawowe typy danych i operatory +#################################################### + +# Liczby to liczby +3 # => 3 + +# Matematyka jest intuicyjna +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Dzielenie może być kłopotliwe. Poniższe to dzielenie +# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. +5 / 2 # => 2 + +# Aby to naprawić musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. +2.0 # To liczba zmiennoprzecinkowa, tzw. float +11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej + +# Wynik dzielenia całkowitoliczbowego jest obcinany dla liczb +# dodatnich i ujemnych. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # działa też na floatach +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Operator modulo - wyznaczanie reszty z dzielenia +7 % 3 # => 1 + +# Potęgowanie (x do potęgi ytej) +2**4 # => 16 + +# Wymuszanie pierwszeństwa w nawiasach +(1 + 3) * 2 # => 8 + +# Operacje logiczne +# Zauważ, że przy "and" i "or" trzeba zwracać uwagę na rozmiar liter +True and False #=> False # Fałsz +False or True #=> True # Prawda + +# Zauważ, że operatorów logicznych można używać z intami +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +k1 == True #=> True + +# aby zanegować użyj "not" +not True # => False +not False # => True + +# Równość == +1 == 1 # => True +2 == 1 # => False + +# Nierówność != +1 != 1 # => False +2 != 1 # => True + +# Więcej porównań +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porównania można układać w łańcuch! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Napisy (typ string) tworzone są przy użyciu cudzysłowów " lub ' +"Jestem napisem." +'Ja też jestem napisem.' + +# Napisy można dodawać! +"Witaj " + "świecie!" # => "Witaj świecie!" + +# ... a nawet mnożone +"Hej" * 3 # => "HejHejHej" + +# Napis może być traktowany jako lista znaków +"To napis"[0] # => 'T' + +# % może być używane do formatowania napisów: +"%s są %s" % ("napisy", "fajne") + +# Jednak nowszym sposobem formatowania jest metoda "format". +# Ta metoda jest obecnie polecana: +"{0} są {1}".format("napisy", "fajne") +# Jeśli nie chce ci się liczyć użyj słów kluczowych. +"{imie} chce zjeść {jadlo}".format(imie="Bob", jasno="lasagne") + +# None jest obiektem +None # => None + +# Nie używaj "==" żeby porównywać obiekty do None +# Zamiast tego użyj "is" +"etc" is None # => False +None is None # => True + +# Operator 'is' testuje identyczność obiektów. To nie jest zbyt +# pożyteczne, gdy działamy tylko na prostych wartościach, +# ale przydaje się, gdy mamy do czynienia z obiektami. + +# None, 0, i pusty napis "" są odpowiednikami logicznego False. +# Wszystkie inne wartości są True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Zmienne i zbiory danych +#################################################### + +# Python ma wyrażenie wypisujące "print" we wszystkich wersjach 2.x, ale +# zostało usunięte z wersji 3. +print "Jestem Python. Miło poznać!" +# Python ma też funkcję "print" dostępną w wersjach 2.7 and 3... +# ale w 2.7 musisz dodać import (odkomentuj): +# from __future__ import print_function +print("Ja też jestem Python! ") + +# Nie trzeba deklarować zmiennych przed przypisaniem. +jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i podłogi _ +jakas_zmienna # => 5 + +# Próba dostępu do niezadeklarowanej zmiennej da błąd. +# Przejdź do sekcji Obsługa wyjątków po więcej... +inna_zmienna # Wyrzuca nazwę błędu + +# "if" może być użyte jako wyrażenie +"huraaa!" if 3 > 2 else 2 # => "huraaa!" + +# Listy: +li = [] +# Możesz zacząć od wypełnionej listy +inna_li = [4, 5, 6] + +# Dodaj na koniec używając "append" +li.append(1) # li to teraz [1] +li.append(2) # li to teraz [1, 2] +li.append(4) # li to teraz [1, 2, 4] +li.append(3) # li to teraz [1, 2, 4, 3] +# Usuwanie z konca da "pop" +li.pop() # => 3 a li stanie się [1, 2, 4] +# Dodajmy ponownie +li.append(3) # li to znowu [1, 2, 4, 3]. + +# Dostęp do list jak do każdej tablicy +li[0] # => 1 +# Użyj = aby nadpisać wcześniej wypełnione miejsca w liście +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Uwaga: ustawiamy starą wartość +# Tak podglądamy ostatni element +li[-1] # => 3 + +# Jeżeli wyjdziesz poza zakres... +li[4] # ... zobaczysz IndexError + +# Możesz tworzyć wyniki. +li[1:3] # => [2, 4] +# Bez początku +li[2:] # => [4, 3] +# Omijamy koniec +li[:3] # => [1, 2, 4] +# Wybierz co drugi +li[::2] # =>[1, 4] +# Odwróć listę +li[::-1] # => [3, 4, 2, 1] +# Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki +# li[paczatek:koniec:krok] + +# Usuń element używając "del" +del li[2] # li to teraz [1, 2, 3] + +# Listy można dodawać +li + inna_li # => [1, 2, 3, 4, 5, 6] +# Uwaga: wartości poszczególnych list się nie zmieniają. + +# Do łączenia list użyj "extend()" +li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] + +# Sprawdź czy jest w liście używając "in" +1 in li # => True + +# "len()" pokazuje długość listy +len(li) # => 6 + + +# Krotki (tuple) są jak listy, ale nie można ich modyfikować. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # wyrzuci TypeError + +# Ale wielu akcji dla list możesz używać przy krotkach +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Można rozpakować krotki i listy do poszczególych zmiennych +a, b, c = (1, 2, 3) # a to teraz 1, b jest 2 a c to 3 +# Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki +d, e, f = 4, 5, 6 +# Popatrz jak prosto zamienić wartości +e, d = d, e # d to teraz 5 a e to 4 + + +# Słowniki są również pożyteczne +pusty_slownik = {} +# Tu tworzymy wypełniony: +pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} + +# Podglądany wartość +pelen_slownik["one"] # => 1 + +# Wypisz wszystkie klucze używając "keys()" +pelen_slownik.keys() # => ["trzy", "dwa", "raz"] +# Uwaga: słowniki nie gwarantują kolejności występowania kluczy. + +# A teraz wszystkie wartości "values()" +pelen_slownik.values() # => [3, 2, 1] +# Uwaga: to samo dotyczy wartości. + +# Sprawdzanie czy występuje to "in" +"raz" in pelen_slownik # => True +1 in pelen_slownik # => False + +# Próba dobrania się do nieistniejącego klucza da KeyError +pelen_slownik["cztery"] # KeyError + +# Użyj "get()" method aby uniknąć KeyError +pelen_slownik.get("raz") # => 1 +pelen_slownik.get("cztery") # => None +# Metoda get zwraca domyślną wartość gdy brakuje klucza +pelen_slownik.get("one", 4) # => 1 +pelen_slownik.get("cztery", 4) # => 4 +# zauważ, że pelen_slownik.get("cztery") jest wciąż => None +# (get nie ustawia wartości słownika) + +# przypisz wartość do klucza podobnie jak w listach +pelen_slownik["cztery"] = 4 # teraz: pelen_slownik["cztery"] => 4 + +# "setdefault()" wstawia do słownika tylko jeśli nie było klucza +pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 +pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 + + +# Teraz zbiory (set) ... cóż zbiory (to po prostu listy ale bez potórzeń) +pusty_zbior = set() +# Inicjalizujemy "set()" pewnymi wartościami +jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) + +# kolejność nie jest gwarantowana, nawet gdy wydaje się posortowane +inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) + +# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru +pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Dodaj więcej elementów przez "add()" +pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} + +# Znajdź przecięcie zbiorów używając & +inny_zbior = {3, 4, 5, 6} +pelen_zbior & other_set # => {3, 4, 5} + +# Suma zbiorów | +pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} + +# Różnicę zbiorów da - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Sprawdzanie obecności w zbiorze: "in". +2 in pelen_zbior # => True +10 in pelen_zbior # => False + + +#################################################### +## 3. Kontrola przepływu +#################################################### + +# Tworzymy zmienną some_var +some_var = 5 + +# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie! +# wypisze "some_var jest mniejsza niż 10" +if some_var > 10: + print("some_var jest wieksza niż 10") +elif some_var < 10: # This elif clause is optional. + print("some_var jest mniejsza niż 10") +else: # This is optional too. + print("some_var jest równa 10") + + +""" +Pętla for iteruje po elementach listy wypisując: + pies to ssak + kot to ssak + mysz to ssak +""" +for zwierze in ["pies", "kot", "mysz"]: + # Możesz użyć % aby stworzyć sformatowane napisy + print("%s to ssak" % zwierze) + +""" +"range(liczba)" zwraca listę liczb +od zera do danej liczby: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While to pętla która jest wykonywana dopóki spełniony jest warunek: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Skrót od x = x + 1 + +# Wyjątki wyłapujemy używając try, except + +# Działa w Pythonie 2.6 i wyższych: +try: + # Użyj "raise" aby wyrzucić wyjąte + raise IndexError("To błąd indeksu") +except IndexError as e: + pass # Pass to brak reakcji na błąd. Zazwyczaj nanosisz tu poprawki. +except (TypeError, NameError): + pass # kilka wyjątków może być przechwyce razem. +else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu + print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. + + +#################################################### +## 4. Funkcjie +#################################################### + +# Użyj "def" aby stworzyć nową funkcję +def dodaj(x, y): + print("x to %s a y to %s" % (x, y)) + return x + y # słówko kluczowe return zwraca wynik działania + +# Tak wywołuje się funkcję z parametrami (args): +dodaj(5, 6) # => wypisze "x to 5 a y to 6" i zwróci 11 + +# Innym sposobem jest wywołanie z parametrami nazwanymi. +dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. + + +# Można też stworzyć funkcję, które przyjmują różną ilość parametrów +# nienazwanych args, co będzie interpretowane jako krotka jeśli nie użyjesz * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Można też stworzyć funkcję, które przyjmują różną ilość parametrów +# nazwanych kwargs, które będa interpretowane jako słownik jeśli nie dasz ** +def keyword_args(**kwargs): + return kwargs + +# Wywołajmy to i sprawdźmy co się dzieje +keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} + + +# Możesz też to pomieszać +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) wyrzuci: + (1, 2) + {"a": 3, "b": 4} +""" + +# Użyj * aby rozwinąć parametry z krotki args +# i użyj ** aby rozwinąć parametry nazwane ze słownika kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # odpowiednik foo(1, 2, 3, 4) +all_the_args(**kwargs) # odpowiednik foo(a=3, b=4) +all_the_args(*args, **kwargs) # odpowiednik foo(1, 2, 3, 4, a=3, b=4) + +# Możesz podać parametry args i kwargs do funkcji równocześnie +# przez rozwinięcie odpowiednio * i ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Zakres widoczności +x = 5 + +def setX(num): + # Lokalna zmienna x nie jest tym samym co zmienna x + x = num # => 43 + print x # => 43 + +def setGlobalX(num): + global x + print x # => 5 + x = num # globalna zmienna to teraz 6 + print x # => 6 + +setX(43) +setGlobalX(6) + +# Można tworzyć funkcje wewnętrzne i zwrócić je jako wynik +def rob_dodawacz(x): + def dodawacz(y): + return x + y + return dodawacz + +dodaj_10 = rob_dodawacz(10) +dodaj_10(3) # => 13 + +# Są również funkcje nienazwane "lambda" +(lambda x: x > 2)(3) # => True + +# Są także wbudowane funkcje wysokiego poziomu +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Można używać wyrażeń listowych do mapowania (map) i filtrowania (filter) +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Klasy +#################################################### + +# Wszystkie klasy są podklasą object +class Czlowiek(object): + + # Atrybut klasy. Występuje we wszystkich instancjach klasy. + gatunek = "H. sapiens" + + # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. + # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają + # obietky lub atrybuty, który żyją tylko w kontrolowanej przez + # użytkownika przestrzeni nazw. Nie używaj ich we własnych metodach. + def __init__(self, nazwa): + # przypisz parametr "nazwa" do atrybutu instancji + self.nazwa = nazwa + + # Metoda instancji. Wszystkie metody biorą "self" jako pierwszy argument + def mow(self, wiadomosc): + return "%s: %s" % (self.nazwa, wiadomosc) + + # Metoda klasowa współdzielona przez instancje. + # Ma wywołującą klasę jako pierwszy argument. + @classmethod + def daj_gatunek(cls): + return cls.gatunek + + # Metoda statyczna jest wywoływana bez argumentów klasy czy instancji. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancja klasy +i = Czlowiek(name="Ian") +print(i.mow("cześć")) # wypisze "Ian: cześć" + +j = Czlowiek("Joel") +print(j.mow("cześć")) # wypisze "Joel: cześć" + +# Wywołujemy naszą metodę klasową +i.daj_gatunek() # => "H. sapiens" + +# Zmieniamy wspólny parametr +Czlowiek.gatunek = "H. neanderthalensis" +i.daj_gatunek() # => "H. neanderthalensis" +j.daj_gatunek() # => "H. neanderthalensis" + +# Wywołanie metody statycznej +Czlowiek.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduły +#################################################### + +# Tak importuje się moduły: +import math +print(math.sqrt(16)) # => 4 + +# Można podać konkretne funkcje, np. ceil, floor z modułu math +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Można zaimportować wszystkie funkcje z danego modułu. +# Ostrzeżenie: nie jest to polecane. +from math import * + +# Można skracać nazwy modułów. +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# sprawdźmy czy funkcje są równoważne +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Moduły pythona to zwykłe skrypty napisane w tym języku. Możesz +# pisać własne i importować je. Nazwa modułu to nazwa pliku. + +# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. +import math +dir(math) + + +#################################################### +## 7. Zaawansowane +#################################################### + +# Generatory pomagają tworzyć tzw. "leniwy kod" +def podwojne_liczby(iterowalne): + for i in iterowalne: + yield i + i + +# Generatory tworzą wartości w locie. +# W przeciwienstwie do wygenerowania wartości raz i ich zachowania, +# powstają one na bieżąco, w wyniku iteracji. To oznacza, że wartości +# większe niż 15 nie będą przetworzone w funkcji "podwojne_liczby". +# Zauważ, że xrange to generator, który wykonuje tę samą operację co range. +# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, +# a xrange tworzy obiekt generatora zamiast tworzyć całą listę jak range. +# Użyto podkreślinika, aby odróżnić nazwę zmiennej od słówka kluczowego +# Pythona. +xrange_ = xrange(1, 900000000) + +# poniższa pętla będzie podwajać liczby aż do 30 +for i in podwojne_liczby(xrange_): + print(i) + if i >= 30: + break + + +# Dekoratory +# w tym przykładzie "beg" jest nakładką na "say" +# Beg wywołuje say. Jeśli say_please jest prawdziwe wtedy wzracana wartość +# zostanie zmieniona + +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Proszę! Jestem spłukany :(") + return msg + return wrapper + + +@beg +def say(say_please=False): + msg = "Kupisz mi piwo?" + return msg, say_please + + +print(say()) # Kupisz mi piwo? +print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( +``` + +## Gotowy na więcej? + +### Darmowe źródła online + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Inne + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + -- cgit v1.2.3 From 348664088768b25f347cbdf96d48222ecc6f0a83 Mon Sep 17 00:00:00 2001 From: dokato Date: Mon, 9 Mar 2015 20:39:16 +0100 Subject: Small changes --- pl-pl/python-pl.html.markdown | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown index 1f4cfd0b..ae6f5ca6 100644 --- a/pl-pl/python-pl.html.markdown +++ b/pl-pl/python-pl.html.markdown @@ -1,4 +1,3 @@ - --- name: python category: language @@ -12,6 +11,7 @@ translators: - ["Dominik Krzemiński", "https://github.com/dokato"] lang: pl-pl --- + Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. Obecnie jest jednym z najbardziej popularnych języków programowania. Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. @@ -23,12 +23,13 @@ Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. ```python +# -*- coding: utf-8 -*- # Pojedyncze komentarze oznaczamy takim symbolem. """ Wielolinijkowe napisy zapisywane są przy użyciu trzech znaków cudzysłowiu i często - wykorzystywane są jako komentarze + wykorzystywane są jako komentarze. """ #################################################### @@ -302,7 +303,7 @@ pelen_zbior & other_set # => {3, 4, 5} # Suma zbiorów | pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} -# Różnicę zbiorów da - +# Różnicę zbiorów da znak - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # Sprawdzanie obecności w zbiorze: "in". @@ -317,7 +318,7 @@ pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} # Tworzymy zmienną some_var some_var = 5 -# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie! +# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie! # wypisze "some_var jest mniejsza niż 10" if some_var > 10: print("some_var jest wieksza niż 10") @@ -611,8 +612,13 @@ print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( ``` ## Gotowy na więcej? +### Polskie + +* [Zanurkuj w Pythonie](http://pl.wikibooks.org/wiki/Zanurkuj_w_Pythonie) +* [LearnPythonPl](http://www.learnpython.org/pl/) -### Darmowe źródła online +### Angielskie: +#### Darmowe źródła online * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) @@ -621,7 +627,7 @@ print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -### Inne +#### Inne * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 48657c4af5db67db5bb5b7ca43bbcd4d61f225ef Mon Sep 17 00:00:00 2001 From: dokato Date: Mon, 9 Mar 2015 20:43:57 +0100 Subject: three bugs fixed --- pl-pl/python-pl.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown index ae6f5ca6..b936faeb 100644 --- a/pl-pl/python-pl.html.markdown +++ b/pl-pl/python-pl.html.markdown @@ -128,7 +128,7 @@ not False # => True # None jest obiektem None # => None -# Nie używaj "==" żeby porównywać obiekty do None +# Nie używaj "==" w celu porównania obiektów z None # Zamiast tego użyj "is" "etc" is None # => False None is None # => True @@ -204,7 +204,7 @@ li[::2] # =>[1, 4] # Odwróć listę li[::-1] # => [3, 4, 2, 1] # Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki -# li[paczatek:koniec:krok] +# li[poczatek:koniec:krok] # Usuń element używając "del" del li[2] # li to teraz [1, 2, 3] @@ -235,7 +235,7 @@ tup[:2] # => (1, 2) 2 in tup # => True # Można rozpakować krotki i listy do poszczególych zmiennych -a, b, c = (1, 2, 3) # a to teraz 1, b jest 2 a c to 3 +a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 # Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki d, e, f = 4, 5, 6 # Popatrz jak prosto zamienić wartości -- cgit v1.2.3 From bb5fcc32d71f9ef3a65e97850c5759da0a055cff Mon Sep 17 00:00:00 2001 From: dokato Date: Tue, 10 Mar 2015 17:52:24 +0100 Subject: email added there is polish and english version now --- pl-pl/python-pl.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown index b936faeb..c3e8287a 100644 --- a/pl-pl/python-pl.html.markdown +++ b/pl-pl/python-pl.html.markdown @@ -17,7 +17,9 @@ Obecnie jest jednym z najbardziej popularnych języków programowania. Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. To po prostu wykonywalny pseudokod. -Zapraszam do kontaktu. Złapiecie mnie na [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] +Zapraszam do kontaktu. Złapiecie nas na: +- kontakt polski: raymon92 [at] [google's email service] +- kontakt angielski: [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. -- cgit v1.2.3 From 8cfb7ba02f7d53b6b33ff5e776289ee4fcb48618 Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Thu, 23 Apr 2015 02:06:43 +0530 Subject: [python/en] Range function arguments. Range function with start and stop. --- python3.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 6c5e1059..470eb6e4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -339,6 +339,18 @@ prints: for i in range(4): print(i) +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + """ While loops go until a condition is no longer met. prints: -- cgit v1.2.3 From a3818d119ea677e1992fa05d5ab130a012086a56 Mon Sep 17 00:00:00 2001 From: Chaitanya Krishna Ande Date: Thu, 23 Apr 2015 13:54:52 +0200 Subject: initial version for latex --- latex.html.markdown | 133 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 latex.html.markdown diff --git a/latex.html.markdown b/latex.html.markdown new file mode 100644 index 00000000..cc1d99cb --- /dev/null +++ b/latex.html.markdown @@ -0,0 +1,133 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] +filename: learn-latex.tex +--- + +LaTeX is known to create aesthetically pleasing documents without you worrying +about the formatting. It is also great if one wants to create documents +containing a lot of mathematics. Getting a good document is very easy, but +getting it to behave exactly the way you want can be a bit hairy. + + +```latex +% All comment lines start with % +% There are no multi-line comments + +% LaTeX is NOT a ``What You See Is What You Get'' word processing software like +% MS Word, or OpenOffice Writer + +% Getting to the final document using LaTeX consists of the following steps: +% 1. Write the document in plain text +% 2. Compile plain text document to produce a pdf +% The compilation step looks something like this: +% $ pdflatex your-tex-file.tex your-tex-file.pdf +% A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +% software. So, you get to see Step 1, but not Step 2 completely. +% Step 2 is still happening behind the scenes. + +% You write all your formatting information in plain text in Step 1. +% The compilation part in Step 2 takes care of producing the document in the +% format you defined in Step 1. + +% For Step 1, it is best if you get a good text editor +% On Windows, probably Notepad++ +% For Step 2, you will need to get a TeX distribution +% Windows: MikTeX +% MacOS: MacTeX +% Linux: Should be available from your package manager + +% Let's get to the final pdf document as soon as possible + +% Choose the kind of document you want to write. +% You can replace article with book, report, etc. +\documentclass{article} +% begin the document +\begin{document} +% end the document +\end{document} +% Compile to pdf +% Now, you already have a final document which of course it is empty. +% Everything that you write is between the +% \begin{document} +% \end{document} + +% Start a new document from here. +% Let's do a decent document +\documentclass{article} +% required for inserting images +\usepackage{graphicx} +% begin the document +\begin{document} +% set the title (optional) +\title{Title of the document} +% set the author (optional) +\author{Chaitanya Krishna Ande} + +% make the title (optional) +\maketitle + +% start the first section +\section{Introduction} + +% write your text +This is the introduction. + +% start another section +\section{Another section} +This is the text for another section. + +% another section with subsection +\section{Section with sub-section} +Text for the section. +\subsection{Sub-section} +Let's discuss the Pythagoras theorem. +\subsubsection{Pythagoras Theorm} +% for cross-reference +\label{subsec:pythagoras} + +% notice how the sections and sub-sections are automatically numbered + +% Some math +% Inline math within $ $ +For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, $b$ and $c$, where $c$ is the +hypotenuse, the following holds: +% Display math with the equation 'environment' +\begin{equation} + c^2 = a^2 + b^2. + % for cross-reference + \label{eq:pythagoras} +\end{equation} + +% Let's cross-reference the equation +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. + +\subsubsection{Figure} +Let's insert a Figure. + +\begin{figure} + \centering + \includegraphics[width=0.8\linewidth]{right-triangle.png} + \caption{Right triangle with sides a, b, c} + \label{fig:right-triangle} +\end{figure} + + +\subsubsection{Table} +Let's insert a Table. + +\begin{table} +\caption{Caption for the Table.} +\begin{tabular}{ccc} +Number & Last Name & First Name \\ +\hline +1 & Biggus & Dickus \\ +2 & Monty & Python +\end{tabular} +\end{table} + +% end the document +\end{document} +``` -- cgit v1.2.3 From 98aa4ef43c84b9bdaa988971174bbb21e042e6ac Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Fri, 24 Apr 2015 01:50:17 +0530 Subject: [python/en] Added range(start, stop). --- python.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 63547bf6..668e04f9 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -346,6 +346,18 @@ prints: for i in range(4): print(i) +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + """ While loops go until a condition is no longer met. prints: -- cgit v1.2.3 From 19f6739cbaa06b6b40b835115a0361f5e77bd0e0 Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Fri, 24 Apr 2015 02:36:54 +0530 Subject: [bash/en] Fixed overflowing line. --- bash.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 3b163638..35bed9a2 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -235,11 +235,13 @@ uniq -d file.txt cut -d ',' -f 1 file.txt # replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) sed -i 's/okay/great/g' file.txt -# print to stdout all lines of file.txt which match some regex, the example prints lines which begin with "foo" and end in "bar" +# print to stdout all lines of file.txt which match some regex +# The example prints lines which begin with "foo" and end in "bar" grep "^foo.*bar$" file.txt # pass the option "-c" to instead print the number of lines matching the regex grep -c "^foo.*bar$" file.txt -# if you literally want to search for the string, and not the regex, use fgrep (or grep -F) +# if you literally want to search for the string, +# and not the regex, use fgrep (or grep -F) fgrep "^foo.*bar$" file.txt -- cgit v1.2.3 From 6b6342a7dc8d4280eb4465894bc15cdd5b7ff383 Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Fri, 24 Apr 2015 22:57:33 +0530 Subject: [python/en] Moved to default python2 print statements. --- python.html.markdown | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 668e04f9..899a97f8 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -145,8 +145,10 @@ bool("") # => False print "I'm Python. Nice to meet you!" # Python also has a print function, available in versions 2.7 and 3... # but for 2.7 you need to add the import (uncommented): -# from __future__ import print_function +from __future__ import print_function print("I'm also Python! ") +# This is useful to maintain compatibility, +# but for this doc, we'll use the python 2 print statement # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores @@ -316,11 +318,11 @@ some_var = 5 # Here is an if statement. Indentation is significant in python! # prints "some_var is smaller than 10" if some_var > 10: - print("some_var is totally bigger than 10.") + print "some_var is totally bigger than 10." elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") + print "some_var is smaller than 10." else: # This is optional too. - print("some_var is indeed 10.") + print "some_var is indeed 10." """ @@ -332,7 +334,7 @@ prints: """ for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings - print("%s is a mammal" % animal) + print "%s is a mammal" % animal """ "range(number)" returns a list of numbers @@ -344,7 +346,7 @@ prints: 3 """ for i in range(4): - print(i) + print i """ "range(lower, upper)" returns a list of numbers @@ -356,7 +358,7 @@ prints: 7 """ for i in range(4, 8): - print(i) + print i """ While loops go until a condition is no longer met. @@ -368,7 +370,7 @@ prints: """ x = 0 while x < 4: - print(x) + print x x += 1 # Shorthand for x = x + 1 # Handle exceptions with a try/except block @@ -391,7 +393,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks # Use "def" to create new functions def add(x, y): - print("x is %s and y is %s" % (x, y)) + print "x is %s and y is %s" % (x, y) return x + y # Return values with a return statement # Calling functions with parameters @@ -420,8 +422,8 @@ keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like def all_the_args(*args, **kwargs): - print(args) - print(kwargs) + print args + print kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) @@ -517,10 +519,10 @@ class Human(object): # Instantiate a class i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +print i.say("hi") # prints out "Ian: hi" j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" +print j.say("hello") # prints out "Joel: hello" # Call our class method i.get_species() # => "H. sapiens" @@ -540,12 +542,12 @@ Human.grunt() # => "*grunt*" # You can import modules import math -print(math.sqrt(16)) # => 4 +print math.sqrt(16) # => 4 # You can get specific functions from a module from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 # You can import all functions from a module. # Warning: this is not recommended @@ -591,7 +593,7 @@ xrange_ = xrange(1, 900000000) # will double all numbers until a result >=30 found for i in double_numbers(xrange_): - print(i) + print i if i >= 30: break @@ -620,8 +622,8 @@ def say(say_please=False): return msg, say_please -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ``` ## Ready For More? -- cgit v1.2.3 From 10ece6fabbed6787c63520004c1491220011afe4 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 24 Apr 2015 11:34:48 -0600 Subject: Fix issue #959 --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 1c577efb..b1143dac 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -127,7 +127,7 @@ __此文本也是__ +或者一个制表符(tab)实现--> This is code So is this -- cgit v1.2.3 From c2963cdc31ea9c0cce9d5abf8b0a6d606d11b3a0 Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Fri, 24 Apr 2015 23:29:01 +0530 Subject: [python/en] Removed python3 print. --- python.html.markdown | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 899a97f8..7281a330 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -141,14 +141,8 @@ bool("") # => False ## 2. Variables and Collections #################################################### -# Python has a print statement, in all 2.x versions but removed from 3. +# Python has a print statement print "I'm Python. Nice to meet you!" -# Python also has a print function, available in versions 2.7 and 3... -# but for 2.7 you need to add the import (uncommented): -from __future__ import print_function -print("I'm also Python! ") -# This is useful to maintain compatibility, -# but for this doc, we'll use the python 2 print statement # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores -- cgit v1.2.3 From 041064416115985ef336babe6ef7dbac726327fa Mon Sep 17 00:00:00 2001 From: Jonathan Scott Duff Date: Fri, 24 Apr 2015 17:07:55 -0500 Subject: Add a link about parrot suspension --- perl6.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b2d7d48c..bcf56800 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -7,11 +7,13 @@ contributors: - ["Nami-Doc", "http://github.com/Nami-Doc"] --- -Perl 6 is a highly capable, feature-rich programming language made for the -upcoming hundred years. +Perl 6 is a highly capable, feature-rich programming language made for at +least the next hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM -and [the MoarVM](http://moarvm.com). +The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on +the JVM and [the MoarVM](http://moarvm.com) and +[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/), +[the Parrot VM](http://parrot.org/). Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. -- cgit v1.2.3 From f3ba1c8a19ae42d296b5b10d50f6254ce2736c23 Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Fri, 24 Apr 2015 22:45:14 -0700 Subject: added italian JSON translation --- it-it/json-it.html.markdown | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 it-it/json-it.html.markdown diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown new file mode 100644 index 00000000..0c401753 --- /dev/null +++ b/it-it/json-it.html.markdown @@ -0,0 +1,62 @@ +--- + +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] +lang: it-it + +--- + +Dato che JSON è un formato per lo scambio di dati estremamente semplice, questo sarà con molta probabilità +il più semplice Learn X in Y Minutes. + +Nella sua forma più pura JSON non ha commenti, ma molti parser accettano +commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sarà +100% JSON valido. Fortunatamente, si spiega da sè. + +```json +{ + "chiave": "valore", + + "chiavi": "devono sempre essere racchiuse tra doppi apici", + "numeri": 0, + "stringhe": "Ciaø, møndø. Tutti gli unicode sono permessi, assieme con l \"escaping\".", + "ha booleani?": true, + "il nulla": null, + + "numero grande": 1.2e+100, + + "oggetti": { + "commento": "La maggior parte della tua struttura viene dagli oggetti.", + + "array": [0, 1, 2, 3, "Gli array possono contenere qualsiasi cosa.", 5], + + "un altro oggetto": { + "commento": "Queste cose possono essere annidate, molto utile." + } + }, + + "sciocchezze": [ + { + "sorgenti di potassio": ["banane"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "stile alternativo": { + "commento": "Guarda quà!" + , "posizione della virgola": "non conta - fintantochè è prima del valore, allora è valida" + , "un altro commento": "che bello" + }, + + "è stato molto breve": "Ed hai finito. Adesso sai tutto cio che JSON ha da offrire." +} +``` -- cgit v1.2.3 From 02bc5183512e1548bfb3a54bacc85443dc33f86d Mon Sep 17 00:00:00 2001 From: James Baker Date: Sun, 26 Apr 2015 09:59:15 +0100 Subject: Standard ML has references Standard ML is not a pure language and has imperative structures like references while and seq --- standard-ml.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index b545f3e1..cc5132f1 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -8,8 +8,8 @@ contributors: Standard ML is a functional programming language with type inference and some side-effects. Some of the hard parts of learning Standard ML are: Recursion, pattern matching, type inference (guessing the right types but never allowing -implicit type conversion). If you have an imperative background, not being able -to update variables can feel severely inhibiting. +implicit type conversion). Standard ML is distinguished from Haskell by including +references, allowing variables to be updated. ```ocaml (* Comments in Standard ML begin with (* and end with *). Comments can be -- cgit v1.2.3 From f8260574d9a29d5302dccf8fb883d5e3d60592d0 Mon Sep 17 00:00:00 2001 From: James Baker Date: Sun, 26 Apr 2015 10:00:21 +0100 Subject: Add examples of imperative-style control Make reference and update, add use of a while and use of seq --- standard-ml.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index cc5132f1..8fc849cb 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -383,6 +383,25 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", "Violets are blue.", "I have a gun.", "Get in the van." ] *) + +(* We can create references to data which can be updated *) +val counter = ref 0 (* Produce a reference with the ref function *) + +(* Assign to a reference with the assignment operator *) +fun set_five reference = reference := 5 + +(* Read a reference with the dereference operator *) +fun equals_five reference = !reference = 5 + +(* We can use while loops for when recursion is messy *) +fun decrement_to_zero r = if !r < 0 + then r := 0 + else while !r >= 0 do r := !r - 1 + +(* This returns the unit value (in practical terms, nothing, a 0-tuple) *) + +(* To allow returning a value, we can use the semicolon to sequence evaluations *) +fun decrement_ret x y = (x := !x - 1; y) ``` ## Further learning -- cgit v1.2.3 From 183ca56459828f567457337204c7ef10351a31f0 Mon Sep 17 00:00:00 2001 From: James Baker Date: Sun, 26 Apr 2015 10:01:36 +0100 Subject: Add myself as a contributor --- standard-ml.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 8fc849cb..07896beb 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -3,6 +3,7 @@ language: "Standard ML" contributors: - ["Simon Shine", "http://shine.eu.org/"] - ["David Pedersen", "http://lonelyproton.com/"] + - ["James Baker", "http://www.jbaker.io/"] --- Standard ML is a functional programming language with type inference and some -- cgit v1.2.3 From e89ee08e73d30fdd2911d69560f5000d907d4b7e Mon Sep 17 00:00:00 2001 From: "Andreas L. F" Date: Sun, 26 Apr 2015 11:57:30 +0200 Subject: =?UTF-8?q?Made=20no-nb=20dir=20(Norwegian=20Bokm=C3=A5l)=20and=20?= =?UTF-8?q?copied=20bash,=20translated=20ca=201/2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- no-nb/bash-no.html.markdown | 279 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 279 insertions(+) create mode 100644 no-nb/bash-no.html.markdown diff --git a/no-nb/bash-no.html.markdown b/no-nb/bash-no.html.markdown new file mode 100644 index 00000000..746643f5 --- /dev/null +++ b/no-nb/bash-no.html.markdown @@ -0,0 +1,279 @@ +--- +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/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] +filename: LearnBash-no.sh +translators: + - ["Andreas Lindahl Flåten", "https://github.com/anlif"] +lang: no-nb +--- +Bash er navnet på unix skallet, som også var distribuert som skallet for GNU +operativsystemet og som standard skall på de fleste Linux distribusjoner og +Mac OS X. + +[Les mer her.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Den første linjen i et bash skript starter med `#!' (shebang) +# etterfulgt av stien til bash http://en.wikipedia.org/wiki/Shebang_(Unix) +# Kommentarer starter med #. + +# Enkelt hello world eksempel: +echo Hello world! + +# Hver kommando starter på en ny linje, eller etter et semikolon: +echo 'Dette er den første linjen'; echo 'Dette er en andre linjen' + +# Deklarering av en variabel ser slik ut: +VARIABLE="En tekststreng" + +# Men ikke slik: +VARIABLE = "En tekststreng" +# Bash vil tolke dette som at VARIABLE er en kommando den skal kjøre +# og gi en feilmelding dersom kommandoen ikke finnes + +# Bruk av den nydeklarerte variabelen: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Når du bruker variabelen - setter verdien, eksporterer den, og linkende - +# skriver du navnet dens uten $. Hvis du vil bruke variabelens verdi, +# skriver du $ før variabelnavnet. + +# Strenginnhold i en variabel kan erstattes på følgende måte: +echo ${VARIABLE/tull/ball} +# Dette vil erstatte første forekomst av `tull' med `ball' + +# Substreng (delstreng) av en variabel: +echo ${VARIABLE:0:7} +# Dette vil returnere de første 7 tegnene i en strengvariabel + +# Å angi en standardverdi dersom en variabel er udeklarert gjøres slik: +echo ${FOO:-"StandardVerdiDersomFOOErTom"} +# Dette fungerer for null (FOO=), tom streng (FOO="") og tallet null (FOO=0) + +# Det finnes en rekke hendige innebygde variable, eksempel: +echo "Siste programs returnerte verdi: $?" +echo "Skript's PID: $$" +echo "Antall argumenter: $#" +echo "Alle argumenter til skriptet: $@" +echo "Argumenter til skriptet i egne variable: $1 $2..." + +# Lesing av input: +echo "Hva heter du?" +read NAME # variabelen NAME blir automatisk deklarert av `read' kommandoen +echo Hei, $NAME! + +# if setninger ser slik ut: +# se 'man test' for mer informasjon om betingelser +if [ $NAME -ne $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# Det finnes også betinget eksekvering +echo "Kjøres alltid" || echo "Kjøres kun dersom første kommando feilet" +echo "Kjøres alltid" && echo "Kjøres kun dersom første kommando IKKE feilet" + +# For å bruke && (logisk OG) og || (logisk ELLER) sammen med if setninger, +# trenger man par av firkantklammer [] på hver side av et logisk uttrykk: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "Dette kjører dersom $NAME er Steve OG $AGE er lik 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "Dette kjører dersom $NAME er Daniya ELLER Zach." +fi + +# Matematiske uttrykk skrives slik: +echo $(( 10 + 5 )) + +# Ulikt de fleste programmeringsspråk, så er bash et skall - det medfører at en +# kommando i et skript kjører i en bestemt mappe i filsystemet. Du kan skrive +# ut innholdet i nåværende mappe med ls kommandoen: +ls + +# Kommandoen har parametre som kontrollerer hvordan kommandoen utføres: +ls -l # Skriv hver fil og mappe på sin egen linje + +# Resultatet av forrige kommando kan bli sendt til neste kommando som input. +# grep kommandoen filtrerer input ved hjelp av et regulært uttrykk. +# Ved å bruke grep kan vi skrive ut kun .txt filer på følgende måte: +ls -l | grep "\.txt" # lær mer om grep ved å skrive 'man grep' + +# You can redirect command input and output (stdin, stdout, and stderr). +# Read from stdin until ^EOF$ and overwrite hello.py with the lines +# between "EOF": + +# Input og output fra filer kan dirigeres (stdin, stdout og stderr). +# "cat" kommandoen uten argumenter skriver fra stdin til stdout. +# I det følgende eksempelet overskrives filen hello.py med linjene mellom EOF. +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import 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 + +# Kjør hello.py with ulike stdin, stdout, and stderr omdirigeringer: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# ">" operatoren overskriver filen dersom den finnes. +# Hvis du heller vil legge til på slutten av en eksisterende fil, bruk ">>" +python hello.py >> "output.out" 2>> "error.err" + +# Overskriv output.txt, legg til error.err, og tell antall linjer med "wc": +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Run a command and print its file descriptor (e.g. /dev/fd/123) +# see: man fd +echo <(echo "#helloworld") + +# Overwrite output.txt with "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Cleanup temporary files verbosely (add '-i' for interactive) +rm -v output.out error.err output-and-error.log + +# Commands can be substituted within other commands using $( ): +# The following command displays the number of files and directories in the +# current directory. +echo "There are $(ls | wc -l) items here." + +# The same can be done using backticks `` but they can't be nested - the preferred way +# is to use $( ). +echo "There are `ls | wc -l` items here." + +# Bash uses a case statement that works similarly to switch in Java and C++: +case "$VARIABLE" in + #List patterns for the conditions you want to meet + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# for loops iterate for as many arguments given: +# The contents of $VARIABLE is printed three times. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# Or write it the "traditional for loop" way: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# They can also be used to act on files.. +# This will run the command 'cat' on file1 and file2 +for VARIABLE in file1 file2 +do + cat "$VARIABLE" +done + +# ..or the output from a command +# This will cat the output from ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# while loop: +while [ true ] +do + echo "loop body here..." + break +done + +# You can also define functions +# Definition: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# or simply +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# Calling your function +foo "My name is" $NAME + +# There are a lot of useful commands you should learn: +# prints last 10 lines of file.txt +tail -n 10 file.txt +# prints first 10 lines of file.txt +head -n 10 file.txt +# sort file.txt's lines +sort file.txt +# report or omit repeated lines, with -d it reports them +uniq -d file.txt +# prints only the first column before the ',' character +cut -d ',' -f 1 file.txt +# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) +sed -i 's/okay/great/g' file.txt +# print to stdout all lines of file.txt which match some regex +# The example prints lines which begin with "foo" and end in "bar" +grep "^foo.*bar$" file.txt +# pass the option "-c" to instead print the number of lines matching the regex +grep -c "^foo.*bar$" file.txt +# if you literally want to search for the string, +# and not the regex, use fgrep (or grep -F) +fgrep "^foo.*bar$" file.txt + + +# Read Bash shell builtins documentation with the bash 'help' builtin: +help +help help +help for +help return +help source +help . + +# Read Bash manpage documentation with man +apropos bash +man 1 bash +man bash + +# Read info documentation with info (? for help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Read bash info documentation: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 6e6378f139f15ae43f248b594240c0056c23af53 Mon Sep 17 00:00:00 2001 From: "Andreas L. F" Date: Sun, 26 Apr 2015 16:19:16 +0200 Subject: translating done --- no-nb/bash-no.html.markdown | 113 ++++++++++++++++++++------------------------ 1 file changed, 52 insertions(+), 61 deletions(-) diff --git a/no-nb/bash-no.html.markdown b/no-nb/bash-no.html.markdown index 746643f5..ab0c064f 100644 --- a/no-nb/bash-no.html.markdown +++ b/no-nb/bash-no.html.markdown @@ -23,7 +23,7 @@ Mac OS X. ```bash #!/bin/bash -# Den første linjen i et bash skript starter med `#!' (shebang) +# Den første linjen i et bash skript starter med '#!' (shebang) # etterfulgt av stien til bash http://en.wikipedia.org/wiki/Shebang_(Unix) # Kommentarer starter med #. @@ -45,15 +45,15 @@ VARIABLE = "En tekststreng" echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' -# Når du bruker variabelen - setter verdien, eksporterer den, og linkende - +# Når du bruker variabelen, for eksempel setter verdien eller eksporterer den, # skriver du navnet dens uten $. Hvis du vil bruke variabelens verdi, # skriver du $ før variabelnavnet. # Strenginnhold i en variabel kan erstattes på følgende måte: echo ${VARIABLE/tull/ball} -# Dette vil erstatte første forekomst av `tull' med `ball' +# Dette vil erstatte første forekomst av 'tull' med 'ball' -# Substreng (delstreng) av en variabel: +# Substreng av en variabel: echo ${VARIABLE:0:7} # Dette vil returnere de første 7 tegnene i en strengvariabel @@ -70,7 +70,7 @@ echo "Argumenter til skriptet i egne variable: $1 $2..." # Lesing av input: echo "Hva heter du?" -read NAME # variabelen NAME blir automatisk deklarert av `read' kommandoen +read NAME # variabelen NAME blir automatisk deklarert av 'read' kommandoen echo Hei, $NAME! # if setninger ser slik ut: @@ -114,12 +114,8 @@ ls -l # Skriv hver fil og mappe på sin egen linje # Ved å bruke grep kan vi skrive ut kun .txt filer på følgende måte: ls -l | grep "\.txt" # lær mer om grep ved å skrive 'man grep' -# You can redirect command input and output (stdin, stdout, and stderr). -# Read from stdin until ^EOF$ and overwrite hello.py with the lines -# between "EOF": - # Input og output fra filer kan dirigeres (stdin, stdout og stderr). -# "cat" kommandoen uten argumenter skriver fra stdin til stdout. +# 'cat' kommandoen uten argumenter skriver fra stdin til stdout. # I det følgende eksempelet overskrives filen hello.py med linjene mellom EOF. cat > hello.py << EOF #!/usr/bin/env python @@ -131,128 +127,123 @@ for line in sys.stdin: print(line, file=sys.stdout) EOF -# Kjør hello.py with ulike stdin, stdout, and stderr omdirigeringer: +# Kjør hello.py (et python skript) +# med ulike stdin, stdout, and stderr omdirigeringer: python hello.py < "input.in" python hello.py > "output.out" python hello.py 2> "error.err" python hello.py > "output-and-error.log" 2>&1 python hello.py > /dev/null 2>&1 -# ">" operatoren overskriver filen dersom den finnes. -# Hvis du heller vil legge til på slutten av en eksisterende fil, bruk ">>" +# '>' operatoren overskriver filen dersom den finnes. +# Hvis du heller vil legge til på slutten av en eksisterende fil, bruk '>>' python hello.py >> "output.out" 2>> "error.err" -# Overskriv output.txt, legg til error.err, og tell antall linjer med "wc": +# Overskriv output.txt, legg til error.err, og tell antall linjer med 'wc': info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err # Run a command and print its file descriptor (e.g. /dev/fd/123) -# see: man fd +# Kjør en kommando og print tilhørende 'file descriptor' +# se 'man fd' echo <(echo "#helloworld") -# Overwrite output.txt with "#helloworld": +# Ulike måter å overskrive output.out med '#helloworld': cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null -# Cleanup temporary files verbosely (add '-i' for interactive) +# Slett noen filer med økt verbositet '-v', legg til '-i' for interaktiv modus rm -v output.out error.err output-and-error.log -# Commands can be substituted within other commands using $( ): -# The following command displays the number of files and directories in the -# current directory. +# Kommandoer kan kjøres i deklarasjonen av andre kommandoer ved å bruke $( ): +# Følgende kommando skriver antall filer og mapper i nåværende mappe echo "There are $(ls | wc -l) items here." -# The same can be done using backticks `` but they can't be nested - the preferred way -# is to use $( ). +# Det samme kan gjøres med backticks `` men de kan ikke være nøstede, +# det anbefales å bruke $( ) slik som i forrige eksempel. echo "There are `ls | wc -l` items here." -# Bash uses a case statement that works similarly to switch in Java and C++: +# Bash har en 'case' setning som fungerer omtrent som en 'switch' i Java/C: case "$VARIABLE" in - #List patterns for the conditions you want to meet + # Skriv ønskede match med tilhørende kommandoer 0) echo "There is a zero.";; 1) echo "There is a one.";; *) echo "It is not null.";; esac -# for loops iterate for as many arguments given: -# The contents of $VARIABLE is printed three times. +# for løkker kan iterere over en mengde argumenter: for VARIABLE in {1..3} do echo "$VARIABLE" done -# Or write it the "traditional for loop" way: +# Eller vi kan skrive en for løkke omtrent slik det kan gjøres i Java/C: for ((a=1; a <= 3; a++)) do echo $a done -# They can also be used to act on files.. -# This will run the command 'cat' on file1 and file2 -for VARIABLE in file1 file2 -do - cat "$VARIABLE" -done - -# ..or the output from a command -# This will cat the output from ls. +# Man kan også iterere over resultatet av en annen kommando. for OUTPUT in $(ls) do cat "$OUTPUT" done -# while loop: +# while løkke, se if setninger: while [ true ] do echo "loop body here..." break done -# You can also define functions -# Definition: +# Man kan også definere funksjoner. +# Definisjon: function foo () { - echo "Arguments work just like script arguments: $@" - echo "And: $1 $2..." - echo "This is a function" + echo "Argumenter fungerer akkurat som skript argumenter: $@" + echo "Og: $1 $2..." + echo "Dette er en funksjon" return 0 } -# or simply +# eller bare: bar () { - echo "Another way to declare functions!" + echo "En annen måte å deklarere en funksjon." return 0 } -# Calling your function -foo "My name is" $NAME +# Å kalle en funksjon: +foo "Mitt navn er" $NAME # There are a lot of useful commands you should learn: # prints last 10 lines of file.txt +# Det er mange nyttige kommandoer du bør lære deg: +# "tail" skriver ut slutten av en fil, i dette tilfellet de siste 10 linjene tail -n 10 file.txt -# prints first 10 lines of file.txt +# skriv ut de første 10 linjene av file.txt head -n 10 file.txt -# sort file.txt's lines +# sorter linjene i file.txt ("man sort") sort file.txt -# report or omit repeated lines, with -d it reports them +# skriv ut eller fjern repeterte linjer, med -d skrives de ut uniq -d file.txt -# prints only the first column before the ',' character +# skriver kun den første kolonnen før ',' tegnet cut -d ',' -f 1 file.txt -# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) -sed -i 's/okay/great/g' file.txt -# print to stdout all lines of file.txt which match some regex -# The example prints lines which begin with "foo" and end in "bar" +# erstatter hvert tilfelle av 'bjarne' med 'alfa' i file.txt, +# sed støtter regulære uttrykk ("man sed"). +sed -i 's/bjarne/alfa/g' file.txt +# skriv til stdout alle linjer i file.txt som matches av et regulært uttrykk +# eksempelet skriver ut alle linjer som begynner med "foo" og slutter med "bar" grep "^foo.*bar$" file.txt -# pass the option "-c" to instead print the number of lines matching the regex +# skriv "-c" hvis du heller vil vite antall linjer som matcher grep -c "^foo.*bar$" file.txt -# if you literally want to search for the string, -# and not the regex, use fgrep (or grep -F) +# hvis du vil matche en bestemt streng, og ikke et regulært uttrykk +# bruker du enten "fgrep" eller ekvivalenten "grep -f" fgrep "^foo.*bar$" file.txt -# Read Bash shell builtins documentation with the bash 'help' builtin: +# Les Bash sin egen dokumentasjon om innebygde konstruksjoner: help help help help for @@ -260,18 +251,18 @@ help return help source help . -# Read Bash manpage documentation with man +# Les Bash sin "manpage": apropos bash man 1 bash man bash -# Read info documentation with info (? for help) +# Les "info" dokumentasjon: apropos info | grep '^info.*(' man info info info info 5 info -# Read bash info documentation: +# Les bash sin info dokumentasjon: info bash info bash 'Bash Features' info bash 6 -- cgit v1.2.3 From 7d5368eda1e2402b6b2bed85586fde0c6af87816 Mon Sep 17 00:00:00 2001 From: MoreMoschops Date: Sun, 26 Apr 2015 15:33:29 +0100 Subject: Neither gcc nor clang accept void main. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neither gcc nor clang accept void main. Remove this bad information. Tested as follows: $ cat 045.cpp void main() { } $ g++ 045.cpp 045.cpp:1:11: error: ‘::main’ must return ‘int’ void main() ^ $ clang++ 045.cpp 045.cpp:1:1: error: 'main' must return 'int' void main() ^~~~ int 1 error generated. $ g++ --version g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 $ clang++ --version Ubuntu clang version 3.4.2-3ubuntu2~xedgers (tags/RELEASE_34/dot2-final) (based on LLVM 3.4.2) --- c++.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 1a84efa4..ae93ceba 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -32,8 +32,7 @@ one of the most widely-used programming languages. // variable declarations, primitive types, and functions. // Just like in C, your program's entry point is a function called -// main with an integer return type, -// though void main() is also accepted by most compilers (gcc, clang, etc.) +// main with an integer return type. // This value serves as the program's exit status. // See http://en.wikipedia.org/wiki/Exit_status for more information. int main(int argc, char** argv) -- cgit v1.2.3 From 9d3462953604d0d331191bb1fca82295e1ece6ed Mon Sep 17 00:00:00 2001 From: Etan Reisner Date: Sun, 26 Apr 2015 13:22:48 -0400 Subject: Add myself as a contributor. --- bash.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/bash.html.markdown b/bash.html.markdown index 35bed9a2..b9cd53ff 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] filename: LearnBash.sh --- -- cgit v1.2.3 From e2ca2c9550474ca3dad0f7ef8735e614da081258 Mon Sep 17 00:00:00 2001 From: Etan Reisner Date: Sun, 26 Apr 2015 13:32:41 -0400 Subject: Add another very common shell variable assignment mistake. --- bash.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index b9cd53ff..77ee37f6 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -37,7 +37,14 @@ VARIABLE="Some string" # But not like this: VARIABLE = "Some string" # Bash will decide that VARIABLE is a command it must execute and give an error -# because it couldn't be found. +# because it can't be found. + +# Or like this: +Variable= 'Some string' +# Bash will decide that 'Some string' is a command it must execute and give an +# error because it can't be found. (In this case the 'Variable=' part is seen +# as a variable assignment valid only for the scope of the 'Some string' +# command.) # Using the variable: echo $VARIABLE -- cgit v1.2.3 From 745ce28d7e72a1de6a1a386f91f8fcae0c99b324 Mon Sep 17 00:00:00 2001 From: Tiddo Langerak Date: Mon, 27 Apr 2015 10:16:16 +0200 Subject: Fixed haskell foldr example For #1068 --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index f28fcfe7..6a64442f 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -282,7 +282,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- This is now the same as -(2 * 3 + (2 * 2 + (2 * 1 + 4))) +(2 * 1 + (2 * 2 + (2 * 3 + 4))) ---------------------------------------------------- -- 7. Data Types -- cgit v1.2.3 From aa11cc659de990a6c4d4104bcc733f373b079ae7 Mon Sep 17 00:00:00 2001 From: Etan Reisner Date: Mon, 27 Apr 2015 07:30:17 -0400 Subject: Follow variable capitalization on this branch. --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 77ee37f6..e0c12f97 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -40,9 +40,9 @@ VARIABLE = "Some string" # because it can't be found. # Or like this: -Variable= 'Some string' +VARIABLE= 'Some string' # Bash will decide that 'Some string' is a command it must execute and give an -# error because it can't be found. (In this case the 'Variable=' part is seen +# error because it can't be found. (In this case the 'VARIABLE=' part is seen # as a variable assignment valid only for the scope of the 'Some string' # command.) -- cgit v1.2.3 From 1cf3a8d797a25071470e6b529aa7db6a54f0b4ab Mon Sep 17 00:00:00 2001 From: Fabio Souto Date: Mon, 27 Apr 2015 17:03:00 +0200 Subject: Added missing section and fixes some typos --- es-es/python-es.html.markdown | 120 +++++++++++++++++++++++++++++++++--------- 1 file changed, 96 insertions(+), 24 deletions(-) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index f7a0ec02..4930eebc 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Fabio Souto", "http://fabiosouto.me"] lang: es-es filename: learnpython-es.py --- @@ -30,27 +31,47 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl # Tienes números 3 #=> 3 -# Matemática es lo que esperarías -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 +# Evidentemente puedes realizar operaciones matemáticas +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 # La división es un poco complicada. Es división entera y toma la parte entera # de los resultados automáticamente. -5 / 2 #=> 2 +5 / 2 #=> 2 # Para arreglar la división necesitamos aprender sobre 'floats' # (números de coma flotante). 2.0 # Esto es un 'float' -11.0 / 4.0 #=> 2.75 ahhh...mucho mejor +11.0 / 4.0 #=> 2.75 ahhh...mucho mejor + +# Resultado de la división de enteros truncada para positivos y negativos +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona con números en coma flotante +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# El operador módulo devuelve el resto de una división entre enteros +7 % 3 # => 1 + +# Exponenciación (x elevado a y) +2**4 # => 16 # Refuerza la precedencia con paréntesis -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 #=> 8 + +# Operadores booleanos +# Nota: "and" y "or" son sensibles a mayúsculas +True and False #=> False +False or True #=> True -# Valores 'boolean' (booleanos) son primitivos -True -False +# Podemos usar operadores booleanos con números enteros +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True # Niega con 'not' not True #=> False @@ -90,7 +111,7 @@ not False #=> True # Una forma más reciente de formatear strings es el método 'format'. # Este método es la forma preferida "{0} pueden ser {1}".format("strings", "formateados") -# Puedes usar palabras claves si no quieres contar. +# Puedes usar palabras clave si no quieres contar. "{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") # None es un objeto @@ -107,8 +128,8 @@ None is None #=> True # None, 0, y strings/listas vacíos(as) todas se evalúan como False. # Todos los otros valores son True -0 == False #=> True -"" == False #=> True +bool(0) #=> False +bool("") #=> False #################################################### @@ -130,16 +151,16 @@ otra_variable # Levanta un error de nombre # 'if' puede ser usado como una expresión "yahoo!" if 3 > 2 else 2 #=> "yahoo!" -# Listas almacenan secuencias +# Las listas almacenan secuencias lista = [] # Puedes empezar con una lista prellenada otra_lista = [4, 5, 6] # Añadir cosas al final de una lista con 'append' -lista.append(1) #lista ahora es [1] -lista.append(2) #lista ahora es [1, 2] -lista.append(4) #lista ahora es [1, 2, 4] -lista.append(3) #lista ahora es [1, 2, 4, 3] +lista.append(1) # lista ahora es [1] +lista.append(2) # lista ahora es [1, 2] +lista.append(4) # lista ahora es [1, 2, 4] +lista.append(3) # lista ahora es [1, 2, 4, 3] # Remueve del final de la lista con 'pop' lista.pop() #=> 3 y lista ahora es [1, 2, 4] # Pongámoslo de vuelta @@ -173,11 +194,11 @@ lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] # Chequea la existencia en una lista con 1 in lista #=> True -# Examina el largo de una lista con 'len' +# Examina el tamaño de una lista con 'len' len(lista) #=> 6 -# Tuplas son como listas pero son inmutables. +# Las tuplas son como las listas, pero son inmutables. tupla = (1, 2, 3) tupla[0] #=> 1 tupla[0] = 3 # Levanta un error TypeError @@ -266,7 +287,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} # Hagamos sólo una variable una_variable = 5 -# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python! # imprime "una_variable es menor que 10" if una_variable > 10: print "una_variable es completamente mas grande que 10." @@ -400,12 +421,12 @@ class Humano(object): # Un atributo de clase es compartido por todas las instancias de esta clase especie = "H. sapiens" - # Constructor basico + # Constructor básico, se llama al instanciar la clase. def __init__(self, nombre): # Asigna el argumento al atributo nombre de la instancia self.nombre = nombre - # Un metodo de instancia. Todos los metodos toman self como primer argumento + # Un método de instancia. Todos los metodos toman self como primer argumento def decir(self, msg): return "%s: %s" % (self.nombre, msg) @@ -470,6 +491,56 @@ import math dir(math) +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores permiten evaluación perezosa +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador crea valores sobre la marcha +# En vez de generar y devolver todos los valores de una vez, crea un valor +# en cada iteración. En este ejemplo los valores mayores que 15 no serán +# procesados en duplicar_numeros. +# Nota: xrange es un generador que hace lo mismo que range. +# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio. +# xrange crea un generador, mientras que range crea toda la lista. +# Añadimos un guion bajo a los nombres de variable que coinciden con palabras +# reservadas de python. +xrange_ = xrange(1, 900000000) + +# duplica todos los números hasta que encuentra un resultado >= 30 +for i in duplicar_numeros(xrange_): + print i + if i >= 30: + break + +# Decoradores +# en este ejemplo pedir rodea a hablar +# Si por_favor es True se cambiará el mensaje. +from functools import wraps + + +def pedir(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, por_favor = target_function(*args, **kwargs) + if por_favor: + return "{} {}".format(msg, "¡Por favor! Soy pobre :(") + return msg + + return wrapper + + +@pedir +def hablar(por_favor=False): + msg = "¿Me puedes comprar una cerveza?" + return msg, por_favor + +print hablar() # ¿Me puedes comprar una cerveza? +print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :( ``` ## ¿Listo para más? @@ -481,6 +552,7 @@ dir(math) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Encuadernados -- cgit v1.2.3 From 5bff1e956ef8003eddfcb64ffdc1161ee3d622bc Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 30 Apr 2015 16:49:49 +0200 Subject: Create typescript-fr.html.markdown Translate the reading block, the introduction part and the type part. --- fr-fr/typescript-fr.html.markdown | 171 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 fr-fr/typescript-fr.html.markdown diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown new file mode 100644 index 00000000..e87bacac --- /dev/null +++ b/fr-fr/typescript-fr.html.markdown @@ -0,0 +1,171 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +filename: learntypescript-fr.ts +lang: fr-fr +--- + +TypeScript est un langage visant à faciliter le developpement d'applications large et scalable écrite en JavaScript. +TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionel) à JavaScript. +C'est une surcouche à JavaScript: tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le compilateur TypeScript émet du JavaScript. + +Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/). + +Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et voir directement le rendu JavaScript. + +```js +// Il y a 3 types basiques en in TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Quand c'est impossible de savoir, il ya le type `Any` +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // ok, définitvement un booléen + +// Pour les collections, il y a les tableaux typés et les tableaux génériques +var list: number[] = [1, 2, 3]; // Un tableaux typé +var list: Array = [1, 2, 3]; // un tableau générique + +// Pour les énumeration +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Enfin, `void` est utilisé dans le cas spécifique d'une fonction ne retournant rien +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Functions are first class citizens, support the lambda "fat arrow" syntax and +// use type inference + +// The following are equivalent, the same signature will be infered by the +// compiler, and same JavaScript will be emitted +var f1 = function(i: number): number { return i * i; } +// Return type inferred +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Return type inferred +var f4 = (i: number) => { return i * i; } +// Return type inferred, one-liner means no return keyword needed +var f5 = (i: number) => i * i; + +// Interfaces are structural, anything that has the properties is compliant with +// the interface +interface Person { + name: string; + // Optional properties, marked with a "?" + age?: number; + // And of course functions + move(): void; +} + +// Object that implements the "Person" interface +// Can be treated as a Person since it has the name and move properties +var p: Person = { name: "Bobby", move: () => {} }; +// Objects that have the optional property: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Is not a person because age is not a number +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Interfaces can also describe a function type +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Only the parameters' types are important, names are not important. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - members are public by default +class Point { + // Properties + x: number; + + // Constructor - the public/private keywords in this context will generate + // the boiler plate code for the property and the initialization in the + // constructor. + // In this example, "y" will be defined just like "x" is, but with less code + // Default values are also supported + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Static members + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y will be 0 + +// Inheritance +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Explicit call to the super class constructor is mandatory + } + + // Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modules, "." can be used as separator for sub modules +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Local alias for referencing a module +import G = Geometry; + +var s2 = new G.Square(10); + +// Generics +// Classes +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Pair { + item1: T; + item2: T; +} + +// And functions +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Including references to a definition file: +/// + +``` + +## Lectures complémentaires + * [Site officiel de TypeScript] (http://www.typescriptlang.org/) + * [Spécification du langage TypeScript (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Code source sur GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From 6f96532a59012aa1041aaf671c160396a7819167 Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 30 Apr 2015 17:12:54 +0200 Subject: Update typescript-fr.html.markdown Translate functions block --- fr-fr/typescript-fr.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown index e87bacac..718a5e9a 100644 --- a/fr-fr/typescript-fr.html.markdown +++ b/fr-fr/typescript-fr.html.markdown @@ -10,19 +10,19 @@ lang: fr-fr TypeScript est un langage visant à faciliter le developpement d'applications large et scalable écrite en JavaScript. TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionel) à JavaScript. -C'est une surcouche à JavaScript: tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le compilateur TypeScript émet du JavaScript. +C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur. Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/). Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et voir directement le rendu JavaScript. ```js -// Il y a 3 types basiques en in TypeScript +// Il y a 3 types basiques en TypeScript var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -// Quand c'est impossible de savoir, il ya le type `Any` +// Quand c'est impossible à déterminer, on utilise le type `Any` var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // ok, définitvement un booléen @@ -40,18 +40,18 @@ function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -// Functions are first class citizens, support the lambda "fat arrow" syntax and -// use type inference +// Les fontions sont des entités de première classe. Elles supportent les expressions lambda et +// utilisent l'inférence de types -// The following are equivalent, the same signature will be infered by the -// compiler, and same JavaScript will be emitted +// Les fonctions ci-dessous sont équivalentes, une signature identique sera inférée par le compilateur, +// et le même JavaScript sera généré var f1 = function(i: number): number { return i * i; } -// Return type inferred +// Retourne un type inféré var f2 = function(i: number) { return i * i; } var f3 = (i: number): number => { return i * i; } -// Return type inferred +// Retourne un type inféré var f4 = (i: number) => { return i * i; } -// Return type inferred, one-liner means no return keyword needed +// Retourne un type inféré, ici le mot clé `return` n'est pas nécessaire var f5 = (i: number) => i * i; // Interfaces are structural, anything that has the properties is compliant with -- cgit v1.2.3 From 0964b9e1edff08d0d4bc570a9fad135e2da45d62 Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 30 Apr 2015 18:42:13 +0200 Subject: Update typescript-fr.html.markdown Add classe block --- fr-fr/typescript-fr.html.markdown | 59 +++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown index 718a5e9a..9e6ee171 100644 --- a/fr-fr/typescript-fr.html.markdown +++ b/fr-fr/typescript-fr.html.markdown @@ -32,7 +32,7 @@ var list: number[] = [1, 2, 3]; // Un tableaux typé var list: Array = [1, 2, 3]; // un tableau générique // Pour les énumeration -enum Color {Red, Green, Blue}; +enum Color { Red, Green, Blue }; var c: Color = Color.Green; // Enfin, `void` est utilisé dans le cas spécifique d'une fonction ne retournant rien @@ -54,73 +54,70 @@ var f4 = (i: number) => { return i * i; } // Retourne un type inféré, ici le mot clé `return` n'est pas nécessaire var f5 = (i: number) => i * i; -// Interfaces are structural, anything that has the properties is compliant with -// the interface +// Les interfaces sont structurés, tout ce qui a les propriétés est compatible avec +// l'interface interface Person { name: string; - // Optional properties, marked with a "?" + // Les propriétés optionnelles sont identifiées avec un "?" age?: number; - // And of course functions + // Et bien sûr, les fonctions move(): void; } -// Object that implements the "Person" interface -// Can be treated as a Person since it has the name and move properties +// Un objet implémentant l'interface "Person" peut être traité comme +// une Person car il a les propriétés "name" et "move" var p: Person = { name: "Bobby", move: () => {} }; -// Objects that have the optional property: -var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; -// Is not a person because age is not a number -var invalidPerson: Person = { name: "Bobby", age: true }; +// Des objets implémentants la propriété optionnelle : +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; // valide car "age" est un nombre +var invalidPerson: Person = { name: "Bobby", age: true }; // invalide car "age" n'est pas un nombre -// Interfaces can also describe a function type +// Les interfaces peuvent aussi décrire un type de fonction interface SearchFunc { (source: string, subString: string): boolean; } -// Only the parameters' types are important, names are not important. +// Seul les types des paramètres sont importants, les noms ne le sont pas var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -// Classes - members are public by default +// Les membres des classes sont publiques par défaut class Point { - // Properties + // Propriétés x: number; - // Constructor - the public/private keywords in this context will generate - // the boiler plate code for the property and the initialization in the - // constructor. - // In this example, "y" will be defined just like "x" is, but with less code - // Default values are also supported - + // Constructeur - Les mots clés "public" et "private" dans ce contexte génèrent + // le code de la propriété et son initialisation dans le constructeur. + // Dans cet exemple, "y" sera défini de la même façon que "x", mais avec moins de code + // Les valeurs par défaut sont supportées constructor(x: number, public y: number = 0) { this.x = x; } - // Functions + // Fonctions dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - // Static members + // Membres statiques static origin = new Point(0, 0); } var p1 = new Point(10 ,20); var p2 = new Point(25); //y will be 0 -// Inheritance +// Héritage class Point3D extends Point { constructor(x: number, y: number, public z: number = 0) { - super(x, y); // Explicit call to the super class constructor is mandatory + super(x, y); // Un appel explicite au constructeur de la super classe est obligatoire. } - // Overwrite + // Redéfinition dist() { var d = super.dist(); return Math.sqrt(d * d + this.z * this.z); } } -// Modules, "." can be used as separator for sub modules +// Modules, "." peut être utilisé comme un séparateur de sous modules. module Geometry { export class Square { constructor(public sideLength: number = 0) { @@ -133,12 +130,12 @@ module Geometry { var s1 = new Geometry.Square(5); -// Local alias for referencing a module +// Alias local pour référencer un module import G = Geometry; var s2 = new G.Square(10); -// Generics +// Génériques // Classes class Tuple { constructor(public item1: T1, public item2: T2) { @@ -151,14 +148,14 @@ interface Pair { item2: T; } -// And functions +// Et fonctions var pairToTuple = function(p: Pair) { return new Tuple(p.item1, p.item2); }; var tuple = pairToTuple({ item1:"hello", item2:"world"}); -// Including references to a definition file: +// Inclure des références à un fichier : /// ``` -- cgit v1.2.3 From f5fec6341b9a7ed280a5dbfd86d9cc5ee4fa82cf Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 30 Apr 2015 18:47:21 +0200 Subject: Update typescript-fr.html.markdown Fix translation --- fr-fr/typescript-fr.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown index 9e6ee171..14caec7c 100644 --- a/fr-fr/typescript-fr.html.markdown +++ b/fr-fr/typescript-fr.html.markdown @@ -8,13 +8,13 @@ filename: learntypescript-fr.ts lang: fr-fr --- -TypeScript est un langage visant à faciliter le developpement d'applications large et scalable écrite en JavaScript. -TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionel) à JavaScript. -C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur. +TypeScript est un langage visant à faciliter le développement d'applications large et scalable écrite en JavaScript. +TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript. +C'est une sur-couche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/). -Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et voir directement le rendu JavaScript. +Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et accéder directement au rendu JavaScript. ```js // Il y a 3 types basiques en TypeScript -- cgit v1.2.3 From abd5437b6d94a4635df8ade836ecde2206aa9625 Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 30 Apr 2015 18:54:07 +0200 Subject: Update typescript-fr.html.markdown Adjust to 80 columns --- fr-fr/typescript-fr.html.markdown | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown index 14caec7c..63ed4c34 100644 --- a/fr-fr/typescript-fr.html.markdown +++ b/fr-fr/typescript-fr.html.markdown @@ -25,7 +25,7 @@ var name: string = "Anders"; // Quand c'est impossible à déterminer, on utilise le type `Any` var notSure: any = 4; notSure = "maybe a string instead"; -notSure = false; // ok, définitvement un booléen +notSure = false; // ok, définitivement un booléen // Pour les collections, il y a les tableaux typés et les tableaux génériques var list: number[] = [1, 2, 3]; // Un tableaux typé @@ -35,16 +35,17 @@ var list: Array = [1, 2, 3]; // un tableau générique enum Color { Red, Green, Blue }; var c: Color = Color.Green; -// Enfin, `void` est utilisé dans le cas spécifique d'une fonction ne retournant rien +// Enfin, `void` est utilisé dans le cas spécifique +// d'une fonction ne retournant rien function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -// Les fontions sont des entités de première classe. Elles supportent les expressions lambda et -// utilisent l'inférence de types +// Les fontions sont des entités de première classe. Elles supportent +// les expressions lambda et utilisent l'inférence de types -// Les fonctions ci-dessous sont équivalentes, une signature identique sera inférée par le compilateur, -// et le même JavaScript sera généré +// Les fonctions ci-dessous sont équivalentes, une signature identique +// sera inférée par le compilateur, et le même JavaScript sera généré var f1 = function(i: number): number { return i * i; } // Retourne un type inféré var f2 = function(i: number) { return i * i; } @@ -54,8 +55,8 @@ var f4 = (i: number) => { return i * i; } // Retourne un type inféré, ici le mot clé `return` n'est pas nécessaire var f5 = (i: number) => i * i; -// Les interfaces sont structurés, tout ce qui a les propriétés est compatible avec -// l'interface +// Les interfaces sont structurés, tout ce qui a les propriétés est compatible +// avec l'interface interface Person { name: string; // Les propriétés optionnelles sont identifiées avec un "?" @@ -68,28 +69,30 @@ interface Person { // une Person car il a les propriétés "name" et "move" var p: Person = { name: "Bobby", move: () => {} }; // Des objets implémentants la propriété optionnelle : -var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; // valide car "age" est un nombre -var invalidPerson: Person = { name: "Bobby", age: true }; // invalide car "age" n'est pas un nombre +// valide car "age" est un nombre +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// invalide car "age" n'est pas un nombre +var invalidPerson: Person = { name: "Bobby", age: true }; // Les interfaces peuvent aussi décrire un type de fonction interface SearchFunc { (source: string, subString: string): boolean; } -// Seul les types des paramètres sont importants, les noms ne le sont pas +// Seul les types des paramètres sont importants, les noms ne le sont pas. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -// Les membres des classes sont publiques par défaut +// Les membres des classes sont publiques par défaut. class Point { // Propriétés x: number; - // Constructeur - Les mots clés "public" et "private" dans ce contexte génèrent - // le code de la propriété et son initialisation dans le constructeur. - // Dans cet exemple, "y" sera défini de la même façon que "x", mais avec moins de code - // Les valeurs par défaut sont supportées + // Constructeur - Les mots clés "public" et "private" dans ce contexte + // génèrent le code de la propriété et son initialisation dans le + // constructeur. Ici, "y" sera défini de la même façon que "x", + // mais avec moins de code. Les valeurs par défaut sont supportées. constructor(x: number, public y: number = 0) { this.x = x; } @@ -107,7 +110,9 @@ var p2 = new Point(25); //y will be 0 // Héritage class Point3D extends Point { constructor(x: number, y: number, public z: number = 0) { - super(x, y); // Un appel explicite au constructeur de la super classe est obligatoire. + // Un appel explicite au constructeur de la super classe + // est obligatoire. + super(x, y); } // Redéfinition -- cgit v1.2.3 From e13e00945dc4bb20c7cf6b9cd4af87f73b965ddb Mon Sep 17 00:00:00 2001 From: Rinoc Johnson Date: Thu, 30 Apr 2015 17:56:01 -0400 Subject: Fix Python typo. --- python.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 7281a330..f081a6a7 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -46,7 +46,7 @@ to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://lea 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better -# Result of integer division truncated down both for positive and negative. +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 @@ -191,7 +191,7 @@ li[2:] # => [4, 3] li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Revert the list +# Reverse the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] @@ -439,14 +439,14 @@ def pass_all_the_args(*args, **kwargs): print varargs(*args) print keyword_args(**kwargs) -# Function Scope +# Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 print x # => 43 - + def setGlobalX(num): global x print x # => 5 -- cgit v1.2.3 From 5ebe2dcb6eeaf7e34daf07f76dcfa2403f05a332 Mon Sep 17 00:00:00 2001 From: Rinoc Johnson Date: Thu, 30 Apr 2015 19:31:38 -0400 Subject: Clarify wording for list reversal. --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index f081a6a7..ace3f794 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -191,14 +191,14 @@ li[2:] # => [4, 3] li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Reverse the list +# Reverse a copy of the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] - +r # You can add lists li + other_li # => [1, 2, 3, 4, 5, 6] # Note: values for li and for other_li are not modified. -- cgit v1.2.3 From ffc5ac247c52071c3e4e639ecd363c4fca89bec9 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 30 Apr 2015 23:44:09 -0600 Subject: Python3 doc cleanup --- python3.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 470eb6e4..a112912f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -39,7 +39,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea # Except division which returns floats by default 35 / 5 # => 7.0 -# Result of integer division truncated down both for positive and negative. +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 @@ -73,8 +73,8 @@ False or True #=> True # Note using Bool operators with ints 0 and 2 #=> 0 -5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False +0 == False #=> True +2 == True #=> False 1 == True #=> True # Equality is == @@ -145,7 +145,7 @@ bool({}) #=> False # Python has a print function print("I'm Python. Nice to meet you!") -# No need to declare variables before assigning to them. +# No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores some_var = 5 some_var # => 5 @@ -186,7 +186,7 @@ li[2:] # => [4, 3] li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Revert the list +# Return a reversed copy of the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] @@ -196,7 +196,7 @@ del li[2] # li is now [1, 2, 3] # You can add lists # Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] @@ -213,7 +213,7 @@ tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError -# You can do all those list thingies on tuples too +# You can do most of the list operations on tuples too len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) @@ -235,15 +235,15 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] # => 1 -# Get all keys as a list with "keys()". -# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. +# Get all keys as an iterable with "keys()". We need to wrap the call in list() +# to turn it into a list. We'll talk about those later. Note - Dictionary key +# ordering is not guaranteed. Your results might not match this exactly. list(filled_dict.keys()) # => ["three", "two", "one"] -# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. -# Note - Same as above regarding key ordering. +# Get all values as an iterable with "values()". Once again we need to wrap it +# in list() to get it out of the iterable. Note - Same as above regarding key +# ordering. list(filled_dict.values()) # => [3, 2, 1] @@ -281,7 +281,7 @@ some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} # Can set new variables to a set filled_set = some_set -# Add one more item to the set +# Add one more item to the set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & @@ -328,7 +328,7 @@ for animal in ["dog", "cat", "mouse"]: print("{} is a mammal".format(animal)) """ -"range(number)" returns a list of numbers +"range(number)" returns an iterable of numbers from zero to the given number prints: 0 @@ -340,7 +340,7 @@ for i in range(4): print(i) """ -"range(lower, upper)" returns a list of numbers +"range(lower, upper)" returns an iterable of numbers from the lower number to the upper number prints: 4 @@ -458,14 +458,14 @@ all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) -# Function Scope +# Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 print (x) # => 43 - + def setGlobalX(num): global x print (x) # => 5 @@ -512,8 +512,8 @@ class Human(object): # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects # or attributes that are used by python but that live in user-controlled - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) # You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute @@ -600,7 +600,7 @@ def double_numbers(iterable): # double_numbers. # Note range is a generator too. Creating a list 1-900000000 would take lot of # time to be made -# We use a trailing underscore in variable names when we want to use a name that +# We use a trailing underscore in variable names when we want to use a name that # would normally collide with a python keyword range_ = range(1, 900000000) # will double all numbers until a result >=30 found -- cgit v1.2.3 From a4c0f3536bc18e9c157a77dc5dd33ae47c6fe03e Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Sat, 2 May 2015 15:31:56 +0400 Subject: WIP --- ru-ru/bash-ru.html.markdown | 281 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 281 insertions(+) create mode 100644 ru-ru/bash-ru.html.markdown diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown new file mode 100644 index 00000000..264b7439 --- /dev/null +++ b/ru-ru/bash-ru.html.markdown @@ -0,0 +1,281 @@ +--- +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/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +filename: LearnBash.sh +--- + +Bash это командная оболочка unix (unix shell), которая распространяется как оболочка для операционной системы GNU и используется в качестве оболочки по умолчанию для Linux и Mac OS X. +Почти все нижеприведенные примеры могут могут быть частью shell-скриптов или быть исполнены напрямую в shell. + +[Подробнее.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Первая строка скрипта - это shebang, который сообщает системе как испольнять +# этот скрипт: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Как вы уже поняли, комментарии начинаются с #. Shebang - это тоже коммантарий. + +# Простой пример hello world: +echo Hello world! + +# Отдельные команды начинаются с новой строки или разделяются точкой с запятой: +echo 'This is the first line'; echo 'This is the second line' + +# Вот так объявляется пемеренная: +VARIABLE="Some string" + +# Но не так: +VARIABLE = "Some string" +# Bash решит что VARIABLE - это команда, которую он должен исполнить, +# и выдаст ошибку, потому что не сможет найти ее. + +# И не так: +VARIABLE= 'Some string' +# Тут Bash решит что 'Some string' - это команда, которую он должен исполнить, +# и выдаст ошибку, потому что не сможет найти ее (здесь 'VARIABLE=' выглядит +# как присвоение значения переменной, но только в контексте исполнения +# команды 'Some string'). + +# Использование переменой: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Когда вы используете переменную — присвоение, экспорт и т.д — вы пищете её +# имя без $. А для получения значения переменной, используйте $. +# Заметте что ' (одинарные кавычки) не раскрывают переменные в них. + +# Подстановка строк в переменных +echo ${VARIABLE/Some/A} +# Это выражение заменит первую встреченную подстроку "Some" на "A" + +# Подстановка из переменной +LENGTH=7 +echo ${VARIABLE:0:LENGTH} +# This will return only the first 7 characters of the value + +# Default value for variable +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 + +# Builtin variables: +# There are some useful builtin variables, like +echo "Last program return value: $?" +echo "Script's PID: $$" +echo "Number of arguments: $#" +echo "Scripts arguments: $@" +echo "Scripts arguments seperated in different variables: $1 $2..." + +# Reading a value from input: +echo "What's your name?" +read NAME # Note that we didn't need to declare a new variable +echo Hello, $NAME! + +# We have the usual if structure: +# use 'man test' for more info about conditionals +if [ $NAME -ne $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# There is also conditional execution +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# To use && and || with if statements, you need multiple pairs of square brackets: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "This will run if $NAME is Steve AND $AGE is 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "This will run if $NAME is Daniya OR Zach." +fi + +# Expressions are denoted with the following format: +echo $(( 10 + 5 )) + +# Unlike other programming languages, bash is a shell — so it works in a context +# of current directory. You can list files and directories in the current +# directory with the ls command: +ls + +# These commands have options that control their execution: +ls -l # Lists every file and directory on a separate line + +# Results of the previous command can be passed to the next command as input. +# grep command filters the input with provided patterns. That's how we can list +# .txt files in the current directory: +ls -l | grep "\.txt" + +# You can redirect command input and output (stdin, stdout, and stderr). +# Read from stdin until ^EOF$ and overwrite hello.py with the lines +# between "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import 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 + +# Run hello.py with various stdin, stdout, and stderr redirections: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# The output error will overwrite the file if it exists, +# if you want to append instead, use ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Overwrite output.txt, append to error.err, and count lines: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Run a command and print its file descriptor (e.g. /dev/fd/123) +# see: man fd +echo <(echo "#helloworld") + +# Overwrite output.txt with "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Cleanup temporary files verbosely (add '-i' for interactive) +rm -v output.out error.err output-and-error.log + +# Commands can be substituted within other commands using $( ): +# The following command displays the number of files and directories in the +# current directory. +echo "There are $(ls | wc -l) items here." + +# The same can be done using backticks `` but they can't be nested - the preferred way +# is to use $( ). +echo "There are `ls | wc -l` items here." + +# Bash uses a case statement that works similarly to switch in Java and C++: +case "$VARIABLE" in + #List patterns for the conditions you want to meet + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# for loops iterate for as many arguments given: +# The contents of $VARIABLE is printed three times. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# Or write it the "traditional for loop" way: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# They can also be used to act on files.. +# This will run the command 'cat' on file1 and file2 +for VARIABLE in file1 file2 +do + cat "$VARIABLE" +done + +# ..or the output from a command +# This will cat the output from ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# while loop: +while [ true ] +do + echo "loop body here..." + break +done + +# You can also define functions +# Definition: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# or simply +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# Calling your function +foo "My name is" $NAME + +# There are a lot of useful commands you should learn: +# prints last 10 lines of file.txt +tail -n 10 file.txt +# prints first 10 lines of file.txt +head -n 10 file.txt +# sort file.txt's lines +sort file.txt +# report or omit repeated lines, with -d it reports them +uniq -d file.txt +# prints only the first column before the ',' character +cut -d ',' -f 1 file.txt +# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) +sed -i 's/okay/great/g' file.txt +# print to stdout all lines of file.txt which match some regex +# The example prints lines which begin with "foo" and end in "bar" +grep "^foo.*bar$" file.txt +# pass the option "-c" to instead print the number of lines matching the regex +grep -c "^foo.*bar$" file.txt +# if you literally want to search for the string, +# and not the regex, use fgrep (or grep -F) +fgrep "^foo.*bar$" file.txt + + +# Read Bash shell builtins documentation with the bash 'help' builtin: +help +help help +help for +help return +help source +help . + +# Read Bash manpage documentation with man +apropos bash +man 1 bash +man bash + +# Read info documentation with info (? for help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Read bash info documentation: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 8758bb845b063b76b55d2c178d0dc393b2a39c5c Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Sat, 2 May 2015 15:34:56 +0400 Subject: Clear that length and position can be set by variable in substring extraction --- bash.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index e0c12f97..81f85d28 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -59,7 +59,8 @@ echo ${VARIABLE/Some/A} # This will substitute the first occurance of "Some" with "A" # Substring from a variable -echo ${VARIABLE:0:7} +LENGTH=7 +echo ${VARIABLE:0:LENGTH} # This will return only the first 7 characters of the value # Default value for variable -- cgit v1.2.3 From 6848f45ebeee759afdaa34e6cdf367fe31bf1bab Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Sat, 2 May 2015 16:21:03 +0400 Subject: Clear explanation of default value expression --- bash.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index e0c12f97..58dc3003 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -64,7 +64,8 @@ echo ${VARIABLE:0:7} # Default value for variable echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} -# This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 +# This works for null (FOO=) and empty string (FOO=""); zero (FOO=0) returns 0. +# Note that it only returns default value and doesn't change variable value. # Builtin variables: # There are some useful builtin variables, like -- cgit v1.2.3 From af9588f8adb39717660ed66768c475d5228a8af7 Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Sun, 3 May 2015 00:19:06 +0400 Subject: Bash Russian translation --- ru-ru/bash-ru.html.markdown | 218 ++++++++++++++++++++++---------------------- 1 file changed, 109 insertions(+), 109 deletions(-) diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown index 264b7439..f8b28294 100644 --- a/ru-ru/bash-ru.html.markdown +++ b/ru-ru/bash-ru.html.markdown @@ -21,108 +21,110 @@ Bash это командная оболочка unix (unix shell), котора ```bash #!/bin/bash -# Первая строка скрипта - это shebang, который сообщает системе как испольнять +# Первая строка скрипта - это shebang, который сообщает системе как исполнять # этот скрипт: http://en.wikipedia.org/wiki/Shebang_(Unix) -# Как вы уже поняли, комментарии начинаются с #. Shebang - это тоже коммантарий. +# Как вы уже поняли, комментарии начинаются с #. Shebang — тоже коммантарий. # Простой пример hello world: echo Hello world! # Отдельные команды начинаются с новой строки или разделяются точкой с запятой: -echo 'This is the first line'; echo 'This is the second line' +echo 'Это первая строка'; echo 'Это вторая строка' # Вот так объявляется пемеренная: -VARIABLE="Some string" +VARIABLE="Просто строка" -# Но не так: -VARIABLE = "Some string" +# но не так: +VARIABLE = "Просто строка" # Bash решит что VARIABLE - это команда, которую он должен исполнить, # и выдаст ошибку, потому что не сможет найти ее. -# И не так: -VARIABLE= 'Some string' -# Тут Bash решит что 'Some string' - это команда, которую он должен исполнить, -# и выдаст ошибку, потому что не сможет найти ее (здесь 'VARIABLE=' выглядит -# как присвоение значения переменной, но только в контексте исполнения -# команды 'Some string'). +# и не так: +VARIABLE= 'Просто строка' +# Тут Bash решит, что 'Просто строка' - это команда, которую он должен исполнить, +# и выдаст ошибку, потому что не сможет найти такой команды +# (здесь 'VARIABLE=' выглядит как присвоение значения переменной, +# но только в контексте исполнения команды 'Просто строка'). # Использование переменой: echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' -# Когда вы используете переменную — присвоение, экспорт и т.д — вы пищете её +# Когда вы используете переменную - присвоение, экспорт и т.д - пишите её # имя без $. А для получения значения переменной, используйте $. # Заметте что ' (одинарные кавычки) не раскрывают переменные в них. -# Подстановка строк в переменных -echo ${VARIABLE/Some/A} -# Это выражение заменит первую встреченную подстроку "Some" на "A" +# Подстановка строк в переменные +echo ${VARIABLE/Просто/A} +# Это выражение заменит первую встреченную подстроку "Просто" на "A" # Подстановка из переменной LENGTH=7 echo ${VARIABLE:0:LENGTH} -# This will return only the first 7 characters of the value +# Это выражение вернет только первые 7 символов переменной VARIABLE -# Default value for variable +# Значение по умолчанию echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} -# This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 - -# Builtin variables: -# There are some useful builtin variables, like -echo "Last program return value: $?" -echo "Script's PID: $$" -echo "Number of arguments: $#" -echo "Scripts arguments: $@" -echo "Scripts arguments seperated in different variables: $1 $2..." - -# Reading a value from input: -echo "What's your name?" -read NAME # Note that we didn't need to declare a new variable -echo Hello, $NAME! - -# We have the usual if structure: -# use 'man test' for more info about conditionals +# Это сработает при отсутствующем значении (FOO=) и пустой строке (FOO=""); +# ноль (FOO=0) вернет 0. +# Заметте, что в любом случае значение самой переменной FOO не изменится. + +# Встроенные переменные: +# В bash есть полезные встроенные переменные, например +echo "Последее возвращенное значение: $?" +echo "PID скрипта: $$" +echo "Количество аргументов: $#" +echo "Аргументы скрипта: $@" +echo "Аргументы скрипта рапределенные по отдельным переменным: $1 $2..." + +# Чтение аргументов из входа: +echo "Как Вас зовут?" +read NAME # Заметте, что нам не нужно определять новую переменную +echo Привет, $NAME! + +# У нас есть обычная структура if: +# наберите 'man test' для подробностях о форматах условия if [ $NAME -ne $USER ] then - echo "Your name isn't your username" + echo "Имя не совпадает с именем пользователя" else - echo "Your name is your username" + echo "Имя совпадает с именем пользователя" fi -# There is also conditional execution -echo "Always executed" || echo "Only executed if first command fails" -echo "Always executed" && echo "Only executed if first command does NOT fail" +# Также есть условное исполнение +echo "Исполнится всегда" || echo "Исполнится, если первая команда провалится" +echo "Исполнится всегда" && echo "Исполнится, если первая команда выполнится удачно" -# To use && and || with if statements, you need multiple pairs of square brackets: +# Можно использовать && и || в выражениях if, когда нужно несколько пар скобок: if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] then - echo "This will run if $NAME is Steve AND $AGE is 15." + echo "Исполнится, если $NAME равно Steve И $AGE равно 15." fi if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] then - echo "This will run if $NAME is Daniya OR Zach." + echo "Исполнится, если $NAME равно Daniya ИЛИ Zach." fi -# Expressions are denoted with the following format: +# Выражения обозначаются таким форматом: echo $(( 10 + 5 )) -# Unlike other programming languages, bash is a shell — so it works in a context -# of current directory. You can list files and directories in the current -# directory with the ls command: +# В отличае от других языков программирования, bash это командная оболочка - +# значит он работает в контексте текущей директории. +# Вы можете просматривать файлы и директории в текущей директории командой ls: ls -# These commands have options that control their execution: -ls -l # Lists every file and directory on a separate line +# У этой команды есть опции: +ls -l # Показать каждый файл и директорию на отдельной строке -# Results of the previous command can be passed to the next command as input. -# grep command filters the input with provided patterns. That's how we can list -# .txt files in the current directory: +# Результат предыдущей команды может быть направлен на вход следующей. +# Команда grep фильтрует ввод по шаблону. +# Так мы можем просмотреть только *.txt файлы в текущей директории: ls -l | grep "\.txt" -# You can redirect command input and output (stdin, stdout, and stderr). -# Read from stdin until ^EOF$ and overwrite hello.py with the lines -# between "EOF": +# Вы можете перенаправить ввод и вывод команды (stdin, stdout и stderr). +# Следующая команда означает: читать из stdin пока не встретится ^EOF$ и +# перезаписать hello.py следующим строками (до строки "EOF"): cat > hello.py << EOF #!/usr/bin/env python from __future__ import print_function @@ -133,128 +135,126 @@ for line in sys.stdin: print(line, file=sys.stdout) EOF -# Run hello.py with various stdin, stdout, and stderr redirections: +# Запуск hello.py с разными вариантами перенаправления потоков +# стандартных ввода, вывода и ошибок: python hello.py < "input.in" python hello.py > "output.out" python hello.py 2> "error.err" python hello.py > "output-and-error.log" 2>&1 python hello.py > /dev/null 2>&1 -# The output error will overwrite the file if it exists, -# if you want to append instead, use ">>": +# Поток ошибок перезапишет файл, если этот файл существует, +# поэтому если вы хотите дописывать файл используйте ">>": python hello.py >> "output.out" 2>> "error.err" -# Overwrite output.txt, append to error.err, and count lines: +# Переписать output.txt, дописать error.err и сосчитать строки: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err -# Run a command and print its file descriptor (e.g. /dev/fd/123) -# see: man fd +# Запустить команду и вывести ее файловый дескриптор (смотрите: man fd) echo <(echo "#helloworld") -# Overwrite output.txt with "#helloworld": +# Перезаписать output.txt строкой "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null -# Cleanup temporary files verbosely (add '-i' for interactive) +# Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим) rm -v output.out error.err output-and-error.log -# Commands can be substituted within other commands using $( ): -# The following command displays the number of files and directories in the -# current directory. -echo "There are $(ls | wc -l) items here." +# Команды могут быть подставлены в строку используя $( ): +# следующие команды выводят число файлов и директорий в текущей директории. +echo "Здесь $(ls | wc -l) элементов." -# The same can be done using backticks `` but they can't be nested - the preferred way -# is to use $( ). -echo "There are `ls | wc -l` items here." +# То же самое можно сделать использую обратные кавычки, но они не могут быть +# вложенными - предпочтительно использовать $( ). +echo "Здесь `ls | wc -l` элементов." -# Bash uses a case statement that works similarly to switch in Java and C++: +# В Bash есть структура case, которая похожа на switch в Java и C++: case "$VARIABLE" in - #List patterns for the conditions you want to meet - 0) echo "There is a zero.";; - 1) echo "There is a one.";; - *) echo "It is not null.";; + # Перечислите шаблоны для условий, которые хотите отловить + 0) echo "Тут ноль.";; + 1) echo "Тут один.";; + *) echo "Это не пустое значение.";; esac -# for loops iterate for as many arguments given: -# The contents of $VARIABLE is printed three times. +# Цикл for перебирает элементы переданные в аргументе: +# Содержимое $VARIABLE будет напечатано три раза. for VARIABLE in {1..3} do echo "$VARIABLE" done -# Or write it the "traditional for loop" way: +# Или перепишем "традиционным" синтаксисом цикла for: for ((a=1; a <= 3; a++)) do echo $a done -# They can also be used to act on files.. -# This will run the command 'cat' on file1 and file2 +# Цикл for можно использовать для действий с файлами. +# Запустим команду 'cat' для файлов file1 и file2 for VARIABLE in file1 file2 do cat "$VARIABLE" done -# ..or the output from a command -# This will cat the output from ls. +# ..или выводом из команд +# Запустим cat для вывода из ls. for OUTPUT in $(ls) do cat "$OUTPUT" done -# while loop: +# Цикл while: while [ true ] do - echo "loop body here..." + echo "тело цикла здесь..." break done -# You can also define functions -# Definition: +# Вы можете определять функции +# Определение: function foo () { - echo "Arguments work just like script arguments: $@" - echo "And: $1 $2..." - echo "This is a function" + echo "Аргументы работают также как аругменты скрипта: $@" + echo "и: $1 $2..." + echo "Это функция" return 0 } -# or simply +# или просто bar () { - echo "Another way to declare functions!" + echo "Другой способ определить функцию!" return 0 } -# Calling your function -foo "My name is" $NAME +# Вызов функции +foo "Мое имя" $NAME -# There are a lot of useful commands you should learn: -# prints last 10 lines of file.txt +# Есть много полезных команд, которые нужно знать: +# напечатать последние 10 строк файла file.txt tail -n 10 file.txt -# prints first 10 lines of file.txt +# напечатать первые 10 строк файла file.txt head -n 10 file.txt -# sort file.txt's lines +# отсортировать строки file.txt sort file.txt -# report or omit repeated lines, with -d it reports them +# отобрать или наоборот пропустить повторяющиеся строки (с опцией -d отбирает) uniq -d file.txt -# prints only the first column before the ',' character +# напечатать только первую колонку перед символом ',' cut -d ',' -f 1 file.txt -# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) +# заменить каждое 'okay' на 'great' в файле file.txt (regex поддерживается) sed -i 's/okay/great/g' file.txt -# print to stdout all lines of file.txt which match some regex -# The example prints lines which begin with "foo" and end in "bar" +# вывести в stdout все строки из file.txt, совпадающие с шаблоном regex; +# этот пример выводит строки, которые начинаются на "foo" и оканчиваются "bar" grep "^foo.*bar$" file.txt -# pass the option "-c" to instead print the number of lines matching the regex +# передайте опцию -c чтобы вывести число строк, в которых совпал шаблон grep -c "^foo.*bar$" file.txt -# if you literally want to search for the string, -# and not the regex, use fgrep (or grep -F) +# чтобы искать прямо строку, а не шаблон regex, используйте fgrep (или grep -F) fgrep "^foo.*bar$" file.txt -# Read Bash shell builtins documentation with the bash 'help' builtin: +# Читайте встроенную документацию оболочки Bash командой 'help': help help help help for @@ -262,18 +262,18 @@ help return help source help . -# Read Bash manpage documentation with man +# Читайте Bash man-документацию apropos bash man 1 bash man bash -# Read info documentation with info (? for help) +# Читайте документацию info (? для помощи) apropos info | grep '^info.*(' man info info info info 5 info -# Read bash info documentation: +# Читайте bash info документацию: info bash info bash 'Bash Features' info bash 6 -- cgit v1.2.3 From 3a9138beafc9f0ca0b007ac7c27f664f6c7c42af Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Sat, 2 May 2015 17:00:56 -0700 Subject: added italian translation of bash --- .DS_Store | Bin 0 -> 6148 bytes it-it/bash-it.html.markdown | 275 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 275 insertions(+) create mode 100644 .DS_Store create mode 100644 it-it/bash-it.html.markdown diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..79a35b6f Binary files /dev/null and b/.DS_Store differ diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown new file mode 100644 index 00000000..a4391258 --- /dev/null +++ b/it-it/bash-it.html.markdown @@ -0,0 +1,275 @@ +--- +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/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] +filename: LearnBash.sh +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] +lang: it-it +--- + +Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X. +Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell. + +[Per saperne di piu'.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# La prima riga dello script è lo shebang il quale dice al sistema come eseguire +# lo script: http://it.wikipedia.org/wiki/Shabang +# Come avrai già immaginato, i commenti iniziano con #. Lo shebang stesso è un commento. + +# Semplice esempio ciao mondo: +echo Ciao mondo! + +# Ogni comando inizia su una nuova riga, o dopo un punto e virgola: +echo 'Questa è la prima riga'; echo 'Questa è la seconda riga' + +# Per dichiarare una variabile: +VARIABILE="Una stringa" + +# Ma non così: +VARIABILE = "Una stringa" +# Bash stabilirà che VARIABILE è un comando da eseguire e darà un errore +# perchè non esiste. + +# Usare la variabile: +echo $VARIABILE +echo "$VARIABILE" +echo '$VARIABILE' +# Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi +# il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $. +# Nota che ' (singolo apice) non espande le variabili! + +# Sostituzione di stringhe nelle variabili +echo ${VARIABILE/Una/A} +# Questo sostituirà la prima occorrenza di "Una" con "La" + +# Sottostringa di una variabile +echo ${VARIABILE:0:7} +# Questo ritornera solamente i primi 7 caratteri + +# Valore di default per la variabile +echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} +# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0 + +# Variabili builtin: +# Ci sono delle variabili builtin molto utili, come +echo "Valore di ritorno dell'ultimo programma eseguito: $?" +echo "PID dello script: $$" +echo "Numero di argomenti: $#" +echo "Argomenti dello script: $@" +echo "Argomenti dello script separati in variabili distinte: $1 $2..." + +# Leggere un valore di input: +echo "Come ti chiami?" +read NOME # Nota che non abbiamo dovuto dichiarare una nuova variabile +echo Ciao, $NOME! + +# Classica struttura if: +# usa 'man test' per maggiori informazioni sulle condizionali +if [ $NOME -ne $USER ] +then + echo "Il tuo nome non è lo username" +else + echo "Il tuo nome è lo username" +fi + +# C'è anche l'esecuzione condizionale +echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce" +echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce" + +# Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre: +if [ $NOME == "Steve" ] && [ $ETA -eq 15 ] +then + echo "Questo verrà eseguito se $NOME è Steve E $ETA è 15." +fi + +if [ $NOME == "Daniya" ] || [ $NOME == "Zach" ] +then + echo "Questo verrà eseguito se $NAME è Daniya O Zach." +fi + +# Le espressioni sono nel seguente formato: +echo $(( 10 + 5 )) + +# A differenza di altri linguaggi di programmazione, bash è una shell - quindi lavora nel contesto +# della cartella corrente. Puoi elencare i file e le cartelle nella cartella +# corrente con il comando ls: +ls + +# Questi comandi hanno opzioni che controllano la loro esecuzione: +ls -l # Elenca tutti i file e le cartelle su una riga separata + +# I risultati del comando precedente possono essere passati al comando successivo come input. +# Il comando grep filtra l'input con il pattern passato. Ecco come possiamo elencare i +# file .txt nella cartella corrente: +ls -l | grep "\.txt" + +# Puoi redirezionare l'input e l'output del comando (stdin, stdout, e stderr). +# Leggi da stdin finchè ^EOF$ e sovrascrivi hello.py con le righe +# comprese tra "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import 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 + +# Esegui hello.py con diverse redirezioni stdin, stdout, e stderr: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Lo output error sovrascriverà il file se esiste, +# se invece vuoi appendere usa ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Sovrascrivi output.txt, appendi a error.err, e conta le righe: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Esegui un comando e stampa il suo file descriptor (esempio: /dev/fd/123) +# vedi: man fd +echo <(echo "#ciaomondo") + +# Sovrascrivi output.txt con "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Pulisci i file temporanei verbosamente (aggiungi '-i' per la modalità interattiva) +rm -v output.out error.err output-and-error.log + +# I comandi possono essere sostituiti con altri comandi usando $( ): +# Il comando seguente mostra il numero di file e cartelle nella +# cartella corrente. +echo "Ci sono $(ls | wc -l) oggetti qui." + +# Lo stesso puo' essere usato usando backticks `` ma non possono essere innestati - il modo migliore +# è usando $( ). +echo "Ci sono `ls | wc -l` oggetti qui." + +# Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++: +case "$VARIABILE" in + #Lista di pattern per le condizioni che vuoi soddisfare + 0) echo "C'è uno zero.";; + 1) echo "C'è un uno.";; + *) echo "Non è null.";; +esac + +# I cicli for iterano per ogni argomento fornito: +# I contenuti di $VARIABILE sono stampati tre volte. +for VARIABILE in {1..3} +do + echo "$VARIABILE" +done + +# O scrivilo con il "ciclo for tradizionale": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Possono essere usati anche per agire su file.. +# Questo eseguirà il comando 'cat' su file1 e file2 +for VARIABILE in file1 file2 +do + cat "$VARIABILE" +done + +# ..o dall'output di un comando +# Questo eseguirà cat sull'output di ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# while loop: +while [ true ] +do + echo "corpo del loop..." + break +done + +# Puoi anche definire funzioni +# Definizione: +function foo () +{ + echo "Gli argomenti funzionano come gli argomenti dello script: $@" + echo "E: $1 $2..." + echo "Questa è una funzione" + return 0 +} + +# o semplicemente +bar () +{ + echo "Un altro modo per dichiarare funzioni!" + return 0 +} + +# Per chiamare la funzione +foo "Il mio nome è" $NOME + +# Ci sono un sacco di comandi utili che dovresti imparare: +# stampa le ultime 10 righe di file.txt +tail -n 10 file.txt +# stampa le prime 10 righe di file.txt +head -n 10 file.txt +# ordina le righe di file.txt +sort file.txt +# riporta o ometti le righe ripetute, con -d le riporta +uniq -d file.txt +# stampa solamente la prima colonna prima del carattere ',' +cut -d ',' -f 1 file.txt +# sostituisce ogni occorrenza di 'okay' con 'great' in file.txt (compatible con le regex) +sed -i 's/okay/great/g' file.txt +# stampa su stdout tutte le righe di file.txt che soddisfano una certa regex +# L'esempio stampa le righe che iniziano con "foo" e che finiscono con "bar" +grep "^foo.*bar$" file.txt +# passa l'opzione "-c" per stampare invece il numero delle righe che soddisfano la regex +grep -c "^foo.*bar$" file.txt +# se vuoi letteralmente cercare la stringa, +# e non la regex, usa fgrep (o grep -F) +fgrep "^foo.*bar$" file.txt + + +# Leggi la documentazione dei builtin di bash con il builtin 'help' di bash: +help +help help +help for +help return +help source +help . + +# Leggi la manpage di bash con man +apropos bash +man 1 bash +man bash + +# Leggi la documentazione con info (? per help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Leggi la documentazione di bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From e5c7c1db4c0597da69fd867ea0831ab71068ba8a Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Sat, 2 May 2015 17:03:38 -0700 Subject: rm .DS --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 79a35b6f..00000000 Binary files a/.DS_Store and /dev/null differ -- cgit v1.2.3 From df788639e6e4ee824ecf817e28e8dcaac48b5504 Mon Sep 17 00:00:00 2001 From: sinkswim Date: Sat, 2 May 2015 17:24:45 -0700 Subject: Update bash-it.html.markdown --- it-it/bash-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index a4391258..f892845f 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -55,7 +55,7 @@ echo ${VARIABILE/Una/A} # Sottostringa di una variabile echo ${VARIABILE:0:7} -# Questo ritornera solamente i primi 7 caratteri +# Questo ritornerà solamente i primi 7 caratteri # Valore di default per la variabile echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} -- cgit v1.2.3 From 88dd3f24dab91c35f73157a1b1fffcf6d9bc4dc3 Mon Sep 17 00:00:00 2001 From: Jim Garrison Date: Sat, 2 May 2015 22:26:12 -0700 Subject: [julia/en] Update for Julia 0.3 and fix a few typos --- julia.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 3a52018c..5ccd6484 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -8,7 +8,7 @@ filename: learnjulia.jl Julia is a new homoiconic functional language focused on technical computing. While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. -This is based on the current development version of Julia, as of October 18th, 2013. +This is based on Julia 0.3. ```ruby @@ -91,7 +91,7 @@ false # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# You can put any Julia expression inside the parenthesis. +# You can put any Julia expression inside the parentheses. # Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 @@ -190,7 +190,7 @@ end # inside the julia folder to find these files. # You can initialize arrays from ranges -a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] @@ -264,7 +264,7 @@ in(("two", 3), filled_dict) # => false haskey(filled_dict, "one") # => true haskey(filled_dict, 1) # => false -# Trying to look up a non-existant key will raise an error +# Trying to look up a non-existent key will raise an error try filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e -- cgit v1.2.3 From 288fcf7c2e03610400088381fae528294daa9f54 Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 3 May 2015 18:37:52 +0200 Subject: Create json-fr.html.markdown --- fr-fr/json-fr.html.markdown | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 fr-fr/json-fr.html.markdown diff --git a/fr-fr/json-fr.html.markdown b/fr-fr/json-fr.html.markdown new file mode 100644 index 00000000..9664dd73 --- /dev/null +++ b/fr-fr/json-fr.html.markdown @@ -0,0 +1,62 @@ +--- +language: json +filename: learnjson-fr.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + translators: + - ["Alois de Gouvello","https://github.com/aloisdg"] + lang: fr-fr +--- + +Comme JSON est un format d'échange de données êxtremement simple, ce Apprendre X en Y minutes +est susceptible d'être le plus simple jamais réalisé. + +JSON dans son état le plus pur n'a aucun commentaire, mais la majorité des parseurs accepterons +les commentaires du langage C (//, /\* \*/). Pour les besoins de ce document, cependant, +tout sera du JSON 100% valide. Heureusement, il s'explique par lui-même. + + +```json +{ + "Clé": "valeur", + + "Clés": "devront toujours être entourées par des guillemets", + "nombres": 0, + "chaînes de caractères": "Hellø, wørld. Tous les caractères Unicode sont autorisés, accompagné d'un \"caractère d'échappement\".", + "a des booléens ?": true, + "rien": null, + + "grand nombre": 1.2e+100, + + "objets": { + "commentaire": "La majorité de votre strucutre sera des objets.", + + "tableau": [0, 1, 2, 3, "Les tableaux peuvent contenir n'importe quoi.", 5], + + "un autre objet": { + "commentaire": "Ces choses peuvent être imbriquées. C'est très utile." + } + }, + + "bêtises": [ + { + "sources de potassium": ["bananes"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "style alternatif": { + "commentaire": "regarde ça !" + , "position de la virgule": "n'a pas d'importance - aussi longtemps qu'elle est avant la valeur, alors elle est valide." + , "un autre commentaire": "comme c'est gentil" + }, + + "C'était court": "Et, vous avez terminé. Maintenant, vous savez tout ce que JSON a à offrir." +} +``` -- cgit v1.2.3 From c09e8af49e05cfba07a95e6cc471a874fe703563 Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 3 May 2015 18:49:19 +0200 Subject: Update json-fr.html.markdown Thank you @vendethiel for your comments --- fr-fr/json-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/json-fr.html.markdown b/fr-fr/json-fr.html.markdown index 9664dd73..dc46e043 100644 --- a/fr-fr/json-fr.html.markdown +++ b/fr-fr/json-fr.html.markdown @@ -9,11 +9,11 @@ contributors: lang: fr-fr --- -Comme JSON est un format d'échange de données êxtremement simple, ce Apprendre X en Y minutes +Comme JSON est un format d'échange de données extrêmement simple, ce Apprendre X en Y minutes est susceptible d'être le plus simple jamais réalisé. JSON dans son état le plus pur n'a aucun commentaire, mais la majorité des parseurs accepterons -les commentaires du langage C (//, /\* \*/). Pour les besoins de ce document, cependant, +les commentaires du langage C (`//`, `\* \*`). Pour les besoins de ce document, cependant, tout sera du JSON 100% valide. Heureusement, il s'explique par lui-même. -- cgit v1.2.3 From c0bfad80f0b9590081bf9e6a3cd9eea933632a29 Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 3 May 2015 20:43:17 +0200 Subject: Update typescript-fr.html.markdown Add modifications from @vendethiel's comments. See #1075 --- fr-fr/typescript-fr.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown index 63ed4c34..b8807104 100644 --- a/fr-fr/typescript-fr.html.markdown +++ b/fr-fr/typescript-fr.html.markdown @@ -8,9 +8,9 @@ filename: learntypescript-fr.ts lang: fr-fr --- -TypeScript est un langage visant à faciliter le développement d'applications large et scalable écrite en JavaScript. +TypeScript est un langage visant à faciliter le développement d'applications larges et scalables, écrites en JavaScript. TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript. -C'est une sur-couche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur +C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur. Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/). @@ -22,7 +22,7 @@ var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -// Quand c'est impossible à déterminer, on utilise le type `Any` +// Si nous ne pouvons pas déterminer le type, on utilise `Any` var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // ok, définitivement un booléen @@ -38,11 +38,11 @@ var c: Color = Color.Green; // Enfin, `void` est utilisé dans le cas spécifique // d'une fonction ne retournant rien function bigHorribleAlert(): void { - alert("I'm a little annoying box!"); + alert("Je suis une petite boîte ennuyeuse !"); } -// Les fontions sont des entités de première classe. Elles supportent -// les expressions lambda et utilisent l'inférence de types +// Les fonctions sont des entités de première classe. Le langage supporte +// les expressions lambda et utilise l'inférence de type // Les fonctions ci-dessous sont équivalentes, une signature identique // sera inférée par le compilateur, et le même JavaScript sera généré @@ -55,8 +55,8 @@ var f4 = (i: number) => { return i * i; } // Retourne un type inféré, ici le mot clé `return` n'est pas nécessaire var f5 = (i: number) => i * i; -// Les interfaces sont structurés, tout ce qui a les propriétés est compatible -// avec l'interface +// Les interfaces sont structurées, tout les objets qui ont ces propriétés +// sont compatible avec l'interface interface Person { name: string; // Les propriétés optionnelles sont identifiées avec un "?" @@ -78,7 +78,8 @@ var invalidPerson: Person = { name: "Bobby", age: true }; interface SearchFunc { (source: string, subString: string): boolean; } -// Seul les types des paramètres sont importants, les noms ne le sont pas. + +// Seul les types des paramètres sont importants. Les noms ne le sont pas. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; @@ -86,7 +87,7 @@ mySearch = function(src: string, sub: string) { // Les membres des classes sont publiques par défaut. class Point { - // Propriétés + // Propriétés x: number; // Constructeur - Les mots clés "public" et "private" dans ce contexte @@ -105,7 +106,7 @@ class Point { } var p1 = new Point(10 ,20); -var p2 = new Point(25); //y will be 0 +var p2 = new Point(25); // y sera 0 // Héritage class Point3D extends Point { -- cgit v1.2.3 From 699c6d22390e359d586ad584eb44ab757858b4c4 Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 3 May 2015 20:55:14 +0200 Subject: Fix Markdown --- json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/json.html.markdown b/json.html.markdown index f5287138..f57b82b8 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -10,7 +10,7 @@ As JSON is an extremely simple data-interchange format, this is most likely goin to be the simplest Learn X in Y Minutes ever. JSON in its purest form has no actual comments, but most parsers will accept -C-style (//, /\* \*/) comments. For the purposes of this, however, everything is +C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. ```json -- cgit v1.2.3 From 5042c531cc1ced74ae5e12dac225ba219ff713dc Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 3 May 2015 20:58:03 +0200 Subject: Fix Markdown --- fr-fr/json-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/json-fr.html.markdown b/fr-fr/json-fr.html.markdown index dc46e043..41d79b18 100644 --- a/fr-fr/json-fr.html.markdown +++ b/fr-fr/json-fr.html.markdown @@ -13,7 +13,7 @@ Comme JSON est un format d'échange de données extrêmement simple, ce Apprendr est susceptible d'être le plus simple jamais réalisé. JSON dans son état le plus pur n'a aucun commentaire, mais la majorité des parseurs accepterons -les commentaires du langage C (`//`, `\* \*`). Pour les besoins de ce document, cependant, +les commentaires du langage C (`//`, `/* */`). Pour les besoins de ce document, cependant, tout sera du JSON 100% valide. Heureusement, il s'explique par lui-même. -- cgit v1.2.3 From 86f406d99c829d0f3074f18346173387f1eb6064 Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 3 May 2015 20:59:27 +0200 Subject: Fix Header --- fr-fr/json-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/json-fr.html.markdown b/fr-fr/json-fr.html.markdown index 41d79b18..49c95820 100644 --- a/fr-fr/json-fr.html.markdown +++ b/fr-fr/json-fr.html.markdown @@ -4,9 +4,9 @@ filename: learnjson-fr.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] - translators: +translators: - ["Alois de Gouvello","https://github.com/aloisdg"] - lang: fr-fr +lang: fr-fr --- Comme JSON est un format d'échange de données extrêmement simple, ce Apprendre X en Y minutes -- cgit v1.2.3 From afb44df97380cbfe037cdf5cf6bcb07355615552 Mon Sep 17 00:00:00 2001 From: chtiprog Date: Sun, 7 Dec 2014 01:47:25 +0100 Subject: Add French translation for R --- fr-fr/r-fr.html.markdown | 721 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 721 insertions(+) create mode 100644 fr-fr/r-fr.html.markdown diff --git a/fr-fr/r-fr.html.markdown b/fr-fr/r-fr.html.markdown new file mode 100644 index 00000000..8db78ef3 --- /dev/null +++ b/fr-fr/r-fr.html.markdown @@ -0,0 +1,721 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["Anne-Catherine Dehier", "https://github.com/spellart"] +filename: learnr-fr.r +--- + +R est un langage de programmation statistique. Il dispose de nombreuses +librairies pour le téléchargement et le nettoyage des ensembles de données, +l'exécution de procédures statistiques, et pour faire des graphiques. +On peut également exécuter les commmandes R à l'aide d'un document LaTeX. + + +```r + +# Les commentaires commencent avec des symboles numériques. + +# Il n'est pas possible de faire des commentaires multilignes, +# mais on peut superposer plusieurs commentaires comme ceci. + +# Sur Windows ou Mac, taper COMMAND-ENTER pour exécuter une ligne + + + +############################################################################# +# Les choses que vous pouvez faire sans rien comprendre à la programmation +############################################################################# + +# In this section, we show off some of the cool stuff you can do in +# Dans cette section, nous vous montrons quelques trucs cools que vous +# pouvez faire avec R sans rien comprendre à la programmation. +# Ne vous inquiétez pas si vous ne comprenez pas tout ce que le code fait. +# Profitez simplement ! + +data() # parcours les ensembles de données préchargées +data(rivers) # obtiens celui-ci: "Lengths of Major North American Rivers" +ls() # notez que "rivers" apparaît maintenant dans votre espace de travail +head(rivers) # Jetez un coup d'oeil à l'ensemble de données +# 735 320 325 392 524 450 + +length(rivers) # Combien de rivers ont été mesurées ? +# 141 +summary(rivers) # quelles sont les statistiques sommaires ? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# Fait un diagramme à tiges et à feuilles (visualisation de données de +types histogramme) +stem(rivers) + + +# Le point décimal est de 2 chiffres à droite du | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) # Notez que les données ne sont ni normales ni lognormales ! +# Prenez-ça les fondamentalistes, la courbe en cloche + +# Le point décimal est à 1 chiffre à gauche du | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + +# Fais un histogramme : +hist(rivers, col="#333333", border="white", breaks=25) # amusez-vous avec ces parenthèses +hist(log(rivers), col="#333333", border="white", breaks=25) # vous ferez plus de tracés plus tard + +# Ici d'autres données nettes qui viennent préchargées. R en a des tonnes. +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", + main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", + main="Number of important discoveries per year") + +# Plutôt que de laisser l'ordre par défaut (par années) +# Nous pourrions aussi trier pour voir ce qu'il y a de typique +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# Le point décimale est à la | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + +# Lance un dès quelques fois +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Vos numéros diffèreront des miens à moins que nous mettions le même random.seed(31337) + +# Dessine à partir d'une normale Gaussienne 9 fois +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +################################################## +# les types de données et l'arithmétique de base +################################################## + +# Now for the programming-oriented part of the tutorial. +# In this section you will meet the important data types of R: +# integers, numerics, characters, logicals, and factors. +# There are others, but these are the bare minimum you need to +# get started. + +# Maintenant pour la partie orientée programmation du tutoriel. +# Dans cette section vous rencontrerez les types de données importants de R : +# les entiers, les numériques, les caractères, les logiques, et les facteurs. + +# LES ENTIERS +# Les entiers de mémoire longue sont écrit avec L +5L # 5 +class(5L) # "integer" +# (Essayez ?class pour plus d'information sur la fonction class().) +# Avec R, chaque valeur seule, comme 5L, est considéré comme un vecteur de longueur 1 +length(5L) # 1 +# On peut avoir un vecteur d'entiers avec une longueur > 1 aussi : +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# LES NUMÉRIQUES +# Un "numeric" est un nombre à virgule flottante avec une double précision +5 # 5 +class(5) # "numeric" +# Encore une fois, tout dans R est un vecteur ; +# Vous pouvez faire un vecteur numérique avec plus d'un élément +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# Vous pouvez utiliser la notation scientifique aussi +5e4 # 50000 +6.02e23 # nombre d'Avogadro +1.6e-35 # longueur de Planck +# Vous pouvez également avoir des nombres infiniments grands ou petits +class(Inf) # "numeric" +class(-Inf) # "numeric" +# Vous pouvez utiliser "Inf", par exemple, dans integrate(dnorm, 3, Inf); +# Ça permet d'éviter des tableaux Z-scores. + +# ARITHMÉTIQUES DE BASE +# Vous pouvez faire de l'arithmétique avec des nombres +# Faire des opérations arithmétiques en mixant des entiers et des numériques +# donne un autre numérique +10L + 66L # 76 # un entier plus un entier donne un entier +53.2 - 4 # 49.2 # un numérique moins un numérique donne un numérique +2.0 * 2L # 4 # un numérique multiplié par un entier donne un numérique +3L / 4 # 0.75 # un entier sur un numérique donne un numérique +3 %% 2 # 1 # le reste de deux numériques est un autre numérique +# Les opérations arithmétiques illégales rapportent un "Not A Number" : +0 / 0 # NaN +class(NaN) # "numeric" +# You can do arithmetic on two vectors with length greater than 1, +# Vous pouvez faire des opérations arithmétiques avec deux vecteurs d'une +# longueur plus grande que 1, à condition que la longueur du plus grand +# vecteur soit un multiple entier du plus petit +c(1,2,3) + c(1,2,3) # 2 4 6 + +# LES CARACTÈRES +# Il n'y a pas de différences entre les chaînes de caractères et les caractères en R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# Ceux-ci sont tous les deux des vecteurs de longueur 1 +# Ici un plus long : +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# Vous pouvez faire des expressions rationnelles sur les vecteurs de caractères : +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R possède plusieurs vecteurs de caractères préconstruits : +letters +# => +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + +# LES TYPES LOGIQUES +# En R, un "logical" est un booléen +class(TRUE) # "logical" +class(FALSE) # "logical" +# Leur comportement est normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Les données manquantes (NA) sont logiques également +class(NA) # "logical" +# Ici nous avons un vecteur de type logique avec plusieurs éléments : +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# LES FACTEURS +# The factor class is for categorical data +# La classe facteur sert aux données catégorielles +# les facteurs peuvent être ordonnés (comme les niveaux de catégorie d'enfants) +# ou non ordonnés (comme le sexe) +factor(c("female", "female", "male", NA, "female")) +# female female male female +# Les niveaux : female male +# Les "levels" sont les valeurs que les données catégorielles peuvent prendre +# Notez que cette donnée manquante n'entre pas dans le niveau +levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" +# Si le vecteur de facteurs a une longueur 1, ses niveaux seront de longueur 1 également +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# On rencontre communément des facteurs dans des trames de données, +# une structure de données que nous couvrirons plus tard +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" est bizarre ; on l'utilise pour effacer un vecteur +class(NULL) # NULL +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL + +# LES CONTRAINTES DE TYPES +# Les contraintes de types servent à forcer une valeur à prendre un type différent +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# Si vous mettez des éléments de différents types dans un vecteur, des coercitions bizarres se produisent : +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Message d'avertissement : +# NAs est introduit par coercition + +# Notez également : ce n'étaient que des types de données basiques +# Il y a beaucoup d'autres types de données, comme pour les dates, les séries de temps, etc ... + + + +################################################## +# Variables, boucles , if/else +################################################## + +# Une variable est comme une boîte où l'on garde une valeur pour l'utiliser plus tard. +# Nous appellons ça "assigner" une valeur à une variable. +# Avoir des variables nous permets d'écrire des boucles, des fonctions, et +# des instructions conditionnelles (if/else) + +# LES VARIABLES +# Beaucoup de façons d'assigner des choses : +x = 5 # c'est possible +y <- "1" # c'est préféré +TRUE -> z # ça marche mais c'est bizarre + +# LES BOUCLES +# Il y a les boucles for : +for (i in 1:4) { + print(i) +} +# Il y a les boucles while : +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# Gardez à l'esprit que les boucles for et while s'exécute lentement en R +# Des opérations sur des vecteurs entiers (ex un ligne entière, une colonne entière), +# ou la fonction apply()-type (nous en parlerons plus tard), sont préférés + +# IF/ELSE +# Encore une fois assez standard +if (4 > 3) { + print("4 is greater than 3") +} else { + print("4 is not greater than 3") +} +# => +# [1] "4 is greater than 3" + +# LES FONCTIONS +# se définissent comme ceci : +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + return(x) +} +# Appelée comme n'importe quelle autre fonction R : +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################### +# Les structures de données : les vecteurs, les matrices, les trames de données et les tableaux +########################################################################### + +# À UNE DIMENSION + +# Commençons par le tout début, et avec quelque chose que vous connaissez déjà : les vecteurs. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# Nous demandons des éléments spécifiques en les mettant entre crochets +# (Notez que R commence à compter par 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# Nous pouvons également rechercher des indices de composants spécifiques, +which(vec %% 2 == 0) # 1 3 +# Récupèrer seulement quelques premières ou dernières entrées du vecteur, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# ou trouver si un certaine valeur est dans le vecteur +any(vec == 10) # TRUE +# Si un index "dépasse" vous obtiendrez NA : +vec[6] # NA +# Vous pouvez trouver la longueur de votre vecteur avec length() +length(vec) # 4 +# Vous pouvez réaliser des opérations sur des vecteurs entiers ou des sous-ensembles de vecteurs +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE +# Et R a beaucoup de fonctions préconstruites pour résumer les vecteurs +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Quelques fonctions préconstruites sympas supplémentaires : +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# => +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +# À DEUX DIMENSIONS (TOUT DANS UNE CLASSE) + +# Vous pouvez faire une matrice de toutes les entrées du même type comme ceci : +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Différemment du vecteur, la classe d'une matrice est "matrix",peut importe ce qu'elle contient +class(mat) # => "matrix" +# Demander la première ligne +mat[1,] # 1 4 +# Réaliser une opération sur la première colonne +3 * mat[,1] # 3 6 9 +# Ask for a specific cell +mat[3,2] # 6 + +# Transposer la matrice entière +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# La multiplication de matrices +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() colle des vecteurs ensemble en colonne pour faire une matrice +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +# Encore une fois notez ce qui se passe ! +# Parce que les matrices peuvent contenir des entrées de toutes sortes de classes, +# tout sera converti en classe caractère +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() colle des vecteurs ensemble par lignes pour faire une matrice +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, tout de la même classe. Pas de coercitions. Beaucoup mieux. + +# À DEUX DIMENSIONS (DE CLASSES DIFFÉRENTES) + +# Pour des colonnes de différents types, utiliser une trame de donnée +# Cette structure de données est si utile pour la programmation statistique, +# qu'une version a été ajoutée à Python dans le paquet "pandas". + +students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(students) <- c("name", "year", "house") # name the columns +class(students) # "data.frame" +students +# => +# name year house +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(students$year) # "numeric" +class(students[,3]) # "factor" +# Trouver les dimensions +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# La fonction data.frame() convertit les vecteurs caractères en vecteurs de facteurs +# par défaut; désactiver cette fonction en règlant stringsAsFactors = FALSE +# quand vous créer la data.frame +?data.frame + +# Il y a plusieurs façons tortueuses de subdiviser les trames de données +# toutes subtilement différentes +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + +# Une version augmentée de la structure data.frame est data.table +# Si vous travaillez avec des données volumineuses ou des panels, ou avez +# besoin de fusionner quelques ensembles de données, data.table peut être +# un bon choix. Ici un tour éclair : +install.packages("data.table") # download the package from CRAN +require(data.table) # load it +students <- as.data.table(students) +students # note the slightly different print-out +# => +# name year house +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +students[name=="Ginny"] # get rows with name == "Ginny" +# => +# name year house +# 1: Ginny -1 G +students[year==2] # get rows with year == 2 +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +# data.table facilite la fusion entre deux ensembles de données +# Faisons un autre data.table pour fusionner students +founders <- data.table(house=c("G","H","R","S"), + founder=c("Godric","Helga","Rowena","Salazar")) +founders +# => +# house founder +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(students, house) +setkey(founders, house) +students <- founders[students] # merge the two data sets by matching "house" +setnames(students, c("house","houseFounderName","studentName","year")) +students[,order(c("name","year","house","houseFounderName")), with=F] +# => +# studentName year house houseFounderName +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + +# data.table facilite le sommaire des tableaux +students[,sum(year),by=house] +# => +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# Pour supprimer une colonne d'une data.frame ou data.table, +# assignez-lui la valeur NULL +students$houseFounderName <- NULL +students +# => +# studentName year house +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Supprimer une ligne en subdivisant +# En utilisant data.table : +students[studentName != "Draco"] +# => +# house studentName year +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# En utilisant data.frame : +students <- as.data.frame(students) +students[students$house != "G",] +# => +# house houseFounderName studentName year +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTI-DIMENSIONNELLE (TOUS ÉLÉMENTS D'UN TYPE) + +# Les arrays créent des tableaux de n dimensions +# Tous les éléments doivent être du même type +# Vous pouvez faire un tableau à 2 dimensions (une sorte de matrice) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# Vous pouvez utiliser array pour faire des matrices à 3 dimensions aussi +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LES LISTES (MULTI-DIMENSIONNELLES, ÉVENTUELLEMMENT DÉCHIRÉES, DE DIFFÉRENTS TYPES) + +# Enfin R a des listes (de vecteurs) +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1 +# Vous pouvez obtenir des éléments de la liste comme ceci +list1$time # one way +list1[["time"]] # another way +list1[[1]] # yet another way +# => +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# Vous pouvez subdiviser les éléments d'une liste comme n'importe quel vecteur +list1$price[4] + +# Les listes ne sont pas les structures de données les plus efficaces +# pour travailler en R; +# À moins d'avoir une très bonne raison, vous devriez appliquer data.frames +# Les listes sont souvent retournées par des fonctions qui effectuent des régressions linéaires + +################################################## +# La famille de fonction apply() +################################################## + +# Vous vous rappelez mat ? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Utilisez apply(X, MARGIN, FUN) pour appliquer la fonction FUN à la matrice X +# sur les lignes (MAR = 1) ou les colonnes (MAR = 2) +# R fait FUN à chaque lignes (ou colonnes) de X, beaucoup plus rapidement +# qu'une bouce for ou while le ferait +apply(mat, MAR = 2, jiggle) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# D'autres fonctions : ?lapply, ?sapply + +# Ne soyez pas trop intimidé ; tout le monde reconnaît que c'est un peu déroutant + +# Le paque plyr vise à remplacer (et améliorer !) la famille *apply(). +install.packages("plyr") +require(plyr) +?plyr + + + +######################### +# Charger des données +######################### + +# "pets.csv" est un fichier sur internet +# (mais il pourrait être tout aussi facilement sur votre ordinateur) +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # first two rows +tail(pets, 1) # last row + +# Pour sauver une trame de donnée ou une matrice en fichier .csv +write.csv(pets, "pets2.csv") # to make a new .csv file +# définir le répertoire de travail avec setwd(), le récupérer avec getwd() + +# Essayez ?read.csv et ?write.csv pour plus d'informations + + + +######################### +# Les tracés +######################### + +# LES FONCTIONS DE TRACÉS PRÉCONSTRUITES +# Les diagrammes de dispersion ! +plot(list1$time, list1$price, main = "fake data") +# Les régressions ! +linearModel <- lm(price ~ time, data = list1) +linearModel # sort le résultat de la régression +# Tracer une ligne de regression sur une tracé existant +abline(linearModel, col = "red") +# Obtenir une variété de diagnostiques sympas +plot(linearModel) +# Les histogrammes ! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Les diagrammes en bâtons ! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# Mais ceux-ci ne sont même pas les plus jolis tracés de R +# Essayez le paquet ggplot2 pour d'avantages de graphiques meilleurs +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(students, aes(x=house)) +pp + geom_histogram() +ll <- as.data.table(list1) +pp <- ggplot(ll, aes(x=time,price)) +pp + geom_point() +# ggplot2 a une documentation excellente (disponible sur http://docs.ggplot2.org/current/) + + + +``` + +## How do I get R? + +* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) is another GUI -- cgit v1.2.3 From a6c01bf515c02522f3ff128a7d55806908ea3871 Mon Sep 17 00:00:00 2001 From: Chtiprog Date: Sun, 3 May 2015 21:44:23 -0300 Subject: add french translation of R --- fr-fr/r-fr.html.markdown | 286 +++++++++++++++++++++++++---------------------- 1 file changed, 154 insertions(+), 132 deletions(-) diff --git a/fr-fr/r-fr.html.markdown b/fr-fr/r-fr.html.markdown index 8db78ef3..d6879c1f 100644 --- a/fr-fr/r-fr.html.markdown +++ b/fr-fr/r-fr.html.markdown @@ -9,9 +9,9 @@ filename: learnr-fr.r --- R est un langage de programmation statistique. Il dispose de nombreuses -librairies pour le téléchargement et le nettoyage des ensembles de données, -l'exécution de procédures statistiques, et pour faire des graphiques. -On peut également exécuter les commmandes R à l'aide d'un document LaTeX. +librairies pour le téléchargement et le nettoyage d'ensembles de données, +l'exécution de procédures statistiques, et la réalisation de graphiques. +On peut également exécuter les commmandes `R` au sein d'un document LaTeX. ```r @@ -25,30 +25,30 @@ On peut également exécuter les commmandes R à l'aide d'un document LaTeX. -############################################################################# -# Les choses que vous pouvez faire sans rien comprendre à la programmation -############################################################################# +######################################################################## +# Les choses que vous pouvez faire sans rien comprendre +# à la programmation +######################################################################## -# In this section, we show off some of the cool stuff you can do in # Dans cette section, nous vous montrons quelques trucs cools que vous # pouvez faire avec R sans rien comprendre à la programmation. # Ne vous inquiétez pas si vous ne comprenez pas tout ce que le code fait. # Profitez simplement ! -data() # parcours les ensembles de données préchargées -data(rivers) # obtiens celui-ci: "Lengths of Major North American Rivers" -ls() # notez que "rivers" apparaît maintenant dans votre espace de travail -head(rivers) # Jetez un coup d'oeil à l'ensemble de données +data() # parcours les ensembles de données préchargées +data(rivers) # récupère ceci : "Lengths of Major North American Rivers" +ls() # notez que "rivers" apparaît maintenant dans votre espace de travail +head(rivers) # donne un aperçu des données # 735 320 325 392 524 450 length(rivers) # Combien de rivers ont été mesurées ? # 141 -summary(rivers) # quelles sont les statistiques sommaires ? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 +summary(rivers) # Quels sont les principales données statistiques ? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 # Fait un diagramme à tiges et à feuilles (visualisation de données de -types histogramme) +# types histogramme) stem(rivers) @@ -64,23 +64,24 @@ stem(rivers) # 14 | 56 # 16 | 7 # 18 | 9 -# 20 | +# 20 | # 22 | 25 # 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | # 36 | 1 -stem(log(rivers)) # Notez que les données ne sont ni normales ni lognormales ! -# Prenez-ça les fondamentalistes, la courbe en cloche +stem(log(rivers)) # Notez que les données ne sont ni normales +# ni lognormales ! +# Prenez-ça, la courbe en cloche # Le point décimal est à 1 chiffre à gauche du | # # 48 | 1 -# 50 | +# 50 | # 52 | 15578 # 54 | 44571222466689 # 56 | 023334677000124455789 @@ -95,14 +96,14 @@ stem(log(rivers)) # Notez que les données ne sont ni normales ni lognormales ! # 74 | 84 # 76 | 56 # 78 | 4 -# 80 | +# 80 | # 82 | 2 # Fais un histogramme : -hist(rivers, col="#333333", border="white", breaks=25) # amusez-vous avec ces parenthèses +hist(rivers, col="#333333", border="white", breaks=25) # amusez-vous avec ces paramètres hist(log(rivers), col="#333333", border="white", breaks=25) # vous ferez plus de tracés plus tard -# Ici d'autres données nettes qui viennent préchargées. R en a des tonnes. +# Ici d'autres données qui viennent préchargées. R en a des tonnes. data(discoveries) plot(discoveries, col="#333333", lwd=3, xlab="Year", main="Number of important discoveries per year") @@ -118,7 +119,7 @@ sort(discoveries) # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 stem(discoveries, scale=2) -# +# # Le point décimale est à la | # # 0 | 000000000 @@ -132,19 +133,20 @@ stem(discoveries, scale=2) # 8 | 0 # 9 | 0 # 10 | 0 -# 11 | +# 11 | # 12 | 0 max(discoveries) # 12 summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 -# Lance un dès quelques fois +# Lance un dès plusieurs fois round(runif(7, min=.5, max=6.5)) # 1 4 6 1 4 6 4 -# Vos numéros diffèreront des miens à moins que nous mettions le même random.seed(31337) +# Vos numéros diffèreront des miens à moins que nous mettions +# le même random.seed(31337) # Dessine à partir d'une normale Gaussienne 9 fois rnorm(9) @@ -153,15 +155,9 @@ rnorm(9) -################################################## +############################################################## # les types de données et l'arithmétique de base -################################################## - -# Now for the programming-oriented part of the tutorial. -# In this section you will meet the important data types of R: -# integers, numerics, characters, logicals, and factors. -# There are others, but these are the bare minimum you need to -# get started. +############################################################## # Maintenant pour la partie orientée programmation du tutoriel. # Dans cette section vous rencontrerez les types de données importants de R : @@ -171,22 +167,23 @@ rnorm(9) # Les entiers de mémoire longue sont écrit avec L 5L # 5 class(5L) # "integer" -# (Essayez ?class pour plus d'information sur la fonction class().) -# Avec R, chaque valeur seule, comme 5L, est considéré comme un vecteur de longueur 1 +# (Essayez ?class pour plus d'informations sur la fonction class().) +# Avec R, chaque valeur seule, comme 5L, est considéré comme +# un vecteur de longueur 1 length(5L) # 1 -# On peut avoir un vecteur d'entiers avec une longueur > 1 aussi : +# On peut avoir un vecteur d'entiers avec une longueur > 1 : c(4L, 5L, 8L, 3L) # 4 5 8 3 length(c(4L, 5L, 8L, 3L)) # 4 class(c(4L, 5L, 8L, 3L)) # "integer" # LES NUMÉRIQUES -# Un "numeric" est un nombre à virgule flottante avec une double précision +# Un "numeric" est un nombre à virgule flottante d'une précision double 5 # 5 class(5) # "numeric" # Encore une fois, tout dans R est un vecteur ; # Vous pouvez faire un vecteur numérique avec plus d'un élément c(3,3,3,2,2,1) # 3 3 3 2 2 1 -# Vous pouvez utiliser la notation scientifique aussi +# Vous pouvez aussi utiliser la notation scientifique 5e4 # 50000 6.02e23 # nombre d'Avogadro 1.6e-35 # longueur de Planck @@ -198,24 +195,25 @@ class(-Inf) # "numeric" # ARITHMÉTIQUES DE BASE # Vous pouvez faire de l'arithmétique avec des nombres -# Faire des opérations arithmétiques en mixant des entiers et des numériques +# Faire des opérations arithmétiques en mixant des entiers +# et des numériques # donne un autre numérique 10L + 66L # 76 # un entier plus un entier donne un entier 53.2 - 4 # 49.2 # un numérique moins un numérique donne un numérique 2.0 * 2L # 4 # un numérique multiplié par un entier donne un numérique 3L / 4 # 0.75 # un entier sur un numérique donne un numérique -3 %% 2 # 1 # le reste de deux numériques est un autre numérique -# Les opérations arithmétiques illégales rapportent un "Not A Number" : +3 %% 2 # 1 # le reste de deux numériques est un autre numérique +# Les opérations arithmétiques illégales donnent un "Not A Number" : 0 / 0 # NaN class(NaN) # "numeric" -# You can do arithmetic on two vectors with length greater than 1, # Vous pouvez faire des opérations arithmétiques avec deux vecteurs d'une # longueur plus grande que 1, à condition que la longueur du plus grand # vecteur soit un multiple entier du plus petit c(1,2,3) + c(1,2,3) # 2 4 6 # LES CARACTÈRES -# Il n'y a pas de différences entre les chaînes de caractères et les caractères en R +# Il n'y a pas de différences entre les chaînes de caractères et +# les caractères en R "Horatio" # "Horatio" class("Horatio") # "character" class('H') # "character" @@ -225,7 +223,7 @@ c('alef', 'bet', 'gimmel', 'dalet', 'he') # => # "alef" "bet" "gimmel" "dalet" "he" length(c("Call","me","Ishmael")) # 3 -# Vous pouvez faire des expressions rationnelles sur les vecteurs de caractères : +# Vous pouvez utiliser des expressions rationnelles sur les vecteurs de caractères : substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." # R possède plusieurs vecteurs de caractères préconstruits : @@ -246,45 +244,57 @@ FALSE != FALSE # FALSE FALSE != TRUE # TRUE # Les données manquantes (NA) sont logiques également class(NA) # "logical" +# On utilise | et & pour les operations logiques. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Vous pouvez tester si x est TRUE +isTRUE(TRUE) # TRUE # Ici nous avons un vecteur de type logique avec plusieurs éléments : c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE # LES FACTEURS -# The factor class is for categorical data -# La classe facteur sert aux données catégorielles -# les facteurs peuvent être ordonnés (comme les niveaux de catégorie d'enfants) +# La classe facteur sert pour les données catégorielles +# les facteurs peuvent être ordonnés (comme les niveaux de +# catégorie d'enfants) # ou non ordonnés (comme le sexe) factor(c("female", "female", "male", NA, "female")) # female female male female # Les niveaux : female male -# Les "levels" sont les valeurs que les données catégorielles peuvent prendre -# Notez que cette donnée manquante n'entre pas dans le niveau +# Les "levels" sont les valeurs que les données catégorielles +# peuvent prendre +# Notez que les données manquantes n'entrent pas dans le niveau levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" -# Si le vecteur de facteurs a une longueur 1, ses niveaux seront de longueur 1 également +# Si le vecteur de facteurs a une longueur 1, ses niveaux seront +# de longueur 1 également length(factor("male")) # 1 length(levels(factor("male"))) # 1 -# On rencontre communément des facteurs dans des trames de données, -# une structure de données que nous couvrirons plus tard +# On rencontre communément des facteurs dans des "data frame", +# un type de données que nous couvrirons plus tard data(infert) # "Infertility after Spontaneous and Induced Abortion" levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" # NULL # "NULL" est bizarre ; on l'utilise pour effacer un vecteur class(NULL) # NULL +parakeet = c("beak", "feathers", "wings", "eyes") parakeet # => -# [1] "beak" "feathers" "wings" "eyes" +# [1] "beak" "feathers" "wings" "eyes" parakeet <- NULL parakeet # => # NULL # LES CONTRAINTES DE TYPES -# Les contraintes de types servent à forcer une valeur à prendre un type différent +# Les contraintes de types servent à forcer une valeur à prendre +# un type différent as.character(c(6, 8)) # "6" "8" as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE -# Si vous mettez des éléments de différents types dans un vecteur, des coercitions bizarres se produisent : +# Si vous mettez des éléments de différents types dans un vecteur, +# des coercitions bizarres se produisent : c(TRUE, 4) # 1 4 c("dog", TRUE, 4) # "dog" "TRUE" "4" as.numeric("Bilbo") @@ -294,17 +304,19 @@ as.numeric("Bilbo") # NAs est introduit par coercition # Notez également : ce n'étaient que des types de données basiques -# Il y a beaucoup d'autres types de données, comme pour les dates, les séries de temps, etc ... +# Il y a beaucoup d'autres types de données, comme pour les dates, +# les séries temporelles, etc ... -################################################## +####################################### # Variables, boucles , if/else -################################################## +####################################### -# Une variable est comme une boîte où l'on garde une valeur pour l'utiliser plus tard. +# Une variable est comme une boîte dans laquelle on garde une valeur +# pour l'utiliser plus tard. # Nous appellons ça "assigner" une valeur à une variable. -# Avoir des variables nous permets d'écrire des boucles, des fonctions, et +# Avoir des variables nous permet d'écrire des boucles, des fonctions, et # des instructions conditionnelles (if/else) # LES VARIABLES @@ -321,19 +333,22 @@ for (i in 1:4) { # Il y a les boucles while : a <- 10 while (a > 4) { - cat(a, "...", sep = "") - a <- a - 1 + cat(a, "...", sep = "") + a <- a - 1 } -# Gardez à l'esprit que les boucles for et while s'exécute lentement en R -# Des opérations sur des vecteurs entiers (ex un ligne entière, une colonne entière), -# ou la fonction apply()-type (nous en parlerons plus tard), sont préférés +# Gardez à l'esprit que les boucles for et while s'exécutent lentement +# en R +# Des opérations sur des vecteurs entiers (ex une ligne entière, +# une colonne entière), +# ou les fonctions de type apply() (nous en parlerons plus tard), +# sont préférées # IF/ELSE # Encore une fois assez standard if (4 > 3) { - print("4 is greater than 3") + print("4 is greater than 3") } else { - print("4 is not greater than 3") + print("4 is not greater than 3") } # => # [1] "4 is greater than 3" @@ -341,25 +356,27 @@ if (4 > 3) { # LES FONCTIONS # se définissent comme ceci : jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise - return(x) + x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + return(x) } -# Appelée comme n'importe quelle autre fonction R : +# Appelées comme n'importe quelles autres fonction R : jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 -########################################################################### -# Les structures de données : les vecteurs, les matrices, les trames de données et les tableaux -########################################################################### +########################################################################## +# Les structures de données : les vecteurs, les matrices, +# les data frame et les tableaux +########################################################################## # À UNE DIMENSION -# Commençons par le tout début, et avec quelque chose que vous connaissez déjà : les vecteurs. +# Commençons par le tout début, et avec quelque chose que +# vous connaissez déjà : les vecteurs. vec <- c(8, 9, 10, 11) vec # 8 9 10 11 # Nous demandons des éléments spécifiques en les mettant entre crochets -# (Notez que R commence à compter par 1) +# (Notez que R commence à compter à partir de 1) vec[1] # 8 letters[18] # "r" LETTERS[13] # "M" @@ -367,7 +384,7 @@ month.name[9] # "September" c(6, 8, 7, 5, 3, 0, 9)[3] # 7 # Nous pouvons également rechercher des indices de composants spécifiques, which(vec %% 2 == 0) # 1 3 -# Récupèrer seulement quelques premières ou dernières entrées du vecteur, +# Récupèrer seulement les premières ou dernières entrées du vecteur, head(vec, 1) # 8 tail(vec, 2) # 10 11 # ou trouver si un certaine valeur est dans le vecteur @@ -376,7 +393,8 @@ any(vec == 10) # TRUE vec[6] # NA # Vous pouvez trouver la longueur de votre vecteur avec length() length(vec) # 4 -# Vous pouvez réaliser des opérations sur des vecteurs entiers ou des sous-ensembles de vecteurs +# Vous pouvez réaliser des opérations sur des vecteurs entiers ou des +# sous-ensembles de vecteurs vec * 4 # 16 20 24 28 vec[2:3] * 5 # 25 30 any(vec[2:3] == 8) # FALSE @@ -396,7 +414,7 @@ seq(from=0, to=31337, by=1337) # À DEUX DIMENSIONS (TOUT DANS UNE CLASSE) -# Vous pouvez faire une matrice de toutes les entrées du même type comme ceci : +# Vous pouvez créer une matrice à partir d'entrées du même type comme ceci : mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) mat # => @@ -404,13 +422,14 @@ mat # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 -# Différemment du vecteur, la classe d'une matrice est "matrix",peut importe ce qu'elle contient +# Différemment du vecteur, la classe d'une matrice est "matrix", +# peut importe ce qu'elle contient class(mat) # => "matrix" # Demander la première ligne mat[1,] # 1 4 # Réaliser une opération sur la première colonne 3 * mat[,1] # 3 6 9 -# Ask for a specific cell +# Demander une cellule spécifique mat[3,2] # 6 # Transposer la matrice entière @@ -432,15 +451,15 @@ mat %*% t(mat) mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix -# Encore une fois notez ce qui se passe ! -# Parce que les matrices peuvent contenir des entrées de toutes sortes de classes, -# tout sera converti en classe caractère +# Encore une fois regardez ce qui se passe ! +# Parce que les matrices peuvent contenir des entrées de toutes sortes de +# classes, tout sera converti en classe caractère c(class(mat2[,1]), class(mat2[,2])) # rbind() colle des vecteurs ensemble par lignes pour faire une matrice @@ -454,7 +473,7 @@ mat3 # À DEUX DIMENSIONS (DE CLASSES DIFFÉRENTES) -# Pour des colonnes de différents types, utiliser une trame de donnée +# Pour des colonnes de différents types, utiliser une data frame # Cette structure de données est si utile pour la programmation statistique, # qu'une version a été ajoutée à Python dans le paquet "pandas". @@ -478,25 +497,25 @@ class(students[,3]) # "factor" nrow(students) # 6 ncol(students) # 3 dim(students) # 6 3 -# La fonction data.frame() convertit les vecteurs caractères en vecteurs de facteurs -# par défaut; désactiver cette fonction en règlant stringsAsFactors = FALSE -# quand vous créer la data.frame +# La fonction data.frame() convertit les vecteurs caractères en vecteurs de +# facteurs par défaut; désactiver cette fonction en règlant +# stringsAsFactors = FALSE quand vous créer la data.frame ?data.frame -# Il y a plusieurs façons tortueuses de subdiviser les trames de données +# Il y a plusieurs façons de subdiviser les trames de données # toutes subtilement différentes students$year # 3 2 2 1 0 -1 students[,2] # 3 2 2 1 0 -1 students[,"year"] # 3 2 2 1 0 -1 # Une version augmentée de la structure data.frame est data.table -# Si vous travaillez avec des données volumineuses ou des panels, ou avez +# Si vous travaillez avec des données volumineuses ou des panels, ou avez # besoin de fusionner quelques ensembles de données, data.table peut être # un bon choix. Ici un tour éclair : -install.packages("data.table") # download the package from CRAN -require(data.table) # load it +install.packages("data.table") # télécharge le paquet depuis CRAN +require(data.table) # le charge students <- as.data.table(students) -students # note the slightly different print-out +students # regardez la différence à l'impression # => # name year house # 1: Cedric 3 H @@ -505,17 +524,17 @@ students # note the slightly different print-out # 4: Cho 1 R # 5: Draco 0 S # 6: Ginny -1 G -students[name=="Ginny"] # get rows with name == "Ginny" +students[name=="Ginny"] # obtiens les lignes avec name == "Ginny" # => # name year house # 1: Ginny -1 G -students[year==2] # get rows with year == 2 +students[year==2] # obtiens les lignes avec year == 2 # => # name year house # 1: Fred 2 G # 2: George 2 G # data.table facilite la fusion entre deux ensembles de données -# Faisons un autre data.table pour fusionner students +# Faisons une autre data.table pour fusionner students founders <- data.table(house=c("G","H","R","S"), founder=c("Godric","Helga","Rowena","Salazar")) founders @@ -527,7 +546,7 @@ founders # 4: S Salazar setkey(students, house) setkey(founders, house) -students <- founders[students] # merge the two data sets by matching "house" +students <- founders[students] # merge les deux ensembles de données qui matchent "house" setnames(students, c("house","houseFounderName","studentName","year")) students[,order(c("name","year","house","houseFounderName")), with=F] # => @@ -539,7 +558,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F] # 5: Cho 1 R Rowena # 6: Draco 0 S Salazar -# data.table facilite le sommaire des tableaux +# data.table facilite le résumé des tableaux students[,sum(year),by=house] # => # house V1 @@ -561,7 +580,7 @@ students # 5: Cho 1 R # 6: Draco 0 S -# Supprimer une ligne en subdivisant +# Supprimer une ligne en subdivisant # En utilisant data.table : students[studentName != "Draco"] # => @@ -607,16 +626,17 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # [2,] 60 7 # [3,] 0 847 -# LES LISTES (MULTI-DIMENSIONNELLES, ÉVENTUELLEMMENT DÉCHIRÉES, DE DIFFÉRENTS TYPES) +# LES LISTES (MULTI-DIMENSIONNELLES, ÉVENTUELLEMMENT DÉCHIRÉES, +# DE DIFFÉRENTS TYPES) # Enfin R a des listes (de vecteurs) list1 <- list(time = 1:40) list1$price = c(rnorm(40,.5*list1$time,4)) # random list1 # Vous pouvez obtenir des éléments de la liste comme ceci -list1$time # one way -list1[["time"]] # another way -list1[[1]] # yet another way +list1$time # une façon +list1[["time"]] # une autre façon +list1[[1]] # encore une façon différente # => # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 # [34] 34 35 36 37 38 39 40 @@ -624,13 +644,14 @@ list1[[1]] # yet another way list1$price[4] # Les listes ne sont pas les structures de données les plus efficaces -# pour travailler en R; -# À moins d'avoir une très bonne raison, vous devriez appliquer data.frames -# Les listes sont souvent retournées par des fonctions qui effectuent des régressions linéaires +# à utiliser avec R; +# À moins d'avoir une très bonne raison, vous devriez utiliser data.frames +# Les listes sont souvent retournées par des fonctions qui effectuent +# des régressions linéaires -################################################## +########################################## # La famille de fonction apply() -################################################## +########################################## # Vous vous rappelez mat ? mat @@ -641,8 +662,8 @@ mat # [3,] 3 6 # Utilisez apply(X, MARGIN, FUN) pour appliquer la fonction FUN à la matrice X # sur les lignes (MAR = 1) ou les colonnes (MAR = 2) -# R fait FUN à chaque lignes (ou colonnes) de X, beaucoup plus rapidement -# qu'une bouce for ou while le ferait +# R exécute FUN à chaque lignes (ou colonnes) de X, beaucoup plus rapidement +# que le ferait une boucle for ou while apply(mat, MAR = 2, jiggle) # => # [,1] [,2] @@ -650,7 +671,7 @@ apply(mat, MAR = 2, jiggle) # [2,] 7 19 # [3,] 11 23 # D'autres fonctions : ?lapply, ?sapply - + # Ne soyez pas trop intimidé ; tout le monde reconnaît que c'est un peu déroutant # Le paque plyr vise à remplacer (et améliorer !) la famille *apply(). @@ -660,9 +681,9 @@ require(plyr) -######################### +############################ # Charger des données -######################### +############################ # "pets.csv" est un fichier sur internet # (mais il pourrait être tout aussi facilement sur votre ordinateur) @@ -671,7 +692,7 @@ pets head(pets, 2) # first two rows tail(pets, 1) # last row -# Pour sauver une trame de donnée ou une matrice en fichier .csv +# Pour sauvegarder une data frame ou une matrice en fichier .csv write.csv(pets, "pets2.csv") # to make a new .csv file # définir le répertoire de travail avec setwd(), le récupérer avec getwd() @@ -679,9 +700,9 @@ write.csv(pets, "pets2.csv") # to make a new .csv file -######################### +################ # Les tracés -######################### +################ # LES FONCTIONS DE TRACÉS PRÉCONSTRUITES # Les diagrammes de dispersion ! @@ -700,7 +721,7 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) # GGPLOT2 # Mais ceux-ci ne sont même pas les plus jolis tracés de R -# Essayez le paquet ggplot2 pour d'avantages de graphiques meilleurs +# Essayez le paquet ggplot2 pour d'avantages de graphiques install.packages("ggplot2") require(ggplot2) ?ggplot2 @@ -709,13 +730,14 @@ pp + geom_histogram() ll <- as.data.table(list1) pp <- ggplot(ll, aes(x=time,price)) pp + geom_point() -# ggplot2 a une documentation excellente (disponible sur http://docs.ggplot2.org/current/) +# ggplot2 a une documentation excellente +#(disponible sur http://docs.ggplot2.org/current/) ``` -## How do I get R? +## Comment j'obtiens R ? -* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) -* [RStudio](http://www.rstudio.com/ide/) is another GUI +* Obtiens R et R GUI depuis [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) est un autre GUI -- cgit v1.2.3 From c21cf5a1e230dadf81bc4e31e2d2f9133551b365 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 4 May 2015 02:40:04 -0600 Subject: Templates and such --- c++.html.markdown | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index ae93ceba..10c39c9c 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -432,6 +432,81 @@ int main () { return 0; } +///////////////////// +// Templates +///////////////////// + +// Templates in C++ are mostly used for generic programming, though they are +// much more powerful than generics constructs in other languages. It also +// supports explicit and partial specialization, functional-style type classes, +// and also it's Turing-complete. + +// We start with the kind of generic programming you might be familiar with. To +// define a class or function that takes a type parameter: +template +class Box { + // In this class, T can be used as any other type. + void insert(const T&) { ... } +}; + +// During compilation, the compiler actually generates copies of each template +// with parameters substituted, and so the full definition of the class must be +// present at each invocation. This is why you will see template classes defined +// entirely in header files. + +// To instantiate a template class on the stack: +Box intBox; + +// and you can use it as you would expect: +intBox.insert(123); + +// You can, of course, nest templates: +Box > boxOfBox; +boxOfBox.insert(intBox); + +// Up until C++11, you muse place a space between the two '>'s, otherwise '>>' +// will be parsed as the right shift operator. + +// You will sometimes see +// template +// instead. The 'class' keyword and 'typename' keyword are _mostly_ +// interchangeable in this case. For full explanation, see +// http://en.wikipedia.org/wiki/Typename +// (yes, that keyword has its own Wikipedia page). + +// Similarly, a template function: +template +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// Notice that nothing is specified about the type parameters here. The compiler +// will generate and then type-check every invocation of the template, so the +// above function works with any type 'T' that has a const 'bark' method! + +Dog fluffy; +fluffy.setName("Fluffy") +barkThreeTimes(fluffy); Prints "Fluffy barks" three times. + +// Template parameters don't have to be classes, though this is used very rarely: +template +void printMessage() { + cout << "Learn C++ in " << Y << " minutes!" << endl; +} + +// And you can explicitly specialize templates for more efficient code: +template<> +void printMessage<10>() { + cout << "Learn C++ faster in only 10 minutes!" << endl; +} + +printMessage<20>(); // Prints "Learn C++ in 20 minutes!" +printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" + + ///////////////////// // Exception Handling ///////////////////// @@ -585,6 +660,33 @@ void doSomethingWithAFile(const std::string& filename) // vector (i.e. self-resizing array), hash maps, and so on // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock + + +///////////////////// +// Fun stuff +///////////////////// + +// Aspects of C++ that may be surprising to newcomers (and even some veterans): + +// You can override private methods! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // overrides Foo::bar! +}; + +// 0, false, NULL are all the same thing! +bool* pt = new bool; +*pt = 0; // Sets the value points by 'pt' to false. +pt = 0; // Sets 'pt' to the null pointer. Yes both lines compile without warning. + +// '=' != '=' +Foo f1 = f2; // Calls Foo::Foo(const Foo&) or some variant copy constructor. + +Foo f1; +f1 = f2; // Calls Foo::operator=(Foo&) or variant. + ``` Futher Reading: -- cgit v1.2.3 From 05c2617aaf6d040b1e4372d8f83df11288ff2279 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 4 May 2015 02:45:31 -0600 Subject: Minor fix --- c++.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 10c39c9c..e50c33fa 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -489,15 +489,16 @@ void barkThreeTimes(const T& input) Dog fluffy; fluffy.setName("Fluffy") -barkThreeTimes(fluffy); Prints "Fluffy barks" three times. +barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. -// Template parameters don't have to be classes, though this is used very rarely: +// Template parameters don't have to be classes: template void printMessage() { cout << "Learn C++ in " << Y << " minutes!" << endl; } -// And you can explicitly specialize templates for more efficient code: +// And you can explicitly specialize templates for more efficient code (most +// real-world uses of specialization are not as trivial as this): template<> void printMessage<10>() { cout << "Learn C++ faster in only 10 minutes!" << endl; -- cgit v1.2.3 From 6c635d1c3e5bb88940fb0afb01218d2e7d3f11c0 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Tue, 5 May 2015 00:45:14 -0600 Subject: Response to comments --- c++.html.markdown | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index e50c33fa..517ce367 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -497,8 +497,10 @@ void printMessage() { cout << "Learn C++ in " << Y << " minutes!" << endl; } -// And you can explicitly specialize templates for more efficient code (most -// real-world uses of specialization are not as trivial as this): +// And you can explicitly specialize templates for more efficient code. Of +// course, most real-world uses of specialization are not as trivial as this. +// Note that you still need to declare the function (or class) as a template +// even if you explicitly specified all parameters. template<> void printMessage<10>() { cout << "Learn C++ faster in only 10 minutes!" << endl; @@ -667,7 +669,9 @@ void doSomethingWithAFile(const std::string& filename) // Fun stuff ///////////////////// -// Aspects of C++ that may be surprising to newcomers (and even some veterans): +// Aspects of C++ that may be surprising to newcomers (and even some veterans). +// This section is, unfortunately, wildly incomplete; C++ is one of the easiest +// languages with which to shoot yourself in the foot. // You can override private methods! class Foo { @@ -677,16 +681,35 @@ class FooSub : public Foo { virtual void bar(); // overrides Foo::bar! }; -// 0, false, NULL are all the same thing! + +// 0 == false == NULL (most of the time)! bool* pt = new bool; *pt = 0; // Sets the value points by 'pt' to false. -pt = 0; // Sets 'pt' to the null pointer. Yes both lines compile without warning. +pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings. + +// nullptr is supposed to fix some of that issue: +int* pt2 = new int; +*pt2 = nullptr; // Doesn't compile +pt2 = nullptr; // Sets pt2 to null. + +// But somehow 'bool' type is an exception. +*pt = nullptr; // This still compiles, even though '*pt' is a bool! + + +// '=' != '=' != '='! +// Calls Foo::Foo(const Foo&) or some variant copy constructor. +Foo f2; +Foo f1 = f2; -// '=' != '=' -Foo f1 = f2; // Calls Foo::Foo(const Foo&) or some variant copy constructor. +// Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of +// 'fooSub'. Any extra members of 'fooSub' are discarded. This lovely behavior +// is called "object slicing." +FooSub fooSub; +Foo f1 = fooSub; +// Calls Foo::operator=(Foo&) or variant. Foo f1; -f1 = f2; // Calls Foo::operator=(Foo&) or variant. +f1 = f2; ``` Futher Reading: -- cgit v1.2.3 From 4e28ec0efdc127b51930aaa8de4f92e08c66011f Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Tue, 5 May 2015 21:21:53 -0700 Subject: new C++ it version --- it-it/c++-it.html.markdown | 597 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 597 insertions(+) create mode 100644 it-it/c++-it.html.markdown diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown new file mode 100644 index 00000000..8914c234 --- /dev/null +++ b/it-it/c++-it.html.markdown @@ -0,0 +1,597 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] +lang: it-it +--- + +Il C++ e' un linguaggio di programmazione il quale, +[secondo il suo inventore Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +e' stato progettato per + +- essere un "miglior C" +- supportare l'astrazione dei dati +- supportare la programmazione orientata agli oggetti +- supportare la programmazione generica + +Nonostante la sintassi possa risultare piu' difficile o complessa di linguaggi piu' recenti, +e' usato in maniera vasta poiche' viene compilato in istruzioni macchina che possono +essere eseguite direttamente dal processore ed offre un controllo stretto sull'hardware (come il linguaggio C) +ed allo stesso tempo offre caratteristiche ad alto livello come i generici, le eccezioni, e le classi. +Questa combinazione di velocita' e funzionalita' rende il C++ +uno dei piu' utilizzati linguaggi di programmazione. + +```c++ +////////////////// +// Confronto con il C +////////////////// + +// Il C++ e' _quasi_ un superset del C e con esso condivide la sintassi di base per +// la dichiarazione di variabili, tipi primitivi, e funzioni. + +// Proprio come nel C, l'inizio del programma e' una funzione chiamata +// main con un intero come tipo di ritorno, +// nonostante void main() sia anch'essa accettata dalla maggior parte dei compilatori(gcc, clang, ecc...) +// Questo valore serve come stato d'uscita del programma. +// Vedi http://it.wikipedia.org/wiki/Valore_di_uscita per maggiori informazioni. +int main(int argc, char** argv) +{ + // Gli argomenti a linea di comando sono passati tramite argc e argv cosi' come + // avviene in C. + // argc indica il numero di argomenti, + // e argv e' un array in stile-C di stringhe (char*) + // che rappresenta gl iargomenti. + // Il primo argomento e' il nome che e' stato assegnato al programma. + // argc e argv possono essere omessi se non hai bisogno di argomenti, + // in questa maniera la funzione avra' int main() come firma. + + // Lo stato di uscita 0 indica successo. + return 0; +} + +// Tuttavia, il C++ varia nei seguenti modi: + +// In C++, i caratteri come letterali sono da un byte. +sizeof('c') == 1 + +// In C, i caratteri come letterali sono della stessa dimensione degli interi. +sizeof('c') == sizeof(10) + + +// C++ ha prototipizzazione rigida +void func(); // funziona che non accetta argomenti + +// In C +void func(); // funzione che puo' accettare un qualsiasi numero di argomenti + +// Usa nullptr invece di NULL in C++ +int* ip = nullptr; + +// Gli header C standard sono disponibili in C++, +// ma sono prefissati con "c" e non hanno il suffisso ".h". +#include + +int main() +{ + printf("Ciao, mondo!\n"); + return 0; +} + +/////////////////////////////// +// Overloading per le funzioni +////////////////////////////// + +// Il C++ supporta l'overloading per le funzioni +// sia dato che ogni funzione accetta parametri diversi. + +void print(char const* myString) +{ + printf("Stringa %s\n", myString); +} + +void print(int myInt) +{ + printf("Il mio int e' %d", myInt); +} + +int main() +{ + print("Ciao"); // Viene chiamata void print(const char*) + print(15); // Viene chiamata void print(int) +} + +//////////////////////// +// Argomenti di default +/////////////////////// + +// Puoi fornire argomenti di default per una funzione +// se non sono forniti dal chiamante. + +void faiQualcosaConInteri(int a = 1, int b = 4) +{ + // fai qualcosa con gli interi qui +} + +int main() +{ + faiQualcosaConInteri(); // a = 1, b = 4 + faiQualcosaConInteri(20); // a = 20, b = 4 + faiQualcosaConInteri(20, 5); // a = 20, b = 5 +} + +// Gli argomenti di default devono essere alla fine della lista degli argomenti. + +void dichiarazioneInvalida(int a = 1, int b) // Errore! +{ +} + + +///////////// +// Namespaces +///////////// + +// I namespaces forniscono visibilita' separata per dichiarazioni di variabili, funzioni, +// ed altro. +// I namespaces possono essere annidati. + +namespace Primo { + namespace Annidato { + void foo() + { + printf("Questa e' Primo::Annidato::foo\n"); + } + } // fine di namespace Annidato +} // fine di namespace Primo + +namespace Secondo { + void foo() + { + printf("Questa e' Secondo::foo\n") + } +} + +void foo() +{ + printf("Questa e' foo globale\n"); +} + +int main() +{ + // Assume che tutto venga dal namespace "Secondo" + // a meno che non venga dichiarato altrimenti. + using namespace Secondo; + + foo(); // stampa "Questa e' Secondo::foo" + Primo::Annidato::foo(); // stampa "Questa e' Primo::Annidato::foo" + ::foo(); // stampa "Questa e' foo globale" +} + +/////////////// +// Input/Output +/////////////// + +// L'input e l'output in C++ utilizza gli streams +// cin, cout, e cerr i quali rappresentano stdin, stdout, e stderr. +// << e' l'operatore di inserzione >> e' l'operatore di estrazione. + +#include // Include for I/O streams + +using namespace std; // Gli streams sono nel namespace std (libreria standard) + +int main() +{ + int myInt; + + // Stampa su stdout (o terminalee/schermo) + cout << "Inserisci il tuo numero preferito:\n"; + // Prende l'input + cin >> myInt; + + // cout puo' anche essere formattato + cout << "Il tuo numero preferito e' " << myInt << "\n"; + // stampa "Il tuo numero preferito e' " + + cerr << "Usato per messaggi di errore"; +} + +//////////// +// Stringhe +/////////// + +// Le stringhe in C++ sono oggetti ed hanno molte funzioni membro +#include + +using namespace std; // Anche le stringhe sono contenute nel namespace std (libreria standard) + +string myString = "Ciao"; +string myOtherString = " Mondo"; + +// + e' usato per la concatenazione. +cout << myString + myOtherString; // "Ciao Mondo" + +cout << myString + " Bella"; // "Ciao Bella" + +// le stringhe in C++ possono essere modificate. +myString.append(" Mario"); +cout << myString; // "Ciao Mario" + + +/////////////// +// Riferimenti +////////////// + +// Oltre ai puntatori come quelli in C, +// il C++ ha i _riferimenti_. +// Questi non sono tipi puntatori che non possono essere riassegnati una volta settati +// e non possono essere null. +// Inoltre, essi hanno la stessa sintassi della variabile stessa: +// * non e' necessario per la dereferenziazione e +// & ("indirizzo di") non e' usato per l'assegnamento. + +using namespace std; + +string foo = "Io sono foo"; +string bar = "Io sono bar"; + + +string& fooRef = foo; // Questo crea un riferimento a foo. +fooRef += ". Ciao!"; // Modifica foo attraverso il riferimento +cout << fooRef; // Stampa "Io sono foo. Ciao!" + +// Non riassegna "fooRef". Questo e' come scrivere "foo = bar", e +// foo == "Io sono bar" +// dopo questa riga. +fooRef = bar; + +const string& barRef = bar; // Crea un riferimento const a bar. +// Come in C, i valori const (i puntatori e i riferimenti) non possono essere modificati. +barRef += ". Ciao!"; // Errore, i riferimenti const non possono essere modificati. + +////////////////////////////////////////////////// +// Classi e programmazione orientata agli oggetti +///////////////////////////////////////////////// + +// Primo esempio delle classi +#include + +// Dichiara una classe. +// Le classi sono in genere dichiara in un header file (.h o .hpp). +class Cane { + // Variabili e funzioni membro sono private di default. + std::string nome; + int peso; + +// Tutti i membri dopo questo sono pubblici (public) +// finche' "private:" o "protected:" non compaiono. +public: + + // Costruttore di default + Cane(); + + // Dichiarazioni di funzioni membro (le implentazioni sono a seguito) + // Nota che stiamo usando std::string invece di porre + // using namespace std; + // sopra. + // Mai usare uno statement "using namespace" in uno header. + void impostaNome(const std::string& nomeCane); + + void impostaPeso(int pesoCane); + + // Le funzioni che non modificano lo stato dell'oggetto + // dovrebbero essere marcate come const. + // Questo permette di chiamarle con un riferimento const all'oggetto. + // Inoltre, nota che le funzioni devono essere dichiarate espliciamente come _virtual_ + // per essere sovrascritte in classi derivate. + // Le funzioni non sono virtual di default per motivi di performance. + virtual void print() const; + + // Le funzioni possono essere definite anche all'interno del corpo della classe. + // Le funzioni definite in questo modo sono automaticamente inline. + void abbaia() const { std::cout << nome << " abbaia!\n"; } + + // Assieme con i costruttori, il C++ fornisce i distruttori. + // Questi sono chiamati quando un oggetto e' rimosso o esce dalla visibilita'. + // Questo permette paradigmi potenti come il RAII + // (vedi sotto) + // I distruttori devono essere virtual per permettere a classi di essere derivate da questa. + virtual ~Dog(); + +}; // Un punto e virgola deve seguire la definizione della funzione + +// Class member functions are usually implemented in .cpp files. +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// Objects (such as strings) should be passed by reference +// if you are modifying them or const reference if you are not. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Notice that "virtual" is only needed in the declaration, not the definition. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // prints "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg" + return 0; +} // prints "Goodbye Barkley" + +// Inheritance: + +// This class inherits everything public and protected from the Dog class +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // Override the behavior of the print function for all OwnedDogs. See + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // for a more general introduction if you are unfamiliar with + // subtype polymorphism. + // The override keyword is optional but makes sure you are actually + // overriding the method in a base class. + void print() const override; + +private: + std::string owner; +}; + +// Meanwhile, in the corresponding .cpp file: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Call the print function in the base Dog class + std::cout << "Dog is owned by " << owner << "\n"; + // Prints "Dog is and weights " + // "Dog is owned by " +} + +////////////////////////////////////////// +// Initialization and Operator Overloading +////////////////////////////////////////// + +// In C++ you can overload the behavior of operators such as +, -, *, /, etc. +// This is done by defining a function which is called +// whenever the operator is used. + +#include +using namespace std; + +class Point { +public: + // Member variables can be given default values in this manner. + double x = 0; + double y = 0; + + // Define a default constructor which does nothing + // but initialize the Point to the default value (0, 0) + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* Do nothing except initialize the values */ } + + // Overload the + operator. + Point operator+(const Point& rhs) const; + + // Overload the += operator + Point& operator+=(const Point& rhs); + + // It would also make sense to add the - and -= operators, + // but we will skip those for brevity. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Create a new point that is the sum of this one and rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // This calls the Point + operator + // Point up calls the + (function) with right as its paramater + Point result = up + right; + // Prints "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +//////////////////////////// +// Gestione delle eccezioni +/////////////////////////// + +// La libreria standard fornisce un paio di tipi d'eccezioni +// (vedi http://en.cppreference.com/w/cpp/error/exception) +// ma ogni tipo puo' essere lanciato come eccezione +#include + +// Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi +// handlers _catch_. +try { + // Non allocare eccezioni nello heap usando _new_. + throw std::exception("E' avvenuto un problema"); +} +// Cattura le eccezioni come riferimenti const se sono oggetti +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Cattura ogni eccezioni non catturata dal blocco _catch_ precedente +} catch (...) +{ + std::cout << "Catturata un'eccezione sconosciuta"; + throw; // Rilancia l'eccezione +} + +/////// +// RAII +/////// + +// RAII sta per Resource Allocation Is Initialization. +// Spesso viene considerato come il piu' potente paradigma in C++. +// E' un concetto semplice: un costruttore di un oggetto +// acquisisce le risorse di tale oggetto ed il distruttore le rilascia. + +// Per comprendere come questo sia vantaggioso, +// consideriamo una funzione che usa un gestore di file in C: +void faiQualcosaConUnFile(const char* nomefile) +{ + // Per cominciare, assumiamo che niente possa fallire. + + FILE* fh = fopen(nomefile, "r"); // Apri il file in modalita' lettura. + + faiQualcosaConUnFile(fh); + faiQualcosAltroConEsso(fh); + + fclose(fh); // Chiudi il gestore di file. +} + +// Unfortunately, things are quickly complicated by error handling. +// Suppose fopen can fail, and that doSomethingWithTheFile and +// doSomethingElseWithIt return error codes if they fail. +// (Exceptions are the preferred way of handling failure, +// but some programmers, especially those with a C background, +// disagree on the utility of exceptions). +// We now have to check each call for failure and close the file handle +// if a problem occurred. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) // The returned pointer is null on failure. + return false; // Report that failure to the caller. + + // Assume each function returns false if it failed + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + + fclose(fh); // Close the file handle so it doesn't leak. + return true; // Indicate success +} + +// C programmers often clean this up a little bit using goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indicate success + +failure: + fclose(fh); + return false; // Propagate the error +} + +// If the functions indicate errors using exceptions, +// things are a little cleaner, but still sub-optimal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) + throw std::exception("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Be sure to close the file if an error occurs. + throw; // Then re-throw the exception. + } + + fclose(fh); // Close the file + // Everything succeeded +} + +// Compare this to the use of C++'s file stream class (fstream) +// fstream uses its destructor to close the file. +// Recall from above that destructors are automatically called +// whenever an object falls out of scope. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream is short for input file stream + std::ifstream fh(filename); // Open the file + + // Do things with the file + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // The file is automatically closed here by the destructor + +// This has _massive_ advantages: +// 1. No matter what happens, +// the resource (in this case the file handle) will be cleaned up. +// Once you write the destructor correctly, +// It is _impossible_ to forget to close the handle and leak the resource. +// 2. Note that the code is much cleaner. +// The destructor handles closing the file behind the scenes +// without you having to worry about it. +// 3. The code is exception safe. +// An exception can be thrown anywhere in the function and cleanup +// will still occur. + +// All idiomatic C++ code uses RAII extensively for all resources. +// Additional examples include +// - Memory using unique_ptr and shared_ptr +// - Containers - the standard library linked list, +// vector (i.e. self-resizing array), hash maps, and so on +// all automatically destroy their contents when they fall out of scope. +// - Mutexes using lock_guard and unique_lock +``` +Letture consigliate: + +Un riferimento aggiornato del linguaggio puo' essere trovato qui + + +Risorse addizionali possono essere trovate qui -- cgit v1.2.3 From 763e7eb224fce450cbf35004d4a5e11e57198cf0 Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Wed, 6 May 2015 11:09:31 -0700 Subject: added and finished C++-it --- it-it/c++-it.html.markdown | 370 ++++++++++++++++++++++----------------------- 1 file changed, 185 insertions(+), 185 deletions(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index 8914c234..429c976f 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -9,45 +9,45 @@ translators: lang: it-it --- -Il C++ e' un linguaggio di programmazione il quale, +Il C++ è un linguaggio di programmazione il quale, [secondo il suo inventore Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), -e' stato progettato per +è stato progettato per - essere un "miglior C" - supportare l'astrazione dei dati - supportare la programmazione orientata agli oggetti - supportare la programmazione generica -Nonostante la sintassi possa risultare piu' difficile o complessa di linguaggi piu' recenti, -e' usato in maniera vasta poiche' viene compilato in istruzioni macchina che possono +Nonostante la sintassi possa risultare più difficile o complessa di linguaggi più recenti, +è usato in maniera vasta poichè viene compilato in istruzioni macchina che possono essere eseguite direttamente dal processore ed offre un controllo stretto sull'hardware (come il linguaggio C) ed allo stesso tempo offre caratteristiche ad alto livello come i generici, le eccezioni, e le classi. -Questa combinazione di velocita' e funzionalita' rende il C++ -uno dei piu' utilizzati linguaggi di programmazione. +Questa combinazione di velocità e funzionalità rende il C++ +uno dei più utilizzati linguaggi di programmazione. ```c++ ////////////////// // Confronto con il C ////////////////// -// Il C++ e' _quasi_ un superset del C e con esso condivide la sintassi di base per +// Il C++ è _quasi_ un superset del C e con esso condivide la sintassi di base per // la dichiarazione di variabili, tipi primitivi, e funzioni. -// Proprio come nel C, l'inizio del programma e' una funzione chiamata +// Proprio come nel C, l'inizio del programma è una funzione chiamata // main con un intero come tipo di ritorno, // nonostante void main() sia anch'essa accettata dalla maggior parte dei compilatori(gcc, clang, ecc...) // Questo valore serve come stato d'uscita del programma. // Vedi http://it.wikipedia.org/wiki/Valore_di_uscita per maggiori informazioni. int main(int argc, char** argv) { - // Gli argomenti a linea di comando sono passati tramite argc e argv cosi' come + // Gli argomenti a linea di comando sono passati tramite argc e argv così come // avviene in C. // argc indica il numero di argomenti, - // e argv e' un array in stile-C di stringhe (char*) + // e argv è un array in stile-C di stringhe (char*) // che rappresenta gl iargomenti. - // Il primo argomento e' il nome che e' stato assegnato al programma. + // Il primo argomento è il nome che è stato assegnato al programma. // argc e argv possono essere omessi se non hai bisogno di argomenti, - // in questa maniera la funzione avra' int main() come firma. + // in questa maniera la funzione avrà int main() come firma. // Lo stato di uscita 0 indica successo. return 0; @@ -66,7 +66,7 @@ sizeof('c') == sizeof(10) void func(); // funziona che non accetta argomenti // In C -void func(); // funzione che puo' accettare un qualsiasi numero di argomenti +void func(); // funzione che può accettare un qualsiasi numero di argomenti // Usa nullptr invece di NULL in C++ int* ip = nullptr; @@ -95,7 +95,7 @@ void print(char const* myString) void print(int myInt) { - printf("Il mio int e' %d", myInt); + printf("Il mio int è %d", myInt); } int main() @@ -134,7 +134,7 @@ void dichiarazioneInvalida(int a = 1, int b) // Errore! // Namespaces ///////////// -// I namespaces forniscono visibilita' separata per dichiarazioni di variabili, funzioni, +// I namespaces forniscono visibilità separata per dichiarazioni di variabili, funzioni, // ed altro. // I namespaces possono essere annidati. @@ -142,7 +142,7 @@ namespace Primo { namespace Annidato { void foo() { - printf("Questa e' Primo::Annidato::foo\n"); + printf("Questa è Primo::Annidato::foo\n"); } } // fine di namespace Annidato } // fine di namespace Primo @@ -150,13 +150,13 @@ namespace Primo { namespace Secondo { void foo() { - printf("Questa e' Secondo::foo\n") + printf("Questa è Secondo::foo\n") } } void foo() { - printf("Questa e' foo globale\n"); + printf("Questa è foo globale\n"); } int main() @@ -165,9 +165,9 @@ int main() // a meno che non venga dichiarato altrimenti. using namespace Secondo; - foo(); // stampa "Questa e' Secondo::foo" - Primo::Annidato::foo(); // stampa "Questa e' Primo::Annidato::foo" - ::foo(); // stampa "Questa e' foo globale" + foo(); // stampa "Questa è Secondo::foo" + Primo::Annidato::foo(); // stampa "Questa è Primo::Annidato::foo" + ::foo(); // stampa "Questa è foo globale" } /////////////// @@ -176,7 +176,7 @@ int main() // L'input e l'output in C++ utilizza gli streams // cin, cout, e cerr i quali rappresentano stdin, stdout, e stderr. -// << e' l'operatore di inserzione >> e' l'operatore di estrazione. +// << è l'operatore di inserzione >> è l'operatore di estrazione. #include // Include for I/O streams @@ -191,9 +191,9 @@ int main() // Prende l'input cin >> myInt; - // cout puo' anche essere formattato - cout << "Il tuo numero preferito e' " << myInt << "\n"; - // stampa "Il tuo numero preferito e' " + // cout può anche essere formattato + cout << "Il tuo numero preferito è " << myInt << "\n"; + // stampa "Il tuo numero preferito è " cerr << "Usato per messaggi di errore"; } @@ -210,7 +210,7 @@ using namespace std; // Anche le stringhe sono contenute nel namespace std (libr string myString = "Ciao"; string myOtherString = " Mondo"; -// + e' usato per la concatenazione. +// + è usato per la concatenazione. cout << myString + myOtherString; // "Ciao Mondo" cout << myString + " Bella"; // "Ciao Bella" @@ -229,8 +229,8 @@ cout << myString; // "Ciao Mario" // Questi non sono tipi puntatori che non possono essere riassegnati una volta settati // e non possono essere null. // Inoltre, essi hanno la stessa sintassi della variabile stessa: -// * non e' necessario per la dereferenziazione e -// & ("indirizzo di") non e' usato per l'assegnamento. +// * non è necessario per la dereferenziazione e +// & ("indirizzo di") non è usato per l'assegnamento. using namespace std; @@ -242,7 +242,7 @@ string& fooRef = foo; // Questo crea un riferimento a foo. fooRef += ". Ciao!"; // Modifica foo attraverso il riferimento cout << fooRef; // Stampa "Io sono foo. Ciao!" -// Non riassegna "fooRef". Questo e' come scrivere "foo = bar", e +// Non riassegna "fooRef". Questo è come scrivere "foo = bar", e // foo == "Io sono bar" // dopo questa riga. fooRef = bar; @@ -266,7 +266,7 @@ class Cane { int peso; // Tutti i membri dopo questo sono pubblici (public) -// finche' "private:" o "protected:" non compaiono. +// finchè "private:" o "protected:" non compaiono. public: // Costruttore di default @@ -294,7 +294,7 @@ public: void abbaia() const { std::cout << nome << " abbaia!\n"; } // Assieme con i costruttori, il C++ fornisce i distruttori. - // Questi sono chiamati quando un oggetto e' rimosso o esce dalla visibilita'. + // Questi sono chiamati quando un oggetto è rimosso o esce dalla visibilità. // Questo permette paradigmi potenti come il RAII // (vedi sotto) // I distruttori devono essere virtual per permettere a classi di essere derivate da questa. @@ -302,122 +302,122 @@ public: }; // Un punto e virgola deve seguire la definizione della funzione -// Class member functions are usually implemented in .cpp files. -void Dog::Dog() +// Le funzioni membro di una classe sono generalmente implementate in files .cpp . +void Cane::Cane() { - std::cout << "A dog has been constructed\n"; + std::cout << "Un cane è stato costruito\n"; } -// Objects (such as strings) should be passed by reference -// if you are modifying them or const reference if you are not. -void Dog::setName(const std::string& dogsName) +// Gli oggetti (ad esempio le stringhe) devono essere passati per riferimento +// se li stai modificando o come riferimento const altrimenti. +void Cane::impostaNome(const std::string& nomeCane) { - name = dogsName; + nome = nomeCane; } -void Dog::setWeight(int dogsWeight) +void Cane::impostaPeso(int pesoCane) { - weight = dogsWeight; + peso = pesoCane; } -// Notice that "virtual" is only needed in the declaration, not the definition. -void Dog::print() const +// Notare che "virtual" è solamente necessario nelle dichiarazioni, non nelle definizioni. +void Cane::print() const { - std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; + std::cout << "Il cane è " << nome << " e pesa " << peso << "kg\n"; } -void Dog::~Dog() +void Cane::~Cane() { - cout << "Goodbye " << name << "\n"; + cout << "Ciao ciao " << nome << "\n"; } int main() { - Dog myDog; // prints "A dog has been constructed" - myDog.setName("Barkley"); - myDog.setWeight(10); - myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg" + Cane myDog; // stampa "Un cane è stato costruito" + myDog.impostaNome("Barkley"); + myDog.impostaPeso(10); + myDog.print(); // stampa "Il cane è Barkley e pesa 10 kg" return 0; -} // prints "Goodbye Barkley" +} // stampa "Ciao ciao Barkley" -// Inheritance: +// Ereditarietà: -// This class inherits everything public and protected from the Dog class -class OwnedDog : public Dog { +// Questa classe eredita tutto ciò che è public e protected dalla classe Cane +class MioCane : public Cane { - void setOwner(const std::string& dogsOwner) + void impostaProprietario(const std::string& proprietarioCane) - // Override the behavior of the print function for all OwnedDogs. See - // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping - // for a more general introduction if you are unfamiliar with - // subtype polymorphism. - // The override keyword is optional but makes sure you are actually - // overriding the method in a base class. + // Sovrascrivi il comportamento della funzione print per tutti i MioCane. Vedi + // http://it.wikipedia.org/wiki/Polimorfismo_%28informatica%29 + // per una introduzione più generale se non sei familiare con + // il polimorfismo. + // La parola chiave override è opzionale ma fa sì che tu stia effettivamente + // sovrascrivendo il metodo nella classe base. void print() const override; private: - std::string owner; + std::string proprietario; }; -// Meanwhile, in the corresponding .cpp file: +// Nel frattempo, nel file .cpp corrispondente: -void OwnedDog::setOwner(const std::string& dogsOwner) +void MioCane::impostaProprietario(const std::string& proprietarioCane) { - owner = dogsOwner; + proprietario = proprietarioCane; } -void OwnedDog::print() const +void MioCane::print() const { - Dog::print(); // Call the print function in the base Dog class - std::cout << "Dog is owned by " << owner << "\n"; - // Prints "Dog is and weights " - // "Dog is owned by " + Cane::print(); // Chiama la funzione print nella classe base Cane + std::cout << "Il cane è di " << proprietario << "\n"; + // stampa "Il cane è e pesa " + // "Il cane è di " } -////////////////////////////////////////// -// Initialization and Operator Overloading -////////////////////////////////////////// +/////////////////////////////////////////////////// +// Inizializzazione ed Overloading degli Operatori +////////////////////////////////////////////////// -// In C++ you can overload the behavior of operators such as +, -, *, /, etc. -// This is done by defining a function which is called -// whenever the operator is used. +// In C++ puoi sovrascrivere il comportamento di operatori come +, -, *, /, ecc... +// Questo è possibile definendo una funzioneche viene chiamata +// ogniqualvolta l'operatore è usato. #include using namespace std; -class Point { +class Punto { public: - // Member variables can be given default values in this manner. + // Così si assegna alle variabili membro un valore di default. double x = 0; double y = 0; - // Define a default constructor which does nothing - // but initialize the Point to the default value (0, 0) - Point() { }; + // Definisce un costruttore di default che non fa nulla + // ma inizializza il Punto ai valori di default (0, 0) + Punto() { }; - // The following syntax is known as an initialization list - // and is the proper way to initialize class member values - Point (double a, double b) : + // La sintassi seguente è nota come lista di inizializzazione + // ed è il modo appropriato di inizializzare i valori membro della classe + Punto (double a, double b) : x(a), y(b) - { /* Do nothing except initialize the values */ } + { /* Non fa nulla eccetto inizializzare i valori */ } - // Overload the + operator. - Point operator+(const Point& rhs) const; + // Sovrascrivi l'operatore +. + Punto operator+(const Punto& rhs) const; - // Overload the += operator - Point& operator+=(const Point& rhs); + // Sovrascrivi l'operatore += + Punto& operator+=(const Punto& rhs); - // It would also make sense to add the - and -= operators, - // but we will skip those for brevity. + // Avrebbe senso aggiungere gli operatori - e -=, + // ma li saltiamo per rendere la guida più breve. }; -Point Point::operator+(const Point& rhs) const +Punto Punto::operator+(const Punto& rhs) const { - // Create a new point that is the sum of this one and rhs. - return Point(x + rhs.x, y + rhs.y); + // Crea un nuovo punto come somma di questo e di rhs. + return Punto(x + rhs.x, y + rhs.y); } -Point& Point::operator+=(const Point& rhs) +Punto& Punto::operator+=(const Punto& rhs) { x += rhs.x; y += rhs.y; @@ -425,13 +425,13 @@ Point& Point::operator+=(const Point& rhs) } int main () { - Point up (0,1); - Point right (1,0); - // This calls the Point + operator - // Point up calls the + (function) with right as its paramater - Point result = up + right; - // Prints "Result is upright (1,1)" - cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + Punto su (0,1); + Punto destro (1,0); + // Questo chiama l'operatore + di Punto + // Il Punto su chiama la funzione + con destro come argomento + Punto risultato = su + destro; + // Stampa "Risultato è spostato in (1,1)" + cout << "Risultato è spostato (" << risultato.x << ',' << risultato.y << ")\n"; return 0; } @@ -441,14 +441,14 @@ int main () { // La libreria standard fornisce un paio di tipi d'eccezioni // (vedi http://en.cppreference.com/w/cpp/error/exception) -// ma ogni tipo puo' essere lanciato come eccezione +// ma ogni tipo può essere lanciato come eccezione #include // Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi // handlers _catch_. try { // Non allocare eccezioni nello heap usando _new_. - throw std::exception("E' avvenuto un problema"); + throw std::exception("È avvenuto un problema"); } // Cattura le eccezioni come riferimenti const se sono oggetti catch (const std::exception& ex) @@ -466,8 +466,8 @@ catch (const std::exception& ex) /////// // RAII sta per Resource Allocation Is Initialization. -// Spesso viene considerato come il piu' potente paradigma in C++. -// E' un concetto semplice: un costruttore di un oggetto +// Spesso viene considerato come il più potente paradigma in C++. +// È un concetto semplice: un costruttore di un oggetto // acquisisce le risorse di tale oggetto ed il distruttore le rilascia. // Per comprendere come questo sia vantaggioso, @@ -476,122 +476,122 @@ void faiQualcosaConUnFile(const char* nomefile) { // Per cominciare, assumiamo che niente possa fallire. - FILE* fh = fopen(nomefile, "r"); // Apri il file in modalita' lettura. + FILE* fh = fopen(nomefile, "r"); // Apri il file in modalità lettura. - faiQualcosaConUnFile(fh); + faiQualcosaConIlFile(fh); faiQualcosAltroConEsso(fh); fclose(fh); // Chiudi il gestore di file. } -// Unfortunately, things are quickly complicated by error handling. -// Suppose fopen can fail, and that doSomethingWithTheFile and -// doSomethingElseWithIt return error codes if they fail. -// (Exceptions are the preferred way of handling failure, -// but some programmers, especially those with a C background, -// disagree on the utility of exceptions). -// We now have to check each call for failure and close the file handle -// if a problem occurred. -bool doSomethingWithAFile(const char* filename) +// Sfortunatamente, le cose vengono complicate dalla gestione degli errori. +// Supponiamo che fopen fallisca, e che faiQualcosaConUnFile e +// faiQualcosAltroConEsso ritornano codici d'errore se falliscono. +// (Le eccezioni sono la maniera preferita per gestire i fallimenti, +// ma alcuni programmatori, specialmente quelli con un passato in C, +// non sono d'accordo con l'utilità delle eccezioni). +// Adesso dobbiamo verificare che ogni chiamata per eventuali fallimenti e chiudere il gestore di file +// se un problema è avvenuto. +bool faiQualcosaConUnFile(const char* nomefile) { - FILE* fh = fopen(filename, "r"); // Open the file in read mode - if (fh == nullptr) // The returned pointer is null on failure. - return false; // Report that failure to the caller. - - // Assume each function returns false if it failed - if (!doSomethingWithTheFile(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // Propagate the error. + FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura + if (fh == nullptr) // Il puntatore restituito è null in caso di fallimento. + return false; // Riporta il fallimento al chiamante. + + // Assumiamo che ogni funzione ritorni false se ha fallito + if (!faiQualcosaConIlFile(fh)) { + fclose(fh); // Chiude il gestore di file così che non sprechi memoria. + return false; // Propaga l'errore. } - if (!doSomethingElseWithIt(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // Propagate the error. + if (!faiQualcosAltroConEsso(fh)) { + fclose(fh); // Chiude il gestore di file così che non sprechi memoria. + return false; // Propaga l'errore. } - fclose(fh); // Close the file handle so it doesn't leak. - return true; // Indicate success + fclose(fh); // Chiudi il gestore di file così che non sprechi memoria. + return true; // Indica successo } -// C programmers often clean this up a little bit using goto: -bool doSomethingWithAFile(const char* filename) +// I programmatori C in genere puliscono questa procedura usando goto: +bool faiQualcosaConUnFile(const char* nomefile) { - FILE* fh = fopen(filename, "r"); + FILE* fh = fopen(nomefile, "r"); if (fh == nullptr) return false; - if (!doSomethingWithTheFile(fh)) - goto failure; + if (!faiQualcosaConIlFile(fh)) + goto fallimento; - if (!doSomethingElseWithIt(fh)) - goto failure; + if (!faiQualcosAltroConEsso(fh)) + goto fallimento; - fclose(fh); // Close the file - return true; // Indicate success + fclose(fh); // Chiude il file + return true; // Indica successo -failure: +fallimento: fclose(fh); - return false; // Propagate the error + return false; // Propaga l'errore } -// If the functions indicate errors using exceptions, -// things are a little cleaner, but still sub-optimal. -void doSomethingWithAFile(const char* filename) +// Se le funzioni indicano errori usando le eccezioni, +// le cose sono un pò più pulite, ma sono sempre sub-ottimali. +void faiQualcosaConUnFile(const char* nomefile) { - FILE* fh = fopen(filename, "r"); // Open the file in read mode + FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura if (fh == nullptr) - throw std::exception("Could not open the file."); + throw std::exception("Non è stato possibile aprire il file."). try { - doSomethingWithTheFile(fh); - doSomethingElseWithIt(fh); + faiQualcosaConIlFile(fh); + faiQualcosAltroConEsso(fh); } catch (...) { - fclose(fh); // Be sure to close the file if an error occurs. - throw; // Then re-throw the exception. + fclose(fh); // Fai sì che il file venga chiuso se si ha un errore. + throw; // Poi rilancia l'eccezione. } - fclose(fh); // Close the file - // Everything succeeded + fclose(fh); // Chiudi il file + // Tutto è andato bene } -// Compare this to the use of C++'s file stream class (fstream) -// fstream uses its destructor to close the file. -// Recall from above that destructors are automatically called -// whenever an object falls out of scope. -void doSomethingWithAFile(const std::string& filename) +// Confronta questo con l'utilizzo della classe C++ file stream (fstream) +// fstream usa i distruttori per chiudere il file. +// Come detto sopra, i distruttori sono automaticamente chiamati +// ogniqualvolta un oggetto esce dalla visibilità. +void faiQualcosaConUnFile(const std::string& nomefile) { - // ifstream is short for input file stream - std::ifstream fh(filename); // Open the file - - // Do things with the file - doSomethingWithTheFile(fh); - doSomethingElseWithIt(fh); - -} // The file is automatically closed here by the destructor - -// This has _massive_ advantages: -// 1. No matter what happens, -// the resource (in this case the file handle) will be cleaned up. -// Once you write the destructor correctly, -// It is _impossible_ to forget to close the handle and leak the resource. -// 2. Note that the code is much cleaner. -// The destructor handles closing the file behind the scenes -// without you having to worry about it. -// 3. The code is exception safe. -// An exception can be thrown anywhere in the function and cleanup -// will still occur. - -// All idiomatic C++ code uses RAII extensively for all resources. -// Additional examples include -// - Memory using unique_ptr and shared_ptr -// - Containers - the standard library linked list, -// vector (i.e. self-resizing array), hash maps, and so on -// all automatically destroy their contents when they fall out of scope. -// - Mutexes using lock_guard and unique_lock + // ifstream è l'abbreviazione di input file stream + std::ifstream fh(nomefile); // Apre il file + + // Fai qualcosa con il file + faiQualcosaConIlFile(fh); + faiQualcosAltroConEsso(fh); + +} // Il file viene chiuso automaticamente chiuso qui dal distruttore + +// Questo ha vantaggi _enormi_: +// 1. Può succedere di tutto ma +// la risorsa (in questo caso il file handler) verrà ripulito. +// Una volta che scrivi il distruttore correttamente, +// È _impossibile_ scordarsi di chiudere l'handler e sprecare memoria. +// 2. Nota che il codice è molto più pulito. +// Il distruttore gestisce la chiusura del file dietro le scene +// senza che tu debba preoccupartene. +// 3. Il codice è sicuro da eccezioni. +// Una eccezione può essere lanciata in qualunque punto nella funzione e la ripulitura +// avverrà lo stesso. + +// Tutto il codice C++ idiomatico usa RAII in maniera vasta su tutte le risorse. +// Esempi aggiuntivi includono +// - Utilizzo della memoria con unique_ptr e shared_ptr +// - I contenitori - la lista della libreria standard, +// vettori (i.e. array auto-aggiustati), mappe hash, e così via +// sono tutti automaticamente distrutti con i loro contenuti quando escono dalla visibilità. +// - I mutex usano lock_guard e unique_lock ``` Letture consigliate: -Un riferimento aggiornato del linguaggio puo' essere trovato qui +Un riferimento aggiornato del linguaggio può essere trovato qui Risorse addizionali possono essere trovate qui -- cgit v1.2.3 From 25bd06d77a70964acfbdbf8a7c7a50eb312eae9f Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 6 May 2015 15:25:28 -0600 Subject: comment changes --- c++.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 517ce367..66d4aeb1 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -692,7 +692,7 @@ int* pt2 = new int; *pt2 = nullptr; // Doesn't compile pt2 = nullptr; // Sets pt2 to null. -// But somehow 'bool' type is an exception. +// But somehow 'bool' type is an exception (this is to make `if (ptr)` compile). *pt = nullptr; // This still compiles, even though '*pt' is a bool! @@ -702,8 +702,8 @@ Foo f2; Foo f1 = f2; // Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of -// 'fooSub'. Any extra members of 'fooSub' are discarded. This lovely behavior -// is called "object slicing." +// 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes +// horrifying behavior is called "object slicing." FooSub fooSub; Foo f1 = fooSub; -- cgit v1.2.3 From 8b7a2fff9a71b8fa8754947434b8b1f184ed2de1 Mon Sep 17 00:00:00 2001 From: Etan Reisner Date: Wed, 29 Apr 2015 22:11:20 -0400 Subject: Don't use ALL_CAPS variable names. ALL_CAPS variable names are traditionally "reserved" for use by the shell/system. (People often try to use PATH for things locally and then wonder why their commands all stop working for example. --- bash.html.markdown | 58 +++++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 4c50c653..937d2c96 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -32,40 +32,40 @@ echo Hello world! echo 'This is the first line'; echo 'This is the second line' # Declaring a variable looks like this: -VARIABLE="Some string" +Variable="Some string" # But not like this: -VARIABLE = "Some string" -# Bash will decide that VARIABLE is a command it must execute and give an error +Variable = "Some string" +# Bash will decide that Variable is a command it must execute and give an error # because it can't be found. # Or like this: -VARIABLE= 'Some string' +Variable= 'Some string' # Bash will decide that 'Some string' is a command it must execute and give an -# error because it can't be found. (In this case the 'VARIABLE=' part is seen +# error because it can't be found. (In this case the 'Variable=' part is seen # as a variable assignment valid only for the scope of the 'Some string' # command.) # Using the variable: -echo $VARIABLE -echo "$VARIABLE" -echo '$VARIABLE' +echo $Variable +echo "$Variable" +echo '$Variable' # When you use the variable itself — assign it, export it, or else — you write # its name without $. If you want to use variable's value, you should use $. # Note that ' (single quote) won't expand the variables! # String substitution in variables -echo ${VARIABLE/Some/A} +echo ${Variable/Some/A} # This will substitute the first occurance of "Some" with "A" # Substring from a variable -LENGTH=7 -echo ${VARIABLE:0:LENGTH} +Length=7 +echo ${Variable:0:Length} # This will return only the first 7 characters of the value # Default value for variable -echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} -# This works for null (FOO=) and empty string (FOO=""); zero (FOO=0) returns 0. +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. # Builtin variables: @@ -78,12 +78,12 @@ echo "Scripts arguments seperated in different variables: $1 $2..." # Reading a value from input: echo "What's your name?" -read NAME # Note that we didn't need to declare a new variable -echo Hello, $NAME! +read Name # Note that we didn't need to declare a new variable +echo Hello, $Name! # We have the usual if structure: # use 'man test' for more info about conditionals -if [ $NAME -ne $USER ] +if [ $Name -ne $USER ] then echo "Your name isn't your username" else @@ -95,14 +95,14 @@ echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" # To use && and || with if statements, you need multiple pairs of square brackets: -if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +if [ $Name == "Steve" ] && [ $Age -eq 15 ] then - echo "This will run if $NAME is Steve AND $AGE is 15." + echo "This will run if $Name is Steve AND $Age is 15." fi -if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] then - echo "This will run if $NAME is Daniya OR Zach." + echo "This will run if $Name is Daniya OR Zach." fi # Expressions are denoted with the following format: @@ -171,7 +171,7 @@ echo "There are $(ls | wc -l) items here." echo "There are `ls | wc -l` items here." # Bash uses a case statement that works similarly to switch in Java and C++: -case "$VARIABLE" in +case "$Variable" in #List patterns for the conditions you want to meet 0) echo "There is a zero.";; 1) echo "There is a one.";; @@ -179,10 +179,10 @@ case "$VARIABLE" in esac # for loops iterate for as many arguments given: -# The contents of $VARIABLE is printed three times. -for VARIABLE in {1..3} +# The contents of $Variable is printed three times. +for Variable in {1..3} do - echo "$VARIABLE" + echo "$Variable" done # Or write it the "traditional for loop" way: @@ -193,16 +193,16 @@ done # They can also be used to act on files.. # This will run the command 'cat' on file1 and file2 -for VARIABLE in file1 file2 +for Variable in file1 file2 do - cat "$VARIABLE" + cat "$Variable" done # ..or the output from a command # This will cat the output from ls. -for OUTPUT in $(ls) +for Output in $(ls) do - cat "$OUTPUT" + cat "$Output" done # while loop: @@ -230,7 +230,7 @@ bar () } # Calling your function -foo "My name is" $NAME +foo "My name is" $Name # There are a lot of useful commands you should learn: # prints last 10 lines of file.txt -- cgit v1.2.3 From 483997e4340b84d96f6e14688484d5a6b96c616e Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 9 May 2015 23:05:58 +0200 Subject: Fix #1094 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b2d7d48c..c3626057 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -211,7 +211,7 @@ say $x; #=> 52 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), 0, "0", "", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: (), 0, "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { -- cgit v1.2.3 From e6900d270be10d1516a8ea32f208bba2d8611e4f Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Sat, 9 May 2015 14:54:19 -0700 Subject: C++ italian is up to date --- it-it/c++-it.html.markdown | 125 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 124 insertions(+), 1 deletion(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index 429c976f..39afced5 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -35,7 +35,6 @@ uno dei più utilizzati linguaggi di programmazione. // Proprio come nel C, l'inizio del programma è una funzione chiamata // main con un intero come tipo di ritorno, -// nonostante void main() sia anch'essa accettata dalla maggior parte dei compilatori(gcc, clang, ecc...) // Questo valore serve come stato d'uscita del programma. // Vedi http://it.wikipedia.org/wiki/Valore_di_uscita per maggiori informazioni. int main(int argc, char** argv) @@ -435,6 +434,83 @@ int main () { return 0; } +///////////////// +// Templates +//////////////// + +// Generalmente i templates in C++ sono utilizzati per programmazione generica, anche se +// sono molto più potenti dei costrutti generici in altri linguaggi. Inoltre, +// supportano specializzazione esplicita e parziale, classi in stile funzionale, +// e sono anche complete per Turing. + +// Iniziamo con il tipo di programmazione generica con cui forse sei familiare. Per +// definire una classe o una funzione che prende un parametro di un dato tipo: +template +class Box { + // In questa classe, T può essere usato come qualsiasi tipo. + void inserisci(const T&) { ... } +}; + +// Durante la compilazione, il compilatore in effetti genera copie di ogni template +// con i parametri sostituiti, e così la definizione completa della classe deve essere +// presente ad ogni invocazione. Questo è il motivo per cui vedrai le classi template definite +// interamente in header files. + +// Per instanziare una classe template sullo stack: +Box intBox; + +// e puoi usarla come aspettato: +intBox.inserisci(123); + +//Puoi, ovviamente, innestare i templates: +Box > boxOfBox; +boxOfBox.inserisci(intBox); + +// Fino al C++11, devi porre uno spazio tra le due '>', altrimenti '>>' +// viene visto come l'operatore di shift destro. + +// Qualche volta vedrai +// template +// invece. La parole chiavi 'class' e 'typename' sono _generalmente_ +// intercambiabili in questo caso. Per una spiegazione completa, vedi +// http://en.wikipedia.org/wiki/Typename +// (si, quella parola chiave ha una sua pagina di Wikipedia propria). + +// Similmente, una funzione template: +template +void abbaiaTreVolte(const T& input) +{ + input.abbaia(); + input.abbaia(); + input.abbaia(); +} + +// Nota che niente è specificato relativamente al tipo di parametri. Il compilatore +// genererà e poi verificherà il tipo di ogni invocazione del template, così che +// la funzione di cui sopra funzione con ogni tipo 'T' che ha const 'abbaia' come metodo! + +Cane fluffy; +fluffy.impostaNome("Fluffy") +abbaiaTreVolte(fluffy); // Stampa "Fluffy abbaia tre volte. + +// I parametri template non devono essere classi: +template +void stampaMessaggio() { + cout << "Impara il C++ in " << Y << " minuti!" << endl; +} + +// E poi esplicitamente specializzare i template per avere codice più efficiente. Ovviamente, +// la maggior parte delle casistiche reali non sono così triviali. +// Notare che avrai comunque bisogna di dichiarare la funzione (o classe) come un template +// anche se hai esplicitamente specificato tutti i parametri. +template<> +void stampaMessaggio<10>() { + cout << "Impara il C++ più velocemente in soli 10 minuti!" << endl; +} + +printMessage<20>(); // Stampa "impara il C++ in 20 minuti!" +printMessage<10>(); // Stampa "Impara il C++ più velocemente in soli 10 minuti!" + //////////////////////////// // Gestione delle eccezioni /////////////////////////// @@ -588,6 +664,53 @@ void faiQualcosaConUnFile(const std::string& nomefile) // vettori (i.e. array auto-aggiustati), mappe hash, e così via // sono tutti automaticamente distrutti con i loro contenuti quando escono dalla visibilità. // - I mutex usano lock_guard e unique_lock + +/////////////////////// +// Roba divertente +////////////////////// + +// Aspetti del C++ che potrebbero sbalordire i nuovi arrivati (e anche qualche veterano). +// Questa sezione è, fortunatamente, selvaggiamente incompleta; il C++ è uno dei linguaggi +// più facili con cui puoi spararti da solo nel piede. + +// Puoi sovrascrivere metodi privati! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // sovrascrive Foo::bar! +}; + + +// 0 == false == NULL (la maggior parte delle volte)! +bool* pt = new bool; +*pt = 0; // Setta il valore puntato da 'pt' come falso. +pt = 0; // Setta 'pt' al puntatore null. Entrambe le righe vengono compilate senza warnings. + +// nullptr dovrebbe risolvere alcune di quei problemi: +int* pt2 = new int; +*pt2 = nullptr; // Non compila +pt2 = nullptr; // Setta pt2 a null. + +// Ma in qualche modo il tipo 'bool' è una eccezione (questo è per rendere compilabile `if (ptr)`. +*pt = nullptr; // Questo compila, anche se '*pt' è un bool! + + +// '=' != '=' != '='! +// Chiama Foo::Foo(const Foo&) o qualche variante del costruttore di copia. +Foo f2; +Foo f1 = f2; + +// Chiama Foo::Foo(const Foo&) o qualche variante, ma solo copie di 'Foo' che fanno parte di +// 'fooSub'. Ogni altro membro di 'fooSub' viene scartato. Questo comportamento +// orribile viene chiamato "object slicing." +FooSub fooSub; +Foo f1 = fooSub; + +// Chiama Foo::operator=(Foo&) o una sua variante. +Foo f1; +f1 = f2; + ``` Letture consigliate: -- cgit v1.2.3 From 9311ca75afcc2338a03980b800f4f1eaa40bee8c Mon Sep 17 00:00:00 2001 From: robertmargelli Date: Sat, 9 May 2015 19:18:04 -0700 Subject: fixed C++/it typos --- it-it/c++-it.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index 39afced5..4f5ac8a2 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -42,8 +42,8 @@ int main(int argc, char** argv) // Gli argomenti a linea di comando sono passati tramite argc e argv così come // avviene in C. // argc indica il numero di argomenti, - // e argv è un array in stile-C di stringhe (char*) - // che rappresenta gl iargomenti. + // e argv è un array di stringhe in stile-C (char*) + // che rappresenta gli argomenti. // Il primo argomento è il nome che è stato assegnato al programma. // argc e argv possono essere omessi se non hai bisogno di argomenti, // in questa maniera la funzione avrà int main() come firma. @@ -177,7 +177,7 @@ int main() // cin, cout, e cerr i quali rappresentano stdin, stdout, e stderr. // << è l'operatore di inserzione >> è l'operatore di estrazione. -#include // Include for I/O streams +#include // Include gli streams di I/O using namespace std; // Gli streams sono nel namespace std (libreria standard) @@ -377,7 +377,7 @@ void MioCane::print() const ////////////////////////////////////////////////// // In C++ puoi sovrascrivere il comportamento di operatori come +, -, *, /, ecc... -// Questo è possibile definendo una funzioneche viene chiamata +// Questo è possibile definendo una funzione che viene chiamata // ogniqualvolta l'operatore è usato. #include @@ -491,7 +491,7 @@ void abbaiaTreVolte(const T& input) Cane fluffy; fluffy.impostaNome("Fluffy") -abbaiaTreVolte(fluffy); // Stampa "Fluffy abbaia tre volte. +abbaiaTreVolte(fluffy); // Stampa "Fluffy abbaia" tre volte. // I parametri template non devono essere classi: template @@ -670,7 +670,7 @@ void faiQualcosaConUnFile(const std::string& nomefile) ////////////////////// // Aspetti del C++ che potrebbero sbalordire i nuovi arrivati (e anche qualche veterano). -// Questa sezione è, fortunatamente, selvaggiamente incompleta; il C++ è uno dei linguaggi +// Questa sezione è, sfortunatamente, selvaggiamente incompleta; il C++ è uno dei linguaggi // più facili con cui puoi spararti da solo nel piede. // Puoi sovrascrivere metodi privati! -- cgit v1.2.3 From e4c261567533921f35ce4e65ebfe6621a128992b Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 11 May 2015 21:20:02 -0500 Subject: Fix issue with referring to "output.txt" but examples use "output.out" Fixes https://github.com/adambard/learnxinyminutes-docs/issues/1095 --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 937d2c96..ee783c14 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -144,7 +144,7 @@ python hello.py > /dev/null 2>&1 # if you want to append instead, use ">>": python hello.py >> "output.out" 2>> "error.err" -# Overwrite output.txt, append to error.err, and count lines: +# Overwrite output.out, append to error.err, and count lines: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err @@ -152,7 +152,7 @@ wc -l output.out error.err # see: man fd echo <(echo "#helloworld") -# Overwrite output.txt with "#helloworld": +# Overwrite output.out with "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out -- cgit v1.2.3 From cbf2f6d371faf02e6fbe9c106e81340483817df6 Mon Sep 17 00:00:00 2001 From: David Warring Date: Wed, 13 May 2015 12:20:54 +1200 Subject: Parrot is no longer supported. Also mention MoarVM before JVM. --- perl6.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index c3626057..3bb87916 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -10,8 +10,7 @@ contributors: Perl 6 is a highly capable, feature-rich programming language made for the upcoming hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM -and [the MoarVM](http://moarvm.com). +Perl 6 runs on [the MoarVM](http://moarvm.com) and the JVM. Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. -- cgit v1.2.3 From 6370487b72c9f03baeca91d41f3f7f308381bf30 Mon Sep 17 00:00:00 2001 From: Alois Date: Wed, 13 May 2015 11:00:57 +0200 Subject: Update clojure.html.markdown --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 7917ab08..a125d18f 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -22,7 +22,7 @@ and often automatically. ; Clojure is written in "forms", which are just ; lists of things inside parentheses, separated by whitespace. ; -; The clojure reader assumes that the first thing is a +; The clojure reader assumes that the first thing is a ; function or macro to call, and the rest are arguments. ; The first call in a file should be ns, to set the namespace -- cgit v1.2.3 From 7458e15cd208982f12ae3a8d04261aaaf8332044 Mon Sep 17 00:00:00 2001 From: tleb Date: Thu, 14 May 2015 21:30:15 +0000 Subject: add ; to php/en --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 039288a0..2d4565e0 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -60,7 +60,7 @@ $float = 1.2e3; $float = 7E-10; // Delete variable -unset($int1) +unset($int1); // Arithmetic $sum = 1 + 1; // 2 -- cgit v1.2.3 From 00a246e77b8cf8fd84812844de7bca78f220b2c5 Mon Sep 17 00:00:00 2001 From: Antonio Ognio Date: Fri, 15 May 2015 17:12:45 -0500 Subject: Updating rust.html.markdown for Rust 1.0 --- rust.html.markdown | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index dcb54733..17f7dc90 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -6,14 +6,21 @@ filename: learnrust.rs --- Rust is an in-development programming language developed by Mozilla Research. -It is relatively unique among systems languages in that it can assert memory -safety *at compile time* without resorting to garbage collection. Rust’s first -release, 0.1, occurred in January 2012, and development moves so quickly that at -the moment the use of stable releases is discouraged, and instead one should use -nightly builds. On January 9 2015, Rust 1.0 Alpha was released, and the rate of -changes to the Rust compiler that break existing code has dropped significantly -since. However, a complete guarantee of backward compatibility will not exist -until the final 1.0 release. +Rust combines low-level control over performance with high-level convenience and +safety guarantees. + +It achieves these goals without requiring a garbage collector or runtime, making +it possible to use Rust libraries as a "drop-in replacement" for C. + +Rust’s first release, 0.1, occurred in January 2012, and for 3 years development +moved so quickly that until recently the use of stable releases was discouraged +and instead the general advise was to use nightly builds. + +On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward +compatibility. Improvements to compile times and other aspects of the compiler are +currently available in the nightly builds. Rust has adopted a train-based release +model with regular releases every six weeks. Rust 1.1 beta was made available at +the same time of the release of Rust 1.0. Although Rust is a relatively low-level language, Rust has some functional concepts that are generally found in higher-level languages. This makes -- cgit v1.2.3 From 95e0a50cc44a46561069d538fb5a89a4e1edea99 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Thu, 26 Feb 2015 17:40:57 +0300 Subject: [objective-c/ru] Updating Objective-C guide --- ru-ru/objective-c-ru.html.markdown | 654 ++++++++++++++++++++++++++++++++----- 1 file changed, 578 insertions(+), 76 deletions(-) diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index 3246de82..ddff2e5c 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -1,106 +1,171 @@ --- language: Objective-C -filename: LearnObjectiveC.m +filename: LearnObjectiveC-ru.m contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] translators: - ["Evlogy Sutormin", "http://evlogii.com"] + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] lang: ru-ru --- -Objective-C — компилируемый объектно-ориентированный язык программирования, используемый корпорацией Apple, -построенный на основе языка Си и парадигм Smalltalk. -В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения. +Objective-C — основной язык программирования, используемый корпорацией Apple +для операционных систем OS X и iOS и их соответствующих фреймворках Cocoa и +Cocoa Touch. +Он является объектно-ориентированным языком программирования общего назначения, +который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C. ```objective_c -// Однострочный комментарий +// Однострочные комментарии начинаются с // /* -Многострочный -комментарий +Так выглядят многострочные комментарии */ -// Импорт файлов фреймворка Foundation с помощью #import +// Импорт заголовочных файлов фреймворка Foundation с помощью #import +// Используйте <>, чтобы импортировать глобальные файлы (обычно фреймворки) +// Используйте "", чтобы импортировать локальные файлы (из проекта) #import #import "MyClass.h" -// Точка входа в программу это функция main, -// которая возвращает целый тип integer +// Если вы включили модули для iOS >= 7.0 или OS X >= 10.9 проектов в +// Xcode 5, вы можете импортировать фреймворки подобным образом: +@import Foundation; + +// Точка входа в программу - это функция main, +// которая возвращает целый тип int main (int argc, const char * argv[]) { - // Создание autorelease pool для управления памятью + // Создание autorelease pool для управления памятью в программе NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - + // В место этого воспользуйтесь @autoreleasepool, если вы используете + // автоматический подсчет ссылок (ARC) + @autoreleasepool { + // Используйте NSLog для печати в консоль - NSLog(@"Hello World!"); // Напечатает строку "Hello World!" + NSLog(@"Привет Мир!"); // Напечатает строку "Привет Мир!" /////////////////////////////////////// // Типы и переменные /////////////////////////////////////// - // Простое объявление + // Объявление простых типов int myPrimitive1 = 1; long myPrimitive2 = 234554664565; + // Объявление объектов // Помещайте * в начало названия объекта для строго типизированного объявления MyClass *myObject1 = nil; // Строгая типизация id myObject2 = nil; // Слабая типизация - - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" // %@ – это объект - // 'description' это общий для всех объектов метод вывода данных + // 'description' - это общий для всех объектов метод вывода данных + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" // Строка - NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // напечатает "Hello World!" + NSString *worldString = @"Мир"; + NSLog(@"Привет %@!", worldString); // напечатает "Привет Мир!" + // NSMutableString - это изменяемая версия NSString-объекта + NSMutableString *mutableString = [NSMutableString stringWithString:@"Привет"]; + [mutableString appendString:@" Мир!"]; + NSLog(@"%@", mutableString); // напечатает => "Привет Мир!" // Символьные литералы NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; + char theLetterZ = [theLetterZNumber charValue]; // или 'Z' NSLog(@"%c", theLetterZ); - // Целочисленный литералы + // Целочисленные литералы NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; + int fortyTwo = [fortyTwoNumber intValue]; // или '42' NSLog(@"%i", fortyTwo); // Беззнаковый целочисленный литерал NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // или 42 NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // или 42 NSLog(@"%hi", fortyTwoShort); + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // или 41 + NSLog(@"%u", fortyOneUnsigned); + NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // или 42 NSLog(@"%li", fortyTwoLong); + + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // или 53 + NSLog(@"%lu", fiftyThreeUnsigned); // Вещественный литерал NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; - NSLog(@"%f", piFloat); + float piFloat = [piFloatNumber floatValue]; // или 3.141592654f + NSLog(@"%f", piFloat); // напечатает 3.141592654 + NSLog(@"%5.2f", piFloat); // напечатает " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; // или 3.1415926535 NSLog(@"%f", piDouble); - + NSLog(@"%4.2f", piDouble); // напечатает "3.14" + + // NSDecimalNumber - это класс с фиксированной точкой, который является + // более точным, чем float или double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber не способен использовать стандартные +, -, *, / операторы, + // поэтому он предоставляет свои собственные: + [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // напечатает "10.99", т.к. NSDecimalNumber - изменяемый + // BOOL (булевый) литерал NSNumber *yesNumber = @YES; NSNumber *noNumber = @NO; - + // или + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // напечатает 1 + // Массив + // Может содержать различные типы данных, но должен быть объектом Objective-C NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + NSLog(@"Третье число = %@", thirdNumber); // Напечатает "Третье число = 3" + // NSMutableArray - это изменяемая версия NSArray, допускающая вам изменять + // элементы в массиве и расширять или сокращать массив. + // Удобный, но не эффективный как NSArray. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Привет"]; + [mutableArray addObject:@"Мир"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // напечатает "Мир" // Словарь - NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; - NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // Напечатает "Object = (null)" - + NSDictionary *aDictionary = @{ @"ключ1" : @"значение1", @"ключ2" : @"значение2" }; + NSObject *valueObject = aDictionary[@"Ключ"]; + NSLog(@"Объект = %@", valueObject); // Напечатает "Объект = (null)" + // NSMutableDictionary тоже доступен, как изменяемый словарь + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"значение1" forKey:@"ключ1"]; + [mutableDictionary setObject:@"значение2" forKey:@"ключ2"]; + [mutableDictionary removeObjectForKey:@"ключ1"]; + + // Множество + NSSet *set = [NSSet setWithObjects:@"Привет", @"Привет", @"Мир", nil]; + NSLog(@"%@", set); // напечатает {(Hello, World)} (порядок может отличаться) + // NSMutableSet тоже доступен, как изменяемое множество + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Привет"]; + [mutableSet addObject:@"Привет"]; + NSLog(@"%@", mutableSet); // напечатает => {(Привет)} + /////////////////////////////////////// // Операторы /////////////////////////////////////// @@ -124,13 +189,13 @@ int main (int argc, const char * argv[]) // Условный оператор if (NO) { - NSLog(@"I am never run"); + NSLog(@"Я никогда не выполнюсь"); } else if (0) { - NSLog(@"I am also never run"); + NSLog(@"Я тоже никогда не выполнюсь"); } else { - NSLog(@"I print"); + NSLog(@"Я напечатаюсь"); } // Ветвление с множественным выбором @@ -138,15 +203,15 @@ int main (int argc, const char * argv[]) { case 0: { - NSLog(@"I am never run"); + NSLog(@"Я никогда не выполнюсь"); } break; case 1: { - NSLog(@"I am also never run"); + NSLog(@"Я тоже никогда не выполнюсь"); } break; default: { - NSLog(@"I print"); + NSLog(@"Я напечатаюсь"); } break; } @@ -170,7 +235,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // // Цикл просмотра + // Цикл просмотра NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { @@ -180,20 +245,32 @@ int main (int argc, const char * argv[]) // "2," // "3," + // Цикл for для объектов. Может использоваться с любым объектом Objective-C + for (id item in values) { + NSLog(@"%@,", item); + } // напечатает => "0," + // "1," + // "2," + // "3," + // Обработка исключений @try { // Ваше исключение здесь @throw [NSException exceptionWithName:@"FileNotFoundException" - reason:@"File Not Found on System" userInfo:nil]; + reason:@"Файл не найден в системе" userInfo:nil]; } @catch (NSException * e) { - NSLog(@"Exception: %@", e); + NSLog(@"Исключение: %@", e); } @finally { - NSLog(@"Finally"); - } // => напечатает "Exception: File Not Found on System" - // "Finally" + NSLog(@"В конце отводится время для очистки."); + } // => напечатает "Исключение: Файл не найден в системе" + // "В конце отводится время для очистки." + + // NSError - это полезные объекты для аргументов функции, чтобы заполнить их + // пользовательскими ошибками. + NSError *error = [NSError errorWithDomain:@"Неправильный эл. адрес." code:4 userInfo:nil]; /////////////////////////////////////// // Объекты @@ -203,13 +280,16 @@ int main (int argc, const char * argv[]) // Объект не является полнофункциональным пока обе части не выполнятся. MyClass *myObject = [[MyClass alloc] init]; - // В Objective-C можель ООП базируется на передаче сообщений. + // В Objective-C модель ООП базируется на передаче сообщений. // В Objective-C Вы не просто вызваете метод; вы посылаете сообщение. - [myObject instanceMethodWithParameter:@"Steve Jobs"]; + [myObject instanceMethodWithParameter:@"Стив Джобс"]; // Очищайте память, перед завершением работы программы. [pool drain]; + // Конец @autoreleasepool + } + // Конец программы. return 0; } @@ -222,63 +302,144 @@ int main (int argc, const char * argv[]) // Синтаксис объявления: // @interface ИмяКласса : ИмяКлассаРодителя <ИмплементируемыеПротоколы> // { -// Объявление переменных; +// тип имя; <= Объявление переменных; // } +// @property тип имя; <= объявление свойств // -/+ (тип) Объявление метода(ов). // @end - - -@interface MyClass : NSObject +@interface MyClass : NSObject // NSObject - это базовый класс в Objective-C. { - int count; - id data; + // Объявления экземпляров переменных (может существовать в файлах интерфейса или реализвации) + int count; // По умолчанию защищенный доступ. + @private id data; // Приватный доступ (Намного удобнее объявлять в файле реализации) NSString *name; } -// При объявлении свойств сразу генерируются геттер и сеттер -@property int count; -@property (copy) NSString *name; // Скопировать объект в ходе присвоения. -@property (readonly) id data; // Генерация только геттера +// Удобное обозначение для переменных с открытым (public) доступом +// автоматически генерируется сеттер-метод +// По умолчанию название сеттер-метода начинается с 'set' с последующим именем +// переменной из @property +@property int propInt; // Имя сеттер-метода = 'setPropInt' +@property (copy) id copyId; // (copy) => Скопировать объект в ходе присвоения. +// (readonly) => Не позволяет установить значение вне @interface +@property (readonly) NSString *roString; // Используйте @synthesize + // в @implementation, чтобы создать аксессор +// Вы можете настроить геттер и сеттер имена вместо используемого 'set'-имени по умолчанию: +@property (getter=lengthGet, setter=lengthSet:) int length; // Методы -+/- (return type)methodSignature:(Parameter Type *)parameterName; ++/- (возвращаемый тип)сигнатураМетода:(Параметр типа *)имяПараметра; // + для методов класса + (NSString *)classMethod; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; -// - для метода объекта +// - для методов объекта - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -@end +// Методы-конструктор с аргументом: +- (id)initWithDistance:(int)defaultDistance; +// В Objective-C имена методов очень описательные. Всегда имена методов соответствуют своим аргументам + +@end // Устанавливает конец интерфейса (interface) + + +// Чтобы обратиться к открытым (public) переменным из файла реализации, @property генерирует сеттер-метод +// автоматически. Название метода - это 'set' с последующим именем переменной из @property: +MyClass *myClass = [[MyClass alloc] init]; // создает экземпляр объекта класса MyClass +[myClass setCount:10]; +NSLog(@"%d", [myClass count]); // напечатает => 10 +// Или используйте свой геттер и сеттер методы, которые определены в @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // напечатает => 32 +// Для удобства вы можете использовать точечную нотацию, +// чтобы установить и получить доступ к переменным объекта: +myClass.count = 45; +NSLog(@"%i", myClass.count); // напечатает => 45 + +// Вызов методов класса: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Привет"]; + +// Вызов методов экземпляра: +MyClass *myClass = [[MyClass alloc] init]; // Создает экземпляр объекта MyClass +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Привет"]; + +// Селекторы +// Это способ динамически представить методы. Используйте для вызова методов класса, передайте методы +// через функции, чтобы сказать другим классам, что они должны вызвать их и сохранить методы +// как переменные +// SEL - это тип данных. @selector() вернет селектор из предоставленного имени метода +// methodAParameterAsString:andAParameterAsNumber: - это название метода в MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Проверяет содержит ли класс метод + // Необходимо установить все аргументы метода в один объект, что отправить его в performSelector-функцию + NSArray *arguments = [NSArray arrayWithObjects:@"Привет", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Вызывает метод +} else { + // NSStringFromSelector() вернет NSString название метода полученного селектором + NSLog(@"MyClass не содержит метод: %@", NSStringFromSelector(selectedVar)); +} // Имплементируйте методы в файле МойКласс.m: +@implementation MyClass { + long distance; // Переменная экземпляра с закрытым (private) доступом + NSNumber height; +} -@implementation MyClass +// To access a public variable from the interface file, use '_' followed by variable name: +_count = 5; // References "int count" from MyClass interface +// Access variables defined in implementation file: +distance = 18; // References "long distance" from MyClass implementation +// To use @property variable in implementation, use @synthesize to create accessor variable: +@synthesize roString = _roString; // _roString available now in @implementation + +// Called before calling any class methods or instantiating any objects ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} // Вызывается при высвобождении памяти под объектом - (void)dealloc { + [height release]; // Если не используется ARC, убедитесь в освобождении переменных объекта класса + [super dealloc]; // and call parent class dealloc } -// Конструкторы – это способ осздания объектов класса. -// Это обычный конструктор вызываемый при создании объекта клсааа. +// Конструкторы – это способ создания объектов класса. +// Это конструктор по умолчанию, который вызывается, когда объект инициализируется. - (id)init { - if ((self = [super init])) + if ((self = [super init])) // 'super' используется для того, чтобы обратиться к методам родительского класса { - self.count = 1; + self.count = 1; // 'self' используется для вызова самого себя } return self; } +// Можно создать конструкторы, которые содержат аргументы: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + (NSString *)classMethod { return [[self alloc] init]; } ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + - (NSString *)instanceMethodWithParameter:(NSString *)string { - return @"New string"; + return @"Новая строка"; } - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number @@ -286,23 +447,364 @@ int main (int argc, const char * argv[]) return @42; } +// Objective-C не содержит объявление приватных методов, но вы можете имитировать их. +// Чтобы сымитировать приватный метод, создайте метод в @implementation, но не в @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Вызывает приватный метод + // Методы объявленные в МyProtocol (см. далее) - (void)myProtocolMethod { - // имплементация + // операторы } +@end // Устанавливает конец реализации (implementation) + +/////////////////////////////////////// +// Категории +/////////////////////////////////////// +// Категория - это группа методов предназначенные для того, чтобы расширить класс. Они позволяют вам добавить новые методы +// к существующему классу для организационных целей. Это не стоит путать с подклассами. +// Подклассы предназначены для ИЗМЕНЕНИЯ функциональности объекта пока как категории ДОБАВЛЯЮТ +// функциональность в объект. +// Категории позволяют вам: +// -- Добавлять методы в существующий класс для организационных целей. +// -- Допускает вам расширять объекты Objective-C классов (напр.: NSString) добавить ваши собственные методы. +// -- Добавляет возможность создать защищенные и закрытые методы классов. +// ПРИМЕЧАНИЕ: Не переопределяйте методы базового класса в категории даже если у вас есть возможность это сделать +// to. Переопределение методов может привести к ошибкам компиляции позднее между различными категориями и это +// нарушает цель категорий, чтобы добавлять только функциональность. Вместо этого подклассы переопределяют методы. + +// Здесь простой базовый класс Car. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + @end -/* - * Протокол объявляет методы которые должны быть имплементированы - * Протокол не является классом. Он просто определяет интерфейс, - * который должен быть имплементирован. - */ +// И реализация базового класса Car: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Машина заведена."); +} +- (void)accelerate { + NSLog(@"Ускорение."); +} -@protocol MyProtocol - - (void)myProtocolMethod; @end + +// Теперь, если мы хотели создать грузовой объект, мы должны вместо создания подкласса класса Car, как это будет +// изменять функциональность Car чтобы вести себя подобно грузовику. Но давайте посмотрим, если мы хотим только добавить +// функциональность в существующий Car. Хороший пример должен быть чистить автомобиль. Итак мы создадим +// категорию для добавления его очистительных методов: +// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h) +#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения. + +@interface Car (Clean) // Имя категории внутри (), следующие после имени базового класса. + +- (void)washWindows; // Названия новых методов, которые мы добавляем в наш объект Car. +- (void)wax; + +@end + +// @implementation имя файла: Car+Clean.m (ИмяБазовогоКласса+ИмяКатегории.m) +#import "Car+Clean.h" // Импортируйте Очистку файл @interface категории. + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Окна промыли."); +} +- (void)wax { + NSLog(@"Воском натерли."); +} + +@end + +// Любой экземпляр объекта Car имеет возможность воспользоваться категорией. Все, что нужно сделать, это импортировать ее: +#import "Car+Clean.h" // Импортировать как множество различных категорий, как вы хотите использовать. +#import "Car.h" // Кроме того, необходимо импортировать базовый класс для использования его оригинальные функциональные возможности. + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Красный"; + mustang.make = @"Форд"; + + [mustang turnOn]; // Используйте методы из базового класса Car. + [mustang washWindows]; // Используйте методы категории Clean из класса Car. + } + return 0; +} + +// Objective-C не поддерживает объявление защищенных методов, но вы можете имитировать их. +// Создайте категорию, содержащую все защищенные методы, затем импортируйте ее только в +// @implementation-файле класса, относящегося к классу Car: +@interface Car (Protected) // Наименование категории с помощью 'Protected' +// дает знать, что методы защищенные. + +- (void)lockCar; // Здесь перечисляются методы, которые должны быть созданы +// только с помощью объектов класса Car. + +@end +// Чтобы воспользоваться защищенными методами, импортируйте категорию, затем реализуйте методы: +#import "Car+Protected.h" // Запомните, делайте импорт только в файле с @implementation. + +@implementation Car + +- (void)lockCar { + NSLog(@"Машина закрыта."); // Экземпляры класса Car не могут использовать +// метод lockCar, потому что он объявлен не в @interface. +} + +@end + +/////////////////////////////////////// +// Расширения +/////////////////////////////////////// +// Расширения позволяют вам переопределять атрибуты свойств и методов +// с открытым доступом в @interface. +// @interface имя файла: Shape.h +@interface Shape : NSObject // Расширение базового класса Shape переопределяет + // свои поля ниже. + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// Вы можете переопределить numOfSides-переменную или getNumOfSides-метод +// Внесение изменений с помощью расширения делается следующим образом: +// @implementation имя файла: Shape.m +#import "Shape.h" +// Расширения "живут" в том же файле, где и @implementation класса. +@interface Shape () // После имени базового класса скобки () объявляют расширение. + +@property (copy) NSNumber *numOfSides; // Делает numOfSides-свойство + // копирующим (copy) вместо свойства только для чтения (readonly). +-(NSNumber)getNumOfSides; // Изменяет метод getNumOfSides так, + // чтобы он возвращал объект NSNumber вместо типа int. +-(void)privateMethod; // Вы также можете создать новый закрытый метод + // внутри расширения. + +@end +// Главный @implementation: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // Все операторы внутри расширения + // должны быть в @implementation. + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Закрытый метод созданный с помощью расширения."); + NSLog(@"Экземпляр Shape не может вызвать этот метод."); +} + +@end + +/////////////////////////////////////// +// Протоколы +/////////////////////////////////////// +// Протокол объявляет методы, которые могут быть реализованы с помощью +// любого класса. Протоколы сами по себе не являются классами. Они просто +// определяют интерфейс, который должен быть реализован другими объектами. +// @protocol имя файла: "CarUtilities.h" +@protocol CarUtilities // => Имя другого протокола, +// который включен в этот протокол. + @property BOOL engineOn; // Адаптирующий класс должен определить +// все @synthesize для @property и + - (void)turnOnEngine; // определить все методы. +@end +// Ниже пример класса, реализующий протокол. +#import "CarUtilities.h" // Импорт файла с @protocol. + +@interface Car : NSObject // Внутри <> имя протокола +// Здесь вам не нужно указывать @property или имена методов для CarUtilities. +// Они нужны только для @implementation. +- (void)turnOnEngineWithUtilities:(id )car; // Вы также можете +// указать тип протоколов. +@end +// В @implementation нужно реализовать все @property и методы для протокола. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Создайте @synthesize-оператор +// для "@property engineOn". + +- (void)turnOnEngine { // Реализуйте turnOnEngine как вам угодно. Протоколы +// не определят, + _engineOn = YES; // как вам реализовать метод, он только требует, +// чтобы вы реализовали его. +} +// Вы можете использовать протокол как данные, если вы знаете, что он реализует +// методы и переменные. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // У вас есть доступ к переменным объекта + [objectOfSomeKind turnOnEngine]; // и методам. + [objectOfSomeKind engineOn]; // Может или не может быть значение YES. Класс +// реализует как нужно. +} + +@end +// Экземпляры класса Car сейчас имеют доступ к протоколу. +Car *carInstance = [[Car alloc] init]; +[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Двигатель запущен."); // напечатает => "Двигатель запущен." +} +// Убедитись в том, что объект типа 'id' реализует протокол перед вызовом методов протокола: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"Не работает, т.к. класс MyClass не реализует протокол CarUtilities."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"Работает как класс Car, который реализует протокол CarUtilities."); +} +// Категории тоже могут реализовать протоколы: +// @interface Car (CarCategory) +// Вы можете реализовать много протоколов: +// @interface Car : NSObject +// ЗАМЕЧАНИЕ: Если два или более протоколов полагаются друг на друга, +// убедитесь, что они ранее объявлены: +#import "Brother.h" + +@protocol Brother; // Оператор раннего объявления. Без него компилятор +// выдаст ошибку. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; + +@end + +// Рассмотрите проблему, где протокол Sister полагается на протокол Brother, +// а Brother полагается на Sister. +#import "Sister.h" + +@protocol Sister; // Эти строки предотвращают рекурсию, решая этим проблему. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end + + +/////////////////////////////////////// +// Блоки +/////////////////////////////////////// +// Блоки - это операторы кода, наподобие функции, которую возможно использовать +// как данные. +// Ниже простой блок с целочисленным аргументом, и возвращает аргумент плюс 4. +int (^addUp)(int n); // Объявите переменную, чтобы сохранить блок. +void (^noParameterBlockVar)(void); // Пример объявления блока-переменной +// без аргументов. +// Блоки имею доступ к переменным в той же области видимости. Но переменные +// будут только для чтения, и значения переданных в блок станут значением +// переменной, когда блок создастся. +int outsideVar = 17; // Если мы редактируем outsideVar после объявления addUp, +// outsideVar остается равным 17. +__block long mutableVar = 3; // __block делают переменные перезаписываемыми +// в блоках, в отличие от outsideVar. +addUp = ^(int n) { // Удалите (int n) в блоке, чтобы не принимать +// какие-либо параметры. + NSLog(@"Вы можете иметь столько строк в блоке, сколько вы хотели."); + NSSet *blockSet; // Также вы можете объявить локальные переменные. + mutableVar = 32; // Присвоить новое значение к __block-переменной. + return n + outsideVar; // Необязательный оператор возврата. +} +int addUp = add(10 + 16); // Вызывает блок кода с аргументами. +// Блоки часто используются как аргументы функции, чтобы позже их вызвать, или +// как функции обратного вызова (callbacks). +@implementation BlockExample : NSObject + +- (void)runBlock:(void (^)(NSString))block { + NSLog(@"В аргументе блок ничего не возвращает и принимает NSString-объект."); + block(@"Аргумент передан блоку на исполнение."); // Вызов блока. +} + +@end + + +/////////////////////////////////////// +// Управление памятью +/////////////////////////////////////// +/* +Для каждого объекта, используемого в приложении, должна быть выделена память +для таких объектов. Когда приложение прекращает использование объекта, память +должна быть освобождена, чтобы гарантировать эффективность приложения. +Objective-C не использует сборщик мусора, а вместо этого применяет подсчет ссылок. +Пока существует по крайней мере одна ссылка на объект (также называется +"владение" объектом), то объект будет доступен к использованию (еще известно +как "право владения"). + +Когда экземпляр владеет объектом, его ссылка увеличивается на один. Когда +объекта освобождается, счетчик ссылки уменьшается на один. Когда счетчик ссылки +равен нулю, объект удаляется из памяти. + +Над всеми объектами взаимодействуют, следуя паттерну: +(1) создание объекта, (2) использование объекта, (3) затем освобождение объекта из памяти. +*/ + +MyClass *classVar = [MyClass alloc]; // 'alloc' устанавливает счетчик ссылки +// объекта classVar на 1 и возвращает указатель на объект. +[classVar release]; // Уменьшает счетчик ссылки объекта classVar +// 'retain' заявляет право собственности на существующий экземпляр объекта +// и увеличивает счетчик ссылки. Затем вернет указатель на объект. +MyClass *newVar = [classVar retain]; // Если classVar освободится, объект +// останется в памяти, потому что newVar - владелец +[classVar autorelease]; // Удалит право на владение объектом +// в конце @autoreleasepool блока. Вернет указатель на объект. + +// @property может использовать 'retain' и 'assign' тоже для маленького +// удобного определения +@property (retain) MyClass *instance; // Освободит старое значение и сохранит +// одно новое (строгая ссылка) +@property (assign) NSSet *set; // Укажет на новое значение +// без сохранения/освобождения старого значения (слабая ссылка) + +// Автоматический подсчет ссылок (ARC) +// Управление памятью может быть трудным, поэтому в Xcode 4.2 и iOS 4 введен +// автоматический подсчет ссылок (ARC). +// ARC - это особенность компилятора, который помещает "retain", "release" +// и "autorelease" автоматически за вас тогда, когда используется ARC, +// вам не нужно больше обращаться к "retain", "relase" или "autorelease" +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... код, использующий объект arcMyClass +// Без ARC, вам нужно было бы вызвать: [arcMyClass release] после того, как вы +// завершите работу с объектом arcMyClass. Но с ARC, +// теперь этого не нужно делать. Он будет помещать release-вызов за вас + +// Что касается 'assign' и 'retain' @property атрибутов, в ARC вы должны +// использовать 'weak' и 'strong' +@property (weak) MyClass *weakVar; // 'weak' не принимает право на владение +// объектом. Если исходный счетчик ссылки экземпляра обнуляется, +// weakVar-свойство автоматически примет значение nil, +// во избежание падения приложения +@property (strong) MyClass *strongVar; // 'strong' принимает право на владение +// объектом. Гарантирует, что объект останится в памяти для использования + +// Для обычных переменных (не объявленных с помощью @property), используйте +// следующий способ: +__strong NSString *strongString; // По умолчанию. Переменная сохраняется в памяти, +// пока она не покинет область видимости +__weak NSSet *weakSet; // Слабая ссылка на существующий объект. Когда существующий +// объект освобождается, weakSet принимает nil +__unsafe_unretained NSArray *unsafeArray; // Похож на __weak, но unsafeArray +// не принимает nil, когда существующий объект освобождается + ``` ## На почитать -- cgit v1.2.3 From 1989c6773a2c8dd35c16fdabaa2464db4e79f7fc Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Fri, 27 Mar 2015 12:36:14 +0300 Subject: [brainfuck/ru] Updating brainfuck guide --- ru-ru/brainfuck-ru.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown index 500ac010..fcee185f 100644 --- a/ru-ru/brainfuck-ru.html.markdown +++ b/ru-ru/brainfuck-ru.html.markdown @@ -11,6 +11,8 @@ lang: ru-ru Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень маленький Тьюринг-полный язык программирования лишь с 8 командами. +Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). + ``` Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. -- cgit v1.2.3 From a0ca5283d69be29bf7fa26ddd082ff927068883b Mon Sep 17 00:00:00 2001 From: Chtiprog Date: Mon, 18 May 2015 00:03:52 -0300 Subject: Refactor r french translation --- fr-fr/r-fr.html.markdown | 85 +++++++++++++++++++++++++----------------------- 1 file changed, 44 insertions(+), 41 deletions(-) diff --git a/fr-fr/r-fr.html.markdown b/fr-fr/r-fr.html.markdown index d6879c1f..3f225a0f 100644 --- a/fr-fr/r-fr.html.markdown +++ b/fr-fr/r-fr.html.markdown @@ -9,9 +9,9 @@ filename: learnr-fr.r --- R est un langage de programmation statistique. Il dispose de nombreuses -librairies pour le téléchargement et le nettoyage d'ensembles de données, +bibliothèques pour le téléchargement et le nettoyage d'ensembles de données, l'exécution de procédures statistiques, et la réalisation de graphiques. -On peut également exécuter les commmandes `R` au sein d'un document LaTeX. +On peut également exécuter des commmandes `R` au sein d'un document LaTeX. ```r @@ -19,9 +19,11 @@ On peut également exécuter les commmandes `R` au sein d'un document LaTeX. # Les commentaires commencent avec des symboles numériques. # Il n'est pas possible de faire des commentaires multilignes, -# mais on peut superposer plusieurs commentaires comme ceci. +# mais on peut placer plusieurs commentaires les uns en dessous +# des autres comme ceci. -# Sur Windows ou Mac, taper COMMAND-ENTER pour exécuter une ligne +# Sur Mac, taper COMMAND-ENTER pour exécuter une ligne +# et sur Windows taper CTRL-ENTER @@ -43,7 +45,7 @@ head(rivers) # donne un aperçu des données length(rivers) # Combien de rivers ont été mesurées ? # 141 -summary(rivers) # Quels sont les principales données statistiques ? +summary(rivers) # Quelles sont les principales données statistiques ? # Min. 1st Qu. Median Mean 3rd Qu. Max. # 135.0 310.0 425.0 591.2 680.0 3710.0 @@ -99,7 +101,7 @@ stem(log(rivers)) # Notez que les données ne sont ni normales # 80 | # 82 | 2 -# Fais un histogramme : +# Fait un histogramme : hist(rivers, col="#333333", border="white", breaks=25) # amusez-vous avec ces paramètres hist(log(rivers), col="#333333", border="white", breaks=25) # vous ferez plus de tracés plus tard @@ -110,7 +112,7 @@ plot(discoveries, col="#333333", lwd=3, xlab="Year", plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", main="Number of important discoveries per year") -# Plutôt que de laisser l'ordre par défaut (par années) +# Plutôt que de laisser l'ordre par défaut (par année) # Nous pourrions aussi trier pour voir ce qu'il y a de typique sort(discoveries) # [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 @@ -142,7 +144,7 @@ summary(discoveries) # Min. 1st Qu. Median Mean 3rd Qu. Max. # 0.0 2.0 3.0 3.1 4.0 12.0 -# Lance un dès plusieurs fois +# Lance un dé plusieurs fois round(runif(7, min=.5, max=6.5)) # 1 4 6 1 4 6 4 # Vos numéros diffèreront des miens à moins que nous mettions @@ -164,11 +166,11 @@ rnorm(9) # les entiers, les numériques, les caractères, les logiques, et les facteurs. # LES ENTIERS -# Les entiers de mémoire longue sont écrit avec L +# Les entiers de type long sont écrits avec L 5L # 5 class(5L) # "integer" # (Essayez ?class pour plus d'informations sur la fonction class().) -# Avec R, chaque valeur seule, comme 5L, est considéré comme +# Avec R, chaque valeur seule, comme 5L, est considérée comme # un vecteur de longueur 1 length(5L) # 1 # On peut avoir un vecteur d'entiers avec une longueur > 1 : @@ -191,7 +193,7 @@ c(3,3,3,2,2,1) # 3 3 3 2 2 1 class(Inf) # "numeric" class(-Inf) # "numeric" # Vous pouvez utiliser "Inf", par exemple, dans integrate(dnorm, 3, Inf); -# Ça permet d'éviter des tableaux Z-scores. +# Ça permet d'éviter de réaliser une table de la loi normale. # ARITHMÉTIQUES DE BASE # Vous pouvez faire de l'arithmétique avec des nombres @@ -233,7 +235,7 @@ letters # [20] "t" "u" "v" "w" "x" "y" "z" month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" -# LES TYPES LOGIQUES +# LES TYPES BOOLÉENS # En R, un "logical" est un booléen class(TRUE) # "logical" class(FALSE) # "logical" @@ -256,15 +258,16 @@ c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE # LES FACTEURS -# La classe facteur sert pour les données catégorielles -# les facteurs peuvent être ordonnés (comme les niveaux de -# catégorie d'enfants) -# ou non ordonnés (comme le sexe) +# Les facteurs sont généralement utilisés pour y stocker des +# variables qualitatives (catégorielles). +# Les facteurs peuvent être ordonnés (comme le niveau scolaire +# des enfants) ou non ordonnés (comme le sexe) factor(c("female", "female", "male", NA, "female")) # female female male female # Les niveaux : female male -# Les "levels" sont les valeurs que les données catégorielles -# peuvent prendre +# Les facteurs possèdent un attribut appelé niveau ("level"). +# Les niveaux sont des vecteurs contenant toutes les valeurs +# que peuvent prendre les données catégorielles. # Notez que les données manquantes n'entrent pas dans le niveau levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" # Si le vecteur de facteurs a une longueur 1, ses niveaux seront @@ -288,8 +291,8 @@ parakeet # => # NULL -# LES CONTRAINTES DE TYPES -# Les contraintes de types servent à forcer une valeur à prendre +# LES CONVERSIONS DE TYPES +# Les conversions de types servent à forcer une valeur à prendre # un type différent as.character(c(6, 8)) # "6" "8" as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE @@ -304,7 +307,7 @@ as.numeric("Bilbo") # NAs est introduit par coercition # Notez également : ce n'étaient que des types de données basiques -# Il y a beaucoup d'autres types de données, comme pour les dates, +# Il y a beaucoup d'autres types de données, comme les dates, # les séries temporelles, etc ... @@ -321,7 +324,7 @@ as.numeric("Bilbo") # LES VARIABLES # Beaucoup de façons d'assigner des choses : -x = 5 # c'est possible +x = 5 # c'est correct y <- "1" # c'est préféré TRUE -> z # ça marche mais c'est bizarre @@ -337,11 +340,11 @@ while (a > 4) { a <- a - 1 } # Gardez à l'esprit que les boucles for et while s'exécutent lentement -# en R -# Des opérations sur des vecteurs entiers (ex une ligne entière, +# en R. +# Des opérations sur la totalité d'un vecteur (ex une ligne entière, # une colonne entière), # ou les fonctions de type apply() (nous en parlerons plus tard), -# sont préférées +# sont préférées. # IF/ELSE # Encore une fois assez standard @@ -356,7 +359,7 @@ if (4 > 3) { # LES FONCTIONS # se définissent comme ceci : jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + x = x + rnorm(1, sd=.1) # ajoute un peu de bruit (contrôlé) return(x) } # Appelées comme n'importe quelles autres fonction R : @@ -366,7 +369,7 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 ########################################################################## # Les structures de données : les vecteurs, les matrices, -# les data frame et les tableaux +# les data frames et les tableaux ########################################################################## # À UNE DIMENSION @@ -387,7 +390,7 @@ which(vec %% 2 == 0) # 1 3 # Récupèrer seulement les premières ou dernières entrées du vecteur, head(vec, 1) # 8 tail(vec, 2) # 10 11 -# ou trouver si un certaine valeur est dans le vecteur +# ou vérifier si un certaine valeur est dans le vecteur any(vec == 10) # TRUE # Si un index "dépasse" vous obtiendrez NA : vec[6] # NA @@ -398,7 +401,7 @@ length(vec) # 4 vec * 4 # 16 20 24 28 vec[2:3] * 5 # 25 30 any(vec[2:3] == 8) # FALSE -# Et R a beaucoup de fonctions préconstruites pour résumer les vecteurs +# Et R a beaucoup de méthodes statistiques pré-construites pour les vecteurs : mean(vec) # 9.5 var(vec) # 1.666667 sd(vec) # 1.290994 @@ -425,7 +428,7 @@ mat # Différemment du vecteur, la classe d'une matrice est "matrix", # peut importe ce qu'elle contient class(mat) # => "matrix" -# Demander la première ligne +# Récupérer la première ligne mat[1,] # 1 4 # Réaliser une opération sur la première colonne 3 * mat[,1] # 3 6 9 @@ -502,13 +505,13 @@ dim(students) # 6 3 # stringsAsFactors = FALSE quand vous créer la data.frame ?data.frame -# Il y a plusieurs façons de subdiviser les trames de données +# Il y a plusieurs façons de subdiviser les data frames, # toutes subtilement différentes students$year # 3 2 2 1 0 -1 students[,2] # 3 2 2 1 0 -1 students[,"year"] # 3 2 2 1 0 -1 -# Une version augmentée de la structure data.frame est data.table +# Une version améliorée de la structure data.frame est data.table. # Si vous travaillez avec des données volumineuses ou des panels, ou avez # besoin de fusionner quelques ensembles de données, data.table peut être # un bon choix. Ici un tour éclair : @@ -601,15 +604,15 @@ students[students$house != "G",] # MULTI-DIMENSIONNELLE (TOUS ÉLÉMENTS D'UN TYPE) -# Les arrays créent des tableaux de n dimensions -# Tous les éléments doivent être du même type +# Les arrays créent des tableaux de n dimensions. +# Tous les éléments doivent être du même type. # Vous pouvez faire un tableau à 2 dimensions (une sorte de matrice) array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 # [2,] 2 5 9 6 -# Vous pouvez utiliser array pour faire des matrices à 3 dimensions aussi +# Vous pouvez aussi utiliser array pour faire des matrices à 3 dimensions : array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # => # , , 1 @@ -629,7 +632,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # LES LISTES (MULTI-DIMENSIONNELLES, ÉVENTUELLEMMENT DÉCHIRÉES, # DE DIFFÉRENTS TYPES) -# Enfin R a des listes (de vecteurs) +# Enfin, R a des listes (de vecteurs) list1 <- list(time = 1:40) list1$price = c(rnorm(40,.5*list1$time,4)) # random list1 @@ -644,10 +647,10 @@ list1[[1]] # encore une façon différente list1$price[4] # Les listes ne sont pas les structures de données les plus efficaces -# à utiliser avec R; +# à utiliser avec R ; # À moins d'avoir une très bonne raison, vous devriez utiliser data.frames # Les listes sont souvent retournées par des fonctions qui effectuent -# des régressions linéaires +# des régressions linéaires. ########################################## # La famille de fonction apply() @@ -674,7 +677,7 @@ apply(mat, MAR = 2, jiggle) # Ne soyez pas trop intimidé ; tout le monde reconnaît que c'est un peu déroutant -# Le paque plyr vise à remplacer (et améliorer !) la famille *apply(). +# Le paquet plyr vise à remplacer (et améliorer !) la famille *apply(). install.packages("plyr") require(plyr) ?plyr @@ -704,7 +707,7 @@ write.csv(pets, "pets2.csv") # to make a new .csv file # Les tracés ################ -# LES FONCTIONS DE TRACÉS PRÉCONSTRUITES +# LES FONCTIONS DE TRACÉ PRÉCONSTRUITES # Les diagrammes de dispersion ! plot(list1$time, list1$price, main = "fake data") # Les régressions ! @@ -737,7 +740,7 @@ pp + geom_point() ``` -## Comment j'obtiens R ? +## Comment obtenir R ? * Obtiens R et R GUI depuis [http://www.r-project.org/](http://www.r-project.org/) * [RStudio](http://www.rstudio.com/ide/) est un autre GUI -- cgit v1.2.3 From 6df96946b43999ff8754807446d4bf4f73144480 Mon Sep 17 00:00:00 2001 From: Baurzhan Muftakhidinov Date: Mon, 18 May 2015 14:17:45 +0500 Subject: Fix links to nim-lang website. --- nim.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index aa15e591..2955c7bc 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -155,7 +155,7 @@ var anotherArray = ["Default index", "starts at", "0"] # More data structures are available, including tables, sets, lists, queues, # and crit bit trees. -# http://nimrod-lang.org/lib.html#collections-and-algorithms +# http://http://nim-lang.org/docs/lib.html#collections-and-algorithms # # IO and Control Flow @@ -174,7 +174,7 @@ else: # `while`, `if`, `continue`, `break` -import strutils as str # http://nimrod-lang.org/strutils.html +import strutils as str # http://nim-lang.org/docs/strutils.html echo "I'm thinking of a number between 41 and 43. Guess which!" let number: int = 42 var @@ -263,11 +263,11 @@ performance, and compile-time features. ## Further Reading -* [Home Page](http://nimrod-lang.org) -* [Download](http://nimrod-lang.org/download.html) -* [Community](http://nimrod-lang.org/community.html) -* [FAQ](http://nimrod-lang.org/question.html) -* [Documentation](http://nimrod-lang.org/documentation.html) -* [Manual](http://nimrod-lang.org/manual.html) -* [Standard Library](http://nimrod-lang.org/lib.html) -* [Rosetta Code](http://rosettacode.org/wiki/Category:Nimrod) +* [Home Page](http://nim-lang.org) +* [Download](http://nim-lang.org/download.html) +* [Community](http://nim-lang.org/community.html) +* [FAQ](http://nim-lang.org/question.html) +* [Documentation](http://nim-lang.org/documentation.html) +* [Manual](http://nim-lang.org/docs/manual.html) +* [Standard Library](http://nim-lang.org/docs/lib.html) +* [Rosetta Code](http://rosettacode.org/wiki/Category:Nim) -- cgit v1.2.3 From fb903329c65a70fce2419da98842f038cd41ba82 Mon Sep 17 00:00:00 2001 From: Baurzhan Muftakhidinov Date: Mon, 18 May 2015 14:19:46 +0500 Subject: Fix copy-paste typo. --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 2955c7bc..c9548a1c 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -155,7 +155,7 @@ var anotherArray = ["Default index", "starts at", "0"] # More data structures are available, including tables, sets, lists, queues, # and crit bit trees. -# http://http://nim-lang.org/docs/lib.html#collections-and-algorithms +# http://nim-lang.org/docs/lib.html#collections-and-algorithms # # IO and Control Flow -- cgit v1.2.3 From c33063fe7a2ac967d0992ae9000b048ee8fefd06 Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Mon, 18 May 2015 11:55:43 +0100 Subject: [erlang/en] Various (mostly cosmetic) improvements * Add missing square brackets in example of pattern matching on lists * Keep lines under 80 characters * Hiphenate complex modifiers (e.g. "pattern-matching operation") * Consistently proper case the language name * Improve punctuation in comments * Properly format Markdown inline code * Tense changes (where appropriate) --- erlang.html.markdown | 85 +++++++++++++++++++++++++++------------------------- 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index a7390c3e..322e437d 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -18,7 +18,7 @@ filename: learnerlang.erl % Periods (`.`) (followed by whitespace) separate entire functions and % expressions in the shell. % Semicolons (`;`) separate clauses. We find clauses in several contexts: -% function definitions and in `case`, `if`, `try..catch` and `receive` +% function definitions and in `case`, `if`, `try..catch`, and `receive` % expressions. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -27,20 +27,20 @@ filename: learnerlang.erl Num = 42. % All variable names must start with an uppercase letter. -% Erlang has single assignment variables, if you try to assign a different value -% to the variable `Num`, you’ll get an error. +% Erlang has single-assignment variables; if you try to assign a different +% value to the variable `Num`, you’ll get an error. Num = 43. % ** exception error: no match of right hand side value 43 % In most languages, `=` denotes an assignment statement. In Erlang, however, -% `=` denotes a pattern matching operation. `Lhs = Rhs` really means this: -% evaluate the right side (Rhs), and then match the result against the pattern -% on the left side (Lhs). +% `=` denotes a pattern-matching operation. `Lhs = Rhs` really means this: +% evaluate the right side (`Rhs`), and then match the result against the +% pattern on the left side (`Lhs`). Num = 7 * 6. -% Floating point number. +% Floating-point number. Pi = 3.14159. -% Atoms, are used to represent different non-numerical constant values. Atoms +% Atoms are used to represent different non-numerical constant values. Atoms % start with lowercase letters, followed by a sequence of alphanumeric % characters or the underscore (`_`) or at (`@`) sign. Hello = hello. @@ -53,34 +53,34 @@ AtomWithSpace = 'some atom with space'. % Tuples are similar to structs in C. Point = {point, 10, 45}. -% If we want to extract some values from a tuple, we use the pattern matching +% If we want to extract some values from a tuple, we use the pattern-matching % operator `=`. {point, X, Y} = Point. % X = 10, Y = 45 % We can use `_` as a placeholder for variables that we’re not interested in. % The symbol `_` is called an anonymous variable. Unlike regular variables, -% several occurrences of _ in the same pattern don’t have to bind to the same -% value. +% several occurrences of `_` in the same pattern don’t have to bind to the +% same value. Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. {_, {_, {_, Who}, _}, _} = Person. % Who = joe % We create a list by enclosing the list elements in square brackets and % separating them with commas. % The individual elements of a list can be of any type. -% The first element of a list is the head of the list. If you imagine removing the -% head from the list, what’s left is called the tail of the list. +% The first element of a list is the head of the list. If you imagine removing +% the head from the list, what’s left is called the tail of the list. ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. % If `T` is a list, then `[H|T]` is also a list, with head `H` and tail `T`. % The vertical bar (`|`) separates the head of a list from its tail. % `[]` is the empty list. -% We can extract elements from a list with a pattern matching operation. If we +% We can extract elements from a list with a pattern-matching operation. If we % have a nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y` % are unbound variables, will extract the head of the list into `X` and the tail % of the list into `Y`. [FirstThing|OtherThingsToBuy] = ThingsToBuy. % FirstThing = {apples, 10} -% OtherThingsToBuy = {pears, 6}, {milk, 3} +% OtherThingsToBuy = [{pears, 6}, {milk, 3}] % There are no strings in Erlang. Strings are really just lists of integers. % Strings are enclosed in double quotation marks (`"`). @@ -117,17 +117,19 @@ c(geometry). % {ok,geometry} geometry:area({rectangle, 10, 5}). % 50 geometry:area({circle, 1.4}). % 6.15752 -% In Erlang, two functions with the same name and different arity (number of arguments) -% in the same module represent entirely different functions. +% In Erlang, two functions with the same name and different arity (number of +% arguments) in the same module represent entirely different functions. -module(lib_misc). --export([sum/1]). % export function `sum` of arity 1 accepting one argument: list of integers. +-export([sum/1]). % export function `sum` of arity 1 + % accepting one argument: list of integers. sum(L) -> sum(L, 0). sum([], N) -> N; sum([H|T], N) -> sum(T, H+N). -% Funs are "anonymous" functions. They are called this way because they have no -% name. However they can be assigned to variables. -Double = fun(X) -> 2*X end. % `Double` points to an anonymous function with handle: #Fun +% Funs are "anonymous" functions. They are called this way because they have +% no name. However, they can be assigned to variables. +Double = fun(X) -> 2 * X end. % `Double` points to an anonymous function + % with handle: #Fun Double(2). % 4 % Functions accept funs as their arguments and can return funs. @@ -140,8 +142,9 @@ Triple(5). % 15 % The notation `[F(X) || X <- L]` means "the list of `F(X)` where `X` is taken % from the list `L`." L = [1,2,3,4,5]. -[2*X || X <- L]. % [2,4,6,8,10] -% A list comprehension can have generators and filters which select subset of the generated values. +[2 * X || X <- L]. % [2,4,6,8,10] +% A list comprehension can have generators and filters, which select subset of +% the generated values. EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] % Guards are constructs that we can use to increase the power of pattern @@ -155,15 +158,15 @@ max(X, Y) -> Y. % A guard is a series of guard expressions, separated by commas (`,`). % The guard `GuardExpr1, GuardExpr2, ..., GuardExprN` is true if all the guard -% expressions `GuardExpr1, GuardExpr2, ...` evaluate to true. +% expressions `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN` evaluate to `true`. is_cat(A) when is_atom(A), A =:= cat -> true; is_cat(A) -> false. is_dog(A) when is_atom(A), A =:= dog -> true; is_dog(A) -> false. -% A `guard sequence` is either a single guard or a series of guards, separated -%by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at least -% one of the guards `G1, G2, ...` evaluates to true. +% A guard sequence is either a single guard or a series of guards, separated +% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at +% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`. is_pet(A) when is_dog(A); is_cat(A) -> true; is_pet(A) -> false. @@ -188,7 +191,7 @@ X = #todo{}. X1 = #todo{status = urgent, text = "Fix errata in book"}. % #todo{status = urgent, who = joe, text = "Fix errata in book"} X2 = X1#todo{status = done}. -% #todo{status = done,who = joe,text = "Fix errata in book"} +% #todo{status = done, who = joe, text = "Fix errata in book"} % `case` expressions. % `filter` returns a list of all elements `X` in a list `L` for which `P(X)` is @@ -209,8 +212,8 @@ max(X, Y) -> true -> nil end. -% Warning: at least one of the guards in the `if` expression must evaluate to true; -% otherwise, an exception will be raised. +% Warning: at least one of the guards in the `if` expression must evaluate to +% `true`; otherwise, an exception will be raised. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -218,7 +221,7 @@ max(X, Y) -> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Exceptions are raised by the system when internal errors are encountered or -% explicitly in code by calling `throw(Exception)`, `exit(Exception)` or +% explicitly in code by calling `throw(Exception)`, `exit(Exception)`, or % `erlang:error(Exception)`. generate_exception(1) -> a; generate_exception(2) -> throw(a); @@ -227,7 +230,7 @@ generate_exception(4) -> {'EXIT', a}; generate_exception(5) -> erlang:error(a). % Erlang has two methods of catching an exception. One is to enclose the call to -% the function, which raised the exception within a `try...catch` expression. +% the function that raises the exception within a `try...catch` expression. catcher(N) -> try generate_exception(N) of Val -> {N, normal, Val} @@ -241,23 +244,24 @@ catcher(N) -> % exception, it is converted into a tuple that describes the error. catcher(N) -> catch generate_exception(N). -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 4. Concurrency %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Erlang relies on the actor model for concurrency. All we need to write -% concurrent programs in erlang are three primitives: spawning processes, +% concurrent programs in Erlang are three primitives: spawning processes, % sending messages and receiving messages. -% To start a new process we use the `spawn` function, which takes a function +% To start a new process, we use the `spawn` function, which takes a function % as argument. F = fun() -> 2 + 2 end. % #Fun spawn(F). % <0.44.0> -% `spawn` returns a pid (process identifier), you can use this pid to send -% messages to the process. To do message passing we use the `!` operator. -% For all of this to be useful we need to be able to receive messages. This is +% `spawn` returns a pid (process identifier); you can use this pid to send +% messages to the process. To do message passing, we use the `!` operator. +% For all of this to be useful, we need to be able to receive messages. This is % achieved with the `receive` mechanism: -module(calculateGeometry). @@ -272,12 +276,13 @@ calculateArea() -> io:format("We can only calculate area of rectangles or circles.") end. -% Compile the module and create a process that evaluates `calculateArea` in the shell +% Compile the module and create a process that evaluates `calculateArea` in the +% shell. c(calculateGeometry). CalculateArea = spawn(calculateGeometry, calculateArea, []). CalculateArea ! {circle, 2}. % 12.56000000000000049738 -% The shell is also a process, you can use `self` to get the current pid +% The shell is also a process; you can use `self` to get the current pid. self(). % <0.41.0> ``` -- cgit v1.2.3 From 18a45cf7a37eb971383e3fcf65a565292e82224b Mon Sep 17 00:00:00 2001 From: Alwayswithme Date: Wed, 20 May 2015 00:14:10 +0800 Subject: update bash-cn --- zh-cn/bash-cn.html.markdown | 147 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 139 insertions(+), 8 deletions(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 6afa659a..13f85bb7 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -5,7 +5,14 @@ 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/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] translators: + - ["Jinchang Ye", "https://github.com/Alwayswithme"] - ["Chunyang Xu", "https://github.com/XuChunyang"] filename: LearnBash-cn.sh lang: zh-cn @@ -35,6 +42,10 @@ VARIABLE="Some string" VARIABLE = "Some string" # Bash 会把 VARIABLE 当做一个指令,由于找不到该指令,因此这里会报错。 +# 也不可以这样: +Variable= 'Some string' +# Bash 会认为 'Some string' 是一条指令,由于找不到该指令,这里再次报错。 +# (这个例子中 'Variable=' 这部分的赋值仅对 'Some string' 指令起作用。) # 使用变量: echo $VARIABLE @@ -49,6 +60,16 @@ echo '$VARIABLE' echo ${VARIABLE/Some/A} # 会把 VARIABLE 中首次出现的 "some" 替换成 “A”。 +# 变量的截取 +Length=7 +echo ${Variable:0:Length} +# 这样会仅返回变量值的前7个字符 + +# 变量的默认值 +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# 对 null (Foo=) 和空串 (Foo="") 起作用; 零(Foo=0)时返回0 +# 注意这仅返回默认值而不是改变变量的值 + # 内置变量: # 下面的内置变量很有用 echo "Last program return value: $?" @@ -75,6 +96,17 @@ fi echo "Always executed" || echo "Only executed if first command fail" echo "Always executed" && echo "Only executed if first command does NOT fail" +# 在 if 语句中使用 && 和 || 需要多对方括号 +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + # 表达式的格式如下: echo $(( 10 + 5 )) @@ -88,16 +120,52 @@ ls -l # 列出文件和目录的详细信息 # 用下面的指令列出当前目录下所有的 txt 文件: ls -l | grep "\.txt" +# 重定向输入和输出(标准输入,标准输出,标准错误)。 +# 以 ^EOF$ 作为结束标记从标准输入读取数据并覆盖 hello.py : +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import 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 + # 重定向可以到输出,输入和错误输出。 -python2 hello.py < "input.in" -python2 hello.py > "output.out" -python2 hello.py 2> "error.err" +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 # > 会覆盖已存在的文件, >> 会以累加的方式输出文件中。 +python hello.py >> "output.out" 2>> "error.err" + +# 覆盖 output.out , 追加 error.err 并统计行数 +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# 运行指令并打印文件描述符 (比如 /dev/fd/123) +# 具体可查看: man fd +echo <(echo "#helloworld") + +# 以 "#helloworld" 覆盖 output.out: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# 清理临时文件并显示详情(增加 '-i' 选项启用交互模式) +rm -v output.out error.err output-and-error.log # 一个指令可用 $( ) 嵌套在另一个指令内部: # 以下的指令会打印当前目录下的目录和文件总数 echo "There are $(ls | wc -l) items here." +# 反引号 `` 起相同作用,但不允许嵌套 +# 优先使用 $( ). +echo "There are `ls | wc -l` items here." + # Bash 的 case 语句与 Java 和 C++ 中的 switch 语句类似: case "$VARIABLE" in # 列出需要匹配的字符串 @@ -114,6 +182,33 @@ do echo "$VARIABLE" done +# 或传统的 “for循环” : +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# 也可以用于文件 +# 用 cat 输出 file1 和 file2 内容 +for Variable in file1 file2 +do + cat "$Variable" +done + +# 或作用于其他命令的输出 +# 对 ls 输出的文件执行 cat 指令。 +for Output in $(ls) +do + cat "$Output" +done + +# while 循环: +while [ true ] +do + echo "loop body here..." + break +done + # 你也可以使用函数 # 定义函数: function foo () @@ -135,14 +230,50 @@ bar () foo "My name is" $NAME # 有很多有用的指令需要学习: -tail -n 10 file.txt # 打印 file.txt 的最后 10 行 -head -n 10 file.txt +tail -n 10 file.txt # 打印 file.txt 的前 10 行 -sort file.txt +head -n 10 file.txt # 将 file.txt 按行排序 -uniq -d file.txt +sort file.txt # 报告或忽略重复的行,用选项 -d 打印重复的行 -cut -d ',' -f 1 file.txt +uniq -d file.txt # 打印每行中 ',' 之前内容 +cut -d ',' -f 1 file.txt +# 将 file.txt 文件所有 'okay' 替换为 'great', (兼容正则表达式) +sed -i 's/okay/great/g' file.txt +# 将 file.txt 中匹配正则的行打印到标准输出 +# 这里打印以 "foo" 开头, "bar" 结尾的行 +grep "^foo.*bar$" file.txt +# 使用选项 "-c" 统计行数 +grep -c "^foo.*bar$" file.txt +# 如果只是要按字面形式搜索字符串而不是按正则表达式,使用 fgrep (或 grep -F) +fgrep "^foo.*bar$" file.txt + + +# 以 bash 内建的 'help' 指令阅读 Bash 自带文档: +help +help help +help for +help return +help source +help . + +# 用 mam 指令阅读相关的 Bash 手册 +apropos bash +man 1 bash +man bash + +# 用 info 指令查阅命令的 info 文档 (info 中输入 ? 显示帮助信息) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# 阅读 Bash 的 info 文档: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash + ``` -- cgit v1.2.3 From f9032e0eca3c780870127c410edf5ec85db01560 Mon Sep 17 00:00:00 2001 From: sm4rk0 Date: Tue, 19 May 2015 18:17:35 +0200 Subject: Update haxe.html.markdown Correct the condition variable for "do statement always runs at least once" section --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index c807d2d7..9b84a435 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -323,7 +323,7 @@ class LearnHaxe3{ var l = 0; do{ trace("do statement always runs at least once"); - } while (i > 0); + } while (l > 0); // for loop /* -- cgit v1.2.3 From 8909457ae46dc8fb151ef146acb3f6b8402f3407 Mon Sep 17 00:00:00 2001 From: Liam Edwards-Playne Date: Wed, 20 May 2015 11:23:55 +1000 Subject: fix spelling errors --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index ee783c14..c2312d7d 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -56,7 +56,7 @@ echo '$Variable' # String substitution in variables echo ${Variable/Some/A} -# This will substitute the first occurance of "Some" with "A" +# This will substitute the first occurence of "Some" with "A" # Substring from a variable Length=7 @@ -74,7 +74,7 @@ echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $#" echo "Scripts arguments: $@" -echo "Scripts arguments seperated in different variables: $1 $2..." +echo "Scripts arguments separated in different variables: $1 $2..." # Reading a value from input: echo "What's your name?" -- cgit v1.2.3 From 982b98468467c7a85f790fdcea2ff8d425b173de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Stankovi=C4=87?= Date: Wed, 20 May 2015 14:06:05 +0200 Subject: [haxe/en] Few cosmetic fixes * correct the array name in a for loop iterating on an index * add an assignment for "case _" in first switch example * fix case of variable name in trace for control statement returning as an expression * move some inline comments to a separate line above the statement to prevent text overflow --- haxe.html.markdown | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 9b84a435..bbe51c79 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -340,7 +340,7 @@ class LearnHaxe3{ // (more on ranges later as well) var n = ['foo', 'bar', 'baz']; for (val in 0...n.length){ - trace(val + " is the value for val (an index for m)"); + trace(val + " is the value for val (an index for n)"); } @@ -375,7 +375,7 @@ class LearnHaxe3{ case "rex" : favorite_thing = "shoe"; case "spot" : favorite_thing = "tennis ball"; default : favorite_thing = "some unknown treat"; - // case _ : "some unknown treat"; // same as default + // case _ : favorite_thing = "some unknown treat"; // same as default } // The "_" case above is a "wildcard" value // that will match anything. @@ -397,7 +397,7 @@ class LearnHaxe3{ // if statements var k = if (true) 10 else 20; - trace("K equals ", k); // outputs 10 + trace("k equals ", k); // outputs 10 var other_favorite_thing = switch(my_dog_name) { case "fido" : "teddy"; @@ -495,8 +495,10 @@ class LearnHaxe3{ // foo_instance.public_read = 4; // this will throw an error if uncommented: // trace(foo_instance.public_write); // as will this. - trace(foo_instance + " is the value for foo_instance"); // calls the toString method - trace(foo_instance.toString() + " is the value for foo_instance.toString()"); // same thing + // calls the toString method + trace(foo_instance + " is the value for foo_instance"); + // same thing + trace(foo_instance.toString() + " is the value for foo_instance.toString()"); /* @@ -524,8 +526,8 @@ class LearnHaxe3{ */ class FooClass extends BarClass implements BarInterface{ public var public_any:Int; // public variables are accessible anywhere - public var public_read (default,null): Int; // use this style to only enable public read - public var public_write (null, default): Int; // or public write + public var public_read (default, null): Int; // enable only public read + public var public_write (null, default): Int; // or only public write public var property (get, set): Int; // use this style to enable getters/setters // private variables are not available outside the class. @@ -534,9 +536,10 @@ class FooClass extends BarClass implements BarInterface{ // a public constructor public function new(arg:Int){ - super(); // call the constructor of the parent object, since we extended BarClass + // call the constructor of the parent object, since we extended BarClass + super(); - this.public_any= 0; + this.public_any = 0; this._private = arg; } -- cgit v1.2.3 From 5816b59be65d47e6377cdad4c72b89f683bd0632 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Stankovi=C4=87?= Date: Wed, 20 May 2015 14:29:05 +0200 Subject: [haxe/en] Adding colon after comments ...as per @vendethiel's advice --- haxe.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index bbe51c79..ee214540 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -495,9 +495,9 @@ class LearnHaxe3{ // foo_instance.public_read = 4; // this will throw an error if uncommented: // trace(foo_instance.public_write); // as will this. - // calls the toString method + // calls the toString method: trace(foo_instance + " is the value for foo_instance"); - // same thing + // same thing: trace(foo_instance.toString() + " is the value for foo_instance.toString()"); @@ -536,7 +536,7 @@ class FooClass extends BarClass implements BarInterface{ // a public constructor public function new(arg:Int){ - // call the constructor of the parent object, since we extended BarClass + // call the constructor of the parent object, since we extended BarClass: super(); this.public_any = 0; -- cgit v1.2.3 From bad283ee14dadd02f9b21d5fbcff226bfb5c954f Mon Sep 17 00:00:00 2001 From: Hans Ole Hatzel Date: Wed, 20 May 2015 19:38:11 +0200 Subject: [c++/en] Fixed typos. --- c++.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 66d4aeb1..9f8f5f32 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -425,7 +425,7 @@ int main () { Point up (0,1); Point right (1,0); // This calls the Point + operator - // Point up calls the + (function) with right as its paramater + // Point up calls the + (function) with right as its parameter Point result = up + right; // Prints "Result is upright (1,1)" cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; @@ -464,7 +464,7 @@ intBox.insert(123); Box > boxOfBox; boxOfBox.insert(intBox); -// Up until C++11, you muse place a space between the two '>'s, otherwise '>>' +// Up until C++11, you must place a space between the two '>'s, otherwise '>>' // will be parsed as the right shift operator. // You will sometimes see @@ -712,7 +712,7 @@ Foo f1; f1 = f2; ``` -Futher Reading: +Further Reading: An up-to-date language reference can be found at -- cgit v1.2.3 From c7c3e973612c3730615f0d7fee0cafae48d1ade9 Mon Sep 17 00:00:00 2001 From: tomnor Date: Fri, 22 May 2015 23:05:37 +0200 Subject: editorial revert of a change, remove trailing whitespace Now the regular expression is back to what it was and align with how it is in other languages. Also it aligns with the commented description of the regular expression. --- elisp.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/elisp.html.markdown b/elisp.html.markdown index 3208ffb8..3bed5d1c 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -29,7 +29,7 @@ filename: learn-emacs-lisp.el ;; I hereby decline any responsability. Have fun! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; +;; ;; Fire up Emacs. ;; ;; Hit the `q' key to dismiss the welcome message. @@ -42,9 +42,9 @@ filename: learn-emacs-lisp.el ;; The scratch buffer is the default buffer when opening Emacs. ;; You are never editing files: you are editing buffers that you ;; can save to a file. -;; +;; ;; "Lisp interaction" refers to a set of commands available here. -;; +;; ;; Emacs has a built-in set of commands available in every buffer, ;; and several subsets of commands available when you activate a ;; specific mode. Here we use the `lisp-interaction-mode', which @@ -109,7 +109,7 @@ filename: learn-emacs-lisp.el ;; The empty parentheses in the function's definition means that ;; it does not accept arguments. But always using `my-name' is ;; boring, let's tell the function to accept one argument (here -;; the argument is called "name"): +;; the argument is called "name"): (defun hello (name) (insert "Hello " name)) ;; `C-xC-e' => hello @@ -305,7 +305,7 @@ filename: learn-emacs-lisp.el (defun boldify-names () (switch-to-buffer-other-window "*test*") (goto-char (point-min)) - (while (re-search-forward "Bonjour \\([^!]+\\)!" nil 't) + (while (re-search-forward "Bonjour \\(.+\\)!" nil 't) (add-text-properties (match-beginning 1) (match-end 1) (list 'face 'bold))) @@ -318,7 +318,7 @@ filename: learn-emacs-lisp.el ;; The regular expression is "Bonjour \\(.+\\)!" and it reads: ;; the string "Bonjour ", and ;; a group of | this is the \\( ... \\) construct -;; any character not ! | this is the [^!] +;; any character | this is the . ;; possibly repeated | this is the + ;; and the "!" string. -- cgit v1.2.3 From 933f0a461d0cd6bcb70c8864778f7ae7e912c00c Mon Sep 17 00:00:00 2001 From: Simon Morgan Date: Sat, 23 May 2015 12:13:07 +0100 Subject: A bunch of small changes to aid clarity, brevity and/or consistency, none of which should alter the semantics. --- java.html.markdown | 171 +++++++++++++++++++++++++---------------------------- 1 file changed, 80 insertions(+), 91 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 10dd498c..363a16f6 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,16 +1,16 @@ --- - language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - - ["Madison Dickson", "http://github.com/mix3d"] - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] filename: LearnJava.java - --- -Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. -[Read more here.](http://docs.oracle.com/javase/tutorial/java/index.html) +Java is a general-purpose, concurrent, class-based, object-oriented computer +programming language. +[Read more here.](http://docs.oracle.com/javase/tutorial/java/) ```java // Single-line comments start with // @@ -101,10 +101,10 @@ public class LearnJava { System.out.println(bazString); // Arrays - //The array size must be decided upon instantiation - //The following formats work for declaring an array - //[] = new []; - // [] = new []; + // The array size must be decided upon instantiation + // The following formats work for declaring an array + // [] = new []; + // [] = new []; int[] intArray = new int[10]; String[] stringArray = new String[1]; boolean boolArray[] = new boolean[100]; @@ -122,17 +122,17 @@ public class LearnJava { System.out.println("intArray @ 1: " + intArray[1]); // => 1 // Others to check out - // ArrayLists - Like arrays except more functionality is offered, - // and the size is mutable + // ArrayLists - Like arrays except more functionality is offered, and + // the size is mutable // LinkedLists - Implementation of doubly-linked list. All of the - // operations perform as could be expected for - // a doubly-linked list. - // Maps - A set of objects that maps keys to values. A map cannot contain - // duplicate keys; each key can map to at most one value. - // HashMaps - This class uses a hashtable to implement the Map interface. - // This allows the execution time of basic operations, - // such as get and insert element, to remain constant even - // for large sets. + // operations perform as could be expected for a + // doubly-linked list. + // Maps - A set of objects that maps keys to values. A map cannot + // contain duplicate keys; each key can map to at most one value. + // HashMaps - This class uses a hashtable to implement the Map + // interface. This allows the execution time of basic + // operations, such as get and insert element, to remain + // constant even for large sets. /////////////////////////////////////// // Operators @@ -175,10 +175,10 @@ public class LearnJava { // The ++ and -- operators increment and decrement by 1 respectively. // If they are placed before the variable, they increment then return; // after the variable they return then increment. - System.out.println(i++); //i = 1, prints 0 (post-increment) - System.out.println(++i); //i = 2, prints 2 (pre-increment) - System.out.println(i--); //i = 1, prints 2 (post-decrement) - System.out.println(--i); //i = 0, prints 0 (pre-decrement) + System.out.println(i++); // i = 1, prints 0 (post-increment) + System.out.println(++i); // i = 2, prints 2 (pre-increment) + System.out.println(i--); // i = 1, prints 2 (post-decrement) + System.out.println(--i); // i = 0, prints 0 (pre-decrement) /////////////////////////////////////// // Control Structures @@ -197,73 +197,68 @@ public class LearnJava { // While loop int fooWhile = 0; - while(fooWhile < 100) - { - //System.out.println(fooWhile); - //Increment the counter - //Iterated 100 times, fooWhile 0,1,2...99 + while(fooWhile < 100) { + System.out.println(fooWhile); + // Increment the counter + // Iterated 100 times, fooWhile 0,1,2...99 fooWhile++; } System.out.println("fooWhile Value: " + fooWhile); // Do While Loop int fooDoWhile = 0; - do - { - //System.out.println(fooDoWhile); - //Increment the counter - //Iterated 99 times, fooDoWhile 0->99 + do { + System.out.println(fooDoWhile); + // Increment the counter + // Iterated 99 times, fooDoWhile 0->99 fooDoWhile++; - }while(fooDoWhile < 100); + } while(fooDoWhile < 100); System.out.println("fooDoWhile Value: " + fooDoWhile); // For Loop int fooFor; - //for loop structure => for(; ; ) - for(fooFor=0; fooFor<10; fooFor++){ - //System.out.println(fooFor); - //Iterated 10 times, fooFor 0->9 + // for loop structure => for(; ; ) + for(fooFor = 0; fooFor < 10; fooFor++){ + System.out.println(fooFor); + // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); // For Each Loop // An automatic iteration through an array or list of objects. int[] fooList = {1,2,3,4,5,6,7,8,9}; - //for each loop structure => for( : ) - //reads as: for each object in the array - //note: the object type must match the array. + // for each loop structure => for( : ) + // reads as: for each object in the array + // note: the object type must match the array. - for( int bar : fooList ){ - //System.out.println(bar); + for (int bar : fooList){ + System.out.println(bar); //Iterates 9 times and prints 1-9 on new lines } // Switch Case // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // 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"; + switch (month) { + case 1: monthString = "January"; break; - case 3: - monthString = "March"; + case 2: monthString = "February"; break; - default: - monthString = "Some other month"; + case 3: monthString = "March"; break; + default: monthString = "Some other month"; + break; } System.out.println("Switch Case Result: " + monthString); // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. - // Reads as "If (statement) is true, use , otherwise, use " + // Reads as "If (statement) is true, use , otherwise, use + // " int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println(bar); // Prints A, because the statement is true @@ -287,9 +282,8 @@ public class LearnJava { // String // Typecasting - // You can also cast java objects, there's a lot of details and - // deals with some more intermediate concepts. - // Feel free to check it out here: + // You can also cast Java objects, there's a lot of details and deals + // with some more intermediate concepts. Feel free to check it out here: // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html @@ -319,9 +313,9 @@ public class LearnJava { // Class Declaration Syntax: -// class { -// //data fields, constructors, functions all inside. -// //functions are called as methods in Java. +// class { +// // data fields, constructors, functions all inside. +// // functions are called as methods in Java. // } class Bicycle { @@ -342,7 +336,8 @@ class Bicycle { } // This is a constructor that takes arguments - public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { this.gear = startGear; this.cadence = startCadence; this.speed = startSpeed; @@ -388,10 +383,8 @@ class Bicycle { //Method to display the attribute values of this Object. @Override public String toString() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + speed + - " name: " + name; + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; } } // end class Bicycle @@ -405,26 +398,26 @@ class PennyFarthing extends Bicycle { super(startCadence, startSpeed, 0, "PennyFarthing"); } - // You should mark a method you're overriding with an @annotation - // To learn more about what annotations are and their purpose - // check this out: http://docs.oracle.com/javase/tutorial/java/annotations/ + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { gear = 0; } - } -//Interfaces -//Interface declaration syntax -// interface extends { -// //Constants -// //Method declarations -//} +// Interfaces +// Interface declaration syntax +// interface extends { +// // Constants +// // Method declarations +// } -//Example - Food: +// Example - Food: public interface Edible { - public void eat(); //Any class that implements this interface, must implement this method + public void eat(); // Any class that implements this interface, must + // implement this method. } public interface Digestible { @@ -432,33 +425,31 @@ public interface Digestible { } -//We can now create a class that implements both of these interfaces +// We can now create a class that implements both of these interfaces. public class Fruit implements Edible, Digestible { @Override public void eat() { - //... + // ... } @Override public void digest() { - //... + // ... } } -//In java, you can extend only one class, but you can implement many interfaces. -//For example: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { +// In Java, you can extend only one class, but you can implement many +// interfaces. For example: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { @Override public void InterfaceOneMethod() { - } @Override public void InterfaceTwoMethod() { - } } - ``` ## Further Reading @@ -500,5 +491,3 @@ The links provided here below are just to get an understanding of the topic, fee * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) * [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) - - -- cgit v1.2.3 From b72c575c0442006c4eed1da46e1f6a0129f55d99 Mon Sep 17 00:00:00 2001 From: Simon Morgan Date: Sat, 23 May 2015 12:37:04 +0100 Subject: Some more small changes that don't affect semantics. --- java.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 363a16f6..f6bc82c6 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -31,17 +31,17 @@ import java.security.*; // the file. public class LearnJava { - // A program must have a main method as an entry point + // A program must have a main method as an entry point. public static void main (String[] args) { - // Use System.out.println to print lines + // Use System.out.println() to print lines. System.out.println("Hello World!"); System.out.println( "Integer: " + 10 + " Double: " + 3.14 + " Boolean: " + true); - // To print without a newline, use System.out.print + // To print without a newline, use System.out.print(). System.out.print("Hello "); System.out.print("World"); @@ -69,7 +69,7 @@ public class LearnJava { // L is used to denote that this variable value is of type Long; // anything without is treated as integer by default. - // Note: Java has no unsigned types + // Note: Java has no unsigned types. // Float - Single-precision 32-bit IEEE 754 Floating Point float fooFloat = 234.5f; @@ -86,7 +86,7 @@ public class LearnJava { // Char - A single 16-bit Unicode character char fooChar = 'A'; - // final variables can't be reassigned to another object + // final variables can't be reassigned to another object. final int HOURS_I_WORK_PER_WEEK = 9001; // Strings @@ -123,7 +123,7 @@ public class LearnJava { // Others to check out // ArrayLists - Like arrays except more functionality is offered, and - // the size is mutable + // the size is mutable. // LinkedLists - Implementation of doubly-linked list. All of the // operations perform as could be expected for a // doubly-linked list. @@ -160,13 +160,13 @@ public class LearnJava { // Bitwise operators! /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - >>> Unsigned right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR */ // Incrementations @@ -218,7 +218,7 @@ public class LearnJava { // For Loop int fooFor; // for loop structure => for(; ; ) - for(fooFor = 0; fooFor < 10; fooFor++){ + for (fooFor = 0; fooFor < 10; fooFor++) { System.out.println(fooFor); // Iterated 10 times, fooFor 0->9 } @@ -226,12 +226,12 @@ public class LearnJava { // For Each Loop // An automatic iteration through an array or list of objects. - int[] fooList = {1,2,3,4,5,6,7,8,9}; - // for each loop structure => for( : ) + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each loop structure => for ( : ) // reads as: for each object in the array // note: the object type must match the array. - for (int bar : fooList){ + for (int bar : fooList) { System.out.println(bar); //Iterates 9 times and prints 1-9 on new lines } -- cgit v1.2.3 From 7560b334dbc528784580d810d5857ac6a859f6e1 Mon Sep 17 00:00:00 2001 From: Simon Morgan Date: Sat, 23 May 2015 12:51:20 +0100 Subject: Improve description of the for loop. --- java.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index f6bc82c6..7ab22823 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -225,11 +225,12 @@ public class LearnJava { System.out.println("fooFor Value: " + fooFor); // For Each Loop - // An automatic iteration through an array or list of objects. + // The for loop is also able to iterate over arrays as well as objects + // that implement the Iterable interface. int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - // for each loop structure => for ( : ) - // reads as: for each object in the array - // note: the object type must match the array. + // for each loop structure => for ( : ) + // reads as: for each element in the collection + // note: the object type must match the element type of the collection. for (int bar : fooList) { System.out.println(bar); -- cgit v1.2.3 From 9319e442b1004d7b3ebec334b67e63810a8a90e2 Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Sun, 24 May 2015 16:03:32 +0400 Subject: Update header, fix typos and mistakes in Bash/ru translations --- ru-ru/bash-ru.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown index f8b28294..556c60f3 100644 --- a/ru-ru/bash-ru.html.markdown +++ b/ru-ru/bash-ru.html.markdown @@ -11,10 +11,13 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] - ["Etan Reisner", "https://github.com/deryni"] -filename: LearnBash.sh +translators: + - ["Andrey Samsonov", "https://github.com/kryzhovnik"] +filename: LearnBash-ru.sh +lang: ru-ru --- -Bash это командная оболочка unix (unix shell), которая распространяется как оболочка для операционной системы GNU и используется в качестве оболочки по умолчанию для Linux и Mac OS X. +Bash - это командная оболочка unix (unix shell), которая распространяется как оболочка для операционной системы GNU и используется в качестве оболочки по умолчанию для Linux и Mac OS X. Почти все нижеприведенные примеры могут могут быть частью shell-скриптов или быть исполнены напрямую в shell. [Подробнее.](http://www.gnu.org/software/bash/manual/bashref.html) -- cgit v1.2.3 From bdf4636d2302bb7ff84e105cdfeb25e7e3e6fa92 Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Sun, 24 May 2015 16:06:35 +0400 Subject: Fix typos and mistakes in Bash/ru translations --- ru-ru/bash-ru.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown index 556c60f3..f5b8c109 100644 --- a/ru-ru/bash-ru.html.markdown +++ b/ru-ru/bash-ru.html.markdown @@ -17,16 +17,16 @@ filename: LearnBash-ru.sh lang: ru-ru --- -Bash - это командная оболочка unix (unix shell), которая распространяется как оболочка для операционной системы GNU и используется в качестве оболочки по умолчанию для Linux и Mac OS X. -Почти все нижеприведенные примеры могут могут быть частью shell-скриптов или быть исполнены напрямую в shell. +Bash - это командная оболочка unix (unix shell), которая распространялась как оболочка для операционной системы GNU и используется в качестве оболочки по умолчанию для Linux и Mac OS X. +Почти все нижеприведенные примеры могут быть частью shell-скриптов или исполнены напрямую в shell. [Подробнее.](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash -# Первая строка скрипта - это shebang, который сообщает системе как исполнять +# Первая строка скрипта - это shebang, который сообщает системе, как исполнять # этот скрипт: http://en.wikipedia.org/wiki/Shebang_(Unix) -# Как вы уже поняли, комментарии начинаются с #. Shebang — тоже коммантарий. +# Как вы уже поняли, комментарии начинаются с #. Shebang - тоже комментарий. # Простой пример hello world: echo Hello world! @@ -34,12 +34,12 @@ echo Hello world! # Отдельные команды начинаются с новой строки или разделяются точкой с запятой: echo 'Это первая строка'; echo 'Это вторая строка' -# Вот так объявляется пемеренная: +# Вот так объявляется переменная: VARIABLE="Просто строка" # но не так: VARIABLE = "Просто строка" -# Bash решит что VARIABLE - это команда, которую он должен исполнить, +# Bash решит, что VARIABLE - это команда, которую он должен исполнить, # и выдаст ошибку, потому что не сможет найти ее. # и не так: -- cgit v1.2.3 From de676b62b83fcaaa9977cca9adb9c38383b64f35 Mon Sep 17 00:00:00 2001 From: Liam Edwards-Playne Date: Tue, 26 May 2015 11:25:07 +1000 Subject: fixed spelling error --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index c2312d7d..08182c2c 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -56,7 +56,7 @@ echo '$Variable' # String substitution in variables echo ${Variable/Some/A} -# This will substitute the first occurence of "Some" with "A" +# This will substitute the first occurrence of "Some" with "A" # Substring from a variable Length=7 -- cgit v1.2.3 From 22f1081ff2e940300cee0f0adcbbaf41abfb1c5f Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Tue, 26 May 2015 13:13:55 +0400 Subject: Fix typos and mistakes in Bash/ru translation --- ru-ru/bash-ru.html.markdown | 45 ++++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown index f5b8c109..e6741b1b 100644 --- a/ru-ru/bash-ru.html.markdown +++ b/ru-ru/bash-ru.html.markdown @@ -53,15 +53,15 @@ VARIABLE= 'Просто строка' echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' -# Когда вы используете переменную - присвоение, экспорт и т.д - пишите её -# имя без $. А для получения значения переменной, используйте $. -# Заметте что ' (одинарные кавычки) не раскрывают переменные в них. +# Когда вы используете переменную - присваиваете, экспортируете и т.д. - +# пишите её имя без $. А для получения значения переменной используйте $. +# Заметьте, что ' (одинарные кавычки) не раскрывают переменные в них. # Подстановка строк в переменные echo ${VARIABLE/Просто/A} # Это выражение заменит первую встреченную подстроку "Просто" на "A" -# Подстановка из переменной +# Взять подстроку из переменной LENGTH=7 echo ${VARIABLE:0:LENGTH} # Это выражение вернет только первые 7 символов переменной VARIABLE @@ -70,23 +70,23 @@ echo ${VARIABLE:0:LENGTH} echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} # Это сработает при отсутствующем значении (FOO=) и пустой строке (FOO=""); # ноль (FOO=0) вернет 0. -# Заметте, что в любом случае значение самой переменной FOO не изменится. +# Заметьте, что в любом случае значение самой переменной FOO не изменится. # Встроенные переменные: # В bash есть полезные встроенные переменные, например -echo "Последее возвращенное значение: $?" +echo "Последнее возвращенное значение: $?" echo "PID скрипта: $$" echo "Количество аргументов: $#" echo "Аргументы скрипта: $@" -echo "Аргументы скрипта рапределенные по отдельным переменным: $1 $2..." +echo "Аргументы скрипта, распределённые по отдельным переменным: $1 $2..." -# Чтение аргументов из входа: +# Чтение аргументов из устройста ввода: echo "Как Вас зовут?" -read NAME # Заметте, что нам не нужно определять новую переменную +read NAME # Обратите внимание, что нам не нужно определять новую переменную echo Привет, $NAME! # У нас есть обычная структура if: -# наберите 'man test' для подробностях о форматах условия +# наберите 'man test' для получения подробной информации о форматах условия if [ $NAME -ne $USER ] then echo "Имя не совпадает с именем пользователя" @@ -95,7 +95,7 @@ else fi # Также есть условное исполнение -echo "Исполнится всегда" || echo "Исполнится, если первая команда провалится" +echo "Исполнится всегда" || echo "Исполнится, если первая команда завершится ошибкой" echo "Исполнится всегда" && echo "Исполнится, если первая команда выполнится удачно" # Можно использовать && и || в выражениях if, когда нужно несколько пар скобок: @@ -112,8 +112,8 @@ fi # Выражения обозначаются таким форматом: echo $(( 10 + 5 )) -# В отличае от других языков программирования, bash это командная оболочка - -# значит он работает в контексте текущей директории. +# В отличие от других языков программирования, Bash - это командная оболочка, +# а значит, работает в контексте текущей директории. # Вы можете просматривать файлы и директории в текущей директории командой ls: ls @@ -126,7 +126,7 @@ ls -l # Показать каждый файл и директорию на от ls -l | grep "\.txt" # Вы можете перенаправить ввод и вывод команды (stdin, stdout и stderr). -# Следующая команда означает: читать из stdin пока не встретится ^EOF$ и +# Следующая команда означает: читать из stdin, пока не встретится ^EOF$, и # перезаписать hello.py следующим строками (до строки "EOF"): cat > hello.py << EOF #!/usr/bin/env python @@ -146,7 +146,7 @@ python hello.py 2> "error.err" python hello.py > "output-and-error.log" 2>&1 python hello.py > /dev/null 2>&1 # Поток ошибок перезапишет файл, если этот файл существует, -# поэтому если вы хотите дописывать файл используйте ">>": +# поэтому, если вы хотите дописывать файл, используйте ">>": python hello.py >> "output.out" 2>> "error.err" # Переписать output.txt, дописать error.err и сосчитать строки: @@ -165,12 +165,12 @@ echo "#helloworld" | tee output.out >/dev/null # Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим) rm -v output.out error.err output-and-error.log -# Команды могут быть подставлены в строку используя $( ): +# Команды могут быть подставлены в строку с помощью $( ): # следующие команды выводят число файлов и директорий в текущей директории. echo "Здесь $(ls | wc -l) элементов." -# То же самое можно сделать использую обратные кавычки, но они не могут быть -# вложенными - предпочтительно использовать $( ). +# То же самое можно сделать с использованием обратных кавычек, +# но они не могут быть вложенными, поэтому предпочтительно использовать $( ). echo "Здесь `ls | wc -l` элементов." # В Bash есть структура case, которая похожа на switch в Java и C++: @@ -188,7 +188,7 @@ do echo "$VARIABLE" done -# Или перепишем "традиционным" синтаксисом цикла for: +# Или с использованием "традиционного" синтаксиса цикла for: for ((a=1; a <= 3; a++)) do echo $a @@ -201,7 +201,7 @@ do cat "$VARIABLE" done -# ..или выводом из команд +# ... или выводом из команд # Запустим cat для вывода из ls. for OUTPUT in $(ls) do @@ -219,7 +219,7 @@ done # Определение: function foo () { - echo "Аргументы работают также как аругменты скрипта: $@" + echo "Аргументы работают также, как аргументы скрипта: $@" echo "и: $1 $2..." echo "Это функция" return 0 @@ -253,10 +253,9 @@ sed -i 's/okay/great/g' file.txt grep "^foo.*bar$" file.txt # передайте опцию -c чтобы вывести число строк, в которых совпал шаблон grep -c "^foo.*bar$" file.txt -# чтобы искать прямо строку, а не шаблон regex, используйте fgrep (или grep -F) +# чтобы искать по строке, а не шаблону regex, используйте fgrep (или grep -F) fgrep "^foo.*bar$" file.txt - # Читайте встроенную документацию оболочки Bash командой 'help': help help help -- cgit v1.2.3 From 8c3a0be856770aab3484e48cd1d1c11162b72db4 Mon Sep 17 00:00:00 2001 From: Simon Morgan Date: Tue, 26 May 2015 20:21:43 +0100 Subject: Further improve for loop description. --- java.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 7ab22823..928eb39f 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -228,9 +228,9 @@ public class LearnJava { // The for loop is also able to iterate over arrays as well as objects // that implement the Iterable interface. int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - // for each loop structure => for ( : ) - // reads as: for each element in the collection - // note: the object type must match the element type of the collection. + // for each loop structure => for ( : ) + // reads as: for each element in the iterable + // note: the object type must match the element type of the iterable. for (int bar : fooList) { System.out.println(bar); -- cgit v1.2.3 From 7a4538374c4b86a355573039cc5426a32e936d11 Mon Sep 17 00:00:00 2001 From: ryan ouyang Date: Thu, 28 May 2015 13:07:01 +0800 Subject: Update type error of chinese translation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Line 344: From "行数" to "函数" --- zh-cn/javascript-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 64b0aadc..b450ab84 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -341,7 +341,7 @@ var myFunc = myObj.myFunc; myFunc(); // = undefined // 相应的,一个函数也可以被指定为一个对象的方法,并且可以通过`this`访问 -// 这个对象的成员,即使在行数被定义时并没有依附在对象上。 +// 这个对象的成员,即使在函数被定义时并没有依附在对象上。 var myOtherFunc = function(){ return this.myString.toUpperCase(); } -- cgit v1.2.3 From fbfd64b3675fb0e0d9981378b0b6861c61945fcb Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Wed, 20 May 2015 08:45:15 +0100 Subject: [erlang/en] Fix #970 --- erlang.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 322e437d..a897755e 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -167,8 +167,12 @@ is_dog(A) -> false. % A guard sequence is either a single guard or a series of guards, separated % by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at % least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`. -is_pet(A) when is_dog(A); is_cat(A) -> true; -is_pet(A) -> false. +is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true; +is_pet(A) -> false. + +% Warning: not all valid Erlang expressions can be used as guard expressions; +% in particular, our `is_cat` and `is_dog` functions cannot be used within the +% guard sequence in `is_pet`'s definition. % Records provide a method for associating a name with a particular element in a % tuple. -- cgit v1.2.3 From e4c0629c38223db43e91414b2d44a540da47565e Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Wed, 20 May 2015 10:35:04 +0100 Subject: [erlang/en] Add link to Erlang reference manual --- erlang.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index a897755e..e5db6423 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -172,7 +172,10 @@ is_pet(A) -> false. % Warning: not all valid Erlang expressions can be used as guard expressions; % in particular, our `is_cat` and `is_dog` functions cannot be used within the -% guard sequence in `is_pet`'s definition. +% guard sequence in `is_pet`'s definition. For a list of the built-in +% functions (BIFs) allowed in guard sequences, refer to this +% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912) +% of the Erlang reference manual. % Records provide a method for associating a name with a particular element in a % tuple. -- cgit v1.2.3 From f9649ac5529eed31a6b954b160c4e461a6bc25dd Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Thu, 28 May 2015 09:21:27 +0200 Subject: [erlang/en] Clarify bit about guard sequences --- erlang.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index e5db6423..a3b571d1 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -172,8 +172,8 @@ is_pet(A) -> false. % Warning: not all valid Erlang expressions can be used as guard expressions; % in particular, our `is_cat` and `is_dog` functions cannot be used within the -% guard sequence in `is_pet`'s definition. For a list of the built-in -% functions (BIFs) allowed in guard sequences, refer to this +% guard sequence in `is_pet`'s definition. For a description of the +% expressions allowed in guard sequences, refer to this % [section](http://erlang.org/doc/reference_manual/expressions.html#id81912) % of the Erlang reference manual. -- cgit v1.2.3 From 1aa91a6420b17d6d982fb3361ba938511355fc7c Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Thu, 28 May 2015 20:40:39 +0200 Subject: [erlang/fr] Add french translation --- fr-fr/erlang-fr.html.markdown | 325 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 325 insertions(+) create mode 100644 fr-fr/erlang-fr.html.markdown diff --git a/fr-fr/erlang-fr.html.markdown b/fr-fr/erlang-fr.html.markdown new file mode 100644 index 00000000..564e176f --- /dev/null +++ b/fr-fr/erlang-fr.html.markdown @@ -0,0 +1,325 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: + - ["Julien Cretel", "https://github.com/Jubobs"] +filename: learnerlang-fr.erl +lang: fr-fr +--- + +```erlang +% Un signe pour cent marque le début d'un commentaire de fin de ligne. + +%% Deux signes pour cent sont utilisés pour commenter les fonctions. + +%%% Trois signes pour cent sont utilisés pour commenter les modules. + +% Trois types de ponctuation sont utilisés en Erlang. +% Les virgules (`,`) servent à séparer les paramètres dans les appels de +% fonctions, les contructeurs, et les motifs. +% Les points (`.`) (suivis par des caractères blancs) servent à séparer +% les fonctions et les expressions dans l'interpréteur. +% Les points-virgules (`;`) servent à séparer les clauses. Ces dernières +% apparaissent dans différent cas de figure : définitions de fonctions et +% expressions `case`, `if`, `try..catch`, et `receive`. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. Variables et filtrage par motif. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Nb = 42. % Chaque nom de variable doit commencer par une lettre majuscule. + +% Les variables Erlang ne peuvent être affectées qu'une seule fois ; si vous +% essayez d'affecter une autre valeur à la variable `Nb`, vous obtiendrez +% une erreur. +Nb = 43. % ** exception error: no match of right hand side value 43 + +% Dans la plupart des languages, `=` indique une affectation. En Erlang, +% cependant, `=` indique un filtrage par motif. En fait, `Gauche = Droit` +% signifie ce qui suit : évalue le côté droit (`Droit`), et ensuite filtre le +% résultat à l'aide du motif du côté gauche (`Gauche`). +Nb = 7 * 6. + +% Nombre en virgule flottante. +Pi = 3.14159. + +% Les atomes représentent des valeurs constantes non-numériques. Un atome +% commence par une lettre minuscule, suivie d'une séquence composée de +% caractères alphanumériques, de tirets bas (`_`), ou d'arobases (`@`). +Bonjour = bonjour. +AutreNoeud = exemple@noeud. + +% Les atomes de valeur autre qu'alphanumérique peuvent être délimités par +% des guillemets droits simples. +AtomeAvecEspace = 'un atome contenant des espaces'. + +% Les tuples sont similaires aux enregistrements du language C. +Point = {point, 10, 45}. + +% Pour extraire des valeurs d'un tuple, on filtre par motif avec +% l'opérateur `=`. +{point, X, Y} = Point. % X = 10, Y = 45 + +% On peut utiliser `_` comme caractère joker pour les variables qui ne nous +% intéressent pas. Le symbol `_` est appelé variable muette. Contrairement +% aux variables normales, de multiples apparitions de `_` dans un même motif +% ne lient pas nécessairement à la même valeur. +Personne = {personne, {nom, {prenom, joe}, {famille, armstrong}}, + {pointure, 42}}. +{_, {_, {_, Qui}, _}, _} = Personne. % Qui = joe + +% Pour créer une liste, on écrit les éléments de la liste entre crochets, en +% les séparant par des virgules. +% Les éléments d'une liste peuvent avoir n'importe quel type. +% Le premier élément d'une liste est appelé la tête de la liste. Si on retire +% la tête d'une liste, ce qui reste est appelée la queue de la liste. +Articles = [{pommes, 10}, {poires, 6}, {lait, 3}]. + +% Si `Q` est une liste, alors `[T|Q]` est aussi une liste dont la tête est `T` +% et dont la queue est `Q`. La barre verticale (`|`) sépare la tête d'une +% liste de sa queue. +% `[]` est la liste vide. +% On peut extraire des éléments d'une liste par filtrage de motif. Si `L` est +% une liste non vide, alors l'expression `[X|Y] = L`, où `X` et `Y` sont des +% variables non affectées, va extraire la tête de la liste dans `X` et la +% queue de la liste dans `Y`. +[PremierArticle|AutresArticles] = Articles. +% PremierArticle = {pommmes, 10} +% AutresArticles = [{poires, 6}, {lait, 3}] + +% Il n'y a pas de chaînes de caractères en Erlang. Les chaînes de caractères +% ne sont rien de plus que des listes d'entiers. +% Les chaînes de caractères sont délimitées par des guillemets droits doubles +% (`"`). +Nom = "Bonjour". +[66, 111, 110, 106, 111, 117, 114] = "Bonjour". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. Programmation séquentielle. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Les modules constituent l'unité de base d'un programme Erlang. Toutes les +% fonctions que l'on écrit sont sauvées dans des modules. Les modules sont +% enregistrés dans des fichiers avec une extension `.erl`. +% Les modules doivent être compilés afin d'éxecuter le programme. +% Un module compilé a une extension `.beam`. +-module(geometrie). +-export([aire/1]). % la liste des fonctions exportées par le module. + +% La fonction `aire` est composée de deux clauses. Les clauses sont séparées +% par un point-virgule, et la dernière clause est suivie d'un point et un +% espace blanc. Chaque clause a une en-tête et un corps ; l'en-tête consiste +% en un nom de fonction suivi d'un motif (entre parenthèses), et le corps +% consiste en une séquence d'expressions, qui sont évaluées si le motif de +% l'en-tête est cohérent par rapport à la valeur des paramètres d'appel. +% L'expression est filtrée séquentiellement par les différents motifs, dans +% l'ordre dans lequel ils apparaissent dans la définition de la fonction. +aire({rectangle, Largeur, Hauteur}) -> Largeur * Hauteur; +aire({cercle, R}) -> 3.14159 * R * R. + +% Compilation du code du fichier geometrie.erl. +c(geometrie). % {ok,geometrie} + +% Le nom du module doit être inclus avec le nom de la fonction afin +% d'identifier précisément quelle fonction on souhaite appeler. +geometrie:aire({rectangle, 10, 5}). % 50 +geometrie:area({cercle, 1.4}). % 6.15752 + +% En Erlang, deux fonctions portant le même nom mais ayant des arités +% différentes (c'est à dire ne prenant pas le même nombre de paramètres) +% au sein d'un même module représentent des fonctions complètement +% différentes. +-module(lib_divers). +-export([somme/1]). % exporte la fonction `somme` d'arité 1 + % acceptant un paramètre : une liste d'entiers. +somme(L) -> somme(L, 0). +somme([], N) -> N; +somme([T|Q], N) -> somme(Q, T+N). + +% Les funs sont des fonctions "anonymes" ; elles sont appelées ainsi parce +% qu'elles n'ont pas de noms. Cependant, elles peuvent être affectées à des +% variables. +Doubler = fun(X) -> 2 * X end. % `Doubler` pointe vers une fonction anonyme + % dont le handle est : #Fun +Doubler(2). % 4 + +% Les fonctions peuvent prendre des funs comme paramètres et peuvent renvoyer +% des funs. +Mult = fun(Fois) -> ( fun(X) -> X * Fois end ) end. +Tripler = Mult(3). +Tripler(5). % 15 + +% Les listes en compréhension sont des expressions qui créent des listes sans +% requérir ni funs, ni maps, ni filters. +% La notation `[F(X) || X <- L]` signifie "la liste des `F(X)` où `X` est +% extrait de la liste `L`." +L = [1,2,3,4,5]. +[2 * X || X <- L]. % [2,4,6,8,10] +% Une liste en compréhension peut avoir des générateurs, ainsi que des gardes, +% qui sélectionnent un sous-ensemble des valeurs générées. +NombresPairs = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% La garde est un élément syntaxique qui rend le filtrage par motif encore +% plus puissant. Les gardes permettent de d'effectuer de simple tests et +% comparaisons sur les variables d'un motif. Les gardes peuvent être +% utilisées dans les en-têtes de fonctions, au sein desquelles elles sont +% introduites par le mot-clé `when`, ou encore à n'importe quel endroit où +% une expression est autorisée. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% Une garde est une série d'expressions gardes, séparées par des virgules (`,`). +% La garde `ExprGarde1, ExprGarde2, ..., ExprGardeN` est vraie si toutes les +% expressions gardes `ExprGarde1`, `ExprGarde2, ..., `ExprGardeN` ont pour +% valeur `true`. +est_chat(A) when is_atom(A), A =:= chat -> true; +est_chat(A) -> false. +est_chien(A) when is_atom(A), A =:= chien -> true; +est_chien(A) -> false. + +% Une séquence de gardes est composée soit d'une seule garde ou bien d'une +% série de gardes, séparées par des points-virgules (`;`). La séquence de +% gardes `G1; G2; ...; Gn` est vraie si au moins l'une des gardes `G1`, `G2`, +% ..., `Gn` a pour valeur `true`. +est_animal(A) when is_atom(A), (A =:= chien) or (A =:= chat) -> true; +est_animal(A) -> false. + +% Attention : les expressions Erlang valides ne peuvent pas toutes être +% utilisées comme expressions gardes ; en particulier, nos fonctions +% `est_chat` et `est_chien` ne sont pas autorisées au sein de la séquence de +% gardes dans la définition de `est_animal`. Pour plus de détails sur les +% expressions autorisées ands les séquences de gardes, voir cette +% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912) +% du manuel Erlang. + +% Les enregistrements permettent d'associer un nom à un certain élément dans +% un tuple. +% Les enregistrements peuvent être définis dans des fichiers sources Erlang +% ou bien dans des fichiers avec une extension `.hrl`, qui sont ensuite inclus +% dans des fichiers sources Erlang. +-record(afaire, { + statut = rappel, % Valeur par défaut + qui = joe, + texte +}). + +% Les définitions d'enregistrements doivent être lues dans l'interpreteur +% pour qu'on puisse définir un enregistrement. On utilise la fonction `rr` +% (abbréviation de *read records* en anglais, ou *lire enregistrements* en +% français) pour ça. +rr("enregistrements.hrl"). % [afaire] + +% Création et mise à jour d'enregistrements : +X = #afaire{}. +% #afaire{statut = rappel, qui = joe, texte = undefined} +X1 = #afaire{statut = urgent, texte = "Corriger erreurs dans livre"}. +% #afaire{statut = urgent, qui = joe, texte = "Corriger erreurs dans livre"} +X2 = X1#afaire{statut = fini}. +% #afaire{statut = fini, qui = joe, texte = "Corriger erreurs dans livre"} + +% Expressions `case`. +% `filter` renvoie une liste de tous les éléments `X` d'une liste `L` pour +% lesquels `P(X)` est vrai. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% Expressions `if`. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil + end. + +% Attention : au moins l'une des gardes dans l'expression `if` doit avoir pour +% valeur `true` ; autrement, une exception sera lancée. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. Exceptions. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Des exceptions sont lancées par le système quand des erreurs internes +% surviennent, ou de manière explicite dans le programme en appelant +% `throw(Exception)`, `exit(Exception)`, ou `erlang:error(Exception)`. +generer_exception(1) -> a; +generer_exception(2) -> throw(a); +generer_exception(3) -> exit(a); +generer_exception(4) -> {'EXIT', a}; +generer_exception(5) -> erlang:error(a). + +% Erlang dispose de deux méthodes pour capturer une exception. La première +% consiste à inclure l'appel de de la fonction qui lance l'exception dans une +% expression `try...catch`. +catcher(N) -> + try generer_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% L'autre méthode consiste à inclure l'appel dans une expression `catch`. +% Quand une exception est capturée, elle est convertie en un tuple qui décrit +% l'erreur. +catcher(N) -> catch generer_exception(N). + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 4. Concurrence +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang est basé sur le modèle d'acteur pour la concurrence. Seulement trois +% opérations sont requises pour écrire des programmes concurrents en Erlang : +% la création de processus, l'envoi de messages, et la réception de messages. + +% Pour démarrer un nouveau processus, on utilise la fonction `spawn`, qui +% prend une fonction comme paramètre. + +F = fun() -> 2 + 2 end. % #Fun +spawn(F). % <0.44.0> + +% `spawn` renvoie un pid (*process identifier* en anglais, ou *identifiant de +% processus* en français), qui peut être utilisé pour envoyer des messages au +% processus en question. Pour passer des messages, on utilise l'opérateur `!`. +% Pour que cela soit utile, on doit aussi être en mesure de recevoir des +% messages, ce qui est accompli grâce à une clause `receive` : + +-module(calculerGeometrie). +-compile(export_all). +calculerAire() -> + receive + {rectangle, W, H} -> + W * H; + {cercle, R} -> + 3.14 * R * R; + _ -> + io:format("Seule l'aire d'un rectangle / cercle peut etre calculee.") + end. + +% Compilation du module and création d'un processus qui évalue `calculerAire` +% dans l'interpréteur. +c(calculerGeometrie). +CalculerAire = spawn(calculerGeometrie, calculerAire, []). +CalculerAire ! {cercle, 2}. % 12.56000000000000049738 + +% L'interpréteur est lui-même un processus ; on peut utiliser `self` pour +% obtenir le pid actuel. +self(). % <0.41.0> + +``` + +## Références + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) -- cgit v1.2.3 From 5d3e938574b74704801dcb61043a8603ac087f73 Mon Sep 17 00:00:00 2001 From: Bobby Wilson Date: Sat, 30 May 2015 11:43:37 -0600 Subject: Use keywords in POST/PUT examples Using strings doesn't work for the POST/PUT examples here, changing them to keywords fixes this --- compojure.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 36a8d123..32181e26 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -155,8 +155,8 @@ Now, your handlers may utilize query parameters: ```clojure (defroutes myapp (GET "/posts" req - (let [title (get (:params req) "title") - author (get (:params req) "author")] + (let [title (get (:params req) :title) + author (get (:params req) :author)] (str "Title: " title ", Author: " author)))) ``` @@ -165,8 +165,8 @@ Or, for POST and PUT requests, form parameters as well ```clojure (defroutes myapp (POST "/posts" req - (let [title (get (:params req) "title") - author (get (:params req) "author")] + (let [title (get (:params req) :title) + author (get (:params req) :author)] (str "Title: " title ", Author: " author)))) ``` -- cgit v1.2.3 From 462ac892179d64437b1124263402378a6054e50b Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 31 May 2015 21:38:03 -0400 Subject: Remove return type from Dog class constructor and destructor, change nonexistant printDog function to print. --- c++.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 9f8f5f32..2c6d51a9 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -300,7 +300,7 @@ public: }; // A semicolon must follow the class definition. // Class member functions are usually implemented in .cpp files. -void Dog::Dog() +Dog::Dog() { std::cout << "A dog has been constructed\n"; } @@ -323,7 +323,7 @@ void Dog::print() const std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; } -void Dog::~Dog() +Dog::~Dog() { cout << "Goodbye " << name << "\n"; } @@ -332,7 +332,7 @@ int main() { Dog myDog; // prints "A dog has been constructed" myDog.setName("Barkley"); myDog.setWeight(10); - myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg" + myDog.print(); // prints "Dog is Barkley and weighs 10 kg" return 0; } // prints "Goodbye Barkley" -- cgit v1.2.3 From 3db1042157204ad05484d6b42140261f849040cc Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 31 May 2015 21:42:03 -0400 Subject: Add missing semicolons. --- c++.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 2c6d51a9..5cd491b9 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -288,7 +288,7 @@ public: // Functions can also be defined inside the class body. // Functions defined as such are automatically inlined. - void bark() const { std::cout << name << " barks!\n" } + void bark() const { std::cout << name << " barks!\n"; } // Along with constructors, C++ provides destructors. // These are called when an object is deleted or falls out of scope. @@ -341,7 +341,7 @@ int main() { // This class inherits everything public and protected from the Dog class class OwnedDog : public Dog { - void setOwner(const std::string& dogsOwner) + void setOwner(const std::string& dogsOwner); // Override the behavior of the print function for all OwnedDogs. See // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping -- cgit v1.2.3 From bdedf51a72156d925b1814776e272572a9c8e581 Mon Sep 17 00:00:00 2001 From: Avjinder Singh Sekhon Date: Mon, 1 Jun 2015 23:46:04 +0530 Subject: Added 'Stages of Git', link to Pro Git, and other forms of git help --- git.html.markdown | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index af65afb0..dd93dd88 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -79,6 +79,11 @@ this pointer will automatically update and point to the latest commit. HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. head is a pointer that points to any commit. A repository can have any number of heads. +###Stages of Git +* Committed - Files have been committed to the Git Database +* Modified - Changes have been made to a file but file has not been committed to Git Database yet +* Staged - Marks a modified file to go into your next commit snapshot + ### Conceptual Resources * [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) @@ -131,6 +136,10 @@ $ git help -a $ git help add $ git help commit $ git help init +# or git --help +$ git add --help +$ git commit --help +$ git init --help ``` ### status @@ -149,8 +158,8 @@ $ git help status ### add -To add files to the current working tree/directory/repo. If you do not `git add` new files to the -working tree/directory, they will not be included in commits! +To add files to the staging area/index. If you do not `git add` new files to the +staging area/index, they will not be included in commits! ```bash # add a file in your current working directory @@ -163,6 +172,8 @@ $ git add /path/to/file/HelloWorld.c $ git add ./*.java ``` +This only addds a file to the staging area/index, it doesn't commit it to the working directory/repo. + ### branch Manage your branches. You can view, edit, create, delete branches using this command. @@ -462,3 +473,5 @@ $ git rm /pather/to/the/file/HelloWorld.c * [GitGuys](http://www.gitguys.com/) * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) -- cgit v1.2.3 From 470da394f6641dd0a56f48da5bb5f451ea0cbcdc Mon Sep 17 00:00:00 2001 From: Avjinder Singh Sekhon Date: Mon, 1 Jun 2015 23:49:05 +0530 Subject: Fixed some typos --- git.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index dd93dd88..1b83e3a3 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -172,7 +172,7 @@ $ git add /path/to/file/HelloWorld.c $ git add ./*.java ``` -This only addds a file to the staging area/index, it doesn't commit it to the working directory/repo. +This only adds a file to the staging area/index, it doesn't commit it to the working directory/repo. ### branch -- cgit v1.2.3 From cea52ca43490b74316781c23779654fd46aaeab4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jun 2015 21:57:18 -0400 Subject: Exceptions do not take a string argument in their constructor. --- c++.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 5cd491b9..b214de7a 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -523,7 +523,7 @@ printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" // _catch_ handlers. try { // Do not allocate exceptions on the heap using _new_. - throw std::exception("A problem occurred"); + throw std::exception(); } // Catch exceptions by const reference if they are objects catch (const std::exception& ex) @@ -614,7 +614,7 @@ void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Open the file in read mode if (fh == nullptr) - throw std::exception("Could not open the file."); + throw std::exception(); try { doSomethingWithTheFile(fh); -- cgit v1.2.3 From 47d3cea47e8c5203efa857070a00dcfbff67b019 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jun 2015 22:00:52 -0400 Subject: Template example class should have public method so it can get called externally. --- c++.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/c++.html.markdown b/c++.html.markdown index b214de7a..d049408a 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -445,6 +445,7 @@ int main () { // define a class or function that takes a type parameter: template class Box { +public: // In this class, T can be used as any other type. void insert(const T&) { ... } }; -- cgit v1.2.3 From 59b719015a5fadf6a1d12854a19b0196c8481ec8 Mon Sep 17 00:00:00 2001 From: Alwayswithme Date: Tue, 2 Jun 2015 15:55:12 +0800 Subject: minor revision --- zh-cn/bash-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 13f85bb7..63bec888 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -45,7 +45,7 @@ VARIABLE = "Some string" # 也不可以这样: Variable= 'Some string' # Bash 会认为 'Some string' 是一条指令,由于找不到该指令,这里再次报错。 -# (这个例子中 'Variable=' 这部分的赋值仅对 'Some string' 指令起作用。) +# (这个例子中 'Variable=' 这部分会被当作仅对 'Some string' 起作用的赋值。) # 使用变量: echo $VARIABLE @@ -264,7 +264,7 @@ apropos bash man 1 bash man bash -# 用 info 指令查阅命令的 info 文档 (info 中输入 ? 显示帮助信息) +# 用 info 指令查阅命令的 info 文档 (info 中按 ? 显示帮助信息) apropos info | grep '^info.*(' man info info info -- cgit v1.2.3 From da0d1819f85489990418713f565013f51811bdb9 Mon Sep 17 00:00:00 2001 From: Alwayswithme Date: Tue, 2 Jun 2015 16:38:11 +0800 Subject: only capitalize first character of the variable --- zh-cn/bash-cn.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 63bec888..1b79f326 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -36,11 +36,11 @@ echo Hello, world! echo 'This is the first line'; echo 'This is the second line' # 声明一个变量: -VARIABLE="Some string" +Variable="Some string" # 下面是错误的做法: -VARIABLE = "Some string" -# Bash 会把 VARIABLE 当做一个指令,由于找不到该指令,因此这里会报错。 +Variable = "Some string" +# Bash 会把 Variable 当做一个指令,由于找不到该指令,因此这里会报错。 # 也不可以这样: Variable= 'Some string' @@ -48,17 +48,17 @@ Variable= 'Some string' # (这个例子中 'Variable=' 这部分会被当作仅对 'Some string' 起作用的赋值。) # 使用变量: -echo $VARIABLE -echo "$VARIABLE" -echo '$VARIABLE' +echo $Variable +echo "$Variable" +echo '$Variable' # 当你赋值 (assign) 、导出 (export),或者以其他方式使用变量时,变量名前不加 $。 # 如果要使用变量的值, 则要加 $。 # 注意: ' (单引号) 不会展开变量(即会屏蔽掉变量)。 # 在变量内部进行字符串代换 -echo ${VARIABLE/Some/A} -# 会把 VARIABLE 中首次出现的 "some" 替换成 “A”。 +echo ${Variable/Some/A} +# 会把 Variable 中首次出现的 "some" 替换成 “A”。 # 变量的截取 Length=7 @@ -80,12 +80,12 @@ echo "Scripts arguments separeted in different variables: $1 $2..." # 读取输入: echo "What's your name?" -read NAME # 这里不需要声明新变量 -echo Hello, $NAME! +read Name # 这里不需要声明新变量 +echo Hello, $Name! # 通常的 if 结构看起来像这样: # 'man test' 可查看更多的信息 -if [ $NAME -ne $USER ] +if [ $Name -ne $USER ] then echo "Your name is you username" else @@ -167,7 +167,7 @@ echo "There are $(ls | wc -l) items here." echo "There are `ls | wc -l` items here." # Bash 的 case 语句与 Java 和 C++ 中的 switch 语句类似: -case "$VARIABLE" in +case "$Variable" in # 列出需要匹配的字符串 0) echo "There is a zero.";; 1) echo "There is a one.";; @@ -175,11 +175,11 @@ case "$VARIABLE" in esac # 循环遍历给定的参数序列: -# 变量$VARIABLE 的值会被打印 3 次。 +# 变量$Variable 的值会被打印 3 次。 # 注意 ` ` 和 $( ) 等价。seq 返回长度为 3 的数组。 -for VARIABLE in `seq 3` +for Variable in `seq 3` do - echo "$VARIABLE" + echo "$Variable" done # 或传统的 “for循环” : @@ -227,7 +227,7 @@ bar () } # 调用函数 -foo "My name is" $NAME +foo "My name is" $Name # 有很多有用的指令需要学习: # 打印 file.txt 的最后 10 行 -- cgit v1.2.3 From ee7f99fc461afad7d4aba4ac4226bdf7102abee4 Mon Sep 17 00:00:00 2001 From: Alwayswithme Date: Tue, 2 Jun 2015 17:02:23 +0800 Subject: command sync with english version --- zh-cn/bash-cn.html.markdown | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 1b79f326..558d9110 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -30,7 +30,7 @@ Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的 # 如你所见,注释以 # 开头,shebang 也是注释。 # 显示 “Hello world!” -echo Hello, world! +echo Hello world! # 每一句指令以换行或分号隔开: echo 'This is the first line'; echo 'This is the second line' @@ -76,7 +76,7 @@ echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $#" echo "Scripts arguments: $@" -echo "Scripts arguments separeted in different variables: $1 $2..." +echo "Scripts arguments separated in different variables: $1 $2..." # 读取输入: echo "What's your name?" @@ -87,13 +87,13 @@ echo Hello, $Name! # 'man test' 可查看更多的信息 if [ $Name -ne $USER ] then - echo "Your name is you username" + echo "Your name isn't your username" else - echo "Your name isn't you username" + echo "Your name is your username" fi # 根据上一个指令执行结果决定是否执行下一个指令 -echo "Always executed" || echo "Only executed if first command fail" +echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" # 在 if 语句中使用 && 和 || 需要多对方括号 @@ -176,8 +176,7 @@ esac # 循环遍历给定的参数序列: # 变量$Variable 的值会被打印 3 次。 -# 注意 ` ` 和 $( ) 等价。seq 返回长度为 3 的数组。 -for Variable in `seq 3` +for Variable in {1..3} do echo "$Variable" done @@ -275,5 +274,4 @@ info bash info bash 'Bash Features' info bash 6 info --apropos bash - ``` -- cgit v1.2.3 From 894792e1e17173823a5d50de24439427c69d63f4 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jun 2015 16:30:35 -0400 Subject: Using std::runtime_error instead of std::exception. --- c++.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index d049408a..6f4d2959 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -519,12 +519,13 @@ printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" // (see http://en.cppreference.com/w/cpp/error/exception) // but any type can be thrown an as exception #include +#include // All exceptions thrown inside the _try_ block can be caught by subsequent // _catch_ handlers. try { // Do not allocate exceptions on the heap using _new_. - throw std::exception(); + throw std::runtime_error("A problem occurred"); } // Catch exceptions by const reference if they are objects catch (const std::exception& ex) -- cgit v1.2.3 From 628a4ccfc2d55de69a55622c9cd8a0d9d7819013 Mon Sep 17 00:00:00 2001 From: Avjinder Singh Sekhon Date: Wed, 3 Jun 2015 03:02:38 +0530 Subject: Changed the order of the Stages of Git --- git.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index 1b83e3a3..4bbc58e7 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -80,9 +80,9 @@ HEAD is a pointer that points to the current branch. A repository only has 1 *ac head is a pointer that points to any commit. A repository can have any number of heads. ###Stages of Git -* Committed - Files have been committed to the Git Database * Modified - Changes have been made to a file but file has not been committed to Git Database yet * Staged - Marks a modified file to go into your next commit snapshot +* Committed - Files have been committed to the Git Database ### Conceptual Resources -- cgit v1.2.3 From 06889be239622266d9c36c750f7ee755ccdae05d Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jun 2015 19:14:52 -0400 Subject: Updated other exception to also be runtime_error type instead. --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6f4d2959..ff2a98fd 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -616,7 +616,7 @@ void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Open the file in read mode if (fh == nullptr) - throw std::exception(); + throw std::runtime_error("Could not open the file."); try { doSomethingWithTheFile(fh); -- cgit v1.2.3 From 152c03ddf9072ed80efef0528968ca132385a2aa Mon Sep 17 00:00:00 2001 From: inaimathi Date: Sat, 6 Jun 2015 12:51:45 -0400 Subject: Add notes about records to Standard ML page. --- standard-ml.html.markdown | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 07896beb..125183c0 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Simon Shine", "http://shine.eu.org/"] - ["David Pedersen", "http://lonelyproton.com/"] - ["James Baker", "http://www.jbaker.io/"] + - ["Leo Zovic", "http://langnostic.inaimathi.ca/"] --- Standard ML is a functional programming language with type inference and some @@ -136,9 +137,29 @@ val mixup = [ ("Alice", 39), val good_bad_stuff = (["ice cream", "hot dogs", "chocolate"], - ["liver", "paying the rent" ]) (* string list * string list *) + ["liver", "paying the rent" ]) (* : string list * string list *) +(* Records are tuples with named slots *) + +val rgb = { r=0.23, g=0.56, b=0.91 } (* : {b:real, g:real, r:real} *) + +(* You don't need to declare their slots ahead of time. Records with + different slot names are considered different types, even if their + slot value types match up. For instance... *) + +val Hsl = { H=310.3, s=0.51, l=0.23 } (* : {H:real, l:real, s:real} *) +val Hsv = { H=310.3, s=0.51, v=0.23 } (* : {H:real, s:real, v:real} *) + +(* ...trying to evaluate `Hsv = Hsl` or `rgb = Hsl` would give a type + error. While they're all three-slot records composed only of `real`s, + they each have different names for at least some slots. *) + +(* You can use hash notation to get values out of tuples. *) + +val H = #H Hsv (* : real *) +val s = #s Hsl (* : real *) + (* Functions! *) fun add_them (a, b) = a + b (* A simple function that adds two numbers *) val test_it = add_them (3, 4) (* gives 7 *) @@ -225,17 +246,26 @@ fun fibonacci 0 = 0 (* Base case *) | fibonacci 1 = 1 (* Base case *) | fibonacci n = fibonacci (n - 1) + fibonacci (n - 2) (* Recursive case *) -(* Pattern matching is also possible on composite types like tuples and lists. - Writing "fun solve2 (a, b, c) = ..." is in fact a pattern match on the one - three-tuple solve2 takes as argument. Similarly, but less intuitively, you - can match on a list consisting of elements in it (from the beginning of the - list only). *) +(* Pattern matching is also possible on composite types like tuples, lists and + records. Writing "fun solve2 (a, b, c) = ..." is in fact a pattern match on + the one three-tuple solve2 takes as argument. Similarly, but less intuitively, + you can match on a list consisting of elements in it (from the beginning of + the list only). *) fun first_elem (x::xs) = x fun second_elem (x::y::xs) = y fun evenly_positioned_elems (odd::even::xs) = even::evenly_positioned_elems xs | evenly_positioned_elems [odd] = [] (* Base case: throw away *) | evenly_positioned_elems [] = [] (* Base case *) +(* When matching on records, you must use their slot names, and you must bind + every slot in a record. The order of the slots doesn't matter though. *) + +fun rgbToTup {r, g, b} = (r, g, b) (* fn : {b:'a, g:'b, r:'c} -> 'c * 'b * 'a *) +fun mixRgbToTup {g, b, r} = (r, g, b) (* fn : {b:'a, g:'b, r:'c} -> 'c * 'b * 'a *) + +(* If called with {r=0.1, g=0.2, b=0.3}, either of the above functions + would return (0.1, 0.2, 0.3). But it would be a type error to call them + with {r=0.1, g=0.2, b=0.3, a=0.4} *) (* Higher order functions: Functions can take other functions as arguments. Functions are just other kinds of values, and functions don't need names -- cgit v1.2.3 From 21c3187f11cbb9926959af23d76743718e96d77b Mon Sep 17 00:00:00 2001 From: inaimathi Date: Sat, 6 Jun 2015 12:53:33 -0400 Subject: Fix indentation --- standard-ml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 125183c0..143980e7 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Simon Shine", "http://shine.eu.org/"] - ["David Pedersen", "http://lonelyproton.com/"] - ["James Baker", "http://www.jbaker.io/"] - - ["Leo Zovic", "http://langnostic.inaimathi.ca/"] + - ["Leo Zovic", "http://langnostic.inaimathi.ca/"] --- Standard ML is a functional programming language with type inference and some -- cgit v1.2.3 From be761f49ef2b99302e8f1d86c4a7d9e3e0b8cbe4 Mon Sep 17 00:00:00 2001 From: Jack Union Date: Sun, 7 Jun 2015 12:03:50 +0300 Subject: css/ru translation --- ru-ru/css-ru.html.markdown | 250 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 ru-ru/css-ru.html.markdown diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown new file mode 100644 index 00000000..2e2d40b7 --- /dev/null +++ b/ru-ru/css-ru.html.markdown @@ -0,0 +1,250 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] +filename: learncss-ru.css +lang: ru-ru +--- + +В свои ранние дни веб состоял в основном из чистого текста. С развитием браузеров +веб-страницы с графическими элементами стали обычным делом. +CSS - язык, разграничивающий содержимое (HTML) и внешний вид веб-страниц. + +Если коротко, то CSS предоставляет синтаксис, позволяющий выбирать различные +HTML элементы и определять их внешний вид. + +Как и у других языков, у CSS много версий. Мы описываем CSS2.0 - не самую новую, +но самую поддерживаемую и распространенную версию. + +**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида +элементов, постарайтесь использовать CSS-песочницы при изучении языка. +Например [dabblet](http://dabblet.com/). +В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации. + + +```css +/* Для комментариев используется слеш-астериск, как на этой строчке. + В CSS нет однострочных комментариев; все комментарии записываются таким способом */ + +/* #################### + ## СЕЛЕКТОРЫ + #################### */ + +/* Выражения в CSS очень просты */ +селектор { атрибут: значение; /* другие атрибуты...*/ } + +/* селекторы используются для выбора элементов на странице + +Чтобы выбрать все элементы, используйте астериск: */ +* { color:red; } + +/* +Если на странице присутствует такой элемент: + +
+*/ + +/* его можно выбрать по одному классу */ +.some-class { } + +/* или по обоим классам */ +.some-class.class2 { } + +/* по названию тега */ +div { } + +/* по идентификатору */ +#someId { } + +/* по имеющемуся атрибуту */ +[attr] { font-size:smaller; } + +/* или по атрибуту с определенным значением */ +[attr='value'] { font-size:smaller; } + +/* можно выбрать атрибуты, начинающиеся с определенного значения (CSS3) */ +[attr^='val'] { font-size:smaller; } + +/* или заканчивающиеся определенным значением (CSS3) */ +[attr$='ue'] { font-size:smaller; } + +/* содержащие отделенное пробелами значение в названии атрибута (CSS3) */ +[otherAttr~='foo'] { font-size:smaller; } + +/* можно выбрать атрибут как с точным, так и со стоящим после значения “-” (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Более того, все это можно использовать вместе - между разными частями +не должно быть пробелов, иначе селектор будет иметь совершенно иное значение */ +div.some-class[attr$='ue'] { } + +/* Вы можете выбрать элемент по его родителю */ + +/* прямой потомок другого элемента (выбранного с помощью селектора) */ +div.some-parent > .class-name {} + +/* потомок любого родителя в дереве элементов + следующая строка означает: "любой элемент класса "class-name", + являющийся потомком div-элемента класса "some-parent" + НЕЗАВИСИМО ОТ УРОВНЯ ВЛОЖЕННОСТИ" */ +div.some-parent .class-name {} + +/* важно: этот же селектор без пробелов имеет иное значение + можете догадаться, какое? */ +div.some-parent.class-name {} + +/* вы можете выбрать элемент по первому предшествующему + родственному элементу */ +.i-am-before + .this-element { } + +/* или любому предшествующему родственнику перед элементом */ +.i-am-any-before ~ .this-element {} + + +/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента + в зависимости от событий, произошедших с элементом */ + +/* например, когда курсор наведен на элемент */ +element:hover {} + +/* когда пользователь проходил по ссылке ранее */ +element:visited {} + +/* или еще не проходил по ней */ +element:link {} + +/* выбранное поле воода (input) */ +element:focus {} + + +/* #################### + ## АТРИБУТЫ + #################### */ + +selector { + + /* Единицы измерения */ + width: 50%; /* проценты */ + font-size: 2em; /* умножается на высоту шрифта (2em - в два раза больше) */ + width: 200px; /* пиксели */ + font-size: 20pt; /* пункты */ + width: 5cm; /* сантиметры */ + min-width: 50mm; /* милиметры */ + max-width: 5in; /* дюймы */ + height: 0.2vh; /* умножается на высоту окна браузера (CSS3) */ + width: 0.4vw; /* умножается на ширину окна браузера (CSS3) */ + min-height: 0.1vmin; /* наименьшее из vh и vw (CSS3) */ + max-width: 0.3vmax; /* наибольшее из vh и vw (CSS3) */ + + /* Цвета */ + background-color: #F6E; /* сокращенная запись шестнадцатеричного кода */ + background-color: #F262E2; /* стандартная запись шестнадцатеричного кода */ + background-color: tomato; /* название цвета */ + background-color: rgb(255, 255, 255); /* цветовая модель rgb */ + background-color: rgb(10%, 20%, 50%); /* цветовая модель rgb в процентах */ + background-color: rgba(255, 0, 0, 0.3); /* цветовая модель rgb (последний аргумент отвечает за прозрачность цвета) (CSS3) */ + background-color: transparent; /* прозрачный цвет */ + background-color: hsl(0, 100%, 50%); /* в формате hsl (CSS3) */ + background-color: hsla(0, 100%, 50%, 0.3); /* в формате hsl (последний аргумент отвечает за непрозрачность цвета) (CSS3) */ + + + /* Изображения */ + background-image: url(/path-to-image/image.jpg); /* кавычки внутри url() опциональны */ + + /* Шрифты */ + font-family: Arial; + font-family: "Courier New"; /* если в названии есть пробелы, заключите его в кавычки */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* если шрифт не найден, + будет использован следующий за ним в списке */ +} + +``` + +## Использование + +Сохраните готовый файл с расширением .css + +```xml + + + + + + + + + +
+
+ +``` + +## Приоритет + +Как вы заметили, внешний вид элемента может определяться несколькими селекторами, +а значение атрибута элемента может быть установлено больше одного раза. +В подобных случаях одно из значений оказывается приоритетнее остальных. + +Если взять следующую таблицу стилей: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +и следующую разметку: + +```xml +

+

+``` + +Приоритет стилей будет таким: +Помните: приоритет выставляется для **атрибута**, а не для всего блока стилей. + +* `E` имеет наивысший приоритет благодаря ключевому слову `!important`. + Используйте только в случае крайней необходимости. +* `F` идет следующим, так как является встроенным стилем. +* `A` следующий, как самый конкретизированный. + конкретизированный == большее количество определителей. + В этом примере 3 определителя: 1 тег `p` + + название класса `class1` + 1 атрибут `attr='value'` +* `C` следующий. Несмотря на одинаковое с `B` количество определителей, + `C` определен позже. +* Затем `B` +* И последний `D`. + +## Совместимость + +Несмотря на то, что большая часть функций CSS2 (а также CSS3) подеррживается всеми +браузерами и устройствами, не забывайте проверять совместимость CSS-правил +с современными браузерами. + +[QuirksMode CSS](http://www.quirksmode.org/css/) замечательно подходит для этого. + +To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. + +## Ресурсы для самостоятельного изучения + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -- cgit v1.2.3 From fff6f8c57ac57999c5efe70650fcd5592a2348f7 Mon Sep 17 00:00:00 2001 From: Erik Reinecke Date: Sun, 7 Jun 2015 12:06:05 -0500 Subject: Corrected link to Groovy documentatin --- groovy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 8fb1b346..629b6d18 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -405,7 +405,7 @@ assert sum(2,5) == 7 ## Further resources -[Groovy documentation](http://groovy.codehaus.org/Documentation) +[Groovy documentation](http://www.groovy-lang.org/documentation.html) [Groovy web console](http://groovyconsole.appspot.com/) -- cgit v1.2.3 From 6529748da383c52c6cd1487b86b051b15047d48e Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:30:16 -0400 Subject: Prompt addition of D --- .d.html.markdown.swp | Bin 0 -> 12288 bytes d.html.markdown | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 .d.html.markdown.swp create mode 100644 d.html.markdown diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp new file mode 100644 index 00000000..f310c87d Binary files /dev/null and b/.d.html.markdown.swp differ diff --git a/d.html.markdown b/d.html.markdown new file mode 100644 index 00000000..9f322423 --- /dev/null +++ b/d.html.markdown @@ -0,0 +1,61 @@ +--- +language: d +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: en +--- + +If you're like me and spend way to much time on the internet, odds are you've heard +about [D](http://dlang.org/). The D programming language is a modern, general-purpose, +multi-paradigm language with fantastic support for OOP, functional programming, metaprogramming, +and easy concurrency and parallelism, and runs the gamut from low-level features such as +memory management, inline assembly, and pointer arithmetic, to high-level constructs +such as higher-order functions and generic structures and functions via templates, all with +a pleasant syntax, and blazing fast performance! + +D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool +dudes. With all that out of the way, let's look at some examples! + +'''d +// You know what's coming... +import std.stdio; + +// args is optional +void main(string[] args) { + writeln("Hello, World!"); +} + +// Conditionals and loops work as expected. +import std.stdio; + +void main() { + for(int i = 0; i < 5; i++) { + writeln(i); + } + + auto n = 1; // use auto for type inferred variables + + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For and while are nice, but in D-land we prefer foreach + foreach(i; 1..int.max) { // The .. creates a continuous range + if(n % 2 == 0) + writeln(i); + } + + foreach_reverse(i; short.max) { + if(n % 2 == 1) + writeln(i); + else + writeln("No!"); + } +} + +''' -- cgit v1.2.3 From de5d895079abaa81d83734a332f993a7fced8282 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:30:44 -0400 Subject: Prompt addition of D --- .d.html.markdown.swp | Bin 12288 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .d.html.markdown.swp diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp deleted file mode 100644 index f310c87d..00000000 Binary files a/.d.html.markdown.swp and /dev/null differ -- cgit v1.2.3 From ab637d83f235a1766cbfc4c8a1d84cde4a670820 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:30:16 -0400 Subject: Prompt addition of D --- .d.html.markdown.swp | Bin 0 -> 12288 bytes d.html.markdown | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 .d.html.markdown.swp create mode 100644 d.html.markdown diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp new file mode 100644 index 00000000..f310c87d Binary files /dev/null and b/.d.html.markdown.swp differ diff --git a/d.html.markdown b/d.html.markdown new file mode 100644 index 00000000..9f322423 --- /dev/null +++ b/d.html.markdown @@ -0,0 +1,61 @@ +--- +language: d +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: en +--- + +If you're like me and spend way to much time on the internet, odds are you've heard +about [D](http://dlang.org/). The D programming language is a modern, general-purpose, +multi-paradigm language with fantastic support for OOP, functional programming, metaprogramming, +and easy concurrency and parallelism, and runs the gamut from low-level features such as +memory management, inline assembly, and pointer arithmetic, to high-level constructs +such as higher-order functions and generic structures and functions via templates, all with +a pleasant syntax, and blazing fast performance! + +D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool +dudes. With all that out of the way, let's look at some examples! + +'''d +// You know what's coming... +import std.stdio; + +// args is optional +void main(string[] args) { + writeln("Hello, World!"); +} + +// Conditionals and loops work as expected. +import std.stdio; + +void main() { + for(int i = 0; i < 5; i++) { + writeln(i); + } + + auto n = 1; // use auto for type inferred variables + + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For and while are nice, but in D-land we prefer foreach + foreach(i; 1..int.max) { // The .. creates a continuous range + if(n % 2 == 0) + writeln(i); + } + + foreach_reverse(i; short.max) { + if(n % 2 == 1) + writeln(i); + else + writeln("No!"); + } +} + +''' -- cgit v1.2.3 From 0a9b7ebb07c00778ec5e03ffb76a706e8f805dda Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:30:44 -0400 Subject: Prompt addition of D --- .d.html.markdown.swp | Bin 12288 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .d.html.markdown.swp diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp deleted file mode 100644 index f310c87d..00000000 Binary files a/.d.html.markdown.swp and /dev/null differ -- cgit v1.2.3 From 8bdf48dc8c2d41f945db734ac1837b0e434e7a95 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:39:01 -0400 Subject: fixed D syntax` --- d.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 9f322423..a6245a99 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -1,5 +1,5 @@ --- -language: d +language: D filename: learnd.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] @@ -17,7 +17,7 @@ a pleasant syntax, and blazing fast performance! D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool dudes. With all that out of the way, let's look at some examples! -'''d +```d // You know what's coming... import std.stdio; @@ -58,4 +58,4 @@ void main() { } } -''' +``` -- cgit v1.2.3 From c5ac70f706802e9642c7ddc81caf88482a0eb2c6 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:50:05 -0400 Subject: D stuff --- d.html.markdown | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index a6245a99..be9f8fb0 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -50,12 +50,47 @@ void main() { writeln(i); } - foreach_reverse(i; short.max) { + foreach_reverse(i; 1..short.max) { if(n % 2 == 1) writeln(i); else writeln("No!"); } } +``` + +We can define new types and functions with `struct`, `class`, `union`, and `enum`. Structs and unions +are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, +we can use templates to parameterize all of these on both types and values! + +``` +// Here, T is a type parameter. Think from C++/C#/Java +struct(T) LinkedList { + T data = null; + LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think +} + +class BinTree(T) { + T data = null; + + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Use alias to create abbreviations for types + +alias IntList = LinkedList!int; + +alias NumTree = BinTree!double; ``` -- cgit v1.2.3 From f8da3b96ff93723f5e61aff24da7aa9e1c65f4a8 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Sun, 7 Jun 2015 22:52:34 -0400 Subject: fucking syntax highlighting --- d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index be9f8fb0..f3836c2c 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -63,7 +63,7 @@ We can define new types and functions with `struct`, `class`, `union`, and `enum are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, we can use templates to parameterize all of these on both types and values! -``` +```d // Here, T is a type parameter. Think from C++/C#/Java struct(T) LinkedList { T data = null; -- cgit v1.2.3 From d6bf5fe3def6b4b032c4eccebfd7be8e82b72488 Mon Sep 17 00:00:00 2001 From: Sam Kvale Date: Tue, 9 Jun 2015 10:42:26 -0500 Subject: Update visualbasic.html.markdown Copy - Paste error --- visualbasic.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index fbfa500d..123ec56c 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -159,7 +159,7 @@ Module Module1 Console.Write(a.ToString() + " - " + b.ToString()) Console.WriteLine(" = " + e.ToString.PadLeft(3)) Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) Console.ReadLine() End Sub -- cgit v1.2.3 From b4a6669d44e57c6b5c7338fea42d0e55182258f8 Mon Sep 17 00:00:00 2001 From: Sam Kvale Date: Tue, 9 Jun 2015 10:43:26 -0500 Subject: Update visualbasic.html.markdown --- visualbasic.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index 123ec56c..00d61843 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -189,7 +189,7 @@ Module Module1 Console.Write(a.ToString() + " - " + b.ToString()) Console.WriteLine(" = " + e.ToString.PadLeft(3)) Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) Console.ReadLine() 'Ask the question, does the user wish to continue? Unfortunately it 'is case sensitive. -- cgit v1.2.3 From 75ecb5aa8133325f14d97d00675c3b039da06530 Mon Sep 17 00:00:00 2001 From: Mark Canlas Date: Wed, 10 Jun 2015 00:00:12 +0200 Subject: tamed indentation/whitespace --- perl.html.markdown | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index aac95939..ab8c7a32 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -47,9 +47,9 @@ my %fruit_color = ("apple", "red", "banana", "yellow"); # You can use whitespace and the "=>" operator to lay them out more nicely: my %fruit_color = ( - apple => "red", - banana => "yellow", - ); + apple => "red", + banana => "yellow", +); # Scalars, arrays and hashes are documented more fully in perldata. # (perldoc perldata). @@ -60,17 +60,17 @@ my %fruit_color = ( # Perl has most of the usual conditional and looping constructs. -if ( $var ) { - ... -} elsif ( $var eq 'bar' ) { - ... +if ($var) { + ... +} elsif ($var eq 'bar') { + ... } else { - ... + ... } -unless ( condition ) { - ... - } +unless (condition) { + ... +} # This is provided as a more readable version of "if (!condition)" # the Perlish post-condition way @@ -78,19 +78,19 @@ print "Yow!" if $zippy; print "We have no bananas" unless $bananas; # while - while ( condition ) { - ... - } +while (condition) { + ... +} # for and foreach for ($i = 0; $i <= $max; $i++) { - ... - } + ... +} foreach (@array) { - print "This element is $_\n"; - } + print "This element is $_\n"; +} #### Regular expressions @@ -129,9 +129,11 @@ my @lines = <$in>; # Writing subroutines is easy: sub logger { - my $logmessage = shift; - open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; - print $logfile $logmessage; + my $logmessage = shift; + + open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; + + print $logfile $logmessage; } # Now we can use the subroutine just as any other built-in function: -- cgit v1.2.3 From 66379e80cdc805612327e71a6cfa79d4699a8186 Mon Sep 17 00:00:00 2001 From: Mark Canlas Date: Wed, 10 Jun 2015 00:05:36 +0200 Subject: revamped for loops --- perl.html.markdown | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index ab8c7a32..3c0699ad 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -83,13 +83,23 @@ while (condition) { } -# for and foreach -for ($i = 0; $i <= $max; $i++) { - ... +# for loops and iteration +for (my $i = 0; $i < $max; $i++) { + print "index is $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "Current element is " . $elements[$i]; } -foreach (@array) { - print "This element is $_\n"; +for my $element (@elements) { + print $element; +} + +# implicitly + +for (@elements) { + print; } -- cgit v1.2.3 From 839e2e4b272816a811f25eb46baca743c2b542c1 Mon Sep 17 00:00:00 2001 From: Andrey Samsonov Date: Wed, 10 Jun 2015 12:08:45 +0400 Subject: Add Andre Polykanine to bash/ru transtators list --- ru-ru/bash-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown index e6741b1b..21377b6c 100644 --- a/ru-ru/bash-ru.html.markdown +++ b/ru-ru/bash-ru.html.markdown @@ -13,6 +13,7 @@ contributors: - ["Etan Reisner", "https://github.com/deryni"] translators: - ["Andrey Samsonov", "https://github.com/kryzhovnik"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: LearnBash-ru.sh lang: ru-ru --- -- cgit v1.2.3 From 8f24f723e0b7cccde9dfcef2e2aa87d7eeb3822b Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 11:54:16 -0400 Subject: more D --- .d.html.markdown.swp | Bin 0 -> 12288 bytes d.html.markdown | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 .d.html.markdown.swp diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp new file mode 100644 index 00000000..5cd11360 Binary files /dev/null and b/.d.html.markdown.swp differ diff --git a/d.html.markdown b/d.html.markdown index f3836c2c..10a2be29 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -19,6 +19,8 @@ dudes. With all that out of the way, let's look at some examples! ```d // You know what's coming... +module hello; + import std.stdio; // args is optional @@ -65,7 +67,7 @@ we can use templates to parameterize all of these on both types and values! ```d // Here, T is a type parameter. Think from C++/C#/Java -struct(T) LinkedList { +struct LinkedList(T) { T data = null; LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think } @@ -90,7 +92,33 @@ enum Day { // Use alias to create abbreviations for types alias IntList = LinkedList!int; - alias NumTree = BinTree!double; +// We can create function templates as well! + +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// Use the ref keyword to pass by referece +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = a; +} + +// With templates, we can also parameterize on values, not just types +class Matrix(T = int, uint m, uint n) { + T[m] rows; + T[n] columns; +} ``` + +Speaking of classes, let's talk about properties for a second. A property +is roughly a function that may act like an lvalue, so we can +have the syntax of POD structures (`structure.x = 7`) with the semantics of +getter and setter methods (`object.setX(7)`)! -- cgit v1.2.3 From 4b35798f832878f65308f1d8b1764580d8039bc4 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 11:54:25 -0400 Subject: more D --- .d.html.markdown.swp | Bin 12288 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .d.html.markdown.swp diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp deleted file mode 100644 index 5cd11360..00000000 Binary files a/.d.html.markdown.swp and /dev/null differ -- cgit v1.2.3 From e5fa463b3477813bb11d590beaf7ed8b49e9c733 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 12:18:45 -0400 Subject: So much D --- d.html.markdown | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 10a2be29..f547cc56 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -53,10 +53,11 @@ void main() { } foreach_reverse(i; 1..short.max) { - if(n % 2 == 1) + if(n % 2 == 1) { writeln(i); - else + } else { writeln("No!"); + } } } ``` @@ -122,3 +123,73 @@ Speaking of classes, let's talk about properties for a second. A property is roughly a function that may act like an lvalue, so we can have the syntax of POD structures (`structure.x = 7`) with the semantics of getter and setter methods (`object.setX(7)`)! + +```d +// Consider a class parameterized on a types T, U + +class MyClass(T, U) { + T _data; + U _other; + +} + +// We define "setter" methods as follows + +class MyClass(T, U) { + T _data; + U _other; + + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// And "getter" methods like so +class MyClass(T, U) { + T _data; + U _other; + + // Constructors are always named `this` + this(T t, U u) { + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} +// And we use them in this manner + +void main() { + auto mc = MyClass!(int, string); + + mc.data = 7; + mc.other = "seven"; + + writeln(mc.data); + writeln(mc.other); +} +``` + +With properties, we can add any amount of validation to +our getter and setter methods, and keep the clean syntax of +accessing members directly! -- cgit v1.2.3 From cd207d1590897b9d410eb7e91992a6b11d36cd50 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 12:21:11 -0400 Subject: So much D --- d.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index f547cc56..d816a312 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -6,7 +6,7 @@ contributors: lang: en --- -If you're like me and spend way to much time on the internet, odds are you've heard +If you're like me and spend way too much time on the internet, odds are you've heard about [D](http://dlang.org/). The D programming language is a modern, general-purpose, multi-paradigm language with fantastic support for OOP, functional programming, metaprogramming, and easy concurrency and parallelism, and runs the gamut from low-level features such as @@ -113,10 +113,13 @@ void swap(T)(ref T a, ref T b) { } // With templates, we can also parameterize on values, not just types -class Matrix(T = int, uint m, uint n) { +class Matrix(uint m, uint n, T = int) { T[m] rows; T[n] columns; } + +auto mat = new Matrix!(3, 3); + ``` Speaking of classes, let's talk about properties for a second. A property -- cgit v1.2.3 From cc5729245ff988ebd92fddb6bcb2678be0d64cec Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 12:42:10 -0400 Subject: I looooove the D --- d.html.markdown | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index d816a312..0ffe3508 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -109,7 +109,7 @@ void swap(T)(ref T a, ref T b) { auto temp = a; a = b; - b = a; + b = temp; } // With templates, we can also parameterize on values, not just types @@ -118,7 +118,7 @@ class Matrix(uint m, uint n, T = int) { T[n] columns; } -auto mat = new Matrix!(3, 3); +auto mat = new Matrix!(3, 3); // We've defaulted T to int ``` @@ -196,3 +196,47 @@ void main() { With properties, we can add any amount of validation to our getter and setter methods, and keep the clean syntax of accessing members directly! + +Other object-oriented goodness for all your enterprise needs +include `interface`s, `abstract class`es, +and `override`ing methods. + +We've seen D's OOP facilities, but let's switch gears. D offers +functional programming with first-class functions, `pure` +functions, and immutable data. In addition, all of your favorite +functional algorithms (map, filter, reduce and friends) can be +found in the wonderful `std.algorithm` module! + +```d +import std.algorithm; + +void main() { + // We want to print the sum of a list of squares of even ints + // from 1 to 100. Easy! + + // Just pass lambda expressions as template parameters! + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Notice how we got to build a nice Haskellian pipeline to compute num? +That's thanks to a D innovation know as Uniform Function Call Syntax. +With UFCS, we can choose whether to write a function call as a method +or free function all. In general, if we have a function + +```d +f(A, B, C, ...) +``` + +Then we may write + +```d +A.f(B, C, ...) +``` + +and the two are equivalent! No more fiddling to remember if it's +str.length or length(str)! -- cgit v1.2.3 From 455875cd919d829874156ea97887e514e2b06493 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 14:07:14 -0400 Subject: improvements to D --- d.html.markdown | 38 ++++++++++++++------------------------ 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 0ffe3508..4b993a2d 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -47,12 +47,13 @@ void main() { } while(n > 0); // For and while are nice, but in D-land we prefer foreach - foreach(i; 1..int.max) { // The .. creates a continuous range + // The .. creates a continuous range, excluding the end + foreach(i; 1..1000000) { if(n % 2 == 0) writeln(i); } - foreach_reverse(i; 1..short.max) { + foreach_reverse(i; 1..int.max) { if(n % 2 == 1) { writeln(i); } else { @@ -62,7 +63,7 @@ void main() { } ``` -We can define new types and functions with `struct`, `class`, `union`, and `enum`. Structs and unions +We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, we can use templates to parameterize all of these on both types and values! @@ -75,7 +76,8 @@ struct LinkedList(T) { class BinTree(T) { T data = null; - + + // If there is only one template parameter, we can omit parens BinTree!T left; BinTree!T right; } @@ -104,7 +106,9 @@ T max(T)(T a, T b) { return a; } -// Use the ref keyword to pass by referece +// Use the ref keyword to ensure pass by referece. +// That is, even if a and b are value types, they +// will always be passed by reference to swap void swap(T)(ref T a, ref T b) { auto temp = a; @@ -136,22 +140,7 @@ class MyClass(T, U) { } -// We define "setter" methods as follows - -class MyClass(T, U) { - T _data; - U _other; - - @property void data(T t) { - _data = t; - } - - @property void other(U u) { - _other = u; - } -} - -// And "getter" methods like so +// And "getter" and "setter" methods like so class MyClass(T, U) { T _data; U _other; @@ -197,7 +186,7 @@ With properties, we can add any amount of validation to our getter and setter methods, and keep the clean syntax of accessing members directly! -Other object-oriented goodness for all your enterprise needs +Other object-oriented goodies at our disposal include `interface`s, `abstract class`es, and `override`ing methods. @@ -208,12 +197,13 @@ functional algorithms (map, filter, reduce and friends) can be found in the wonderful `std.algorithm` module! ```d -import std.algorithm; +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range void main() { // We want to print the sum of a list of squares of even ints // from 1 to 100. Easy! - + // Just pass lambda expressions as template parameters! auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) -- cgit v1.2.3 From f30876d3f659d2c28ebe97bd4416d4dd514e5d22 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 14:13:38 -0400 Subject: So much D in my life --- d.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/d.html.markdown b/d.html.markdown index 4b993a2d..36153500 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -205,6 +205,7 @@ void main() { // from 1 to 100. Easy! // Just pass lambda expressions as template parameters! + // You can pass any old function you like, but lambdas are convenient here. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) .reduce!((a, b) => a + b); -- cgit v1.2.3 From 2db99047ef98ec636b78e29b72f46dc347b37d38 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Wed, 10 Jun 2015 14:31:02 -0400 Subject: Update d.html.markdown --- d.html.markdown | 7 ------- 1 file changed, 7 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 36153500..3a5a6c9b 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -133,13 +133,6 @@ getter and setter methods (`object.setX(7)`)! ```d // Consider a class parameterized on a types T, U - -class MyClass(T, U) { - T _data; - U _other; - -} - // And "getter" and "setter" methods like so class MyClass(T, U) { T _data; -- cgit v1.2.3 From e191446b333856afff0456349edb71da9634f6aa Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 11 Jun 2015 17:35:20 -0600 Subject: Add language marking for R --- fr-fr/r-fr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/r-fr.html.markdown b/fr-fr/r-fr.html.markdown index 3f225a0f..7d30a48d 100644 --- a/fr-fr/r-fr.html.markdown +++ b/fr-fr/r-fr.html.markdown @@ -6,6 +6,7 @@ contributors: translators: - ["Anne-Catherine Dehier", "https://github.com/spellart"] filename: learnr-fr.r +lang: fr-fr --- R est un langage de programmation statistique. Il dispose de nombreuses -- cgit v1.2.3 From 337710e13d726b91fd6cdde9e58d8c0db24c73f0 Mon Sep 17 00:00:00 2001 From: Jingwen Date: Sat, 13 Jun 2015 17:27:05 +0800 Subject: Fixed typo: changing an immutable ref will not compile --- rust.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index 17f7dc90..49303b0d 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -281,7 +281,7 @@ fn main() { println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); // var = 5; // this would not compile because `var` is borrowed - // *ref_var = 6; // this would too, because `ref_var` is an immutable reference + // *ref_var = 6; // this would not too, because `ref_var` is an immutable reference // Mutable reference // While a value is mutably borrowed, it cannot be accessed at all. -- cgit v1.2.3 From 9c6aec3ceb41a207e77a36b3b22b8bcab99fa86d Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Sun, 14 Jun 2015 13:24:24 +0100 Subject: [erlang/fr] Integrate feedback on PR --- fr-fr/erlang-fr.html.markdown | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/fr-fr/erlang-fr.html.markdown b/fr-fr/erlang-fr.html.markdown index 564e176f..55453c56 100644 --- a/fr-fr/erlang-fr.html.markdown +++ b/fr-fr/erlang-fr.html.markdown @@ -15,19 +15,21 @@ lang: fr-fr %%% Trois signes pour cent sont utilisés pour commenter les modules. -% Trois types de ponctuation sont utilisés en Erlang. +% Trois symboles de ponctuation sont utilisés en Erlang. % Les virgules (`,`) servent à séparer les paramètres dans les appels de % fonctions, les contructeurs, et les motifs. -% Les points (`.`) (suivis par des caractères blancs) servent à séparer -% les fonctions et les expressions dans l'interpréteur. +% Les points (`.`) (suivis par des blancs) servent à séparer les fonctions et +% les expressions dans l'interpréteur. % Les points-virgules (`;`) servent à séparer les clauses. Ces dernières % apparaissent dans différent cas de figure : définitions de fonctions et -% expressions `case`, `if`, `try..catch`, et `receive`. +% expressions `case`, `if`, `try..catch`, `receive`. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% 1. Variables et filtrage par motif. +%% 1. Variables et filtrage par motif %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +(L'équivalent anglais de *filtrage par motif* est *pattern patching*.) + Nb = 42. % Chaque nom de variable doit commencer par une lettre majuscule. % Les variables Erlang ne peuvent être affectées qu'une seule fois ; si vous @@ -101,7 +103,7 @@ Nom = "Bonjour". %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Les modules constituent l'unité de base d'un programme Erlang. Toutes les -% fonctions que l'on écrit sont sauvées dans des modules. Les modules sont +% fonctions que l'on écrit sont enregistrées dans des modules. Les modules sont % enregistrés dans des fichiers avec une extension `.erl`. % Les modules doivent être compilés afin d'éxecuter le programme. % Un module compilé a une extension `.beam`. @@ -138,27 +140,27 @@ somme(L) -> somme(L, 0). somme([], N) -> N; somme([T|Q], N) -> somme(Q, T+N). -% Les funs sont des fonctions "anonymes" ; elles sont appelées ainsi parce -% qu'elles n'ont pas de noms. Cependant, elles peuvent être affectées à des +% Les `fun`s sont des fonctions "anonymes" ; elles sont appelées ainsi parce +% qu'elles n'ont pas de nom. Cependant, elles peuvent être affectées à des % variables. Doubler = fun(X) -> 2 * X end. % `Doubler` pointe vers une fonction anonyme % dont le handle est : #Fun Doubler(2). % 4 -% Les fonctions peuvent prendre des funs comme paramètres et peuvent renvoyer -% des funs. +% Les fonctions peuvent prendre des `fun`s comme paramètres et peuvent renvoyer +% des `fun`s. Mult = fun(Fois) -> ( fun(X) -> X * Fois end ) end. Tripler = Mult(3). Tripler(5). % 15 % Les listes en compréhension sont des expressions qui créent des listes sans -% requérir ni funs, ni maps, ni filters. +% requérir ni `fun`s, ni maps, ni filters. % La notation `[F(X) || X <- L]` signifie "la liste des `F(X)` où `X` est % extrait de la liste `L`." L = [1,2,3,4,5]. [2 * X || X <- L]. % [2,4,6,8,10] -% Une liste en compréhension peut avoir des générateurs, ainsi que des gardes, -% qui sélectionnent un sous-ensemble des valeurs générées. +% Une liste en compréhension peut être constituée de générateurs, ainsi que de +% gardes, qui sélectionnent un sous-ensemble des valeurs générées. NombresPairs = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] % La garde est un élément syntaxique qui rend le filtrage par motif encore @@ -186,7 +188,7 @@ est_chien(A) -> false. est_animal(A) when is_atom(A), (A =:= chien) or (A =:= chat) -> true; est_animal(A) -> false. -% Attention : les expressions Erlang valides ne peuvent pas toutes être +% Attention : toutes les expressions Erlang valides ne peuvent pas être % utilisées comme expressions gardes ; en particulier, nos fonctions % `est_chat` et `est_chien` ne sont pas autorisées au sein de la séquence de % gardes dans la définition de `est_animal`. Pour plus de détails sur les @@ -317,7 +319,7 @@ self(). % <0.41.0> ``` -## Références +## Ressources (en anglais) * ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) * ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) -- cgit v1.2.3 From 302723b2c5c964d805cfafefdc40924df31dd9d0 Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Tue, 16 Jun 2015 22:42:55 +0800 Subject: update the groovy web site link in some docs --- groovy.html.markdown | 8 ++++---- pt-br/groovy-pt.html.markdown | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 629b6d18..519f36ce 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -6,7 +6,7 @@ contributors: filename: learngroovy.groovy --- -Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org) +Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) ```groovy @@ -231,7 +231,7 @@ for ( e in map ) { Operators Operator Overloading for a list of the common operators that Groovy supports: - http://groovy.codehaus.org/Operator+Overloading + http://www.groovy-lang.org/operators.html#Operator-Overloading Helpful groovy operators */ @@ -249,7 +249,7 @@ def username = user?.username A Groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. - More info at: http://groovy.codehaus.org/Closures+-+Formal+Definition + More info at: http://www.groovy-lang.org/closures.html */ //Example: def clos = { println "Hello World!" } @@ -409,7 +409,7 @@ assert sum(2,5) == 7 [Groovy web console](http://groovyconsole.appspot.com/) -Join a [Groovy user group](http://groovy.codehaus.org/User+Groups) +Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) ## Books diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown index 885d5b27..2ec7d967 100644 --- a/pt-br/groovy-pt.html.markdown +++ b/pt-br/groovy-pt.html.markdown @@ -9,7 +9,7 @@ translators: lang: pt-br --- -Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://groovy.codehaus.org) +Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://www.groovy-lang.org/) ```groovy @@ -236,7 +236,7 @@ for ( e in map ) { Sobrecarregamento de Operadores para uma lsita dos operadores comuns que Grooby suporta: - http://groovy.codehaus.org/Operator+Overloading + http://www.groovy-lang.org/operators.html#Operator-Overloading Operadores Groovy úteis */ @@ -255,7 +255,7 @@ def nomeUsuario = usuario?.nomeUsuario Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método. É um pedação de código que é definido e executado em um momento posterior. - Mais informação em: http://groovy.codehaus.org/Closures+-+Formal+Definition + Mais informação em: http://www.groovy-lang.org/closures.html */ //Exemplo: def clos = { println "Hello World!" } @@ -413,11 +413,11 @@ assert soma(2,5) == 7 ## Referências -[Groovy documentation](http://groovy.codehaus.org/Documentation) +[Groovy documentation](http://www.groovy-lang.org/documentation.html) [Groovy web console](http://groovyconsole.appspot.com/) -Junte-se a um [grupo de usuários Groovy](http://groovy.codehaus.org/User+Groups) +Junte-se a um [grupo de usuários Groovy](http://www.groovy-lang.org/usergroups.html) ## Livro -- cgit v1.2.3 From 5f8c78bc9983ea23b624a3b82aed17c1cc4d4ebe Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Tue, 16 Jun 2015 18:14:36 +0100 Subject: [erlang/en] Fix #1142 --- erlang.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/erlang.html.markdown b/erlang.html.markdown index a3b571d1..8b67a76a 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -164,6 +164,13 @@ is_cat(A) -> false. is_dog(A) when is_atom(A), A =:= dog -> true; is_dog(A) -> false. +% We won't dwell on the `=:=` operator here; just be aware that it is used to +% check whether two Erlang expressions have the same value *and* the same type. +% Contrast this behaviour to that of the `==` operator: +1 + 2 =:= 3. % true +1 + 2 =:= 3.0. % false +1 + 2 == 3.0. % true + % A guard sequence is either a single guard or a series of guards, separated % by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at % least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`. -- cgit v1.2.3 From 7070304d60715405bb5f2432f4c84868a6418376 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Tue, 16 Jun 2015 12:54:54 -0600 Subject: Fix explanation of "and" and "or" in ruby. --- ruby.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 792c9c95..66a0774d 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -79,10 +79,14 @@ true && false #=> false true || false #=> true !true #=> false -# Alternate spellings of logical operators -true and false #=> false -true or false #=> true -not true #=> false +# There are alternate versions of the logical operators with much lower +# precedence. These are meant to be used as flow-control constructs to chain +# statements together until one of them returns true or false. + +# `do_something_else` only called if `do_something` succeeds. +do_something() and do_something_else() +# `log_error` only called if `do_something` fails. +do_something() or log_error() # Strings are objects -- cgit v1.2.3 From 8bb2c3db63b87582764dca2641c8d84b39ed017f Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Tue, 16 Jun 2015 17:10:57 -0400 Subject: UFCS corrections; shorter intro --- .d.html.markdown.swp | Bin 0 -> 20480 bytes d.html.markdown | 53 +++++++++++++++++++++------------------------------ 2 files changed, 22 insertions(+), 31 deletions(-) create mode 100644 .d.html.markdown.swp diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp new file mode 100644 index 00000000..017dbf4e Binary files /dev/null and b/.d.html.markdown.swp differ diff --git a/d.html.markdown b/d.html.markdown index 36153500..f0e9ce02 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -6,17 +6,6 @@ contributors: lang: en --- -If you're like me and spend way too much time on the internet, odds are you've heard -about [D](http://dlang.org/). The D programming language is a modern, general-purpose, -multi-paradigm language with fantastic support for OOP, functional programming, metaprogramming, -and easy concurrency and parallelism, and runs the gamut from low-level features such as -memory management, inline assembly, and pointer arithmetic, to high-level constructs -such as higher-order functions and generic structures and functions via templates, all with -a pleasant syntax, and blazing fast performance! - -D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool -dudes. With all that out of the way, let's look at some examples! - ```d // You know what's coming... module hello; @@ -28,16 +17,27 @@ void main(string[] args) { writeln("Hello, World!"); } -// Conditionals and loops work as expected. +If you're like me and spend way too much time on the internet, odds are you've heard +about [D](http://dlang.org/). The D programming language is a modern, general-purpose, +multi-paradigm language with support for everything from low-level features to +expressive high-level abstractions. + +D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool +dudes. With all that out of the way, let's look at some examples! + + import std.stdio; void main() { - for(int i = 0; i < 5; i++) { + + // Conditionals and loops work as expected. + for(int i = 0; i < 10000; i++) { writeln(i); } auto n = 1; // use auto for type inferred variables - + + // Numeric literals can use _ as a digit seperator for clarity while(n < 10_000) { n += n; } @@ -48,7 +48,7 @@ void main() { // For and while are nice, but in D-land we prefer foreach // The .. creates a continuous range, excluding the end - foreach(i; 1..1000000) { + foreach(i; 1..1_000_000) { if(n % 2 == 0) writeln(i); } @@ -122,7 +122,7 @@ class Matrix(uint m, uint n, T = int) { T[n] columns; } -auto mat = new Matrix!(3, 3); // We've defaulted T to int +auto mat = new Matrix!(3, 3); // We've defaulted type T to int ``` @@ -176,19 +176,20 @@ void main() { mc.data = 7; mc.other = "seven"; - + writeln(mc.data); writeln(mc.other); } ``` -With properties, we can add any amount of validation to +With properties, we can add any amount of logic to our getter and setter methods, and keep the clean syntax of accessing members directly! Other object-oriented goodies at our disposal include `interface`s, `abstract class`es, -and `override`ing methods. +and `override`ing methods. D does inheritance just like Java: +Extend one class, implement as many interfaces as you please. We've seen D's OOP facilities, but let's switch gears. D offers functional programming with first-class functions, `pure` @@ -217,17 +218,7 @@ void main() { Notice how we got to build a nice Haskellian pipeline to compute num? That's thanks to a D innovation know as Uniform Function Call Syntax. With UFCS, we can choose whether to write a function call as a method -or free function all. In general, if we have a function +or free function call! Walter wrote a nice article on this [http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394](here.) In short, you can call functions whose first parameter +is of some type A on any expression of type A as a methods. -```d -f(A, B, C, ...) -``` - -Then we may write - -```d -A.f(B, C, ...) -``` -and the two are equivalent! No more fiddling to remember if it's -str.length or length(str)! -- cgit v1.2.3 From c04bb1a39c0a6feacbff5aaf950a33f8d29f6d79 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Tue, 16 Jun 2015 17:15:14 -0400 Subject: formatting --- .d.html.markdown.swp | Bin 20480 -> 0 bytes d.html.markdown | 10 +++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) delete mode 100644 .d.html.markdown.swp diff --git a/.d.html.markdown.swp b/.d.html.markdown.swp deleted file mode 100644 index 017dbf4e..00000000 Binary files a/.d.html.markdown.swp and /dev/null differ diff --git a/d.html.markdown b/d.html.markdown index ee06a425..39c6a4d3 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -16,6 +16,7 @@ import std.stdio; void main(string[] args) { writeln("Hello, World!"); } +``` If you're like me and spend way too much time on the internet, odds are you've heard about [D](http://dlang.org/). The D programming language is a modern, general-purpose, @@ -133,6 +134,13 @@ getter and setter methods (`object.setX(7)`)! ```d // Consider a class parameterized on a types T, U + +class MyClass(T, U) { + T _data; + U _other; + +} + // And "getter" and "setter" methods like so class MyClass(T, U) { T _data; @@ -212,6 +220,6 @@ Notice how we got to build a nice Haskellian pipeline to compute num? That's thanks to a D innovation know as Uniform Function Call Syntax. With UFCS, we can choose whether to write a function call as a method or free function call! Walter wrote a nice article on this [http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394](here.) In short, you can call functions whose first parameter -is of some type A on any expression of type A as a methods. +is of some type A on any expression of type A as a method. -- cgit v1.2.3 From 4df0b5fc697ededd3d1e733214bd94033f4cba53 Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Tue, 16 Jun 2015 17:16:24 -0400 Subject: formatting --- d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index 39c6a4d3..4ccf65d3 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -26,7 +26,7 @@ expressive high-level abstractions. D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool dudes. With all that out of the way, let's look at some examples! - +```d import std.stdio; void main() { -- cgit v1.2.3 From 5f0d8c28cc8c8f33db45c82a79699a9c1ff6fbbc Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Tue, 16 Jun 2015 17:19:30 -0400 Subject: formatting --- d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index 4ccf65d3..7356174d 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -219,7 +219,7 @@ void main() { Notice how we got to build a nice Haskellian pipeline to compute num? That's thanks to a D innovation know as Uniform Function Call Syntax. With UFCS, we can choose whether to write a function call as a method -or free function call! Walter wrote a nice article on this [http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394](here.) In short, you can call functions whose first parameter +or free function call! Walter wrote a nice article on this [here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) In short, you can call functions whose first parameter is of some type A on any expression of type A as a method. -- cgit v1.2.3 From a54c5b580b9a2900f2f6eb1b2b5f07d0c1dd2e9d Mon Sep 17 00:00:00 2001 From: NickPapanastasiou Date: Tue, 16 Jun 2015 17:46:58 -0400 Subject: parallel stuff --- d.html.markdown | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index 7356174d..88c7e37f 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -219,7 +219,29 @@ void main() { Notice how we got to build a nice Haskellian pipeline to compute num? That's thanks to a D innovation know as Uniform Function Call Syntax. With UFCS, we can choose whether to write a function call as a method -or free function call! Walter wrote a nice article on this [here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) In short, you can call functions whose first parameter +or free function call! Walter wrote a nice article on this +[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +In short, you can call functions whose first parameter is of some type A on any expression of type A as a method. +I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! +```d +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // We want take the square root every number in our array, + // and take advantage of as many cores as we have available. + auto arr = new double[1_000_000]; + + // Use an index, and an array element by referece, + // and just call parallel on the array! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` -- cgit v1.2.3 From 68b05bcc518064dab26c5098ea369a71bb9b5d8e Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 17 Jun 2015 23:25:16 +0200 Subject: Fix adambard/learnxinyminutes-site#12 --- it-it/c++-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index 4f5ac8a2..e7e1d89e 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -1,6 +1,6 @@ --- language: c++ -filename: learncpp.cpp +filename: learncpp-it.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] -- cgit v1.2.3 From ad344ac7c68ecbfa55f5d7d50bc8b3e7c162f14b Mon Sep 17 00:00:00 2001 From: Esption Date: Wed, 17 Jun 2015 18:35:32 -0500 Subject: Rust: Change '&*' to '&' --- rust.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 17f7dc90..fbfa4cdf 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -84,7 +84,7 @@ fn main() { // This is basically an immutable pointer to a string – it doesn’t // actually contain the contents of a string, just a pointer to // something that does (in this case, `s`) - let s_slice: &str = &*s; + let s_slice: &str = &s; println!("{} {}", s, s_slice); // hello world hello world @@ -99,7 +99,7 @@ fn main() { // A slice – an immutable view into a vector or array // This is much like a string slice, but for vectors - let slice: &[i32] = &*vector; + let slice: &[i32] = &vector; // Use `{:?}` to print something debug-style println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] -- cgit v1.2.3 From 6b109e1460e11cb1030f4832ee67e89283cc6808 Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Thu, 18 Jun 2015 22:20:30 +0800 Subject: cp original file to zh-cn/ --- zh-cn/groovy-cn.html.markdown | 427 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 427 insertions(+) create mode 100644 zh-cn/groovy-cn.html.markdown diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown new file mode 100644 index 00000000..519f36ce --- /dev/null +++ b/zh-cn/groovy-cn.html.markdown @@ -0,0 +1,427 @@ +--- +language: Groovy +filename: learngroovy.groovy +contributors: + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] +filename: learngroovy.groovy +--- + +Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) + +```groovy + +/* + Set yourself up: + + 1) Install GVM - http://gvmtool.net/ + 2) Install Groovy: gvm install groovy + 3) Start the groovy console by typing: groovyConsole + +*/ + +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ + +// Hello World +println "Hello world!" + +/* + Variables: + + You can assign values to variables for later use +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + Collections and maps +*/ + +//Creating an empty list +def technologies = [] + +/*** Adding a elements to the list ***/ + +// As with Java +technologies.add("Grails") + +// Left shift adds, and returns the list +technologies << "Groovy" + +// Add multiple elements +technologies.addAll(["Gradle","Griffon"]) + +/*** Removing elements from the list ***/ + +// As with Java +technologies.remove("Griffon") + +// Subtraction works also +technologies = technologies - 'Grails' + +/*** Iterating Lists ***/ + +// Iterate over elements of a list +technologies.each { println "Technology: $it"} +technologies.eachWithIndex { it, i -> println "$i: $it"} + +/*** Checking List contents ***/ + +//Evaluate if a list contains element(s) (boolean) +contained = technologies.contains( 'Groovy' ) + +// Or +contained = 'Groovy' in technologies + +// Check for multiple contents +technologies.containsAll(['Groovy','Grails']) + +/*** Sorting Lists ***/ + +// Sort a list (mutates original list) +technologies.sort() + +// To sort without mutating original, you can do: +sortedTechnologies = technologies.sort( false ) + +/*** Manipulating Lists ***/ + +//Replace all elements in the list +Collections.replaceAll(technologies, 'Gradle', 'gradle') + +//Shuffle a list +Collections.shuffle(technologies, new Random()) + +//Clear a list +technologies.clear() + +//Creating an empty map +def devMap = [:] + +//Add values +devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +devMap.put('lastName','Perez') + +//Iterate over elements of a map +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +//Evaluate if a map contains a key +assert devMap.containsKey('name') + +//Evaluate if a map contains a value +assert devMap.containsValue('Roberto') + +//Get the keys of a map +println devMap.keySet() + +//Get the values of a map +println devMap.values() + +/* + Groovy Beans + + GroovyBeans are JavaBeans but using a much simpler syntax + + When Groovy is compiled to bytecode, the following rules are used. + + * If the name is declared with an access modifier (public, private or + protected) then a field is generated. + + * A name declared with no access modifier generates a private field with + public getter and setter (i.e. a property). + + * If a property is declared final the private field is created final and no + setter is generated. + + * You can declare a property and also declare your own getter or setter. + + * You can declare a property and a field of the same name, the property will + use that field then. + + * If you want a private or protected property you have to provide your own + getter and setter which must be declared private or protected. + + * If you access a property from within the class the property is defined in + at compile time with implicit or explicit this (for example this.foo, or + simply foo), Groovy will access the field directly instead of going though + the getter and setter. + + * If you access a property that does not exist using the explicit or + implicit foo, then Groovy will access the property through the meta class, + which may fail at runtime. + +*/ + +class Foo { + // read only property + final String name = "Roberto" + + // read only property with public getter and protected setter + String language + protected void setLanguage(String language) { this.language = language } + + // dynamically typed property + def lastName +} + +/* + Logical Branching and Looping +*/ + +//Groovy supports the usual if - else syntax +def x = 3 + +if(x==1) { + println "One" +} else if(x==2) { + println "Two" +} else { + println "X greater than Two" +} + +//Groovy also supports the ternary operator: +def y = 10 +def x = (y > 1) ? "worked" : "failed" +assert x == "worked" + +//For loop +//Iterate over a range +def x = 0 +for (i in 0 .. 30) { + x += i +} + +//Iterate over a list +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +//Iterate over an array +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +//Iterate over a map +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} + +/* + Operators + + Operator Overloading for a list of the common operators that Groovy supports: + http://www.groovy-lang.org/operators.html#Operator-Overloading + + Helpful groovy operators +*/ +//Spread operator: invoke an action on all items of an aggregate object. +def technologies = ['Groovy','Grails','Gradle'] +technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() } + +//Safe navigation operator: used to avoid a NullPointerException. +def user = User.get(1) +def username = user?.username + + +/* + Closures + A Groovy Closure is like a "code block" or a method pointer. It is a piece of + code that is defined and then executed at a later point. + + More info at: http://www.groovy-lang.org/closures.html +*/ +//Example: +def clos = { println "Hello World!" } + +println "Executing the Closure:" +clos() + +//Passing parameters to a closure +def sum = { a, b -> println a+b } +sum(2,4) + +//Closures may refer to variables not listed in their parameter list. +def x = 5 +def multiplyBy = { num -> num * x } +println multiplyBy(10) + +// If you have a Closure that takes a single argument, you may omit the +// parameter definition of the Closure +def clos = { print it } +clos( "hi" ) + +/* + Groovy can memorize closure results [1][2][3] +*/ +def cl = {a, b -> + sleep(3000) // simulate some time consuming processing + a + b +} + +mem = cl.memoize() + +def callClosure(a, b) { + def start = System.currentTimeMillis() + mem(a, b) + println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs." +} + +callClosure(1, 2) +callClosure(1, 2) +callClosure(2, 3) +callClosure(2, 3) +callClosure(3, 4) +callClosure(3, 4) +callClosure(1, 2) +callClosure(2, 3) +callClosure(3, 4) + +/* + Expando + + The Expando class is a dynamic bean so we can add properties and we can add + closures as methods to an instance of this class + + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def user = new Expando(name:"Roberto") + assert 'Roberto' == user.name + + user.lastName = 'Pérez' + assert 'Pérez' == user.lastName + + user.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println user.showInfo(sw) + + +/* + Metaprogramming (MOP) +*/ + +//Using ExpandoMetaClass to add behaviour +String.metaClass.testAdd = { + println "we added this" +} + +String x = "test" +x?.testAdd() + +//Intercepting method calls +class Test implements GroovyInterceptable { + def sum(Integer x, Integer y) { x + y } + + def invokeMethod(String name, args) { + System.out.println "Invoke method $name with args: $args" + } +} + +def test = new Test() +test?.sum(2,3) +test?.multiply(2,3) + +//Groovy supports propertyMissing for dealing with property resolution attempts. +class Foo { + def propertyMissing(String name) { name } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + TypeChecked and CompileStatic + Groovy, by nature, is and will always be a dynamic language but it supports + typechecked and compilestatic + + More info: http://www.infoq.com/articles/new-groovy-20 +*/ +//TypeChecked +import groovy.transform.TypeChecked + +void testMethod() {} + +@TypeChecked +void test() { + testMeethod() + + def name = "Roberto" + + println naameee + +} + +//Another example: +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numbers = [1,2,3,4] + + Date date = numbers[1] + + return "Test" + +} + +//CompileStatic example: +import groovy.transform.CompileStatic + +@CompileStatic +int sum(int x, int y) { + x + y +} + +assert sum(2,5) == 7 + + +``` + +## Further resources + +[Groovy documentation](http://www.groovy-lang.org/documentation.html) + +[Groovy web console](http://groovyconsole.appspot.com/) + +Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) + +## Books + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html + + + -- cgit v1.2.3 From 021c80723e3b28d81c852b6fd58b6ec9e34670ff Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Fri, 19 Jun 2015 10:58:39 +0800 Subject: zh-cn translation for groovy --- zh-cn/groovy-cn.html.markdown | 203 ++++++++++++++++++++---------------------- 1 file changed, 98 insertions(+), 105 deletions(-) diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown index 519f36ce..ccd48a4c 100644 --- a/zh-cn/groovy-cn.html.markdown +++ b/zh-cn/groovy-cn.html.markdown @@ -1,36 +1,38 @@ --- language: Groovy -filename: learngroovy.groovy +filename: learngroovy-cn.groovy contributors: - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] -filename: learngroovy.groovy +translators: + - ["Todd Gao", "http://github.com/7c00"] +lang: zh-cn --- -Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) +Groovy - Java平台的动态语言。[了解更多。](http://www.groovy-lang.org/) ```groovy /* - Set yourself up: + 安装: - 1) Install GVM - http://gvmtool.net/ - 2) Install Groovy: gvm install groovy - 3) Start the groovy console by typing: groovyConsole + 1) 安装 GVM - http://gvmtool.net/ + 2) 安装 Groovy: gvm install groovy + 3) 启动 groovy 控制台,键入: groovyConsole */ -// Single line comments start with two forward slashes +// 双斜线开始的是单行注释 /* -Multi line comments look like this. +像这样的是多行注释 */ // Hello World println "Hello world!" /* - Variables: + 变量: - You can assign values to variables for later use + 可以给变量赋值,稍后再用 */ def x = 1 @@ -49,142 +51,137 @@ x = "Groovy!" println x /* - Collections and maps + 集合和map */ -//Creating an empty list +//创建一个空的列表 def technologies = [] -/*** Adding a elements to the list ***/ +/*** 往列表中增加一个元素 ***/ -// As with Java +// 和Java一样 technologies.add("Grails") -// Left shift adds, and returns the list +// 左移添加,返回该列表 technologies << "Groovy" -// Add multiple elements +// 增加多个元素 technologies.addAll(["Gradle","Griffon"]) -/*** Removing elements from the list ***/ +/*** 从列表中删除元素 ***/ -// As with Java +// 和Java一样 technologies.remove("Griffon") -// Subtraction works also +// 减法也行 technologies = technologies - 'Grails' -/*** Iterating Lists ***/ +/*** 遍历列表 ***/ -// Iterate over elements of a list +// 遍历列表中的元素 technologies.each { println "Technology: $it"} technologies.eachWithIndex { it, i -> println "$i: $it"} -/*** Checking List contents ***/ +/*** 检查列表内容 ***/ -//Evaluate if a list contains element(s) (boolean) +//判断列表是否包含某元素,返回boolean contained = technologies.contains( 'Groovy' ) -// Or +// 或 contained = 'Groovy' in technologies -// Check for multiple contents +// 检查多个元素 technologies.containsAll(['Groovy','Grails']) -/*** Sorting Lists ***/ +/*** 排序列表 ***/ -// Sort a list (mutates original list) +// 排序列表(修改原列表) technologies.sort() -// To sort without mutating original, you can do: +// 要想不修改原列表,可以这样: sortedTechnologies = technologies.sort( false ) -/*** Manipulating Lists ***/ +/*** 操作列表 ***/ -//Replace all elements in the list +//替换列表元素 Collections.replaceAll(technologies, 'Gradle', 'gradle') -//Shuffle a list +//打乱列表 Collections.shuffle(technologies, new Random()) -//Clear a list +//清空列表 technologies.clear() -//Creating an empty map +//创建空的map def devMap = [:] -//Add values +//增加值 devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] devMap.put('lastName','Perez') -//Iterate over elements of a map +//遍历map元素 devMap.each { println "$it.key: $it.value" } devMap.eachWithIndex { it, i -> println "$i: $it"} -//Evaluate if a map contains a key +//判断map是否包含某键 assert devMap.containsKey('name') -//Evaluate if a map contains a value +//判断map是否包含某值 assert devMap.containsValue('Roberto') -//Get the keys of a map +//取得map所有的键 println devMap.keySet() -//Get the values of a map +//取得map所有的值 println devMap.values() /* Groovy Beans - GroovyBeans are JavaBeans but using a much simpler syntax + GroovyBeans 是 JavaBeans,但使用了更简单的语法 - When Groovy is compiled to bytecode, the following rules are used. + Groovy 被编译为字节码时,遵循下列规则。 - * If the name is declared with an access modifier (public, private or - protected) then a field is generated. + * 如果一个名字声明时带有访问修饰符(public, private, 或者 protected), + 则会生成一个字段(field)。 - * A name declared with no access modifier generates a private field with - public getter and setter (i.e. a property). + * 名字声明时没有访问修饰符,则会生成一个带有public getter和setter的 + private字段,即属性(property)。 - * If a property is declared final the private field is created final and no - setter is generated. + * 如果一个属性声明为final,则会创建一个final的private字段,但不会生成setter。 - * You can declare a property and also declare your own getter or setter. + * 可以声明一个属性的同时定义自己的getter和setter。 - * You can declare a property and a field of the same name, the property will - use that field then. + * 可以声明具有相同名字的属性和字段,该属性会使用该字段。 - * If you want a private or protected property you have to provide your own - getter and setter which must be declared private or protected. + * 如果要定义private或protected属性,必须提供声明为private或protected的getter + 和setter。 - * If you access a property from within the class the property is defined in - at compile time with implicit or explicit this (for example this.foo, or - simply foo), Groovy will access the field directly instead of going though - the getter and setter. + * 如果使用显式或隐式的 this(例如 this.foo, 或者 foo)访问类的在编译时定义的属性, + Groovy会直接访问对应字段,而不是使用getter或者setter - * If you access a property that does not exist using the explicit or - implicit foo, then Groovy will access the property through the meta class, - which may fail at runtime. + * 如果使用显式或隐式的 foo 访问一个不存在的属性,Groovy会通过元类(meta class) + 访问它,这可能导致运行时错误。 */ class Foo { - // read only property + // 只读属性 final String name = "Roberto" - // read only property with public getter and protected setter + // 只读属性,有public getter和protected setter String language protected void setLanguage(String language) { this.language = language } - // dynamically typed property + // 动态类型属性 def lastName } /* - Logical Branching and Looping + 逻辑分支和循环 */ -//Groovy supports the usual if - else syntax +//Groovy支持常见的if - else语法 def x = 3 if(x==1) { @@ -195,32 +192,32 @@ if(x==1) { println "X greater than Two" } -//Groovy also supports the ternary operator: +//Groovy也支持三元运算符 def y = 10 def x = (y > 1) ? "worked" : "failed" assert x == "worked" -//For loop -//Iterate over a range +//for循环 +//使用区间(range)遍历 def x = 0 for (i in 0 .. 30) { x += i } -//Iterate over a list +//遍历列表 x = 0 for( i in [5,3,2,1] ) { x += i } -//Iterate over an array +//遍历数组 array = (0..20).toArray() x = 0 for (i in array) { x += i } -//Iterate over a map +//遍历map def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] x = 0 for ( e in map ) { @@ -228,54 +225,52 @@ for ( e in map ) { } /* - Operators + 运算符 - Operator Overloading for a list of the common operators that Groovy supports: + Groovy中下列运算符支持重载: http://www.groovy-lang.org/operators.html#Operator-Overloading - Helpful groovy operators + 实用的groovy运算符 */ -//Spread operator: invoke an action on all items of an aggregate object. +//展开(spread)运算符:对聚合对象的所有元素施加操作 def technologies = ['Groovy','Grails','Gradle'] -technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() } +technologies*.toUpperCase() // 相当于 technologies.collect { it?.toUpperCase() } -//Safe navigation operator: used to avoid a NullPointerException. +//安全导航(safe navigation)运算符:用来避免NullPointerException def user = User.get(1) def username = user?.username /* - Closures - A Groovy Closure is like a "code block" or a method pointer. It is a piece of - code that is defined and then executed at a later point. + 闭包 + Groovy闭包好比代码块或者方法指针,它是一段定义稍后执行的代码。 - More info at: http://www.groovy-lang.org/closures.html + 更多信息见:http://www.groovy-lang.org/closures.html */ -//Example: +//例子: def clos = { println "Hello World!" } println "Executing the Closure:" clos() -//Passing parameters to a closure +//传参数给闭包 def sum = { a, b -> println a+b } sum(2,4) -//Closures may refer to variables not listed in their parameter list. +//闭包可以引用参数列表以外的变量 def x = 5 def multiplyBy = { num -> num * x } println multiplyBy(10) -// If you have a Closure that takes a single argument, you may omit the -// parameter definition of the Closure +// 只有一个参数的闭包可以省略参数的定义 def clos = { print it } clos( "hi" ) /* - Groovy can memorize closure results [1][2][3] + Groovy可以记忆闭包结果 [1][2][3] */ def cl = {a, b -> - sleep(3000) // simulate some time consuming processing + sleep(3000) // 模拟费时操作 a + b } @@ -300,8 +295,7 @@ callClosure(3, 4) /* Expando - The Expando class is a dynamic bean so we can add properties and we can add - closures as methods to an instance of this class + Expando类是一种动态bean类,可以给它的实例添加属性和添加闭包作为方法 http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html */ @@ -321,10 +315,10 @@ callClosure(3, 4) /* - Metaprogramming (MOP) + 元编程(MOP) */ -//Using ExpandoMetaClass to add behaviour +//使用ExpandoMetaClass增加行为 String.metaClass.testAdd = { println "we added this" } @@ -332,7 +326,7 @@ String.metaClass.testAdd = { String x = "test" x?.testAdd() -//Intercepting method calls +//方法调用注入 class Test implements GroovyInterceptable { def sum(Integer x, Integer y) { x + y } @@ -345,7 +339,7 @@ def test = new Test() test?.sum(2,3) test?.multiply(2,3) -//Groovy supports propertyMissing for dealing with property resolution attempts. +//Groovy支持propertyMissing,来处理属性解析尝试 class Foo { def propertyMissing(String name) { name } } @@ -354,13 +348,12 @@ def f = new Foo() assertEquals "boo", f.boo /* - TypeChecked and CompileStatic - Groovy, by nature, is and will always be a dynamic language but it supports - typechecked and compilestatic + 类型检查和静态编译 + Groovy天生是并将永远是一门静态语言,但也支持类型检查和静态编译 - More info: http://www.infoq.com/articles/new-groovy-20 + 更多: http://www.infoq.com/articles/new-groovy-20 */ -//TypeChecked +//类型检查 import groovy.transform.TypeChecked void testMethod() {} @@ -375,7 +368,7 @@ void test() { } -//Another example: +//另一例子 import groovy.transform.TypeChecked @TypeChecked @@ -390,7 +383,7 @@ Integer test() { } -//CompileStatic example: +//静态编译例子 import groovy.transform.CompileStatic @CompileStatic @@ -403,15 +396,15 @@ assert sum(2,5) == 7 ``` -## Further resources +## 进阶资源 -[Groovy documentation](http://www.groovy-lang.org/documentation.html) +[Groovy文档](http://www.groovy-lang.org/documentation.html) [Groovy web console](http://groovyconsole.appspot.com/) -Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) +加入[Groovy用户组](http://www.groovy-lang.org/usergroups.html) -## Books +## 图书 * [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) -- cgit v1.2.3 From a6a498efab8b3ed2e8062a97e0fd47fb181b98f4 Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Fri, 19 Jun 2015 12:16:41 +0800 Subject: update Chinese translation --- zh-cn/groovy-cn.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown index ccd48a4c..562a0284 100644 --- a/zh-cn/groovy-cn.html.markdown +++ b/zh-cn/groovy-cn.html.markdown @@ -32,7 +32,7 @@ println "Hello world!" /* 变量: - 可以给变量赋值,稍后再用 + 可以给变量赋值,以便稍后使用 */ def x = 1 @@ -51,7 +51,7 @@ x = "Groovy!" println x /* - 集合和map + 集合和映射 */ //创建一个空的列表 @@ -73,7 +73,7 @@ technologies.addAll(["Gradle","Griffon"]) // 和Java一样 technologies.remove("Griffon") -// 减法也行 +// 减号也行 technologies = technologies - 'Grails' /*** 遍历列表 ***/ @@ -93,7 +93,7 @@ contained = 'Groovy' in technologies // 检查多个元素 technologies.containsAll(['Groovy','Grails']) -/*** 排序列表 ***/ +/*** 列表排序 ***/ // 排序列表(修改原列表) technologies.sort() @@ -101,7 +101,7 @@ technologies.sort() // 要想不修改原列表,可以这样: sortedTechnologies = technologies.sort( false ) -/*** 操作列表 ***/ +/*** 列表操作 ***/ //替换列表元素 Collections.replaceAll(technologies, 'Gradle', 'gradle') @@ -112,27 +112,27 @@ Collections.shuffle(technologies, new Random()) //清空列表 technologies.clear() -//创建空的map +//创建空的映射 def devMap = [:] //增加值 devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] devMap.put('lastName','Perez') -//遍历map元素 +//遍历映射元素 devMap.each { println "$it.key: $it.value" } devMap.eachWithIndex { it, i -> println "$i: $it"} -//判断map是否包含某键 +//判断映射是否包含某键 assert devMap.containsKey('name') -//判断map是否包含某值 +//判断映射是否包含某值 assert devMap.containsValue('Roberto') -//取得map所有的键 +//取得映射所有的键 println devMap.keySet() -//取得map所有的值 +//取得映射所有的值 println devMap.values() /* @@ -217,7 +217,7 @@ for (i in array) { x += i } -//遍历map +//遍历映射 def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] x = 0 for ( e in map ) { @@ -227,7 +227,7 @@ for ( e in map ) { /* 运算符 - Groovy中下列运算符支持重载: + 在Groovy中以下常用运算符支持重载: http://www.groovy-lang.org/operators.html#Operator-Overloading 实用的groovy运算符 @@ -243,7 +243,7 @@ def username = user?.username /* 闭包 - Groovy闭包好比代码块或者方法指针,它是一段定义稍后执行的代码。 + Groovy闭包好比代码块或者方法指针,它是一段代码定义,可以以后执行。 更多信息见:http://www.groovy-lang.org/closures.html */ @@ -326,7 +326,7 @@ String.metaClass.testAdd = { String x = "test" x?.testAdd() -//方法调用注入 +//拦截方法调用 class Test implements GroovyInterceptable { def sum(Integer x, Integer y) { x + y } @@ -349,7 +349,7 @@ assertEquals "boo", f.boo /* 类型检查和静态编译 - Groovy天生是并将永远是一门静态语言,但也支持类型检查和静态编译 + Groovy天生是并将永远是一门动态语言,但也支持类型检查和静态编译 更多: http://www.infoq.com/articles/new-groovy-20 */ -- cgit v1.2.3 From e4931ee126a23a851c6a2ab474e84996e1b28f3e Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Fri, 19 Jun 2015 23:11:38 +0200 Subject: Fixed misinfo regarding sigils also # is more commonly called number sign than number symbol. --- perl.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 3c0699ad..4e172406 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -12,16 +12,16 @@ Perl 5 is a highly capable, feature-rich programming language with over 25 years Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects. ```perl -# Single line comments start with a number symbol. +# Single line comments start with a number sign. #### Perl variable types -# Variables begin with the $ symbol. +# Variables begin with a sigil, which is a symbol showing the type. # A valid variable name starts with a letter or underscore, # followed by any number of letters, numbers, or underscores. -### Perl has three main variable types: scalars, arrays, and hashes. +### Perl has three main variable types: $scalar, @array, and %hash. ## Scalars # A scalar represents a single value: -- cgit v1.2.3 From 8d22be8f85339a73f4dcf09be4feefe1be9156b9 Mon Sep 17 00:00:00 2001 From: Michael Simpson Date: Mon, 22 Jun 2015 16:03:24 -0400 Subject: Remove in-development from Rust's description Now that Rust is stable at 1.0 saying "in-development" might not be appropriate any more. --- rust.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index fbfa4cdf..dd03acdd 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnrust.rs --- -Rust is an in-development programming language developed by Mozilla Research. +Rust is a programming language developed by Mozilla Research. Rust combines low-level control over performance with high-level convenience and safety guarantees. -- cgit v1.2.3 From 5e2eed46b23130353122c5bf80be2f3aa2f656bb Mon Sep 17 00:00:00 2001 From: Christian Schlensker Date: Wed, 24 Jun 2015 10:50:39 -0700 Subject: Fix typo in elixer --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index fb5f183a..c8599838 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -195,7 +195,7 @@ cond do "But I will" end -# It is common to see the last condition equal to `true`, which will always match. +# It is common to set the last condition equal to `true`, which will always match. cond do 1 + 1 == 3 -> "I will never be seen" -- cgit v1.2.3 From ed8f34eb3337bd78e2dca23be34746d01272f1ae Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 27 Jun 2015 16:07:21 +0200 Subject: fix typo, resolves #1156 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 44ad333c..de7d2f25 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1044,7 +1044,7 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # *everything* -- with great power comes great responsibility) ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep +# Oh boy, get ready. Get ready, because we're delving deep # into the rabbit's hole, and you probably won't want to go # back to other languages after reading that. # (I'm guessing you don't want to already at that point). -- cgit v1.2.3 From 9f17872f21bc3a43a1023325414802c2e4467534 Mon Sep 17 00:00:00 2001 From: Leonardo Diez Date: Fri, 3 Jul 2015 11:34:26 +0200 Subject: Update git-es.html.markdown --- es-es/git-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 5c9d3378..73853a9d 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -38,7 +38,7 @@ uno o varios archivos, a lo largo del tiempo. * Se puede trabajar sin conexion. * Colaborar con otros es sencillo!. * Derivar, Crear ramas del proyecto (aka: Branching) es facil!. -* Combinar (aka: Marging) +* Combinar (aka: Merging) * Git es rapido. * Git es flexible. -- cgit v1.2.3 From 92096a65ed309e84439f84f7b410a044386a2959 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 08:35:31 -0600 Subject: python/en - added two resources --- python.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index ace3f794..354fd9a1 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -630,10 +630,12 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) +* [Real Python](https://realpython.com/) -- cgit v1.2.3 From 55f9ff0654f6489aa53e3a799af2dd462fa9c5c8 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 08:36:51 -0600 Subject: python/en - added two resources --- python3.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index a112912f..9369a3ad 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -645,15 +645,16 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) - * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) +* [Real Python](https://realpython.com/) -- cgit v1.2.3 From c6caa7664c53d8decb2076987f601a7c99fd6951 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 21:12:12 -0600 Subject: Update python.html.markdown --- python.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 354fd9a1..b89fe57d 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -637,5 +637,3 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -* [Real Python](https://realpython.com/) - -- cgit v1.2.3 From 5b66758d761afceb797ae0f21d5c99351d29361e Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 21:12:58 -0600 Subject: Update python3.html.markdown --- python3.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 9369a3ad..dd57bf58 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -656,5 +656,3 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -* [Real Python](https://realpython.com/) - -- cgit v1.2.3 From 8544847845c0405e54acadf5125edc0554d73b75 Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 6 Jul 2015 10:40:05 +0200 Subject: change haskell's operator `$` description wording for #1161 --- haskell.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6a64442f..369b1b20 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -209,14 +209,15 @@ foo 5 -- 75 -- the expression on its right is applied as the parameter to the function on its left. -- before -(even (fib 7)) -- false - --- after -even . fib $ 7 -- false +even (fib 7) -- false -- equivalently even $ fib 7 -- false +-- composing functions +even . fib $ 7 -- false + + ---------------------------------------------------- -- 5. Type signatures ---------------------------------------------------- -- cgit v1.2.3 From 6066176a9f5dd7c487bee439ec0db3b4dd9afa46 Mon Sep 17 00:00:00 2001 From: Morgan Date: Wed, 8 Jul 2015 10:54:37 +0200 Subject: [livescript/fr] initial commit --- fr-fr/livescript-fr.html.markdown | 351 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 351 insertions(+) create mode 100644 fr-fr/livescript-fr.html.markdown diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown new file mode 100644 index 00000000..0ed9763b --- /dev/null +++ b/fr-fr/livescript-fr.html.markdown @@ -0,0 +1,351 @@ +--- +language: LiveScript +filename: learnLivescript-fr.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] + - ["Morgan Bohn", "https://github.com/morganbohn"] +lang: fr-fr +--- + +LiveScript est un langage qui se compile en JavaScript. Il a un rapport direct +avec JavaScript, et vous permet d'écrire du JavaScript de façon considérables +sans répétitivité. LiveScript ajoute non seulement des fonctionnalités pour +écrire du code fonctionnel, mais possède aussi nombre d'améliorations pour la +programmation orientée objet et la programmation impérative. + +LiveScript est un descendant indirect de [CoffeeScript][], direct de [Coco][] +avec beaucoup plus de compatibilité. + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +Vous pouvez contacter l'auteur du guide original en anglais ici : +[@kurisuwhyte](https://twitter.com/kurisuwhyte) + + +```coffeescript +# Comme son cousin CoffeeScript, LiveScript utilise le symbole dièse pour les +# commentaires sur une ligne. + +/* + Les commentaires sur plusieurs lignes utilisent la syntaxe du C. Utilisez-les + si vous voulez préserver les commentaires dans la sortie JavaScript. + */ +``` +```coffeescript +# LiveScript utilise l'indentation pour délimiter les blocs de code plutôt que +# les accolades, et les espaces pour appliquer les fonctions, plutôt que les +# parenthèses. + + +######################################################################## +## 1. Valeurs basiques +######################################################################## + +# Les valeurs non définies sont représentées par le mot clé `void` à la place de +# `undefined` +void # comme `undefined` mais plus sûr (ne peut pas être redéfini) + +# Une valeur non valide est représentée par Null. +null + + +# Les booléens se déclarent de la façon suivante: +true +false + +# Et il existe divers alias les représentant également: +on; off +yes; no + + +# Puis viennent les nombres entiers et décimaux. +10 +0.4 # Notez que le `0` est requis + +# Dans un souci de lisibilité, vous pouvez utiliser les tirets bas et les +# suffixes sur les nombres. Il seront ignorés à la compilation. +12_344km + + +# Les chaînes sont des séquences immutables de caractères, comme en JS: +"Christina" # Les apostrophes fonctionnent également! +"""Multi-line + strings + are + okay + too.""" + +# De temps à autre, vous voulez encoder un mot clé; la notation en backslash +# rend cela facile: +\keyword # => 'keyword' + + +# Les tableaux sont des collections ordonnées de valeurs. +fruits = + * \apple + * \orange + * \pear + +# Il peuvent être écrits de manière plus consises à l'aide des crochets: +fruits = [ \apple, \orange, \pear ] + +# Vous pouvez également utiliser la syntaxe suivante, à l'aide d'espaces, pour +# créer votre liste de valeurs: +fruits = <[ apple orange pear ]> + +# Vous pouvez récupérer une entrée à l'aide de son index: +fruits[0] # => "apple" + +# Les objets sont une collection non ordonnées de paires clé/valeur, et +# d'autres choses (que nous verrons plus tard). +person = + name: "Christina" + likes: + * "kittens" + * "and other cute stuff" + +# A nouveau, vous pouvez utiliser une expression plus consise à l'aide des +# accolades: +person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} + +# Vous pouvez récupérer une entrée via sa clé: +person.name # => "Christina" +person["name"] # => "Christina" + + +# Les expressions régulières utilisent la même syntaxe que JavaScript: +trailing-space = /\s$/ # les mots-composés deviennent motscomposés + +# A l'exception que vous pouvez pouvez utiliser des expressions sur plusieurs +# lignes! +# (les commentaires et les espaces seront ignorés) +funRE = // + function\s+(.+) # nom + \s* \((.*)\) \s* # arguments + { (.*) } # corps + // + + +######################################################################## +## 2. Les opérations basiques +######################################################################## + +# Les opérateurs arithmétiques sont les mêmes que pour JavaScript: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# Les comparaisons sont presque identiques, à l'exception que `==` équivaut au +# `===` de JS, là où le `==` de JS est `~=` en LiveScript, et `===` active la +# comparaison d'objets et de tableaux, ainsi que les comparaisons strictes +2 == 2 # => true +2 == "2" # => false +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false + +# Les opérateurs suivants sont également disponibles: <, <=, > et >= + +# Les valeurs logiques peuvent être combinéees grâce aux opérateurs logiques +# `or`, `and` et `not` +true and false # => false +false or true # => true +not false # => true + + +# Les collections ont également des opérateurs additionnels +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'name' of { name: 'Chris' } # => true + + +######################################################################## +## 3. Fonctions +######################################################################## + +# Puisque LiveScript est fonctionnel, vous vous attendez à une bonne prise en +# charge des fonctions. En LiveScript, il est encore plus évident que les +# fonctions sont de premier ordre: +add = (left, right) -> left + right +add 1, 2 # => 3 + +# Les fonctions qui ne prennent pas d'arguments sont appelées avec un point +# d'exclamation! +two = -> 2 +two! + +# LiveScript utilise l'environnement de la fonction, comme JavaScript. +# A l'inverse de JavaScript, le `=` fonctionne comme un opérateur de +# déclaration, et il déclarera toujours la variable située à gauche. + +# L'opérateur `:=` est disponible pour réutiliser un nom provenant de +# l'environnement parent. + + +# Vous pouvez "déballer" les arguments d'une fonction pour récupérer +# rapidement les valeurs qui vous intéressent dans une structure de données +# complexe: +tail = ([head, ...rest]) -> rest +tail [1, 2, 3] # => [2, 3] + +# Vous pouvez également transformer les arguments en utilisant les opérateurs +# binaires. Définir des arguments par défaut est aussi possible. +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# You pouvez utiliser cela pour cloner un argument en particulier pour éviter +# les effets secondaires. Par exemple: +copy = (^^target, source) -> + for k,v of source => target[k] = v + target +a = { a: 1 } +copy a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + + +# Une fonction peut être réduite en utilisant une longue flèche à la place +# d'une courte: +add = (left, right) --> left + right +add1 = add 1 +add1 2 # => 3 + +# Les fonctions ont un argument `it` implicite si vous n'en déclarez pas: +identity = -> it +identity 1 # => 1 + +# Les opérateurs ne sont pas des fonctions en LiveScript, mais vous pouvez +# facilement les transformer en fonction: +divide-by-two = (/ 2) +[2, 4, 8, 16].map(divide-by-two) .reduce (+) + +# Comme dans tout bon langage fonctionnel, vous pouvez créer des fonctions +# composées d'autres fonctions: +double-minus-one = (- 1) . (* 2) + +# En plus de la formule mathématique `f . g`, vous avez les opérateurs `>>` +# et `<<`, qui décrivent l'ordre d'application des fonctions. +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + + +# Pour appliquer une valeur à une fonction, vous pouvez utiliser les opérateurs +# `|>` et `<|`: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# You pouvez aussi choisir où vous voulez que la valeur soit placée, en +# marquant la position avec un tiret bas (_): +reduce = (f, xs, initial) --> xs.reduce f, initial +[1 2 3] |> reduce (+), _, 0 # => 6 + + +# Le tiret bas est également utilisé pour l'application régulière partielle, +# que vous pouvez utiliser pour toute fonction: +div = (left, right) -> left / right +div-by-two = div _, 2 +div-by-two 4 # => 2 + + +# Pour conclure, LiveScript vous permet d'utiliser les fonctions de rappel +# (mais vous devriez essayer des approches plus fonctionnelles, comme +# Promises): +readFile = (name, f) -> f name +a <- readFile 'foo' +b <- readFile 'bar' +console.log a + b + +# Equivalent à: +readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. Conditionnalités +######################################################################## + +# Vous pouvez faire de la conditionnalité à l'aide de l'expression `if...else`: +x = if n > 0 then \positive else \negative + +# A la place de `then`, vous pouvez utiliser `=>` +x = if n > 0 => \positive + else \negative + +# Pour les conditions complexes, il vaut mieux utiliser l'expresssion `switch`: +y = {} +x = switch + | (typeof y) is \number => \number + | (typeof y) is \string => \string + | 'length' of y => \array + | otherwise => \object # `otherwise` et `_` correspondent. + +# Le corps des fonctions, les déclarations et les assignements disposent d'un +# `switch` implicite, donc vous n'avez pas besoin de le réécrire: +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. Compréhensions +######################################################################## + +# Comme en python, vous allez pouvoir utiliser les listes en compréhension, +# ce qui permet de générer rapidement et de manière élégante une liste de +# valeurs: +oneToTwenty = [1 to 20] +evens = [x for x in oneToTwenty when x % 2 == 0] + +# `when` et `unless` peuvent être utilisés comme des filtres. + +# Cette technique fonctionne sur les objets de la même manière, via la syntaxe +# suivante: +copy = { [k, v] for k, v of source } + + +######################################################################## +## 4. Programmation orientée objet +######################################################################## + +# Bien que LiveScript soit un langage fonctionnel, il dispose d'intéressants +# outils pour la programmation objet. La syntaxe de déclaration d'une classe +# est héritée de CoffeeScript: +class Animal + (@name, kind) -> + @kind = kind + action: (what) -> "*#{@name} (a #{@kind}) #{what}*" + +class Cat extends Animal + (@name) -> super @name, 'cat' + purr: -> @action 'purrs' + +kitten = new Cat 'Mei' +kitten.purr! # => "*Mei (a cat) purrs*" + +# En plus de l'héritage classique, vous pouvez utiliser autant de mixins +# que vous voulez pour votre classe. Les mixins sont justes des objets: +Huggable = + hug: -> @action 'is hugged' + +class SnugglyCat extends Cat implements Huggable + +kitten = new SnugglyCat 'Purr' +kitten.hug! # => "*Mei (a cat) is hugged*" +``` + +## Lectures complémentaires + +Il y a beaucoup plus de choses à dire sur LiveScript, mais ce guide devrait +suffire pour démarrer l'écriture de petites fonctionnalités. +Le [site officiel](http://livescript.net/) dispose de beaucoup d'information, +ainsi que d'un compilateur en ligne vous permettant de tester le langage! + +Jetez également un coup d'oeil à [prelude.ls](http://gkz.github.io/prelude-ls/), +et consultez le channel `#livescript` sur le réseau Freenode. -- cgit v1.2.3 From 93486c8e7ab1bbfe2af08bcb27bde6b198a18b1c Mon Sep 17 00:00:00 2001 From: Morgan Date: Wed, 8 Jul 2015 11:16:07 +0200 Subject: [livescript/fr] add translators, correct intro --- fr-fr/livescript-fr.html.markdown | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown index 0ed9763b..c6a115ee 100644 --- a/fr-fr/livescript-fr.html.markdown +++ b/fr-fr/livescript-fr.html.markdown @@ -3,18 +3,20 @@ language: LiveScript filename: learnLivescript-fr.ls contributors: - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +translators: - ["Morgan Bohn", "https://github.com/morganbohn"] lang: fr-fr --- -LiveScript est un langage qui se compile en JavaScript. Il a un rapport direct -avec JavaScript, et vous permet d'écrire du JavaScript de façon considérables -sans répétitivité. LiveScript ajoute non seulement des fonctionnalités pour -écrire du code fonctionnel, mais possède aussi nombre d'améliorations pour la -programmation orientée objet et la programmation impérative. +LiveScript est un langage qui compile en JavaScript. Il a un rapport direct +avec JavaScript, et vous permet d'écrire du JavaScript plus simplement, plus +efficacement et sans répétitivité. LiveScript ajoute non seulement des +fonctionnalités pour écrire du code fonctionnel, mais possède aussi nombre +d'améliorations pour la programmation orientée objet et la programmation +impérative. -LiveScript est un descendant indirect de [CoffeeScript][], direct de [Coco][] -avec beaucoup plus de compatibilité. +LiveScript est un descendant direct de [Coco][], indirect de [CoffeeScript][], +avec lequel il a beaucoup plus de compatibilité. [Coco]: http://satyr.github.io/coco/ [CoffeeScript]: http://coffeescript.org/ -- cgit v1.2.3 From 71cdcb34436925d59258144404080b6c83f74bc4 Mon Sep 17 00:00:00 2001 From: Morgan Date: Wed, 8 Jul 2015 13:41:15 +0200 Subject: [livescript/fr] corrections --- fr-fr/livescript-fr.html.markdown | 47 ++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown index c6a115ee..5760332d 100644 --- a/fr-fr/livescript-fr.html.markdown +++ b/fr-fr/livescript-fr.html.markdown @@ -36,8 +36,8 @@ Vous pouvez contacter l'auteur du guide original en anglais ici : ``` ```coffeescript # LiveScript utilise l'indentation pour délimiter les blocs de code plutôt que -# les accolades, et les espaces pour appliquer les fonctions, plutôt que les -# parenthèses. +# les accolades, et les espaces pour appliquer les fonctions (bien que les +# parenthèses soient utilisables). ######################################################################## @@ -52,7 +52,7 @@ void # comme `undefined` mais plus sûr (ne peut pas être redéfini) null -# Les booléens se déclarent de la façon suivante: +# Les booléens s'utilisent de la façon suivante: true false @@ -143,7 +143,8 @@ funRE = // # Les comparaisons sont presque identiques, à l'exception que `==` équivaut au # `===` de JS, là où le `==` de JS est `~=` en LiveScript, et `===` active la -# comparaison d'objets et de tableaux, ainsi que les comparaisons strictes +# comparaison d'objets et de tableaux, ainsi que les comparaisons strictes +# (sans conversion de type) 2 == 2 # => true 2 == "2" # => false 2 ~= "2" # => true @@ -180,27 +181,28 @@ not false # => true add = (left, right) -> left + right add 1, 2 # => 3 -# Les fonctions qui ne prennent pas d'arguments sont appelées avec un point -# d'exclamation! +# Les fonctions qui ne prennent pas d'arguments peuvent être appelées avec un +# point d'exclamation! two = -> 2 two! # LiveScript utilise l'environnement de la fonction, comme JavaScript. # A l'inverse de JavaScript, le `=` fonctionne comme un opérateur de -# déclaration, et il déclarera toujours la variable située à gauche. +# déclaration, et il déclarera toujours la variable située à gauche (sauf si +# la variable a été déclarée dans l'environnement parent). # L'opérateur `:=` est disponible pour réutiliser un nom provenant de # l'environnement parent. -# Vous pouvez "déballer" les arguments d'une fonction pour récupérer +# Vous pouvez extraire les arguments d'une fonction pour récupérer # rapidement les valeurs qui vous intéressent dans une structure de données # complexe: tail = ([head, ...rest]) -> rest tail [1, 2, 3] # => [2, 3] # Vous pouvez également transformer les arguments en utilisant les opérateurs -# binaires. Définir des arguments par défaut est aussi possible. +# binaires et unaires. Définir des arguments par défaut est aussi possible. foo = (a = 1, b = 2) -> a + b foo! # => 3 @@ -214,7 +216,7 @@ copy a, { b: 2 } # => { a: 1, b: 2 } a # => { a: 1 } -# Une fonction peut être réduite en utilisant une longue flèche à la place +# Une fonction peut être curryfiée en utilisant une longue flèche à la place # d'une courte: add = (left, right) --> left + right add1 = add 1 @@ -227,14 +229,14 @@ identity 1 # => 1 # Les opérateurs ne sont pas des fonctions en LiveScript, mais vous pouvez # facilement les transformer en fonction: divide-by-two = (/ 2) -[2, 4, 8, 16].map(divide-by-two) .reduce (+) +[2, 4, 8, 16].map(divide-by-two).reduce (+) # Comme dans tout bon langage fonctionnel, vous pouvez créer des fonctions # composées d'autres fonctions: double-minus-one = (- 1) . (* 2) # En plus de la formule mathématique `f . g`, vous avez les opérateurs `>>` -# et `<<`, qui décrivent l'ordre d'application des fonctions. +# et `<<`, qui décrivent l'ordre d'application des fonctions composées. double-minus-one = (* 2) >> (- 1) double-minus-one = (- 1) << (* 2) @@ -244,22 +246,27 @@ double-minus-one = (- 1) << (* 2) map = (f, xs) --> xs.map f [1 2 3] |> map (* 2) # => [2 4 6] +# La version sans pipe correspont à: +((map (* 2)) [1, 2, 3]) + # You pouvez aussi choisir où vous voulez que la valeur soit placée, en # marquant la position avec un tiret bas (_): reduce = (f, xs, initial) --> xs.reduce f, initial [1 2 3] |> reduce (+), _, 0 # => 6 -# Le tiret bas est également utilisé pour l'application régulière partielle, +# Le tiret bas est également utilisé pour l'application partielle, # que vous pouvez utiliser pour toute fonction: div = (left, right) -> left / right div-by-two = div _, 2 div-by-two 4 # => 2 -# Pour conclure, LiveScript vous permet d'utiliser les fonctions de rappel +# Pour conclure, LiveScript vous permet d'utiliser les fonctions de rappel. # (mais vous devriez essayer des approches plus fonctionnelles, comme -# Promises): +# Promises). +# Un fonction de rappel est une fonction qui est passée en argument à une autre +# fonction: readFile = (name, f) -> f name a <- readFile 'foo' b <- readFile 'bar' @@ -291,8 +298,8 @@ x = switch # Le corps des fonctions, les déclarations et les assignements disposent d'un # `switch` implicite, donc vous n'avez pas besoin de le réécrire: take = (n, [x, ...xs]) --> - | n == 0 => [] - | _ => [x] ++ take (n - 1), xs + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs ######################################################################## @@ -307,8 +314,8 @@ evens = [x for x in oneToTwenty when x % 2 == 0] # `when` et `unless` peuvent être utilisés comme des filtres. -# Cette technique fonctionne sur les objets de la même manière, via la syntaxe -# suivante: +# Cette technique fonctionne sur les objets de la même manière. Vous allez +# pouvoir générer l'ensemble de paires clé/valeur via la syntaxe suivante: copy = { [k, v] for k, v of source } @@ -332,7 +339,7 @@ kitten = new Cat 'Mei' kitten.purr! # => "*Mei (a cat) purrs*" # En plus de l'héritage classique, vous pouvez utiliser autant de mixins -# que vous voulez pour votre classe. Les mixins sont justes des objets: +# que vous voulez pour votre classe. Les mixins sont juste des objets: Huggable = hug: -> @action 'is hugged' -- cgit v1.2.3 From f63aa01211010b865bf663fa7a6b5128b49e2282 Mon Sep 17 00:00:00 2001 From: Morgan Date: Wed, 8 Jul 2015 13:43:17 +0200 Subject: [livescript/fr] corrections --- fr-fr/livescript-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown index 5760332d..9c3b8003 100644 --- a/fr-fr/livescript-fr.html.markdown +++ b/fr-fr/livescript-fr.html.markdown @@ -246,7 +246,7 @@ double-minus-one = (- 1) << (* 2) map = (f, xs) --> xs.map f [1 2 3] |> map (* 2) # => [2 4 6] -# La version sans pipe correspont à: +# La version sans pipe correspond à: ((map (* 2)) [1, 2, 3]) # You pouvez aussi choisir où vous voulez que la valeur soit placée, en -- cgit v1.2.3 From abcb4e25de06ce4b295b1999fd251d76f60d5fc5 Mon Sep 17 00:00:00 2001 From: Guangming Mao Date: Wed, 8 Jul 2015 20:51:09 +0800 Subject: rust/zh Add chinese translation for rust --- zh-cn/rust-cn.html.markdown | 296 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 296 insertions(+) create mode 100644 zh-cn/rust-cn.html.markdown diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown new file mode 100644 index 00000000..f50c1566 --- /dev/null +++ b/zh-cn/rust-cn.html.markdown @@ -0,0 +1,296 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Guangming Mao", "http://maogm.com"] +filename: learnrust-cn.rs +lang: zh-cn +--- + +Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制和高级语言的便利性和安全保障结合在了一起。 + +而 Rust 并不需要一个垃圾回收器或者运行时即可实现这个目的,这使得 Rust 库可以成为一种 C 语言的替代品。 + +Rust 第一版(0.1 版)发布于 2012 年 1 月,3 年以来一直在紧锣密鼓地迭代。 +因为更新太频繁,一般建议使用每夜构建版而不是稳定版,直到最近 1.0 版本的发布。 + +2015 年 3 月 15 日,Rust 1.0 发布,完美向后兼容,最新的每夜构建版提供了缩短编译时间等新特性。 +Rust 采用了持续迭代模型,每 6 周一个发布版。Rust 1.1 beta 版在 1.0 发布时同时发布。 + +尽管 Rust 相对来说是一门底层语言,它提供了一些常见于高级语言的函数式编程的特性。这让 Rust 不仅高效,并且易用。 + +```rust +// 这是注释,单行注释... +/* ...这是多行注释 */ + +/////////////// +// 1. 基础 // +/////////////// + +// 函数 (Functions) +// `i32` 是有符号 32 位整数类型(32-bit signed integers) +fn add2(x: i32, y: i32) -> i32 { + // 隐式返回 (不要分号) + x + y +} + +// 主函数(Main function) +fn main() { + // 数字 (Numbers) // + + // 不可变绑定 + let x: i32 = 1; + + // 整形/浮点型数 后缀 + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // 类型推导 + // 大部分时间,Rust 编译器会推导变量类型,所以不必把类型显式写出来。 + // 这个教程里面很多地方都显式写了类型,但是只是为了示范。 + // 绝大部分时间可以交给类型推导。 + let implicit_x = 1; + let implicit_f = 1.3; + + // 算术运算 + let sum = x + y + 13; + + // 可变变量 + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // 字符串 (Strings) // + + // 字符串字面量 + let x: &str = "hello world!"; + + // 输出 + println!("{} {}", f, x); // 1.3 hello world + + // 一个 `String` – 在堆上分配空间的字符串 + let s: String = "hello world".to_string(); + + // 字符串分片(slice) - 另一个字符串的不可变视图 + // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何类容,只是一个指向某个东西的指针 + // 比如这里就是 `s` + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // hello world hello world + + // 数组 (Vectors/arrays) // + + // 长度固定的数组 (array) + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // 变长数组 (vector) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // 分片 - 某个数组(vector/array)的不可变视图 + // 和字符串分片基本一样,只不过是针对数组的 + let slice: &[i32] = &vector; + + // 使用 `{:?}` 按调试样式输出 + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // 元组 (Tuples) // + + // 元组是固定大小的一组值,可以是不同类型 + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // 解构 `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // 索引 + println!("{}", x.1); // hello + + ////////////// + // 2. 类型 (Type) // + ////////////// + + // 结构体(Sturct) + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // 匿名成员结构体,又叫“元组结构体”(‘tuple struct’) + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // 基础的 C 风格枚举类型(enum) + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // 有成员的枚举类型 + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // 泛型 (Generics) // + + struct Foo { bar: T } + + // 这个在标准库里面有实现,叫 `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // 方法 (Methods) // + + impl Foo { + // 方法需要一个显式的 `self` 参数 + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // 接口(Traits) (其他语言里叫 interfaces 或 typeclasses) // + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + /////////////////////////////////// + // 3. 模板匹配 (Pattern matching) // + /////////////////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), + } + + // 高级模板匹配 + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("The second number is Nothing!"), + } + + /////////////////////////////// + // 4. 条件控制 (Control flow) // + /////////////////////////////// + + // `for` 循环 + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // 区间 (Ranges) + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // 输出 `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` 可以当表达式 + let value = if true { + "good" + } else { + "bad" + }; + + // `while` 循环 + while 1 == 1 { + println!("The universe is operating normally."); + } + + // 无限循环 + loop { + println!("Hello!"); + } + + //////////////////////////////////////////////// + // 5. 内存安全和指针 (Memory safety & pointers) // + //////////////////////////////////////////////// + + // 独占指针 (Owned pointer) - 同一时刻只能有一个对象能“拥有”这个指针 + // 意味着 `Box` 离开他的作用域后,会被安全的释放 + let mut mine: Box = Box::new(3); + *mine = 5; // 解引用 + // `now_its_mine` 获取了 `mine` 的所有权。换句话说,`mine` 移动 (move) 了 + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // 编译报错,因为现在 `now_its_mine` 独占那个指针 + + // 引用 (Reference) – 引用其他数据的不可变指针 + // 当引用指向某个值,我们称为“借用”这个值,因为是被不可变的借用,所以不能被修改,也不能移动 + // 借用一直持续到生命周期结束,即离开作用域 + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); //不像 `box`, `var` 还可以继续使用 + println!("{}", *ref_var); + // var = 5; // 编译报错,因为 `var` 被借用了 + // *ref_var = 6; // 编译报错,因为 `ref_var` 是不可变引用 + + // 可变引用 (Mutable reference) + // 当一个变量被可变地借用时,也不可使用 + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; + + println!("{}", *ref_var2); // 6 + // var2 = 2; // 编译报错,因为 `var2` 被借用了 +} +``` + +## 更深入的资料 + +Rust 还有很多很多其他类容 - 这只是 Rust 最基础的东西,帮助你了解 Rust 里面最重要的东西。 +如果想深入学习 Rust,可以去阅读 +[The Rust Programming Language](http://doc.rust-lang.org/book/index.html) +或者上 reddit [/r/rust](http://reddit.com/r/rust) 订阅。 +同时 irc.mozilla.org 的 #rust 频道上的小伙伴们也非常欢迎新来的朋友。 + +你可以在这个在线编译器 [Rust playpen](http://play.rust-lang.org) 上尝试 Rust 的一些特性 +或者上[官方网站](http://rust-lang.org). -- cgit v1.2.3 From 56171326c725f70cfdec99d8086d9c5dc8d1a211 Mon Sep 17 00:00:00 2001 From: = <=> Date: Sun, 12 Jul 2015 16:17:23 -0700 Subject: added chapel.html.markdown, performed a first pass at the tutorial, and the beginning readme of the tutorial. Currently missing topics [ reduction, scal, non-loop tuple expansion, whole array/partial array assignment] --- chapel.html.markdown | 722 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 722 insertions(+) create mode 100644 chapel.html.markdown diff --git a/chapel.html.markdown b/chapel.html.markdown new file mode 100644 index 00000000..a17222b9 --- /dev/null +++ b/chapel.html.markdown @@ -0,0 +1,722 @@ +--- +language: chapel +filename: learnchapel.chpl +contributors: + - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola.com/"] +lang: en +--- +What is Chapel? +=============== +You can read all about chapel at [Cray's official Chapel website](chapel.cray.com). +In short, Chapel is an open-source, high-productivity, parallel-programming language in development +at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. + +Chapel is currently in-development so there are occasional hiccups with +performance and language features, which is why you should write as much Chapel + +Your input, questions, and discoveries are important to us! +----------------------------------------------------------- +The more information you give the Chapel development team about issues you encounter with the language, +the better the language gets. +Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) +There is also a #chapel-developers hosted at chat.freenode.net. + +If you're really interested in the cutting edge compiler or contributing to the project, +the git repository for Chapel is open-source at [github](https://github.com/chapel-lang/chapel) +under the Apache v2.0 license + +Installing the Compiler +----------------------- +Chapel can be built and installed on your average 'nix machine (and cygwin). +Download the latest release version from https://github.com/chapel-lang/chapel/releases/ +and its as easy as +1. ```tar -xvf chapel-1.11.0.tar.gz``` +2. ```cd chapel-1.11.0``` +3. ```make``` +4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + +You will need to ```source util/setchplenv.*``` from the chapel directory every +time your terminal starts so its suggested that you drop that command in a script +that will get executed on startup (like .bashrc). + + +Chapel is easily installed with Brew for OS X +1. ```brew update``` +2. ```brew install chapel``` + +Who is this tutorial for? +------------------------- +This tutorial is for people who want to learn the ropes of chapel without having to +hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations +differ between one another. +It won't teach you how to develop amazingly performant code, and it's not exhaustive. +Refer to the [language specification](http://chapel.cray.com/language.html) +and the [library-documentation](http://chapel.cray.com/docs/latest/) for more details. + +Occasionally check here back to see if more topics have been added. + +```chapel +// Comments are C-family style +// one line comment +/* + multi-line comment +*/ + +// Basic printing +write( "Hello, " ); +writeln( "World!" ); +// write and writeln can take a list of things to print. +// each thing is printed right next to each other, so include your spacing! +writeln( "There are ", 3, " commas (\",\") in this line of code" ); +// Different output channels +stdout.writeln( "This goes to standard output (just like plain writeln() does)"); +stderr.writeln( "This goes to standard error" ); + +// Variables +// Variables dont have to be explicitly as long as the compiler can figure +// out the type that it will hold. +var myVar = 10; // 10 is an int, so myVar is implicitly an int +myVar = -10; +// var anError; // compile time error, dont know what type anError should be. + +// We can (and should) explicitly type things +var mySecondVar: real; // define mySecondVar as a real +var myThirdVar: real = -1.234; +mySecondVar = myThirdVar; + +// There are a number of basic types. +var myInt: int = -1000; // signed ints +var myUint: uint = 1234; // unsigned ints +var myReal: real = 9.876; // floating point numbers +var myImag: imag = 5.0i; // imaginary numbers +var myCplx: complex = 10 + 9i; // complex numbers +myCplx = myInt + myImag ; // another way to form complex numbers +var myBool: bool = false; // booleans +var myStr: string = "Some string..."; // strings + +// Some types can have sizes +var my8Int: int(8) = 10; // 8 bit (one byte) sized int; +var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real + +// Typecasting +var intFromReal = myReal : int; +// could also explicitly type intFromReal +// var intFromReal: int = myReal : int; + +// Operators +// Math operators +var a: int, thisInt = 1234, thatInt = 5678; +a = thisInt + thatInt; // Addition +a = thisInt * thatInt; // Multiplication +a = thisInt - thatInt; // Subtraction +a = thisInt / thatInt; // division +a = thisInt ** thatInt; // exponentiation +a = thisInt % thatInt; // remainder (modulo) + +// Logical Operators +var b: bool, thisBool = false, thatBool = true; +b = thisBool && thatBool; // logical and +b = thisBool || thatBool; // logical or +b = !thisBool; // logical negation + +// Relational Operators +b = thisInt > thatInt; // greater-than +b = thisInt >= thatInt; // greater-than-or-equal-to +b = thisInt < a && a <= thatInt; // less-than, and, less-than-or-equal-to +b = thisInt != thatInt; // not-equal-to +b = thisInt == thatInt; // equal-to + +// Bitwise operations +a = thisInt << 10; // left-bit-shift by 10 bits; +a = thatInt >> 5; // right-bit-shift by 5 bits; +a = ~thisInt; // bitwise-negation +a = thisInt ^ thatInt; // bitwise exclusive-or + +// Compound assignment operations +a += thisInt; // addition-equals ( a = a + thisInt;) +a *= thatInt; // times-equals ( a = a * thatInt; ) +b &&= thatBool; // logical-and-equals ( b = b && thatBool; ) +a <<= 3; // left-bit-shift-equals ( a = a << 10; ) +// and so on... +// Unlike other C family languages there are no +// pre/post-increment/decrement operators like +// ++j, --j, j++, j-- + + +// Swap operator +var temp_this = thisInt; +var temp_that = thatInt; +thisInt <=> thatInt; // Swap the values of thisInt and thatInt +writeln( (temp_this == thatInt) && (temp_that == thisInt) ); + +// We can also define operator overloads, +// which we'll cover with procedures. + +// Tuples +// tuples can be of the same type +var sameTup: 2*int = (10,-1); +// or different types +var diffTup: (int,real,complex) = (5, 1.928, myCplx); +// Accessed using array bracket notation +// However, tuples are all 1-indexed +writeln( "(", sameTup[1], ",", sameTup[2], ")" ); +writeln( diffTup ); +// Tuples can also be written into. +diffTup[1] = -1; +// Can also be used to easily write a collection of variables +// as is common in debugging +writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); + +// Type aliasing +type chroma = int; // type of a single hue +type RGBColor = 3*chroma; // type representing a full color +var black: RGBColor = ( 0,0,0 ); +var white: RGBColor = ( 255, 255, 255 ); + + + +// If-Then statements +// if-thens dont require parentheses around the condition +// as they do in C (however, we will use them) +// and a single line body can use the 'then' keyword instead of braces +// and else statements can be written similarly +// (but we're only going to show it once). +if 10 < 100 then + writeln( "All is well" ); + +if -1 < 1 then + writeln( "Continuing to believe reality" ); +else + writeln( "Send mathematician, something's wrong" ); + + +if ( 10 > 100 ) { + writeln( "Universe broken. Please reboot universe." ); +} + +if ( a % 2 == 0 ) { + writeln( a, " is even." ); +} else { + writeln( a, " is odd." ); +} + +if ( a % 3 == 0 ) { + writeln( a, " is even divisible by 3." ); +} else if ( a % 3 == 1 ){ + writeln( a, " is divided by 3 with a remainder of 1." ); +} else { + writeln( b, " is divided by 3 with a remainder of 2." ); +} + +// Ternary: if-then-else in a statement +var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; + +// Select statements +// Select statements are much like switch statements in other languages +// However, Select statements dont cascade like in C or Java +var inputOption = "anOption"; +select( inputOption ){ + when "anOption" do writeln( "Chose 'anOption'" ); + when "otherOption" { + writeln( "Chose 'otherOption'" ); + writeln( "Which has a body" ); + } + otherwise { + writeln( "Any other Input" ); + writeln( "the otherwise case doesn't need a do if the body is one line" ); + writeln( "Oh, and when statements dont cascade like the case statements" ); + writeln( "of other languages" ); + } +} + +// Loops +// While Loops +// While loops and Do-While loops are basically the same in every language. + +var j: int = 1; +var jSum: int = 0; +while( j <= 1000 ){ + jSum += j; + j += 1; // there are no ++j, --j, j++, j--, operators +} +writeln( jSum ); + +// basic Do-While loop +do{ + jSum += j; + j += 1; +}while( j <= 10000 ); +writeln( jSum ); + +// For loops +// For loops are much like those in python in that they iterate over a range. +// ranges themselves are types, and can be stuffed into variables +// (more about that later) + +for i in 1..10 do write( i , ", ") ; +writeln(); + +var iSum: int = 0; +for i in 1..1000 { + iSum += i; +} +writeln( iSum ); + +for x in 1..10 { + for y in 1..10 { + write( (x,y), "\t" ); + } + writeln(); +} + +// Ranges and Domains +// For-loops and arrays both use ranges and domains to +// define an index set that can be iterated over. +// Ranges are single dimensional +// Domains can be multi-dimensional and represent indicies +// of different types as well. +// They are types, and can be assigned into variables; +var range1to10: range = 1..10; // // 1, 2, 3, ... , 10 + +// Ranges can be strided using the 'by' operator. +// Note: the stridable=true is only necessary if we type the variable +var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 + +// The end point of a range can be determined using the count (#) operator +var rangeCount: range = -5..#12; // range from -5 to 6 + +// Can mix operators +var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5 +writeln( rangeCountBy ); + +// Can query properties of the range +// Print the first index, last index, number of indices, +// stride, and ask if 2 is include in the range +writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length, + rangeCountBy.stride, rangeCountBy.member( 2 ) ) ); + +for i in rangeCountBy{ + write( i, if i == rangeCountBy.last then "\n" else ", " ); +} + +// domains are similarly defined using range notation +var domain1to10: domain(1) = {1..10}; // domain from 1..10; +var twoDimensions: domain(2) = {-2..2,0..2}; // domain over two dimensions + +// Can iterate over the indices as tuples +for idx in twoDimensions do + write( idx , ", "); +writeln(); + +// Or can deconstruct the tuple +for (x,y) in twoDimensions { + write( (x,y), ", " ); +} +writeln(); + +// Associative domains act like sets +var intSet: domain(int); // empty set of ints +intSet += 1; +intSet += 2; +intSet += 3; +intSet += 1; // redundant add 1 +intSet -= 3; // remove 3 +writeln( intSet ); + + +// Arrays +// Array are similar to those of other languages. +// Their sizes are defined using ranges and domains. +// that represent their indices, but we'll touch more on those later +var intArray: [1..10] int; // array of integers defined using range literal + +// Accessed using bracket notation +for i in 1..10 do + intArray[i] = -i; +writeln( intArray ); +// we cannot access intArray[0] because it exists outside +// of the index set we defined (1..10) +// intArray[11] is illegal for the same reason. + +var realDomain: domain(2) = {1..5,1..7}; +var realArray: [realDomain] real; +// similarly we could have done: +// var realArray: [1..5,1..7] real; + +for i in 1..5 { + // use the range from 2nd dimension of the domain + for j in realDomain.dim(2) { + realArray[i,j] = -1.61803 * i + 0.5 * j; // access using index list + var idx: 2*int = (i,j); // note: 'index' is a keyword + realArray[idx] = - realArray[(i,j)]; // index using tuples + } +} + +// arrays have domains as members that we can iterate over +for idx in realArray.domain { // idx is, again, a 2*int tuple + realArray[idx] = 1 / realArray[idx[1],idx[2]]; // access by tuple and list +} + +writeln( realArray ); + +// can also iterate over the values of an array +var rSum: real = 0; +for value in realArray { + rSum += value; // read a value + value = rSum; // write a value +} +writeln( rSum, "\n", realArray ); + +// Using associative domains we can create associative arrays (dictionaries) +var dictDomain: domain(string) = { "one", "two" }; +var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; +dict["three"] = 3; +writeln( dict ); + + +// Procedures +// Chapel procedures have similar syntax to other languages functions. + +proc fibonacci( n : int ) : int { + if ( n == 0 || n == 1 ) then return n; + return fibonacci( n-1 ) + fibonacci( n-2 ); +} + +// input parameters can be untyped +proc doublePrint( thing ): void { + write( thing, " ", thing, "\n"); +} + +// return type can be inferred (as long as the compiler can figure it out) +proc addThree( n ) { + return n + 3; +} + +doublePrint( addThree( fibonacci( 20 ) ) ); + +// Can also take unlimited number of parameters +proc maxOf( x ...?k ) { + // x refers to a tuple of one type, with k elements + var maximum = x[1]; + for i in 2..k do maximum = if (maximum < x[i]) then x[i] else maximum; + return maximum; +} +writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); + +// the ? operator is called the query operator, and is used to take +// undetermined values (like tuple and array sizes, and generic types). + +// Taking arrays as parameters. +// The query operator is used to determine the domain of A. +// this is important to define the return type (if you wanted to) +proc invertArray( A: [?D] int ): [D] int{ + for a in A do a = -a; + return A; +} + +writeln( invertArray( intArray ) ); + +// Procedures can have default parameter values, and +// the parameters can be named in the call, even out of order +proc defaultsProc( x: int, y: real = 1.2634 ): (int,real){ + return (x,y); +} + +writeln( defaultsProc( 10 ) ); +writeln( defaultsProc( x=11 ) ); +writeln( defaultsProc( x=12, y=5.432 ) ); +writeln( defaultsProc( y=9.876, x=13 ) ); + +// Generic procedures can still retain type +// Here we define a procedure that takes two arguments +// of the same type, yet we dont define what that type is. +proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { + select( valueType ){ + when int do writeln( arg1, " and ", arg2, " are ints" ); + when real do writeln( arg1, " and ", arg2, " are reals" ); + otherwise writeln( arg1, " and ", arg2, " are somethings!" ); + } +} + +genericProc( 1, 2 ); +genericProc( 1.2, 2.3 ); +genericProc( 1.0+2.0i, 3.0+4.0i ); + +// We can also enforce a form of polymorphism with the 'where' clause +// This allows the compiler to decide which function to use. +// Note: that means that all information needs to be known at compile +// time. Hence, we use params here to assert that the arguments must +// be known at compile time. +proc whereProc( param N : int ): void + where ( N > 0 ) { + writeln( "N is greater than 0" ); +} + +proc whereProc( param N : int ): void + where ( N < 0 ) { + writeln( "N is less than 0" ); +} + +whereProc( 10 ); +whereProc( -1 ); +// whereProc( 0 ) would result in a compiler error because there +// are no functions that satisfy the where clause's condition. +// We could have defined a whereProc without a where clause that would +// then have been called. + +// Operator definitions are through procedures as well +// we can define the unary operators: +// + - ! ~ +// and the binary operators: +// + - * / % ** == <= >= < > << >> & | ˆ by +// += -= *= /= %= **= &= |= ˆ= <<= >>= <=> + +// boolean exclusive or operator +proc ^( left : bool, right : bool ): bool { + return (left || right) && !( left && right ); +} + +writeln( true ^ true ); +writeln( false ^ true ); +writeln( true ^ false ); +writeln( false ^ false ); + +// Define a * operator on any two types. +proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ + return (left, right ); +} + +writeln( 1 * "a" ); // uses our * operator +writeln( 1 * 2 ); // uses the original * operator + +/* +Note: You could break everything if you + get careless with your overloads. +This here will break everything. Dont do it. +proc +( left: int, right: int ): int{ + return left - right; +} +*/ + +// Classes +class MyClass { + // Member variables + var memberInt : int; + var memberBool : bool = true; + + // Classes have default constructors that dont need to be coded (see below) + // Our explicitly defined constructor + proc MyClass( val : real ){ + this.memberInt = ceil( val ): int; + } + + // Our explicitly defined destructor + proc ~MyClass( ){ + writeln( "MyClass Destructor called ", (this.memberInt, this.memberBool) ); + } + + // Class methods + proc setMemberInt( val: int ){ + this.memberInt = val; + } + + proc setMemberBool( val: bool ){ + this.memberBool = val; + } + + proc getMemberInt( ): int{ + return this.memberInt; + } + + proc getMemberBool(): bool { + return this.memberBool; + } + +} + +// Construct using default constructor, using default values +var myObject = new MyClass( 10 ); + myObject = new MyClass( memberInt = 10 ); // equivalent +writeln( myObject.getMemberInt() ); +// ... using our values +var myDiffObject = new MyClass( -1, true ); + myDiffObject = new MyClass( memberInt = -1, + memberBool = false ); // equivalent +writeln( (myDiffObject.getMemberInt(), myDiffObject.getMemberBool() )); + +// Construct using written constructor +var myOtherObject = new MyClass( 1.95 ); + myOtherObject = new MyClass( val = 1.95 ); // equivalent +writeln( myOtherObject.getMemberInt() ); + +// We can define an operator on our class as well but +// the definition has to be outside the class definition +proc +( A : MyClass, B : MyClass) : MyClass { + return new MyClass( memberInt = A.getMemberInt() + B.getMemberInt(), + memberBool = A.getMemberBool() || B.getMemberBool() ); +} + +var plusObject = myObject + myDiffObject; +writeln( (plusObject.getMemberInt(), plusObject.getMemberBool() ) ); + +// destruction +delete myObject; +delete myDiffObject; +delete myOtherObject; +delete plusObject; + +// Classes can inherit from one or more parent classes +class MyChildClass : MyClass { + var memberComplex: complex; +} + +// Generic Classes +class GenericClass { + type classType; + var classDomain: domain(1); + var classArray: [classDomain] classType; + + // Explicit constructor + proc GenericClass( type classType, elements : int ){ + this.classDomain = {1..#elements}; + } + + // Copy constructor + // Note: We still have to put the the type as an argument, but we can + // default to the type of the other object using the query (?) operator + // Further, we can take advantage of this to allow our copy constructor + // to copy classes of different types + proc GenericClass( other : GenericClass(?otherType), + type classType = otherType ) { + this.classDomain = other.classDomain; + // Copy and cast + [ idx in this.classDomain ] this[ idx ] = other[ idx ] : classType; + } + + // Define bracket notation on a GenericClass object + // i.e. objVar[ i ] or objVar( i ) + proc this( i : int ) ref : classType { + return this.classArray[ i ]; + } + + // Define an iterator for the class. + // i.e. for i in objVar do .... + iter these() ref : classType { + for i in this.classDomain do + yield this[i]; + } + +} + +var realList = new GenericClass( real, 10 ); +// We can assign to the array in the object using the bracket notation +for i in realList.classDomain do realList[i] = i + 1.0; +// We can iterate over a +for value in realList do write( value, ", " ); +writeln(); + +// Make a copy of realList using the copy constructor +var copyList = new GenericClass( realList ); +for value in copyList do write( value, ", " ); +writeln(); + +// make a copy of realList and change the type, also using the copy constructor +var copyNewTypeList = new GenericClass( realList, int ); +for value in copyNewTypeList do write( value, ", " ); +writeln(); + + +// Tasks +// A task is some work that will be done separately from +// the current task, and (if there are any available) in its own thread. + +// a synch statement will ensure that the progress of the +// main task will not progress until the children have synced back up. +sync { +// a begin statement will spin the body off into one new task + begin { + var a = 0; + for i in 1..1000 do a += 1; + writeln( "Done: ", a); + } + writeln( "spun off a task!"); +} +writeln( "Back together" ); + +proc printFibb( n: int ){ + writeln( "fibonacci(",n,") = ", fibonacci( n ) ); +} + +// a cobegin statement will spin each +// statement of the body into one new task +cobegin { + printFibb( 20 ); + printFibb( 10 ); + printFibb( 5 ); + { + // this is a nested statement body and thus is a single statement + // to the parent statement and is executed by a single task + writeln( "this gets" ); + writeln( "executed as" ); + writeln( "a whole" ); + } +} +// Notice here that the prints may happen in any order. + +// Coforall loop will create a new task for EACH iteration +// NOTE! coforall should be used only for creating tasks! +// Using it to iterating over an array or something like that is very a bad idea! + +var num_tasks = 10; // Number of tasks we want +coforall taskID in 1..#num_tasks { + writeln( "Hello from task# ", taskID ); +} +// Again we see that prints happen in any order. + +// forall loops are another parallel loop, but only create a smaller number +// of tasks, specifically dataParTasksPerLocale number of task (more later) +forall i in 1..100 { + write( i, ", "); +} +writeln(); +// Here we see that there are sections that are in order, followed by +// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ) +// this is because each task is taking on a chunk of the range 1..10 +// (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens +// in parallel. +// Your results may depend on your machine and configuration + +// For both the forall and coforall loops, the execution of the parent task +// will not continue until all the children sync up. + +// forall loops are particularly useful for parallel iteration over arrays +// Lets run an experiment to see how much faster a parallel loop is +use Time; // Import the Time module to use Timer objects +var timer: Timer; +var myBigArray: [{1..4000,1..4000}] real; // large array we will write into +// Serial Experiment +timer.start(); // start timer +for (x,y) in myBigArray.domain { // serial iteration + myBigArray[x,y] = (x:real) / (y:real); +} +timer.stop(); // stop timer +writeln( "Serial: ", timer.elapsed() ); // print elapsed time +timer.clear(); // clear timer for parallel loop + +// Parallel Experiment +timer.start(); // start timer +forall (x,y) in myBigArray.domain { // parallel iteration + myBigArray[x,y] = (x:real) / (y:real); +} +timer.stop(); // stop timer +writeln( "Parallel: ", timer.elapsed() ); // print elapsed time +timer.clear(); +// you may have noticed that (depending on how many cores you have) that +// the parallel loop went faster than the serial loop + +// A succinct way of writing a forall loop over an array: +[ val in myBigArray ] val = 1 / val; // iterate over values +// or +[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; // iterate over indicies + +``` \ No newline at end of file -- cgit v1.2.3 From 3ad75a4fb79e819a1ea5b2ab74bbfbb2c59c17fd Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:40:32 -0700 Subject: Minor fix removed .com from my (ian bertolacci) website link --- chapel.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index a17222b9..df9c1a44 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -2,7 +2,7 @@ language: chapel filename: learnchapel.chpl contributors: - - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola.com/"] + - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] lang: en --- What is Chapel? @@ -719,4 +719,4 @@ timer.clear(); // or [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; // iterate over indicies -``` \ No newline at end of file +``` -- cgit v1.2.3 From 2ba9af4b85de0a2214d3c4de0f1509440a41adef Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:43:42 -0700 Subject: Header modified Found an unfinished sentence, fixed it. --- chapel.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index df9c1a44..01826a9c 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -11,11 +11,10 @@ You can read all about chapel at [Cray's official Chapel website](chapel.cray.co In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -Chapel is currently in-development so there are occasional hiccups with -performance and language features, which is why you should write as much Chapel - Your input, questions, and discoveries are important to us! ----------------------------------------------------------- +Chapel is currently in-development so there are occasional hiccups with +performance and language features. The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) @@ -39,7 +38,6 @@ You will need to ```source util/setchplenv.*``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). - Chapel is easily installed with Brew for OS X 1. ```brew update``` 2. ```brew install chapel``` -- cgit v1.2.3 From cbbb833445e0e2b6223ce1c30943ed92ebc87ad7 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:45:18 -0700 Subject: List formatting Lists needed a space before numbers to actually become html list formatted. --- chapel.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 01826a9c..9005b05f 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -29,18 +29,18 @@ Installing the Compiler Chapel can be built and installed on your average 'nix machine (and cygwin). Download the latest release version from https://github.com/chapel-lang/chapel/releases/ and its as easy as -1. ```tar -xvf chapel-1.11.0.tar.gz``` -2. ```cd chapel-1.11.0``` -3. ```make``` -4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + 1. ```tar -xvf chapel-1.11.0.tar.gz``` + 2. ```cd chapel-1.11.0``` + 3. ```make``` + 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` You will need to ```source util/setchplenv.*``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X -1. ```brew update``` -2. ```brew install chapel``` + 1. ```brew update``` + 2. ```brew install chapel``` Who is this tutorial for? ------------------------- -- cgit v1.2.3 From 7ff3bd31d86009aec4d14292b2cbd02a3352e70f Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:48:34 -0700 Subject: Link and header fix 1. put latest release url under the text [download the latest ....] 2. changed '... important to us!' to '... important to the developers!' so not to confuse the us (chapel dev team) with the tutorial people (learnxinyminutes) --- chapel.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 9005b05f..db566454 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -11,8 +11,8 @@ You can read all about chapel at [Cray's official Chapel website](chapel.cray.co In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -Your input, questions, and discoveries are important to us! ------------------------------------------------------------ +Your input, questions, and discoveries are important to the developers! +----------------------------------------------------------------------- Chapel is currently in-development so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter with the language, @@ -27,7 +27,7 @@ under the Apache v2.0 license Installing the Compiler ----------------------- Chapel can be built and installed on your average 'nix machine (and cygwin). -Download the latest release version from https://github.com/chapel-lang/chapel/releases/ +[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as 1. ```tar -xvf chapel-1.11.0.tar.gz``` 2. ```cd chapel-1.11.0``` -- cgit v1.2.3 From 70a5440d4c4575dfe07495cadc9aa48f1d85d016 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:49:49 -0700 Subject: Bad Link fix fixed a link that was suppose to go to the chapel.cray.com site, but did not. --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index db566454..90b64854 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -7,7 +7,7 @@ lang: en --- What is Chapel? =============== -You can read all about chapel at [Cray's official Chapel website](chapel.cray.com). +You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -- cgit v1.2.3 From 28f2817ac36e6fd85bff29e8dcda71f452d4b97e Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:50:55 -0700 Subject: removed hyphen removed hyphen from library-documentation --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 90b64854..1c5bcc15 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -49,7 +49,7 @@ hear about what fiber mixture the ropes are, or how they were braided, or how th differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) -and the [library-documentation](http://chapel.cray.com/docs/latest/) for more details. +and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check here back to see if more topics have been added. -- cgit v1.2.3 From 7bdcbc834e25c89a4ae59ac6282e82e75f6f7fb6 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Mon, 13 Jul 2015 16:42:46 -0700 Subject: removed IRC node. That node refers to people developing in the compiler, no developers using the language --- chapel.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 1c5bcc15..3e6c7bb6 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -18,7 +18,6 @@ performance and language features. The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) -There is also a #chapel-developers hosted at chat.freenode.net. If you're really interested in the cutting edge compiler or contributing to the project, the git repository for Chapel is open-source at [github](https://github.com/chapel-lang/chapel) -- cgit v1.2.3 From 2a41844229c841894b58f64b1841802e24483803 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 07:40:53 -0700 Subject: changed some wording in header. added tuple expansion --- chapel.html.markdown | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 3e6c7bb6..3563e4c1 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -17,11 +17,10 @@ Chapel is currently in-development so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. -Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) +Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). -If you're really interested in the cutting edge compiler or contributing to the project, -the git repository for Chapel is open-source at [github](https://github.com/chapel-lang/chapel) -under the Apache v2.0 license +If you're really interested in the development of the compiler or contributing to the project, +[check out the master Github repository](https://github.com/chapel-lang/chapel). Installing the Compiler ----------------------- @@ -33,7 +32,7 @@ and its as easy as 3. ```make``` 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` -You will need to ```source util/setchplenv.*``` from the chapel directory every +You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). @@ -160,10 +159,14 @@ writeln( "(", sameTup[1], ",", sameTup[2], ")" ); writeln( diffTup ); // Tuples can also be written into. diffTup[1] = -1; -// Can also be used to easily write a collection of variables -// as is common in debugging +// you can expand tuples as well +var (tupInt, tupReal, tupCplx) = diffTup; +writeln( diffTup == (tupInt, tupReal, tupCplx) ); +// Can also be used to easily write a collection of +// variables as a list (common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); + // Type aliasing type chroma = int; // type of a single hue type RGBColor = 3*chroma; // type representing a full color -- cgit v1.2.3 From df0cd1395db5178aabc68bf17d48a8278f16d749 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 17:30:09 -0700 Subject: numerous slight modifications, and additions. Notable: added const, param, config --- chapel.html.markdown | 197 +++++++++++++++++++++++++++------------------------ 1 file changed, 103 insertions(+), 94 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 3563e4c1..6382f75a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -8,15 +8,12 @@ lang: en What is Chapel? =============== You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). -In short, Chapel is an open-source, high-productivity, parallel-programming language in development -at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. +In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- -Chapel is currently in-development so there are occasional hiccups with -performance and language features. -The more information you give the Chapel development team about issues you encounter with the language, -the better the language gets. +Chapel is currently in-development so there are occasional hiccups with performance and language features. +The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). If you're really interested in the development of the compiler or contributing to the project, @@ -32,9 +29,7 @@ and its as easy as 3. ```make``` 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` -You will need to ```source util/setchplenv.EXT``` from the chapel directory every -time your terminal starts so its suggested that you drop that command in a script -that will get executed on startup (like .bashrc). +You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X 1. ```brew update``` @@ -42,12 +37,9 @@ Chapel is easily installed with Brew for OS X Who is this tutorial for? ------------------------- -This tutorial is for people who want to learn the ropes of chapel without having to -hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations -differ between one another. +This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) -and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check here back to see if more topics have been added. @@ -69,11 +61,11 @@ stdout.writeln( "This goes to standard output (just like plain writeln() does)") stderr.writeln( "This goes to standard error" ); // Variables -// Variables dont have to be explicitly as long as the compiler can figure -// out the type that it will hold. +// Variables dont have to be explicitly typed as long as +// the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; -// var anError; // compile time error, dont know what type anError should be. +// var anError; // this would be a compile time error. // We can (and should) explicitly type things var mySecondVar: real; // define mySecondVar as a real @@ -96,10 +88,26 @@ var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real // Typecasting var intFromReal = myReal : int; -// could also explicitly type intFromReal -// var intFromReal: int = myReal : int; +var intFromReal2: int = myReal : int; + +// consts are constants, they cannot be changed after set in runtime +const almostPi: real = 11.0/7.0; +// params are constants whose value must be known statically at compile time +// Like consts, they cannot be changed during runtime +param compileTimeConst: int = 16; + +// The config modifier allows values to be set at the command line +// and is much easier that the usual getOpts debacle +// config vars and consts can be changed through the command line at run time +config var varCmdLineArg: int = -123; +config const constCmdLineArg: int = 777; +// set with --VarName=Value or --VarName Value at run time + +// config params can be set at compile time +config param paramCmdLineArg: bool = false; +writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); +//set config with --set paramCmdLineArg=value at compile time -// Operators // Math operators var a: int, thisInt = 1234, thatInt = 5678; a = thisInt + thatInt; // Addition @@ -138,12 +146,11 @@ a <<= 3; // left-bit-shift-equals ( a = a << 10; ) // pre/post-increment/decrement operators like // ++j, --j, j++, j-- - // Swap operator -var temp_this = thisInt; -var temp_that = thatInt; +var old_this = thisInt; +var old_that = thatInt; thisInt <=> thatInt; // Swap the values of thisInt and thatInt -writeln( (temp_this == thatInt) && (temp_that == thisInt) ); +writeln( (old_this == thatInt) && (old_that == thisInt) ); // We can also define operator overloads, // which we'll cover with procedures. @@ -162,13 +169,13 @@ diffTup[1] = -1; // you can expand tuples as well var (tupInt, tupReal, tupCplx) = diffTup; writeln( diffTup == (tupInt, tupReal, tupCplx) ); -// Can also be used to easily write a collection of -// variables as a list (common in debugging) +// Can also be used to easily write a collection +// of variables as a list (common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); // Type aliasing -type chroma = int; // type of a single hue +type chroma = int; // type of a single hue type RGBColor = 3*chroma; // type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); @@ -176,11 +183,11 @@ var white: RGBColor = ( 255, 255, 255 ); // If-Then statements -// if-thens dont require parentheses around the condition +// if-thens dont require parentheses around the condition // as they do in C (however, we will use them) -// and a single line body can use the 'then' keyword instead of braces -// and else statements can be written similarly -// (but we're only going to show it once). +// A single line body can use the 'then' keyword instead of +// braces and else statements can be written similarly + if 10 < 100 then writeln( "All is well" ); @@ -211,7 +218,6 @@ if ( a % 3 == 0 ) { // Ternary: if-then-else in a statement var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; -// Select statements // Select statements are much like switch statements in other languages // However, Select statements dont cascade like in C or Java var inputOption = "anOption"; @@ -229,10 +235,7 @@ select( inputOption ){ } } -// Loops -// While Loops // While loops and Do-While loops are basically the same in every language. - var j: int = 1; var jSum: int = 0; while( j <= 1000 ){ @@ -248,11 +251,10 @@ do{ }while( j <= 10000 ); writeln( jSum ); -// For loops + // For loops are much like those in python in that they iterate over a range. -// ranges themselves are types, and can be stuffed into variables +// Ranges themselves are types, and can be stuffed into variables // (more about that later) - for i in 1..10 do write( i , ", ") ; writeln(); @@ -273,14 +275,23 @@ for x in 1..10 { // For-loops and arrays both use ranges and domains to // define an index set that can be iterated over. // Ranges are single dimensional -// Domains can be multi-dimensional and represent indicies -// of different types as well. +// Domains can be multi-dimensional and can +// represent indicies of different types as well. // They are types, and can be assigned into variables; var range1to10: range = 1..10; // // 1, 2, 3, ... , 10 +var range2to11 = 2..11; // 2, 3, 4, ..., 11 + +//ranges can be unbounded +var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... +var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 +// Note: the range(boundedType= ... ) is only +// necessary if we explicitly type the variable // Ranges can be strided using the 'by' operator. -// Note: the stridable=true is only necessary if we type the variable var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 +var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 +// Note: the range(stridable=true) is only +// necessary if we explicitly type the variable // The end point of a range can be determined using the count (#) operator var rangeCount: range = -5..#12; // range from -5 to 6 @@ -299,9 +310,11 @@ for i in rangeCountBy{ write( i, if i == rangeCountBy.last then "\n" else ", " ); } -// domains are similarly defined using range notation -var domain1to10: domain(1) = {1..10}; // domain from 1..10; -var twoDimensions: domain(2) = {-2..2,0..2}; // domain over two dimensions +// Rectangular domains are similarly defined using range notation +var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; +var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges +var thirdDim: range = 1..16; +var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable // Can iterate over the indices as tuples for idx in twoDimensions do @@ -310,38 +323,37 @@ writeln(); // Or can deconstruct the tuple for (x,y) in twoDimensions { - write( (x,y), ", " ); + write( "(", x, ", ", y, ")", ", " ); } writeln(); // Associative domains act like sets -var intSet: domain(int); // empty set of ints -intSet += 1; -intSet += 2; -intSet += 3; -intSet += 1; // redundant add 1 -intSet -= 3; // remove 3 -writeln( intSet ); +var stringSet: domain(string); // empty set of strings +stringSet += "a"; +stringSet += "b"; +stringSet += "c"; +stringSet += "a"; // redundant add "a" +stringSet -= "c"; // remove "c" +writeln( stringSet ); -// Arrays // Array are similar to those of other languages. -// Their sizes are defined using ranges and domains. -// that represent their indices, but we'll touch more on those later -var intArray: [1..10] int; // array of integers defined using range literal +// Their sizes are defined using domains that represent their indices +var intArray: [1..10] int; +var intArray2: [{1..10}] int; //equivalent // Accessed using bracket notation for i in 1..10 do intArray[i] = -i; writeln( intArray ); // we cannot access intArray[0] because it exists outside -// of the index set we defined (1..10) +// of the index set, {1..10}, we defined it to have // intArray[11] is illegal for the same reason. var realDomain: domain(2) = {1..5,1..7}; var realArray: [realDomain] real; -// similarly we could have done: -// var realArray: [1..5,1..7] real; +var realArray2: [1..5,1..7] real; // equivalent +var realArray3: [{1..5,1..7}] real; // equivalent for i in 1..5 { // use the range from 2nd dimension of the domain @@ -353,7 +365,7 @@ for i in 1..5 { } // arrays have domains as members that we can iterate over -for idx in realArray.domain { // idx is, again, a 2*int tuple +for idx in realArray.domain { // again, idx is a 2*int tuple realArray[idx] = 1 / realArray[idx[1],idx[2]]; // access by tuple and list } @@ -373,16 +385,13 @@ var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; dict["three"] = 3; writeln( dict ); - -// Procedures // Chapel procedures have similar syntax to other languages functions. - proc fibonacci( n : int ) : int { - if ( n == 0 || n == 1 ) then return n; + if ( n <= 1 ) then return n; return fibonacci( n-1 ) + fibonacci( n-2 ); } -// input parameters can be untyped +// input parameters can be untyped (a generic procedure) proc doublePrint( thing ): void { write( thing, " ", thing, "\n"); } @@ -394,7 +403,7 @@ proc addThree( n ) { doublePrint( addThree( fibonacci( 20 ) ) ); -// Can also take unlimited number of parameters +// Can also take 'unlimited' number of parameters proc maxOf( x ...?k ) { // x refers to a tuple of one type, with k elements var maximum = x[1]; @@ -404,7 +413,7 @@ proc maxOf( x ...?k ) { writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); // the ? operator is called the query operator, and is used to take -// undetermined values (like tuple and array sizes, and generic types). +// undetermined values (like tuple or array sizes, and generic types). // Taking arrays as parameters. // The query operator is used to determine the domain of A. @@ -427,9 +436,9 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// Generic procedures can still retain type -// Here we define a procedure that takes two arguments -// of the same type, yet we dont define what that type is. +// We can query the type of arguments to make safer generic procedures +// Here we define a procedure that takes two arguments of +// the same type, yet we dont define what that type is. proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { select( valueType ){ when int do writeln( arg1, " and ", arg2, " are ints" ); @@ -481,24 +490,24 @@ writeln( false ^ true ); writeln( true ^ false ); writeln( false ^ false ); -// Define a * operator on any two types. +// Define a * operator on any two types that returns a tupe of those types proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ return (left, right ); } writeln( 1 * "a" ); // uses our * operator -writeln( 1 * 2 ); // uses the original * operator +writeln( 1 * 2 ); // uses the original * operator /* -Note: You could break everything if you - get careless with your overloads. -This here will break everything. Dont do it. +Note: You could break everything if you get careless with your overloads. +This here will break everything. Don't do it. proc +( left: int, right: int ): int{ return left - right; } */ -// Classes +// Classes are similar to those in C++ and Java. +// They currently lack privatization class MyClass { // Member variables var memberInt : int; @@ -541,8 +550,8 @@ writeln( myObject.getMemberInt() ); // ... using our values var myDiffObject = new MyClass( -1, true ); myDiffObject = new MyClass( memberInt = -1, - memberBool = false ); // equivalent -writeln( (myDiffObject.getMemberInt(), myDiffObject.getMemberBool() )); + memberBool = true ); // equivalent +writeln( myDiffObject ); // Construct using written constructor var myOtherObject = new MyClass( 1.95 ); @@ -557,7 +566,7 @@ proc +( A : MyClass, B : MyClass) : MyClass { } var plusObject = myObject + myDiffObject; -writeln( (plusObject.getMemberInt(), plusObject.getMemberBool() ) ); +writeln( plusObject ); // destruction delete myObject; @@ -609,9 +618,11 @@ class GenericClass { } var realList = new GenericClass( real, 10 ); -// We can assign to the array in the object using the bracket notation +// We can assign to the member array of the object using the bracket +// notation that we defined ( proc this( i: int ){ ... } ) for i in realList.classDomain do realList[i] = i + 1.0; -// We can iterate over a +// We can iterate over the values in our list with the iterator +// we defined ( iter these(){ ... } ) for value in realList do write( value, ", " ); writeln(); @@ -626,11 +637,10 @@ for value in copyNewTypeList do write( value, ", " ); writeln(); -// Tasks -// A task is some work that will be done separately from -// the current task, and (if there are any available) in its own thread. +// A task is some work that will be done separately from the current +// task, and (if there are any available) in its own thread. -// a synch statement will ensure that the progress of the +// a sync statement will ensure that the progress of the // main task will not progress until the children have synced back up. sync { // a begin statement will spin the body off into one new task @@ -661,20 +671,19 @@ cobegin { writeln( "a whole" ); } } -// Notice here that the prints may happen in any order. +// Notice here that the prints from each statement may happen in any order. // Coforall loop will create a new task for EACH iteration -// NOTE! coforall should be used only for creating tasks! -// Using it to iterating over an array or something like that is very a bad idea! - var num_tasks = 10; // Number of tasks we want coforall taskID in 1..#num_tasks { writeln( "Hello from task# ", taskID ); } // Again we see that prints happen in any order. +// NOTE! coforall should be used only for creating tasks! +// Using it to iterating over a structure is very a bad idea! // forall loops are another parallel loop, but only create a smaller number -// of tasks, specifically dataParTasksPerLocale number of task (more later) +// of tasks, specifically --dataParTasksPerLocale=number of task forall i in 1..100 { write( i, ", "); } @@ -715,8 +724,8 @@ timer.clear(); // the parallel loop went faster than the serial loop // A succinct way of writing a forall loop over an array: -[ val in myBigArray ] val = 1 / val; // iterate over values -// or -[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; // iterate over indicies - +// iterate over values +[ val in myBigArray ] val = 1 / val; +// or iterate over indicies +[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; ``` -- cgit v1.2.3 From 6a6673b1540eda903981bdaccc844a5fc802a216 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Tue, 14 Jul 2015 17:32:00 -0700 Subject: Fixed almost pi 22/7ths is closer to pi than 11/7ths. Almost twice as close! --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 6382f75a..fd01b0f2 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -91,7 +91,7 @@ var intFromReal = myReal : int; var intFromReal2: int = myReal : int; // consts are constants, they cannot be changed after set in runtime -const almostPi: real = 11.0/7.0; +const almostPi: real = 22.0/7.0; // params are constants whose value must be known statically at compile time // Like consts, they cannot be changed during runtime param compileTimeConst: int = 16; -- cgit v1.2.3 From e8b259f4c6fa71cea3ba9d0f65469b2a5eb56da6 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 17:44:55 -0700 Subject: Moved majority of header to bottom. Less preachy? --- chapel.html.markdown | 77 +++++++++++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 34 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index fd01b0f2..799d32c3 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -5,43 +5,11 @@ contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] lang: en --- -What is Chapel? -=============== + You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -Your input, questions, and discoveries are important to the developers! ------------------------------------------------------------------------ -Chapel is currently in-development so there are occasional hiccups with performance and language features. -The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. -Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). - -If you're really interested in the development of the compiler or contributing to the project, -[check out the master Github repository](https://github.com/chapel-lang/chapel). - -Installing the Compiler ------------------------ -Chapel can be built and installed on your average 'nix machine (and cygwin). -[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) -and its as easy as - 1. ```tar -xvf chapel-1.11.0.tar.gz``` - 2. ```cd chapel-1.11.0``` - 3. ```make``` - 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` - -You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). - -Chapel is easily installed with Brew for OS X - 1. ```brew update``` - 2. ```brew install chapel``` - -Who is this tutorial for? -------------------------- -This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. -It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. - -Occasionally check here back to see if more topics have been added. +More information and support can be found at the bottom of this document. ```chapel // Comments are C-family style @@ -729,3 +697,44 @@ timer.clear(); // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; ``` +Who is this tutorial for? +------------------------- +This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. +It won't teach you how to develop amazingly performant code, and it's not exhaustive. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. + +Occasionally check back here and on the Chapel site to see if more topics have been added or more tutorials created. + +Your input, questions, and discoveries are important to the developers! +----------------------------------------------------------------------- +The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. +The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. +Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). + +If you're really interested in the development of the compiler or contributing to the project, +[check out the master Github repository](https://github.com/chapel-lang/chapel). +It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0). + +Installing the Compiler +----------------------- +Chapel can be built and installed on your average 'nix machine (and cygwin). +[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) +and its as easy as + 1. ```tar -xvf chapel-1.11.0.tar.gz``` + 2. ```cd chapel-1.11.0``` + 3. ```make``` + 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + +You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). + +Chapel is easily installed with Brew for OS X + 1. ```brew update``` + 2. ```brew install chapel``` + +Compiling Code +-------------- +Builds like other compilers +```chpl myFile.chpl -o myExe`` + +A notable argument: + * ``--fast``: enables a number of optimizations and disables array bounds checks. Only enable when application is stable. -- cgit v1.2.3 From 343ae6ca1bd908aedfabe1dad948e4efff449628 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 17:49:59 -0700 Subject: Almost last update. Small changes to wording --- chapel.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 799d32c3..5633214a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -703,7 +703,7 @@ This tutorial is for people who want to learn the ropes of chapel without having It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. -Occasionally check back here and on the Chapel site to see if more topics have been added or more tutorials created. +Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- @@ -734,7 +734,7 @@ Chapel is easily installed with Brew for OS X Compiling Code -------------- Builds like other compilers -```chpl myFile.chpl -o myExe`` +```chpl myFile.chpl -o myExe``` A notable argument: - * ``--fast``: enables a number of optimizations and disables array bounds checks. Only enable when application is stable. + * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From 2e7ebaa3b940ec9de04f2266138abca58becaf30 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 18:40:53 -0700 Subject: A number of edits. Some cosmetic. Added iterators, argument/return intents --- chapel.html.markdown | 129 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 87 insertions(+), 42 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 5633214a..ecbab2a2 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -28,7 +28,6 @@ writeln( "There are ", 3, " commas (\",\") in this line of code" ); stdout.writeln( "This goes to standard output (just like plain writeln() does)"); stderr.writeln( "This goes to standard error" ); -// Variables // Variables dont have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int @@ -123,39 +122,31 @@ writeln( (old_this == thatInt) && (old_that == thisInt) ); // We can also define operator overloads, // which we'll cover with procedures. -// Tuples -// tuples can be of the same type +// Tuples can be of the same type var sameTup: 2*int = (10,-1); +var sameTup2 = (11, -6); // or different types var diffTup: (int,real,complex) = (5, 1.928, myCplx); +var diffTupe2 = ( 7, 5.64, 6.0+1.5i ); // Accessed using array bracket notation // However, tuples are all 1-indexed writeln( "(", sameTup[1], ",", sameTup[2], ")" ); writeln( diffTup ); // Tuples can also be written into. diffTup[1] = -1; -// you can expand tuples as well +// Can expand tuple values into their own variables var (tupInt, tupReal, tupCplx) = diffTup; writeln( diffTup == (tupInt, tupReal, tupCplx) ); -// Can also be used to easily write a collection -// of variables as a list (common in debugging) +// Useful for writing a list of variables ( as is common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); - // Type aliasing type chroma = int; // type of a single hue type RGBColor = 3*chroma; // type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); - - -// If-Then statements -// if-thens dont require parentheses around the condition -// as they do in C (however, we will use them) -// A single line body can use the 'then' keyword instead of -// braces and else statements can be written similarly - +// if-then-else works just like any other C-family language if 10 < 100 then writeln( "All is well" ); @@ -164,7 +155,6 @@ if -1 < 1 then else writeln( "Send mathematician, something's wrong" ); - if ( 10 > 100 ) { writeln( "Universe broken. Please reboot universe." ); } @@ -219,7 +209,6 @@ do{ }while( j <= 10000 ); writeln( jSum ); - // For loops are much like those in python in that they iterate over a range. // Ranges themselves are types, and can be stuffed into variables // (more about that later) @@ -245,9 +234,11 @@ for x in 1..10 { // Ranges are single dimensional // Domains can be multi-dimensional and can // represent indicies of different types as well. -// They are types, and can be assigned into variables; -var range1to10: range = 1..10; // // 1, 2, 3, ... , 10 +// They are first-class citizen types, and can be assigned into variables +var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 +var rangeThistoThat: range = thisInt..thatInt; // using variables +var rangeEmpty: range = 100..-100 ; // this is a valid, but empty range //ranges can be unbounded var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... @@ -257,10 +248,12 @@ var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 // Ranges can be strided using the 'by' operator. var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 -var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 // Note: the range(stridable=true) is only // necessary if we explicitly type the variable +// Use by to create a reverse range +var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 + // The end point of a range can be determined using the count (#) operator var rangeCount: range = -5..#12; // range from -5 to 6 @@ -278,7 +271,7 @@ for i in rangeCountBy{ write( i, if i == rangeCountBy.last then "\n" else ", " ); } -// Rectangular domains are similarly defined using range notation +// Rectangular domains are defined using the same range syntax var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges var thirdDim: range = 1..16; @@ -324,8 +317,7 @@ var realArray2: [1..5,1..7] real; // equivalent var realArray3: [{1..5,1..7}] real; // equivalent for i in 1..5 { - // use the range from 2nd dimension of the domain - for j in realDomain.dim(2) { + for j in realDomain.dim(2) { // only use the 2nd dimension of the domain realArray[i,j] = -1.61803 * i + 0.5 * j; // access using index list var idx: 2*int = (i,j); // note: 'index' is a keyword realArray[idx] = - realArray[(i,j)]; // index using tuples @@ -351,7 +343,7 @@ writeln( rSum, "\n", realArray ); var dictDomain: domain(string) = { "one", "two" }; var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; dict["three"] = 3; -writeln( dict ); +for key in dictDomain do writeln( dict[key] ); // Chapel procedures have similar syntax to other languages functions. proc fibonacci( n : int ) : int { @@ -404,7 +396,40 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// We can query the type of arguments to make safer generic procedures +// intent modifiers on the arguments convey how +// those arguments are passed to the procedure +// in: copy arg in, but not out +// out: copy arg out, but not in +// inout: copy arg in, copy arg out +// ref: pass arg by reference +proc intentsProc( in inarg, out outarg, inout inoutarg, ref refarg ){ + writeln( "Inside Before: ", (inarg, outarg, inoutarg, refarg) ); + inarg = inarg + 100; + outarg = outarg + 100; + inoutarg = inoutarg + 100; + refarg = refarg + 100; + writeln( "Inside After: ", (inarg, outarg, inoutarg, refarg) ); +} + +var inVar: int = 1; +var outVar: int = 2; +var inoutVar: int = 3; +var refVar: int = 4; +writeln( "Outside Before: ", (inVar, outVar, inoutVar, refVar) ); +intentsProc( inVar, outVar, inoutVar, refVar ); +writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) ); + +// Similarly we can define intents on the return type +proc makeArray( elems: int, startNumber: int ) ref : [1..#elems] int { + var array: [1..#elems] int; + for idx in array.domain do array[idx] = startNumber + idx; + return array; +} +writeln( makeArray( 10, -1 ) ); +// this makes more practical sense for class methods where references to +// elements in a data-structure are returned via a method or iterator + +// We can query the type of arguments to generic procedures // Here we define a procedure that takes two arguments of // the same type, yet we dont define what that type is. proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { @@ -421,9 +446,8 @@ genericProc( 1.0+2.0i, 3.0+4.0i ); // We can also enforce a form of polymorphism with the 'where' clause // This allows the compiler to decide which function to use. -// Note: that means that all information needs to be known at compile -// time. Hence, we use params here to assert that the arguments must -// be known at compile time. +// Note: that means that all information needs to be known at compile time. +// The param modifier on the arg is used to enforce this constraint. proc whereProc( param N : int ): void where ( N > 0 ) { writeln( "N is greater than 0" ); @@ -474,6 +498,25 @@ proc +( left: int, right: int ): int{ } */ +// iterators are a close cousin to the procedure. +// However, instead of returning a single value, +// iterators yield many values to a loop. +// This is useful when a complicated set or order of iterations is needed but +// allows the code defining the iterations to be separate from the loop body. +iter oddsThenEvens( N: int ): int { + for i in 1..N by 2 { + yield i; // yield values instead of returning. + } + + for i in 2..N by 2 { + yield i; + } +} + +for i in oddsThenEvens( 10 ) do write( i, ", " ); +writeln(); + + // Classes are similar to those in C++ and Java. // They currently lack privatization class MyClass { @@ -567,16 +610,18 @@ class GenericClass { type classType = otherType ) { this.classDomain = other.classDomain; // Copy and cast - [ idx in this.classDomain ] this[ idx ] = other[ idx ] : classType; + for idx in this.classDomain do this[ idx ] = other[ idx ] : classType; } - // Define bracket notation on a GenericClass object + // Define bracket notation on a GenericClass + // object so it can behave like a normal array // i.e. objVar[ i ] or objVar( i ) proc this( i : int ) ref : classType { return this.classArray[ i ]; } - // Define an iterator for the class. + // Define an iterator for the class to + // yield values from the array to a loop // i.e. for i in objVar do .... iter these() ref : classType { for i in this.classDomain do @@ -604,19 +649,20 @@ var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); writeln(); +// Parallelism +// In other languages, parallelism is typically this is done with +// complicated libraries and strange class structure hierarchies. +// Chapel has it baked right into the language. -// A task is some work that will be done separately from the current -// task, and (if there are any available) in its own thread. - +// A begin statement will spin the body of that statement off into one new task. // a sync statement will ensure that the progress of the // main task will not progress until the children have synced back up. sync { -// a begin statement will spin the body off into one new task - begin { + begin { // start of new task's body var a = 0; for i in 1..1000 do a += 1; writeln( "Done: ", a); - } + } // end of new tasks body writeln( "spun off a task!"); } writeln( "Back together" ); @@ -625,12 +671,11 @@ proc printFibb( n: int ){ writeln( "fibonacci(",n,") = ", fibonacci( n ) ); } -// a cobegin statement will spin each -// statement of the body into one new task +// a cobegin statement will spin each statement of the body into one new task cobegin { - printFibb( 20 ); - printFibb( 10 ); - printFibb( 5 ); + printFibb( 20 ); // new task + printFibb( 10 ); // new task + printFibb( 5 ); // new task { // this is a nested statement body and thus is a single statement // to the parent statement and is executed by a single task -- cgit v1.2.3 From 7640ea4a306b979912d63d646864da824103c082 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 19:07:59 -0700 Subject: Some rewriting, hopefully the last commit before pull request --- chapel.html.markdown | 276 +++++++++++++++++++++++++++------------------------ 1 file changed, 145 insertions(+), 131 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index ecbab2a2..8b41dc32 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -25,29 +25,30 @@ writeln( "World!" ); // each thing is printed right next to each other, so include your spacing! writeln( "There are ", 3, " commas (\",\") in this line of code" ); // Different output channels -stdout.writeln( "This goes to standard output (just like plain writeln() does)"); +stdout.writeln( "This goes to standard output (just like plain writeln( ) does)"); stderr.writeln( "This goes to standard error" ); // Variables dont have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; +var mySecondVar = myVar; // var anError; // this would be a compile time error. // We can (and should) explicitly type things -var mySecondVar: real; // define mySecondVar as a real -var myThirdVar: real = -1.234; -mySecondVar = myThirdVar; +var myThirdVar: real; // define mySecondVar as a real +var myFourthVar: real = -1.234; +myThirdVar = myFourthVar; // There are a number of basic types. -var myInt: int = -1000; // signed ints -var myUint: uint = 1234; // unsigned ints -var myReal: real = 9.876; // floating point numbers -var myImag: imag = 5.0i; // imaginary numbers -var myCplx: complex = 10 + 9i; // complex numbers -myCplx = myInt + myImag ; // another way to form complex numbers -var myBool: bool = false; // booleans -var myStr: string = "Some string..."; // strings +var myInt: int = -1000; // Signed ints +var myUint: uint = 1234; // Unsigned ints +var myReal: real = 9.876; // Floating point numbers +var myImag: imag = 5.0i; // Imaginary numbers +var myCplx: complex = 10 + 9i; // Complex numbers +myCplx = myInt + myImag ; // Another way to form complex numbers +var myBool: bool = false; // Booleans +var myStr: string = "Some string..."; // Strings // Some types can have sizes var my8Int: int(8) = 10; // 8 bit (one byte) sized int; @@ -59,6 +60,7 @@ var intFromReal2: int = myReal : int; // consts are constants, they cannot be changed after set in runtime const almostPi: real = 22.0/7.0; + // params are constants whose value must be known statically at compile time // Like consts, they cannot be changed during runtime param compileTimeConst: int = 16; @@ -68,47 +70,47 @@ param compileTimeConst: int = 16; // config vars and consts can be changed through the command line at run time config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; -// set with --VarName=Value or --VarName Value at run time +// Set with --VarName=Value or --VarName Value at run time // config params can be set at compile time config param paramCmdLineArg: bool = false; writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); -//set config with --set paramCmdLineArg=value at compile time +// Set config with --set paramCmdLineArg=value at compile time // Math operators var a: int, thisInt = 1234, thatInt = 5678; a = thisInt + thatInt; // Addition a = thisInt * thatInt; // Multiplication a = thisInt - thatInt; // Subtraction -a = thisInt / thatInt; // division -a = thisInt ** thatInt; // exponentiation -a = thisInt % thatInt; // remainder (modulo) +a = thisInt / thatInt; // Division +a = thisInt ** thatInt; // Exponentiation +a = thisInt % thatInt; // Remainder (modulo) // Logical Operators var b: bool, thisBool = false, thatBool = true; -b = thisBool && thatBool; // logical and -b = thisBool || thatBool; // logical or -b = !thisBool; // logical negation +b = thisBool && thatBool; // Logical and +b = thisBool || thatBool; // Logical or +b = !thisBool; // Logical negation // Relational Operators -b = thisInt > thatInt; // greater-than -b = thisInt >= thatInt; // greater-than-or-equal-to -b = thisInt < a && a <= thatInt; // less-than, and, less-than-or-equal-to -b = thisInt != thatInt; // not-equal-to -b = thisInt == thatInt; // equal-to +b = thisInt > thatInt; // Greater-than +b = thisInt >= thatInt; // Greater-than-or-equal-to +b = thisInt < a && a <= thatInt; // Less-than, and, less-than-or-equal-to +b = thisInt != thatInt; // Not-equal-to +b = thisInt == thatInt; // Equal-to // Bitwise operations -a = thisInt << 10; // left-bit-shift by 10 bits; -a = thatInt >> 5; // right-bit-shift by 5 bits; -a = ~thisInt; // bitwise-negation -a = thisInt ^ thatInt; // bitwise exclusive-or +a = thisInt << 10; // Left-bit-shift by 10 bits; +a = thatInt >> 5; // Right-bit-shift by 5 bits; +a = ~thisInt; // Bitwise-negation +a = thisInt ^ thatInt; // Bitwise exclusive-or // Compound assignment operations -a += thisInt; // addition-equals ( a = a + thisInt;) -a *= thatInt; // times-equals ( a = a * thatInt; ) -b &&= thatBool; // logical-and-equals ( b = b && thatBool; ) -a <<= 3; // left-bit-shift-equals ( a = a << 10; ) -// and so on... +a += thisInt; // Addition-equals ( a = a + thisInt;) +a *= thatInt; // Times-equals ( a = a * thatInt; ) +b &&= thatBool; // Logical-and-equals ( b = b && thatBool; ) +a <<= 3; // LEft-bit-shift-equals ( a = a << 10; ) +// and many, many more. // Unlike other C family languages there are no // pre/post-increment/decrement operators like // ++j, --j, j++, j-- @@ -119,8 +121,7 @@ var old_that = thatInt; thisInt <=> thatInt; // Swap the values of thisInt and thatInt writeln( (old_this == thatInt) && (old_that == thisInt) ); -// We can also define operator overloads, -// which we'll cover with procedures. +// Operator overloads can also be defined, as we'll see with procedures // Tuples can be of the same type var sameTup: 2*int = (10,-1); @@ -128,25 +129,29 @@ var sameTup2 = (11, -6); // or different types var diffTup: (int,real,complex) = (5, 1.928, myCplx); var diffTupe2 = ( 7, 5.64, 6.0+1.5i ); + // Accessed using array bracket notation // However, tuples are all 1-indexed writeln( "(", sameTup[1], ",", sameTup[2], ")" ); writeln( diffTup ); + // Tuples can also be written into. diffTup[1] = -1; + // Can expand tuple values into their own variables var (tupInt, tupReal, tupCplx) = diffTup; writeln( diffTup == (tupInt, tupReal, tupCplx) ); + // Useful for writing a list of variables ( as is common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); // Type aliasing -type chroma = int; // type of a single hue -type RGBColor = 3*chroma; // type representing a full color +type chroma = int; // Type of a single hue +type RGBColor = 3*chroma; // Type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); -// if-then-else works just like any other C-family language +// If-then-else works just like any other C-family language if 10 < 100 then writeln( "All is well" ); @@ -193,16 +198,16 @@ select( inputOption ){ } } -// While loops and Do-While loops are basically the same in every language. +// While and Do-While loops are basically the same in every language. var j: int = 1; var jSum: int = 0; while( j <= 1000 ){ jSum += j; - j += 1; // there are no ++j, --j, j++, j--, operators + j += 1; } writeln( jSum ); -// basic Do-While loop +// Do-While loop do{ jSum += j; j += 1; @@ -213,7 +218,7 @@ writeln( jSum ); // Ranges themselves are types, and can be stuffed into variables // (more about that later) for i in 1..10 do write( i , ", ") ; -writeln(); +writeln( ); var iSum: int = 0; for i in 1..1000 { @@ -225,7 +230,7 @@ for x in 1..10 { for y in 1..10 { write( (x,y), "\t" ); } - writeln(); + writeln( ); } // Ranges and Domains @@ -238,14 +243,16 @@ for x in 1..10 { var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 var rangeThistoThat: range = thisInt..thatInt; // using variables -var rangeEmpty: range = 100..-100 ; // this is a valid, but empty range +var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices -//ranges can be unbounded -var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... -var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 +// Ranges can be unbounded +var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; +// 1, 2, 3, 4, 5, ... // Note: the range(boundedType= ... ) is only // necessary if we explicitly type the variable +var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 + // Ranges can be strided using the 'by' operator. var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 // Note: the range(stridable=true) is only @@ -280,24 +287,23 @@ var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable // Can iterate over the indices as tuples for idx in twoDimensions do write( idx , ", "); -writeln(); +writeln( ); -// Or can deconstruct the tuple +// or can deconstruct the tuple for (x,y) in twoDimensions { write( "(", x, ", ", y, ")", ", " ); } -writeln(); +writeln( ); // Associative domains act like sets var stringSet: domain(string); // empty set of strings stringSet += "a"; stringSet += "b"; stringSet += "c"; -stringSet += "a"; // redundant add "a" -stringSet -= "c"; // remove "c" +stringSet += "a"; // Redundant add "a" +stringSet -= "c"; // Remove "c" writeln( stringSet ); - // Array are similar to those of other languages. // Their sizes are defined using domains that represent their indices var intArray: [1..10] int; @@ -307,35 +313,35 @@ var intArray2: [{1..10}] int; //equivalent for i in 1..10 do intArray[i] = -i; writeln( intArray ); -// we cannot access intArray[0] because it exists outside -// of the index set, {1..10}, we defined it to have +// We cannot access intArray[0] because it exists outside +// of the index set, {1..10}, we defined it to have. // intArray[11] is illegal for the same reason. var realDomain: domain(2) = {1..5,1..7}; var realArray: [realDomain] real; -var realArray2: [1..5,1..7] real; // equivalent -var realArray3: [{1..5,1..7}] real; // equivalent +var realArray2: [1..5,1..7] real; // Equivalent +var realArray3: [{1..5,1..7}] real; // Equivalent for i in 1..5 { - for j in realDomain.dim(2) { // only use the 2nd dimension of the domain - realArray[i,j] = -1.61803 * i + 0.5 * j; // access using index list - var idx: 2*int = (i,j); // note: 'index' is a keyword - realArray[idx] = - realArray[(i,j)]; // index using tuples + for j in realDomain.dim(2) { // Only use the 2nd dimension of the domain + realArray[i,j] = -1.61803 * i + 0.5 * j; // Access using index list + var idx: 2*int = (i,j); // Note: 'index' is a keyword + realArray[idx] = - realArray[(i,j)]; // Index using tuples } } -// arrays have domains as members that we can iterate over -for idx in realArray.domain { // again, idx is a 2*int tuple - realArray[idx] = 1 / realArray[idx[1],idx[2]]; // access by tuple and list +// Arrays have domains as members that we can iterate over +for idx in realArray.domain { // Again, idx is a 2*int tuple + realArray[idx] = 1 / realArray[idx[1],idx[2]]; // Access by tuple and list } writeln( realArray ); -// can also iterate over the values of an array +// Can also iterate over the values of an array var rSum: real = 0; for value in realArray { - rSum += value; // read a value - value = rSum; // write a value + rSum += value; // Read a value + value = rSum; // Write a value } writeln( rSum, "\n", realArray ); @@ -351,12 +357,12 @@ proc fibonacci( n : int ) : int { return fibonacci( n-1 ) + fibonacci( n-2 ); } -// input parameters can be untyped (a generic procedure) +// Input parameters can be untyped (a generic procedure) proc doublePrint( thing ): void { write( thing, " ", thing, "\n"); } -// return type can be inferred (as long as the compiler can figure it out) +// Return type can be inferred (as long as the compiler can figure it out) proc addThree( n ) { return n + 3; } @@ -372,12 +378,12 @@ proc maxOf( x ...?k ) { } writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); -// the ? operator is called the query operator, and is used to take +// The ? operator is called the query operator, and is used to take // undetermined values (like tuple or array sizes, and generic types). // Taking arrays as parameters. // The query operator is used to determine the domain of A. -// this is important to define the return type (if you wanted to) +// This is important to define the return type (if you wanted to) proc invertArray( A: [?D] int ): [D] int{ for a in A do a = -a; return A; @@ -396,7 +402,7 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// intent modifiers on the arguments convey how +// Intent modifiers on the arguments convey how // those arguments are passed to the procedure // in: copy arg in, but not out // out: copy arg out, but not in @@ -426,7 +432,7 @@ proc makeArray( elems: int, startNumber: int ) ref : [1..#elems] int { return array; } writeln( makeArray( 10, -1 ) ); -// this makes more practical sense for class methods where references to +// This makes more practical sense for class methods where references to // elements in a data-structure are returned via a method or iterator // We can query the type of arguments to generic procedures @@ -462,17 +468,17 @@ whereProc( 10 ); whereProc( -1 ); // whereProc( 0 ) would result in a compiler error because there // are no functions that satisfy the where clause's condition. -// We could have defined a whereProc without a where clause that would -// then have been called. +// We could have defined a whereProc without a where clause that would then have +// served as a catch all for all the other cases (of which there is only one). -// Operator definitions are through procedures as well -// we can define the unary operators: +// Operator definitions are through procedures as well. +// We can define the unary operators: // + - ! ~ // and the binary operators: // + - * / % ** == <= >= < > << >> & | ˆ by // += -= *= /= %= **= &= |= ˆ= <<= >>= <=> -// boolean exclusive or operator +// Boolean exclusive or operator proc ^( left : bool, right : bool ): bool { return (left || right) && !( left && right ); } @@ -487,8 +493,8 @@ proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ return (left, right ); } -writeln( 1 * "a" ); // uses our * operator -writeln( 1 * 2 ); // uses the original * operator +writeln( 1 * "a" ); // Uses our * operator +writeln( 1 * 2 ); // Uses the default * operator /* Note: You could break everything if you get careless with your overloads. @@ -498,24 +504,21 @@ proc +( left: int, right: int ): int{ } */ -// iterators are a close cousin to the procedure. +// Iterators are a sisters to the procedure, and almost +// everything about procedures also applies to iterators // However, instead of returning a single value, // iterators yield many values to a loop. // This is useful when a complicated set or order of iterations is needed but // allows the code defining the iterations to be separate from the loop body. iter oddsThenEvens( N: int ): int { - for i in 1..N by 2 { + for i in 1..N by 2 do yield i; // yield values instead of returning. - } - - for i in 2..N by 2 { + for i in 2..N by 2 do yield i; - } } for i in oddsThenEvens( 10 ) do write( i, ", " ); -writeln(); - +writeln( ); // Classes are similar to those in C++ and Java. // They currently lack privatization @@ -548,7 +551,7 @@ class MyClass { return this.memberInt; } - proc getMemberBool(): bool { + proc getMemberBool( ): bool { return this.memberBool; } @@ -556,30 +559,30 @@ class MyClass { // Construct using default constructor, using default values var myObject = new MyClass( 10 ); - myObject = new MyClass( memberInt = 10 ); // equivalent -writeln( myObject.getMemberInt() ); + myObject = new MyClass( memberInt = 10 ); // Equivalent +writeln( myObject.getMemberInt( ) ); // ... using our values var myDiffObject = new MyClass( -1, true ); myDiffObject = new MyClass( memberInt = -1, - memberBool = true ); // equivalent + memberBool = true ); // Equivalent writeln( myDiffObject ); // Construct using written constructor var myOtherObject = new MyClass( 1.95 ); - myOtherObject = new MyClass( val = 1.95 ); // equivalent -writeln( myOtherObject.getMemberInt() ); + myOtherObject = new MyClass( val = 1.95 ); // Equivalent +writeln( myOtherObject.getMemberInt( ) ); // We can define an operator on our class as well but // the definition has to be outside the class definition proc +( A : MyClass, B : MyClass) : MyClass { - return new MyClass( memberInt = A.getMemberInt() + B.getMemberInt(), - memberBool = A.getMemberBool() || B.getMemberBool() ); + return new MyClass( memberInt = A.getMemberInt( ) + B.getMemberInt( ), + memberBool = A.getMemberBool( ) || B.getMemberBool( ) ); } var plusObject = myObject + myDiffObject; writeln( plusObject ); -// destruction +// Destruction delete myObject; delete myDiffObject; delete myOtherObject; @@ -620,10 +623,10 @@ class GenericClass { return this.classArray[ i ]; } - // Define an iterator for the class to - // yield values from the array to a loop + // Define an implicit iterator for the class + // to yield values from the array to a loop // i.e. for i in objVar do .... - iter these() ref : classType { + iter these( ) ref : classType { for i in this.classDomain do yield this[i]; } @@ -635,19 +638,19 @@ var realList = new GenericClass( real, 10 ); // notation that we defined ( proc this( i: int ){ ... } ) for i in realList.classDomain do realList[i] = i + 1.0; // We can iterate over the values in our list with the iterator -// we defined ( iter these(){ ... } ) +// we defined ( iter these( ){ ... } ) for value in realList do write( value, ", " ); -writeln(); +writeln( ); // Make a copy of realList using the copy constructor var copyList = new GenericClass( realList ); for value in copyList do write( value, ", " ); -writeln(); +writeln( ); -// make a copy of realList and change the type, also using the copy constructor +// Make a copy of realList and change the type, also using the copy constructor var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); -writeln(); +writeln( ); // Parallelism // In other languages, parallelism is typically this is done with @@ -655,14 +658,14 @@ writeln(); // Chapel has it baked right into the language. // A begin statement will spin the body of that statement off into one new task. -// a sync statement will ensure that the progress of the -// main task will not progress until the children have synced back up. +// A sync statement will ensure that the progress of the main +// task will not progress until the children have synced back up. sync { - begin { // start of new task's body + begin { // Start of new task's body var a = 0; for i in 1..1000 do a += 1; writeln( "Done: ", a); - } // end of new tasks body + } // End of new tasks body writeln( "spun off a task!"); } writeln( "Back together" ); @@ -671,13 +674,13 @@ proc printFibb( n: int ){ writeln( "fibonacci(",n,") = ", fibonacci( n ) ); } -// a cobegin statement will spin each statement of the body into one new task +// A cobegin statement will spin each statement of the body into one new task cobegin { printFibb( 20 ); // new task printFibb( 10 ); // new task printFibb( 5 ); // new task { - // this is a nested statement body and thus is a single statement + // This is a nested statement body and thus is a single statement // to the parent statement and is executed by a single task writeln( "this gets" ); writeln( "executed as" ); @@ -700,41 +703,41 @@ coforall taskID in 1..#num_tasks { forall i in 1..100 { write( i, ", "); } -writeln(); +writeln( ); // Here we see that there are sections that are in order, followed by -// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ) -// this is because each task is taking on a chunk of the range 1..10 +// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). +// This is because each task is taking on a chunk of the range 1..10 // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens // in parallel. // Your results may depend on your machine and configuration -// For both the forall and coforall loops, the execution of the parent task -// will not continue until all the children sync up. +// For both the forall and coforall loops, the execution of the +// parent task will not continue until all the children sync up. -// forall loops are particularly useful for parallel iteration over arrays +// forall loops are particularly useful for parallel iteration over arrays. // Lets run an experiment to see how much faster a parallel loop is use Time; // Import the Time module to use Timer objects var timer: Timer; -var myBigArray: [{1..4000,1..4000}] real; // large array we will write into +var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into // Serial Experiment -timer.start(); // start timer -for (x,y) in myBigArray.domain { // serial iteration +timer.start( ); // Start timer +for (x,y) in myBigArray.domain { // Serial iteration myBigArray[x,y] = (x:real) / (y:real); } -timer.stop(); // stop timer -writeln( "Serial: ", timer.elapsed() ); // print elapsed time -timer.clear(); // clear timer for parallel loop +timer.stop( ); // Stop timer +writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time +timer.clear( ); // Clear timer for parallel loop // Parallel Experiment -timer.start(); // start timer -forall (x,y) in myBigArray.domain { // parallel iteration +timer.start( ); // start timer +forall (x,y) in myBigArray.domain { // Parallel iteration myBigArray[x,y] = (x:real) / (y:real); } -timer.stop(); // stop timer -writeln( "Parallel: ", timer.elapsed() ); // print elapsed time -timer.clear(); -// you may have noticed that (depending on how many cores you have) that -// the parallel loop went faster than the serial loop +timer.stop( ); // Stop timer +writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time +timer.clear( ); +// You may have noticed that (depending on how many cores you have) +// that the parallel loop went faster than the serial loop // A succinct way of writing a forall loop over an array: // iterate over values @@ -750,6 +753,17 @@ Refer to the [language specification](http://chapel.cray.com/language.html) and Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. +### What this tutorial is lacking: + * Modules and standard modules + * Synchronize and atomic variables + * Multiple Locales (distributed memory system) + * proc main(){ ... } + * Records + * Whole/sliced array assignment + * Reductions and scans + * Range and domain slicing + * Parallel iterators + Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. -- cgit v1.2.3 From d6f8b8e629b0eb043710864566f894c0ce5f871c Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Tue, 14 Jul 2015 19:09:10 -0700 Subject: Codify proc() main lacking note --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 8b41dc32..2cd55a66 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -757,7 +757,7 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to * Modules and standard modules * Synchronize and atomic variables * Multiple Locales (distributed memory system) - * proc main(){ ... } + * ```proc main(){ ... }``` * Records * Whole/sliced array assignment * Reductions and scans -- cgit v1.2.3 From cf26b05a233950c4ae30e0915b6892399c7f0151 Mon Sep 17 00:00:00 2001 From: Guangming Mao Date: Wed, 15 Jul 2015 16:01:37 +0800 Subject: Refine some sentences and fix some typos --- zh-cn/rust-cn.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown index f50c1566..17a897df 100644 --- a/zh-cn/rust-cn.html.markdown +++ b/zh-cn/rust-cn.html.markdown @@ -8,7 +8,7 @@ filename: learnrust-cn.rs lang: zh-cn --- -Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制和高级语言的便利性和安全保障结合在了一起。 +Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制与高级语言的便利性和安全保障结合在了一起。 而 Rust 并不需要一个垃圾回收器或者运行时即可实现这个目的,这使得 Rust 库可以成为一种 C 语言的替代品。 @@ -73,7 +73,7 @@ fn main() { let s: String = "hello world".to_string(); // 字符串分片(slice) - 另一个字符串的不可变视图 - // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何类容,只是一个指向某个东西的指针 + // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何内容,只是一个指向某个东西的指针 // 比如这里就是 `s` let s_slice: &str = &s; @@ -181,7 +181,7 @@ fn main() { println!("{:?}", another_foo.frobnicate()); // Some(1) /////////////////////////////////// - // 3. 模板匹配 (Pattern matching) // + // 3. 模式匹配 (Pattern matching) // /////////////////////////////////// let foo = OptionalI32::AnI32(1); @@ -190,7 +190,7 @@ fn main() { OptionalI32::Nothing => println!("it’s nothing!"), } - // 高级模板匹配 + // 高级模式匹配 struct FooBar { x: i32, y: OptionalI32 } let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; @@ -206,7 +206,7 @@ fn main() { } /////////////////////////////// - // 4. 条件控制 (Control flow) // + // 4. 流程控制 (Control flow) // /////////////////////////////// // `for` 循环 @@ -251,7 +251,7 @@ fn main() { //////////////////////////////////////////////// // 独占指针 (Owned pointer) - 同一时刻只能有一个对象能“拥有”这个指针 - // 意味着 `Box` 离开他的作用域后,会被安全的释放 + // 意味着 `Box` 离开他的作用域后,会被安全地释放 let mut mine: Box = Box::new(3); *mine = 5; // 解引用 // `now_its_mine` 获取了 `mine` 的所有权。换句话说,`mine` 移动 (move) 了 @@ -286,8 +286,8 @@ fn main() { ## 更深入的资料 -Rust 还有很多很多其他类容 - 这只是 Rust 最基础的东西,帮助你了解 Rust 里面最重要的东西。 -如果想深入学习 Rust,可以去阅读 +Rust 还有很多很多其他内容 - 这只是 Rust 最基本的功能,帮助你了解 Rust 里面最重要的东西。 +如果想深入学习 Rust,可以去读 [The Rust Programming Language](http://doc.rust-lang.org/book/index.html) 或者上 reddit [/r/rust](http://reddit.com/r/rust) 订阅。 同时 irc.mozilla.org 的 #rust 频道上的小伙伴们也非常欢迎新来的朋友。 -- cgit v1.2.3 From 37257b592275a5ddb41d7e1d6545aa039b1a35c3 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Wed, 15 Jul 2015 12:08:15 -0700 Subject: epiphany on ref returns. lead to better example of ref returns and then also a description of ref vars --- chapel.html.markdown | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 8b41dc32..77efbf5a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -77,6 +77,15 @@ config param paramCmdLineArg: bool = false; writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); // Set config with --set paramCmdLineArg=value at compile time +// refs operate much like a reference in C++ +var actual = 10; +ref refToActual = actual; // refToActual refers to actual +writeln( actual, " == ", refToActual ); // prints the same value +actual = -123; // modify actual (which refToActual refers to) +writeln( actual, " == ", refToActual ); // prints the same value +refToActual = 99999999; // modify what refToActual refers to (which is actual) +writeln( actual, " == ", refToActual ); // prints the same value + // Math operators var a: int, thisInt = 1234, thatInt = 5678; a = thisInt + thatInt; // Addition @@ -426,12 +435,19 @@ intentsProc( inVar, outVar, inoutVar, refVar ); writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) ); // Similarly we can define intents on the return type -proc makeArray( elems: int, startNumber: int ) ref : [1..#elems] int { - var array: [1..#elems] int; - for idx in array.domain do array[idx] = startNumber + idx; - return array; -} -writeln( makeArray( 10, -1 ) ); +// refElement returns a reference to an element of array +proc refElement( array : [?D] ?T, idx ) ref : T { + return array[ idx ]; // returns a reference to +} + +var myChangingArray : [1..5] int = [1,2,3,4,5]; +writeln( myChangingArray ); +// Store reference to element in ref variable +ref refToElem = refElement( myChangingArray, 5 ); +writeln( refToElem ); +refToElem = -2; // modify reference which modifies actual value in array +writeln( refToElem ); +writeln( myChangingArray ); // This makes more practical sense for class methods where references to // elements in a data-structure are returned via a method or iterator -- cgit v1.2.3 From 90c27c72cfbd1fc2fa4b5700a5e08efc6c3ed874 Mon Sep 17 00:00:00 2001 From: Kado Date: Thu, 16 Jul 2015 18:43:13 +0300 Subject: Update matlab.html.markdown --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 9de41275..00f4c53a 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -43,7 +43,7 @@ edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window profile on % turns on the code profiler -profile of % turns off the code profiler +profile off % turns off the code profiler profile viewer % Open profiler help command % Displays documentation for command in Command Window -- cgit v1.2.3 From d995a0ae2792b3e6acc832438b84e9fed570d0e4 Mon Sep 17 00:00:00 2001 From: Mark Miller <725mrm@gmail.com> Date: Thu, 16 Jul 2015 16:45:25 -0500 Subject: Changed %s formatting to {n} style. If line 117 is accurate, then {n} style string formatting is the preferred style, and it should be reflected in the examples. --- python.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index b89fe57d..3b233f7f 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -327,8 +327,8 @@ prints: mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: - # You can use % to interpolate formatted strings - print "%s is a mammal" % animal + # You can use {0} to interpolate formatted strings. (See above.) + print "{0} is a mammal".format(animal) """ "range(number)" returns a list of numbers @@ -387,7 +387,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks # Use "def" to create new functions def add(x, y): - print "x is %s and y is %s" % (x, y) + print "x is {0} and y is {1}".format(x, y) return x + y # Return values with a return statement # Calling functions with parameters @@ -497,7 +497,7 @@ class Human(object): # An instance method. All methods take "self" as the first argument def say(self, msg): - return "%s: %s" % (self.name, msg) + return "{0}: {1}".format(self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument -- cgit v1.2.3 From c22acdf8bd8750b664393422e1e00d4055f69e31 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 17 Jul 2015 14:45:18 +0900 Subject: Update chapel.html.markdown Make sure nothing breaks (too badly) --- chapel.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d4d6d648..d4ce4dfa 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -3,7 +3,6 @@ language: chapel filename: learnchapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] -lang: en --- You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). @@ -11,7 +10,7 @@ In short, Chapel is an open-source, high-productivity, parallel-programming lang More information and support can be found at the bottom of this document. -```chapel +```c // Comments are C-family style // one line comment /* -- cgit v1.2.3 From 4edb920f518327325d092f76a99f901821f35c76 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:09:21 -0700 Subject: capitalization and attempt to fix lists --- chapel.html.markdown | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d4ce4dfa..f308d1d8 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1,11 +1,11 @@ --- -language: chapel +language: Chapel filename: learnchapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] --- -You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). +You can read all about Chapel at [Cray's official Chapel website](http://chapel.cray.com). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. More information and support can be found at the bottom of this document. @@ -762,7 +762,7 @@ timer.clear( ); ``` Who is this tutorial for? ------------------------- -This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. +This tutorial is for people who want to learn the ropes of Chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. @@ -793,22 +793,27 @@ Installing the Compiler ----------------------- Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) -and its as easy as - 1. ```tar -xvf chapel-1.11.0.tar.gz``` - 2. ```cd chapel-1.11.0``` - 3. ```make``` - 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` +and its as easy as + +1. ```tar -xvf chapel-1.11.0.tar.gz``` + +2. ```cd chapel-1.11.0``` + +3. ```make``` + +4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X - 1. ```brew update``` - 2. ```brew install chapel``` + +1. ```brew update``` + +2. ```brew install chapel``` Compiling Code -------------- Builds like other compilers ```chpl myFile.chpl -o myExe``` -A notable argument: - * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. +A notable argument, ``--fast`` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From 4ae7b4921979998152c828a2b70576258a1f1468 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:13:51 -0700 Subject: Changed bash examples from block code Bash examples were in block code form (triple tick), should have been in inline mode (single tic) --- chapel.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index f308d1d8..5a0c3920 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -795,25 +795,25 @@ Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as -1. ```tar -xvf chapel-1.11.0.tar.gz``` +`tar -xvf chapel-1.11.0.tar.gz` -2. ```cd chapel-1.11.0``` +`cd chapel-1.11.0` -3. ```make``` +`make` -4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` +`source util/setchplenv.bash # or .sh or .csh or .fish` -You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). +You will need to `source util/setchplenv.EXT` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X -1. ```brew update``` +`brew update` -2. ```brew install chapel``` +`brew install chapel` Compiling Code -------------- Builds like other compilers -```chpl myFile.chpl -o myExe``` +`chpl myFile.chpl -o myExe` -A notable argument, ``--fast`` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. +A notable argument, `--fast` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From 77c4ddb522881b4975bff0e6b34e46566336e266 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:15:29 -0700 Subject: Put lists back in Pretty sure what was causing the 'back end' error was my bad markdown skills --- chapel.html.markdown | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 5a0c3920..c6c4a191 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -794,26 +794,21 @@ Installing the Compiler Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as - -`tar -xvf chapel-1.11.0.tar.gz` - -`cd chapel-1.11.0` - -`make` - -`source util/setchplenv.bash # or .sh or .csh or .fish` + 1. `tar -xvf chapel-1.11.0.tar.gz` + 2. `cd chapel-1.11.0` + 3. `make` + 4. `source util/setchplenv.bash # or .sh or .csh or .fish` You will need to `source util/setchplenv.EXT` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X - -`brew update` - -`brew install chapel` + 1. `brew update` + 2. `brew install chapel` Compiling Code -------------- Builds like other compilers + `chpl myFile.chpl -o myExe` A notable argument, `--fast` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From e7fe0b267a4c11136f4703493206d5862fa0fb76 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:24:16 -0700 Subject: Spellcheck --- chapel.html.markdown | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index c6c4a191..b03aee7b 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -117,7 +117,7 @@ a = thisInt ^ thatInt; // Bitwise exclusive-or a += thisInt; // Addition-equals ( a = a + thisInt;) a *= thatInt; // Times-equals ( a = a * thatInt; ) b &&= thatBool; // Logical-and-equals ( b = b && thatBool; ) -a <<= 3; // LEft-bit-shift-equals ( a = a << 10; ) +a <<= 3; // Left-bit-shift-equals ( a = a << 10; ) // and many, many more. // Unlike other C family languages there are no // pre/post-increment/decrement operators like @@ -190,7 +190,7 @@ if ( a % 3 == 0 ) { var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; // Select statements are much like switch statements in other languages -// However, Select statements dont cascade like in C or Java +// However, Select statements don't cascade like in C or Java var inputOption = "anOption"; select( inputOption ){ when "anOption" do writeln( "Chose 'anOption'" ); @@ -201,8 +201,6 @@ select( inputOption ){ otherwise { writeln( "Any other Input" ); writeln( "the otherwise case doesn't need a do if the body is one line" ); - writeln( "Oh, and when statements dont cascade like the case statements" ); - writeln( "of other languages" ); } } @@ -246,7 +244,7 @@ for x in 1..10 { // define an index set that can be iterated over. // Ranges are single dimensional // Domains can be multi-dimensional and can -// represent indicies of different types as well. +// represent indices of different types as well. // They are first-class citizen types, and can be assigned into variables var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 @@ -452,7 +450,7 @@ writeln( myChangingArray ); // We can query the type of arguments to generic procedures // Here we define a procedure that takes two arguments of -// the same type, yet we dont define what that type is. +// the same type, yet we don't define what that type is. proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { select( valueType ){ when int do writeln( arg1, " and ", arg2, " are ints" ); @@ -620,10 +618,10 @@ class GenericClass { } // Copy constructor - // Note: We still have to put the the type as an argument, but we can + // Note: We still have to put the type as an argument, but we can // default to the type of the other object using the query (?) operator // Further, we can take advantage of this to allow our copy constructor - // to copy classes of different types + // to copy classes of different types and cast on the fly proc GenericClass( other : GenericClass(?otherType), type classType = otherType ) { this.classDomain = other.classDomain; -- cgit v1.2.3 From 6a54bca6ee74486b6eddadec17b6fc7f0c8bf43b Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:31:32 -0700 Subject: Capitalization, Chapel Directory. --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index b03aee7b..fb54d5a1 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -797,7 +797,7 @@ and its as easy as 3. `make` 4. `source util/setchplenv.bash # or .sh or .csh or .fish` -You will need to `source util/setchplenv.EXT` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). +You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X 1. `brew update` -- cgit v1.2.3 From 71f87d44fd4aae061e0c9d1b52a202a1be4fc332 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sat, 18 Jul 2015 09:21:14 +0900 Subject: More line breaks Fix formatting in places --- chapel.html.markdown | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d4ce4dfa..ec46a083 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -760,8 +760,10 @@ timer.clear( ); // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; ``` + Who is this tutorial for? ------------------------- + This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. @@ -769,6 +771,7 @@ Refer to the [language specification](http://chapel.cray.com/language.html) and Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. ### What this tutorial is lacking: + * Modules and standard modules * Synchronize and atomic variables * Multiple Locales (distributed memory system) @@ -781,6 +784,7 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- + The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). @@ -791,9 +795,11 @@ It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0) Installing the Compiler ----------------------- + Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as + 1. ```tar -xvf chapel-1.11.0.tar.gz``` 2. ```cd chapel-1.11.0``` 3. ```make``` @@ -802,13 +808,17 @@ and its as easy as You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X + 1. ```brew update``` 2. ```brew install chapel``` Compiling Code -------------- -Builds like other compilers + +Builds like other compilers: + ```chpl myFile.chpl -o myExe``` A notable argument: + * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From bad5266d05485cd61ab1aa0884180ab78738cd9b Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sat, 18 Jul 2015 14:16:08 -0700 Subject: Slight modifications. --- chapel.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index c97a5f2b..7ac73bbb 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1,6 +1,6 @@ --- language: Chapel -filename: learnchapel.chpl +filename: learnChapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] --- @@ -27,7 +27,7 @@ writeln( "There are ", 3, " commas (\",\") in this line of code" ); stdout.writeln( "This goes to standard output (just like plain writeln( ) does)"); stderr.writeln( "This goes to standard error" ); -// Variables dont have to be explicitly typed as long as +// Variables don't have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; @@ -540,7 +540,7 @@ class MyClass { var memberInt : int; var memberBool : bool = true; - // Classes have default constructors that dont need to be coded (see below) + // Classes have default constructors that don't need to be coded (see below) // Our explicitly defined constructor proc MyClass( val : real ){ this.memberInt = ceil( val ): int; @@ -771,7 +771,7 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to ### What this tutorial is lacking: * Modules and standard modules - * Synchronize and atomic variables + * Synchronize variables and atomic operations * Multiple Locales (distributed memory system) * ```proc main(){ ... }``` * Records -- cgit v1.2.3 From fe0c14b8ad0f04b1d493fa6612a14d6cc7a48650 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 19 Jul 2015 16:01:04 -0700 Subject: De-capitalization Changed language name and filename back to lower case 'chapel' in keeping with previous name to avoid possible site breakage. --- chapel.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 7ac73bbb..53e9747c 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1,6 +1,6 @@ --- -language: Chapel -filename: learnChapel.chpl +language: chapel +filename: learnchapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] --- -- cgit v1.2.3 From 155bf5d0a285de2c4dec4033c8e9c20f6a42072b Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 19 Jul 2015 19:59:30 -0700 Subject: Added sync, single, and atomic vars. --- chapel.html.markdown | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 7ac73bbb..4f857775 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -757,6 +757,83 @@ timer.clear( ); [ val in myBigArray ] val = 1 / val; // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; + +proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } +} + +// sync vars have two states: empty and full. +// If you read an empty variable or write a full variable, you are waited +// until the variable is full or empty again +var someSyncVar$: sync int; // varName$ is a convention not a law. +sync { + begin { + writeln( "Waiting to read" ); + var read_sync = someSyncVar$; + writeln( "value is ", read_sync ); + } + + begin { + writeln( "Writing in..." ); + countdown( 3 ); + someSyncVar$ = 123; + } +} + +// single vars can only be written once. A read on an unwritten single results +// in a wait, but when the variable has a value it can be read indefinitely +var someSingleVar$: single int; // varName$ is a convention not a law. +sync { + begin { + writeln( "Waiting to read" ); + for i in 1..5 { + var read_single = someSingleVar$; + writeln( i,"th time around an the value is ", read_single ); + } + } + + begin { + writeln( "Writing in..." ); + countdown( 3 ); + someSingleVar$ = 5; // first and only write ever. + } +} + +// atomic variables can be of type bool, int, uint, and real of any size. +var uranium: atomic int; +uranium.write( 238 ); // atomically write a variable +writeln( uranium.read() ); // atomically read a variable +// operations are described as functions, you could define your own operators. +uranium.sub( 3 ); // atomically subtract a variable +writeln( uranium.read() ); +var replaceWith = 239; +var was = uranium.exchange( replaceWith ); +writeln( "uranium was ", was, " but is now ", replaceWith ); +var isEqualTo = 235; +if uranium.compareExchange( isEqualTo, replaceWith ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); +} else { + writeln( "uranium was not equal to ", isEqualTo, + " value stays the same... whatever it was" ); +} + +sync { + begin { + writeln( "Waiting to for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Uranium was set (by someone) to ", isEqualTo ); + } + + begin { + writeln( "Waiting to write uranium to ", isEqualTo ); + countdown( 3 ); + uranium.write( isEqualTo ); + } +} ``` Who is this tutorial for? @@ -771,7 +848,6 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to ### What this tutorial is lacking: * Modules and standard modules - * Synchronize variables and atomic operations * Multiple Locales (distributed memory system) * ```proc main(){ ... }``` * Records -- cgit v1.2.3 From bcc84f9c768041b7f260907d4432e12658b76626 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 08:09:28 -0700 Subject: Explained atomics, moved atomics first Felt the need to add in an explanation about atomics, then felt that (because atomics are common in language and in theory) it should go before sync and single vars. Should I explain sync and single? --- chapel.html.markdown | 69 +++++++++++++++++++++++++++------------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 6fe7c1b0..bbbf50e8 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -765,6 +765,42 @@ proc countdown( seconds: int ){ } } +// Atomic variables, common to many languages, are ones whose operations +// occur uninterupted. Multiple threads can both modify atomic variables +// and can know that their values are safe. +// Chapel atomic variables can be of type bool, int, uint, and real. +var uranium: atomic int; +uranium.write( 238 ); // atomically write a variable +writeln( uranium.read() ); // atomically read a variable +// operations are described as functions, you could define your own operators. +uranium.sub( 3 ); // atomically subtract a variable +writeln( uranium.read() ); +var replaceWith = 239; +var was = uranium.exchange( replaceWith ); +writeln( "uranium was ", was, " but is now ", replaceWith ); +var isEqualTo = 235; +if uranium.compareExchange( isEqualTo, replaceWith ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); +} else { + writeln( "uranium was not equal to ", isEqualTo, + " value stays the same... whatever it was" ); +} + +sync { + begin { + writeln( "Waiting to for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Uranium was set (by someone) to ", isEqualTo ); + } + + begin { + writeln( "Waiting to write uranium to ", isEqualTo ); + countdown( 3 ); + uranium.write( isEqualTo ); + } +} + // sync vars have two states: empty and full. // If you read an empty variable or write a full variable, you are waited // until the variable is full or empty again @@ -801,39 +837,6 @@ sync { someSingleVar$ = 5; // first and only write ever. } } - -// atomic variables can be of type bool, int, uint, and real of any size. -var uranium: atomic int; -uranium.write( 238 ); // atomically write a variable -writeln( uranium.read() ); // atomically read a variable -// operations are described as functions, you could define your own operators. -uranium.sub( 3 ); // atomically subtract a variable -writeln( uranium.read() ); -var replaceWith = 239; -var was = uranium.exchange( replaceWith ); -writeln( "uranium was ", was, " but is now ", replaceWith ); -var isEqualTo = 235; -if uranium.compareExchange( isEqualTo, replaceWith ) { - writeln( "uranium was equal to ", isEqualTo, - " so replaced value with ", replaceWith ); -} else { - writeln( "uranium was not equal to ", isEqualTo, - " value stays the same... whatever it was" ); -} - -sync { - begin { - writeln( "Waiting to for uranium to be ", isEqualTo ); - uranium.waitFor( isEqualTo ); - writeln( "Uranium was set (by someone) to ", isEqualTo ); - } - - begin { - writeln( "Waiting to write uranium to ", isEqualTo ); - countdown( 3 ); - uranium.write( isEqualTo ); - } -} ``` Who is this tutorial for? -- cgit v1.2.3 From d2d98a381047d30e0355a8dacd0fdbe1188345c0 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 08:17:01 -0700 Subject: Spelling error Tupe -> Tuple --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index bbbf50e8..9ce184c0 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -501,7 +501,7 @@ writeln( false ^ true ); writeln( true ^ false ); writeln( false ^ false ); -// Define a * operator on any two types that returns a tupe of those types +// Define a * operator on any two types that returns a tuple of those types proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ return (left, right ); } -- cgit v1.2.3 From 2936ca4c69f7b96dfbe7f67de0ebcad910395ba1 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 12:59:35 -0700 Subject: Erroneous comment removed "define mySecondVar as a real" unnecessary and incorrect. --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 9ce184c0..4cbc5a4b 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -35,7 +35,7 @@ var mySecondVar = myVar; // var anError; // this would be a compile time error. // We can (and should) explicitly type things -var myThirdVar: real; // define mySecondVar as a real +var myThirdVar: real; var myFourthVar: real = -1.234; myThirdVar = myFourthVar; -- cgit v1.2.3 From d35d9d213c3ce3ba1bb53aef896898d87e213d58 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 13:01:25 -0700 Subject: Word error that -> than --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 4cbc5a4b..b124f54a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -65,7 +65,7 @@ const almostPi: real = 22.0/7.0; param compileTimeConst: int = 16; // The config modifier allows values to be set at the command line -// and is much easier that the usual getOpts debacle +// and is much easier than the usual getOpts debacle // config vars and consts can be changed through the command line at run time config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; -- cgit v1.2.3 From 77daaef8ed6d2fed88405cf038d4e5f0b82dc1ef Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 13:07:23 -0700 Subject: config param changeup changed some of the wording of the param config example. Namely put the comment immediately below the example. Also added --set to the noteable arguments list. Also changed "compile(?: )?time" to "compile-time" --- chapel.html.markdown | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index b124f54a..520f959d 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -32,7 +32,7 @@ stderr.writeln( "This goes to standard error" ); var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; var mySecondVar = myVar; -// var anError; // this would be a compile time error. +// var anError; // this would be a compile-time error. // We can (and should) explicitly type things var myThirdVar: real; @@ -57,11 +57,11 @@ var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real var intFromReal = myReal : int; var intFromReal2: int = myReal : int; -// consts are constants, they cannot be changed after set in runtime +// consts are constants, they cannot be changed after set in runtime. const almostPi: real = 22.0/7.0; -// params are constants whose value must be known statically at compile time -// Like consts, they cannot be changed during runtime +// params are constants whose value must be known statically at compile-time +// Their value cannot be changed. param compileTimeConst: int = 16; // The config modifier allows values to be set at the command line @@ -71,10 +71,10 @@ config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; // Set with --VarName=Value or --VarName Value at run time -// config params can be set at compile time +// config params can be set/changed at compile-time config param paramCmdLineArg: bool = false; +// Set config with --set paramCmdLineArg=value at compile-time writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); -// Set config with --set paramCmdLineArg=value at compile time // refs operate much like a reference in C++ var actual = 10; @@ -465,7 +465,7 @@ genericProc( 1.0+2.0i, 3.0+4.0i ); // We can also enforce a form of polymorphism with the 'where' clause // This allows the compiler to decide which function to use. -// Note: that means that all information needs to be known at compile time. +// Note: that means that all information needs to be known at compile-time. // The param modifier on the arg is used to enforce this constraint. proc whereProc( param N : int ): void where ( N > 0 ) { @@ -896,6 +896,7 @@ Builds like other compilers: ```chpl myFile.chpl -o myExe``` -A notable argument: +Notable arguments: * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. + * ```--set =```: set config param to at compile-time -- cgit v1.2.3 From 3332ce43bb73dcb850250847c6cffdc396338d5e Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Wed, 22 Jul 2015 19:08:22 -0700 Subject: added scans and reductions --- chapel.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/chapel.html.markdown b/chapel.html.markdown index 520f959d..e058bde9 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -837,6 +837,25 @@ sync { someSingleVar$ = 5; // first and only write ever. } } + +// we can define the operations + * & | ^ && || min max minloc maxloc +// over an entire array using scans and reductions +// Reductions apply the operation over the entire array and +// result in a single value +var listOfValues: [1..10] int = [456,354,15,57,36,45,15,8,678,2]; +var sumOfValues = + reduce listOfValues; +var maxValue = max reduce listOfValues; // give just max value +// gives max value and index of the max value +var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, listOfValues.domain); +writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); + +// Scans apply the operation incrementally and return an array of the +// value of the operation at that index as it progressed through the +// array from array.domain.low to array.domain.high +var runningSumOfValues = + scan listOfValues; +var maxScan = max scan listOfValues; +writeln( runningSumOfValues ); +writeln( maxScan ); ``` Who is this tutorial for? -- cgit v1.2.3 From 8a968db2bc0f596e2e9d865b73d909b02ff774d6 Mon Sep 17 00:00:00 2001 From: Al Sweigart Date: Thu, 23 Jul 2015 11:24:40 -0700 Subject: Added links to the free book "Automate the Boring Stuff with Python" to the "Free Online" section. --- python.html.markdown | 1 + python3.html.markdown | 1 + 2 files changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 3b233f7f..88e0deb1 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -624,6 +624,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ### Free Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [The Official Docs](http://docs.python.org/2.6/) diff --git a/python3.html.markdown b/python3.html.markdown index dd57bf58..36298566 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -642,6 +642,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) -- cgit v1.2.3 From ac2dfe7dc782cf1663944c0de48f6bbe810a56d8 Mon Sep 17 00:00:00 2001 From: Genki Marshall Date: Fri, 24 Jul 2015 13:21:01 -0700 Subject: [python3/en] Use `next()` instead of `__next__()` Fixes issue #1148. The reasoning is well explained by the issue. One can also refer to the docs [0], showing it is more idiomatic to use `next()`. [0]: https://www.python.org/dev/peps/pep-3114/ #double-underscore-methods-and-built-in-functions --- python3.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 36298566..9d965fb1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -394,15 +394,15 @@ our_iterable[1] # Raises a TypeError our_iterator = iter(our_iterable) # Our iterator is an object that can remember the state as we traverse through it. -# We get the next object by calling the __next__ function. -our_iterator.__next__() #=> "one" +# We get the next object with "next()". +next(our_iterator) #=> "one" -# It maintains state as we call __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +# It maintains state as we iterate. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception -our_iterator.__next__() # Raises StopIteration +next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. list(filled_dict.keys()) #=> Returns ["one", "two", "three"] -- cgit v1.2.3 From c2f85b27b5620054bb0306ee4730cefff60ad87c Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sat, 1 Aug 2015 17:02:51 -0700 Subject: added count-down mutex example. Cleaned up some of the reductions and scans prints --- chapel.html.markdown | 88 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 65 insertions(+), 23 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index e058bde9..0d1d38dc 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -533,6 +533,12 @@ iter oddsThenEvens( N: int ): int { for i in oddsThenEvens( 10 ) do write( i, ", " ); writeln( ); +// The 'zippered' iterator is an iterator that takes two or more iterators that +// have the same number of iterations and zips them together into one stream + // Ranges have implicit iterators +for (odd, even) in zip( 1..#10 by 2, 2..#10 by 2 ) do + writeln( (odd, even) ); + // Classes are similar to those in C++ and Java. // They currently lack privatization class MyClass { @@ -569,7 +575,7 @@ class MyClass { } } - + // Construct using default constructor, using default values var myObject = new MyClass( 10 ); myObject = new MyClass( memberInt = 10 ); // Equivalent @@ -732,6 +738,7 @@ writeln( ); use Time; // Import the Time module to use Timer objects var timer: Timer; var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into + // Serial Experiment timer.start( ); // Start timer for (x,y) in myBigArray.domain { // Serial iteration @@ -754,7 +761,8 @@ timer.clear( ); // A succinct way of writing a forall loop over an array: // iterate over values -[ val in myBigArray ] val = 1 / val; +[ val in myBigArray ] val = 1 / val; + // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; @@ -770,32 +778,35 @@ proc countdown( seconds: int ){ // and can know that their values are safe. // Chapel atomic variables can be of type bool, int, uint, and real. var uranium: atomic int; -uranium.write( 238 ); // atomically write a variable +uranium.write( 238 ); // atomically write a variable writeln( uranium.read() ); // atomically read a variable + // operations are described as functions, you could define your own operators. uranium.sub( 3 ); // atomically subtract a variable writeln( uranium.read() ); + var replaceWith = 239; var was = uranium.exchange( replaceWith ); writeln( "uranium was ", was, " but is now ", replaceWith ); + var isEqualTo = 235; if uranium.compareExchange( isEqualTo, replaceWith ) { writeln( "uranium was equal to ", isEqualTo, " so replaced value with ", replaceWith ); } else { writeln( "uranium was not equal to ", isEqualTo, - " value stays the same... whatever it was" ); + " so value stays the same... whatever it was" ); } sync { - begin { - writeln( "Waiting to for uranium to be ", isEqualTo ); + begin { // Reader task + writeln( "Reader: waiting for uranium to be ", isEqualTo ); uranium.waitFor( isEqualTo ); - writeln( "Uranium was set (by someone) to ", isEqualTo ); + writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); } - begin { - writeln( "Waiting to write uranium to ", isEqualTo ); + begin { // Writer task + writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); countdown( 3 ); uranium.write( isEqualTo ); } @@ -806,14 +817,14 @@ sync { // until the variable is full or empty again var someSyncVar$: sync int; // varName$ is a convention not a law. sync { - begin { - writeln( "Waiting to read" ); + begin { // Reader task + writeln( "Reader: waiting to read." ); var read_sync = someSyncVar$; writeln( "value is ", read_sync ); } - begin { - writeln( "Writing in..." ); + begin { // Writer task + writeln( "Writer: will write in..." ); countdown( 3 ); someSyncVar$ = 123; } @@ -823,30 +834,62 @@ sync { // in a wait, but when the variable has a value it can be read indefinitely var someSingleVar$: single int; // varName$ is a convention not a law. sync { - begin { - writeln( "Waiting to read" ); + begin { // Reader task + writeln( "Reader: waiting to read." ); for i in 1..5 { var read_single = someSingleVar$; - writeln( i,"th time around an the value is ", read_single ); + writeln( "Reader: iteration ", i,", and the value is ", read_single ); } } - begin { - writeln( "Writing in..." ); + begin { // Writer task + writeln( "Writer: will write in..." ); countdown( 3 ); someSingleVar$ = 5; // first and only write ever. } } +// Heres an example of using atomics and a synch variable to create a +// count-down mutex (also known as a multiplexer) +var count: atomic int; // our counter +var lock$: sync bool; // the mutex lock + +count.write( 2 ); // Only let two tasks in at a time. +lock$.writeXF( true ); // Set lock$ to full (unlocked) +// Note: The value doesnt actually matter, just the state +// (full:unlocked / empty:locked) +// Also, writeXF() fills (F) the sync var regardless of its state (X) + +coforall task in 1..#5 { // Generate tasks + // Create a barrier + do{ + lock$; // Read lock$ (wait) + }while count.read() < 1; // Keep waiting until a spot opens up + + count.sub(1); // decrement the counter + lock$.writeXF( true ); // Set lock$ to full (signal) + + // Actual 'work' + writeln( "Task #", task, " doing work." ); + sleep( 2 ); + + count.add( 1 ); // Increment the counter + lock$.writeXF( true ); // Set lock$ to full (signal) +} + // we can define the operations + * & | ^ && || min max minloc maxloc // over an entire array using scans and reductions // Reductions apply the operation over the entire array and // result in a single value -var listOfValues: [1..10] int = [456,354,15,57,36,45,15,8,678,2]; +var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; var sumOfValues = + reduce listOfValues; -var maxValue = max reduce listOfValues; // give just max value -// gives max value and index of the max value -var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, listOfValues.domain); +var maxValue = max reduce listOfValues; // 'max' give just max value + +// 'maxloc' gives max value and index of the max value +// Note: We have to zip the array and domain together with the zip iterator +var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, + listOfValues.domain); + writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); // Scans apply the operation incrementally and return an array of the @@ -874,7 +917,6 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to * ```proc main(){ ... }``` * Records * Whole/sliced array assignment - * Reductions and scans * Range and domain slicing * Parallel iterators -- cgit v1.2.3 From 919f255a58d7af0a65d0fbf9b5232317ec20db28 Mon Sep 17 00:00:00 2001 From: Thiago van Dieten Date: Sun, 2 Aug 2015 12:58:23 +0300 Subject: Fix 'filename' collision between csharp{,-tr}.html.markdown Both were set to LearnCSharp.cs, so the live site has been serving the Turkish version for English. --- tr-tr/csharp-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 7755ed44..a68026a5 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["Melih Mucuk", "http://melihmucuk.com"] lang: tr-tr -filename: LearnCSharp.cs +filename: LearnCSharp-tr.cs --- -- cgit v1.2.3 From 11ca1012e402bbc51f70283c4e20ee8bf31deb7f Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 14:35:41 -0700 Subject: Clarified some wording on the zipper iterator. Changed the example to something more simple and informative. --- chapel.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 0d1d38dc..cfde0454 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -533,11 +533,13 @@ iter oddsThenEvens( N: int ): int { for i in oddsThenEvens( 10 ) do write( i, ", " ); writeln( ); -// The 'zippered' iterator is an iterator that takes two or more iterators that -// have the same number of iterations and zips them together into one stream - // Ranges have implicit iterators -for (odd, even) in zip( 1..#10 by 2, 2..#10 by 2 ) do - writeln( (odd, even) ); +// We can zipper together two or more iterators (who have the same number +// of iterations) using zip() to create a single zipped iterator, where each +// iteration of the zipped iterator yields a tuple of one value yielded +// from each iterator. + // Ranges have implicit iterators +for (positive, negative) in zip( 1..5, -5..-1) do + writeln( (positive, negative) ); // Classes are similar to those in C++ and Java. // They currently lack privatization -- cgit v1.2.3 From b27d5268227f8812c894a217a08fd8c6221d1797 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 15:37:01 -0700 Subject: Added modules and main() Worth noting that this will change the diff of the parallel section quite a bit, since they became the body of the main procedure. Thus each line in intented. --- chapel.html.markdown | 462 ++++++++++++++++++++++++++++----------------------- 1 file changed, 258 insertions(+), 204 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index cfde0454..d8783728 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -673,234 +673,288 @@ var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); writeln( ); -// Parallelism -// In other languages, parallelism is typically this is done with -// complicated libraries and strange class structure hierarchies. -// Chapel has it baked right into the language. - -// A begin statement will spin the body of that statement off into one new task. -// A sync statement will ensure that the progress of the main -// task will not progress until the children have synced back up. -sync { - begin { // Start of new task's body - var a = 0; - for i in 1..1000 do a += 1; - writeln( "Done: ", a); - } // End of new tasks body - writeln( "spun off a task!"); -} -writeln( "Back together" ); -proc printFibb( n: int ){ - writeln( "fibonacci(",n,") = ", fibonacci( n ) ); -} +// Modules are Chapel's way of managing name spaces. +// The files containing these modules do not need to be named after the modules +// (as is with Java), but files implicitly name modules. +// In this case, this file implicitly names the 'learnchapel' module -// A cobegin statement will spin each statement of the body into one new task -cobegin { - printFibb( 20 ); // new task - printFibb( 10 ); // new task - printFibb( 5 ); // new task - { - // This is a nested statement body and thus is a single statement - // to the parent statement and is executed by a single task - writeln( "this gets" ); - writeln( "executed as" ); - writeln( "a whole" ); +module OurModule { + // We can use modules inside of other modules. + use Time; + + // We'll use this a procedure in the parallelism section. + proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } + } + + // Submodule of Ourmodule + // It is possible to create arbitrarily deep module nests. + module ChildModule { + proc foo(){ + writeln( "ChildModule.foo()"); + } } -} -// Notice here that the prints from each statement may happen in any order. - -// Coforall loop will create a new task for EACH iteration -var num_tasks = 10; // Number of tasks we want -coforall taskID in 1..#num_tasks { - writeln( "Hello from task# ", taskID ); -} -// Again we see that prints happen in any order. -// NOTE! coforall should be used only for creating tasks! -// Using it to iterating over a structure is very a bad idea! - -// forall loops are another parallel loop, but only create a smaller number -// of tasks, specifically --dataParTasksPerLocale=number of task -forall i in 1..100 { - write( i, ", "); -} -writeln( ); -// Here we see that there are sections that are in order, followed by -// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). -// This is because each task is taking on a chunk of the range 1..10 -// (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens -// in parallel. -// Your results may depend on your machine and configuration - -// For both the forall and coforall loops, the execution of the -// parent task will not continue until all the children sync up. - -// forall loops are particularly useful for parallel iteration over arrays. -// Lets run an experiment to see how much faster a parallel loop is -use Time; // Import the Time module to use Timer objects -var timer: Timer; -var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into - -// Serial Experiment -timer.start( ); // Start timer -for (x,y) in myBigArray.domain { // Serial iteration - myBigArray[x,y] = (x:real) / (y:real); -} -timer.stop( ); // Stop timer -writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time -timer.clear( ); // Clear timer for parallel loop - -// Parallel Experiment -timer.start( ); // start timer -forall (x,y) in myBigArray.domain { // Parallel iteration - myBigArray[x,y] = (x:real) / (y:real); -} -timer.stop( ); // Stop timer -writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time -timer.clear( ); -// You may have noticed that (depending on how many cores you have) -// that the parallel loop went faster than the serial loop - -// A succinct way of writing a forall loop over an array: -// iterate over values -[ val in myBigArray ] val = 1 / val; - -// or iterate over indicies -[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; - -proc countdown( seconds: int ){ - for i in 1..seconds by -1 { - writeln( i ); - sleep( 1 ); + + module SiblingModule { + proc foo(){ + writeln( "SiblingModule.foo()" ); + } } -} +} // end OurModule + +// Using OurModule also uses all the modules it uses. +// Since OurModule uses Time, we also use time. +use OurModule; + +// At this point we have not used ChildModule or SiblingModule so their symbols +// (i.e. foo ) are not available to us. +// However, the module names are, and we can explicitly call foo() through them. +SiblingModule.foo(); // Calls SiblingModule.foo() + +// Super explicit naming. +OurModule.ChildModule.foo(); // Calls ChildModule.foo() + +use ChildModule; +foo(); // Less explicit call on ChildModule.foo() + +// We can declare a main procedure +// Note: all the code above main still gets executed. +proc main(){ + + // Parallelism + // In other languages, parallelism is typically this is done with + // complicated libraries and strange class structure hierarchies. + // Chapel has it baked right into the language. + + // A begin statement will spin the body of that statement off + // into one new task. + // A sync statement will ensure that the progress of the main + // task will not progress until the children have synced back up. + sync { + begin { // Start of new task's body + var a = 0; + for i in 1..1000 do a += 1; + writeln( "Done: ", a); + } // End of new tasks body + writeln( "spun off a task!"); + } + writeln( "Back together" ); -// Atomic variables, common to many languages, are ones whose operations -// occur uninterupted. Multiple threads can both modify atomic variables -// and can know that their values are safe. -// Chapel atomic variables can be of type bool, int, uint, and real. -var uranium: atomic int; -uranium.write( 238 ); // atomically write a variable -writeln( uranium.read() ); // atomically read a variable - -// operations are described as functions, you could define your own operators. -uranium.sub( 3 ); // atomically subtract a variable -writeln( uranium.read() ); - -var replaceWith = 239; -var was = uranium.exchange( replaceWith ); -writeln( "uranium was ", was, " but is now ", replaceWith ); - -var isEqualTo = 235; -if uranium.compareExchange( isEqualTo, replaceWith ) { - writeln( "uranium was equal to ", isEqualTo, - " so replaced value with ", replaceWith ); -} else { - writeln( "uranium was not equal to ", isEqualTo, - " so value stays the same... whatever it was" ); -} + proc printFibb( n: int ){ + writeln( "fibonacci(",n,") = ", fibonacci( n ) ); + } -sync { - begin { // Reader task - writeln( "Reader: waiting for uranium to be ", isEqualTo ); - uranium.waitFor( isEqualTo ); - writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); + // A cobegin statement will spin each statement of the body into one new task + cobegin { + printFibb( 20 ); // new task + printFibb( 10 ); // new task + printFibb( 5 ); // new task + { + // This is a nested statement body and thus is a single statement + // to the parent statement and is executed by a single task + writeln( "this gets" ); + writeln( "executed as" ); + writeln( "a whole" ); + } } + // Notice here that the prints from each statement may happen in any order. - begin { // Writer task - writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); - countdown( 3 ); - uranium.write( isEqualTo ); + // Coforall loop will create a new task for EACH iteration + var num_tasks = 10; // Number of tasks we want + coforall taskID in 1..#num_tasks { + writeln( "Hello from task# ", taskID ); + } + // Again we see that prints happen in any order. + // NOTE! coforall should be used only for creating tasks! + // Using it to iterating over a structure is very a bad idea! + + // forall loops are another parallel loop, but only create a smaller number + // of tasks, specifically --dataParTasksPerLocale=number of task + forall i in 1..100 { + write( i, ", "); + } + writeln( ); + // Here we see that there are sections that are in order, followed by + // a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). + // This is because each task is taking on a chunk of the range 1..10 + // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens + // in parallel. + // Your results may depend on your machine and configuration + + // For both the forall and coforall loops, the execution of the + // parent task will not continue until all the children sync up. + + // forall loops are particularly useful for parallel iteration over arrays. + // Lets run an experiment to see how much faster a parallel loop is + use Time; // Import the Time module to use Timer objects + var timer: Timer; + var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into + + // Serial Experiment + timer.start( ); // Start timer + for (x,y) in myBigArray.domain { // Serial iteration + myBigArray[x,y] = (x:real) / (y:real); + } + timer.stop( ); // Stop timer + writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time + timer.clear( ); // Clear timer for parallel loop + + // Parallel Experiment + timer.start( ); // start timer + forall (x,y) in myBigArray.domain { // Parallel iteration + myBigArray[x,y] = (x:real) / (y:real); + } + timer.stop( ); // Stop timer + writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time + timer.clear( ); + // You may have noticed that (depending on how many cores you have) + // that the parallel loop went faster than the serial loop + + // A succinct way of writing a forall loop over an array: + // iterate over values + [ val in myBigArray ] val = 1 / val; + + // or iterate over indicies + [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; + + proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } } -} -// sync vars have two states: empty and full. -// If you read an empty variable or write a full variable, you are waited -// until the variable is full or empty again -var someSyncVar$: sync int; // varName$ is a convention not a law. -sync { - begin { // Reader task - writeln( "Reader: waiting to read." ); - var read_sync = someSyncVar$; - writeln( "value is ", read_sync ); + // Atomic variables, common to many languages, are ones whose operations + // occur uninterupted. Multiple threads can both modify atomic variables + // and can know that their values are safe. + // Chapel atomic variables can be of type bool, int, uint, and real. + var uranium: atomic int; + uranium.write( 238 ); // atomically write a variable + writeln( uranium.read() ); // atomically read a variable + + // operations are described as functions, you could define your own operators. + uranium.sub( 3 ); // atomically subtract a variable + writeln( uranium.read() ); + + var replaceWith = 239; + var was = uranium.exchange( replaceWith ); + writeln( "uranium was ", was, " but is now ", replaceWith ); + + var isEqualTo = 235; + if uranium.compareExchange( isEqualTo, replaceWith ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); + } else { + writeln( "uranium was not equal to ", isEqualTo, + " so value stays the same... whatever it was" ); } - begin { // Writer task - writeln( "Writer: will write in..." ); - countdown( 3 ); - someSyncVar$ = 123; + sync { + begin { // Reader task + writeln( "Reader: waiting for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); + } + + begin { // Writer task + writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); + countdown( 3 ); + uranium.write( isEqualTo ); + } } -} -// single vars can only be written once. A read on an unwritten single results -// in a wait, but when the variable has a value it can be read indefinitely -var someSingleVar$: single int; // varName$ is a convention not a law. -sync { - begin { // Reader task - writeln( "Reader: waiting to read." ); - for i in 1..5 { - var read_single = someSingleVar$; - writeln( "Reader: iteration ", i,", and the value is ", read_single ); + // sync vars have two states: empty and full. + // If you read an empty variable or write a full variable, you are waited + // until the variable is full or empty again + var someSyncVar$: sync int; // varName$ is a convention not a law. + sync { + begin { // Reader task + writeln( "Reader: waiting to read." ); + var read_sync = someSyncVar$; + writeln( "value is ", read_sync ); + } + + begin { // Writer task + writeln( "Writer: will write in..." ); + countdown( 3 ); + someSyncVar$ = 123; } } - begin { // Writer task - writeln( "Writer: will write in..." ); - countdown( 3 ); - someSingleVar$ = 5; // first and only write ever. + // single vars can only be written once. A read on an unwritten single results + // in a wait, but when the variable has a value it can be read indefinitely + var someSingleVar$: single int; // varName$ is a convention not a law. + sync { + begin { // Reader task + writeln( "Reader: waiting to read." ); + for i in 1..5 { + var read_single = someSingleVar$; + writeln( "Reader: iteration ", i,", and the value is ", read_single ); + } + } + + begin { // Writer task + writeln( "Writer: will write in..." ); + countdown( 3 ); + someSingleVar$ = 5; // first and only write ever. + } } -} -// Heres an example of using atomics and a synch variable to create a -// count-down mutex (also known as a multiplexer) -var count: atomic int; // our counter -var lock$: sync bool; // the mutex lock - -count.write( 2 ); // Only let two tasks in at a time. -lock$.writeXF( true ); // Set lock$ to full (unlocked) -// Note: The value doesnt actually matter, just the state -// (full:unlocked / empty:locked) -// Also, writeXF() fills (F) the sync var regardless of its state (X) - -coforall task in 1..#5 { // Generate tasks - // Create a barrier - do{ - lock$; // Read lock$ (wait) - }while count.read() < 1; // Keep waiting until a spot opens up + // Heres an example of using atomics and a synch variable to create a + // count-down mutex (also known as a multiplexer) + var count: atomic int; // our counter + var lock$: sync bool; // the mutex lock + + count.write( 2 ); // Only let two tasks in at a time. + lock$.writeXF( true ); // Set lock$ to full (unlocked) + // Note: The value doesnt actually matter, just the state + // (full:unlocked / empty:locked) + // Also, writeXF() fills (F) the sync var regardless of its state (X) + + coforall task in 1..#5 { // Generate tasks + // Create a barrier + do{ + lock$; // Read lock$ (wait) + }while count.read() < 1; // Keep waiting until a spot opens up - count.sub(1); // decrement the counter - lock$.writeXF( true ); // Set lock$ to full (signal) + count.sub(1); // decrement the counter + lock$.writeXF( true ); // Set lock$ to full (signal) - // Actual 'work' - writeln( "Task #", task, " doing work." ); - sleep( 2 ); + // Actual 'work' + writeln( "Task #", task, " doing work." ); + sleep( 2 ); - count.add( 1 ); // Increment the counter - lock$.writeXF( true ); // Set lock$ to full (signal) -} + count.add( 1 ); // Increment the counter + lock$.writeXF( true ); // Set lock$ to full (signal) + } -// we can define the operations + * & | ^ && || min max minloc maxloc -// over an entire array using scans and reductions -// Reductions apply the operation over the entire array and -// result in a single value -var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; -var sumOfValues = + reduce listOfValues; -var maxValue = max reduce listOfValues; // 'max' give just max value - -// 'maxloc' gives max value and index of the max value -// Note: We have to zip the array and domain together with the zip iterator -var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, - listOfValues.domain); + // we can define the operations + * & | ^ && || min max minloc maxloc + // over an entire array using scans and reductions + // Reductions apply the operation over the entire array and + // result in a single value + var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; + var sumOfValues = + reduce listOfValues; + var maxValue = max reduce listOfValues; // 'max' give just max value + + // 'maxloc' gives max value and index of the max value + // Note: We have to zip the array and domain together with the zip iterator + var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, + listOfValues.domain); -writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); - -// Scans apply the operation incrementally and return an array of the -// value of the operation at that index as it progressed through the -// array from array.domain.low to array.domain.high -var runningSumOfValues = + scan listOfValues; -var maxScan = max scan listOfValues; -writeln( runningSumOfValues ); -writeln( maxScan ); + writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); + + // Scans apply the operation incrementally and return an array of the + // value of the operation at that index as it progressed through the + // array from array.domain.low to array.domain.high + var runningSumOfValues = + scan listOfValues; + var maxScan = max scan listOfValues; + writeln( runningSumOfValues ); + writeln( maxScan ); +} ``` Who is this tutorial for? -- cgit v1.2.3 From 27cc82076214e68d9d93c90aafe5ae567fe78892 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 15:44:16 -0700 Subject: Uniform tics, noteable arguments addition. Changed all N-tics for preformatted/code text into single tics if that code was sinle line (i.e. bash commands, compiler arguments) Added --main-module, --module-dir to Notable arguments section. Realized that the text was disappering, so changed it to ``. Need to confirm it success. --- chapel.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d8783728..14bbe9f5 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -968,9 +968,8 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to ### What this tutorial is lacking: - * Modules and standard modules + * Exposition of the standard modules * Multiple Locales (distributed memory system) - * ```proc main(){ ... }``` * Records * Whole/sliced array assignment * Range and domain slicing @@ -994,26 +993,28 @@ Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as - 1. ```tar -xvf chapel-1.11.0.tar.gz``` - 2. ```cd chapel-1.11.0``` - 3. ```make``` - 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + 1. `tar -xvf chapel-1.11.0.tar.gz` + 2. `cd chapel-1.11.0` + 3. `make` + 4. `source util/setchplenv.bash # or .sh or .csh or .fish` You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X - 1. ```brew update``` - 2. ```brew install chapel``` + 1. `brew update` + 2. `brew install chapel` Compiling Code -------------- Builds like other compilers: -```chpl myFile.chpl -o myExe``` +`chpl myFile.chpl -o myExe` Notable arguments: - * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. - * ```--set =```: set config param to at compile-time + * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. + * `--set =`: set config param `` to `` at compile-time. + * `--main-module `: use the main() procedure found in the module `` as the executable's main. + * `--module-dir `: includes ` Date: Sun, 2 Aug 2015 15:53:19 -0700 Subject: Small corrections. Removed duplicate countDown. Weird leftover words from parallelism statemet General corrections so spelling capitalization --- chapel.html.markdown | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 14bbe9f5..a4bcfb9f 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -683,7 +683,7 @@ module OurModule { // We can use modules inside of other modules. use Time; - // We'll use this a procedure in the parallelism section. + // We'll use this procedure in the parallelism section. proc countdown( seconds: int ){ for i in 1..seconds by -1 { writeln( i ); @@ -691,7 +691,7 @@ module OurModule { } } - // Submodule of Ourmodule + // Submodules of OurModule // It is possible to create arbitrarily deep module nests. module ChildModule { proc foo(){ @@ -726,7 +726,7 @@ foo(); // Less explicit call on ChildModule.foo() proc main(){ // Parallelism - // In other languages, parallelism is typically this is done with + // In other languages, parallelism is typically done with // complicated libraries and strange class structure hierarchies. // Chapel has it baked right into the language. @@ -821,13 +821,6 @@ proc main(){ // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; - proc countdown( seconds: int ){ - for i in 1..seconds by -1 { - writeln( i ); - sleep( 1 ); - } - } - // Atomic variables, common to many languages, are ones whose operations // occur uninterupted. Multiple threads can both modify atomic variables // and can know that their values are safe. -- cgit v1.2.3 From 4f6ae05392504f63b5ddd5c23d81700bf6aa1b7a Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 16:05:19 -0700 Subject: Small changes no.2 --- chapel.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index a4bcfb9f..33bdc21d 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -673,15 +673,14 @@ var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); writeln( ); - // Modules are Chapel's way of managing name spaces. // The files containing these modules do not need to be named after the modules -// (as is with Java), but files implicitly name modules. +// (as in Java), but files implicitly name modules. // In this case, this file implicitly names the 'learnchapel' module module OurModule { // We can use modules inside of other modules. - use Time; + use Time; // Time is one of the standard modules. // We'll use this procedure in the parallelism section. proc countdown( seconds: int ){ @@ -947,7 +946,7 @@ proc main(){ var maxScan = max scan listOfValues; writeln( runningSumOfValues ); writeln( maxScan ); -} +} // end main() ``` Who is this tutorial for? @@ -1010,4 +1009,4 @@ Notable arguments: * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. * `--set =`: set config param `` to `` at compile-time. * `--main-module `: use the main() procedure found in the module `` as the executable's main. - * `--module-dir `: includes ``: includes `` in the module search path. \ No newline at end of file -- cgit v1.2.3 From 496b11f8ce33f38fc1e29c23ee8c4261a811b967 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:47:02 +0700 Subject: scala: consistent style, language correction --- scala.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index e6638121..12441af9 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -16,15 +16,16 @@ Scala - the scalable language Set yourself up: 1) Download Scala - http://www.scala-lang.org/downloads - 2) unzip/untar in your favourite location and put the bin subdir on the path - 3) Start a scala REPL by typing scala. You should see the prompt: + 2) Unzip/untar to your favourite location and put the bin subdir in your `PATH` environment variable + 3) Start a Scala REPL by running `scala`. You should see the prompt: scala> - This is the so called REPL (Read-Eval-Print Loop). You may type any valid - Scala expression into it, and the result will be printed. We will explain what - Scala files look like further into this tutorial, but for now, let's start - with some basics. + This is the so called REPL (Read-Eval-Print Loop). You may type any Scala + expression, and the result will be printed. We will explain what Scala files + look like further into this tutorial, but for now, let's start with some + basics. + */ -- cgit v1.2.3 From 9ddf69a14da14c0d29abb5a18b4d2dfd5a39c7b2 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:48:28 +0700 Subject: scala: language correction --- scala.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 12441af9..4121dc9b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -5,6 +5,7 @@ contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] filename: learn.scala --- @@ -33,10 +34,10 @@ Scala - the scalable language // 1. Basics ///////////////////////////////////////////////// -// Single line comments start with two forward slashes +// Single-line comments start with two forward slashes /* - Multi line comments, as you can already see from above, look like this. + Multi-line comments, as you can already see from above, look like this. */ // Printing, and forcing a new line on the next print -- cgit v1.2.3 From 8c06438ec9aec991b78bbd49d2343dc820da7669 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:49:15 +0700 Subject: scala: correct format --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 4121dc9b..03d80043 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -48,7 +48,7 @@ println(10) print("Hello world") // Declaring values is done using either var or val. -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -- cgit v1.2.3 From 5b683b34ddb313b8981f360c4a6b54cfbc3af396 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:49:54 +0700 Subject: scala: easier-to-look comment --- scala.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 03d80043..0bd1a56d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -51,9 +51,9 @@ print("Hello world") // val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 -x = 20 // error: reassignment to val +x = 20 // error: reassignment to val var y = 10 -y = 20 // y is now 20 +y = 20 // y is now 20 /* Scala is a statically typed language, yet note that in the above declarations, @@ -73,17 +73,17 @@ true false // Boolean operations -!true // false -!false // true +!true // false +!false // true true == false // false -10 > 5 // true +10 > 5 // true // Math is as per usual -1 + 1 // 2 -2 - 1 // 1 -5 * 3 // 15 -6 / 2 // 3 -6 / 4 // 1 +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 6.0 / 4 // 1.5 -- cgit v1.2.3 From dbdde5134b4c5777467a81c8fdf2128cb44edacc Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:50:32 +0700 Subject: scala: clearer comments --- scala.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 0bd1a56d..8d93169b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -122,12 +122,12 @@ s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." -s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "f" -f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. -- cgit v1.2.3 From efb338608b3b6e5af3652e71aa7fb85bdf5917b9 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:55:38 +0700 Subject: scala: consistent code format --- scala.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 8d93169b..62af31b6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -173,8 +173,8 @@ def sq(x: Int) = x * x // Compiler can guess return type is Int // Functions can have default parameters: def addWithDefault(x: Int, y: Int = 5) = x + y -addWithDefault(1, 2) // => 3 -addWithDefault(1) // => 6 +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 // Anonymous functions look like this: @@ -195,8 +195,8 @@ sq(10) // => 100 val addOne: Int => Int = _ + 1 val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) -addOne(5) // => 6 -weirdSum(2, 4) // => 16 +addOne(5) // => 6 +weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most @@ -206,9 +206,9 @@ weirdSum(2, 4) // => 16 def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of foo! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonFunc } anonFunc(x) // This line is the return value of foo } @@ -361,7 +361,7 @@ class Dog(br: String) { val mydog = new Dog("greyhound") println(mydog.breed) // => "greyhound" -println(mydog.bark) // => "Woof, woof!" +println(mydog.bark) // => "Woof, woof!" // The "object" keyword creates a type AND a singleton instance of it. It is @@ -543,8 +543,8 @@ implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) // By itself, implicit keyword doesn't change the behavior of the value, so // above values can be used as usual. -myImplicitInt + 2 // => 102 -myImplicitFunction("Pitbull").breed // => "Golden Pitbull" +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" // The difference is that these values are now eligible to be used when another // piece of code "needs" an implicit value. One such situation is implicit @@ -572,8 +572,8 @@ def foo[T : C] = ... // implicit conversion of type A => B, where A is the type of obj, and B has a // method called "method", that conversion is applied. So having // myImplicitFunction above in scope, we can say: -"Retriever".breed // => "Golden Retriever" -"Sheperd".bark // => "Woof, woof!" +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" // Here the String is first converted to Dog using our function above, and then // the appropriate method is called. This is an extremely powerful feature, but -- cgit v1.2.3 From 7c02089687eaee9c1fe9b1db3ab0674153077f56 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:55:59 +0700 Subject: scala: consistent code format --- scala.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 62af31b6..35042ebe 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -220,19 +220,19 @@ def foo(x: Int): Int = { 1 to 5 val r = 1 to 5 -r.foreach( println ) +r.foreach(println) r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English -(5 to 1 by -1) foreach ( println ) +(5 to 1 by -1) foreach (println) // A while loops var i = 0 -while (i < 10) { println("i " + i); i+=1 } +while (i < 10) { println("i " + i); i += 1 } -while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? +while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why? i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very @@ -241,19 +241,19 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less than 10"); + println("x is still less than 10") x += 1 } while (x < 10) // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. -def showNumbersInRange(a:Int, b:Int):Unit = { +def showNumbersInRange(a:Int, b:Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) } -showNumbersInRange(1,14) +showNumbersInRange(1, 14) // Conditionals @@ -307,13 +307,13 @@ s(1) (a, 2, "three") // Why have this? -val divideInts = (x:Int, y:Int) => (x / y, x % y) +val divideInts = (x: Int, y: Int) => (x / y, x % y) -divideInts(10,3) // The function divideInts gives you the result and the remainder +divideInts(10, 3) // The function divideInts gives you the result and the remainder // To access the elements of a tuple, use _._n where n is the 1-based index of // the element -val d = divideInts(10,3) +val d = divideInts(10, 3) d._1 @@ -416,8 +416,8 @@ val otherGeorge = george.copy(phoneNumber = "9876") def matchPerson(person: Person): String = person match { // Then you specify the patterns: case Person("George", number) => "We found George! His number is " + number - case Person("Kate", number) => "We found Kate! Her number is " + number - case Person(name, number) => "We matched someone : " + name + ", phone : " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number } val email = "(.*)@(.*)".r // Define a regex for the next example. @@ -448,7 +448,7 @@ def matchEverything(obj: Any): String = obj match { case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" // You can nest patterns: - case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" + case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" } // In fact, you can pattern match any object with an "unapply" method. This @@ -495,7 +495,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, age:Int) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -596,7 +596,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // Rename an import using '=>' -import scala.collection.immutable.{ List => ImmutableList } +import scala.collection.immutable.{List => ImmutableList} // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -- cgit v1.2.3 From 513235c4754f87e64e5d564bb53ec643ce9333df Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:56:11 +0700 Subject: scala: clearer further resources (itemized) --- scala.html.markdown | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 35042ebe..10db5f78 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -631,13 +631,8 @@ writer.close() ## Further resources -[Scala for the impatient](http://horstmann.com/scala/) - -[Twitter Scala school](http://twitter.github.io/scala_school/) - -[The scala documentation](http://docs.scala-lang.org/) - -[Try Scala in your browser](http://scalatutorials.com/tour/) - -Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) - +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From d61ad107759c99de3dd32dc848086c16dbb14f15 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:58:36 +0700 Subject: scala: consistent code format --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 10db5f78..c482752d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -178,7 +178,7 @@ addWithDefault(1) // => 6 // Anonymous functions look like this: -(x:Int) => x * x +(x: Int) => x * x // Unlike defs, even the input type of anonymous functions can be omitted if the // context makes it clear. Notice the type "Int => Int" which means a function @@ -248,7 +248,7 @@ do { // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. -def showNumbersInRange(a:Int, b:Int): Unit = { +def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) -- cgit v1.2.3 From c4558c47eaf08d7a1d22789f1b0a38c23260fd18 Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:05:22 -0400 Subject: Println deprecated in Swift 2 --- swift.html.markdown | 56 +++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index ffc57e69..8e83a0b3 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,7 +26,9 @@ import UIKit // TODO: Do something soon // FIXME: Fix this code -println("Hello, world") +// In Swift 2, println and print were combined into one print method. +print("Hello, world") // standard print +print("Hello, world", appendNewLine: true) // appending a new line // variables (var) value can change after being set // constants (let) value can NOT be changed after being set @@ -46,12 +48,12 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation // Build Specific values // uses -D build configuration #if false - println("Not printed") + print("Not printed") let buildValue = 3 #else let buildValue = 7 #endif -println("Build value: \(buildValue)") // Build value: 7 +print("Build value: \(buildValue)") // Build value: 7 /* Optionals are a Swift language feature that allows you to store a `Some` or @@ -69,7 +71,7 @@ var someOptionalString2: Optional = "optional" if someOptionalString != nil { // I am not nil if someOptionalString!.hasPrefix("opt") { - println("has the prefix") + print("has the prefix") } let empty = someOptionalString?.isEmpty @@ -138,21 +140,21 @@ var emptyMutableDictionary = [String: Float]() // var == mutable let myArray = [1, 1, 2, 3, 5] for value in myArray { if value == 1 { - println("One!") + print("One!") } else { - println("Not one!") + print("Not one!") } } // for loop (dictionary) var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + print("\(key): \(value)") } // for loop (range) for i in -1...shoppingList.count { - println(i) + print(i) } shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number @@ -165,7 +167,7 @@ while i < 1000 { // do-while loop do { - println("hello") + print("hello") } while 1 == 2 // Switch @@ -222,8 +224,8 @@ let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 // Ignore Tuple (or other) values by using _ (underscore) let (_, price1, _) = pricesTuple // price1 == 3.69 -println(price1 == pricesTuple.1) // true -println("Gas price: \(price)") +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") // Variadic Args func setup(numbers: Int...) { @@ -251,7 +253,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { var someIntA = 7 var someIntB = 3 swapTwoInts(&someIntA, &someIntB) -println(someIntB) // 7 +print(someIntB) // 7 // @@ -305,7 +307,7 @@ struct NamesTable { // Structures have an auto-generated (implicit) designated initializer let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] -println("Name is \(name)") // Name is Them +print("Name is \(name)") // Name is Them // // MARK: Classes @@ -386,7 +388,7 @@ let aShape = mySquare as Shape // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep, it's mySquare") + print("Yep, it's mySquare") } // Optional init @@ -409,13 +411,13 @@ class Circle: Shape { } var myCircle = Circle(radius: 1) -println(myCircle?.getArea()) // Optional(3) -println(myCircle!.getArea()) // 3 +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 var myEmptyCircle = Circle(radius: -1) -println(myEmptyCircle?.getArea()) // "nil" +print(myEmptyCircle?.getArea()) // "nil" if let circle = myEmptyCircle { // will not execute since myEmptyCircle is nil - println("circle is not nil") + print("circle is not nil") } @@ -447,7 +449,7 @@ enum BookName: String { case John = "John" case Luke = "Luke" } -println("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.John.rawValue)") // Enum with associated Values enum Furniture { @@ -467,9 +469,9 @@ enum Furniture { } var desk: Furniture = .Desk(height: 80) -println(desk.description()) // "Desk with 80 cm" +print(desk.description()) // "Desk with 80 cm" var chair = Furniture.Chair("Foo", 40) -println(chair.description()) // "Chair of Foo with 40 cm" +print(chair.description()) // "Chair of Foo with 40 cm" // @@ -522,7 +524,7 @@ extension Square: Printable { } } -println("Square: \(mySquare)") +print("Square: \(mySquare)") // You can also extend built-in types extension Int { @@ -535,8 +537,8 @@ extension Int { } } -println(7.customProperty) // "This is 7" -println(14.multiplyBy(3)) // 42 +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. @@ -550,7 +552,7 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } let foundAtIndex = findIndex([1, 2, 3, 4], 3) -println(foundAtIndex == 2) // true +print(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -566,9 +568,9 @@ prefix func !!! (inout shape: Square) -> Square { } // current value -println(mySquare.sideLength) // 4 +print(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare -println(mySquare.sideLength) // 12 +print(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From 775ac3b8595f80dd3229b7974672cf71d642d94f Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:10:10 -0400 Subject: Updated print description on Swift --- swift.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 8e83a0b3..5ea8da6b 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,9 +26,9 @@ import UIKit // TODO: Do something soon // FIXME: Fix this code -// In Swift 2, println and print were combined into one print method. -print("Hello, world") // standard print -print("Hello, world", appendNewLine: true) // appending a new line +// In Swift 2, println and print were combined into one print method. Print automatically appends a new line. +print("Hello, world") // println is now print +print("Hello, world", appendNewLine: false) // printing without appending a newline // variables (var) value can change after being set // constants (let) value can NOT be changed after being set -- cgit v1.2.3 From d17d41a02b5eb67b0b28a9708cfa5640e17325ef Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:11:44 -0400 Subject: Println deprecated in Swift 2, added name --- swift.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/swift.html.markdown b/swift.html.markdown index 5ea8da6b..509c9d2f 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] filename: learnswift.swift --- -- cgit v1.2.3 From f27ed65af631279845b9871635e2118eba863ea1 Mon Sep 17 00:00:00 2001 From: billpcs Date: Wed, 5 Aug 2015 16:40:37 +0300 Subject: added the translations --- el-gr/racket-gr.html.markdown | 746 ++++++++++++++++++++++++++++++++++++++++++ el-gr/scala-gr.html.markdown | 690 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 1436 insertions(+) create mode 100644 el-gr/racket-gr.html.markdown create mode 100644 el-gr/scala-gr.html.markdown diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown new file mode 100644 index 00000000..6a3f99ef --- /dev/null +++ b/el-gr/racket-gr.html.markdown @@ -0,0 +1,746 @@ +---σ +language: racket +filename: learnracket.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] + - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] + - ["Duong H. Nguyen", "https://github.com/cmpitg"] + - ["Keyan Zhang", "https://github.com/keyanzhang"] +translators: + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +--- + +Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. + +Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3rac25) or th3rac25 [at] [google's email service] + + +```racket +#lang racket ; ορίζει την γλώσσα που χρησιμοποιόυμε + +;;; Σχόλια + +;; Τα σχόλια μιας γραμμής ξεκινούν με ερωτηματικό + +#| Τα σχόλια ολόκληρου μπλόκ + μπορούν να εκτείνονται σε πολλές γραμμές και... + #| + μπορούν να είναι εμφωλευμένα! + |# +|# + +;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την +;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να +;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging + +#; (αυτή η έκφραση δεν θα εκτελεστεί) + +;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε +;; πολύ συντομα!) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Πρωτογενείς τύποι μεταβλητών και τελεστές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Αριθμοί +9999999999999999999999 ; ακέραιοι +#b111 ; δυαδικοί => 7 +#o111 ; οκταδικοί => 73 +#x111 ; δεκαεξαδικοί => 273 +3.14 ; πραγματικοί +6.02e+23 +1/2 ; ρητοί +1+2i ; μιγαδικοί + +;; Οι μορφή των συναρτήσεων είναι (f x y z) +;; όπου το f είναι η συνάρτηση και τα x y z +;; είναι οι όροι που η συνάρτηση δέχεται +;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε +;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να +;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: +'(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη +;; Τώρα , ας κάνουμε μερικές πράξεις +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; Λογικές μεταβλητές +#t ; για το true +#f ; για το false +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; Χαρακτήρες +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής +"Foo\tbar\41\x21\u0021\a\r\n" ; συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, + ; σε Unicode +"λx:(μα.α→α).xx" ; μπορούν να υπάρχουν και Unicode χαρακτήρες + +;; Μπορούμε να εννώσουμε αλφαριθμητικά! +(string-append "Hello " "world!") ; => "Hello world!" + +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε +;; όπως και μια λίστα απο χαρακτήρες +(string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο + +;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για +;; να μορφοποιήσουμε αλφαριθμητικά +(format "~a can be ~a" "strings" "formatted") ;; => "strings can be formatted" + +;; Η εκτύπωση είναι εύκολη. +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Μεταβλητές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; You can create a variable using define +;; a variable name can use any character except: ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; You can also use unicode characters +(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? + ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ +(printf name) +;; θα πάρουμε το παρακάτω μήνυμα +;name: undefined; +; cannot reference undefined identifier +; context...: + +;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...) +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Δομές και συλλογές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Δομές +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => # +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; Ζεύγη (αμετάβλητα) +;; Η δεσμευμένη λέξη `cons' δημιουργεί ζεύγη, +;; και το `car' και το `cdr' εξάγουν το πρώτο και +;; το δεύτερο στοιχείο αντίστοιχα. +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; Λίστες + +;; Οι λίστες είναι linked-list δομές δεδομένων, +;; που έχουν δημιουργηθεί απο ζευγάρια 'cons' +;; και τελειώνουν με 'null' (ή αλλιώς '()) για να +;; δηλώσουν ότι αυτό είναι το τέλος της λίστας +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; Η δεσμευμένη λέξη 'list' είναι ένας εναλλακτικός +;; (και σαφώς πιο βολικός) τρόπος για να δημιουργούμε +;; λίστες +(list 1 2 3) ; => '(1 2 3) +;; αλλά και χρησιμοποιώντας ένα μονό εισαγωγικό το +;; το αποτέλεσμα είναι και πάλι το ίδιο +'(1 2 3) ; => '(1 2 3) + +;; Μπορούμε και πάλι όμως να χρησιμοποιούμε το 'cons' για να +;; προσθέσουμε ένα στοιχείο στην αρχή της λίστας +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Μπορούμε να χρησιμοποιούμε το 'append' για να προσθέτουμε +;; στοιχεία στο τέλος μιας λίστας. Το στοιχείο αυτό μπορεί +;; και να είναι ολόκληρη λίστα! +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Οι λίστες στην Racket είναι πολύ βασικές , οπότε υπάρχουν πολλές +;; δυνατές λειτουργίες για αυτές. Παρακάτω είναι μερικά παραδείγματα: +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; Διανύσματα + +;; Τα διανύσματα είναι πίνακες σταθερού μήκους +#(1 2 3) ; => '#(1 2 3) + +;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Σύνολα + +;; Δημιουργούμε ένα σύνολο απο μία λίστα +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; Αφαιρούμε με το `set-remove' +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; Βλέπουμε αν υπάρχει ένας αριθμός στο σύνολο με το `set-member?' +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; Πίνακες κατακερματισμού + +;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού +(define m (hash 'a 1 'b 2 'c 3)) + +;; Παίρνουμε μια τιμή απο τον πίνακα +(hash-ref m 'a) ; => 1 + +;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση +; (hash-ref m 'd) => no value found for key + +;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν +(hash-ref m 'd 0) ; => 0 + + +;; Χρησιμοποιούμε το 'hash-set' για να επεκτείνουμε +;; ένα πίνακα κατακερματισμού +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; Θυμηθείτε ! Αυτοί οι πίνακες κατακερματισμού +;; είναι αμετάβλητοι! +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' + +;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε +;; κλειδία +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Συναρτήσεις +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Χρησιμοποιούμε το `lambda' για να δημιουργήσουμε συναρτήσεις. +;; Μια συνάρτηση πάντα επιστρέφει την τιμή της τελευταίας της έκφρασης +(lambda () "Hello World") ; => # +;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' +(λ () "Hello World") ; => Ίδια συνάρτηση + +;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; Μπορούμε αυτό να το κάνουμε συντομότερο χρησιμοποιώντας +;; το λεγόμενο syntactic sugar : +(define (hello-world2) "Hello World") + +;; Το () στο παραπάνω είναι η λίστα από τα ορίσματα για την συνάρτηση + +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; ... ή ισοδύναμα, χρησιμοποιώντας sugared ορισμό: +(define (hello2 name) + (string-append "Hello " name)) + +;; Μπορούμε να έχουμε συναρτήσεις με πολλές μεταβλητές χρησιμοποιώντας +;; το `case-lambda' +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; ... ή να ορίσουμε προαιρετικά ορίσματα με μια έκφραση προκαθορισμένης τιμής +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; Οι συναρτήσεις μπορούν να πακετάρουν επιπλέον +;; ορίσματα μέσα σε μια λίστα +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; ... ή με unsugared μορφή `lambda': +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; Μπορούμε να εμπλέξουμε κανονικά και πακεταρισμένα ορίσματα +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; ... και unsugared: +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; Και με λέξεις κλειδία +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Ισότητα +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; για αριθμούς χρησιμοποιούμε το `=' +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; Το `eq?' επιστρέφει #t αν δύο 2 ορίσματα αναφέρονται στο +;; ίδιο αντικείμενο (στη μνήμη),αλλιώς επιστρέφει #f. +;; Με άλλα λόγια, είναι απλή σύγκριση δεικτών. +(eq? '() '()) ; => #t, αφού υπάρχει μόνο μια άδεια λίστα στη μνήμη +(let ([x '()] [y '()]) + (eq? x y)) ; => #t, το ίδιο με πάνω + +(eq? (list 3) (list 3)) ; => #f +(let ([x (list 3)] [y (list 3)]) + (eq? x y)) ; => #f — δεν είναι η ίδια λίστα στην μνήμη! + +(let* ([x (list 3)] [y x]) + (eq? x y)) ; => #t, Αφού το x και το y τώρα δείχνουν στην ίδια θέση + +(eq? 'yes 'yes) ; => #t +(eq? 'yes 'no) ; => #f + +(eq? 3 3) ; => #t — να είστε προσεκτικοί εδώ + ; Είναι προτιμότερο να χρησιμοποιείτε `=' για την + ; σύγκριση αριθμών. +(eq? 3 3.0) ; => #f + +(eq? (expt 2 100) (expt 2 100)) ; => #f +(eq? (integer->char 955) (integer->char 955)) ; => #f + +(eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων +;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. +(eqv? 3 3.0) ; => #f +(eqv? (expt 2 100) (expt 2 100)) ; => #t +(eqv? (integer->char 955) (integer->char 955)) ; => #t + +(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; Το `equal?' υποστηρίζει την σύγκριση των παρακάτω τύπων μεταβλητών: +;; `equal?' supports the comparison of the following datatypes: +;; αλφαριθμητικά, αλφαριθμητικά από bytes, μεταβλητά ζεύγη , διανύσματα, +;; πίνακες κατακερματισμού και δομές. +;; Για άλλα ήδη τύπων μεταβλητών το `equal?' και το `eqv?' επιστρέφουν το +;; ίδιο αποτέλεσμα. +(equal? 3 3.0) ; => #f +(equal? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #t +(equal? (list 3) (list 3)) ; => #t + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Έλεχγος Ροής +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Συνθήκες (conditionals) + +(if #t ; έκφραση ελέχγου + "this is true" ; έκφραση then + "this is false") ; έκφραση else +; => "this is true" + + +;; Στα conditionals, όλες οι μη #f τιμές θεωρούνται ως #t +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; Οι αλυσίδες `cond' είναι σειρές από ελέγχους για να +;; επιλεγεί ένα αποτέλεσμα +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; Αντιστοίχιση μοτίβων + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; Βρόχοι + +;; Οι επαναλήψεις μπορούν να γίνουν μέσω αναδρομής +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; Παρομοίως με τη χρήση 'let' +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + + +;; Θα δείτε παρακάτω πως να προσθέσουμε μια νέα μορφή επανάληψης +;; αλλά η Racket έχει ήδη πολύ ευέλικτη μορφή για τους βρόχους +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; +;;; Επανάληψη μέσα σε ακολουθίες: +;; Το `for' επιτρέπει την επενάληψη μέσα σε πολλά +;; άλλα ήδη από ακολουθίες: Λίστες, διανύσματα, +;; αλφαριθμητικά, σύνολα κτλ.. + +;;allows iteration over many other kinds of sequences: +;; lists, vectors, strings, sets, hash tables, etc... + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; Πιο περίπλοκες επαναλήψεις + +;; Παράλληλη σάρωση σε πολλαπλές ακολουθίες +;; (σταματά στην πιο σύντομη) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; Εμφολευμένοι βρόχοι +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; Συνθήκες +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; Σάρωση σε λίστες +;; Παρόμοιο με τους βρόχους 'for', απλά συλλέγουμε τα αποτελέσματα + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε +;; τιμές από τους βρόχους +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t +;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιύμε +;; το 'for/fold' +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 +;; Αυτό συχνά μπορεί να αντικαταστήσει τους κοινούς +;; προστακτικούς βρόχους (imperative loops) + +;;; Εξαιρέσεις + +;; Για να πιάσουμε τις εξαιρέσεις χρησιμοποιούμε το +;; `with-handlers' +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", αλλά αν γίνει το break => "no time" + +;; Χρησιμοποιούμε το 'raise' για να άρουμε μια εξαίρεση +;; ή οποιαδήποτε άλλη τιμή +(with-handlers ([number? ; πιάνουμε αριθμητικές τιμές + identity]) ; και τις επιστρέφουμε σαν απλές τιμές + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Αλλαγή τιμών +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Χρησιμοποιούμε το 'set!' για να θέσουμε μια νέα τιμή +;; σε μια ήδη υπάρχουσα μεταβλητή +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή +;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της) +;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + + +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι +;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή +;; πχ αλφαριθμητικά, διανύσματα κτλ +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια +;; συγκεκριμένη θέση +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + + +;; Έτσι δημιουργούμε ένα άδειο μεταβλητό πίνακα κατακερματισμού +;; και τον χειριζόμαστε κατάλληλα +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Ενότητες (modules) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + + +;; Οι ενότητες μας επιτρέπουν να οργανώνουμε τον κώδικα σε πολλαπλά +;; αρχεία και επαναχρησιμοποιούμενες βιβλιοθήκες +;; Εδώ χρησιμοποιούμε υπο-ενότητες, εμφωλευμένες μέσα σε μια +;; άλλη ενότητα που δημιουργεί αυτό το κείμενο(ξεκινώντας από +;; την γραμμή '#lang' ) +(module cake racket/base ; ορίζουμε μια ενότητα 'cake' βασισμένο στο + ; racket/base + + (provide print-cake) ; συνάρτηση που εξάγεται από την ενότητα + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; εσωτερική συνάρτηση + (printf fmt (make-string n ch)) + (newline))) + +;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα +;; παρεχόμενα ονόματα από μία ενότητα +(require 'cake) ; το ' είναι για τοπική υποενότητα +(print-cake 3) +; (show "~a" 1 #\A) ; => error, το `show' δεν έχει εξαχθεί + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Κλάσεις και αντικείμενα +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Δημιουργούμε μια κλάση fish% (- συνήθως χρησιμοποιούμε +;; το % στο όνομα μιας κλάσης ) +(define fish% + (class object% + (init size) ; initialization argument + (super-new) ; superclass initialization + ;; Field + (define current-size size) + ;; Public methods + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; Δημιουργούμε ένα instance του fish% +(define charlie + (new fish% [size 10])) + +;; Χρησιμοποιούμε το 'send' για να καλέσουμε +;; τις μεθόδους ενός αντικειμένου +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; Το `fish%' είναι μία τιμή "πρώτης κλάσης" +;; `fish%' is a plain "first class" value, με το οποίο μπορούμε να +;; κάνουμε προσμείξεις +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; ή χωρίς καθόλου ονόματα : +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. Μακροεντολές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε +;; το συντακτικό μιάς γλώσσας. + +;; Ας προσθέσουμε έναν βρόχο while +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; Macros are hygienic, you cannot clobber existing variables! +(define-syntax-rule (swap! x y) ; -! is idiomatic for mutation + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 2) +(define other 3) +(swap! tmp other) +(printf "tmp = ~a; other = ~a\n" tmp other) +;; Η μεταβλητή 'tmp' μετονομάζεται σε 'tmp_1' +;; για να αποφευχθεί η σύγκρουση με τα ονόματα +;; (let ([tmp_1 tmp]) +;; (set! tmp other) +;; (set! other tmp_1)) + +;; But they are still code transformations, for example: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; αυτή η μακροεντολή είναι χαλασένη: δημιουγεί ατέρμονα βρόχο +;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστης +;; θα μπεί στον ατέρμονα βρόχο. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. Συμβόλαια +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται +;; από ενότητες (modules) +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; οι ποσότητες είναι πάντα θετικές + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; Πελάτες που προσπαθούν να καταθέσουν ένα μη θετικό ποσό παίρνουν +;; το μήνυμα (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 11. Είσοδος και έξοδος +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Η Racket έχει την έννοια του "port", που είναι παρόμοιο με τα +;; file descriptors σε άλλες γλώσσες. + +;; Ανοίγουμε το "/tmp/tmp.txt" και γράφουμε μέσα "Hello World" +;; Αυτό θα προκαλούσε σφάλμα αν το αρχείο υπήρχε ήδη +(define out-port (open-output-file "/tmp/tmp.txt")) +(displayln "Hello World" out-port) +(close-output-port out-port) + +;; Προσθέτουμε στο τέλος του "/tmp/tmp.txt" +(define out-port (open-output-file "/tmp/tmp.txt" + #:exists 'append)) +(displayln "Hola mundo" out-port) +(close-output-port out-port) + +;; Διαβάζουμε απο αρχείο ξανά +(define in-port (open-input-file "/tmp/tmp.txt")) +(displayln (read-line in-port)) +; => "Hello World" +(displayln (read-line in-port)) +; => "Hola mundo" +(close-input-port in-port) + +;; Εναλλακτικά, με το call-with-output-file δεν χρειάζεται να κλείσουμε +;; ρητά το αρχείο +(call-with-output-file "/tmp/tmp.txt" + #:exists 'update ; Rewrite the content + (λ (out-port) + (displayln "World Hello!" out-port))) + +;; Και το call-with-input-file κάνει το ίδιο πράγμα για την είσοδο +(call-with-input-file "/tmp/tmp.txt" + (λ (in-port) + (displayln (read-line in-port)))) +``` + +## Επιπλέον πηγές + +Ψάχνεις για περισσότερα ; [Getting Started with Racket](http://docs.racket-lang.org/getting-started/) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown new file mode 100644 index 00000000..dbef92d8 --- /dev/null +++ b/el-gr/scala-gr.html.markdown @@ -0,0 +1,690 @@ +--- +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] +translators: + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +filename: learnscala-gr.scala +lang: el-gr +--- + +Scala - Η επεκτάσιμη γλώσσα + +```scala + +/* + Προετοιμαστείτε: + + 1) Κατεβάστε την Scala - http://www.scala-lang.org/downloads + 2) Κάνετε εξαγωγή στην επιθυμητή σας τοποθεσία και βάλτε τον υποφάκελο bin + στο path του συστήματος + 3) Ξεκινήστε ένα scala REPL γράφοντας scala. Θα πρέπει να βλέπετε το prompt: + + scala> + + Αυτό είναι το αποκαλούμενο REPL (Read-Eval-Print Loop) *. + Μπορείτε να πληκτρολογήσετε οποιαδήποτε έγκυρη έκφραση σε Scala μέσα του , + και το αποτέλεσμα θα τυπωθεί. Θα εξηγήσουμε πως μοιάζουν τα αρχεία της Scala + αργότερα μέσα στο tutorial , αλλά για τώρα ας αρχίσουμε με κάποια βασικά. + *[Βρόχος του Διάβασε - Αξιολόγησε - Τύπωσε] +*/ + + +///////////////////////////////////////////////// +// 1. Βασικές έννοιες +///////////////////////////////////////////////// + +// Τα σχόλια μίας γραμμής ξεκινούν με δύο "/" (:forward slashes) . + +/* + Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε + να δείτε , φαίνοται κάπως έτσι. +*/ + +// Εκτύπωση με εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +println("Hello world!") +println(10) + +// Εκτύπωση χωρίς τον εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +print("Hello world") + +// Η δήλωση μεταβλητών γίνεται χρησιμοποιώντας var ή val. +// Οι δηλώσεις val είναι αμετάβλητες, ενώ οι var είναι μεταβλητές. +// Η αμεταβλητότητα είναι συμφέρουσα και προσπαθούμε να την χρησιμοποιούμε. +val x = 10 // το x είναι τώρα 10 +x = 20 // σφάλμα: αλλαγή σε val +var y = 10 +y = 20 // το y είναι τώρα 20 + +/* + Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω + δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός + χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις + περισσότερες των περιπτώσεων , ο μεταγλωττιστής της Scala μπορεί να + μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: +*/ +val z: Int = 10 +val a: Double = 1.0 + +/* + Προσέξτε ότι υπάρχει αυτόματη μετατροπή από ακέραιο (Int) σε διπλής + ακρίβειας (Double), και συνεπώς το αποτέλεσμα είναι 10.0 και όχι 10. +*/ +val b: Double = 10 + +// Λογικές τιμές +true +false + +// Λογικές Πράξεις +!true // false +!false // true +true == false // false +10 > 5 // true + +// Η αριθμιτική είναι όπως τα συνηθισμένα +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +/* + Αξιολογώντας μια έκφραση στο REPL , σας δίνεται ο τύπος και + η τιμή του αποτελέσματος +*/ + +1 + 7 + +/* Η παραπάνω γραμμή έχει το εξής αποτέλεσμα: + + scala> 1 + 7 + res29: Int = 8 + + Αυτό σημαίνει ότι το αποτέλεσμα της αξιολόγησης του 1 + 7 είναι ένα αντικείμενο + τύπου Int με τιμή 8 + + Σημειώστε ότι το "res29" είναι ένα σειριακά δημιουργούμενο όνομα μεταβλητής + για να αποθηκεύονται τα αποτελέσματα των εκφράσεων που έχετε πληκτρολογήσει + και συνεπώς η έξοδός σας μπορεί να διαφέρει. +*/ + +"Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" +'a' // Ένας χαρακτήρας στην Scala +// res30: Char = a +// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. + +// Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") + +// Έχουν επίσης μερικές επιπλένον μεθόδους Scala. +// Δείτε επίσης : scala.collection.immutable.StringOps +"hello world".take(5) +"hello world".drop(5) + +// Παρεμβολή αλφαριθμητικών : παρατηρήστε το πρόθεμα "s" +val n = 45 +s"We have $n apples" // => "We have 45 apples" + +// Expressions inside interpolated strings are also possible +// Εκφράσεις μέσα σε παρεμβεβλημένα αλφαριθμητικά είναι επίσης εφικτά +val a = Array(11, 9, 6) +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" + +// Μορφοποίηση με παρεμβεβλημένα αλφαριθμητικά με το πρόθεμα "f" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" + +// Raw αλφαριθμητικά, που αγνοούν τους ειδικούς χαρακτήρες. +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." + +// Μερικούς χαρακτήρες πρέπει να τους κάνουμε "escape", +// λ.χ ένα διπλό εισαγωγικό μέσα σε ένα αλφαριθμητικό : +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" + +/* + Τα τριπλά διπλά-εισαγωγικά επιτρέπουν στα αλφαριθμητικά να εκτείνονται σε + πολλαπλές γραμμές και να περιέχουν διπλά εισαγωγικά +*/ +val html = """
+

Press belo', Joe

+ +
""" + + +///////////////////////////////////////////////// +// 2. Συναρτήσεις +///////////////////////////////////////////////// + +// Οι συναρτήσεις ορίζονται ως εξής: +// +// def functionName(args...): ReturnType = { body... } +// +// Αν προέρχεστε απο πιο παραδοσιακές γλώσσες (C/C++ , Java) παρατηρήστε +// την παράλειψη του return. Στην Scala , η τελευταία έκφραση στο μπλόκ +// της συνάρτησης είναι η τιμή που επιστρέφει η συνάρτηση. +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// Τα { } μπορούν να παραλειφθούν αν η συνάρτηση αποτελείται απο μια απλή έκφραση: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y + +// Η σύνταξη για την κλήση συναρτήσεων είναι γνώριμη: +sumOfSquares(3, 4) // => 25 + +// Στις περισσότερες των περιπτώσεων (με τις αναδρομικές συναρτήσεις να αποτελούν +// την πιο αξιοπρόσεκτη εξαίρεση) , ο τύπος επιστροφής της συνάρτησης μπορεί να +// παραλειφθεί, και η ίδια συμπερασματολογία τύπων που είδαμε με τις μεταβλητές +// θα δουλεύει και με τους τύπους επιστροφής της συνάρτησης: +def sq(x: Int) = x * x // Ο μεταγλωττιστής μπορεί να μαντέψει ότι + // ο τύπος επιστροφής της συνάρτησης είναι Int + +// Οι συναρτήσεις μπορούν να έχουν προκαθορισμένες τιμές: +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 + + +// Οι ανώνυμες συναρτήσεις είναι ως εξής: +(x:Int) => x * x + +// Σε αντίθεση με τα defs , ακόμα και ο τύπος εισόδου απο τις ανώνυμες +// συναρτήσεις μπορεί να παραληφθεί αν τα συμφραζόμενα το κάνουν ξεκάθαρο. +// Προσέξτε τον τύπο "Int => Int" που σημαίνει ότι μια συνάρτηση παίρνει +// ένα Int και επιστρέφει ένα Int. +val sq: Int => Int = x => x * x + +// Οι ανώνυμες συναρτήσεις μπορούν να κληθούν όπως συνήθως: +sq(10) // => 100 + +// Αν κάθε όρισμα στην ανώνυμη συνάρτηση χρησιμοποιείται μόνο μία φορά, +// η Scala επιτρέπει έναν ακόμα πιο σύντομο τρόπο να οριστεί. Αυτές +// οι ανώνυμες συναρτήσεις αποδεικνύεται ότι είναι πολύ κοινές , +// όπως θα γίνει προφανές στο μέρος των δομών δεδομένων. +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + +// Η δεσμευμένη λέξη return υπάρχει στην Scala , αλλά επιστρέφει μόνο +// από το πιο εσωτερικό def που την περικλείει. +// ΠΡΟΣΟΧΗ: Η χρήση του return στην Scala είναι επιρρεπής σε λάθη +// και θα πρέπει να αποφεύγεται. +// Δεν έχει καμία επίδραση στις ανώνυμες συναρτήσεις. Για παράδειγμα: +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // Αυτή η σειρά κάνει το z την τιμή που επιστρέφει η foo! + else + z + 2 // Αυτή η γραμμή είναι η τιμή που επιστρέφει η anonFunc + } + anonFunc(x) // Αυτή η γραμμή είναι η τιμή που επιστρέφει η foo +} + + +///////////////////////////////////////////////// +// 3. Έλεγχος ροής +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// ΠΡΟΣΟΧΗ: Η Scala είναι σχετικά επιεικής ως αναφορά τις τελείες και +// τις παρενθέσεις. Διαβάστε τους κανόνες ξεχωριστά. +// Αυτό βοηθάει στο να γράφεις DSLs και APIs που διαβάζονται σαν τα Αγγλικά. + +(5 to 1 by -1) foreach ( println ) + +// Ένας βρόχος while : +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί; + +i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος + // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή + // του βρόχου. Το while είναι πολύ γρήγορο , γρηγορότερο απο τους βρόχους + // της Java , αλλά η χρήση combinators και comprehensions όπως πιο πάνω , + // είναι πιο εύκολη στην κατανόηση και στην παραλληλοποίηση. + +// Ένας βρόχος do while : +do { + println("x is still less than 10"); + x += 1 +} while (x < 10) + +// Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί +// ρητά τον τύπο που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1,14) + + +// Η ροή του ελέγχου. + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. Δομές Δεδομένων +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // "Πετάει" exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // "Πετάει" exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Δείτε το documentation του map εδώ - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + */ + + +// Πλειάδες + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Γιατί να το έχουμε αυτό; +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα + // της ακαίρεας διαίρεσης και το υπόλοιπο. + +// Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n +// όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. +val d = divideInts(10,3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Αντικειμενοστραφής Προγραμματισμός +///////////////////////////////////////////////// + +/* + Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις + (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις + γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν + από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να + έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα + στοιχεία του πάνω επιπέδου που επιτρέπονται στην Scala είναι: + + - αντικείμενα (objects) + - κλάσεις (classes) + - κλάσεις περίπτωσης (case classes στην Scala) + - Χαρακτηριστικά (traits , όπως ονομάζονται στην Scala) + + Και τώρα θα εξηγήσουμε τι είναι αυτά. +*/ +// Οι κλάσεις είναι παρόμοιες με τις κλάσεις σε άλλες γλώσσες. Τα ορίσματα του +// "κατασκευαστή" (constructor) δηλώνονται μετά από το όνομα της κλάσης , +// και η αρχικοποιήση γίνεται μέσα στο σώμα της κλάσης. +class Dog(br: String) { + // Κώδικας για τον "κατασκευαστή" + var breed: String = br + + // Ορίζεται μια μέθοδος bark , που επιστρέφει ένα αλφαριθμητικό + def bark = "Woof, woof!" + + // Οι τιμές και οι μέθοδοι είναι public εκτός αν χρησιμοποιήσουμε κάποια + // απο τις λέξεις κλειδιά "protected" και "private" . + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + + // Οι abstract μέθοδοι είναι απλά μέθοδοι χωρίς σώμα. Αν βγάζαμε + // το σχόλιο απο την επόμενη γραμμή η κλάση Dog θα έπρεπε να + // δηλωθεί ως abstract class Dog(...) { ... } : + // def chaseAfter(what: String): String +} + +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" + + +// Η λέξη "object" δημιουργεί ένα type ΚΑΙ ένα singleton instance αυτού. +// Είναι κοινό για τις κλάσεις στην Scala να έχουν ένα "συντροφικό object", +// όπου η συμπεριφορά για κάθε instance αιχμαλωτίζεται μέσα στις κλάσεις +// αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances +// της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις +// μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. +// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} + +// Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον +// λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην +// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις. +// Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον +// πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις +// τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. +// Ο κύριος σκοπός των case classes είναι να κρατούν δεδομένα που είναι +// σταθερές(immutable). Συνήθως έχουν λίγες μεθόδους και οι μέθοδοι σπάνια +// έχουν παρενέργειες. +case class Person(name: String, phoneNumber: String) + +// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes +// δεν χρειάζονται την λέξη "new" . +val george = Person("George", "1234") +val kate = Person("Kate", "4567") + +// Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: +george.phoneNumber // => "1234" + +// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// κάνουμε override στο .equals) +Person("George", "1234") == Person("Kate", "1236") // => false + +// Έυκολος τρόπος να κάνουμε αντιγραφή. Δημιουργούμε έναν νέο geroge: +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") + +// Και πολλά άλλα. Τα case classes έχουν και αντιστοίχιση προτύπων +// (pattern matching) δωρεάν, δείτε παρακάτω. + +// Τα χαρακτηριστικά (traits) έρχονται σε λίγο καιρό ! + +///////////////////////////////////////////////// +// 6. Αντιστοίχιση Προτύπων +///////////////////////////////////////////////// + +// Η αντιστοίχιση προτύπων (pattern matching) είναι ένα πολύ δυνατό και +// ευρέως χρησιμοποιούμενο χαρακτηριστικό στην Scala. Παρακάτω βλέπουμε +// πως γίνεται το pattern matching σε ένα case class. Σημείωση: Σε +// αντίθεση με άλλες γλώσσες η Scala δεν χρειάζεται breaks, γιατί γίνεται +// αυτόματα όταν γίνει κάποιο match. + +def matchPerson(person: Person): String = person match { + // Μετά προσδιορίζουμε το πρότυπο (pattern): + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number +} + +val email = "(.*)@(.*)".r // Ορίζουμε ένα regex για το επόμενο παράδειγμα. + // (regex <- REGular EXpression) + +// Το pattern matching μπορεί να μοιάζει γνώριμο απο τα switch statements σε +// γλώσσες που ανήκουν στην οικογένεια της C αλλά είναι πολύ πιο ισχυρό. +// Στην Scala , μπορούμε να κάνουμε match πολύ περισσότερα: +def matchEverything(obj: Any): String = obj match { + // Μπορούμε να ταιριάξουμε τιμές: + case "Hello world" => "Got the string Hello world" + + // Μπορούμε να ταιριάξουμε τύπους: + case x: Double => "Got a Double: " + x + + // Μπορούμε να βάλουμε συνθήκες: + case x: Int if x > 10000 => "Got a pretty big number!" + + // Μπορούμε να ταιριάξουμε case classes όπως πρίν: + case Person(name, number) => s"Got contact info for $name!" + + // Μπορούμε να ταιριάξουμε regex: + case email(name, domain) => s"Got email address $name@$domain" + + // Μπορούμε να ταιριάξουμε πλειάδες: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" + + // Μπορούμε να ταιριάξουμε δομές δεδομένων: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" + + // Μπορούμε να ταιριάξουμε πρότυπα που το ένα είναι μέσα στο άλλο: + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" +} + +// Στην πραγματικότητα , μπορούμε να κάνουμε pattern matching σε όποιο αντικείμενο +// έχει την μέθοδο "unapply". Αυτό το χαρακτηριστικό είναι τόσο ισχυρό ώστε +// η Scala επιτρέπει να ορίστούν ολόκληρες συναρτήσεις σαν patterns. +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} + + +///////////////////////////////////////////////// +// 7. Συναρτησιακός Προγραμματισμός +///////////////////////////////////////////////// + +// Η Scala επιτρέπει στις μεθόδους και τις συναρτήσεις να επιστρέφουν ή να +// δέχονται ως παραμέτρους άλλες μεθόδους ή συναρτήσεις. + +val add10: Int => Int = _ + 10 // Μια συνάρτηση που δέχεται Int και επιστρέφει Int +List(1, 2, 3) map add10 // List(11, 12, 13) - το add10 εφαρμόζεται σε κάθε στοιχείο + // μέσω του map + +// Οι ανώνυμες συναρτήσεις μπορούν να χρησιμοποιηθούν αντί +// ονοματισμένων (όπως απο πάνω) : +List(1, 2, 3) map (x => x + 10) + +// Και το σύμβολο της κάτω παύλας , μπορεί να χρησιμοποιηθεί αν υπάρχει μόνο +// ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. +List(1, 2, 3) map (_ + 10) + +// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα +// μπορείτε να παραλείψετε την κάτω παύλα. +List("Dom", "Bob", "Natalia") foreach println + + +// Συνδυαστές + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// Η συνάρτηση filter παίρνει ένα κατηγορούμενο (predicate) +// που είναι μια συνάρτηση απο το A -> Boolean και διαλέγει +// όλα τα στοιχεία που ικανοποιούν αυτό το κατηγορούμενο. +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name:String, age:Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) + + +// Το foreach είναι μια μέθοδος της Scala , που ορίζεται για ορισμένες +// συλλογές (collections). Παίρνει έναν τύπο και επιστρέφει Unit +// (μια μέθοδο void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// For comprehensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* + Προσοχή : Αυτά δεν ήταν βρόχοι for. Η σημασιολογία ενός βρόχου for είναι + η επανάληψη, ενώ ένα for-comprehension ορίζει μια σχέση μεταξύ δύο + συνόλων δεδομένων. +*/ + +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// +/* + ΠΡΟΣΟΧΗ! Τα implicits είναι ένα σύνολο απο ισχυρά χαρακτηριστικά της Scala + και επομένως είναι εύκολο να γίνει κατάχρηση. Οι αρχάριοι στην Scala θα + πρέπει να αντισταθούν στον πειρασμό να τα χρησιμοποιήσουν έως ότου, όχι + μόνο καταλάβουν πως λειτουργούν, αλλά ακόμα εξασκηθούν πάνω τους. + Ο μόνος λόγος που συμπεριλάβαμε αυτό το κομμάτι στο tutorial είναι + γιατί είναι τόσο κοινό στις βιβλιοθήκες της Scala , που αδύνατο να κάνεις + οτιδήποτε σημαντικό χωρίς να χρησιμοποιήσεις μια που να έχει implicits. + +*/ + +// Κάθε τιμή (vals , συναρτήσεις , αντικείμενα , κτλ) μπορεί να δηλωθεί ως +// implicit χρησιμοποιώντας , ναι το μαντέψατε , την λέξη "implicit". +// Σημειώστε ότι χρησιμοποιούμε την κλάση Dog που δημιουργήσαμε στο +// 5ο μέρος των παραδειγμάτων. +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) + + +// Απο μόνη της, η λέξη implicit, δεν αλλάζει την συμπεριφορά μιάς τιμής +// οπότε οι παραπάνω μπορούν να χρησιμοποιοηθούν όπως συνήθως. +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" + +// Η διαφορά είναι ότι τώρα αυτές οι τιμές έχουν την δυνατότητα να +// χρησιμοποιηθούν όταν ένα άλλο κομμάτι κώδικα "χρειάζεται" μια +// implicit τιμή. Μια τέτοια περίπτωση είναι τα ορίσματα μιας implicit +// συνάρτησης: +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" + +// Άν τροφοδοτήσουμε μια τιμή για το "homMany", η συνάρτηση συμπεριφέρεται +// ως συνήθως +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" + +// Αλλά αν παραλείψουμε την παράμετρο implicit , μια implicit τιμή του ιδίου τύπου +// χρησιμοποιείται, στην περίπτωσή μας, το "myImplicitInt" +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" + +// Οι παράμετροι implicit συναρτήσεων μας επιτρέπουν να προσομοιάζουμε +// κλάσεις τύπων (type classes) σε άλλες συναρτησιακές γλώσσες. +// Χρησιμοποιείται τόσο συχνά που έχει την δικιά του συντομογραφία. +// Οι επόμενες δύο γραμμές κώδικα σημαίνουν το ίδιο πράγμα. +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... + + + +// Μια άλλη περίπτωση στην οποία ο μεταγλωττιστής αναζητά μια implicit τιμή +// είναι αν έχετε obj.method (...) +// αλλά το "obj" δεν έχει την "method" ως μέθοδο. Σε αυτή την περίπτωση, +// αν υπάρχει μια implicit μετατροπή του τύπου Α => Β, όπου Α είναι ο τύπος +// του obj, ενώ το Β έχει μία μέθοδο που ονομάζεται «method», εφαρμόζεται η +// εν λόγω μετατροπή. Έτσι, έχοντας την MyImplicitFunction μέσα στο πεδίο +// εφαρμογής(scope), μπορούμε να πούμε: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" + +// Εδώ το String αρχικά μετατρέπεται σε Dog χρησιμοποιώντας την συνάρτησή μας +// παραπάνω, και μετά καλείται η κατάλληλη μέθοδος. Αυτό είναι ένα εξερετικά +// ισχυρό χαρακτηριστικό, αλλά δεν πρέπει να χρησιμοποιείται με ελαφριά την +// καρδιά. Μάλιστα, όταν ορίσατε την συνάρτηση implicit παραπάνω, ο μεταγλωττιστής +// θα πρέπει να σας έδωσε μια προειδοποιήση, ότι δεν πρέπει να το κάνετε αυτό +// εκτός αν πραγματικά γνωρίζετε τι κάνετε. + + +///////////////////////////////////////////////// +// 9. Διάφορα +///////////////////////////////////////////////// + +// Εισαγωγή βιβλιοθηκών κτλ +import scala.collection.immutable.List + +// Εισαγωγή των πάντων απο το scala.collection.immutable +import scala.collection.immutable._ + +// Εισαγωγή πολλών κλάσεων σε μία έκφραση +import scala.collection.immutable.{List, Map} + +// Δώστε ένα νέο όνομα στην εισαγωγή σας χρησιμοποιώντας το '=>' +import scala.collection.immutable.{ List => ImmutableList } + +// Εισαγωγή όλων των κλάσεων εκτός απο μερικές. +// Το επόμενο δεν εισάγει το Map και το Set: +import scala.collection.immutable.{Map => _, Set => _, _} + +// Το σημείο εισαγωγής του προγράμματος σας ορίζεται σε ένα αρχείο scala , +// χρησιμοποιώντας ένα αντικείμενο (object), με μία μέθοδο , την main. +object Application { + def main(args: Array[String]): Unit = { + // Εδω γράφουμε ... + } +} + +// Files can contain multiple classes and objects. Compile with scalac +// Τα files μπορούν να περιέχουν περισσότερες απο μία κλάσεις και +// αντικείμενα. Το compile γίνεται με την εντολή scalac + +// Εισαγωγή και εξαγωγή. + +// Για να διβάσετε ένα αρχείο γραμμή προς γραμμή +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) + +// Για να γράψετε σε ένα αρχείο +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() + +``` + +## Further resources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school](http://twitter.github.io/scala_school/) + +[The scala documentation](http://docs.scala-lang.org/) + +[Try Scala in your browser](http://scalatutorials.com/tour/) + +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) + -- cgit v1.2.3 From cb065fdf377541b09736f2e3918c4dc6caddc29f Mon Sep 17 00:00:00 2001 From: billpcs Date: Wed, 5 Aug 2015 17:06:31 +0300 Subject: update --- el-gr/racket-gr.html.markdown | 13 ++++++------- el-gr/scala-gr.html.markdown | 15 +++++++-------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 6a3f99ef..c5aa1f46 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -208,7 +208,7 @@ my-pet ; => # (set-member? (set 1 2 3) 1) ; => #t (set-member? (set 1 2 3) 4) ; => #f -;;; Πίνακες κατακερματισμού +;;; Πίνακες κατακερματισμού (Hashes) ;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού (define m (hash 'a 1 'b 2 'c 3)) @@ -355,7 +355,6 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f ;; Το `equal?' υποστηρίζει την σύγκριση των παρακάτω τύπων μεταβλητών: -;; `equal?' supports the comparison of the following datatypes: ;; αλφαριθμητικά, αλφαριθμητικά από bytes, μεταβλητά ζεύγη , διανύσματα, ;; πίνακες κατακερματισμού και δομές. ;; Για άλλα ήδη τύπων μεταβλητών το `equal?' και το `eqv?' επιστρέφουν το @@ -426,13 +425,10 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;;; ;;; Επανάληψη μέσα σε ακολουθίες: -;; Το `for' επιτρέπει την επενάληψη μέσα σε πολλά +;; Το `for' επιτρέπει την επανάληψη μέσα σε πολλά ;; άλλα ήδη από ακολουθίες: Λίστες, διανύσματα, ;; αλφαριθμητικά, σύνολα κτλ.. -;;allows iteration over many other kinds of sequences: -;; lists, vectors, strings, sets, hash tables, etc... - (for ([i (in-list '(l i s t))]) (displayln i)) @@ -488,13 +484,16 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε ;; τιμές από τους βρόχους + (for/sum ([i 10]) (* i i)) ; => 285 (for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 (for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t (for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t -;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιύμε + +;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε ;; το 'for/fold' (for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 + ;; Αυτό συχνά μπορεί να αντικαταστήσει τους κοινούς ;; προστακτικούς βρόχους (imperative loops) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown index dbef92d8..e29c7e70 100644 --- a/el-gr/scala-gr.html.markdown +++ b/el-gr/scala-gr.html.markdown @@ -43,11 +43,11 @@ Scala - Η επεκτάσιμη γλώσσα να δείτε , φαίνοται κάπως έτσι. */ -// Εκτύπωση με εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +// Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση println("Hello world!") println(10) -// Εκτύπωση χωρίς τον εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +// Εκτύπωση χωρίς νέα γραμμή στην επόμενη εκτύπωση print("Hello world") // Η δήλωση μεταβλητών γίνεται χρησιμοποιώντας var ή val. @@ -62,7 +62,7 @@ y = 20 // το y είναι τώρα 20 Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις - περισσότερες των περιπτώσεων , ο μεταγλωττιστής της Scala μπορεί να + περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: */ @@ -95,7 +95,7 @@ true == false // false /* - Αξιολογώντας μια έκφραση στο REPL , σας δίνεται ο τύπος και + Αξιολογώντας μια έκφραση στο REPL, σας δίνεται ο τύπος και η τιμή του αποτελέσματος */ @@ -133,8 +133,7 @@ true == false // false val n = 45 s"We have $n apples" // => "We have 45 apples" -// Expressions inside interpolated strings are also possible -// Εκφράσεις μέσα σε παρεμβεβλημένα αλφαριθμητικά είναι επίσης εφικτά +// Παρατηρήστε την χρήση των '{', '}' val a = Array(11, 9, 6) s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." @@ -270,7 +269,7 @@ do { // Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα // πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί -// ρητά τον τύπο που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί // αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -280,7 +279,7 @@ def showNumbersInRange(a:Int, b:Int):Unit = { showNumbersInRange(1,14) -// Η ροή του ελέγχου. +// Έλεγχος Ροής val x = 10 -- cgit v1.2.3 From b1a544d1f04fc6c9769037af5fd165e7032a2985 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Wed, 5 Aug 2015 18:22:56 -0700 Subject: main(), modules, array/range/domain slicing, loop-expressions, array expressions, in depth zippered iterators Quite the addition. Modules required main() because of the begin statement issue. array/range/domain slicing was more intricate than I though. And loop/array expressions had some very very intersting behavior that necessitated a dive into zippered iterators. Some back-of-the-head anxiety about the tutorial being to in depth? Nawww. --- chapel.html.markdown | 115 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 103 insertions(+), 12 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 33bdc21d..c8489371 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -24,7 +24,7 @@ writeln( "World!" ); // each thing is printed right next to each other, so include your spacing! writeln( "There are ", 3, " commas (\",\") in this line of code" ); // Different output channels -stdout.writeln( "This goes to standard output (just like plain writeln( ) does)"); +stdout.writeln( "This goes to standard output, just like plain writeln() does"); stderr.writeln( "This goes to standard error" ); // Variables don't have to be explicitly typed as long as @@ -285,6 +285,7 @@ for i in rangeCountBy{ } // Rectangular domains are defined using the same range syntax +// However they are required to be bounded (unlike ranges) var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges var thirdDim: range = 1..16; @@ -310,6 +311,18 @@ stringSet += "a"; // Redundant add "a" stringSet -= "c"; // Remove "c" writeln( stringSet ); +// Both ranges and domains can be sliced to produce a range or domain with the +// intersection of indices +var rangeA = 1.. ; // range from 1 to infinity +var rangeB = ..5; // range from negative infinity to 5 +var rangeC = rangeA[rangeB]; // resulting range is 1..5 +writeln( (rangeA, rangeB, rangeC ) ); + +var domainA = {1..10, 5..20}; +var domainB = {-5..5, 1..10}; +var domainC = domainA[domainB]; +writeln( (domainA, domainB, domainC) ); + // Array are similar to those of other languages. // Their sizes are defined using domains that represent their indices var intArray: [1..10] int; @@ -357,6 +370,48 @@ var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; dict["three"] = 3; for key in dictDomain do writeln( dict[key] ); +// Arrays can be assigned to each other in different ways +var thisArray : [{0..5}] int = [0,1,2,3,4,5]; +var thatArray : [{0..5}] int; + +// Simply assign one to the other. +// This copies thisArray into thatArray, instead of just creating a reference. +// Modifying thisArray does not also modify thatArray. +thatArray = thisArray; +thatArray[1] = -1; +writeln( (thisArray, thatArray) ); + +// Assign a slice one array to a slice (of the same size) of the other. +thatArray[{4..5}] = thisArray[{1..2}]; +writeln( (thisArray, thatArray) ); + +// Operation can also be promoted to work on arrays. +var thisPlusThat = thisArray + thatArray; +writeln( thisPlusThat ); + +// Arrays and loops can also be expressions, where loop +// body's expression is the result of each iteration. +var arrayFromLoop = for i in 1..10 do i; +writeln( arrayFromLoop ); + +// An expression can result in nothing, +// such as when filtering with an if-expression +var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i; + +writeln( arrayFromLoop ); + +// Or could be written with a bracket notation +// Note: this syntax uses the 'forall' parallel concept discussed later. +var evensOrFivesAgain = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; + +// Or over the values of the array +arrayFromLoop = [ value in arrayFromLoop ] value + 1; + +// Note: this notation can get somewhat tricky. For example: +// evensOrFives = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; +// would break. +// The reasons for this are explained in depth when discussing zipped iterators. + // Chapel procedures have similar syntax to other languages functions. proc fibonacci( n : int ) : int { if ( n <= 1 ) then return n; @@ -533,6 +588,19 @@ iter oddsThenEvens( N: int ): int { for i in oddsThenEvens( 10 ) do write( i, ", " ); writeln( ); +// Iterators can also yield conditionally, the result of which can be nothing +iter absolutelyNothing( N ): int { + for i in 1..N { + if ( N < i ) { // Always false + yield i; // Yield statement never happens + } + } +} + +for i in absolutelyNothing( 10 ){ + writeln( "Woa there! absolutelyNothing yielded ", i ); +} + // We can zipper together two or more iterators (who have the same number // of iterations) using zip() to create a single zipped iterator, where each // iteration of the zipped iterator yields a tuple of one value yielded @@ -541,6 +609,34 @@ writeln( ); for (positive, negative) in zip( 1..5, -5..-1) do writeln( (positive, negative) ); +// Zipper iteration is quite important in the assignment of arrays, +// slices of arrays, and array/loop expressions. +var fromThatArray : [1..#5] int = [1,2,3,4,5]; +var toThisArray : [100..#5] int; + +// The operation +toThisArray = fromThatArray; +// is produced through +for (i,j) in zip( toThisArray.domain, fromThatArray.domain) { + toThisArray[ i ] = fromThatArray[ j ]; +} + +toThisArray = [ j in -100..#5 ] j; +writeln( toThisArray ); +// is produced through +for (i, j) in zip( toThisArray.domain, -100..#5 ){ + toThisArray[i] = j; +} +writeln( toThisArray ); + +// This is all very important in undestanding why the statement +// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; +// exhibits a runtime error. +// Even though the domain of the array and the loop-expression are +// the same size, the body of the expression can be though of as an iterator. +// Because iterators can yield nothing, that iterator yields a different number +// of things than the domain of the array or loop, which is not allowed. + // Classes are similar to those in C++ and Java. // They currently lack privatization class MyClass { @@ -813,12 +909,9 @@ proc main(){ // You may have noticed that (depending on how many cores you have) // that the parallel loop went faster than the serial loop - // A succinct way of writing a forall loop over an array: - // iterate over values - [ val in myBigArray ] val = 1 / val; - - // or iterate over indicies - [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; + // The bracket style loop-expression described + // much earlier implicitly uses a forall loop. + [ val in myBigArray ] val = 1 / val; // Parallel operation // Atomic variables, common to many languages, are ones whose operations // occur uninterupted. Multiple threads can both modify atomic variables @@ -837,7 +930,7 @@ proc main(){ writeln( "uranium was ", was, " but is now ", replaceWith ); var isEqualTo = 235; - if uranium.compareExchange( isEqualTo, replaceWith ) { + if ( uranium.compareExchange( isEqualTo, replaceWith ) ) { writeln( "uranium was equal to ", isEqualTo, " so replaced value with ", replaceWith ); } else { @@ -911,7 +1004,7 @@ proc main(){ // Create a barrier do{ lock$; // Read lock$ (wait) - }while count.read() < 1; // Keep waiting until a spot opens up + }while ( count.read() < 1 ); // Keep waiting until a spot opens up count.sub(1); // decrement the counter lock$.writeXF( true ); // Set lock$ to full (signal) @@ -954,7 +1047,7 @@ Who is this tutorial for? This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [module documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. @@ -963,8 +1056,6 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to * Exposition of the standard modules * Multiple Locales (distributed memory system) * Records - * Whole/sliced array assignment - * Range and domain slicing * Parallel iterators Your input, questions, and discoveries are important to the developers! -- cgit v1.2.3 From c21c4b65cb1660d6af3faecdd7643e5187f5429b Mon Sep 17 00:00:00 2001 From: Bill Panagiotopoulos Date: Thu, 6 Aug 2015 18:41:33 +0300 Subject: Small Fixes Fix small extra character and translate a small text left untranslated by mistake --- el-gr/racket-gr.html.markdown | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index c5aa1f46..d7c144aa 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -1,4 +1,4 @@ ----σ +--- language: racket filename: learnracket.rkt contributors: @@ -8,13 +8,11 @@ contributors: - ["Duong H. Nguyen", "https://github.com/cmpitg"] - ["Keyan Zhang", "https://github.com/keyanzhang"] translators: - - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] --- -Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. - -Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3rac25) or th3rac25 [at] [google's email service] - +H Racket είναι μια γενικού σκοπού, πολυ-υποδειγματική γλώσσα προγραμματισμού που ανήκει +στην οικογένεια της Lisp/Scheme ```racket #lang racket ; ορίζει την γλώσσα που χρησιμοποιόυμε -- cgit v1.2.3 From 2f73cafc7042c92b1358272e6d158f5b1995c15c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 6 Aug 2015 12:26:29 -0500 Subject: Update racket gr to include what language it is in to fix homescreen issue showing up twice. --- el-gr/racket-gr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index d7c144aa..4c76b174 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -1,6 +1,6 @@ --- language: racket -filename: learnracket.rkt +filename: learnracket-gr.rkt contributors: - ["th3rac25", "https://github.com/voila"] - ["Eli Barzilay", "https://github.com/elibarzilay"] @@ -9,6 +9,7 @@ contributors: - ["Keyan Zhang", "https://github.com/keyanzhang"] translators: - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +lang: el-gr --- H Racket είναι μια γενικού σκοπού, πολυ-υποδειγματική γλώσσα προγραμματισμού που ανήκει -- cgit v1.2.3 From 14c628e1d914a72c81daae92d204eb8892e12889 Mon Sep 17 00:00:00 2001 From: ftwbzhao Date: Fri, 7 Aug 2015 14:30:45 +0800 Subject: Update ruby-cn.html.markdown --- zh-cn/ruby-cn.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 99250b43..14d38137 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] - ["lidashuang", "https://github.com/lidashuang"] + - ["ftwbzhao", "https://github.com/ftwbzhao"] translators: - ["Lin Xiangyu", "https://github.com/oa414"] --- @@ -120,11 +121,11 @@ status == :approved #=> false # 数组 # 这是一个数组 -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # 数组可以包含不同类型的元素 -array = [1, "hello", false] #=> => [1, "hello", false] +[1, "hello", false] #=> [1, "hello", false] # 数组可以被索引 # 从前面开始 @@ -140,8 +141,8 @@ array.[] 12 #=> nil # 从尾部开始 array[-1] #=> 5 -# 同时指定开始的位置和结束的位置 -array[2, 4] #=> [3, 4, 5] +# 同时指定开始的位置和长度 +array[2, 3] #=> [3, 4, 5] # 或者指定一个范围 array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From 63a314bd07660f33664708cc3b9e6f02ca895931 Mon Sep 17 00:00:00 2001 From: ftwbzhao Date: Fri, 7 Aug 2015 15:44:47 +0800 Subject: Update go-cn.html.markdown --- zh-cn/go-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 9f6a8c15..3a461efe 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -283,4 +283,4 @@ Go的根源在[Go官方网站](http://golang.org/)。 强烈推荐阅读语言定义部分,很简单而且很简洁!(as language definitions go these days.) -学习Go还要阅读Go标准库的源代码,全部文档化了,可读性非常好,可以学到go,go style和go idioms。在文档中点击函数名,源代码就出来了! +学习Go还要阅读Go[标准库的源代码](http://golang.org/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](http://golang.org/pkg/)中点击函数名,源代码就出来了! -- cgit v1.2.3 From ab81738386a6fd5e5facfa14357e089744af979d Mon Sep 17 00:00:00 2001 From: Bogdan Paun Date: Fri, 7 Aug 2015 12:45:47 +0300 Subject: Added Romanian Clojure translation --- ro-ro/clojure-ro.html.markdown | 385 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 385 insertions(+) create mode 100644 ro-ro/clojure-ro.html.markdown diff --git a/ro-ro/clojure-ro.html.markdown b/ro-ro/clojure-ro.html.markdown new file mode 100644 index 00000000..7dd51615 --- /dev/null +++ b/ro-ro/clojure-ro.html.markdown @@ -0,0 +1,385 @@ +--- +language: clojure +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Bogdan Paun", "http://twitter.com/bgdnpn"] +filename: learnclojure-ro.clj +lang: ro-ro +--- + +Clojure este un limbaj din familia Lisp dezvoltat pentru Masina Virtuala Java +(Java Virtual Machine - JVM). Pune un accent mult mai puternic pe [programarea funcionala](https://en.wikipedia.org/wiki/Functional_programming) pura decat Common Lisp, dar include +utilitare [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) pentru +a gestiona starea, atunci cand aceasta apare. + +Combinatia aceasta ii permite sa gestioneze procese concurente foarte usor, +de multe ori in mod automat. + +(Aveti nevoie deo versiune Clojure 1.2 sau mai noua) + + +```clojure +; Comentariile incep cu punct si virgula. + +; Clojure se scrie in "forme", care nu sunt decat +; liste de lucruri in interiorul unor paranteze, separate prin spatii. +; +; Reader-ul Clojure presupune ca primul lucru este o +; functie sau un macro de apelat, iar restul sunt argumente. + +; Prima apelare intr-un fisier ar trebui sa fie ns, pentru a configura namespace-ul +(ns learnclojure) + +; Mai multe exemple de baza: + +; str va crea un string folosint toate argumentele sale +(str "Hello" " " "World") ; => "Hello World" + +; Matematica este simpla +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; Egalitatea este = +(= 1 1) ; => true +(= 2 1) ; => false + +; Folosim si not pentru logica +(not true) ; => false + +; Formele imbricate functioneaza asa +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Tipuri +;;;;;;;;;;;;; + +; Clojure foloseste sistemul de obiecte Java pentru boolean, string si numere. +; Folositi `class` pentru a le inspecta. +(class 1) ; Numere intregi sunt jaba.lang.Long, in mod normal +(class 1.); Numelere reale sunt java.lang.Double +(class ""); Sirurile de caractere sunt mere intre apostrofuri duble, si sunt java.lang.String +(class false) ; Booleanele sunt java.lang.Boolean +(class nil); Valoarea "null" este numita nil + +; Daca doriti sa creati o lista de date literale, folositi ' pentru a preveni +; evaluarea ei +'(+ 1 2) ; => (+ 1 2) +; (prescurtare pentru (quote (+ 1 2))) + +; Puteti evalua o lista cu apostrof +(eval '(+ 1 2)) ; => 3 + +; Colectii & Secvente +;;;;;;;;;;;;;;;;;;; + +; Listele sunt structuri de date lista-inlantuita, spre deosebire de Vectori +; Vectorii si Listele sunt si ele clase Java! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; O liste ar putea fi scrisa direct ca (1 2 3), dar trebuie sa folosim apostrof +; pentru a preveni reader-ul din a crede ca e o functie. +; De asemenea, (list 1 2 3) este acelasi lucru cu '(1 2 3) + +; "Colectiile" sunt grupuri de date +; Atat listele cat si vectorii sunt colectii: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; "Sequences" (seqs) are abstract descriptions of lists of data. +; Only lists are seqs. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; O secventa necesita un punct de intrare doar cand este accesata. +; Deci, secventele, care pot fi "lazy" -- pot defini serii infinite: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (o serie infinita) +(take 4 (range)) ; (0 1 2 3) + +; Folositi cons pentru a adauga un element la inceputul unei liste sau unui vector +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; Conj va adauga un element unei colectii in modul cel mai eficient. +; Pentru liste, aceastea sunt inserate la inceput. Pentru vectori, sunt inserate la final. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Folositi concat pentru a uni liste sau vectori +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Folositi filter, map pentru a interactiona cu colectiile +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; Folositi reduce pentru a le reduce +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; Reduce poate lua un argument valoare-initiala +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Functii +;;;;;;;;;;;;;;;;;;;;; + +; Folositi fn pentru a crea functii noi. O functie returneaza intotdeauna +; ultima sa instructiune. +(fn [] "Hello World") ; => fn + +; (Necesita paranteze suplimentare pentru a fi apelata) +((fn [] "Hello World")) ; => "Hello World" + +; Puteti crea o variabila folosind def +(def x 1) +x ; => 1 + +; Atribuiti o functie unei variabile +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; Puteti scurta acest proces folosind defn +(defn hello-world [] "Hello World") + +; Elementul [] este lista de argumente a functiei. +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; Puteti, de asemenea, folosi aceasta prescurtare pentru a crea functii: +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; Puteti avea si functii cu mai multe variabile +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; Functiile pot primi mai mult argumente dintr-o secventa +(defn count-args [& args] + (str "Ati specificat " (count args) " argumente: " args)) +(count-args 1 2 3) ; => "Ati specificat 3 argumente: (1 2 3)" + +; Puteti interschimba argumente normale si argumente-secventa +(defn hello-count [name & args] + (str "Salut " name ", ati specificat " (count args) " argumente extra")) +(hello-count "Finn" 1 2 3) +; => "Salut Finn, ai specificat 3 argumente extra" + + +; Maps (Dictionare) +;;;;;;;;;; + +; Hash maps si Array maps impart o interfata. Hash maps au cautari mai rapide +; dar nu retin ordinea cheilor. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Arraymaps de vin automat hashmaps prin majoritatea operatiilor +; daca sunt suficient de mari, asa ca nu trebuie sa va preocupe acest aspect. + +; Dictionarele pot folosi orice tip hashable ca si cheie, dar cuvintele cheie +; (keywords) sunt, de obicei, cele mai indicate. Cuvintele cheie sunt ca niste +; siruri de caractere cu un plus de eficienta +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; Apropo, virgulele sunt intotdeauna considerate echivalente cu spatiile. + +; Apelati un dictionar (map) ca pe o functie pentru a primi o valoare anume +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; Cuvintele cheie pot fi folosite si ele pentru a "cere" dictionarului valorile lor! +(:b keymap) ; => 2 + +; Nu incercati asta cu siruri de caractere. +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Recuperarea unei chei inexistente returneaza nil +(stringmap "d") ; => nil + +; Folositi assoc pentru a adauga nou chei unui ductionar +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Dar retineti ca tipurile sunt imuabile in clojure +keymap ; => {:a 1, :b 2, :c 3} + +; Folositi dissoc pentru a elimina chei +(dissoc keymap :a :b) ; => {:c 3} + +; Seturi (multimi) +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Adaugati un membru cu conj +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Eliminati unul cu disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Testati existenta unuia folosing setul ca o functie: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; Exista mai multe functii in namespace-ul clojure.sets. + +; Forme utile +;;;;;;;;;;;;;;;;; + +; In Clojure constructiile logice sunt macro-uri, si arata ca +; oricare alta forma +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Folositi let pentru a crea atribuiri temporare +(let [a 1 b 2] + (> a b)) ; => false + +; Grupati instructiuni impreuna folosind do +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; Functiile contin un do implicit +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; Asemanator pentru let +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Module +;;;;;;;;;;;;;;; + +; Folositi "use" pentru a recupera toate functiile dintr-un modul +(use 'clojure.set) + +; Acum putem folosi operatiuni pe seturi +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; Puteri de asemenea alege un subset al functiilor de importat +(use '[clojure.set :only [intersection]]) + +; Folositi require pentru a importa un modul +(require 'clojure.string) + +; Folositi / pentru a apela functii dintr-un modul +; In acest caz, modulul este clojure.string, iar functia este blank? +(clojure.string/blank? "") ; => true + +; Puteti atribui un nume mai scurt unui modul in momentul importului +(require '[clojure.string :as str]) +(str/replace "Acesta este un test." #"[a-o]" str/upper-case) ; => "ACEstA EstE un tEst." +; (#"" denota o expresie regulata) + +; Puteti folsi require (sau use, contraindicat) dintr-un namespace folosind :require. +; Nu trebuie sa folositi apostrof pentru module daca procedati astfel. +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java are o biblioteca standard imensa si folositoare, deci +; ar fi util sa stiti cum sa o folositi. + +; Folositi import pentru a incarca un modul Java +(import java.util.Date) + +; Puteti importa si dintr-un namesopace. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Folositi numele clasei cu "." la final pentru a crea o noua instanta +(Date.) ; + +; Folositi . pentru a apela metode. Pe scurt, folositi ".method" +(. (Date.) getTime) ; +(.getTime (Date.)) ; exact acelasi lucru. + +; Folositi / pentru a apela metode statice +(System/currentTimeMillis) ; (System este prezent intotdeauna) + +; Folositi doto pentru a gestiona clase (mutable) mai usor +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory este un mecanism folost de Clojure pentru +; a gestiona stari persistente. Sunt putine instante in care este folosit. + +; Un atom este cel mai simplu exemplu. Dati-i o valoare initiala +(def my-atom (atom {})) + +; Modificati-l cu swap!. +; swap! primeste o functie si o apeleaza cu valoarea actuala a atomului +; ca prim argument si orice argumente suplimentare ca al doilea +(swap! my-atom assoc :a 1) ; Atomul ia valoarea rezultata din (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Atomul ia valoarea rezultata din (assoc {:a 1} :b 2) + +; Folositi '@' pentru a dereferentia atomul si a-i recupera valoarea +my-atom ;=> Atom<#...> (Returmeaza obiectul Atom) +@my-atom ; => {:a 1 :b 2} + +; Aici avem un contor simplu care foloseste un atom +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Alte utilizari ale STM sunt referintele (refs) si agentii (agents). +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Lectura suplimentara + +Lista nu este in niciun caz exhaustiva, dar speram ca este suficienta pentru +a va oferi un inceput bun in Clojure. + +Clojure.org contine multe articole: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org contine documentatie cu exemple pentru majoritatea functiilor de baza: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure este o metoda excelenta pentru a exersa Clojure/FP (Programarea Functionala): +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org are un numar de article pentru incepatori: +[http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From 7cb4534b6e088744f9b79cc6eeaf47ab90ed413b Mon Sep 17 00:00:00 2001 From: Bogdan Paun Date: Fri, 7 Aug 2015 12:47:36 +0300 Subject: fixed some spacing issues --- ro-ro/clojure-ro.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ro-ro/clojure-ro.html.markdown b/ro-ro/clojure-ro.html.markdown index 7dd51615..8b1327d8 100644 --- a/ro-ro/clojure-ro.html.markdown +++ b/ro-ro/clojure-ro.html.markdown @@ -9,8 +9,10 @@ lang: ro-ro --- Clojure este un limbaj din familia Lisp dezvoltat pentru Masina Virtuala Java -(Java Virtual Machine - JVM). Pune un accent mult mai puternic pe [programarea funcionala](https://en.wikipedia.org/wiki/Functional_programming) pura decat Common Lisp, dar include -utilitare [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) pentru +(Java Virtual Machine - JVM). Pune un accent mult mai puternic pe +[programarea funcionala](https://en.wikipedia.org/wiki/Functional_programming) +pura decat Common Lisp, dar include +utilitare [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) pentru a gestiona starea, atunci cand aceasta apare. Combinatia aceasta ii permite sa gestioneze procese concurente foarte usor, -- cgit v1.2.3 From c0a6e8fdf9508348645f895840ff93bcfcb9fa02 Mon Sep 17 00:00:00 2001 From: Bogdan Paun Date: Fri, 7 Aug 2015 12:50:36 +0300 Subject: line length tweaking.. --- ro-ro/clojure-ro.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ro-ro/clojure-ro.html.markdown b/ro-ro/clojure-ro.html.markdown index 8b1327d8..32ba9620 100644 --- a/ro-ro/clojure-ro.html.markdown +++ b/ro-ro/clojure-ro.html.markdown @@ -11,9 +11,8 @@ lang: ro-ro Clojure este un limbaj din familia Lisp dezvoltat pentru Masina Virtuala Java (Java Virtual Machine - JVM). Pune un accent mult mai puternic pe [programarea funcionala](https://en.wikipedia.org/wiki/Functional_programming) -pura decat Common Lisp, dar include -utilitare [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) pentru -a gestiona starea, atunci cand aceasta apare. +pura decat Common Lisp, dar include utilitare [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) +pentru a gestiona starea, atunci cand aceasta apare. Combinatia aceasta ii permite sa gestioneze procese concurente foarte usor, de multe ori in mod automat. -- cgit v1.2.3 From cfb6c3a35ff52d706d337986d62104ecdb424d88 Mon Sep 17 00:00:00 2001 From: sdcuike <303286730@qq.com> Date: Fri, 7 Aug 2015 23:06:17 +0800 Subject: =?UTF-8?q?=20~=20=20=20=20=20=20=20=E5=8F=96=E5=8F=8D=EF=BC=8C?= =?UTF-8?q?=E6=B1=82=E5=8F=8D=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zh-cn/java-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index f08d3507..12afa59a 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -149,7 +149,7 @@ public class LearnJava { // 位运算操作符 /* - ~ 补 + ~ 取反,求反码 << 带符号左移 >> 带符号右移 >>> 无符号右移 -- cgit v1.2.3 From 01d5e4d6dd7a60142fb1342637c851c943f62530 Mon Sep 17 00:00:00 2001 From: TsT Date: Fri, 7 Aug 2015 17:56:09 +0200 Subject: =?UTF-8?q?Quelques=20corrections=20et=20am=C3=A9liorations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/lua-fr.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index b4e2a161..1f592320 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -434,9 +434,9 @@ les librairies standard: Autres références complémentaires: -* Lua for programmers -* Courte de référence de Lua -* Programming In Lua +* Lua pour programmeurs +* Référence condensée de Lua +* Programmer en Lua * Les manuels de référence Lua A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et @@ -446,4 +446,4 @@ Ce tutoriel a été originalement écrit pour tylerney disponible en tant que gist. Il a été traduit en français par Roland Yonaba (voir son github). -Amusez-vous bien avec Lua! \ No newline at end of file +Amusez-vous bien avec Lua! -- cgit v1.2.3 From 4904ab4dee44633407aad6183954907b89129add Mon Sep 17 00:00:00 2001 From: TsT Date: Fri, 7 Aug 2015 18:04:32 +0200 Subject: typo fix --- fr-fr/markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 29c0d65d..e5e7c73a 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -177,7 +177,7 @@ des syntaxes spécifiques --> \`\`\`ruby +gardez juste ```ruby ( ou nom de la syntaxe correspondant à votre code )--> def foobar puts "Hello world!" end -- cgit v1.2.3 From 3d26429ce202f4d00f80182d460ee5b3ccdc87c4 Mon Sep 17 00:00:00 2001 From: Dave Andersen Date: Sun, 9 Aug 2015 22:43:10 -0700 Subject: update "further reading" links Change the chat room reference from Stack Overflow chat to Gitter.im, and add a link to the "Red" Stack Overflow tag. --- red.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/red.html.markdown b/red.html.markdown index 73a13606..f33060c4 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -212,7 +212,9 @@ The source can be found on [github](https://github.com/red/red). The Red/System language specification can be found [here](http://static.red-lang.org/red-system-specs-light.html). -To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). You will need 20 points to chat but if you ask or answer questions about Red or Rebol we will help you get those points. And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). +To learn more about Rebol and Red join the [chat on Gitter](https://gitter.im/red/red). And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). + +Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/red). Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). -- cgit v1.2.3 From 2d79a2be127a4e7e98dcc0dd68c0ea87d7278934 Mon Sep 17 00:00:00 2001 From: runfastlynda Date: Mon, 10 Aug 2015 19:56:54 +0800 Subject: input typo fixed --- zh-cn/javascript-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index b450ab84..dfeb2012 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -402,7 +402,7 @@ myObj.meaningOfLife; // = 42 // 函数也可以工作。 myObj.myFunc() // = "hello world!" -// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型,以此类堆。 +// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型,以此类推。 myPrototype.__proto__ = { myBoolean: true }; -- cgit v1.2.3 From 27b9ee85fb65c9192a070890375e678a7d02f9e6 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 12 Aug 2015 06:38:17 +0900 Subject: Fixes #1196 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 56640a87..91b84b47 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -415,7 +415,7 @@ distance = 18; // References "long distance" from MyClass implementation + (NSString *)classMethod { - return [[self alloc] init]; + return @"Some string"; } + (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight -- cgit v1.2.3 From 612511740298c9b7827c112f455092ce2a655d90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Fri, 14 Aug 2015 11:03:14 -0300 Subject: [Perl/en] translated to [Perl/pt-br] --- pt-br/perl-pt.html.markdown | 166 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 pt-br/perl-pt.html.markdown diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown new file mode 100644 index 00000000..5cad1be3 --- /dev/null +++ b/pt-br/perl-pt.html.markdown @@ -0,0 +1,166 @@ +--- +name: perl +category: language +language: perl +filename: learnperl.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +Perl 5 é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento. + +Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala. + +```perl +# Comentários de uma linha começam com um sinal de número. + +#### Tipos de variáveis em Perl + +# Variáveis iniciam com um sigilo, que é um símbolo que mostra o tipo. +# Um nome de variável válido começa com uma letra ou sublinhado, +# seguido por qualquer número de letras, números ou sublinhados. + +### Perl has three main variable types: $scalar, @array, e %hash. + +## Scalars +# Um scalar representa um valor único: +my $animal = "camelo"; +my $resposta = 42; + +# Valores scalar podem ser strings, inteiros ou números ponto-flutuantes e +# Perl vai automaticamente converter entre eles quando for preciso. + +## Arrays +# Um array representa uma lista de valores: +my @animais = ("camelo", "vaca", "boi"); +my @números = (23, 42, 69); +my @misturado = ("camelo", 42, 1.23); + +## Hashes +# Um hash representa um conjunto de pares chave/valor: + +my %fruta_cor = ("maçã", "vermelho", "banana", "amarelo"); + +# Você pode usar o espaço em branco e o operador "=>" para colocá-los de +# maneira mais agradável: + +my %fruta_cor = ( + maçã => "vermelho", + banana => "amarelo", +); + +# Scalars, arrays and hashes são documentados mais profundamentes em perldata. +# (perldoc perldata). + +# Mais tipos de dados complexos podem ser construídas utilizando referências, +# o que permite que você crie listas e hashes dentro de listas e hashes. + +#### Condicionais e construtores de iteração + +# Perl possui a maioria das construções condicionais e de iteração habituais. + +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (condição) { + ... +} +# Isto é fornecido como uma versão mais legível de "if (!condition)" + +# A forma Perlish pós-condição +print "Yow!" if $zippy; +print "Nós não temos nenhuma banana" unless $bananas; + +# while +while (condição) { + ... +} + +# for +for (my $i = 0; $i < $max; $i++) { + print "valor é $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "Elemento atual é " . $elements[$i]; +} + +for my $element (@elements) { + print $element; +} + +# implícito + +for (@elements) { + print; +} + +#### Expressões regulares + +# O suporte a expressões regulares do Perl é ao mesmo tempo amplo e profundo, +# e é objeto de longa documentação em perlrequick, perlretut, e em outros +# lugares. No entanto, em suma: + +# Casamento simples +if (/foo/) { ... } # verdade se $_ contém "foo" +if ($a =~ /foo/) { ... } # verdade se $a contém "foo" + +# Substituição simples + +$a =~ s/foo/bar/; # substitui foo com bar em $a +$a =~ s/foo/bar/g; # substitui TODAS AS INSTÂNCIAS de foo com bar em $a + +#### Arquivos e I/O + +# Você pode abrir um arquivo para entrada ou saída usando a função "open()". + +open(my $in, "<", "input.txt") ou desistir "Não pode abrir input.txt: $!"; +open(my $out, ">", "output.txt") ou desistir "Não pode abrir output.txt: $!"; +open(my $log, ">>", "my.log") ou desistir "Não pode abrir my.log: $!"; + +# Você pode ler de um arquivo aberto usando o operador "<>". No contexto +# scalar, ele lê uma única linha do arquivo, e em contexto de lista lê o +# arquivo inteiro, atribuindo cada linha a um elemento da lista: + +my $linha = <$in>; +my @linhas = <$in>; + +#### Escrevendo subrotinas + +# Escrever subrotinas é fácil: + +sub logger { + my $mensagem = shift; + + open my $arquivo, ">>", "my.log" or die "Não poderia abrir my.log: $!"; + + print $arquivo $ensagem; +} + +# Agora nós podemos usar a subrotina como qualquer outra função construída: + +logger("Nós temos uma subrotina de log!"); +``` + +#### Usando módulos Perl + +Módulos Perl provê uma lista de recursos para lhe ajudar a evitar redesenhar +a roda, e tudo isso pode ser baixado do CPAN (http://www.cpan.org/). Um número +de módulos populares podem ser incluídos com a própria distribuição do Perl. + +perlfaq contém questões e respostas relacionadas a muitas tarefas comuns, e frequentemente provê sugestões para um bom números de módulos CPAN. + +#### Leitura Adicional + + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` -- cgit v1.2.3 From d46831e598d873940f02d2670464a3408a3c8a0a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sat, 15 Aug 2015 00:08:43 +0900 Subject: Update xml-pt.html.markdown --- pt-br/xml-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/xml-pt.html.markdown b/pt-br/xml-pt.html.markdown index 40ddbc3a..f347f8ef 100644 --- a/pt-br/xml-pt.html.markdown +++ b/pt-br/xml-pt.html.markdown @@ -1,8 +1,8 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-pt.xml contributors: - - ["João Farias", "https://github.com/JoaoGFarias"] + - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] lang: pt-br @@ -130,4 +130,4 @@ com a adição de definição DTD.--> 30.00 -``` \ No newline at end of file +``` -- cgit v1.2.3 From b90d7f1cad68c8d8be6c5786ce825daed1c926e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Fri, 14 Aug 2015 12:57:25 -0300 Subject: Update filename in perl-pt.html.markdown --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index 5cad1be3..cc07a2ec 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -2,7 +2,7 @@ name: perl category: language language: perl -filename: learnperl.pl +filename: learnperl-pt.pl contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] translators: -- cgit v1.2.3 From a0e8d3202b1642d9be1a8fcc6db95273415373b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ismael=20Venegas=20Castell=C3=B3?= Date: Fri, 14 Aug 2015 20:28:08 -0500 Subject: Update julia-es to v0.3.11 --- es-es/julia-es.html.markdown | 1268 ++++++++++++++++++++++++------------------ 1 file changed, 724 insertions(+), 544 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 203ee3bb..1e01c2e3 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -4,757 +4,937 @@ contributors: - ["Leah Hanson", "http://leahhanson.us"] translators: - ["Guillermo Garza", "http://github.com/ggarza"] + - ["Ismael Venegas Castelló", "https://github.com/Ismael-VC"] filename: learnjulia-es.jl lang: es-es --- -Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. -Aunque que tiene todo el poder de macros homoiconic, funciones de primera -clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como -Python. +![JuliaLang](https://camo.githubusercontent.com/e1ae5c7f6fe275a50134d5889a68f0acdd09ada8/687474703a2f2f6a756c69616c616e672e6f72672f696d616765732f6c6f676f5f68697265732e706e67) -Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de -2013. +[Julia](http://julialanges.github.io) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org). -```ruby +En Julia los programas están organizados entorno al [despacho múltiple](http://docs.julialang.org/en/release-0.3/manual/methods/#man-methods); definiendo funciones y sobrecargándolas para diferentes combinaciones de tipos de argumentos, los cuales también pueden ser definidos por el usuario. -# Comentarios de una línea comienzan con una almohadilla (o signo gato) +### ¡Prueba Julia ahora mismo! -#= Commentarios multilinea pueden escribirse - usando '#=' antes de el texto y '=#' - después del texto. También se pueden anidar. +* [TryJupyter](https://try.jupyter.org) +* [JuliaBox](https://juliabox.org) +* [SageMathCloud](https://cloud.sagemath.com) + +### Resumen de Características: + +* [Despacho múltiple](http://en.wikipedia.org/wiki/Multiple_dispatch): permite definir el comportamiento de las funciones a través de múltiples combinaciones de tipos de argumentos (**métodos**). +* Sistema de **tipado dinámico**: tipos para la documentación, la optimización y el despacho. +* [Buen desempeño](http://julialang.org/benchmarks), comparado al de lenguajes **estáticamente compilados** como C. +* [Gestor de paquetes](http://docs.julialang.org/en/release-0.3/stdlib/pkg) integrado. +* [Macros tipo Lisp](http://docs.julialang.org/en/release-0.3/manual/metaprogramming/#macros) y otras comodidades para la [meta programación](http://docs.julialang.org/en/release-0.3/manual/metaprogramming). +* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **Matlab** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)). +* [Llamar funciones de C y Fortran](http://docs.julialang.org/en/release-0.3/manual/calling-c-and-fortran-code) **directamente**: sin necesidad de usar envoltorios u APIs especiales. +* Poderosas características de **línea de comandos** para [gestionar otros procesos](http://docs.julialang.org/en/release-0.3/manual/running-external-programs). +* Diseñado para la [computación paralela y distribuida](http://docs.julialang.org/en/release-0.3/manual/parallel-computing) **desde el principio**. +* [Corrutinas](http://en.wikipedia.org/wiki/Coroutine): hilos ligeros "**verdes**". +* Los [tipos definidos por el usuario](http://docs.julialang.org/en/release-0.3/manual/types) son tan **rápidos y compactos** como los tipos estándar integrados. +* [Generación automática de código](http://docs.julialang.org/en/release-0.3/stdlib/base/?highlight=%40code#internals) **eficiente y especializado** para diferentes tipos de argumentos. +* [Conversiones y promociones](http://docs.julialang.org/en/release-0.3/manual/conversion-and-promotion) para tipos numéricos y de otros tipos, **elegantes y extensibles**. +* Soporte eficiente para [Unicode](http://es.wikipedia.org/wiki/Unicode), incluyendo [UTF-8](http://es.wikipedia.org/wiki/UTF-8) pero sin limitarse solo a este. +* [Licencia MIT](https://github.com/JuliaLang/julia/blob/master/LICENSE.md): libre y de código abierto. + +Esto se basa en la versión `0.3.11`. + +```julia +# Los comentarios de una línea comienzan con una almohadilla (o signo de gato). + +#= + Los commentarios multilínea pueden escribirse + usando '#=' antes de el texto y '=#' + después del texto. También se pueden anidar. =# -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### -# Todo en Julia es una expresión. +############################################## +# 1. Tipos de datos primitivos y operadores. # +############################################## + +# Todo en Julia es una expresión (Expr). # Hay varios tipos básicos de números. -3 # => 3 (Int64) -3.2 # => 3.2 (Float64) -2 + 1im # => 2 + 1im (Complex{Int64}) -2//3 # => 2//3 (Rational{Int64}) +3 # => 3 # Int64 +3.2 # => 3.2 # Float64 +2 + 1im # => 2 + 1im # Complex{Int64} +2 // 3 # => 2//3 # Rational{Int64} # Todos los operadores infijos normales están disponibles. -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 -5/2 # => 2.5 # dividir un Int por un Int siempre resulta en un Float -div (5, 2) # => 2 # para un resultado truncado, usa div -5 \ 35 # => 7.0 -2 ^ 2 # => 4 # exponente, no es xor -12 % 10 # => 2 - -# Refuerza la precedencia con paréntesis -(1 + 3) * 2 # => 8 - -# Operadores a nivel de bit -~2 # => -3 # bitwise not -3 & 5 # => 1 # bitwise and -2 | 4 # => 6 # bitwise or -2 $ 4 # => 6 # bitwise xor -2 >>> 1 # => 1 # logical shift right -2 >> 1 # => 1 # arithmetic shift right -2 << 1 # => 4 # logical/arithmetic shift left - -# Se puede utilizar la función bits para ver la representación binaria de un -# número. +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 # dividir un Int por un Int siempre resulta + # en un Float +5 / 2 # => 2.5 +div(5, 2) # => 2 # para un resultado truncado, usa la función div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # exponente, no es XOR +12 % 10 # => 2 + +# Refuerza la precedencia con paréntesis. +(1 + 3) * 2 # => 8 + +# Operadores a nivel de bit. +~2 # => -3 # bitwise NOT +3 & 5 # => 1 # bitwise AND +2 | 4 # => 6 # bitwise OR +2 $ 4 # => 6 # bitwise XOR +2 >>> 1 # => 1 # desplazamiento lógico hacia la derecha +2 >> 1 # => 1 # desplazamiento aritmético hacia la derecha +2 << 1 # => 4 # desplazamiento lógico/aritmético hacia la izquierda + +# Se puede utilizar la función bits para ver la representación +# binaria de un número. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" + bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" -# Valores 'boolean' (booleanos) son primitivos -true -false - -# Operadores Boolean (booleanos) -!true # => false -!false # => true -1 == 1 # => true -2 == 1 # => false -1 != 1 # => false -2 != 1 # => true -1 < 10 # => true -1 > 10 # => false -2 <= 2 # => true -2 >= 2 # => true +# Los valores booleanos (Bool) son primitivos. +true # => true +false # => false + +# Operadores booleanos. +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true + # ¡Las comparaciones pueden ser concatenadas! -1 < 2 < 3 # => true -2 < 3 < 2 # => false +1 < 2 < 3 # => true +2 < 3 < 2 # => false -# Strings se crean con " -"Esto es un string." +# Los literales de cadenas (String) se crean con la comilla doble: " +"Esto es una cadena." -# Literales de caracteres se escriben con ' +# Los literales de caracteres (Char) se crean con la comilla simple: ' 'a' -# Una string puede ser indexado como una array de caracteres -"Esto es un string."[1] # => 'E' # Índices en Julia empiezen del 1 -# Sin embargo, esto no va a funcionar bien para strings UTF8, +# Una cadena puede ser indexada como una arreglo de caracteres. +"Esto es un string."[1] # => 'E' # Los índices en Julia comienzan en: 1 + +# Sin embargo, esto no va a funcionar bien para las cadenas UTF8 (UTF8String), # Lo que se recomienda es la iteración (map, for, etc). -# $ puede ser utilizado para la interpolación de strings: -"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# Se puede poner cualquier expresión de Julia dentro los paréntesis. +# $ puede ser utilizado para la interpolación de cadenas, se puede poner +# cualquier expresión de Julia dentro los paréntesis. +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" + +# Otra forma para formatear cadenas es usando el macro printf. +@printf "%d es menor de %f\n" 4.5 5.3 # 5 es menor de 5.300000 -# Otro forma de formatear strings es el macro printf -@printf "%d es menor de %f" 4.5 5.3 # 5 es menor de 5.300000 +# ¡Imprimir es muy fácil! +println("¡Hola Julia!") # ¡Hola Julia! -# Imprimir es muy fácil -println("Soy Julia. ¡Encantado de conocerte!") -#################################################### -## 2. Variables y Colecciones -#################################################### +############################## +# 2. Variables y Colecciones # +############################## # No hay necesidad de declarar las variables antes de asignarlas. -una_variable = 5 # => 5 -una_variable # => 5 +una_variable = 5 # => 5 +una_variable # => 5 -# Acceder a variables no asignadas previamente es una excepción. +# Acceder a una variable no asignada previamente es una excepción. try - otra_variable # => ERROR: some_other_var not defined + otra_variable # ERROR: otra_variable not defined catch e - println(e) + println(e) # UndefVarError(:otra_variable) end -# Los nombres de variables comienzan con una letra. -# Después de eso, puedes utilizar letras, dígitos, guiones y signos de +# Los nombres de variables comienzan con una letra o guion bajo: _. +# Después de eso, puedes utilizar letras, dígitos, guiones bajos y signos de # exclamación. -OtraVariable123! = 6 # => 6 +otraVariable_123! = 6 # => 6 + +# También puedes utilizar caracteres Unicode. +☃ = 8 # => 8 -# También puede utilizar caracteres unicode -☃ = 8 # => 8 # Estos son especialmente útiles para la notación matemática -2 * π # => 6.283185307179586 - -# Una nota sobre las convenciones de nomenclatura de Julia: -# -# * Los nombres de las variables aparecen en minúsculas, con separación de -# palabra indicado por underscore ('\ _'). -# -# * Los nombres de los tipos comienzan con una letra mayúscula y separación de -# palabras se muestra con CamelCase en vez de underscore. -# -# * Los nombres de las funciones y los macros están en minúsculas, sin -# underscore. -# -# * Funciones que modifican sus inputs tienen nombres que terminan en!. Estos -# funciones a veces se llaman mutating functions o in-place functions. - -# Los Arrays almacenan una secuencia de valores indexados entre 1 hasta n -a = Int64[] # => 0-element Int64 Array - -# Literales de arrays 1-dimensionales se pueden escribir con valores separados -# por comas. -b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] -b[1] # => 4 -b[end] # => 6 - -# Los arrays 2-dimensionales usan valores separados por espacios y filas -# separados por punto y coma. -matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] - -# Añadir cosas a la final de una lista con push! y append! -push!(a,1) # => [1] -push!(a,2) # => [1,2] -push!(a,4) # => [1,2,4] -push!(a,3) # => [1,2,4,3] -append!(a,b) # => [1,2,4,3,4,5,6] - -# Eliminar de la final con pop -pop!(b) # => 6 y b ahora es [4,5] - -# Vamos a ponerlo de nuevo -push!(b, 6) # b es ahora [4,5,6] de nuevo. - -a[1] # => 1 # recuerdan que los índices de Julia empiezan desde 1, no desde 0! - -# end es una abreviatura para el último índice. Se puede utilizar en cualquier -# expresión de indexación -a[end] # => 6 - -# tambien hay shift y unshift -shift!(a) # => 1 y a es ahora [2,4,3,4,5,6] -unshift!(a,7) # => [7,2,4,3,4,5,6] - -# Nombres de funciónes que terminan en exclamaciones indican que modifican -# su argumento. -arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] -sort(arr) # => [4,5,6]; arr es todavía [5,4,6] -sort!(arr) # => [4,5,6]; arr es ahora [4,5,6] - -# Buscando fuera de límites es un BoundsError +# (multiplicación implicita). +2π # => 6.283185307179586 + +#= + Una nota sobre las convenciones de nomenclatura de Julia: + + * Los nombres de las variables aparecen en minúsculas, con separación de + palabra indicado por un guion bajo: + + otra_variable + + * Los nombres de los tipos comienzan con una letra mayúscula y separación de + palabras se muestra con CamelCase en vez de guion bajo: + + OtroTipo + + * Los nombres de las funciones y los macros están en minúsculas, sin + underscore: + + otromacro + + * Funciones que modifican sus entradas tienen nombres que terminan en: !. + Estas funciones a veces se les llaman funciones transformadoras o + funciones in situ: + + otra_funcion! +=# + +# Los arreglos (Array) almacenan una secuencia de valores indexados de entre 1 hasta n. +a = Int64[] # => 0-element Array{Int64,1} + +# Los literales de arregos unidimensionales se pueden escribir con valores +# separados por comas. +b = [4, 5, 6] +#= + => 3-element Array{Int64,1}: + 4 + 5 + 6 +=# +b[1] # => 4 +b[end] # => 6 + +# Los arreglos bidimensionales usan valores separados por espacios y filas +# separadas por punto y coma. +matrix = [1 2; 3 4] +#= + => 2x2 Array{Int64,2}: + 1 2 + 3 4 +=# + +# Añadir cosas a la final de un arreglo con push! y append!. +push!(a, 1) # => [1] +push!(a, 2) # => [1,2] +push!(a, 4) # => [1,2,4] +push!(a, 3) # => [1,2,4,3] +append!(a, b) # => [1,2,4,3,4,5,6] + +# Eliminar del final con pop!. +pop!(b) # => 6 y b ahora es: [4,5] + +# Vamos a ponerlo de nuevo. +push!(b, 6) # b es ahora [4,5,6] de nuevo + +a[1] # => 1 # recuerda, los índices de Julia empiezan desde 1, no desde 0! + +# end es una abreviatura para el último índice. Se puede utilizar en cualquier +# expresión de indexación. +a[end] # => 6 + +# También hay shift! y unshift!. +shift!(a) # => 1 y a es ahora: [2,4,3,4,5,6] +unshift!(a, 7) # => [7,2,4,3,4,5,6] + +# Los nombres de funciónes que terminan en exclamaciones indican que modifican +# su o sus argumentos de entrada. +arr = [5, 4, 6] # => 3-element Array{Int64,1}: [5,4,6] +sort(arr) # => [4,5,6] y arr es todavía: [5,4,6] +sort!(arr) # => [4,5,6] y arr es ahora: [4,5,6] + +# Buscando fuera de límites es un BoundsError. try - a[0] # => ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 + a[0] # ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # ERROR: BoundsError() in getindex at array.jl:270 catch e - println(e) + println(e) # BoundsError() end -# Errors dan la línea y el archivo de su procedencia, aunque sea en el standard -# library. Si construyes Julia de source, puedes buscar en el source para -# encontrar estos archivos. +# Las excepciones y los errores dan la línea y el archivo de su procedencia, +# aunque provenga de la librería estándar. Si compilas Julia del código fuente, +# puedes buscar en el código para encontrar estos archivos. + +# Se puede inicializar un arreglo con un rango (Range). +a = [1:5] # => 5-element Array{Int64,1}: [1,2,3,4,5] -# Se puede inicializar arrays de un range -a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +# Puedes mirar en los rangos con la sintaxis de rebanada. +a[1:3] # => [1,2,3] +a[2:end] # => [2,3,4,5] -# Puedes mirar en ranges con sintaxis slice. -a[1:3] # => [1, 2, 3] -a[2:end] # => [2, 3, 4, 5] +# Eliminar elementos de un arreglo por índice con splice! +arr = [3, 4, 5] +splice!(arr, 2) # => 4 y arr es ahora: [3,5] -# Eliminar elementos de una array por índice con splice! -arr = [3,4,5] -splice!(arr,2) # => 4 ; arr es ahora [3,5] +# Concatenar arreglos con append! +b = [1, 2, 3] +append!(a, b) # a ahora es: [1,2,3,4,5,1,2,3] -# Concatenar listas con append! -b = [1,2,3] -append!(a,b) # ahroa a es [1, 2, 3, 4, 5, 1, 2, 3] +# Comprueba la existencia de un elemento en un arreglo con in. +in(1, a) # => true -# Comprueba la existencia en una lista con in -in(1, a) # => true +# Examina la longitud con length. +length(a) # => 8 -# Examina la longitud con length -length(a) # => 8 +# Las tuplas (Tuple) son inmutables. +tup = (1, 2, 3) # => (1,2,3) # una tupla tipo (Int64,Int64,Int64) +tup[1] # => 1 -# Tuples son immutable. -tup = (1, 2, 3) # => (1,2,3) # un (Int64,Int64,Int64) tuple. -tup[1] # => 1 try: - tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 # ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) catch e - println(e) + println(e) # MethodError(setindex!,(:tup,3,1)) end -# Muchas funciones de lista también trabajan en las tuples -length(tup) # => 3 -tup[1:2] # => (1,2) -in(2, tup) # => true +# Muchas funciones de arreglos también trabajan en con las tuplas. +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true -# Se puede desempacar tuples en variables -a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +# Se pueden desempacar las tuplas en variables individuales. +a, b, c = (1, 2, 3) # => (1,2,3) # ahora a es 1, b es 2 y c es 3 -# Los tuples se crean, incluso si se omite el paréntesis -d, e, f = 4, 5, 6 # => (4,5,6) +# Los tuplas se crean, incluso si se omiten los paréntesis. +d, e, f = 4, 5, 6 # => (4,5,6) -# Un tuple 1-elemento es distinto del valor que contiene -(1,) == 1 # => false -(1) == 1 # => true +# Una tupla de un elemento es distinta del valor que contiene. +(1,) == 1 # => false +(1) == 1 # => true -# Mira que fácil es cambiar dos valores -e, d = d, e # => (5,4) # d is now 5 and e is now 4 +# Mira que fácil es cambiar dos valores! +e, d = d, e # => (5,4) # ahora d es 5 y e es 4 +# Los diccionarios (Dict) son arreglos asociativos. +dicc_vacio = Dict() # => Dict{Any,Any} with 0 entries -# Dictionaries almanecan mapeos -dict_vacio = Dict() # => Dict{Any,Any}() +# Se puede crear un diccionario usando una literal. +dicc_lleno = ["uno" => 1, "dos" => 2, "tres" => 3] +#= + => Dict{ASCIIString,Int64} with 3 entries: + "tres" => 3 + "dos" => 2 + "uno" => 1 +=# + +# Busca valores con: []. +dicc_lleno["uno"] # => 1 + +# Obtén todas las claves con. +keys(dicc_lleno) +#= + => KeyIterator for a Dict{ASCIIString,Int64} with 3 entries. Keys: + "tres" + "dos" + "uno" +=# -# Se puede crear un dictionary usando un literal -dict_lleno = ["one"=> 1, "two"=> 2, "three"=> 3] -# => Dict{ASCIIString,Int64} +# Nota: los elementos del diccionario no están ordenados y no se guarda el orden +# en que se insertan. -# Busca valores con [] -dict_lleno["one"] # => 1 +# Obtén todos los valores. +values(dicc_lleno) +#= + => ValueIterator for a Dict{ASCIIString,Int64} with 3 entries. Values: + 3 + 2 + 1 +=# -# Obtén todas las claves -keys(dict_lleno) -# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - claves del dictionary no están ordenados ni en el orden en que se -# insertan. +# Nota: igual que el anterior en cuanto a ordenamiento de los elementos. -# Obtén todos los valores -values(dict_lleno) -# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - Igual que el anterior en cuanto a ordenamiento de claves. +# Comprueba si una clave existe en un diccionario con in y haskey. +in(("uno", 1), dicc_lleno) # => true +in(("tres", 3), dicc_lleno) # => false -# Compruebe si hay existencia de claves en un dictionary con in y haskey -in(("uno", 1), dict_lleno) # => true -in(("tres", 3), dict_lleno) # => false -haskey(dict_lleno, "one") # => true -haskey(dict_lleno, 1) # => false +haskey(dicc_lleno, "uno") # => true +haskey(dicc_lleno, 1) # => false -# Tratando de buscar una clave que no existe producirá un error +# Tratar de obtener un valor con una clave que no existe producirá un error. try - dict_lleno["dos"] # => ERROR: key not found: dos in getindex at dict.jl:489 + # ERROR: key not found: cuatro in getindex at dict.jl:489 + dicc_lleno["cuatro"] catch e - println(e) + println(e) # KeyError("cuatro") end -# Utilice el método get para evitar ese error proporcionando un valor -# predeterminado -# get(dictionary,key,default_value) -get(dict_lleno,"one",4) # => 1 -get(dict_lleno,"four",4) # => 4 +# Utiliza el método get para evitar este error proporcionando un valor +# predeterminado: get(diccionario, clave, valor_predeterminado). +get(dicc_lleno, "uno", 4) # => 1 +get(dicc_lleno, "cuatro", 4) # => 4 + +# Usa conjuntos (Set) para representar colecciones de valores únicos, no +# ordenados. +conjunto_vacio = Set() # => Set{Any}({}) -# Usa Sets para representar colecciones (conjuntos) de valores únicos, no -# ordenadas -conjunto_vacio = Set() # => Set{Any}() -# Iniciar una set de valores -conjunto_lleno = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) +# Iniciar una conjunto de valores. +conjunto_lleno = Set(1, 2, 2, 3, 4) # => Set{Int64}({4,2,3,1}) -# Añadir más valores a un conjunto -push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) -push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) +# Añadir más valores a un conjunto. +push!(conjunto_lleno, 5) # => Set{Int64}({4,2,3,5,1}) +push!(conjunto_lleno, 5) # => Set{Int64}({4,2,3,5,1}) -# Compruebe si los valores están en el conjunto -in(2, conjunto_lleno) # => true -in(10, conjunto_lleno) # => false +# Comprobar si los valores están en el conjunto. +in(2, conjunto_lleno) # => true +in(10, conjunto_lleno) # => false -# Hay funciones de intersección de conjuntos, la unión, y la diferencia. -conjunto_otro= Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) -intersect(conjunto_lleno, conjunto_otro) # => Set{Int64}(3,4,5) -union(conjunto_lleno, conjunto_otro) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +# Hay funciones de intersección, unión y diferencia de conjuntos. +otro_conjunto = Set(3, 4, 5, 6) # => Set{Int64}({6,4,5,3}) +intersect(conjunto_lleno, otro_conjunto) # => Set{Int64}({3,4,5}) +union(conjunto_lleno, otro_conjunto) # => Set{Int64}({1,2,3,4,5,6}) +setdiff(Set(1, 2, 3, 4), Set(2, 3, 5)) # => Set{Int64}({1,4}) -#################################################### -## 3. Control de Flujo -#################################################### +####################### +# 3. Control de Flujo # +####################### -# Hagamos una variable +# Hagamos una variable. una_variable = 5 -# Aquí está una declaración de un 'if'. La indentación no es significativa en -# Julia +# Aquí está la declaración de un if. La indentación no es significativa en +# Julia. if una_variable > 10 - println("una_variable es completamente mas grande que 10.") -elseif una_variable < 10 # Este condición 'elseif' es opcional. - println("una_variable es mas chica que 10.") -else # Esto también es opcional. - println("una_variable es de hecho 10.") + println("una_variable es completamente mayor que 10.") +elseif una_variable < 10 # esta condición elseif es opcional + println("una_variable es menor que 10.") +else # esto también es opcional + println("De echo una_variable es 10.") end -# => imprime "una_variable es mas chica que 10." +# imprime: una_variable es menor que 10. -# For itera sobre tipos iterables -# Tipos iterables incluyen Range, Array, Set, Dict, y String. -for animal=["perro", "gato", "raton"] - println("$animal es un mamifero") - # Se puede usar $ para interpolar variables o expresiónes en strings +# El bucle for itera sobre tipos iterables, ie. Range, Array, Set, +# Dict y String. +for animal in ["perro", "gato", "ratón"] + # Se puede usar $ para interpolar variables o expresiones en ls cadenas. + println("$animal es un mamífero.") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -for a in ["perro"=>"mamifero","gato"=>"mamifero","raton"=>"mamifero"] - println("$(a[1]) es un $(a[2])") +for a in ["perro" => "mamífero", "gato" => "mamífero", "ratón" => "mamífero"] + println("$(a[1]) es un $(a[2]).") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -for (k,v) in ["perro"=>"mamifero", "gato"=>"mamifero", "raton"=>"mamifero"] - println("$k es un $v") +for (k,v) in ["perro"=>"mamífero", "gato"=>"mamífero", "ratón"=>"mamífero"] + println("$k es un $v.") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -# While itera hasta que una condición no se cumple. +# El bucle while itera hasta que una condición se deje de cumplir. x = 0 while x < 4 println(x) - x += 1 # versión corta de x = x + 1 + x += 1 # versión corta de: x = x + 1 end -# imprime: -# 0 -# 1 -# 2 -# 3 +#= +imprime: + 0 + 1 + 2 + 3 +=# -# Maneja excepciones con un bloque try/catch -try - error("ayuda") +# Maneja excepciones con un bloque try/catch. +try # intentar + error("Ooops!") catch e - println("capturando $e") + println("capturando: $e") # capturando: ErrorException("Ooops!") end -# => capturando ErrorException("ayuda") -#################################################### -## 4. Funciones -#################################################### +################ +# 4. Funciones # +################ -# Usa 'function' para crear nuevas funciones +# Usa function para crear nuevas funciones. -#function nombre(arglist) -# cuerpo... -#end +#= + function nombre(arglist) + cuerpo... + end +=# function suma(x, y) println("x es $x e y es $y") - # Las funciones devuelven el valor de su última declaración + # las funciones devuelven el valor de su última expresión x + y end +# => suma (generic function with 1 method) -suma(5, 6) # => 11 # después de imprimir "x es 5 e y es de 6" +suma(5, 6) # => 11 # después de imprimir: x es 5 e y es 6 + +# También puedes usar esta otra sintaxis para definir funciones! +resta(x, y) = x - y # => resta (generic function with 1 method) # Puedes definir funciones que toman un número variable de -# argumentos posicionales +# argumentos posicionales (el ... se llama un splat). function varargs(args...) + # Usa la palabra clave return para regresar desde cualquier + # lugar de la función. return args - # Usa la palabra clave return para devolver en cualquier lugar de la función end # => varargs (generic function with 1 method) -varargs(1,2,3) # => (1,2,3) +varargs(1, 2, 3) # => (1,2,3) +varargs([1, 2, 3]) # => ([1,2,3],) -# El ... se llama un splat. -# Acabamos de utilizar lo en una definición de función. -# También se puede utilizar en una llamada de función, -# donde va splat un Array o el contenido de un Tuple en la lista de argumentos. -Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # Produce un Set de Arrays -Set([1,2,3]...) # => Set{Int64}(1,2,3) # esto es equivalente a Set(1,2,3) +# Acabamos de utilizar el splat (...) en la definición de una función. También +# se puede utilizar al llamar a una función, donde se esparce un arreglo, tupla +# o en general una secuencia iterable en la tupla de argumentos. +varargs([1, 2, 3]...) # => (1,2,3) # igual que: varargs(1, 2, 3) -x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # un Set de Tuples -Set(x...) # => Set{Int64}(2,3,1) +x = (1, 2, 3) # => (1,2,3) +varargs(x) # => ((1,2,3),) +varargs(x...) # => (1,2,3) +varargs("abc"...) # => ('a','b','c') -# Puede definir funciones con argumentos posicionales opcionales -function defaults(a,b,x=5,y=6) +# Puedes definir funciones con argumentos posicionales opcionales. +function defaults(a, b, x=5, y=6) return "$a $b y $x $y" end +# => defaults (generic function with 3 methods) + +defaults('h', 'g') # => "h g y 5 6" +defaults('h', 'g', 'j') # => "h g y j 6" +defaults('h', 'g', 'j', 'k') # => "h g y j k" -defaults('h','g') # => "h g y 5 6" -defaults('h','g','j') # => "h g y j 6" -defaults('h','g','j','k') # => "h g y j k" try - defaults('h') # => ERROR: no method defaults(Char,) - defaults() # => ERROR: no methods defaults() + defaults('h') # ERROR: `defaults` has no method matching defaults(::Char) + defaults() # ERROR: `defaults` has no method matching defaults() catch e - println(e) + println(e) # MethodError(defaults,('h',)) end -# Puedes definir funciones que toman argumentos de palabra clave -function args_clave(;k1=4,nombre2="hola") # note the ; - return ["k1"=>k1,"nombre2"=>nombre2] +# Puedes definir funciones que tomen argumentos de palabras clave. +function args_clave(;k1=4, nombre2="hola") # nota el punto y coma: ; + return ["k1" => k1, "nombre2" => nombre2] end +# => args_clave (generic function with 1 method) -args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] -args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] -args_clave() # => ["nombre2"=>"hola","k1"=>4] +args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] +args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] +args_clave() # => ["nombre2"=>"hola","k1"=>4] -# Puedes combinar todo tipo de argumentos en la misma función -function todos_los_args(arg_normal, arg_posicional_opcional=2; arg_clave="foo") - println("argumento normal: $arg_normal") - println("argumento optional: $arg_posicional_opcional") - println("argumento de clave: $arg_clave") +# Puedes combinar todo tipo de argumentos en la misma función. +function todos_los_args(arg_posicional, arg_opcional=2; arg_clave="foo") + println("argumento posicional: $arg_posicional") + println(" argumento opcional: $arg_opcional") + println(" argumento clave: $arg_clave") end +# => todos_los_args (generic function with 2 methods) +# No se necesita punto y coma ; al llamar la función usando un argumento clave, +# esto solo es necesario en la definición de la función. todos_los_args(1, 3, arg_clave=4) -# imprime: -# argumento normal: 1 -# argumento optional: 3 -# argumento de clave: 4 +#= + imprime: + argumento posicional: 1 + argumento opcional: 3 + argumento clave: 4 +=# -# Julia tiene funciones de primera clase +# Julia tiene funciones de primera clase. function crear_suma(x) - suma = function (y) + suma = function (y) # función anónima return x + y end return suma end +# => crear_suma (generic function with 1 method) -# Esta es el sintaxis "stabby lambda" para crear funciones anónimas -(x -> x > 2)(3) # => true +# Esta es otra sintaxis (estilo cálculo lambda), para crear funciones anónimas. +(x -> x > 2)(3) # => true # Esta función es idéntica a la crear_suma implementación anterior. -function crear_suma(x) - y -> x + y -end +crear_suma(x) = y -> x + y -# También puedes nombrar la función interna, si quieres +# También puedes nombrar la función interna, si quieres. function crear_suma(x) function suma(y) x + y end suma end +# => crear_suma (generic function with 1 method) -suma_10 = crear_suma(10) -suma_10(3) # => 13 +suma_10 = crear_suma(10) # => suma (generic function with 1 method) +suma_10(3) # => 13 +# Hay funciones integradas de orden superior. +map(suma_10, [1, 2, 3]) # => [11,12,13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6,7] -# Hay funciones integradas de orden superior -map(suma_10, [1,2,3]) # => [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +# Se puede pasar un bloque a las funciones cuyo primer argumento posicional +# es otra función, como en map y filter. +map([1, 2, 3]) do arr + suma_10(arr) +end +#= + => 3-element Array{Int64,1}: + 11 + 12 + 13 +=# + +filter([3, 4, 5, 6, 7]) do arr + (x -> x > 5)(arr) +end +#= + => 2-element Array{Int64,1}: + 6 + 7 +=# -# Podemos usar listas por comprensión para mapeos -[suma_10(i) for i=[1, 2, 3]] # => [11, 12, 13] -[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# Podemos usar comprensiones de listas multidimensionales. +[suma_10(i) for i = [1, 2, 3]] # => [11, 12, 13] # 1D +[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -#################################################### -## 5. Tipos -#################################################### +[i*j for i = [1:3], j in [1:3]] # 2D +#= + => 3x3 Array{Int64,2}: + 1 2 3 + 2 4 6 + 3 6 9 +=# + +[i*j/k for i = [1:3], j = [1:3], k in [1:3]] # 3D +#= + => 3x3x3 Array{Float64,3}: + [:, :, 1] = + 1.0 2.0 3.0 + 2.0 4.0 6.0 + 3.0 6.0 9.0 + + [:, :, 2] = + 0.5 1.0 1.5 + 1.0 2.0 3.0 + 1.5 3.0 4.5 + + [:, :, 3] = + 0.333333 0.666667 1.0 + 0.666667 1.33333 2.0 + 1.0 2.0 3.0 +=# + + +############ +# 5. Tipos # +############ -# Julia tiene sistema de tipos. # Cada valor tiene un tipo y las variables no tienen propios tipos. -# Se puede utilizar la función `typeof` para obtener el tipo de un valor. -typeof(5) # => Int64 +# Se puede utilizar la función typeof para obtener el tipo de un valor. +typeof(5) # => Int64 # en un sistema de 64 bits, de lo contrario: Int32 -# Los tipos son valores de primera clase -typeof(Int64) # => DataType -typeof(DataType) # => DataType -# DataType es el tipo que representa los tipos, incluyéndose a sí mismo. +# Los tipos son valores de primera clase, DataType es el tipo que representa a +# los tipos, incluyéndose a sí mismo. +typeof(Int64) # => DataType +typeof(DataType) # => DataType -# Los tipos se usan para la documentación, optimizaciones, y envio. -# No están comprobados estáticamente. +# Los tipos se usan para la documentación, para optimizaciones +# y el despacho múltiple. No están comprobados estáticamente. -# Los usuarios pueden definir tipos -# Son como registros o estructuras en otros idiomas. -# Nuevos tipos se definen utilizado la palabra clave `type`. +# Los usuarios pueden definir sus propios tipos. +# Son como registros o estructuras en otros idiomas. +# Un nuevo tipos se define utilizado la palabra clave type. # type Nombre -# field::OptionalType +# atributo::UnTipo # las anotaciones de tipos son opcionales # ... # end type Tigre - longituddecola::Float64 - colordelpelaje # no incluyendo una anotación de tipo es el mismo que `::Any` + longitud_cola::Float64 + color_pelaje # sin una anotación de tipo, es lo mismo que `::Any` end -# Los argumentos del constructor por default son las propiedades -# del tipo, en el orden en que están listados en la definición -tigger = Tigre(3.5,"anaranjado") # => Tiger(3.5,"anaranjado") +# Los argumentos del constructor por defecto son los atributos +# del tipo, en el orden en que están listados en la definición. +tigre = Tigre(3.5, "anaranjado") # => Tigre(3.5,"anaranjado") -# El tipo funciona como la función constructora de valores de ese tipo -sherekhan = typeof(tigger)(5.6,"fuego") # => Tiger(5.6,"fuego") +# El tipo funciona como método constructor para los valores de ese tipo. +sherekhan = typeof(tigre)(5.6, "fuego") # => Tigre(5.6,"fuego") -# Este estilo de tipos son llamados tipos concrete -# Se pueden crear instancias, pero no pueden tener subtipos. -# La otra clase de tipos es tipos abstractos (abstract types). +# Este estilo de tipos son llamados tipos concretos. +# Se pueden crear instancias de estos, pero no pueden tener subtipos. +# La otra clase de tipos son los tipos abstractos. # abstract Nombre -abstract Gato # sólo un nombre y un punto en la jerarquía de tipos - -# De los tipos Abstract no se pueden crear instancias, pero pueden tener -# subtipos. Por ejemplo, Number es un tipo abstracto. -subtypes(Number) # => 6-element Array{Any,1}: - # Complex{Float16} - # Complex{Float32} - # Complex{Float64} - # Complex{T<:Real} - # Real -subtypes(Gato) # => 0-element Array{Any,1} - -# Cada tipo tiene un supertipo, utilice la función `súper` para conseguirlo. -typeof(5) # => Int64 -super(Int64) # => Signed -super(Signed) # => Real -super(Real) # => Number -super(Number) # => Any -super(super(Signed)) # => Number -super(Any) # => Any -# Todo de estos tipos, a excepción de Int64, son abstractos. - -# <: es el operador de subtipos -type Leon <: Gato # Leon es un subtipo de Gato - color_de_crin - rugido::String -end +abstract Gato # sólo un nombre y un punto en la jerarquía de tipos + +# No se pueden crear instancias de los tipos abstractos, pero pueden tener +# subtipos. Por ejemplo, Number es un tipo abstracto. +subtypes(Number) +#= + => 2-element Array{Any,1}: + Complex{T<:Real} + Real +=# + +subtypes(Gato) # => 0-element Array{Any,1} + +# Cada tipo tiene un supertipo, utiliza la función súper para conseguirlo. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Integer +super(Integer) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Real +super(Any) # => Any -# Se puede definir más constructores para su tipo. -# Sólo defina una función del mismo nombre que el tipo -# y llame a un constructor existente para obtener un valor del tipo correcto -Leon(rugido::String) = Leon("verde",rugido) -# Este es un constructor externo porque es fuera de la definición del tipo - -type Pantera <: Gato # Pantera tambien es un a subtipo de Cat - color_de_ojos - Pantera() = new("verde") - # Panteras sólo tendrán este constructor, y ningún constructor - # predeterminado. +# Todos estos tipos, a excepción de Int64, son abstractos. + +# <: es el operador de subtipos. +type Leon <: Gato # Leon es un subtipo de Gato + color_crin + rugido::String end -# Utilizar constructores internos, como Panther hace, te da control sobre cómo -# se pueden crear valores del tipo. Cuando sea posible, debes utilizar -# constructores exteriores en lugar de los internos. -#################################################### -## 6. Envio múltiple -#################################################### +# Se pueden definir más constructores para un tipo. +# Sólo define una función del mismo nombre que el tipo y llama al constructor +# existente para obtener un valor del tipo correcto. -# En Julia, todas las funciones nombradas son funciones genéricas. -# Esto significa que se construyen a partir de muchos métodos pequeños -# Cada constructor de Leon es un método de la función genérica Leon. +# Este es un constructor externo porque es fuera de la definición del tipo. +Leon(rugido::String) = Leon("verde", rugido) -# Por ejemplo, vamos a hacer un maullar función: +type Pantera <: Gato # Pantera también es un a subtipo de Gato + color_ojos -# Definiciones para Leon, Pantera, y Tigre -function maullar(animal::Leon) - animal.rugido # acceso utilizando notación de puntos + # Pantera sólo tendrá este constructor, y ningún constructor predeterminado. + Pantera() = new("verde") end -function maullar(animal::Pantera) - "grrr" -end +# Utilizar constructores internos, como se hace en Pantera, te da control sobre +# cómo se pueden crear valores de este tipo. Cuando sea posible, debes utilizar +# constructores externos en lugar de internos. -function maullar(animal::Tigre) - "rawwwr" -end -# Prueba de la función maullar -maullar(tigger) # => "rawwr" -maullar(Leon("cafe","ROAAR")) # => "ROAAR" -maullar(Pantera()) # => "grrr" +######################## +# 6. Despacho Múltiple # +######################## -# Revisar la jerarquía de tipos locales -issubtype(Tigre,Gato) # => false -issubtype(Leon,Gato) # => true -issubtype(Pantera,Gato) # => true +# En Julia, todas las funciones nombradas son funciones genéricas. +# Esto significa que se construyen a partir de muchos métodosmás pequeños. +# Cada constructor de Leon es un método de la función genérica Leon. -# Definición de una función que toma Gatos -function mascota(gato::Gato) - println("El gato dice $(maullar(gato))") -end +# Por ejemplo, vamos a hacer métodos para para Leon, Pantera, y Tigre de una +# función genérica maullar: + +# acceso utilizando notación de puntos +maullar(animal::Leon) = animal.rugido +# => maullar (generic function with 1 method) +maullar(animal::Pantera) = "grrr" +# => maullar (generic function with 2 methods) +maullar(animal::Tigre) = "rawwwr" +# => maullar (generic function with 3 methods) + +# Se puede obtener una lista de métodos con la función methods. +methods(maullar) +#= + # 3 methods for generic function "maullar": + maullar(animal::Leon) at none:1 + maullar(animal::Pantera) at none:1 + maullar(animal::Tigre) at none:1 +=# + +# Prueba de la función maullar. +maullar(tigre) # => "rawwwr" +maullar(Leon("cafe", "ROAAR")) # => "ROAAR" +maullar(Pantera()) # => "grrr" + +# Revisar la jerarquía de tipos locales. +issubtype(Tigre, Gato) # => false # igual que: Tigre <: Gato +issubtype(Leon, Gato) # => true # igual que: Leon <: Gato +issubtype(Pantera, Gato) # => true + +# Definición de una función que acepta argumentos de tipo Gato. +mascota(gato::Gato) = println("El gato dice $(maullar(gato))") + +mascota(Leon("42")) # El gato dice 42 -mascota(Leon("42")) # => imprime "El gato dice 42" try - mascota(tigger) # => ERROR: no method mascota(Tigre)) + mascota(tigre) # ERROR: `mascota` has no method matching mascota(::Tigre) catch e - println(e) + println(e) # MethodError(mascota,(Tigre(3.5,"anaranjado"),)) end -# En los lenguajes orientados a objetos, expedición única es común. Esto -# significa que el método se recogió basándose en el tipo del primer argumento. -# En Julia, todos los tipos de argumentos contribuyen a seleccionar el mejor -# método. +# En los lenguajes orientados a objetos, el despacho simple es común. Esto +# significa que la implementación del método a llamar se selecciona en base +# al tipo del primer argumento. + +# En Julia, los tipos de todos los argumentos contribuyen a seleccionar método +# más específico. # Vamos a definir una función con más argumentos, para que podamos ver la # diferencia -function pelear(t::Tigre,c::Gato) - println("¡El tigre $(t.colordelpelaje) gana!") -end +pelear(t::Tigre, c::Gato) = println("¡El tigre $(t.color_pelaje) gana!") # => pelear (generic function with 1 method) -pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => ¡El tigre anaranjado gana! +pelear(tigre, Pantera()) # ¡El tigre anaranjado gana! +pelear(tigre, Leon("ROAR")) # ¡El tigre anaranjado gana! -# Vamos a cambiar el comportamiento cuando el Gato es específicamente un Leon -pelear(t::Tigre,l::Leon) = println("El león con melena $(l.color_de_crin) gana") +# Vamos a cambiar el comportamiento cuando el Gato sea específicamente un Leon. +pelear(t::Tigre, l::Leon) = println("El león con melena $(l.color_crin) gana.") # => pelear (generic function with 2 methods) -pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => imprime El león con melena verde gana +pelear(tigre, Pantera()) # ¡El tigre anaranjado gana! +pelear(tigre, Leon("ROAR")) # El león con melena verde gana. -# No necesitamos un tigre para poder luchar -pelear(l::Leon,c::Gato) = println("El gato victorioso dice $(maullar(c))") -# => fight (generic function with 3 methods) +# No necesitamos un tigre para poder luchar. +pelear(l::Leon, c::Gato) = println("El gato victorioso dice $(maullar(c)).") +# => pelear (generic function with 3 methods) + +methods(pelear) +#= + # 3 methods for generic function "pelear": + pelear(t::Tigre,l::Leon) at none:2 + pelear(t::Tigre,c::Gato) at none:1 + pelear(l::Leon,c::Gato) at none:2 +=# -pelear(Leon("balooga!"),Pantera()) # => imprime El gato victorioso dice grrr +pelear(Leon("balooga!"), Pantera()) # El gato victorioso dice grrr. try - pelear(Pantera(),Leon("RAWR")) # => ERROR: no method pelear(Pantera, Leon)) -catch + # ERROR: `pelear` has no method matching pelear(::Pantera, ::Leon) + pelear(Pantera(),Leon("RAWR")) +catch # no hacer nada con la excepción atrapada end -# Un metodo con el gato primero +# Un metodo con el tipo Gato primero. pelear(c::Gato,l::Leon) = println("El gato le gana al León") -# Warning: New definition -# pelear(Gato,Leon) at none:1 -# is ambiguous with: -# pelear(Leon,Gato) at none:1. -# To fix, define -# pelear(Leon,Leon) -# before the new definition. -# pelear (generic function with 4 methods) - -# Esta advertencia se debe a que no está claro que metodo de pelear será llamado -# en: -pelear(Leon("RAR"),Leon("cafe","rar")) # => imprime El gato victorioso dice rar -# El resultado puede ser diferente en otras versiones de Julia +#= + Warning: New definition + pelear(Gato,Leon) at none:1 + is ambiguous with: + pelear(Leon,Gato) at none:1. + To fix, define + pelear(Leon,Leon) + before the new definition. + pelear (generic function with 4 methods) +=# + +# Esta advertencia se debe a que no está claro que método de pelear +# será llamado en: +pelear(Leon("RAR"),Leon("cafe","rar")) # El gato victorioso dice rar. +# El resultado puede ser diferente en otras versiones de Julia pelear(l::Leon,l2::Leon) = println("Los leones llegan a un empate") -pelear(Leon("GR"),Leon("cafe","rar")) # => imprime Los leones llegan a un empate - - -# Un vistazo al nivel bajo -# Se puede echar un vistazo a la LLVM y el código ensamblador generado. - -area_cuadrada(l) = l * l # area_cuadrada (generic function with 1 method) - -area_cuadrada(5) # => 25 - -# ¿Qué sucede cuando damos area_cuadrada diferentes argumentos? -code_native(area_cuadrada, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Prologue - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX - -code_native(area_cuadrada, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) - # pop RBP - # ret - -code_native(area_cuadrada, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) - # pop RBP - # ret - # - -# Ten en cuenta que Julia usará instrucciones de "floating point" si alguno de -# los argumentos son "floats" -# Vamos a calcular el área de un círculo -area_circulo(r) = pi * r * r # circle_area (generic function with 1 method) -area_circulo(5) # 78.53981633974483 + +pelear(Leon("GR"),Leon("cafe","rar")) # Los leones llegan a un empate + + +################################ +# 7. Un vistazo de bajo nivel. # +################################ + +# Se puede echar un vistazo al código IR de LLVM y al código +# ensamblador generado. +area_cuadrado(l) = l * l # => area_cuadrado (generic function with 1 method) + +area_cuadrado(5) # => 25 + +# ¿Qué sucede cuando damos area_cuadrada diferentes tipos de argumentos? +code_native(area_cuadrado, (Int32,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 # prólogo + push RBP + mov RBP, RSP + Source line: 1 + imul RDI, RDI # elevar l al cuadrado + mov RAX, RDI # almacenar el resultado en RAX + pop RBP # restaurar el puntero base anterior + ret # el resultado estará en RAX +=# + +code_native(area_cuadrado, (Float32,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + mulss XMM0, XMM0 # multiplicación escalar de presición simple (AVX) + pop RBP + ret +=# + +code_native(area_cuadrado, (Float64,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + mulsd XMM0, XMM0 # multiplicación escalar de presición doble (AVX) + pop RBP + ret +=# + +# Ten en cuenta que Julia usará instrucciones de punto flotante si el tipo de +# alguno de los argumentos es flotante. + +# Vamos a calcular el área de un círculo. +area_circulo(r) = π * r * r # area_circulo (generic function with 1 method) +area_circulo(5) # 78.53981633974483 code_native(area_circulo, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + cvtsi2sd XMM1, EDI # cargar entero r de la memoria + movabs RAX, 4477117456 # cargar constante matemática π + movsd XMM0, QWORD PTR [RAX] + mulsd XMM0, XMM1 # π * r + mulsd XMM0, XMM1 # (π * r) * r + pop RBP + ret +=# code_native(area_circulo, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + movabs RAX, 4477120336 + movsd XMM1, QWORD PTR [RAX] + Source line: 1 + mulsd XMM1, XMM0 + mulsd XMM1, XMM0 + movaps XMM0, XMM1 + pop RBP + ret +=# ``` -## ¿Listo para más? +![Julia-tan](http://www.mechajyo.org/wp/wp-content/uploads/2014/10/3a2c3b7de5dd39aa7f056a707cd4eb59.png) -Puedes obtener muchos más detalles en [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +## ¿Listo para más? -El mejor lugar para obtener ayuda con Julia es el (muy amable) [lista de correos](https://groups.google.com/forum/#!forum/julia-users). +Para más detalles, lee el [manual de Julia](http://docs.julialang.org/en/release-0.3). +El mejor lugar para obtener ayuda con Julia, es en su amigable [lista de correos](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From be32914cc5fc23f733a90dd117bfe96f66fafb58 Mon Sep 17 00:00:00 2001 From: billpcs Date: Sun, 16 Aug 2015 23:26:23 +0300 Subject: fix some sentences left in english --- el-gr/racket-gr.html.markdown | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 4c76b174..4c4576bb 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -74,8 +74,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ (+ 1+2i 2-3i) ; => 3-1i ;;; Λογικές μεταβλητές -#t ; για το true -#f ; για το false +#t ; για το true (αληθής) +#f ; για το false (ψευδής) (not #t) ; => #f (and 0 #f (error "doesn't get here")) ; => #f (or #f 0 (error "doesn't get here")) ; => 0 @@ -88,9 +88,9 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής -"Foo\tbar\41\x21\u0021\a\r\n" ; συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, - ; σε Unicode -"λx:(μα.α→α).xx" ; μπορούν να υπάρχουν και Unicode χαρακτήρες +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, + ; σε Unicode +"λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες ;; Μπορούμε να εννώσουμε αλφαριθμητικά! (string-append "Hello " "world!") ; => "Hello world!" @@ -109,14 +109,16 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 2. Μεταβλητές ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; You can create a variable using define -;; a variable name can use any character except: ()[]{}",'`;#|\ +;; Μπορούμε να δημιουργήσουμε μεταβλητές +;; χρησιμοποιώντας το define. +;; Ένα όνομα μεταβλητής μπορεί να χρησιμοποιεί οποιονδήποτε +;; χαρακτήρα, εκτός από τους: ()[]{}",'`;#|\ (define some-var 5) some-var ; => 5 -;; You can also use unicode characters +;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. (define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? - ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. + ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. (⊆ (set 3 2) (set 1 2 3)) ; => #t ;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ @@ -560,7 +562,7 @@ vec ; => #(1 2 3 4) ;; Οι ενότητες μας επιτρέπουν να οργανώνουμε τον κώδικα σε πολλαπλά ;; αρχεία και επαναχρησιμοποιούμενες βιβλιοθήκες ;; Εδώ χρησιμοποιούμε υπο-ενότητες, εμφωλευμένες μέσα σε μια -;; άλλη ενότητα που δημιουργεί αυτό το κείμενο(ξεκινώντας από +;; άλλη ενότητα που δημιουργεί αυτό το κείμενο (ξεκινώντας από ;; την γραμμή '#lang' ) (module cake racket/base ; ορίζουμε μια ενότητα 'cake' βασισμένο στο ; racket/base @@ -614,8 +616,7 @@ vec ; => #(1 2 3 4) (send charlie get-size) ; => 16 ;; Το `fish%' είναι μία τιμή "πρώτης κλάσης" -;; `fish%' is a plain "first class" value, με το οποίο μπορούμε να -;; κάνουμε προσμείξεις +;; με το οποίο μπορούμε να κάνουμε προσμείξεις (define (add-color c%) (class c% (init color) @@ -663,17 +664,17 @@ vec ; => #(1 2 3 4) ;; (set! tmp other) ;; (set! other tmp_1)) -;; But they are still code transformations, for example: +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ: (define-syntax-rule (bad-while condition body ...) (when condition body ... (bad-while condition body ...))) -;; αυτή η μακροεντολή είναι χαλασένη: δημιουγεί ατέρμονα βρόχο -;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστης +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο +;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής ;; θα μπεί στον ατέρμονα βρόχο. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 10. Συμβόλαια +;; 10. Συμβόλαια (Contracts) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται -- cgit v1.2.3 From 938720074b8b18a9ada93fb8a040b9ca1a813747 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 17 Aug 2015 14:19:41 -0700 Subject: Update to Chapel A reader/writer sync example was missing a "Reader: " notem --- chapel.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index c8489371..8a88a652 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -960,7 +960,7 @@ proc main(){ begin { // Reader task writeln( "Reader: waiting to read." ); var read_sync = someSyncVar$; - writeln( "value is ", read_sync ); + writeln( "Reader: value is ", read_sync ); } begin { // Writer task @@ -1100,4 +1100,4 @@ Notable arguments: * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. * `--set =`: set config param `` to `` at compile-time. * `--main-module `: use the main() procedure found in the module `` as the executable's main. - * `--module-dir `: includes `` in the module search path. \ No newline at end of file + * `--module-dir `: includes `` in the module search path. -- cgit v1.2.3 From 036577916e76fe4df512da1b6c9253e1f51a5175 Mon Sep 17 00:00:00 2001 From: ozgur sahin Date: Sat, 22 Aug 2015 18:31:39 +0300 Subject: [Swift/tr] Turkish For Swift --- tr-tr/swift-tr.html.markdown | 590 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 590 insertions(+) create mode 100644 tr-tr/swift-tr.html.markdown diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown new file mode 100644 index 00000000..41835e13 --- /dev/null +++ b/tr-tr/swift-tr.html.markdown @@ -0,0 +1,590 @@ +--- +language: swift +contributors: + - ["Özgür Şahin", "https://github.com/ozgurshn/"] +filename: learnswift.swift +--- + +Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi. + +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + +Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı. + +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift. + +Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var. + + + +```swift +// modülü import etme +import UIKit + +// +// MARK: Temeller +// + + +//XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot + listesinde gruplama yapmanıza olanak sağlıyor +// MARK: Bölüm işareti +// TODO: Daha sonra yapılacak +// FIXME: Bu kodu düzelt + + +//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print + otomatik olarak yeni satır ekliyor. +print("Merhaba dünya") // println print olarak kullanılıyor. +print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar. + +// variables (var) değer atandıktan sonra değiştirilebilir. +// constants (let) değer atndıktan sonra değiştirilemez. + +var degiskenim = 42 +let øπΩ = "deger" // unicode degişken adları +let π = 3.1415926 +let convenience = "keyword" // bağlamsal değişken adı +let isim = "ahmet"; let soyad = "un" // farklı ifadeler noktalı virgül +kullanılarak ayrılabilir. +let `class` = "keyword" // rezerve edilmiş keywordler tek tırnak içerisine +alınarak değişken adı olarak kullanılabilir +let doubleOlduguBelli: Double = 70 +let intDegisken = 0007 // 7 +let largeIntDegisken = 77_000 // 77000 +let etiket = "birseyler " + String(degiskenim) // Cast etme +let piYazi = "Pi = \(π), Pi 2 = \(π * 2)" // String içerisine değiken yazdırma + + +// Builde özel değişkenler +// -D build ayarını kullanır. +#if false + print("yazılmadı") + let buildDegiskeni= 3 +#else + let buildDegiskeni = 7 +#endif +print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7 + +/* + Optionals Swift dilinde bazı değerleri veya yokluğu (None) bir değişkende + tutmanıza olanak sağlar. + + Swift'te her bir degişkeninin bir değeri olması gerektiğinden, nil değeri + bile Optional değer olarak saklanır. + + Optional bir enum'dır. +*/ +var baziOptionalString: String? = "optional" // nil olabilir. +// yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay +okunabilir) +var someOptionalString2: Optional = "optional" + + +if baziOptionalString != nil { + // ben nil değilim + if baziOptionalString!.hasPrefix("opt") { + print("ön eki var") + } + + let bos = baziOptionalString?.isEmpty +} +baziOptionalString = nil + +// belirgin olarak acilan(unwrap) opsiyonel (optional) değer +var acilanString: String! = "Değer bekleniliyor" +//yukarıdakiyle aynı ama ! bir postfix operatördür (kolay okunabilir) +var acilanString2: ImplicitlyUnwrappedOptional = "Değer bekleniliyor." + +if let baziOpsiyonelSabitString = baziOptionalString { + // eğer bir değeri varsa, nil değilse + if ! baziOpsiyonelSabitString("tamam") { + // ön eke sahip değil + } +} + +// Swift değişkenlerde herhangi bir tip saklanabilir. +// AnyObject == id +// Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle + çalışabilir (Class, Int, struct, etc) +var herhangiBirObject: AnyObject = 7 +herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün" + +/* + Yorumlar buraya + + /* + İç içe yorum yazılması da mümkün + */ +*/ + +// +// MARK: Koleksiyonlar +// + +/* + Array ve Dictionary tipleri aslında structdırlar. Bu yüzden `let` ve `var` + ayrıca bu tipleri tanımlarken değişebilir(var) veya değişemez(let) + olduğunu belirtir. + +*/ + +// Diziler +var liste = ["balik", "su", "limon"] +liste[1] = "şişe su" +let bosDizi = [String]() // let == değiştirilemez +let bosDizi2 = Array() // yukarıdakiyle aynı +var bosDegistirilebilirDizi = [String]() // var == değişebilir + + +// Dictionary +var meslekler = [ + "Kamil": "Kaptan", + "Ayse": "Analist" +] +meslekler["Cansu"] = "Halkla İlişkiler" +let bosDictionary = [String: Float]() // let == değiştirilemez +let bosDictionary2 = Dictionary() // yukarıdakiyle aynı +var bosDegistirilebirDictionary = [String: Float]() // var == değiştirilebilir + + +// +// MARK: Kontroller +// + +// for döngüsü (dizi) +let dizi = [1, 1, 2, 3, 5] +for deger in dizi { + if deger == 1 { + print("Bir!") + } else { + print("Bir degil!") + } +} + +// for döngüsü (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// for döngüsü (aralık) +for i in -1...liste.count { + print(i) +} +liste[1...2] = ["et", "yogurt"] +// ..< kullanarak son elemanı çıkartabilirsiniz + +// while döngüsü +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while döngüsü +do { + print("merhaba") +} while 1 == 2 + +// Switch +// Çok güçlü, `if` ifadesenin daha kolay okunabilir hali olarak düşünün +// String, object örnekleri, ve primitif tipleri (Int, Double, vs) destekler. +let sebze = "kırmızı biber" +switch sebze { +case "sogan": + let sebzeYorumu = "Biraz da domates ekle" +case "domates", "salata": + let sebzeYorumu = "İyi bir sandviç olur" +case let lokalScopeDegeri where lokalScopeDegeri.hasSuffix("biber"): + let sebzeYorumu = "Acı bir \(lokalScopeDegeri)?" +default: // zorunludur (tüm olasılıkları yakalamak icin) + let sebzeYorumu = "Corbadaki herseyin tadı güzel" +} + + +// +// MARK: Fonksiyonlar +// + +// Fonksiyonlar first-class tiplerdir, yani başka fonksiyon içine konabilir +// ve parametre olarak geçirilebilirler. + +// Swift dökümanlarıylaa birlikte Fonksiyonlar (format as reStructedText) + +/** + selamlama işlemi + + :param: isim e isim + :param: gun e A gun + :returns: isim ve gunu iceren bir String +*/ +func selam(isim: String, gun: String) -> String { + return "Merhaba \(isim), bugün \(gun)." +} +selam("Can", "Salı") + +// fonksiyon parametre davranışı hariç yukarıdakine benzer +func selam2(#gerekliIsim: String, disParametreIsmi lokalParamtreIsmi: String) -> String { + return "Merhaba \(gerekliIsim), bugün \(lokalParamtreIsmi)" +} +selam2(gerekliIsim:"Can", disParametreIsmi: "Salı") + +// Bir tuple ile birden fazla deger dönen fonksiyon +func fiyatlariGetir() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let fiyatTuple = fiyatlariGetir() +let fiyat = fiyatTuple.2 // 3.79 +// _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden +gelir +let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69 +print(fiyat1 == fiyatTuple.1) // true +print("Benzin fiyatı: \(fiyat)") + +// Çeşitli Argümanlar +func ayarla(sayilar: Int...) { + // its an array + let sayi = sayilar[0] + let argumanSAyisi = sayilar.count +} + +// fonksiyonu parametre olarak geçirme veya döndürme +func arttirmaIslemi() -> (Int -> Int) { + func birEkle(sayi: Int) -> Int { + return 1 + sayi + } + return birEkle +} +var arttir = arttirmaIslemi() +arttir(7) + +// referans geçirme +func yerDegistir(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +yerDegistir(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closurelar +// +var sayilar = [1, 2, 6] + +// Fonksiyonlar özelleştirilmiş closurelardır. ({}) + +// Closure örneği. +// `->` parametrelerle dönüş tipini birbirinden ayırır +// `in` closure başlığını closure bodysinden ayırır. +sayilar.map({ + (sayi: Int) -> Int in + let sonuc = 3 * sayi + return sonuc +}) + +// eger tip biliniyorsa, yukarıdaki gibi, şöyle yapabiliriz +sayilar = sayilar.map({ sayi in 3 * sayi }) +// Hatta bunu +//sayilar = sayilar.map({ $0 * 3 }) + +print(sayilar) // [3, 6, 18] + +// Trailing closure +sayilar = sorted(sayilar) { $0 > $1 } + +print(sayilar) // [18, 6, 3] + +// Super kısa hali ise, < operatörü tipleri çıkartabildiği için + +sayilar = sorted(sayilar, < ) + +print(sayilar) // [3, 6, 18] + +// +// MARK: Yapılar +// + +// Structurelar ve sınıflar birçok aynı özelliğe sahiptir. +struct IsimTablosu { + let isimler = [String]() + + // Özelleştirilmiş dizi erişimi + subscript(index: Int) -> String { + return isimler[index] + } +} + +// Structurelar otomatik oluşturulmuş kurucu metoda sahiptir. +let isimTablosu = IsimTablosu(isimler: ["Ben", "Onlar"]) +let isim = isimTablosu[1] +print("İsim \(name)") // İsim Onlar + +// +// MARK: Sınıflar +// + +// Sınıflar, structurelar ve üyeleri 3 seviye erişime sahiptir. +// Bunlar: internal (default), public, private + +public class Sekil { + public func alaniGetir() -> Int { + return 0; + } +} + +// Sınıfın tüm değişkenleri ve metotları publictir. +// Eğer sadece veriyi yapılandırılmış bir objede +// saklamak istiyorsanız, `struct` kullanmalısınız. + +internal class Rect: Sekil { + var yanUzunluk: Int = 1 + + // Özelleştirilmiş getter ve setter propertyleri + private var cevre: Int { + get { + return 4 * yanUzunluk + } + set { + // `newValue ` setterlarda yeni değere erişimi sağlar + yanUzunluk = newValue / 4 + } + } + + // Bir değişkene geç atama(lazy load) yapmak + // altSekil getter cağrılana dek nil (oluşturulmamış) olarak kalır + lazy var altSekil = Rect(yanUzunluk: 4) + + // Eğer özelleştirilmiş getter ve setter a ihtiyacınız yoksa, + // ama bir değişkene get veya set yapıldıktan sonra bir işlem yapmak + // istiyorsanız, `willSet` ve `didSet` metotlarını kullanabilirsiniz + var identifier: String = "defaultID" { + // `willSet` argümanı yeni değer için değişkenin adı olacaktır. + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(yanUzunluk: Int) { + self. yanUzunluk = yanUzunluk + // super.init i her zaman özelleştirilmiş değerleri oluşturduktan sonra + çağırın + super.init() + } + + func kisalt() { + if yanUzunluk > 0 { + --yanUzunluk + } + } + + override func alaniGetir() -> Int { + return yanUzunluk * yanUzunluk + } +} + +// Basit `Kare` sınıfI `Rect` sınıfını extend ediyor. +class Kare: Rect { + convenience init() { + self.init(yanUzunluk: 5) + } +} + +var benimKarem = Kare() +print(m benimKarem.alaniGetir()) // 25 +benimKarem.kisalt() +print(benimKarem.yanUzunluk) // 4 + +// sınıf örneğini cast etme +let birSekil = benimKarem as Sekil + +// örnekleri karşılaştır, objeleri karşılaştıran == (equal to) ile aynı değil +if benimKarem === benimKarem { + print("Evet, bu benimKarem") +} + +// Opsiyonel init +class Daire: Sekil { + var yaricap: Int + override func alaniGetir() -> Int { + return 3 * yaricap * yaricap + } + + // Eğer init opsiyonelse (nil dönebilir) `init` den sonra soru işareti + // son eki ekle. + init?(yaricap: Int) { + self.yaricap = yaricap + super.init() + + if yaricap <= 0 { + return nil + } + } +} + +var benimDairem = Daire(radius: 1) +print(benimDairem?.alaniGetir()) // Optional(3) +print(benimDairem!. alaniGetir()) // 3 +var benimBosDairem = Daire(yaricap: -1) +print(benimBosDairem?. alaniGetir()) // "nil" +if let daire = benimBosDairem { + // benimBosDairem nil olduğu için çalışmayacak + print("circle is not nil") +} + + +// +// MARK: Enumlar +// + +// Enumlar opsiyonel olarak özel bir tip veya kendi tiplerinde olabilirler. +// Sınıflar gibi metotlar içerebilirler. + +enum Kart { + case Kupa, Maca, Sinek, Karo + func getIcon() -> String { + switch self { + case .Maca: return "♤" + case .Kupa: return "♡" + case .Karo: return "♢" + case .Sinek: return "♧" + } + } +} + +// Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz. +var kartTipi: Kart = .Kupa + +// Integer olmayan enumlar direk değer (rawValue) atama gerektirir. +enum KitapAdi: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(KitapAdi.John.rawValue)") + +// Değerlerle ilişkilendirilmiş Enum +enum Mobilya { + // Int ile ilişkilendirilmiş + case Masa(yukseklik: Int) + // String ve Int ile ilişkilendirilmiş + case Sandalye(String, Int) + + func aciklama() -> String { + switch self { + case .Masa(let yukseklik): + return "Masa boyu \(yukseklik) cm" + case .Sandalye(let marka, let yukseklik): + return "\(brand) marka sandalyenin boyu \(yukseklik) cm" + } + } +} + +var masa: Mobilya = .Masa(yukseklik: 80) +print(masa.aciklama()) // "Masa boyu 80 cm" +var sandalye = Mobilya.Sandalye("Foo", 40) +print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm" + + +// +// MARK: Protokoller +// + +// `protocol` onu kullanan tiplerin bazı özel değişkenleri, metotları, +// tip metotlarını,opertörleri ve alt indisleri (subscripts) içermesini +// zorunlu hale getirebilir. + +protocol SekilUretici { + var aktif: Bool { get set } + func sekilOlustur() -> Sekil +} + +// @objc ile tanımlanan protokoller, uygunluğu kontrol edebilmenizi sağlayacak +// şekilde opsiyonel fonksiyonlara izin verir +@objc protocol SekliDondur { + optional func sekillendirilmis() + optional func sekillendirilebilir() -> Bool +} + +class BenimSeklim: Rect { + var delegate: SekliDondur? + + func buyut() { + yanUzlunluk += 2 + + // Bir çalışma zamanı hatası("optional chaining") fırlatmak yerine nil + //değeri görmezden gelerek nil dönmek için opsiyonel değişken, metot veya + // altindisten sonra soru işareti koyabilirsiniz. + if let izinVeriyormu = self.delegate?.sekillendirilebilir?() { + // önce delegate i sonra metodu test edin + self.delegate?.sekillendirilmis?() + } + } +} + + +// +// MARK: Diğerleri +// + +// `extension`lar: Var olan tiplere ekstra özellikler ekleyin + +// Kare artık `Printable` protokolüne uyuyor. +extension Kare: Printable { + var description: String { + return "Alan: \(alaniGetir()) - ID: \(self.identifier)" + } +} + +print("Kare: \(benimKarem)") + +// Dahili tipleri de yeni özellikler ekleyebilirsiniz +extension Int { + var customProperty: String { + return "Bu sayı \(self)" + } + + func carp(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "Bu sayı 7" +print(14.carp(3)) // 42 + +// Genericler: Java ve C#'a benzer şekilde. `where` anahtar kelimesini +// kullanarak genericlerin özelliklerini belirleyin + +func indexiBul(dizi: [T], bulunacakDeger: T) -> Int? { + for (index, deger) in enumerate(dizi) { + if deger == bulunacakDeger { + return index + } + } + return nil +} +let bulunanIndex = indexiBul([1, 2, 3, 4], 3) +print(bulunanIndex == 2) // true + +// Operatorler: +// Özel operatorler şu karakterlerle başlayabilir: +// / = - + * % < > ! & | ^ . ~ +// veya +// Unicode math, symbol, arrow, dingbat, ve line/box karakterleri. +prefix operator !!! {} + +// Yan uzunluğu 3 katına çıkartan prefix operatörü +prefix func !!! (inout sekil: Kare) -> Kare { + sekil.YanUzunluk *= 3 + return sekil +} + +// güncel deger +print(benimKarem.YanUzunluk) // 4 + +// yan uzunluğu !!! operatorü kullanarak 3 katına çıkar +!!!benimKarem +print(benimKarem.YanUzunluk) // 12 +``` -- cgit v1.2.3 From bd3c4e4c1a947dde9c4c42257574a9ecd298b250 Mon Sep 17 00:00:00 2001 From: Ruben Date: Sun, 23 Aug 2015 14:54:07 +0200 Subject: Update yaml-de.html.markdown --- de-de/yaml-de.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index 88318014..19ea9e87 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -1,10 +1,11 @@ --- language: yaml -filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - - ["Ruben M.", https://github.com/switchhax] + - ["Ruben M.", "https://github.com/switchhax"] +filename: learnyaml-de.yaml +lang: de-de --- YAML ist eine Sprache zur Datenserialisierung, die sofort von Menschenhand geschrieben und gelesen werden kann. -- cgit v1.2.3 From b990f84123a755b8aa36db3667a59b7d774daad2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jostein=20Kj=C3=B8nigsen?= Date: Tue, 25 Aug 2015 12:29:44 +0200 Subject: Fix broken line-change in TCL docs. --- tcl.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) mode change 100755 => 100644 tcl.html.markdown diff --git a/tcl.html.markdown b/tcl.html.markdown old mode 100755 new mode 100644 index 198f675e..79b5e87d --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -121,7 +121,8 @@ puts lots\nof\n\n\n\n\n\nnewlines # A word enclosed in braces is not subject to any special interpretation or -# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace +# substitutions, except that a backslash before a brace is not counted when +# looking for the closing brace set somevar { This is a literal $ sign, and this \} escaped brace remains uninterpreted -- cgit v1.2.3 From 9650cdc12468e91cb7a64aad6017671b7a40c1ef Mon Sep 17 00:00:00 2001 From: "Q. Zero Lee" Date: Tue, 25 Aug 2015 22:41:22 +0800 Subject: Added a dollar --- tcl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 79b5e87d..c1cd42ca 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -257,7 +257,7 @@ proc greet greeting\ name return\ \"Hello,\ \$name! proc fold {cmd args} { set res 0 foreach arg $args { - set res [cmd $res $arg] + set res [$cmd $res $arg] } } fold ::tcl::mathop::* 5 3 3 ;# -> 45 -- cgit v1.2.3 From 45c70baa69088ca4aa9189556641a773b2b9c305 Mon Sep 17 00:00:00 2001 From: Aleks-Daniel Jakimenko Date: Tue, 25 Aug 2015 22:31:25 +0300 Subject: In perl6, 0 is not falsey anymore --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index de7d2f25..af545793 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -213,7 +213,7 @@ say $x; #=> 52 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), 0, "", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: (), "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { -- cgit v1.2.3 From c00ac0de6612feb54bf0b6d1040c953e2de5df81 Mon Sep 17 00:00:00 2001 From: Arthur Vieira Date: Wed, 26 Aug 2015 03:15:36 -0300 Subject: Add #push to Array besides shovel operator #push is commonly used imho and it is also used in other languages (e.g. Javascript). --- ruby.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 66a0774d..7bd28d86 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -173,6 +173,8 @@ array[1..3] #=> [2, 3, 4] # Add to an array like this array << 6 #=> [1, 2, 3, 4, 5, 6] +# Or like this +array.push(6) #=> [1, 2, 3, 4, 5, 6] # Check if an item exists in an array array.include?(1) #=> true -- cgit v1.2.3 From 7d2339328d5bb2b0bd642809cd68a604d7d2a34d Mon Sep 17 00:00:00 2001 From: Alexander Farley Date: Wed, 26 Aug 2015 16:47:21 -0400 Subject: Updating line 167 to fix name resolution error at line 73. Also, elaborated on name resolution with set vs. variable. --- tcl.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index c1cd42ca..9ca32f1e 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -164,7 +164,7 @@ set greeting "Hello, $person(name)" # A namespace holds commands and variables namespace eval people { namespace eval person1 { - set name Neo + variable name Neo } } @@ -190,7 +190,10 @@ set greeting "Hello $people::person1::name" namespace delete :: -# Because of name resolution behaviour, it's safer to use the "variable" command to declare or to assign a value to a namespace. +# Because of name resolution behaviour, it's safer to use the "variable" command to +# declare or to assign a value to a namespace. If a variable called "name" already +# exists in the global namespace, using "set" here will assign a value to the global variable +# instead of creating a new variable in the local namespace. namespace eval people { namespace eval person1 { variable name Neo -- cgit v1.2.3 From 97b97408eab97fbe322df4266cda9ab2ed21fceb Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 28 Aug 2015 11:48:38 -0600 Subject: Fix C++ namespace explanation --- c++.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index ff2a98fd..883d3482 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -158,11 +158,12 @@ void foo() int main() { - // Assume everything is from the namespace "Second" - // unless otherwise specified. + // Includes all symbols from `namesapce Second` into the current scope. Note + // that simply `foo()` no longer works, since it is now ambiguous whether + // we're calling the `foo` in `namespace Second` or the top level. using namespace Second; - foo(); // prints "This is Second::foo" + Second::foo(); // prints "This is Second::foo" First::Nested::foo(); // prints "This is First::Nested::foo" ::foo(); // prints "This is global foo" } -- cgit v1.2.3 From 3d0687027a450d1778e6f7336f96962fa385ec53 Mon Sep 17 00:00:00 2001 From: Joe Savage Date: Sat, 29 Aug 2015 11:44:41 +0100 Subject: add missing semicolons in c.html.markdown --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index d3f20eda..e2e15620 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -183,8 +183,8 @@ int main() { i1 / i2; // => 0 (0.5, but truncated towards 0) // You need to cast at least one integer to float to get a floating-point result - (float)i1 / i2 // => 0.5f - i1 / (double)i2 // => 0.5 // Same with double + (float)i1 / i2; // => 0.5f + i1 / (double)i2; // => 0.5 // Same with double f1 / f2; // => 0.5, plus or minus epsilon // Floating-point numbers and calculations are not exact -- cgit v1.2.3 From 85d80b9e5d8a124d00322f5228e5be64cd97c8ea Mon Sep 17 00:00:00 2001 From: Joe Savage Date: Sat, 29 Aug 2015 11:47:09 +0100 Subject: fix resource capitalisation and add resource to c.html.markdown --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index e2e15620..09806d93 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -634,7 +634,7 @@ Best to find yourself a copy of [K&R, aka "The C Programming Language"](https:// It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. -Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/). +Other good resources include [Learn C The Hard Way](http://c.learncodethehardway.org/book/) and [SourceCrunch](https://www.sourcecrunch.com/courses/foundations-of-c). If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com). -- cgit v1.2.3 From 7cb94b3b85608a73a0200469a8fa897e68f7c991 Mon Sep 17 00:00:00 2001 From: Joe Savage Date: Sat, 29 Aug 2015 11:58:03 +0100 Subject: main() -> main(void) & fix spacing in c.html.markdown --- c.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 09806d93..2b087688 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -18,9 +18,9 @@ memory management and C will take you as far as you need to go. ```c // Single-line comments start with // - only available in C99 and later. - /* +/* Multi-line comments look like this. They work in C89 as well. - */ +*/ /* Multi-line comments don't nest /* Be careful */ // comment ends on this line... @@ -55,7 +55,7 @@ int add_two_ints(int x1, int x2); // function prototype // Your program's entry point is a function called // main with an integer return type. -int main() { +int main(void) { // print output using printf, for "print formatted" // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 @@ -157,12 +157,12 @@ int main() { int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char) - //Multi-dimensional arrays: + // Multi-dimensional arrays: int multi_array[2][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 0} }; - //access elements: + // access elements: int array_int = multi_array[0][2]; // => 3 /////////////////////////////////////// @@ -219,13 +219,13 @@ int main() { 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 - //Conditional expression ( ? : ) + // Conditional expression ( ? : ) int e = 5; int f = 10; int z; z = (e > f) ? e : f; // => 10 "if e > f return e, else return f." - //Increment and decrement operators: + // Increment and decrement operators: char *s = "iLoveC"; int j = 0; s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. @@ -371,7 +371,7 @@ int main() { x_array[xx] = 20 - xx; } // Initialize x_array to 20, 19, 18,... 2, 1 - // Declare a pointer of type int and initialize it to point to x_array + // Declare a pointer of type int and initialize it to point to x_array int* x_ptr = x_array; // x_ptr now points to the first element in the array (the integer 20). // This works because arrays often decay into pointers to their first element. @@ -404,8 +404,8 @@ int main() { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - // Dereferencing memory that you haven't allocated gives - // "unpredictable results" - the program is said to invoke "undefined behavior" + // Dereferencing memory that you haven't allocated gives + // "unpredictable results" - the program is said to invoke "undefined behavior" printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. // When you're done with a malloc'd block of memory, you need to free it, @@ -471,13 +471,13 @@ str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ -//if referring to external variables outside function, must use extern keyword. +// if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { extern int i; //i here is now using external variable i } -//make external variables private to source file with static: +// make external variables private to source file with static: static int j = 0; //other files using testFunc2() cannot access variable j void testFunc2() { extern int j; -- cgit v1.2.3 From e0d0e9189bb6e0af14a21e0c315922bc16fc2e14 Mon Sep 17 00:00:00 2001 From: Joe Savage Date: Sun, 30 Aug 2015 20:51:23 +0100 Subject: revert additional resource suggestion in c.html.markdown --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 2b087688..8e631de4 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -634,7 +634,7 @@ Best to find yourself a copy of [K&R, aka "The C Programming Language"](https:// It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. -Other good resources include [Learn C The Hard Way](http://c.learncodethehardway.org/book/) and [SourceCrunch](https://www.sourcecrunch.com/courses/foundations-of-c). +Another good resource is [Learn C The Hard Way](http://c.learncodethehardway.org/book/). If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com). -- cgit v1.2.3 From 1d1def16a5d7925bb8f7fba7dc49182e33359e85 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 30 Aug 2015 14:20:18 -0600 Subject: A little more about C++ references --- c++.html.markdown | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index ff2a98fd..efce0053 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -4,6 +4,7 @@ filename: learncpp.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] lang: en --- @@ -248,6 +249,56 @@ const string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. barRef += ". Hi!"; // Error, const references cannot be modified. +// Sidetrack: Before we talk more about references, we must introduce a concept +// called a temporary object. Suppose we have the following code: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// What happens in the second line is actually: +// - a string object is returned from `tempObjectFun` +// - a new string is constructed with the returned object as arugment to the +// constructor +// - the returned object is destroyed +// The returned object is called a temporary object. Temporary objects are +// created whenever a function returns an object, and they are destroyed at the +// end of the evaluation of the enclosing expression. So in this code: +foo(bar(tempObjectFun())) + +// assuming `foo` and `bar` exist, the object returned from `tempObjectFun` is +// passed to `bar`, and it is destroyed before `foo` is called. + +// Now back to references. The exception to the "at the end of the enclosing +// expression" rule is if a temporary object is bound to a const reference, in +// which case its life gets extended to the current scope: + +void constReferenceTempObjectFun() { + // `constRef` gets the temporary object, and it is valid until the end of this + // function. + const string& constRef = tempObjectFun(); + ... +} + +// Another kind of reference introduced in C++11 is specifically for temporary +// objects. You cannot have a variable of its type, but it takes precedence in +// overload resolution: + +void someFun(string& s) { ... } // Regular reference +void someFun(string&& s) { ... } // Reference to temporary object + +string foo; +someFun(foo); // Calls the version with regular reference +someFun(tempObjectFun()); // Calls the version with temporary reference + +// For example, you will see these two versions of constructors for +// std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// Idea being if we are constructing a new string from a temporary object (which +// is going to be destroyed soon anyway), we can have a more efficient +// constructor that "salvages" parts of that temporary string. You will see this +// concept referred to as the move semantic. + ////////////////////////////////////////// // Classes and object-oriented programming ////////////////////////////////////////// -- cgit v1.2.3 From a230d76307ecbc0f53c4b359cdb90628720f915e Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 30 Aug 2015 14:41:02 -0600 Subject: More about temporary objects --- c++.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index e45c73c3..74bd8913 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -765,6 +765,22 @@ Foo f1 = fooSub; Foo f1; f1 = f2; + +// How to truly clear a container: +class Foo { ... }; +vector v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// Following line sets size of v to 0, but destructors don't get called, +// and resources aren't released! +v.empty(); +v.push_back(Foo()); // New value is copied into the first Foo we inserted in the loop. + +// Truly destroys all values in v. See section about temporary object for +// explanation of why this works. +v.swap(vector()); + ``` Further Reading: -- cgit v1.2.3 From fc9ae44e4887500634bf3a87343d687b4d7d4e3c Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 30 Aug 2015 14:46:46 -0600 Subject: Now that we explained move semantics --- c++.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 74bd8913..fa80e6d5 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -751,7 +751,8 @@ pt2 = nullptr; // Sets pt2 to null. // '=' != '=' != '='! -// Calls Foo::Foo(const Foo&) or some variant copy constructor. +// Calls Foo::Foo(const Foo&) or some variant (see move semantics) copy +// constructor. Foo f2; Foo f1 = f2; -- cgit v1.2.3 From b84858d2df4b738f96241f65072d94da326bf106 Mon Sep 17 00:00:00 2001 From: Luis Alfredo Date: Sun, 30 Aug 2015 19:35:54 -0500 Subject: Actualizar algunos detalles hasta punto 4 --- es-es/javascript-es.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index a1348508..fd01e7b9 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -16,8 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común para front-end que Java. -JavaScript no sólo se limita a los navegadores web: -* Node.js: Un proyecto que provee con un ambiente para el motor V8 de Google Chrome. +JavaScript no sólo se limita a los navegadores web, aunque: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. ¡La retroalimentación es bienvenida! Puedes encontrarme en: [@adambrenecki](https://twitter.com/adambrenecki), o @@ -49,6 +48,7 @@ hazAlgo() // Toda la aritmética básica funciona como uno esperaría. 1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 @@ -102,9 +102,11 @@ false; // Los tipos no importan con el operador ==... "5" == 5; // = true +null == undefined; // = true // ...a menos que uses === "5" === 5; // = false +null === undefined; // false // Los Strings funcionan como arreglos de caracteres // Puedes accesar a cada caracter con la función charAt() @@ -126,7 +128,7 @@ undefined; // usado para indicar que un valor no está presente actualmente // Aunque 0 === "0" sí es false. /////////////////////////////////// -// 2. Variables, Arreglos y Objetos +// 2. Variables, Arrays y Objetos // Las variables se declaran con la palabra var. JavaScript cuenta con tipado dinámico, // así que no se necesitan aplicar tipos. La asignación se logra con el operador =. @@ -220,7 +222,6 @@ for (var i = 0; i < 5; i++){ } // && es un "y" lógico, || es un "o" lógico -var casa = {tamano:"grande",casa:"color"}; if (casa.tamano == "grande" && casa.color == "azul"){ casa.contiene = "oso"; } -- cgit v1.2.3 From dcf0f5de9949da350c9bad4853254fc9b6843bb9 Mon Sep 17 00:00:00 2001 From: Timm Albers Date: Mon, 31 Aug 2015 19:34:31 +0200 Subject: [json/de] translated from [json/en] --- de-de/json-de.html.markdown | 65 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 de-de/json-de.html.markdown diff --git a/de-de/json-de.html.markdown b/de-de/json-de.html.markdown new file mode 100644 index 00000000..3cf4578c --- /dev/null +++ b/de-de/json-de.html.markdown @@ -0,0 +1,65 @@ +--- +language: json +filename: learnjson-de.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Timm Albers", "https://github.com/nunull"] +lang: de-de +--- + +Da JSON ein äußerst einfaches Format für den Austausch von Daten ist, wird dieses +Dokument das vermutlich einfachste "Learn X in Y Minutes" werden. + +In seiner grundlegenden Form hat JSON keine eigentlichen Kommentare. Dennoch +akzeptieren die meisten Parser Kommentare in C-Syntax (`//`, `/* */`). Dennoch +soll für dieses Dokument nur 100% gültiges JSON verwendet werden, weshalbt keine +Kommentare verwendet werden. Glücklicherweise ist das nachfolgende Dokument +selbsterklärend. + +```json +{ + "schlüssel": "wert", + + "alle schlüssel": "müssen durch doppelte Anführungszeichen begrenzt werden", + "zahlen": 0, + "zeichenketten": "Alle Unicode-Zeichen (inklusive \"escaping\") sind erlaubt.", + "boolesche werte": true, + "nullwert": null, + + "große zahlen": 1.2e+100, + + "objekte": { + "kommentar": "Die meisten Datenstrukturen in JSON kommen aus Objekten.", + + "array": [0, 1, 2, "Arrays können Werte jeglichen Datentyps aufnehmen.", 4], + + "weiteres objekt": { + "kommentar": "Objekte können verschachtelt werden." + } + }, + + "quatsch": [ + { + "quellen von kalium": ["Bananen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "Neo"], + [0, 0, 0, 1] + ] + ], + + "alternative formatierung": { + "kommentar": "..." + , "die position": "des Kommas ist nicht relevant - so lange es vor dem Wert steht." + , "weiterer kommentar": "wie schön" + , "übrigens": "Auch die Einrückung ist nicht relevant." + , "jede": "beliebige Anzahl von Leerzeichen / Tabs ist erlaubt.", "wirklich?":true + }, + + "das war kurz": "Und, du bist fertig. Du weißt nun (fast) alles über JSON." +} +``` -- cgit v1.2.3 From 0963dbaba3ff808e13cc33178434633533f3105e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jostein=20Kj=C3=B8nigsen?= Date: Tue, 1 Sep 2015 14:44:46 +0200 Subject: Tcl. Fix mid-page rendering error Github's syntax-highlighting has an error in the Tcl syntax-parser causing the rendering of the page to fail about one third in. This commit bypasses this rendering-error by resetting the syntax highlighting after the error has occurred. --- tcl.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tcl.html.markdown b/tcl.html.markdown index 9ca32f1e..af2911c9 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -149,6 +149,9 @@ set greeting "Hello, [set {first name}]" # To promote the words within a word to individual words of the current # command, use the expansion operator, "{*}". +``` + +```tcl set {*}{name Neo} # is equivalent to -- cgit v1.2.3 From a24e5ef7a115eb32e929a003fdfcdb3704927064 Mon Sep 17 00:00:00 2001 From: Denis Gladkikh Date: Tue, 1 Sep 2015 09:27:40 -0700 Subject: Python: add finally and with statements https://docs.python.org/2/tutorial/errors.html --- python.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 88e0deb1..9493e6a3 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -379,7 +379,13 @@ except (TypeError, NameError): pass # Multiple exceptions can be handled together, if required. else: # Optional clause to the try/except block. Must follow all except blocks print "All good!" # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print "We can clean up resources here" +# Instead of try/finally to cleanup resources you can use with +with open("myfile.txt") as f: + for line in f: + print line #################################################### ## 4. Functions -- cgit v1.2.3 From 3e93c5e5f4a4f968a2371dc0b69047bc78da4640 Mon Sep 17 00:00:00 2001 From: Denis Gladkikh Date: Tue, 1 Sep 2015 10:23:31 -0700 Subject: Update python.html.markdown --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 9493e6a3..16a94c8f 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -382,7 +382,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks finally: # Execute under all circumstances print "We can clean up resources here" -# Instead of try/finally to cleanup resources you can use with +# Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: print line -- cgit v1.2.3 From 1b767166e112aa4cbd9758ac722f2286b534803f Mon Sep 17 00:00:00 2001 From: Denis Gladkikh Date: Tue, 1 Sep 2015 10:25:04 -0700 Subject: Python3: add finally and with statements --- python3.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 9d965fb1..fbed77fe 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -374,6 +374,13 @@ except (TypeError, NameError): pass # Multiple exceptions can be handled together, if required. else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print "We can clean up resources here" + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print line # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -- cgit v1.2.3 From 85f6ba0b57b9d894c694df66449b1e1c555c625b Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 2 Sep 2015 00:46:30 -0600 Subject: A note about RVO --- c++.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index fa80e6d5..26dfe111 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -262,7 +262,10 @@ string retVal = tempObjectFun(); // - the returned object is destroyed // The returned object is called a temporary object. Temporary objects are // created whenever a function returns an object, and they are destroyed at the -// end of the evaluation of the enclosing expression. So in this code: +// end of the evaluation of the enclosing expression (Well, this is what the +// standard says, but compilers are allowed to change this behavior. Look up +// "return value optimization" if you're into this kind of details). So in this +// code: foo(bar(tempObjectFun())) // assuming `foo` and `bar` exist, the object returned from `tempObjectFun` is -- cgit v1.2.3 From 3fa7a3f7d31e929445e134f256e5d535e020d154 Mon Sep 17 00:00:00 2001 From: Jakub Mlokosiewicz Date: Wed, 2 Sep 2015 14:33:01 +0200 Subject: [brainfuck/pl] translated from en --- pl-pl/brainfuck-pl.html.markdown | 93 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 pl-pl/brainfuck-pl.html.markdown diff --git a/pl-pl/brainfuck-pl.html.markdown b/pl-pl/brainfuck-pl.html.markdown new file mode 100644 index 00000000..69d814c4 --- /dev/null +++ b/pl-pl/brainfuck-pl.html.markdown @@ -0,0 +1,93 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jakub Młokosiewicz", "https://github.com/hckr"] +lang: pl-pl +--- + +Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo +minimalistycznym, kompletnym w sensie Turinga, językiem programowania. +Zawiera zaledwie 8 poleceń. + +Możesz przetesotwać brainfucka w swojej przeglądarce, korzystając z narzędzia +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Wszystkie znaki oprócz "><+-.,[]" (wyłączając znaki zapytania) są ignorowane. + +Pamięć w brainfucku jest reprezentowana przez tablicę 30.000 komórek +zainicjalizowanych zerami, ze wskaźnikiem pokazującym na aktualną komórkę. + +Oto osiem poleceń brainfucka: ++ : inkrementuje (zwiększa o jeden) wartość aktualnie wskazywanej komórki +- : dekrementuje (zmniejsza o jeden) wartość aktualnie wskazywanej komórki +> : przesuwa wskaźnik na następną komórkę (w prawo) +< : przesuwa wskaźnik na poprzednią komórkę (w lewo) +. : wyświetla wartość bieżącej komórki (w formie znaku ASCII, np. 65 = 'A') +, : wczytuje (jeden) znak z wejścia do bieżącej komórki + (konkretnie jego numer z tabeli ASCII) +[ : jeśli wartość w bieżącej komórce jest rózna zero, przechodzi do + odpowiadającego ]; w przeciwnym wypdaku przechodzi do następnej instrukcji +] : Jeśli wartość w bieżącej komórce jest rózna od zera, przechodzi do + następnej instrukcji; w przeciwnym wypdaku przechodzi do odpowiadającego [ + +[ i ] oznaczają pętlę while. Oczywiście każda pętla rozpoczęta [ +musi być zakończona ]. + +Zobaczmy kilka prostych programów w brainfucku. + + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ten program wypisuje literę 'A'. Najpierw zwiększa wartość komórki #1 do 6. +Komórka #1 będzie wykorzystana w pętli. Następnie program wchodzi w pętlę ([) +i przechodzi do komórki #2. Pętla wykonuje się sześć razy (komórka #1 jest +dekrementowana sześć razy, nim osiągnie wartość zero, kiedy to program +przechodzi do odpowiadającego ] i wykonuje kolejne instrukcje). + +W tym momencie wskaźnik pokazuje na komórkę #1, mającą wartość 0, podczas gdy +komórka #2 ma wartość 60. Przesuwamy wskaźnik na komórkę #2, inkrementujemy ją +pięć razy, uzyskując wartość 65. Następnie wyświetlamy wartość komórki #2. +65 to 'A' w tabeli ASCII, więc właśnie ten znak jest wypisany na konsolę. + + +, [ > + < - ] > . + +Ten program wczytuje znak z wejścia i umieszcza jego kod ASCII w komórce #1. +Następnie zaczyna się pętla, w której znajdują się następujące instrukcje: +przesunięcie wskaźnika na komórkę #2, inkrementacja wartości komóri #2, +powrót do komórki #1 i dekrementacja wartości komórki #1. Instrukcje pętli +wykonują się aż wartość komórki #1 osiągnie zero, a komórka #2 osiągnie +poprednią wartość komórki #1. Ponieważ na końcu pętli wskaźnik pokazuje na +komórkę #1, po pętli następuje instrukcja przejścia do komórki #2 i wysłanie +jej wartości (w formie znaku ASCII) na wyjście. + +Zauważ, że odstępy służą wyłącznie poprawie czytelności. +Równie dobrze można powyższy program zapisać tak: + +,[>+<-]>. + + +Spróbuj odgadnąć, co robi poniższy program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ten program pobiera z wejścia dwie liczby i je mnoży. + +Po wczytaniu dwóch wejść (do komórek #1 i #2) następuje pętla zewnętrzna, +warunkowana wartością komórki #1. Następnie program przechodzi do komórki #2 +i rozpoczyna pętlę wewnętrzną z warunkiem zakończenia w komórce #2, +inkrementującą komórkę #3. Tu jednak pojawia się problem: w chwili zakończenia +wewnętrznej pętli komórka #2 ma wartość zero. W takim razie wewętrzna pętla +nie wywoła się następny raz. Aby rozwiązać ten problem, inkrementujemy także +wartość komórki #4, a następnie kopiujemy jej wartość do komórki #2. +Ostatecznie wynik działania znajduje się w komórce #3. +``` + +I to właśnie jest brainfuck. Nie taki trudny, co? W ramach rozrywki możesz +napisać własne programy w brainfucku. Możesz też napisać interpreter brainfucka +w innym języku. Implementacja interpretera to dość proste zadanie. Jeśli +jesteś masochistą, spróbuj napisać interpreter brainfucka w... brainfucku. -- cgit v1.2.3 From 11749e1ba0ac173dd609bda6928fa8b8c3421803 Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Sat, 5 Sep 2015 11:10:18 +0800 Subject: Corrected Python3 print() function --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index fbed77fe..bd83c90b 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -375,12 +375,12 @@ except (TypeError, NameError): else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances - print "We can clean up resources here" + print ("We can clean up resources here") # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: - print line + print (line) # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -- cgit v1.2.3 From 1ccebdf972dd000299f48689e3c1b756761fdb64 Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Sat, 5 Sep 2015 21:26:22 +0800 Subject: Update python3.html.markdown --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index bd83c90b..b3acb122 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -375,12 +375,12 @@ except (TypeError, NameError): else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances - print ("We can clean up resources here") + print("We can clean up resources here") # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: - print (line) + print(line) # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -- cgit v1.2.3 From ba9a7303c886499856b130a21298d2d82b9f1626 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Tue, 8 Sep 2015 18:24:00 +0200 Subject: Created cs-cz folder, translated first part of Python3 --- cs-cz/python3.html.markdown | 666 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 666 insertions(+) create mode 100644 cs-cz/python3.html.markdown diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown new file mode 100644 index 00000000..79f064c6 --- /dev/null +++ b/cs-cz/python3.html.markdown @@ -0,0 +1,666 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Tomáš Bedřich", "http://tbedrich.cz"] +filename: learnpython3.py +--- + +Python byl vytvořen Guidem Van Rossum v raných 90 letech. Nyní je jedním z nejpopulárnějších jazyků. +Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. + +Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] (anglicky). + +Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). + +```python + +# Jednořádkový komentář začíná křížkem + +""" Víceřádkové komentáře používají 3x" + a jsou často využívány jako dokumentační komentáře k metodám +""" + +#################################################### +## 1. Primitivní datové typy a operátory +#################################################### + +# Čísla +3 # => 3 + +# Aritmetické operace se chovají běžným způsobem +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Až na dělení, které vrací desetinné číslo +35 / 5 # => 7.0 + +# Při celočíselném dělení je desetinná část oříznuta (pro kladná i záporná čísla) +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # celočíselně dělit lze i desetinným číslem +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Pokud použiteje desetinné číslo, výsledek je jím také +3 * 2.0 # => 6.0 + +# Modulo +7 % 3 # => 1 + +# Mocnění (x na y-tou) +2**4 # => 16 + +# Pro vynucení priority použijte závorky +(1 + 3) * 2 # => 8 + +# Logické hodnoty +True +False + +# Negace se provádí pomocí not +not True # => False +not False # => True + +# Logické operátory +# U operátorů záleží na velikosti písmen +True and False # => False +False or True # => True + +# Používání logických operátorů s čísly +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Rovnost je == +1 == 1 # => True +2 == 1 # => False + +# Nerovnost je != +1 != 1 # => False +2 != 1 # => True + +# Další porovnání +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porovnání se dají řetězit! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + + +# Řetězce používají " nebo ' a mohou obsahovat UTF8 znaky +"Toto je řetězec." +'Toto je také řetězec.' + +# Řetězce se také dají sčítat, ale nepoužívejte to +"Hello " + "world!" # => "Hello world!" +# Dají se spojovat i bez '+' +"Hello " "world!" # => "Hello world!" + +# Řetězec lze považovat za seznam znaků +"Toto je řetězec"[0] # => 'T' + +# .format lze použít ke skládání řetězců +"{} mohou být {}".format("řetězce", "skládány") + +# Formátovací argumenty můžete opakovat +"{0} {1} stříkaček stříkalo přes {0} {1} střech".format("tři sta třicet tři", "stříbrných") +# => "tři sta třicet tři stříbrných stříkaček stříkalo přes tři sta třicet tři stříbrných střech" + +# Pokud nechcete počítat, můžete použít pojmenované argumenty +"{jmeno} si dal {jidlo}".format(jmeno="Franta", jidlo="guláš") # => "Franta si dal guláš" + +# Pokud zároveň potřebujete podporovat Python 2.5 a nižší, můžete použít starší způsob formátování +"%s se dají %s jako v %s" % ("řetězce", "skládat", "jazyce C") + + +# None je objekt (jinde NULL, nil, ...) +None # => None + +# Pokud porovnáváte něco s None, nepoužívejte operátor rovnosti "==", +# použijte raději operátor "is", který testuje identitu. +"něco" is None # => False +None is None # => True + +# None, 0, a prázdný řetězec/seznam/slovník se vyhodnotí jako False +# Vše ostatní se vyhodnotí jako True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print function +print("I'm Python. Nice to meet you!") + +# No need to declare variables before assigning to them. +# Convention is to use lower_case_with_underscores +some_var = 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_unknown_var # Raises a NameError + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# (It's a closed/open range for you mathy types.) +li[1:3] # => [2, 4] +# Omit the beginning +li[2:] # => [4, 3] +# Omit the end +li[:3] # => [1, 2, 4] +# Select every second entry +li[::2] # =>[1, 4] +# Return a reversed copy of the list +li[::-1] # => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# You can add lists +# Note: values for li and for other_li are not modified. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# You can do most of the list operations on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# Tuples are created by default if you leave out the parentheses +d, e, f = 4, 5, 6 +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as an iterable with "keys()". We need to wrap the call in list() +# to turn it into a list. We'll talk about those later. Note - Dictionary key +# ordering is not guaranteed. Your results might not match this exactly. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# Get all values as an iterable with "values()". Once again we need to wrap it +# in list() to get it out of the iterable. Note - Same as above regarding key +# ordering. +list(filled_dict.values()) # => [3, 2, 1] + + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Adding to a dictionary +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 #another way to add to dict + +# Remove keys from a dictionary with del +del filled_dict["one"] # Removes the key "one" from filled dict + + +# Sets store ... well sets +empty_set = set() +# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Can set new variables to a set +filled_set = some_set + +# Add one more item to the set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow and Iterables +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in python! +# prints "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +"range(number)" returns an iterable of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" returns an iterable of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print("All good!") # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print("We can clean up resources here") + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python offers a fundamental abstraction called the Iterable. +# An iterable is an object that can be treated as a sequence. +# The object returned the range function, is an iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface + +# We can loop over it. +for i in our_iterable: + print(i) # Prints one, two, three + +# However we cannot address elements by index. +our_iterable[1] # Raises a TypeError + +# An iterable is an object that knows how to create an iterator. +our_iterator = iter(our_iterable) + +# Our iterator is an object that can remember the state as we traverse through it. +# We get the next object with "next()". +next(our_iterator) # => "one" + +# It maintains state as we iterate. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# After the iterator has returned all of its data, it gives you a StopIterator Exception +next(our_iterator) # Raises StopIteration + +# You can grab all the elements of an iterator by calling list() on it. +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + +# You can define functions that take a variable number of +# positional arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# You can define functions that take a variable number of +# keyword arguments, as well +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand tuples and use ** to expand kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + + +# Function Scope +x = 5 + +def setX(num): + # Local var x not the same as global variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # global var x is now set to 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True + +# TODO - Fix for iterables +# There are built-in higher order functions +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +# List comprehension stores the output as a list which can itself be a nested list +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# We subclass from object to get a class. +class Human(object): + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantiate a class +i = Human(name="Ian") +print(i.say("hi")) # prints out "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # prints out "Joel: hello" + +# Call our class method +i.get_species() # => "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Call the static method +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +print(math.sqrt(16)) # => 4 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# A generator creates values on the fly. +# Instead of generating and returning all values at once it creates one in each +# iteration. This means values bigger than 15 wont be processed in +# double_numbers. +# Note range is a generator too. Creating a list 1-900000000 would take lot of +# time to be made +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +range_ = range(1, 900000000) +# will double all numbers until a result >=30 found +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorators +# in this example beg wraps say +# Beg will call say. If say_please is True then it will change the returned +# message +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From a074b33d29e7968a168c387a51c9a0c7f2748091 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Wed, 9 Sep 2015 13:53:03 +0200 Subject: Collections --- cs-cz/python3.html.markdown | 278 ++++++++++++++++++++++---------------------- 1 file changed, 137 insertions(+), 141 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 79f064c6..68f9f597 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -9,7 +9,7 @@ translators: filename: learnpython3.py --- -Python byl vytvořen Guidem Van Rossum v raných 90 letech. Nyní je jedním z nejpopulárnějších jazyků. +Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] (anglicky). @@ -139,168 +139,164 @@ bool({}) # => False #################################################### -## 2. Variables and Collections +## 2. Proměnné a kolekce #################################################### -# Python has a print function -print("I'm Python. Nice to meet you!") - -# No need to declare variables before assigning to them. -# Convention is to use lower_case_with_underscores -some_var = 5 -some_var # => 5 - -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_unknown_var # Raises a NameError - -# Lists store sequences -li = [] -# You can start with a prefilled list -other_li = [4, 5, 6] - -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop -li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back -li.append(3) # li is now [1, 2, 4, 3] again. - -# Access a list like you would any array -li[0] # => 1 -# Look at the last element -li[-1] # => 3 - -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError - -# You can look at ranges with slice syntax. -# (It's a closed/open range for you mathy types.) -li[1:3] # => [2, 4] -# Omit the beginning -li[2:] # => [4, 3] -# Omit the end -li[:3] # => [1, 2, 4] -# Select every second entry -li[::2] # =>[1, 4] -# Return a reversed copy of the list -li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] - -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] - -# You can add lists -# Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# Check for existence in a list with "in" -1 in li # => True - -# Examine the length with "len()" -len(li) # => 6 - - -# Tuples are like lists but are immutable. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Raises a TypeError - -# You can do most of the list operations on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# Tuples are created by default if you leave out the parentheses +# Python má funkci print +print("Jsem 3. Python 3.") + +# Proměnné není třeba deklarovat před přiřazením +# Konvence je používat male_pismo_s_podtrzitky +nazev_promenne = 5 +nazev_promenne # => 5 + +# Přístup k předtím nepoužité proměnné vyvolá výjimku +# Odchytávání vyjímek - viz další kapitola +neznama_promenna # Vyhodí NameError + +# Seznam se používá pro ukládání sekvencí +sez = [] +# Lze ho rovnou naplnit +jiny_seznam = [4, 5, 6] + +# Na konec seznamu se přidává pomocí append +sez.append(1) # sez je nyní [1] +sez.append(2) # sez je nyní [1, 2] +sez.append(4) # sez je nyní [1, 2, 4] +sez.append(3) # sez je nyní [1, 2, 4, 3] +# Z konce se odebírá se pomocí pop +sez.pop() # => 3 a sez je nyní [1, 2, 4] +# Vložme trojku zpátky +sez.append(3) # sez je nyní znovu [1, 2, 4, 3] + +# Přístup k prvkům funguje jako v poli +sez[0] # => 1 +# Mínus počítá odzadu (-1 je poslední prvek) +sez[-1] # => 3 + +# Přístup mimo seznam vyhodí IndexError +sez[4] # Vyhodí IndexError + +# Pomocí řezů lze ze seznamu vybírat různé intervaly +# (pro matematiky: jedná se o uzavřený/otevřený interval) +sez[1:3] # => [2, 4] +# Odříznutí začátku +sez[2:] # => [4, 3] +# Odříznutí konce +sez[:3] # => [1, 2, 4] +# Vybrání každého druhého prvku +sez[::2] # =>[1, 4] +# Vrácení seznamu v opačném pořadí +sez[::-1] # => [3, 4, 2, 1] +# Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu +# sez[zacatek:konec:krok] + +# Odebírat prvky ze seznamu lze pomocí del +del sez[2] # sez je nyní [1, 2, 3] + +# Seznamy můžete sčítat +# Hodnoty sez a jiny_seznam přitom nejsou změněny +sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] + +# Spojit seznamy lze pomocí extend +sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] + +# Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in +1 in sez # => True + +# Délku seznamu lze zjistit pomocí len +len(sez) # => 6 + + +# N-tice je jako seznam, ale je neměnná +ntice = (1, 2, 3) +ntice[0] # => 1 +ntice[0] = 3 # Vyhodí TypeError + +# S n-ticemi lze dělat většinu operací, jako se seznamy +len(ntice) # => 3 +ntice + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +ntice[:2] # => (1, 2) +2 in ntice # => True + +# N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením +a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 +# N-tice jsou vytvářeny automaticky, když vynecháte závorky d, e, f = 4, 5, 6 -# Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 - - -# Dictionaries store mappings -empty_dict = {} -# Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Look up values with [] -filled_dict["one"] # => 1 +# Prohození proměnných je tak velmi snadné +e, d = d, e # d je nyní 5, e je nyní 4 -# Get all keys as an iterable with "keys()". We need to wrap the call in list() -# to turn it into a list. We'll talk about those later. Note - Dictionary key -# ordering is not guaranteed. Your results might not match this exactly. -list(filled_dict.keys()) # => ["three", "two", "one"] +# Slovníky ukládají klíče a hodnoty +prazdny_slovnik = {} +# Lze je také rovnou naplnit +slovnik = {"jedna": 1, "dva": 2, "tři": 3} -# Get all values as an iterable with "values()". Once again we need to wrap it -# in list() to get it out of the iterable. Note - Same as above regarding key -# ordering. -list(filled_dict.values()) # => [3, 2, 1] +# Přistupovat k hodnotám lze pomocí [] +slovnik["jedna"] # => 1 +# Všechny klíče dostaneme pomocí keys() jako iterátor. Nyní ještě potřebujeme +# obalit volání v list(), abychom dostali seznam. To rozebereme později. +# Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. +list(slovnik.keys()) # => ["dva", "jedna", "tři"] -# Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False +# Všechny hodnoty opět jako iterátor získáme pomocí values(). Opět tedy +# potřebujeme použít list(), abychom dostali seznam. Stejně jako +# v předchozím případě, pořadí není garantováno a může být různé +list(slovnik.values()) # => [3, 2, 1] -# Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +# Operátorem in se lze dotázat na přítomnost klíče +"jedna" in slovnik # => True +1 in slovnik # => False -# Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +# Přístup k neexistujícímu klíči vyhodí KeyError +slovnik["four"] # Vyhodí KeyError -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 +# Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError +slovnik.get("jedna") # => 1 +slovnik.get("čtyři") # => None +# Metodě get() lze předat i výchozí hodnotu místo None +slovnik.get("jedna", 4) # => 1 +slovnik.get("čtyři", 4) # => 4 -# Adding to a dictionary -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 #another way to add to dict +# metoda setdefault() vloží prvek do slovníku pouze pokud tam takový klíč není +slovnik.setdefault("pět", 5) # slovnik["pět"] je nastaven na 5 +slovnik.setdefault("pět", 6) # slovnik["pět"] je pořád 5 -# Remove keys from a dictionary with del -del filled_dict["one"] # Removes the key "one" from filled dict +# Přidání nové hodnoty do slovníku +slovnik["čtyři"] = 4 +# Hromadně aktualizovat nebo přidat data lze pomocí update(), parametrem je opět slovník +slovnik.update({"čtyři": 4}) # slovnik je nyní {"jedna": 1, "dva": 2, "tři": 3, "čtyři": 4, "pět": 5} +# Odebírat ze slovníku dle klíče lze pomocí del +del slovnik["jedna"] # odebere klíč "jedna" ze slovnik -# Sets store ... well sets -empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} -# Can set new variables to a set -filled_set = some_set +# Množiny ukládají ... překvapivě množiny +prazdna_mnozina = set() +# Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. +mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} -# Add one more item to the set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# Přidání položky do množiny +mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} -# Do set intersection with & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} +# Průnik lze udělat pomocí operátoru & +jina_mnozina = {3, 4, 5, 6} +mnozina & jina_mnozina # => {3, 4, 5} -# Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} +# Sjednocení pomocí operátoru | +mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} -# Do set difference with - +# Rozdíl pomocí operátoru - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# Check for existence in a set with in -2 in filled_set # => True -10 in filled_set # => False +# Operátorem in se lze dotázat na přítomnost prvku v množině +2 in mnozina # => True +10 in mnozina # => False #################################################### -## 3. Control Flow and Iterables +## 3. Řízení toku a iterace #################################################### # Let's just make a variable @@ -386,8 +382,8 @@ with open("myfile.txt") as f: # An iterable is an object that can be treated as a sequence. # The object returned the range function, is an iterable. -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() +slovnik = {"one": 1, "two": 2, "three": 3} +our_iterable = slovnik.keys() print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface # We can loop over it. @@ -412,7 +408,7 @@ next(our_iterator) # => "three" next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) # => Returns ["one", "two", "three"] +list(slovnik.keys()) # => Returns ["one", "two", "three"] #################################################### -- cgit v1.2.3 From 49c579f350b200d3e6f170eb207c6bc081b4b0e2 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Wed, 9 Sep 2015 16:14:12 +0200 Subject: If, for, while, iterators --- cs-cz/python3.html.markdown | 166 ++++++++++++++++++++++---------------------- 1 file changed, 84 insertions(+), 82 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 68f9f597..03fa2682 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -149,6 +149,8 @@ print("Jsem 3. Python 3.") # Konvence je používat male_pismo_s_podtrzitky nazev_promenne = 5 nazev_promenne # => 5 +# Názvy proměnných mohou obsahovat i UTF8 znaky +název_proměnné = 5 # Přístup k předtím nepoužité proměnné vyvolá výjimku # Odchytávání vyjímek - viz další kapitola @@ -185,9 +187,9 @@ sez[2:] # => [4, 3] # Odříznutí konce sez[:3] # => [1, 2, 4] # Vybrání každého druhého prvku -sez[::2] # =>[1, 4] +sez[::2] # =>[1, 4] # Vrácení seznamu v opačném pořadí -sez[::-1] # => [3, 4, 2, 1] +sez[::-1] # => [3, 4, 2, 1] # Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu # sez[zacatek:konec:krok] @@ -202,10 +204,10 @@ sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] # Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in -1 in sez # => True +1 in sez # => True # Délku seznamu lze zjistit pomocí len -len(sez) # => 6 +len(sez) # => 6 # N-tice je jako seznam, ale je neměnná @@ -220,11 +222,11 @@ ntice[:2] # => (1, 2) 2 in ntice # => True # N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením -a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 +a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 # N-tice jsou vytvářeny automaticky, když vynecháte závorky d, e, f = 4, 5, 6 # Prohození proměnných je tak velmi snadné -e, d = d, e # d je nyní 5, e je nyní 4 +e, d = d, e # d je nyní 5, e je nyní 4 # Slovníky ukládají klíče a hodnoty @@ -233,7 +235,7 @@ prazdny_slovnik = {} slovnik = {"jedna": 1, "dva": 2, "tři": 3} # Přistupovat k hodnotám lze pomocí [] -slovnik["jedna"] # => 1 +slovnik["jedna"] # => 1 # Všechny klíče dostaneme pomocí keys() jako iterátor. Nyní ještě potřebujeme # obalit volání v list(), abychom dostali seznam. To rozebereme později. @@ -275,58 +277,57 @@ del slovnik["jedna"] # odebere klíč "jedna" ze slovnik # Množiny ukládají ... překvapivě množiny prazdna_mnozina = set() # Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. -mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} +mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} # Přidání položky do množiny -mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} +mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} # Průnik lze udělat pomocí operátoru & jina_mnozina = {3, 4, 5, 6} -mnozina & jina_mnozina # => {3, 4, 5} +mnozina & jina_mnozina # => {3, 4, 5} # Sjednocení pomocí operátoru | -mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} +mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} # Rozdíl pomocí operátoru - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # Operátorem in se lze dotázat na přítomnost prvku v množině -2 in mnozina # => True -10 in mnozina # => False +2 in mnozina # => True +9 in mnozina # => False #################################################### -## 3. Řízení toku a iterace +## 3. Řízení toku programu, cykly #################################################### -# Let's just make a variable -some_var = 5 +# Vytvořme si proměnnou +promenna = 5 -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") +# Takto vypadá podmínka. Na odsazení v Pythonu záleží! +# Vypíše "proměnná je menší než 10". +if promenna > 10: + print("proměnná je velká jak Rusko") +elif promenna < 10: # Část elif je nepovinná + print("proměnná je menší než 10") +else: # Část else je také nepovinná + print("proměnná je právě 10") """ -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal +Smyčka for umí iterovat (nejen) přes seznamy +vypíše: + pes je savec + kočka je savec + myš je savec """ -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) +for zvire in ["pes", "kočka", "myš"]: + # Můžete použít formát pro složení řetězce + print("{} je savec".format(zvire)) """ -"range(number)" returns an iterable of numbers -from zero to the given number -prints: +range(cislo) vrací itarátor čísel od 0 do cislo +vypíše: 0 1 2 @@ -336,9 +337,8 @@ for i in range(4): print(i) """ -"range(lower, upper)" returns an iterable of numbers -from the lower number to the upper number -prints: +range(spodni_limit, horni_limit) vrací itarátor čísel mezi limity +vypíše: 4 5 6 @@ -348,8 +348,8 @@ for i in range(4, 8): print(i) """ -While loops go until a condition is no longer met. -prints: +Smyčka while se opakuje, dokud je podmínka splněna. +vypíše: 0 1 2 @@ -358,61 +358,63 @@ prints: x = 0 while x < 4: print(x) - x += 1 # Shorthand for x = x + 1 + x += 1 # Zkrácený zápis x = x + 1. Pozor, žádné x++ neexisuje. -# Handle exceptions with a try/except block + +# Výjimky lze ošetřit pomocí bloku try/except(/else/finally) try: - # Use "raise" to raise an error - raise IndexError("This is an index error") + # Pro vyhození výjimky použijte raise + raise IndexError("Přistoupil jste k neexistujícímu prvku v seznamu.") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. -except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print("All good!") # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances - print("We can clean up resources here") - -# Instead of try/finally to cleanup resources you can use a with statement -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python offers a fundamental abstraction called the Iterable. -# An iterable is an object that can be treated as a sequence. -# The object returned the range function, is an iterable. + print("Nastala chyba: {}".format(e)) + # Vypíše: Nastala chyba: Přistoupil jste k neexistujícímu prvku v seznamu. +except (TypeError, NameError): # Více výjimek lze zachytit najednou + pass # Pass znamená nedělej nic - nepříliš vhodný způsob ošetření chyb +else: # Volitelný blok else musí být až za bloky except + print("OK!") # Vypíše OK! v případě, že nenastala žádná výjimka +finally: # Blok finally se spustí nakonec za všech okolností + print("Uvolníme zdroje, uzavřeme soubory...") + +# Místo try/finally lze použít with pro automatické uvolnění zdrojů +with open("soubor.txt") as soubor: + for radka in soubor: + print(radka) + +# Python běžně používá iterovatelné objekty, což je prakticky cokoliv, +# co lze považovat za sekvenci. Například to, co vrací metoda range(), +# nebo otevřený soubor, jsou iterovatelné objekty. -slovnik = {"one": 1, "two": 2, "three": 3} -our_iterable = slovnik.keys() -print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface +slovnik = {"jedna": 1, "dva": 2, "tři": 3} +iterovatelny_objekt = slovnik.keys() +print(iterovatelny_objekt) # => dict_keys(["jedna", "dva", "tři"]). Toto je iterovatelný objekt. -# We can loop over it. -for i in our_iterable: - print(i) # Prints one, two, three +# Můžeme použít cyklus for na jeho projití +for klic in iterovatelny_objekt: + print(klic) # vypíše postupně: jedna, dva, tři -# However we cannot address elements by index. -our_iterable[1] # Raises a TypeError +# Ale nelze přistupovat k prvkům pod jejich indexem +iterovatelny_objekt[1] # Vyhodí TypeError -# An iterable is an object that knows how to create an iterator. -our_iterator = iter(our_iterable) +# Všechny položky iterovatelného objektu lze získat jako seznam pomocí list() +list(slovnik.keys()) # => ["jedna", "dva", "tři"] -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object with "next()". -next(our_iterator) # => "one" +# Z iterovatelného objektu lze vytvořit iterátor +iterator = iter(iterovatelny_objekt) -# It maintains state as we iterate. -next(our_iterator) # => "two" -next(our_iterator) # => "three" +# Iterátor je objekt, který si pamatuje stav v rámci svého iterovatelného objektu +# Další hodnotu dostaneme voláním next() +next(iterator) # => "jedna" -# After the iterator has returned all of its data, it gives you a StopIterator Exception -next(our_iterator) # Raises StopIteration +# Iterátor si udržuje svůj stav v mezi jednotlivými voláními next() +next(iterator) # => "dva" +next(iterator) # => "tři" -# You can grab all the elements of an iterator by calling list() on it. -list(slovnik.keys()) # => Returns ["one", "two", "three"] +# Jakmile interátor vrátí všechna svá data, vyhodí výjimku StopIteration +next(iterator) # Vyhodí StopIteration #################################################### -## 4. Functions +## 4. Funkce #################################################### # Use "def" to create new functions -- cgit v1.2.3 From f31f35a32e5774330d6f1989d74f97e3c18cd24f Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Wed, 9 Sep 2015 17:09:18 +0200 Subject: Functions --- cs-cz/python3.html.markdown | 130 ++++++++++++++++++++++---------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 03fa2682..dc7ad34b 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] + - ["Tomáš Bedřich", "http://tbedrich.cz"] translators: - ["Tomáš Bedřich", "http://tbedrich.cz"] filename: learnpython3.py @@ -20,7 +21,7 @@ Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit sta # Jednořádkový komentář začíná křížkem -""" Víceřádkové komentáře používají 3x" +""" Víceřádkové komentáře používají tři uvozovky nebo apostrofy a jsou často využívány jako dokumentační komentáře k metodám """ @@ -417,97 +418,96 @@ next(iterator) # Vyhodí StopIteration ## 4. Funkce #################################################### -# Use "def" to create new functions -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement +# Pro vytvoření nové funkce použijte def +def secist(x, y): + print("x je {} a y je {}".format(x, y)) + return x + y # Hodnoty se vrací pomocí return -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +# Volání funkce s parametry +secist(5, 6) # => Vypíše "x je 5 a y je 6" a vrátí 11 -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +# Jiný způsob, jak volat funkci, je použít pojmenované argumenty +secist(y=6, x=5) # Pojmenované argumenty můžete předat v libovolném pořadí -# You can define functions that take a variable number of -# positional arguments -def varargs(*args): - return args +# Lze definovat funkce s proměnným počtem (pozičních) argumentů +def vrat_argumenty(*argumenty): + return argumenty -varargs(1, 2, 3) # => (1, 2, 3) +vrat_argumenty(1, 2, 3) # => (1, 2, 3) -# You can define functions that take a variable number of -# keyword arguments, as well -def keyword_args(**kwargs): - return kwargs +# Lze definovat také funkce s proměnným počtem pojmenovaných argumentů +def vrat_pojmenovane_argumenty(**pojmenovane_argumenty): + return pojmenovane_argumenty -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} +vrat_pojmenovane_argumenty(kdo="se bojí", nesmi="do lesa") +# => {"kdo": "se bojí", "nesmi": "do lesa"} -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" +# Pokud chcete, lze použít obojí najednou +# Konvence je používat pro tyto účely názvy *args a **kwargs +def vypis_vse(*args, **kwargs): + print(args, kwargs) # print() vypíše všechny své parametry oddělené mezerou -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +vypis_vse(1, 2, a=3, b=4) # Vypíše: (1, 2) {"a": 3, "b": 4} +# * nebo ** lze použít k rozbalení N-tic nebo slovníků! +ntice = (1, 2, 3, 4) +slovnik = {"a": 3, "b": 4} +vypis_vse(ntice) # Vyhodnotí se jako vypis_vse((1, 2, 3, 4)) – jeden parametr, N-tice +vypis_vse(*ntice) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4) +vypis_vse(**slovnik) # Vyhodnotí se jako vypis_vse(a=3, b=4) +vypis_vse(*ntice, **slovnik) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4, a=3, b=4) -# Function Scope + +# Viditelnost proměnných - vytvořme si globální proměnnou x x = 5 -def setX(num): - # Local var x not the same as global variable x - x = num # => 43 - print (x) # => 43 +def nastavX(cislo): + # Lokální proměnná x překryje globální x + x = cislo # => 43 + print(x) # => 43 -def setGlobalX(num): +def nastavGlobalniX(cislo): global x - print (x) # => 5 - x = num # global var x is now set to 6 - print (x) # => 6 + print(x) # => 5 + x = cislo # Nastaví globální proměnnou x na 6 + print(x) # => 6 -setX(43) -setGlobalX(6) +nastavX(43) +nastavGlobalX(6) -# Python has first class functions -def create_adder(x): - def adder(y): - return x + y - return adder +# Funkce jsou first-class objekty +def vyrobit_scitacku(pricitane_cislo): + def scitacka(x): + return x + pricitane_cislo + return scitacka -add_10 = create_adder(10) -add_10(3) # => 13 +pricist_10 = vyrobit_scitacku(10) +pricist_10(3) # => 13 -# There are also anonymous functions -(lambda x: x > 2)(3) # => True +# Klíčové slovo lambda vytvoří anonymní funkci +(lambda parametr: parametr > 2)(3) # => True -# TODO - Fix for iterables -# There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +# Lze použít funkce map() a filter() z funkcionálního programování +map(pricist_10, [1, 2, 3]) +# => - iterovatelný objekt s obsahem: [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) +# => - iterovatelný objekt s obsahem: [6, 7] -# We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# S generátorovou notací lze dosáhnout podobných výsledků, ale vrací seznam +[pricist_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# Generátorová notace funguje i pro slovníky +{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16} +# A také pro množiny +{pismeno for pismeno in "abeceda"} # => {"d", "a", "c", "e", "b"} + #################################################### -## 5. Classes +## 5. Třídy #################################################### - # We subclass from object to get a class. class Human(object): -- cgit v1.2.3 From 7036c4a89c613c0dcd2a56a44c5f631e49c25ed4 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Wed, 9 Sep 2015 17:21:48 +0200 Subject: Fixed wrong info about iterators --- cs-cz/python3.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index dc7ad34b..9733215c 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -238,13 +238,13 @@ slovnik = {"jedna": 1, "dva": 2, "tři": 3} # Přistupovat k hodnotám lze pomocí [] slovnik["jedna"] # => 1 -# Všechny klíče dostaneme pomocí keys() jako iterátor. Nyní ještě potřebujeme -# obalit volání v list(), abychom dostali seznam. To rozebereme později. -# Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. +# Všechny klíče dostaneme pomocí keys() jako iterovatelný objekt. Nyní ještě +# potřebujeme obalit volání v list(), abychom dostali seznam. To rozebereme +# později. Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. list(slovnik.keys()) # => ["dva", "jedna", "tři"] -# Všechny hodnoty opět jako iterátor získáme pomocí values(). Opět tedy -# potřebujeme použít list(), abychom dostali seznam. Stejně jako +# Všechny hodnoty opět jako iterovatelný objekt získáme pomocí values(). Opět +# tedy potřebujeme použít list(), abychom dostali seznam. Stejně jako # v předchozím případě, pořadí není garantováno a může být různé list(slovnik.values()) # => [3, 2, 1] @@ -327,7 +327,7 @@ for zvire in ["pes", "kočka", "myš"]: print("{} je savec".format(zvire)) """ -range(cislo) vrací itarátor čísel od 0 do cislo +range(cislo) vrací iterovatelný objekt čísel od 0 do cislo vypíše: 0 1 @@ -338,7 +338,7 @@ for i in range(4): print(i) """ -range(spodni_limit, horni_limit) vrací itarátor čísel mezi limity +range(spodni_limit, horni_limit) vrací iterovatelný objekt čísel mezi limity vypíše: 4 5 -- cgit v1.2.3 From 61634fc32a4b9962062e890de98250aea8db3c24 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Wed, 9 Sep 2015 17:30:00 +0200 Subject: Added contact to myself and fixed contact to author --- cs-cz/python3.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 9733215c..e842321b 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -13,7 +13,8 @@ filename: learnpython3.py Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. -Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] (anglicky). +Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, +autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). -- cgit v1.2.3 From d06bdd72a3f2f9cb4ec3e60b7d227602f37d3fbc Mon Sep 17 00:00:00 2001 From: ftwbzhao Date: Thu, 10 Sep 2015 14:48:14 +0800 Subject: two spaces --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index b1143dac..b633714d 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -69,7 +69,7 @@ __此文本也是__ -此段落结尾有两个空格(选中以显示)。 +此段落结尾有两个空格(选中以显示)。 上文有一个
! -- cgit v1.2.3 From 6aa3563465b3b9f2a9fc963f8d0b609c99d6be38 Mon Sep 17 00:00:00 2001 From: livehl Date: Thu, 10 Sep 2015 16:37:07 +0800 Subject: =?UTF-8?q?=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 哎,强迫症,看到一半特意过来改了 --- zh-cn/bash-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 558d9110..d85e5b8f 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -258,7 +258,7 @@ help return help source help . -# 用 mam 指令阅读相关的 Bash 手册 +# 用 man 指令阅读相关的 Bash 手册 apropos bash man 1 bash man bash -- cgit v1.2.3 From 003db4af9b6d10d9737c28103a66c61887eb1c19 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Thu, 10 Sep 2015 18:14:25 +0200 Subject: Classes --- cs-cz/python3.html.markdown | 83 ++++++++++++++++++++++----------------------- 1 file changed, 41 insertions(+), 42 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index e842321b..0364b43d 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -509,59 +509,58 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) ## 5. Třídy #################################################### -# We subclass from object to get a class. -class Human(object): - - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" - - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called magic methods (or sometimes called dunder methods) - # You should not invent such names on your own. - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # An instance method. All methods take "self" as the first argument - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # A class method is shared among all instances - # They are called with the calling class as the first argument +# Třída Clovek je potomkem (dědí od) třídy object +class Clovek(object): + + # Atribut třídy - je sdílený všemi instancemi + druh = "H. sapiens" + + # Toto je kostruktor. Je volán, když vytváříme instanci třídy. Dvě + # podtržítka na začátku a na konci značí, že se jedná o atribut nebo + # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami + # definovat jeho chování. Metody jako __init__, __str__, __repr__ + # a další se nazývají "magické metody". Nikdy nepoužívejte toto + # speciální pojmenování pro běžné metody. + def __init__(self, jmeno): + # Přiřazení parametru do atributu instance jmeno + self.jmeno = jmeno + + # Metoda instance - všechny metody instance mají "self" jako první parametr + def rekni(self, hlaska): + return "{jmeno}: {hlaska}".format(jmeno=self.jmeno, hlaska=hlaska) + + # Metoda třídy - sdílená všemi instancemi + # Dostává jako první parametr třídu, na které je volána @classmethod - def get_species(cls): - return cls.species + def vrat_druh(cls): + return cls.druh - # A static method is called without a class or instance reference + # Statická metoda je volána bez reference na třídu nebo instanci @staticmethod - def grunt(): - return "*grunt*" + def odkaslej_si(): + return "*ehm*" -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# Vytvoření instance +d = Clovek(jmeno="David") +a = Clovek("Adéla") +print(d.rekni("ahoj")) # Vypíše: "David: ahoj" +print(a.rekni("nazdar")) # Vypíše: "Adéla: nazdar" -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" +# Volání třídní metody +d.vrat_druh() # => "H. sapiens" -# Call our class method -i.get_species() # => "H. sapiens" +# Změna atributu třídy +Clovek.druh = "H. neanderthalensis" +d.vrat_druh() # => "H. neanderthalensis" +a.vrat_druh() # => "H. neanderthalensis" -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Call the static method -Human.grunt() # => "*grunt*" +# Volání statické metody +Clovek.odkaslej_si() # => "*ehm*" #################################################### -## 6. Modules +## 6. Moduly #################################################### # You can import modules -- cgit v1.2.3 From 5335df886183da20e65c383ad54f3f755ff33f58 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Thu, 10 Sep 2015 18:21:27 +0200 Subject: Modules --- cs-cz/python3.html.markdown | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 0364b43d..a82ec146 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -563,29 +563,27 @@ Clovek.odkaslej_si() # => "*ehm*" ## 6. Moduly #################################################### -# You can import modules +# Lze importovat moduly import math print(math.sqrt(16)) # => 4 -# You can get specific functions from a module +# Lze také importovat pouze vybrané funkce z modulu from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 -# You can import all functions from a module. -# Warning: this is not recommended +# Můžete také importovat všechny funkce z modulu, ale radši to nedělejte from math import * -# You can shorten module names +# Můžete si přejmenovat modul při jeho importu import math as m -math.sqrt(16) == m.sqrt(16) # => True +math.sqrt(16) == m.sqrt(16) # => True -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. +# Modul v Pythonu není nic jiného, než obyčejný soubor .py +# Můžete si napsat vlastní a prostě ho importovat podle jména +from muj_modul import moje_funkce # Nyní vyhodí ImportError - muj_modul neexistuje -# You can find out which functions and attributes -# defines a module. +# Funkcí dir() lze zjistit, co modul obsahuje import math dir(math) -- cgit v1.2.3 From ea5866afc2a48fb4f047a120d1ebab160e74d40b Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Thu, 10 Sep 2015 18:53:10 +0200 Subject: Advanced --- cs-cz/python3.html.markdown | 66 +++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index a82ec146..6d3a7f20 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -589,56 +589,44 @@ dir(math) #################################################### -## 7. Advanced +## 7. Pokročilé #################################################### -# Generators help you make lazy code -def double_numbers(iterable): - for i in iterable: - yield i + i - -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): - print(i) - if i >= 30: - break +# Generátory jsou funkce, které místo return obsahují yield +def nasobicka_2(sekvence): + for i in sekvence: + yield 2 * i +# Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil +# celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. +# To znamená, že čísla větší než 15 se v metodě nasobicka_2 vůbec nezpracují. -# Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message -from functools import wraps +# Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo +# hodně času i paměti, proto se místo toho čísla generují postupně. + +for i in nasobicka_2(range(900000000)): + print(i) # Vypíše čísla 0, 2, 4, 6, 8, ... 30 + if i >= 30: + break -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg +# Dekorátory jsou funkce, které se používají pro obalení jiné funkce, čímž mohou +# přidávat nebo měnit její stávající chování. Funkci dostávají jako parametr +# a typicky místo ní vrací jinou, která uvnitř volá tu původní. - return wrapper +def nekolikrat(puvodni_funkce): + def opakovaci_funkce(*args, **kwargs): + for i in range(3): + puvodni_funkce(*args, **kwargs) + return opakovaci_funkce -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please +@nekolikrat +def pozdrav(jmeno): + print("Měj se {}!".format(jmeno)) -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +pozdrav("Pepo") # Vypíše 3x: Měj se Pepo! ``` ## Ready For More? -- cgit v1.2.3 From babd2b59ffb007aa8f6e6a3254506401acf90bf4 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Thu, 10 Sep 2015 18:59:15 +0200 Subject: Footer --- cs-cz/python3.html.markdown | 21 +++------------------ 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 6d3a7f20..cf9b03b6 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -629,22 +629,7 @@ def pozdrav(jmeno): pozdrav("Pepo") # Vypíše 3x: Měj se Pepo! ``` -## Ready For More? +## Co dál? -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) - -### Dead Tree - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) +Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] +(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. -- cgit v1.2.3 From f1a3493a6e60ad1a476e512337833a7849f99e70 Mon Sep 17 00:00:00 2001 From: Tomas Bedrich Date: Fri, 11 Sep 2015 14:47:32 +0200 Subject: Fixed minor errors --- cs-cz/python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index cf9b03b6..1f380f36 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -254,7 +254,7 @@ list(slovnik.values()) # => [3, 2, 1] 1 in slovnik # => False # Přístup k neexistujícímu klíči vyhodí KeyError -slovnik["four"] # Vyhodí KeyError +slovnik["čtyři"] # Vyhodí KeyError # Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError slovnik.get("jedna") # => 1 @@ -475,7 +475,7 @@ def nastavGlobalniX(cislo): print(x) # => 6 nastavX(43) -nastavGlobalX(6) +nastavGlobalniX(6) # Funkce jsou first-class objekty -- cgit v1.2.3 From daa37af85646b1fa936777bfdcb9662836b66e5e Mon Sep 17 00:00:00 2001 From: Junjie Tao Date: Mon, 14 Sep 2015 21:43:02 +0800 Subject: A tiny bug --- zh-cn/go-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 3a461efe..49224085 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -239,7 +239,7 @@ func learnConcurrency() { go inc(0, c) // go is a statement that starts a new goroutine. go inc(10, c) go inc(-805, c) - // 从channel中独处结果并打印。 + // 从channel中读取结果并打印。 // 打印出什么东西是不可预知的。 fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是读操作。 -- cgit v1.2.3 From ab6fc2fd2348a06667b4fbb4fc1e3cc650bc6f33 Mon Sep 17 00:00:00 2001 From: robochat Date: Mon, 14 Sep 2015 19:27:50 +0200 Subject: adding make tutorial --- make.html.markdown | 236 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 make.html.markdown diff --git a/make.html.markdown b/make.html.markdown new file mode 100644 index 00000000..1cf0d8c7 --- /dev/null +++ b/make.html.markdown @@ -0,0 +1,236 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] +filename: Makefile +--- + +A Makefile defines a graph of rules for creating a target (or targets). +It's purpose is the do the minimum amount of work needed to update a +target to the most recent version of the source. Famously written over a +weekend by Stuart Feldman in 1976, it is still widely used (particularly +on Unix) despite many competitors and criticisms. + +There are many varieties of make in existance, this article assumes that +we are using GNU make which is the standard on Linux. + +```make + +# Comments can be written like this. + +# Files should be named Makefile and then be can run as `make `. +# Otherwise we use `make -f "filename" `. + +# Warning - only use TABS to indent in Makefiles, never spaces! + +#----------------------------------------------------------------------- +# Basics +#----------------------------------------------------------------------- + +# A rule - this rule will only run if file0.txt doesn't exist. +file0.txt: + echo "foo" > file0.txt + # Even comments in these 'recipe' sections get passed to the shell. + # Try `make file0.txt` or simply `make` - first rule is the default. + + +# This rule will only run if file0.txt is newer than file1.txt. +file1.txt: file0.txt + cat file0.txt > file1.txt + # use the same quoting rules as in the shell. + @cat file0.txt >> file1.txt + # @ stops the command from being echoed to stdout. + -@echo 'hello' + # - means that make will keep going in the case of an error. + # Try `make file1.txt` on the commandline. + +# A rule can have multiple targets and multiple prerequisites +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make will complain about multiple recipes for the same rule. Empty +# recipes don't count though and can be used to add new dependencies. + +#----------------------------------------------------------------------- +# Phony Targets +#----------------------------------------------------------------------- + +# A phony target. Any target that isn't a file. +# It will never be up to date so make will always try to run it. +all: faker process + +# We can declare things out of order. +maker: + touch ex0.txt ex1.txt + +# Can avoid phony rules breaking when a real file has the same name by +.PHONY: all maker process +# This is a special target. There are several others. + +# A rule with a dependency on a phony target will always run +ex0.txt ex1.txt: maker + +# Common phony targets are: all make clean install ... + +#----------------------------------------------------------------------- +# Automatic Variables & Wildcards +#----------------------------------------------------------------------- + +process: file*.txt #using a wildcard to match filenames + @echo $^ # $^ is a variable containing the list of prerequisites + @echo $@ # prints the target name + #(for multiple target rules, $@ is whichever caused the rule to run) + @echo $< # the first prerequisite listed + @echo $? # only the dependencies that are out of date + @echo $+ # all dependencies including duplicates (unlike normal) + #@echo $| # all of the 'order only' prerequisites + +# Even if we split up the rule dependency definitions, $^ will find them +process: ex1.txt file0.txt +# ex1.txt will be found but file0.txt will be deduplicated. + +#----------------------------------------------------------------------- +# Patterns +#----------------------------------------------------------------------- + +# Can teach make how to convert certain files into other files. + +%.png: %.svg + inkscape --export-png %.svg + +# Pattern rules will only do anything if make decides to create the \ +target. + +# Directory paths are normally ignored when matching pattern rules. But +# make will try to use the most appropriate rule available. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 %.svg + +# make will use the last version for a pattern rule that it finds. +%.png: %.svg + @echo this rule is chosen + +# however make will use the first pattern rule that can make the target +%.png: %.ps + @echo this rule is not chosen if %.svg and %.ps are both present + +# make already has some pattern rules built-in. For instance, it knows +# how to turn *.c files into *.o files. + +#----------------------------------------------------------------------- +# Variables +#----------------------------------------------------------------------- +# aka. macros + +# Variables are basically all string types + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # This won't work, treated as $(n)ame. + @echo $(name3) # Unknown variables are treated as empty strings. + +# There are 4 places to set variables. +# In order of priority from highest to lowest: +# 1: commandline arguments +# 2: Makefile +# 3: shell enviroment variables - make imports these automatically. +# 4: make has some predefined variables + +name4 ?= Jean +# Only set the variable if enviroment variable is not already defined. + +override name5 = David +# Stops commandline arguments from changing this variable. + +name4 +=grey +# Append values to variable (includes a space). + +# Pattern-specific variable values (GNU extension). +echo: name2 = Sara # True within the matching rule + # and also within it's remade recursive dependencies + # (except it can break when your graph gets too complicated!) + +# Some variables defined automatically by make. +echo_inbuilt: + echo $(CC) + echo ${CXX)} + echo $(FC) + echo ${CFLAGS)} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables 2 +#----------------------------------------------------------------------- + +# The first type of variables are evaluated each time they are used. +# This can be expensive, so a second type of variable exists which is +# only evaluated once. (This is a GNU make extension) + +var := hello +var2 ::= $(var) hello +#:= and ::= are equivalent. + +# These variables are evaluated procedurely (in the order that they +# appear), thus breaking with the rest of the language ! + +# This doesn't work +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Functions +#----------------------------------------------------------------------- + +# make has lots of functions available. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# Format is $(func arg0,arg1,arg2...) + +# Some examples +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Include other makefiles, useful for platform specific code +include foo.mk + +sport = tennis +# Conditional compilation +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo 'They think it's all over; it is now' +endif + +# There are also ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + + +### More Resources + +[gnu make documentation](https://www.gnu.org/software/make/manual/) +[software carpentry tutorial](http://swcarpentry.github.io/make-novice/) +learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) + -- cgit v1.2.3 From b4ad0b800299d53f9cd18cf7da87299d1e71f6dc Mon Sep 17 00:00:00 2001 From: robochat Date: Mon, 14 Sep 2015 20:05:43 +0200 Subject: small corrections to make tutorial --- make.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 1cf0d8c7..16aa0b30 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -58,7 +58,7 @@ file2.txt file3.txt: file0.txt file1.txt # A phony target. Any target that isn't a file. # It will never be up to date so make will always try to run it. -all: faker process +all: maker process # We can declare things out of order. maker: @@ -230,7 +230,7 @@ endif ### More Resources -[gnu make documentation](https://www.gnu.org/software/make/manual/) -[software carpentry tutorial](http://swcarpentry.github.io/make-novice/) -learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) ++ [gnu make documentation](https://www.gnu.org/software/make/manual/) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) -- cgit v1.2.3 From 2508aa0269a9e4ef1542cafea7bfdf4105721be4 Mon Sep 17 00:00:00 2001 From: robochat Date: Mon, 14 Sep 2015 20:49:17 +0200 Subject: make.html: english corrections --- make.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 16aa0b30..63eb3eb7 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -6,7 +6,7 @@ filename: Makefile --- A Makefile defines a graph of rules for creating a target (or targets). -It's purpose is the do the minimum amount of work needed to update a +Its purpose is to do the minimum amount of work needed to update a target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly on Unix) despite many competitors and criticisms. @@ -152,7 +152,7 @@ name4 +=grey # Pattern-specific variable values (GNU extension). echo: name2 = Sara # True within the matching rule - # and also within it's remade recursive dependencies + # and also within its remade recursive dependencies # (except it can break when your graph gets too complicated!) # Some variables defined automatically by make. -- cgit v1.2.3 From 1079fe87ac0b24e8a5f8d59b33bb649f709478d7 Mon Sep 17 00:00:00 2001 From: robochat Date: Wed, 16 Sep 2015 06:56:37 +0000 Subject: Adding a couple of lines about suffix rules to the pattern section --- make.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/make.html.markdown b/make.html.markdown index 63eb3eb7..47e3b457 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -111,13 +111,20 @@ small/%.png: %.svg %.png: %.svg @echo this rule is chosen -# however make will use the first pattern rule that can make the target +# However make will use the first pattern rule that can make the target %.png: %.ps @echo this rule is not chosen if %.svg and %.ps are both present # make already has some pattern rules built-in. For instance, it knows # how to turn *.c files into *.o files. +# Older makefiles might use suffix rules instead of pattern rules +.png.ps: + @echo this rule is similar to a pattern rule. + +# Tell make about the suffix rule +.SUFFIXES: .png + #----------------------------------------------------------------------- # Variables #----------------------------------------------------------------------- -- cgit v1.2.3 From 0cd643e07217d29f6e22a8368f5a098b65d37f7e Mon Sep 17 00:00:00 2001 From: Luca Maroni Date: Fri, 18 Sep 2015 09:54:37 +0200 Subject: added Elixir --- it-it/elixir-it.html.markdown | 418 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 it-it/elixir-it.html.markdown diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown new file mode 100644 index 00000000..f5d0c172 --- /dev/null +++ b/it-it/elixir-it.html.markdown @@ -0,0 +1,418 @@ +--- +language: elixir +contributors: + - ["Luca 'Kino' Maroni", "https://github.com/kino90"] + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +filename: learnelixir-it.ex +lang: it-it +--- + +Elixir è un linguaggio funzionale moderno, costruito sulla VM Erlang. +È totalmente compatibile con Erlang, ma con una sintassi più standard +e molte altre funzionalità. + +```elixir + +# I commenti su una riga iniziano con un cancelletto. + +# Non esistono commenti multilinea, +# ma puoi concatenare più commenti. + +# Per usare la shell di elixir usa il comando `iex`. +# Compila i tuoi moduli con il comando `elixirc`. + +# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato +# elixir correttamente. + +## --------------------------- +## -- Tipi di base +## --------------------------- + +# Numeri +3 # intero (Integer) +0x1F # intero +3.0 # decimale (Float) + +# Atomi, che sono literals, una costante con un nome. Iniziano con `:`. +:ciao # atomo (Atom) + +# Tuple che sono salvate in celle di memoria contigue. +{1,2,3} # tupla (Tuple) + +# Possiamo accedere ad un elemento di una tupla con la funzione `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Liste, che sono implementate come liste concatenate (o linked list). +[1,2,3] # lista (List) + +# Possiamo accedere alla testa (head) e alla coda (tail) delle liste così: +[testa | coda] = [1,2,3] +testa #=> 1 +coda #=> [2,3] + +# In Elixir, proprio come in Erlang, il simbolo `=` denota pattern matching e +# non un assegnamento. +# +# Questo significa che la parte sinistra (pattern) viene confrontata alla +# parte destra. +# +# Questo spiega il funzionamento dell'esempio dell'accesso alla lista di prima. + +# Un pattern match darà errore quando le parti non combaciano, ad esempio se +# le tuple hanno dimensione differente. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Ci sono anche i binari +<<1,2,3>> # binari (Binary) + +# Stringhe e liste di caratteri +"ciao" # stringa (String) +'ciao' # lista di caratteri (List) + +# Stringhe multilinea +""" +Sono una stringa +multi-linea. +""" +#=> "Sono una stringa\nmulti-linea.\n" + +# Le stringhe sono tutte codificate in UTF-8: +"cìaò" +#=> "cìaò" + +# le stringhe in realtà sono dei binari, e le liste di caratteri sono liste. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` in elixir restituisce il valore ASCII della lettera `a` +?a #=> 97 + +# Per concatenare liste si usa `++`, per binari si usa `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'ciao ' ++ 'mondo' #=> 'ciao mondo' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"ciao " <> "mondo" #=> "ciao mondo" + +# Gli intervalli sono rappresentati come `inizio..fine` (estremi inclusi) +1..10 #=> 1..10 (Range) +minore..maggiore = 1..10 # Puoi fare pattern matching anche sugli intervalli +[minore, maggiore] #=> [1, 10] + +## --------------------------- +## -- Operatori +## --------------------------- + +# Un po' di matematica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# In elixir l'operatore `/` restituisce sempre un decimale. + +# Per fare una divisione intera si usa `div` +div(10, 2) #=> 5 + +# Per ottenere il resto di una divisione si usa `rem` +rem(10, 3) #=> 1 + +# Ci sono anche gli operatori booleani: `or`, `and` e `not`. +# Questi operatori si aspettano un booleano come primo argomento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir fornisce anche `||`, `&&` e `!` che accettano argomenti +# di qualsiasi tipo. +# Tutti i valori tranne `false` e `nil` saranno valutati come true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Per i confronti abbiamo: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` sono più rigidi quando si confrontano interi e decimali: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Possiamo anche confrontare tipi di dato diversi: +1 < :ciao #=> true + +# L'ordine generale è definito sotto: +# numeri < atomi < riferimenti < funzioni < porte < pid < tuple < liste +# < stringhe di bit + +# Per citare Joe Armstrong su questo: "L'ordine non è importante, +# ma è importante che sia definito un ordine." + +## --------------------------- +## -- Controllo di flusso +## --------------------------- + +# espressione `se` (`if`) +if false do + "Questo non si vedrà mai" +else + "Questo sì" +end + +# c'è anche un `se non` (`unless`) +unless true do + "Questo non si vedrà mai" +else + "Questo sì" +end + +# Ti ricordi il pattern matching? +# Moltre strutture di controllo di flusso in elixir si basano su di esso. + +# `case` ci permette di confrontare un valore a diversi pattern: +case {:uno, :due} do + {:quattro, :cinque} -> + "Questo non farà match" + {:uno, x} -> + "Questo farà match e binderà `x` a `:due`" + _ -> + "Questo farà match con qualsiasi valore" +end + +# Solitamente si usa `_` se non si ha bisogno di utilizzare un valore. +# Ad esempio, se ci serve solo la testa di una lista: +[testa | _] = [1,2,3] +testa #=> 1 + +# Per aumentare la leggibilità possiamo usarlo in questo modo: +[testa | _coda] = [:a, :b, :c] +testa #=> :a + +# `cond` ci permette di verificare più condizioni allo stesso momento. +# Usa `cond` invece di innestare più espressioni `if`. +cond do + 1 + 1 == 3 -> + "Questa stringa non si vedrà mai" + 2 * 5 == 12 -> + "Nemmeno questa" + 1 + 2 == 3 -> + "Questa sì!" +end + +# È pratica comune mettere l'ultima condizione a `true`, che farà sempre match +cond do + 1 + 1 == 3 -> + "Questa stringa non si vedrà mai" + 2 * 5 == 12 -> + "Nemmeno questa" + true -> + "Questa sì! (essenzialmente funziona come un else)" +end + +# `try/catch` si usa per gestire i valori lanciati (throw), +# Supporta anche una clausola `after` che è invocata in ogni caso. +try do + throw(:ciao) +catch + message -> "Ho ricevuto #{message}." +after + IO.puts("Io sono la clausola 'after'.") +end +#=> Io sono la clausola 'after' +# "Ho ricevuto :ciao" + +## --------------------------- +## -- Moduli e Funzioni +## --------------------------- + +# Funzioni anonime (notare il punto) +quadrato = fn(x) -> x * x end +quadrato.(5) #=> 25 + +# Accettano anche guardie e condizioni multiple. +# le guardie ti permettono di perfezionare il tuo pattern matching, +# sono indicate dalla parola chiave `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir fornisce anche molte funzioni, disponibili nello scope corrente. +is_number(10) #=> true +is_list("ciao") #=> false +elem({1,2,3}, 0) #=> 1 + +# Puoi raggruppare delle funzioni all'interno di un modulo. +# All'interno di un modulo usa `def` per definire le tue funzioni. +defmodule Matematica do + def somma(a, b) do + a + b + end + + def quadrato(x) do + x * x + end +end + +Matematica.somma(1, 2) #=> 3 +Matematica.quadrato(3) #=> 9 + +# Per compilare il modulo 'Matematica' salvalo come `matematica.ex` e usa +# `elixirc`. +# nel tuo terminale: elixirc matematica.ex + +# All'interno di un modulo possiamo definire le funzioni con `def` e funzioni +# private con `defp`. +# Una funzione definita con `def` è disponibile per essere invocata anche da +# altri moduli, una funziona privata può essere invocata solo localmente. +defmodule MatematicaPrivata do + def somma(a, b) do + esegui_somma(a, b) + end + + defp esegui_somma(a, b) do + a + b + end +end + +MatematicaPrivata.somma(1, 2) #=> 3 +# MatematicaPrivata.esegui_somma(1, 2) #=> ** (UndefinedFunctionError) + +# Anche le dichiarazioni di funzione supportano guardie e condizioni multiple: +defmodule Geometria do + def area({:rettangolo, w, h}) do + w * h + end + + def area({:cerchio, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometria.area({:rettangolo, 2, 3}) #=> 6 +Geometria.area({:cerchio, 3}) #=> 28.25999999999999801048 +# Geometria.area({:cerchio, "non_un_numero"}) +#=> ** (FunctionClauseError) no function clause matching in Geometria.area/1 + +# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in elixir +defmodule Ricorsione do + def somma_lista([testa | coda], accumulatore) do + somma_lista(coda, accumulatore + testa) + end + + def somma_lista([], accumulatore) do + accumulatore + end +end + +Ricorsione.somma_lista([1,2,3], 0) #=> 6 + +# I moduli di Elixir supportano attributi. Ci sono degli attributi incorporati +# e puoi anche aggiungerne di personalizzati. +defmodule Modulo do + @moduledoc """ + Questo è un attributo incorporato in un modulo di esempio. + """ + + @miei_dati 100 # Questo è un attributo personalizzato . + IO.inspect(@miei_dati) #=> 100 +end + +## --------------------------- +## -- Strutture ed Eccezioni +## --------------------------- + + +# Le Strutture (Structs) sono estensioni alle mappe che portano +# valori di default, garanzia alla compilazione e polimorfismo in Elixir. +defmodule Persona do + defstruct nome: nil, eta: 0, altezza: 0 +end + +luca = %Persona{ nome: "Luca", eta: 24, altezza: 185 } +#=> %Persona{eta: 24, altezza: 185, nome: "Luca"} + +# Legge al valore di 'nome' +luca.nome #=> "Luca" + +# Modifica il valore di eta +luca_invecchiato = %{ luca | eta: 25 } +#=> %Persona{eta: 25, altezza: 185, nome: "Luca"} + +# Il blocco `try` con la parola chiave `rescue` è usato per gestire le eccezioni +try do + raise "un errore" +rescue + RuntimeError -> "Salvato un errore di Runtime" + _error -> "Questo salverà da qualsiasi errore" +end + +# Tutte le eccezioni hanno un messaggio +try do + raise "un errore" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrenza +## --------------------------- + +# Elixir si basa sul modello degli attori per la concorrenza. +# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir +# sono tre primitive: creare processi, inviare messaggi e ricevere messaggi. + +# Per creare un nuovo processo si usa la funzione `spawn`, che riceve una +# funzione come argomento. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` restituisce un pid (identificatore di processo). Puoi usare questo +# pid per inviare messaggi al processo. +# Per passare messaggi si usa l'operatore `send`. +# Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, +# oltre ad inviarli. Questo è realizzabile con `receive`: +defmodule Geometria do + def calcolo_area do + receive do + {:rettangolo, w, h} -> + IO.puts("Area = #{w * h}") + calcolo_area() + {:cerchio, r} -> + IO.puts("Area = #{3.14 * r * r}") + calcolo_area() + end + end +end + +# Compila il modulo e crea un processo che esegue `calcolo_area` nella shell +pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0> + +# Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive +send pid, {:rettangolo, 2, 3} +#=> Area = 6 +# {:rettangolo,2,3} + +send pid, {:cerchio, 2} +#=> Area = 12.56000000000000049738 +# {:cerchio,2} + +# Anche la shell è un processo. Puoi usare `self` per ottenere il pid corrente +self() #=> #PID<0.27.0> +``` + +## Referenze + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org) +* [Documentazione Elixir](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) di Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) di Joe Armstrong -- cgit v1.2.3 From cb728dc4d3117fdefe91713a8d0d129d48ad7e1d Mon Sep 17 00:00:00 2001 From: Luca Maroni Date: Fri, 18 Sep 2015 09:57:04 +0200 Subject: Added coffeescript --- it-it/coffeescript-it.html.markdown | 102 ++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 it-it/coffeescript-it.html.markdown diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown new file mode 100644 index 00000000..c4bc8ea9 --- /dev/null +++ b/it-it/coffeescript-it.html.markdown @@ -0,0 +1,102 @@ +--- +language: coffeescript +contributors: + - ["Luca 'Kino' Maroni", "http://github.com/kino90"] + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +filename: coffeescript-it.coffee +lang: it-it +--- + +CoffeeScript è un piccolo linguaggio che compila direttamente nell'equivalente JavaScript, non c'è nessuna interpretazione a runtime. Come possibile successore di Javascript, CoffeeScript fa il suo meglio per restituire un codice leggibile, ben stampato e performante in ogni ambiente JavaScript. + +Guarda anche [il sito di CoffeeScript](http://coffeescript.org/), che ha una guida completa a CoffeeScript. + +```coffeescript +# CoffeeScript è un linguaggio hipster. +# Segue le mode di alcuni linguaggi moderni. +# Quindi i commenti sono come quelli di Ruby e Python, usano l'asterisco. + +### +I blocchi di commenti sono definiti con tre cancelletti, che vengono tradotti direttamente in `/*` e `*/` nel codice JavaScript risultante. + +Prima di continuare devi conoscere la maggior parte +delle semantiche JavaScript. +### + +# Assegnamento: +numero = 42 #=> var numero = 42; +contrario = true #=> var contrario = true; + +# Condizioni: +numero = -42 if contrario #=> if(contrario) { numero = -42; } + +# Funzioni: +quadrato = (x) -> x * x #=> var quadrato = function(x) { return x * x; } + +riempi = (contenitore, liquido = "caffè") -> + "Sto riempiendo #{contenitore} con #{liquido}..." +#=>var riempi; +# +#riempi = function(contenitore, liquido) { +# if (liquido == null) { +# liquido = "caffè"; +# } +# return "Sto riempiendo " + contenitore + " con " + liquido + "..."; +#}; + +# Intervalli: +lista = [1..5] #=> var lista = [1, 2, 3, 4, 5]; + +# Oggetti: +matematica = + radice: Math.sqrt + quadrato: quadrato + cubo: (x) -> x * quadrato x +#=> var matematica = { +# "radice": Math.sqrt, +# "quadrato": quadrato, +# "cubo": function(x) { return x * quadrato(x); } +#} + +# Splats: +gara = (vincitore, partecipanti...) -> + print vincitore, partecipanti +#=>gara = function() { +# var partecipanti, vincitore; +# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vincitore, partecipanti); +#}; + +# Esistenza: +alert "Lo sapevo!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); } + +# Comprensione degli Array: +cubi = (matematica.cubo num for num in lista) +#=>cubi = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lista.length; _i < _len; _i++) { +# num = lista[_i]; +# _results.push(matematica.cubo(num)); +# } +# return _results; +# })(); + +cibi = ['broccoli', 'spinaci', 'cioccolato'] +mangia cibo for cibo in cibi when cibo isnt 'cioccolato' +#=>cibi = ['broccoli', 'spinaci', 'cioccolato']; +# +#for (_k = 0, _len2 = cibi.length; _k < _len2; _k++) { +# cibo = cibi[_k]; +# if (cibo !== 'cioccolato') { +# mangia(cibo); +# } +#} +``` + +## Altre risorse + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From 2d056ac5d7b367e61231e3fcad5901a5d620dab9 Mon Sep 17 00:00:00 2001 From: tleb Date: Sat, 19 Sep 2015 10:59:04 +0200 Subject: [ruby-ecosystem/en] Fix typo --- ruby-ecosystem.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 8b292edd..d8a02d36 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -54,7 +54,7 @@ the community has moved to at least 1.9.2 or 1.9.3. ## Ruby Implementations The Ruby ecosystem enjoys many different implementations of Ruby, each with -unique strengths and states of compatability. To be clear, the different +unique strengths and states of compatibility. To be clear, the different implementations are written in different languages, but *they are all Ruby*. Each implementation has special hooks and extra features, but they all run normal Ruby files well. For instance, JRuby is written in Java, but you do -- cgit v1.2.3 From 92eef7f483fd4c1192aab8049e8b2f0e926523e4 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 19 Sep 2015 11:07:26 -0500 Subject: Add Udemy's new git tutorial as a resource. --- git.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 4bbc58e7..bf8fce0c 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -462,6 +462,8 @@ $ git rm /pather/to/the/file/HelloWorld.c * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + * [git-scm - Video Tutorials](http://git-scm.com/videos) * [git-scm - Documentation](http://git-scm.com/docs) -- cgit v1.2.3 From 52b217af04589faac6298f38302c4fad2b33542c Mon Sep 17 00:00:00 2001 From: Luca Maroni Date: Sun, 20 Sep 2015 02:06:53 +0200 Subject: Fixed lines too long and a typo (asterisco => cancelletto) --- it-it/coffeescript-it.html.markdown | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index c4bc8ea9..16eb9bd4 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -8,17 +8,22 @@ filename: coffeescript-it.coffee lang: it-it --- -CoffeeScript è un piccolo linguaggio che compila direttamente nell'equivalente JavaScript, non c'è nessuna interpretazione a runtime. Come possibile successore di Javascript, CoffeeScript fa il suo meglio per restituire un codice leggibile, ben stampato e performante in ogni ambiente JavaScript. +CoffeeScript è un piccolo linguaggio che compila direttamente nell'equivalente +JavaScript, non c'è nessuna interpretazione a runtime. Come possibile +successore di Javascript, CoffeeScript fa il suo meglio per restituire +un codice leggibile, ben stampato e performante in ogni ambiente JavaScript. -Guarda anche [il sito di CoffeeScript](http://coffeescript.org/), che ha una guida completa a CoffeeScript. +Guarda anche [il sito di CoffeeScript](http://coffeescript.org/), che ha una +guida completa a CoffeeScript. ```coffeescript # CoffeeScript è un linguaggio hipster. # Segue le mode di alcuni linguaggi moderni. -# Quindi i commenti sono come quelli di Ruby e Python, usano l'asterisco. +# Quindi i commenti sono come quelli di Ruby e Python, usano il cancelletto. ### -I blocchi di commenti sono definiti con tre cancelletti, che vengono tradotti direttamente in `/*` e `*/` nel codice JavaScript risultante. +I blocchi di commenti sono definiti con tre cancelletti, che vengono tradotti +direttamente in `/*` e `*/` nel codice JavaScript risultante. Prima di continuare devi conoscere la maggior parte delle semantiche JavaScript. -- cgit v1.2.3 From 55e22c0a8cbf68158892790d2942bb594960943b Mon Sep 17 00:00:00 2001 From: robochat Date: Mon, 21 Sep 2015 14:06:38 +0000 Subject: tiny white space changes --- make.html.markdown | 486 ++++++++++++++++++++++++++--------------------------- 1 file changed, 243 insertions(+), 243 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 47e3b457..9aca2c20 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -1,243 +1,243 @@ ---- -language: make -contributors: - - ["Robert Steed", "https://github.com/robochat"] -filename: Makefile ---- - -A Makefile defines a graph of rules for creating a target (or targets). -Its purpose is to do the minimum amount of work needed to update a -target to the most recent version of the source. Famously written over a -weekend by Stuart Feldman in 1976, it is still widely used (particularly -on Unix) despite many competitors and criticisms. - -There are many varieties of make in existance, this article assumes that -we are using GNU make which is the standard on Linux. - -```make - -# Comments can be written like this. - -# Files should be named Makefile and then be can run as `make `. -# Otherwise we use `make -f "filename" `. - -# Warning - only use TABS to indent in Makefiles, never spaces! - -#----------------------------------------------------------------------- -# Basics -#----------------------------------------------------------------------- - -# A rule - this rule will only run if file0.txt doesn't exist. -file0.txt: - echo "foo" > file0.txt - # Even comments in these 'recipe' sections get passed to the shell. - # Try `make file0.txt` or simply `make` - first rule is the default. - - -# This rule will only run if file0.txt is newer than file1.txt. -file1.txt: file0.txt - cat file0.txt > file1.txt - # use the same quoting rules as in the shell. - @cat file0.txt >> file1.txt - # @ stops the command from being echoed to stdout. - -@echo 'hello' - # - means that make will keep going in the case of an error. - # Try `make file1.txt` on the commandline. - -# A rule can have multiple targets and multiple prerequisites -file2.txt file3.txt: file0.txt file1.txt - touch file2.txt - touch file3.txt - -# Make will complain about multiple recipes for the same rule. Empty -# recipes don't count though and can be used to add new dependencies. - -#----------------------------------------------------------------------- -# Phony Targets -#----------------------------------------------------------------------- - -# A phony target. Any target that isn't a file. -# It will never be up to date so make will always try to run it. -all: maker process - -# We can declare things out of order. -maker: - touch ex0.txt ex1.txt - -# Can avoid phony rules breaking when a real file has the same name by -.PHONY: all maker process -# This is a special target. There are several others. - -# A rule with a dependency on a phony target will always run -ex0.txt ex1.txt: maker - -# Common phony targets are: all make clean install ... - -#----------------------------------------------------------------------- -# Automatic Variables & Wildcards -#----------------------------------------------------------------------- - -process: file*.txt #using a wildcard to match filenames - @echo $^ # $^ is a variable containing the list of prerequisites - @echo $@ # prints the target name - #(for multiple target rules, $@ is whichever caused the rule to run) - @echo $< # the first prerequisite listed - @echo $? # only the dependencies that are out of date - @echo $+ # all dependencies including duplicates (unlike normal) - #@echo $| # all of the 'order only' prerequisites - -# Even if we split up the rule dependency definitions, $^ will find them -process: ex1.txt file0.txt -# ex1.txt will be found but file0.txt will be deduplicated. - -#----------------------------------------------------------------------- -# Patterns -#----------------------------------------------------------------------- - -# Can teach make how to convert certain files into other files. - -%.png: %.svg - inkscape --export-png %.svg - -# Pattern rules will only do anything if make decides to create the \ -target. - -# Directory paths are normally ignored when matching pattern rules. But -# make will try to use the most appropriate rule available. -small/%.png: %.svg - inkscape --export-png --export-dpi 30 %.svg - -# make will use the last version for a pattern rule that it finds. -%.png: %.svg - @echo this rule is chosen - -# However make will use the first pattern rule that can make the target -%.png: %.ps - @echo this rule is not chosen if %.svg and %.ps are both present - -# make already has some pattern rules built-in. For instance, it knows -# how to turn *.c files into *.o files. - -# Older makefiles might use suffix rules instead of pattern rules -.png.ps: - @echo this rule is similar to a pattern rule. - -# Tell make about the suffix rule -.SUFFIXES: .png - -#----------------------------------------------------------------------- -# Variables -#----------------------------------------------------------------------- -# aka. macros - -# Variables are basically all string types - -name = Ted -name2="Sarah" - -echo: - @echo $(name) - @echo ${name2} - @echo $name # This won't work, treated as $(n)ame. - @echo $(name3) # Unknown variables are treated as empty strings. - -# There are 4 places to set variables. -# In order of priority from highest to lowest: -# 1: commandline arguments -# 2: Makefile -# 3: shell enviroment variables - make imports these automatically. -# 4: make has some predefined variables - -name4 ?= Jean -# Only set the variable if enviroment variable is not already defined. - -override name5 = David -# Stops commandline arguments from changing this variable. - -name4 +=grey -# Append values to variable (includes a space). - -# Pattern-specific variable values (GNU extension). -echo: name2 = Sara # True within the matching rule - # and also within its remade recursive dependencies - # (except it can break when your graph gets too complicated!) - -# Some variables defined automatically by make. -echo_inbuilt: - echo $(CC) - echo ${CXX)} - echo $(FC) - echo ${CFLAGS)} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} - -#----------------------------------------------------------------------- -# Variables 2 -#----------------------------------------------------------------------- - -# The first type of variables are evaluated each time they are used. -# This can be expensive, so a second type of variable exists which is -# only evaluated once. (This is a GNU make extension) - -var := hello -var2 ::= $(var) hello -#:= and ::= are equivalent. - -# These variables are evaluated procedurely (in the order that they -# appear), thus breaking with the rest of the language ! - -# This doesn't work -var3 ::= $(var4) and good luck -var4 ::= good night - -#----------------------------------------------------------------------- -# Functions -#----------------------------------------------------------------------- - -# make has lots of functions available. - -sourcefiles = $(wildcard *.c */*.c) -objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) - -# Format is $(func arg0,arg1,arg2...) - -# Some examples -ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) - -#----------------------------------------------------------------------- -# Directives -#----------------------------------------------------------------------- - -# Include other makefiles, useful for platform specific code -include foo.mk - -sport = tennis -# Conditional compilation -report: -ifeq ($(sport),tennis) - @echo 'game, set, match' -else - @echo 'They think it's all over; it is now' -endif - -# There are also ifneq, ifdef, ifndef - -foo = true - -ifdef $(foo) -bar = 'hello' -endif -``` - - -### More Resources - -+ [gnu make documentation](https://www.gnu.org/software/make/manual/) -+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) -+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) - +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] +filename: Makefile +--- + +A Makefile defines a graph of rules for creating a target (or targets). +Its purpose is to do the minimum amount of work needed to update a +target to the most recent version of the source. Famously written over a +weekend by Stuart Feldman in 1976, it is still widely used (particularly +on Unix) despite many competitors and criticisms. + +There are many varieties of make in existance, this article assumes that +we are using GNU make which is the standard on Linux. + +```make + +# Comments can be written like this. + +# Files should be named Makefile and then be can run as `make `. +# Otherwise we use `make -f "filename" `. + +# Warning - only use TABS to indent in Makefiles, never spaces! + +#----------------------------------------------------------------------- +# Basics +#----------------------------------------------------------------------- + +# A rule - this rule will only run if file0.txt doesn't exist. +file0.txt: + echo "foo" > file0.txt + # Even comments in these 'recipe' sections get passed to the shell. + # Try `make file0.txt` or simply `make` - first rule is the default. + + +# This rule will only run if file0.txt is newer than file1.txt. +file1.txt: file0.txt + cat file0.txt > file1.txt + # use the same quoting rules as in the shell. + @cat file0.txt >> file1.txt + # @ stops the command from being echoed to stdout. + -@echo 'hello' + # - means that make will keep going in the case of an error. + # Try `make file1.txt` on the commandline. + +# A rule can have multiple targets and multiple prerequisites +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make will complain about multiple recipes for the same rule. Empty +# recipes don't count though and can be used to add new dependencies. + +#----------------------------------------------------------------------- +# Phony Targets +#----------------------------------------------------------------------- + +# A phony target. Any target that isn't a file. +# It will never be up to date so make will always try to run it. +all: maker process + +# We can declare things out of order. +maker: + touch ex0.txt ex1.txt + +# Can avoid phony rules breaking when a real file has the same name by +.PHONY: all maker process +# This is a special target. There are several others. + +# A rule with a dependency on a phony target will always run +ex0.txt ex1.txt: maker + +# Common phony targets are: all make clean install ... + +#----------------------------------------------------------------------- +# Automatic Variables & Wildcards +#----------------------------------------------------------------------- + +process: file*.txt #using a wildcard to match filenames + @echo $^ # $^ is a variable containing the list of prerequisites + @echo $@ # prints the target name + #(for multiple target rules, $@ is whichever caused the rule to run) + @echo $< # the first prerequisite listed + @echo $? # only the dependencies that are out of date + @echo $+ # all dependencies including duplicates (unlike normal) + #@echo $| # all of the 'order only' prerequisites + +# Even if we split up the rule dependency definitions, $^ will find them +process: ex1.txt file0.txt +# ex1.txt will be found but file0.txt will be deduplicated. + +#----------------------------------------------------------------------- +# Patterns +#----------------------------------------------------------------------- + +# Can teach make how to convert certain files into other files. + +%.png: %.svg + inkscape --export-png %.svg + +# Pattern rules will only do anything if make decides to create the \ +target. + +# Directory paths are normally ignored when matching pattern rules. But +# make will try to use the most appropriate rule available. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 %.svg + +# make will use the last version for a pattern rule that it finds. +%.png: %.svg + @echo this rule is chosen + +# However make will use the first pattern rule that can make the target +%.png: %.ps + @echo this rule is not chosen if %.svg and %.ps are both present + +# make already has some pattern rules built-in. For instance, it knows +# how to turn *.c files into *.o files. + +# Older makefiles might use suffix rules instead of pattern rules +.png.ps: + @echo this rule is similar to a pattern rule. + +# Tell make about the suffix rule +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables +#----------------------------------------------------------------------- +# aka. macros + +# Variables are basically all string types + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # This won't work, treated as $(n)ame. + @echo $(name3) # Unknown variables are treated as empty strings. + +# There are 4 places to set variables. +# In order of priority from highest to lowest: +# 1: commandline arguments +# 2: Makefile +# 3: shell enviroment variables - make imports these automatically. +# 4: make has some predefined variables + +name4 ?= Jean +# Only set the variable if enviroment variable is not already defined. + +override name5 = David +# Stops commandline arguments from changing this variable. + +name4 +=grey +# Append values to variable (includes a space). + +# Pattern-specific variable values (GNU extension). +echo: name2 = Sara # True within the matching rule + # and also within its remade recursive dependencies + # (except it can break when your graph gets too complicated!) + +# Some variables defined automatically by make. +echo_inbuilt: + echo $(CC) + echo ${CXX)} + echo $(FC) + echo ${CFLAGS)} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables 2 +#----------------------------------------------------------------------- + +# The first type of variables are evaluated each time they are used. +# This can be expensive, so a second type of variable exists which is +# only evaluated once. (This is a GNU make extension) + +var := hello +var2 ::= $(var) hello +#:= and ::= are equivalent. + +# These variables are evaluated procedurely (in the order that they +# appear), thus breaking with the rest of the language ! + +# This doesn't work +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Functions +#----------------------------------------------------------------------- + +# make has lots of functions available. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# Format is $(func arg0,arg1,arg2...) + +# Some examples +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Include other makefiles, useful for platform specific code +include foo.mk + +sport = tennis +# Conditional compilation +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo 'They think it's all over; it is now' +endif + +# There are also ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + + +### More Resources + ++ [gnu make documentation](https://www.gnu.org/software/make/manual/) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) + -- cgit v1.2.3 From a020a82521904da6289ada6c12904e75d4abab0b Mon Sep 17 00:00:00 2001 From: robochat Date: Tue, 22 Sep 2015 07:41:35 +0000 Subject: fix two small bugs - tab error and quotation marks --- make.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 9aca2c20..244d96e0 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -120,7 +120,7 @@ small/%.png: %.svg # Older makefiles might use suffix rules instead of pattern rules .png.ps: - @echo this rule is similar to a pattern rule. + @echo this rule is similar to a pattern rule. # Tell make about the suffix rule .SUFFIXES: .png @@ -222,7 +222,7 @@ report: ifeq ($(sport),tennis) @echo 'game, set, match' else - @echo 'They think it's all over; it is now' + @echo "They think it's all over; it is now" endif # There are also ifneq, ifdef, ifndef -- cgit v1.2.3 From 3fcea9a3fd69be5f2b55c104c27252d58e7a7cee Mon Sep 17 00:00:00 2001 From: robochat Date: Tue, 22 Sep 2015 08:39:33 +0000 Subject: can't use % stems in the recipe itself. --- make.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 244d96e0..75543dcd 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -97,7 +97,7 @@ process: ex1.txt file0.txt # Can teach make how to convert certain files into other files. %.png: %.svg - inkscape --export-png %.svg + inkscape --export-png $^ # Pattern rules will only do anything if make decides to create the \ target. @@ -105,7 +105,7 @@ target. # Directory paths are normally ignored when matching pattern rules. But # make will try to use the most appropriate rule available. small/%.png: %.svg - inkscape --export-png --export-dpi 30 %.svg + inkscape --export-png --export-dpi 30 $^ # make will use the last version for a pattern rule that it finds. %.png: %.svg @@ -113,7 +113,7 @@ small/%.png: %.svg # However make will use the first pattern rule that can make the target %.png: %.ps - @echo this rule is not chosen if %.svg and %.ps are both present + @echo this rule is not chosen if *.svg and *.ps are both present # make already has some pattern rules built-in. For instance, it knows # how to turn *.c files into *.o files. -- cgit v1.2.3 From 62f27af4c38f546f29fcf095fc653989b0667908 Mon Sep 17 00:00:00 2001 From: Jack Kuan Date: Wed, 23 Sep 2015 00:04:02 -0400 Subject: Update perl6.html.markdown --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index af545793..8d425f7d 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -213,7 +213,7 @@ say $x; #=> 52 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), "", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: 0, (), {}, "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { -- cgit v1.2.3 From e898c628ef68aaeea82be92ac5b6c5922bbb9f5e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 28 Sep 2015 00:10:50 +0800 Subject: Use c highlighting in D article for now. --- d.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 88c7e37f..daba8020 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -6,7 +6,7 @@ contributors: lang: en --- -```d +```c // You know what's coming... module hello; @@ -26,7 +26,7 @@ expressive high-level abstractions. D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool dudes. With all that out of the way, let's look at some examples! -```d +```c import std.stdio; void main() { @@ -68,7 +68,7 @@ We can define new types with `struct`, `class`, `union`, and `enum`. Structs and are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, we can use templates to parameterize all of these on both types and values! -```d +```c // Here, T is a type parameter. Think from C++/C#/Java struct LinkedList(T) { T data = null; @@ -132,7 +132,7 @@ is roughly a function that may act like an lvalue, so we can have the syntax of POD structures (`structure.x = 7`) with the semantics of getter and setter methods (`object.setX(7)`)! -```d +```c // Consider a class parameterized on a types T, U class MyClass(T, U) { @@ -198,7 +198,7 @@ functions, and immutable data. In addition, all of your favorite functional algorithms (map, filter, reduce and friends) can be found in the wonderful `std.algorithm` module! -```d +```c import std.algorithm : map, filter, reduce; import std.range : iota; // builds an end-exclusive range @@ -226,7 +226,7 @@ is of some type A on any expression of type A as a method. I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! -```d +```c import std.stdio; import std.parallelism : parallel; import std.math : sqrt; -- cgit v1.2.3 From f7923b73e65c31356f5ed55fc2856c04da8ce875 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 29 Sep 2015 21:23:42 -0500 Subject: Add lang: tr-tr to Turkish swift file. --- tr-tr/swift-tr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index 41835e13..90f3fcd5 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -3,6 +3,7 @@ language: swift contributors: - ["Özgür Şahin", "https://github.com/ozgurshn/"] filename: learnswift.swift +lang: tr-tr --- Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi. -- cgit v1.2.3 From b0036199c4fa6974f285e3b9520e9e058294d584 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 30 Sep 2015 10:40:48 +0800 Subject: Still can't use `julia` highlighting --- es-es/julia-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 1e01c2e3..65cb4343 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -41,7 +41,7 @@ En Julia los programas están organizados entorno al [despacho múltiple](http:/ Esto se basa en la versión `0.3.11`. -```julia +```ruby # Los comentarios de una línea comienzan con una almohadilla (o signo de gato). #= -- cgit v1.2.3 From 09874aa5c008c3944093dc2d3a5ddca489e2c998 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 30 Sep 2015 10:48:59 +0800 Subject: map->dict --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 16a94c8f..352f7349 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -412,7 +412,7 @@ varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a map if you do not use ** +# keyword args, as well, which will be interpreted as a dict if you do not use ** def keyword_args(**kwargs): return kwargs -- cgit v1.2.3 From 64d031429dd68fdd5b76fdd0e87f8379ba681439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ismael=20Venegas=20Castell=C3=B3?= Date: Wed, 30 Sep 2015 00:10:14 -0500 Subject: Use smaller images I didn't notice they wouldnt fit well, because they fitted ok in github preview. --- es-es/julia-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 65cb4343..95a16412 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -9,7 +9,7 @@ filename: learnjulia-es.jl lang: es-es --- -![JuliaLang](https://camo.githubusercontent.com/e1ae5c7f6fe275a50134d5889a68f0acdd09ada8/687474703a2f2f6a756c69616c616e672e6f72672f696d616765732f6c6f676f5f68697265732e706e67) +![JuliaLang](http://s13.postimg.org/z89djuwyf/julia_small.png) [Julia](http://julialanges.github.io) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org). @@ -931,7 +931,7 @@ code_native(area_circulo, (Float64,)) =# ``` -![Julia-tan](http://www.mechajyo.org/wp/wp-content/uploads/2014/10/3a2c3b7de5dd39aa7f056a707cd4eb59.png) +![Julia-tan](http://s27.postimg.org/x37ndhz0j/julia_tan_small.png) ## ¿Listo para más? -- cgit v1.2.3 From 6f9ce2ebf10d94c00f555ad62abf0bb2820f2b13 Mon Sep 17 00:00:00 2001 From: Leo Arias Date: Wed, 30 Sep 2015 11:36:34 -0600 Subject: Fixed the description of attributes and elements. Fixes issue #1154 --- xml.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/xml.html.markdown b/xml.html.markdown index fce1a3a4..059ea132 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -49,10 +49,11 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i + Elements appear between the open and close tags. --> -- cgit v1.2.3 From 510eeb7684748afc83eb14e27d95a6b6c65deff4 Mon Sep 17 00:00:00 2001 From: willianjusten Date: Wed, 30 Sep 2015 22:40:46 -0300 Subject: [javascript pt-br] : first part --- pt-br/javascript-pt.html.markdown | 533 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 533 insertions(+) create mode 100644 pt-br/javascript-pt.html.markdown diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown new file mode 100644 index 00000000..c4115b3e --- /dev/null +++ b/pt-br/javascript-pt.html.markdown @@ -0,0 +1,533 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript.js +--- + +JavaScript foi criada por Brendan Eich, funcionário da Netscape, em 1995. Ela +foi originalmente criada para ser uma linguagem de script para websites, +complementando o uso de Java para aplicações web mais complexas, mas a sua +integração com páginas web e seu suporte nativo nos browsers fez com que +ela se tornasse mais comum que Java no frontend web. + +Javascript não é somente limitado a browsers web, no entanto: existe o Node.js, +que é um projeto que fornece um interpretador baseado no motor V8 do Google +Chrome e está se tornando cada vez mais famoso. + + +Feedback são muito apreciados! Você me encontrar em +[@adambrenecki](https://twitter.com/adambrenecki), ou +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Comentários são como em C. Comentários de uma linha começam com duas barras, +/* e comentários de múltplas linhas começam com barra-asterisco + e fecham com asterisco-barra */ + +// comandos podem ser terminados com ; +facaAlgo(); + +// ... mas eles não precisam ser, assim como o ponto-e-vírgula é automaticamente +// inserido quando há uma nova linha, exceto alguns casos. +facaAlgo() + +// Porque esses casos podem causar resultados inesperados, vamos continuar +// a usar ponto-e-vírgula neste guia. + +/////////////////////////////////// +// 1. Numbers, Strings and Operators + +// JavaScript has one number type (which is a 64-bit IEEE 754 double). +// Doubles have a 52-bit mantissa, which is enough to store integers +// up to about 9✕10¹⁵ precisely. +3; // = 3 +1.5; // = 1.5 + +// Some basic arithmetic works as you'd expect. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Including uneven division. +5 / 2; // = 2.5 + +// Bitwise operations also work; when you perform a bitwise operation your float +// is converted to a signed int *up to* 32 bits. +1 << 2; // = 4 + +// Precedence is enforced with parentheses. +(1 + 3) * 2; // = 8 + +// There are three special not-a-real-number values: +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 + +// There's also a boolean type. +true; +false; + +// Strings are created with ' or ". +'abc'; +"Hello, world"; + +// Negation uses the ! symbol +!true; // = false +!false; // = true + +// Equality is === +1 === 1; // = true +2 === 1; // = false + +// Inequality is !== +1 !== 1; // = false +2 !== 1; // = true + +// More comparisons +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Strings are concatenated with + +"Hello " + "world!"; // = "Hello world!" + +// and are compared with < and > +"a" < "b"; // = true + +// Type coercion is performed for comparisons with double equals... +"5" == 5; // = true +null == undefined; // = true + +// ...unless you use === +"5" === 5; // = false +null === undefined; // = false + +// ...which can result in some weird behaviour... +13 + !0; // 14 +"13" + !0; // '13true' + +// You can access characters in a string with `charAt` +"This is a string".charAt(0); // = 'T' + +// ...or use `substring` to get larger pieces. +"Hello world".substring(0, 5); // = "Hello" + +// `length` is a property, so don't use (). +"Hello".length; // = 5 + +// There's also `null` and `undefined`. +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although + // `undefined` is actually a value itself) + +// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. +// Note that 0 is falsy and "0" is truthy, even though 0 == "0". + +/////////////////////////////////// +// 2. Variables, Arrays and Objects + +// Variables are declared with the `var` keyword. JavaScript is dynamically +// typed, so you don't need to specify type. Assignment uses a single `=` +// character. +var someVar = 5; + +// if you leave the var keyword off, you won't get an error... +someOtherVar = 10; + +// ...but your variable will be created in the global scope, not in the scope +// you defined it in. + +// Variables declared without being assigned to are set to undefined. +var someThirdVar; // = undefined + +// There's shorthand for performing math operations on variables: +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 + +// and an even-shorter-hand for adding or subtracting 1 +someVar++; // now someVar is 101 +someVar--; // back to 100 + +// Arrays are ordered lists of values, of any type. +var myArray = ["Hello", 45, true]; + +// Their members can be accessed using the square-brackets subscript syntax. +// Array indices start at zero. +myArray[1]; // = 45 + +// Arrays are mutable and of variable length. +myArray.push("World"); +myArray.length; // = 4 + +// Add/Modify at specific index +myArray[3] = "Hello"; + +// JavaScript's objects are equivalent to "dictionaries" or "maps" in other +// languages: an unordered collection of key-value pairs. +var myObj = {key1: "Hello", key2: "World"}; + +// Keys are strings, but quotes aren't required if they're a valid +// JavaScript identifier. Values can be any type. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Object attributes can also be accessed using the subscript syntax, +myObj["my other key"]; // = 4 + +// ... or using the dot syntax, provided the key is a valid identifier. +myObj.myKey; // = "myValue" + +// Objects are mutable; values can be changed and new keys added. +myObj.myThirdKey = true; + +// If you try to access a value that's not yet set, you'll get undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logic and Control Structures + +// The syntax for this section is almost identical to Java's. + +// The `if` structure works as you'd expect. +var count = 1; +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4){ + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} + +// As does `while`. +while (true){ + // An infinite loop! +} + +// Do-while loops are like while loops, except they always run at least once. +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// The `for` loop is the same as C and Java: +// initialisation; continue condition; iteration. +for (var i = 0; i < 5; i++){ + // will run 5 times +} + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default"; + + +// The `switch` statement checks for equality with `===`. +// use 'break' after each case +// or the cases after the correct one will be executed too. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Scope and Closures + +// JavaScript functions are declared with the `function` keyword. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Note that the value to be returned must start on the same line as the +// `return` keyword, otherwise you'll always return `undefined` due to +// automatic semicolon insertion. Watch out for this when using Allman style. +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions are first class objects, so they can be reassigned to +// different variable names and passed to other functions as arguments - for +// example, when supplying an event handler: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000); +// Note: setTimeout isn't part of the JS language, but is provided by browsers +// and Node.js. + +// Function objects don't even have to be declared with a name - you can write +// an anonymous function definition directly into the arguments of another. +setTimeout(function(){ + // this code will be called in 5 seconds' time +}, 5000); + +// JavaScript has function scope; functions get their own scope but other blocks +// do not. +if (true){ + var i = 5; +} +i; // = 5 - not undefined as you'd expect in a block-scoped language + +// This has led to a common pattern of "immediately-executing anonymous +// functions", which prevent temporary variables from leaking into the global +// scope. +(function(){ + var temporary = 5; + // We can access the global scope by assiging to the "global object", which + // in a web browser is always `window`. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 + +// One of JavaScript's most powerful features is closures. If a function is +// defined inside another function, the inner function has access to all the +// outer function's variables, even after the outer function exits. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions are put in the local scope by default, as if they were + // declared with `var`. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the `prompt` variable when it is finally called. +} +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s + +/////////////////////////////////// +// 5. More about Objects; Constructors and Prototypes + +// Objects can contain functions. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// When functions attached to an object are called, they can access the object +// they're attached to using the `this` keyword. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// What this is set to has to do with how the function is called, not where +// it's defined. So, our function doesn't work if it isn't called in the +// context of the object. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Inversely, a function can be assigned to the object and gain access to it +// through `this`, even if it wasn't attached when it was defined. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// We can also specify a context for a function to execute in when we invoke it +// using `call` or `apply`. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// The `apply` function is nearly identical, but takes an array for an argument +// list. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// This is useful when working with a function that accepts a sequence of +// arguments and you want to pass an array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// But, `call` and `apply` are only temporary. When we want it to stick, we can +// use `bind`. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// `bind` can also be used to partially apply (curry) a function. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// When you call a function with the `new` keyword, a new object is created, and +// made available to the function via the this keyword. Functions designed to be +// called like that are called constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Every JavaScript object has a 'prototype'. When you go to access a property +// on an object that doesn't exist on the actual object, the interpreter will +// look at its prototype. + +// Some JS implementations let you access an object's prototype on the magic +// property `__proto__`. While this is useful for explaining prototypes it's not +// part of the standard; we'll get to standard ways of using prototypes later. +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +myObj.myFunc(); // = "hello world!" + +// Of course, if your property isn't on your prototype, the prototype's +// prototype is searched, and so on. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// There's no copying involved here; each object stores a reference to its +// prototype. This means we can alter the prototype and our changes will be +// reflected everywhere. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// We mentioned that `__proto__` was non-standard, and there's no standard way to +// change the prototype of an existing object. However, there are two ways to +// create a new object with a given prototype. + +// The first is Object.create, which is a recent addition to JS, and therefore +// not available in all implementations yet. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// The second way, which works anywhere, has to do with constructors. +// Constructors have a property called prototype. This is *not* the prototype of +// the constructor function itself; instead, it's the prototype that new objects +// are given when they're created with that constructor and the new keyword. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Except, they aren't exactly equivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +// For instance, we mentioned that Object.create isn't yet available in all +// implementations, but we can still use it with this polyfill: +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +## Further Reading + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +more about how to use JavaScript in web pages, start by learning about the +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +guide of all the counter-intuitive parts of the language. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. -- cgit v1.2.3 From aaa818fc2522bf49b07f33a4011d31cce5b01ad0 Mon Sep 17 00:00:00 2001 From: William Claude Tumeo Date: Thu, 1 Oct 2015 01:42:19 -0300 Subject: Add `kbd` tag --- markdown.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/markdown.html.markdown b/markdown.html.markdown index 7541f904..6d19710f 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -232,6 +232,12 @@ can be anything so long as they are unique. --> I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. + + + +Your computer crashed? Try sending a +Ctrl+Alt+Del + -- cgit v1.2.3 From 222cfcd15c7539fd4d2340e5e70cbf3f6b6e087b Mon Sep 17 00:00:00 2001 From: Jonathan Klein Date: Thu, 1 Oct 2015 07:37:05 -0400 Subject: All class constants can be accessed statically --- php.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 2d4565e0..5cc6a785 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -495,7 +495,9 @@ class MyClass } } +// Class constants can always be accessed statically echo MyClass::MY_CONST; // Outputs 'value'; + echo MyClass::$staticVar; // Outputs 'static'; MyClass::myStaticMethod(); // Outputs 'I am static'; -- cgit v1.2.3 From 5254c21bbed437e1f91c9c78209da2b48d22ec8b Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 1 Oct 2015 09:39:00 -0500 Subject: Add lang: to header of Python3 cs-cz file. --- cs-cz/python3.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 1f380f36..11c8a654 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -8,6 +8,7 @@ contributors: translators: - ["Tomáš Bedřich", "http://tbedrich.cz"] filename: learnpython3.py +lang: cs-cz --- Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. -- cgit v1.2.3 From 8eb410208a8d9b0a42f6c52411455ace04c78101 Mon Sep 17 00:00:00 2001 From: George Gognadze Date: Thu, 1 Oct 2015 18:55:28 +0400 Subject: Update c++.html.markdown o should be capitalized. this: overrides should be: Overrides --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 26dfe111..8a7f5a59 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -735,7 +735,7 @@ class Foo { virtual void bar(); }; class FooSub : public Foo { - virtual void bar(); // overrides Foo::bar! + virtual void bar(); // Overrides Foo::bar! }; -- cgit v1.2.3 From 13b575af7f4f0e531218496b7c776cdda2bbda51 Mon Sep 17 00:00:00 2001 From: Leonnardo Rabello Date: Thu, 1 Oct 2015 14:57:11 -0300 Subject: [c++/pt-br] Fix translate on editing object as parameters --- pt-br/c++-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 61625ebe..61e267f5 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -304,7 +304,7 @@ void Dog::Dog() } // Objetos (como strings) devem ser passados por referência -// se você está modificando-os ou referência const se você não é. +// se você pretende modificá-los, ou com const caso contrário. void Dog::setName(const std::string& dogsName) { name = dogsName; -- cgit v1.2.3 From e4a33446a9c910f13bc0224c745c51baf62c1778 Mon Sep 17 00:00:00 2001 From: Jesus Tinoco Date: Thu, 1 Oct 2015 21:34:02 +0200 Subject: Typos fixed in julia-es.html.markdown --- es-es/julia-es.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 95a16412..bf035edf 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -45,7 +45,7 @@ Esto se basa en la versión `0.3.11`. # Los comentarios de una línea comienzan con una almohadilla (o signo de gato). #= - Los commentarios multilínea pueden escribirse + Los comentarios multilínea pueden escribirse usando '#=' antes de el texto y '=#' después del texto. También se pueden anidar. =# @@ -174,7 +174,7 @@ otraVariable_123! = 6 # => 6 otra_variable * Los nombres de los tipos comienzan con una letra mayúscula y separación de - palabras se muestra con CamelCase en vez de guion bajo: + palabras se muestra con CamelCase en vez de guión bajo: OtroTipo @@ -214,7 +214,7 @@ matrix = [1 2; 3 4] 3 4 =# -# Añadir cosas a la final de un arreglo con push! y append!. +# Añadir cosas al final de un arreglo con push! y append!. push!(a, 1) # => [1] push!(a, 2) # => [1,2] push!(a, 4) # => [1,2,4] @@ -237,7 +237,7 @@ a[end] # => 6 shift!(a) # => 1 y a es ahora: [2,4,3,4,5,6] unshift!(a, 7) # => [7,2,4,3,4,5,6] -# Los nombres de funciónes que terminan en exclamaciones indican que modifican +# Los nombres de funciones que terminan en exclamaciones indican que modifican # su o sus argumentos de entrada. arr = [5, 4, 6] # => 3-element Array{Int64,1}: [5,4,6] sort(arr) # => [4,5,6] y arr es todavía: [5,4,6] @@ -710,7 +710,7 @@ end # Sólo define una función del mismo nombre que el tipo y llama al constructor # existente para obtener un valor del tipo correcto. -# Este es un constructor externo porque es fuera de la definición del tipo. +# Este es un constructor externo porque está fuera de la definición del tipo. Leon(rugido::String) = Leon("verde", rugido) type Pantera <: Gato # Pantera también es un a subtipo de Gato @@ -730,7 +730,7 @@ end ######################## # En Julia, todas las funciones nombradas son funciones genéricas. -# Esto significa que se construyen a partir de muchos métodosmás pequeños. +# Esto significa que se construyen a partir de muchos métodos más pequeños. # Cada constructor de Leon es un método de la función genérica Leon. # Por ejemplo, vamos a hacer métodos para para Leon, Pantera, y Tigre de una -- cgit v1.2.3 From 8d48ba536a00f72cd8b960c16f5c9fcaa0badab7 Mon Sep 17 00:00:00 2001 From: Nora Demeter Date: Thu, 1 Oct 2015 16:17:58 -0400 Subject: Fixed some grammatical issues/typos --- css.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 9e8664b3..7224d80a 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -7,19 +7,19 @@ contributors: filename: learncss.css --- -In early days of web there was no visual elements, just pure text. But with the -further development of browser fully visual web pages also became common. +In the early days of the web there were no visual elements, just pure text. But with the +further development of browsers, fully visual web pages also became common. CSS is the standard language that exists to keep the separation between the content (HTML) and the look-and-feel of web pages. In short, what CSS does is to provide a syntax that enables you to target different elements on an HTML page and assign different visual properties to them. -Like any other language, CSS has many versions. Here we focus on CSS2.0 -which is not the most recent but the most widely supported and compatible version. +Like any other languages, CSS has many versions. Here we focus on CSS2.0, +which is not the most recent version, but is the most widely supported and compatible version. -**NOTE:** Because the outcome of CSS is some visual effects, in order to -learn it, you need try all different things in a +**NOTE:** Because the outcome of CSS consists of visual effects, in order to +learn it, you need try everything in a CSS playground like [dabblet](http://dabblet.com/). The main focus of this article is on the syntax and some general tips. -- cgit v1.2.3 From 87d0c402fb596c64a443a5374335508cb6941dc4 Mon Sep 17 00:00:00 2001 From: Philip Rowan Date: Thu, 1 Oct 2015 18:34:11 -0500 Subject: [javascript] Fix for issue 1248 https://github.com/adambard/learnxinyminutes-docs/issues/1248 --- javascript.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 588ea86d..ba2e8ce4 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -475,9 +475,6 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } -if (Number(0)){ - // This code *will* execute, because Number(0) is truthy. -} // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. -- cgit v1.2.3 From 087d0619481c4812cae387a4704e9ff91b935ea5 Mon Sep 17 00:00:00 2001 From: Luqi Pan Date: Thu, 1 Oct 2015 16:42:51 -0700 Subject: Aligned the comment block --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 2d4565e0..52ea2a95 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -487,7 +487,7 @@ class MyClass * Declaring class properties or methods as static makes them accessible without * needing an instantiation of the class. A property declared as static can not * be accessed with an instantiated class object (though a static method can). -*/ + */ public static function myStaticMethod() { -- cgit v1.2.3 From ed2bc5a84c4dfc1af45c05ea8b1a20122ac72620 Mon Sep 17 00:00:00 2001 From: willianjusten Date: Thu, 1 Oct 2015 22:23:18 -0300 Subject: =?UTF-8?q?[javascript=20pt-br]=20:=201.=20N=C3=BAmeros,=20Strings?= =?UTF-8?q?=20e=20Operadores?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/javascript-pt.html.markdown | 75 ++++++++++++++++++++------------------- 1 file changed, 39 insertions(+), 36 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index c4115b3e..72f4cf0f 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -37,96 +37,99 @@ facaAlgo() // a usar ponto-e-vírgula neste guia. /////////////////////////////////// -// 1. Numbers, Strings and Operators +// 1. Números, Strings e Operadores -// JavaScript has one number type (which is a 64-bit IEEE 754 double). -// Doubles have a 52-bit mantissa, which is enough to store integers -// up to about 9✕10¹⁵ precisely. +// Javascript tem um tipo de número (que é o 64-bit IEEE 754 double). +// Doublas tem uma mantissa 52-bit, que é suficiente para guardar inteiros +// acima de 9✕10¹⁵ precisamente. 3; // = 3 1.5; // = 1.5 -// Some basic arithmetic works as you'd expect. +// A aritmética básica funciona seria de esperar. 1 + 1; // = 2 0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -// Including uneven division. +// Inclusive divisão desigual. 5 / 2; // = 2.5 -// Bitwise operations also work; when you perform a bitwise operation your float -// is converted to a signed int *up to* 32 bits. +// Operadores Bitwise também funcionam; quando você faz uma operação bitwise +// seu float é convertido para um int de até 32 bits. 1 << 2; // = 4 -// Precedence is enforced with parentheses. +// A precedência é aplicada com parênteses. (1 + 3) * 2; // = 8 // There are three special not-a-real-number values: -Infinity; // result of e.g. 1/0 --Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 +// Existem três especiais valores não-é-número-real: +Infinity; // resultado de 1/0 +-Infinity; // resultado de -1/0 +NaN; // resultado de 0/0 -// There's also a boolean type. +// Existe também o tipo booleano. true; false; -// Strings are created with ' or ". +// Strings são criados com ' ou ". 'abc'; -"Hello, world"; +"Olá, mundo"; // Negation uses the ! symbol +// Negação usa o símbolo ! !true; // = false !false; // = true -// Equality is === +// Igualdade é === 1 === 1; // = true 2 === 1; // = false -// Inequality is !== +// Desigualdade é !== 1 !== 1; // = false 2 !== 1; // = true -// More comparisons +// Mais comparações 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true 2 >= 2; // = true -// Strings are concatenated with + -"Hello " + "world!"; // = "Hello world!" +// Strings são concatenadas com + +"Olá " + "mundo!"; // = "Olá mundo!" -// and are compared with < and > +// e comparadas com < e > "a" < "b"; // = true -// Type coercion is performed for comparisons with double equals... +// A coerção de tipos é feita para comparações com dois iguais... "5" == 5; // = true null == undefined; // = true -// ...unless you use === +// ...a menos que use === "5" === 5; // = false null === undefined; // = false -// ...which can result in some weird behaviour... +// ...que irá resultar num comportamento estranho... 13 + !0; // 14 "13" + !0; // '13true' -// You can access characters in a string with `charAt` -"This is a string".charAt(0); // = 'T' +// Você pode acessar caracteres de uma String usando o `charAt` +"Isto é uma String".charAt(0); // = 'I' -// ...or use `substring` to get larger pieces. -"Hello world".substring(0, 5); // = "Hello" +// ...ou usar `substring` para pegar pedaços maiores. +"Olá mundo".substring(0, 3); // = "Olá" -// `length` is a property, so don't use (). -"Hello".length; // = 5 +// `length` é uma propriedade, portanto não use (). +"Olá".length; // = 3 -// There's also `null` and `undefined`. -null; // used to indicate a deliberate non-value -undefined; // used to indicate a value is not currently present (although - // `undefined` is actually a value itself) +// Existe também o `null` e o `undefined`. +null; // usado para indicar um valor não considerado +undefined; // usado para indicar um valor que não é a atualmente definido + // (entretando `undefined` é usado como um próprio valor -// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. -// Note that 0 is falsy and "0" is truthy, even though 0 == "0". +// false, null, undefined, NaN, 0 and "" são valores falsy; +// qualquer outro valor é truthy +// Note que 0 é falsy e "0" é truthy, até mesmo 0 == "0". /////////////////////////////////// // 2. Variables, Arrays and Objects -- cgit v1.2.3 From 716e0ced466ef98f7fb9d78d15a5ab606b6b755c Mon Sep 17 00:00:00 2001 From: willianjusten Date: Thu, 1 Oct 2015 23:48:05 -0300 Subject: =?UTF-8?q?[javascript=20pt-br]=20:=202.=20Vari=C3=A1veis,=20Array?= =?UTF-8?q?s=20e=20Objetos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/javascript-pt.html.markdown | 57 ++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 72f4cf0f..6667a77d 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -132,62 +132,65 @@ undefined; // usado para indicar um valor que não é a atualmente definido // Note que 0 é falsy e "0" é truthy, até mesmo 0 == "0". /////////////////////////////////// -// 2. Variables, Arrays and Objects +// 2. Variáveis, Arrays e Objetos -// Variables are declared with the `var` keyword. JavaScript is dynamically -// typed, so you don't need to specify type. Assignment uses a single `=` -// character. +// Variáveis são declarados com a palavra-chave `var`. O Javascript é +// dinâmicamente tipado, portanto você não precisa especificar o tipo. +// Atribuições usam um simples caracter de `=`. var someVar = 5; -// if you leave the var keyword off, you won't get an error... +// se você deixar de colocar a palavra-chave var, você não receber um erro... someOtherVar = 10; -// ...but your variable will be created in the global scope, not in the scope -// you defined it in. +// ...mas sua variável será criada no escopo global, não no escopo em que você +// definiu ela. -// Variables declared without being assigned to are set to undefined. +// Variáveis declaradas sem receberem um valor são definidas como `undefined`. var someThirdVar; // = undefined -// There's shorthand for performing math operations on variables: -someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10; // now someVar is 100 +// Existe um shorthad para operações matemáticas em variáveis: +someVar += 5; // equivalente a someVar = someVar + 5; someVar é 10 agora +someVar *= 10; // agora someVar é 100 -// and an even-shorter-hand for adding or subtracting 1 +// e um para adição e subtração de 1 someVar++; // now someVar is 101 someVar--; // back to 100 -// Arrays are ordered lists of values, of any type. -var myArray = ["Hello", 45, true]; +// Arrays são listas ordenadas de valores, de qualquer tipo. +var myArray = ["Olá", 45, true]; -// Their members can be accessed using the square-brackets subscript syntax. -// Array indices start at zero. +// Seus membros podem ser acessados usando a sintaxe de colchetes. +// O indíce de um Array começa pelo 0. myArray[1]; // = 45 -// Arrays are mutable and of variable length. +// Arrays são mutáveis e de tamanho variável. myArray.push("World"); myArray.length; // = 4 -// Add/Modify at specific index +// Adicionar/modificar em um índice específico myArray[3] = "Hello"; -// JavaScript's objects are equivalent to "dictionaries" or "maps" in other -// languages: an unordered collection of key-value pairs. -var myObj = {key1: "Hello", key2: "World"}; +// Objetos de Javascript são equivalentes aos dicionários ou maps de outras +// linguagens: uma coleção não ordenada de pares chave-valor. +var myObj = {chave1: "Olá", chave2: "Mundo"}; -// Keys are strings, but quotes aren't required if they're a valid -// JavaScript identifier. Values can be any type. +// Chaves são strings, mas as aspas não são necessárias se elas são +// identificadores válidos no Javascript. Valores podem ser de qualquer tipo. var myObj = {myKey: "myValue", "my other key": 4}; -// Object attributes can also be accessed using the subscript syntax, +// Atributos de objetos também podem ser acessados com a sintaxe de colchetes. myObj["my other key"]; // = 4 -// ... or using the dot syntax, provided the key is a valid identifier. +// ... ou usando a sintaxe de ponto, passando a chave que é um identificador +// válido. myObj.myKey; // = "myValue" -// Objects are mutable; values can be changed and new keys added. +// Objetos são mutáveis, valores podem ser modificados e novas chaves +// adicionadas. myObj.myThirdKey = true; -// If you try to access a value that's not yet set, you'll get undefined. +// Se você tentar acessar um valor que não foi determinado ainda, você irá +// receber `undefined`. myObj.myFourthKey; // = undefined /////////////////////////////////// -- cgit v1.2.3 From 32caaabe05e2d920c4be42c278e2e6d51ddea6ed Mon Sep 17 00:00:00 2001 From: willianjusten Date: Fri, 2 Oct 2015 01:05:31 -0300 Subject: =?UTF-8?q?[javascript=20pt-br]=20:=203.=20L=C3=B3gica=20e=20Estru?= =?UTF-8?q?turas=20de=20Controle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/javascript-pt.html.markdown | 42 ++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 6667a77d..14d82146 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -194,52 +194,54 @@ myObj.myThirdKey = true; myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Logic and Control Structures +// 3. Lógica e Estruturas de Controle -// The syntax for this section is almost identical to Java's. +// A sintaxe para essa seção é quase idêntica a maioria das linguagens. // The `if` structure works as you'd expect. -var count = 1; +// A estrutura `if` funciona como deveria ser. +var count = 1 if (count == 3){ - // evaluated if count is 3 + // executa se count é 3 } else if (count == 4){ - // evaluated if count is 4 + // executa se count é 4 } else { - // evaluated if it's not either 3 or 4 + // executa se count não é 3 nem 4 } -// As does `while`. +// Como se faz `while`. while (true){ - // An infinite loop! + // Um loop infinito! } -// Do-while loops are like while loops, except they always run at least once. -var input; +// Os loops do-while são como os loops de while, exceto quando eles sempre +// executam pelo menos uma vez. do { input = getInput(); } while (!isValid(input)) // The `for` loop is the same as C and Java: // initialisation; continue condition; iteration. + +// O loop `for` é o mesmo de C e Java: +// inicialização, condição de continuar; iteração for (var i = 0; i < 5; i++){ - // will run 5 times + // vai rodar cinco vezes } -// && is logical and, || is logical or +// && é o `e` lógico , || é o `ou` lógico if (house.size == "big" && house.colour == "blue"){ house.contains = "bear"; } -if (colour == "red" || colour == "blue"){ - // colour is either red or blue +if (cor == "red" || cor == "blue"){ + // cor é vermelha OU azul } -// && and || "short circuit", which is useful for setting default values. -var name = otherName || "default"; - +// && e || "pequeno circuito", é útil para determinar valores padrões. +var name = otherName || "padrão"; -// The `switch` statement checks for equality with `===`. -// use 'break' after each case -// or the cases after the correct one will be executed too. +// O `switch` checa pela igualdade com `===`. +// Use `break` após cada `case` grade = 'B'; switch (grade) { case 'A': -- cgit v1.2.3 From 2534c71c4f5cc8f6b806914857da11b8ae89f45d Mon Sep 17 00:00:00 2001 From: willianjusten Date: Fri, 2 Oct 2015 01:23:46 -0300 Subject: =?UTF-8?q?[javascript=20pt-br]=20:=20Fun=C3=A7=C3=B5es,=20Escopos?= =?UTF-8?q?=20e=20Closures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/javascript-pt.html.markdown | 79 +++++++++++++++++++++------------------ 1 file changed, 42 insertions(+), 37 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 14d82146..08448d0b 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -209,7 +209,7 @@ if (count == 3){ // executa se count não é 3 nem 4 } -// Como se faz `while`. +// Como se faz um `while`. while (true){ // Um loop infinito! } @@ -224,7 +224,7 @@ do { // initialisation; continue condition; iteration. // O loop `for` é o mesmo de C e Java: -// inicialização, condição de continuar; iteração +// inicialização, condição para continuar; iteração for (var i = 0; i < 5; i++){ // vai rodar cinco vezes } @@ -260,79 +260,84 @@ switch (grade) { /////////////////////////////////// -// 4. Functions, Scope and Closures +// 4. Funções, Escopos e Closures -// JavaScript functions are declared with the `function` keyword. +// Funções Javascript são declaradas com a palavra-chave `function`. function myFunction(thing){ return thing.toUpperCase(); } myFunction("foo"); // = "FOO" -// Note that the value to be returned must start on the same line as the -// `return` keyword, otherwise you'll always return `undefined` due to -// automatic semicolon insertion. Watch out for this when using Allman style. +// Repare que o valor a ser retornado deve começar na mesma linha que +// a palavra-chave `return`, senão você sempre irá retornar `undefined` +// visto que o ponto-e-vírgula é inserido automáticamente nas quebras de +// linha. Preste atenção quando usar o estilo Allman. function myFunction() { - return // <- semicolon automatically inserted here + return // <- ponto-e-vírgula adicionado automaticamente aqui { thisIsAn: 'object literal' } } myFunction(); // = undefined -// JavaScript functions are first class objects, so they can be reassigned to -// different variable names and passed to other functions as arguments - for -// example, when supplying an event handler: +// Funções Javascript são objetos de primeira classe, portanto elas podem +// ser atribuídas a nomes de variáveis e serem passadas para outras funções +// como argumentos - por exemplo, quando criamos um manipulador de eventos: function myFunction(){ - // this code will be called in 5 seconds' time + // este código será chamado em 5 segundos } setTimeout(myFunction, 5000); -// Note: setTimeout isn't part of the JS language, but is provided by browsers -// and Node.js. +// Nota: `setTimeout` não é parte da linguagem Javascript, mas é provido pelos +// browsers e o Node.js. -// Function objects don't even have to be declared with a name - you can write -// an anonymous function definition directly into the arguments of another. +// Objetos de funções não precisam nem serem declarados com nome - você pode +// escrever a definição de uma função anônima diretamente nos argumentos de +// outra função. setTimeout(function(){ - // this code will be called in 5 seconds' time + // este código será chamado em 5 segundos }, 5000); -// JavaScript has function scope; functions get their own scope but other blocks -// do not. +// O Javascript tem escopo de função; as funções tem seu próprio escopo, +// mas outros blocos não. if (true){ var i = 5; } -i; // = 5 - not undefined as you'd expect in a block-scoped language +i; // = 5 - não `undefined` como você esperaria numa linguagem de blogo-escopo -// This has led to a common pattern of "immediately-executing anonymous -// functions", which prevent temporary variables from leaking into the global -// scope. +// Isso levou a padrão comum chamado de IIFE (Imediately Invoked Function +// Expression) ou (Expressão de Função Invocada Imediatamente), que previne +// que variáveis temporárias vazem para o escopo global. (function(){ var temporary = 5; - // We can access the global scope by assiging to the "global object", which - // in a web browser is always `window`. The global object may have a - // different name in non-browser environments such as Node.js. + // Nós podemos acessar o escopo global definindo o "objeto global", que + // no browser vai ser sempre `window`. O objeto global pode ter um nome + // diferente para ambiente não-browser como o Node.js. window.permanent = 10; })(); -temporary; // raises ReferenceError +temporary; // levanta um erro de referência inexiste permanent; // = 10 -// One of JavaScript's most powerful features is closures. If a function is -// defined inside another function, the inner function has access to all the -// outer function's variables, even after the outer function exits. +// Uma das principais características do Javascript é a closure. Que é +// uma função definida dentro de outra função, a função interna pode acessar +// todas as variáveis da função externa, mesmo depois da função de fora +// finalizar sua execução. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; - // Inner functions are put in the local scope by default, as if they were - // declared with `var`. + + // Funções internas são colocadas no escopo local por padrão, assim como + // se fossem declaradas com `var`. function inner(){ alert(prompt); } setTimeout(inner, 5000); - // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will - // exit immediately, and setTimeout will call inner afterwards. However, - // because inner is "closed over" sayHelloInFiveSeconds, inner still has - // access to the `prompt` variable when it is finally called. + // `setTimeout` é assíncrono, portanto a função `sayHelloInFiveSeconds` + // vai sair imediatamente, e o `setTimeout` irá chamar a interna depois. + // Entretanto. como a interna é fechada dentro de "sayHelloInFiveSeconds", + // a interna permanece podendo acessar a variável `prompt` quando depois + // de chamada. } -sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Adam"); // Vai abrir um popup com "Hello, Adam!" em 5s /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 6651b421551ea405350c4290f4d4f159463460f9 Mon Sep 17 00:00:00 2001 From: Rizky Luthfianto Date: Fri, 2 Oct 2015 20:02:37 +0700 Subject: [xml/id] Translated XML to Indonesian (xml-id) --- id-id/xml-id.html.markdown | 129 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 id-id/xml-id.html.markdown diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown new file mode 100644 index 00000000..8e8cdf4e --- /dev/null +++ b/id-id/xml-id.html.markdown @@ -0,0 +1,129 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Rizky Luthfianto", "https://github.com/rilut"] +--- + +XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. + +Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya. + +* Sintaks XML + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +komputer.gif + + +``` + +* Dokumen yang well-formated & Validasi + +Sebuah dokumen XML disebut well-formated jika sintaksisnya benar. +Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen, +menggunakan definisi dokumen, seperti DTD dan XML Schema. + +Sebuah dokumen XML yang mengikuti definisi dokumen disebut valid, +jika sesuai dokumen itu. + +Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From a9e29ee5e3ed8f96bbf18638337a38ee862dbd05 Mon Sep 17 00:00:00 2001 From: Rizky Luthfianto Date: Fri, 2 Oct 2015 20:10:43 +0700 Subject: [xml/id] Translated JSON to Indonesian (json-id) --- id-id/json-id.html.markdown | 60 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 id-id/json-id.html.markdown diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown new file mode 100644 index 00000000..52e61449 --- /dev/null +++ b/id-id/json-id.html.markdown @@ -0,0 +1,60 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators + - ["Rizky Luthfianto", "https://github.com/rilut"] +--- + +JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, +ini adalah "Learn X in Y Minutes" yang paling singkat. + +Murninya, JSON tidak mempunyai fitur komentar, tapi kebanyakan parser akan +menerima komentar bergaya bahasa C (`//`, `/* */`). Namun, pada halaman ini, +hanya dicontohkan JSON yang 100% valid. + +```json +{ + "kunci": "nilai", + + "kunci": "harus selalu diapit tanda kutip", + "angka": 0, + "strings": "Halø, dunia. Semua karaktor unicode diperbolehkan, terumasuk \"escaping\".", + "punya tipe data boolean?": true, + "nilai kosong": null, + + "angka besar": 1.2e+100, + + "obyek": { + "komentar": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Array bisa berisi apapun.", 5], + + "obyek lainnya": { + "komentar": "Obyek-obyek JSON dapat dibuat bersarang, sangat berguna." + } + }, + + "iseng-iseng": [ + { + "sumber potassium": ["pisang"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "gaya alternatif": { + "komentar": "lihat ini!" + , "posisi tanda koma": "tak masalah. selama sebelum nilai berikutnya, valid-valid saja" + , "komentar lainnya": "betapa asyiknya" + }, + + "singkat": "Dan Anda selesai! Sekarang Anda tahu apa saja yang disediakan oleh JSON." +} +``` -- cgit v1.2.3 From 93c8348f3e25cbe2274e8762b3759c61e4375cdc Mon Sep 17 00:00:00 2001 From: Adolfo Jayme Barrientos Date: Fri, 2 Oct 2015 08:30:17 -0500 Subject: [visualbasic/es] Create Spanish translation of VB tutorial --- es-es/visualbasic-es.html.markdown | 286 +++++++++++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 es-es/visualbasic-es.html.markdown diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown new file mode 100644 index 00000000..0702c01e --- /dev/null +++ b/es-es/visualbasic-es.html.markdown @@ -0,0 +1,286 @@ +--- +language: Visual Basic +contributors: + - ["Brian Martin", "http://brianmartin.biz"] +translators: + - ["Adolfo Jayme Barrientos", "https://github.com/fitojb"] +author: Brian Martin +author_url: http://brianmartin.biz +filename: learnvisualbasic-es.vb +lang: es-es +--- + +```vb +Module Module1 + + Sub Main() + ' Un vistazo rápido a las aplicaciones de consola de Visual Basic antes + ' de que profundicemos en el tema. + ' El apóstrofo inicia una línea de comentario. + ' Para explorar este tutorial dentro del Compilador de Visual Basic, + ' he creado un sistema de navegación. + ' Dicho sistema se explicará a medida que avancemos en este + ' tutorial; gradualmente entenderás lo que significa todo. + Console.Title = ("Aprende X en Y minutos") + Console.WriteLine("NAVEGACIÓN") 'Mostrar + Console.WriteLine("") + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine("1. Salida «Hola, mundo»") + Console.WriteLine("2. Entrada «Hola, mundo»") + Console.WriteLine("3. Calcular números enteros") + Console.WriteLine("4. Calcular números decimales") + Console.WriteLine("5. Una calculadora funcional") + Console.WriteLine("6. Uso de bucles «Do While»") + Console.WriteLine("7. Uso de bucles «For While»") + Console.WriteLine("8. Declaraciones condicionales") + Console.WriteLine("9. Selecciona una bebida") + Console.WriteLine("50. Acerca de") + Console.WriteLine("Elige un número de la lista anterior") + Dim selection As String = Console.ReadLine + Select Case selection + Case "1" 'Salida «hola, mundo» + Console.Clear() 'Limpia la consola y abre la subrutina privada + SalidaHolaMundo() 'Abre la subrutina privada nombrada + Case "2" 'Entrada «hola, mundo» + Console.Clear() + EntradaHolaMundo() + Case "3" 'Calcular números enteros + Console.Clear() + CalcularNumerosEnteros() + Case "4" 'Calcular números decimales + Console.Clear() + CalcularNumerosDecimales() + Case "5" 'Una calculadora funcional + Console.Clear() + CalculadoraFuncional() + Case "6" 'Uso de bucles «Do While» + Console.Clear() + UsoBuclesDoWhile() + Case "7" 'Uso de bucles «For While» + Console.Clear() + UsoBuclesFor() + Case "8" 'Declaraciones condicionales + Console.Clear() + DeclaracionCondicional() + Case "9" 'Declaración «If/Else» + Console.Clear() + DeclaracionIfElse() 'Selecciona una bebida + Case "50" 'Cuadro de mensaje «Acerca de» + Console.Clear() + Console.Title = ("Aprende X en Y minutos :: Acerca de") + MsgBox("Tutorial escrito por Brian Martin (@BrianMartinn") + Console.Clear() + Main() + Console.ReadLine() + + End Select + End Sub + + 'Uno - He usado números para guiarme por el sistema de navegación anterior + 'cuando regrese posteriormente a implementarlo. + + 'Usamos subrutinas privadas para separar distintas secciones del programa. + Private Sub SalidaHolaMundo() + 'Título de la aplicación de consola + Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos" + 'Usa Console.Write("") o Console.WriteLine("") para mostrar salidas. + 'Seguido por Console.Read(), o bien, Console.Readline() + 'Console.ReadLine() muestra la salida en la consola. + Console.WriteLine("Hola, mundo") + Console.ReadLine() + End Sub + + 'Dos + Private Sub EntradaHolaMundo() + Console.Title = "«Hola, mundo, soy...» | Aprende X en Y minutos" + ' Variables + ' Los datos que introduzca un usuario deben almacenarse. + ' Las variables también empiezan por Dim y terminan por As VariableType. + + ' En este tutorial queremos conocer tu nombre y hacer que el programa + ' responda a este. + Dim nombredeusuario As String + 'Usamos «string» porque es una variable basada en texto. + Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario. + nombredeusuario = Console.ReadLine() 'Almacenar nombre del usuario. + Console.WriteLine("Hola, " + nombredeusuario) 'La salida es Hola, nombre + Console.ReadLine() 'Muestra lo anterior. + 'El código anterior te hará una pregunta y mostrará la respuesta. + 'Entre otras variables está Integer, la cual usaremos para números enteros. + End Sub + + 'Tres + Private Sub CalcularNumerosEnteros() + Console.Title = "Calcular números enteros | Aprende X en Y minutos" + Console.Write("Primer número: ") 'Escribe un núm. entero, 1, 2, 104, etc + Dim a As Integer = Console.ReadLine() + Console.Write("Segundo número: ") 'Escribe otro número entero. + Dim b As Integer = Console.ReadLine() + Dim c As Integer = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Lo anterior es una calculadora sencilla + End Sub + + 'Cuatro + Private Sub CalcularNumerosDecimales() + Console.Title = "Calcular con tipo doble | Aprende X en Y minutos" + 'Por supuesto, nos gustaría sumar decimales. + 'Por ello podríamos cambiar del tipo Integer al Double. + + 'Escribe un número fraccionario, 1.2, 2.4, 50.1, 104.9 etc + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") 'Escribe el segundo número. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Este programa puede sumar 1.1 y 2.2 + End Sub + + 'Cinco + Private Sub CalculadoraFuncional() + Console.Title = "La calculadora funcional | Aprende X en Y minutos" + 'Pero si quieres que la calculadora reste, divida, multiplique y + 'sume. + 'Copia y pega lo anterior. + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + 'Mediante las líneas siguientes podremos restar, + 'multiplicar y dividir los valores a y b + Console.Write(a.ToString() + " + " + b.ToString()) + 'Queremos dar un margen izquierdo de 3 espacios a los resultados. + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) + Console.ReadLine() + + End Sub + + 'Seis + Private Sub UsoBuclesDoWhile() + 'Igual que la subrutina privada anterior + 'Esta vez preguntaremos al usuario si quiere continuar (¿sí o no?) + 'Usamos el bucle Do While porque no sabemos si el usuario quiere + 'usar el programa más de una vez. + Console.Title = "Uso de bucles «Do While» | Aprende X en Y minutos" + Dim respuesta As String 'Usamos la variable «String» porque la resp. es texto + Do 'Comenzamos el programa con + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) + Console.ReadLine() + 'Preguntar si el usuario quiere continuar. Desafortunadamente, + 'distingue entre mayúsculas y minúsculas. + Console.Write("¿Quieres continuar? (s / n)") + 'El programa toma la variable, la muestra y comienza de nuevo. + respuesta = Console.ReadLine + 'La orden que hará funcionar esta variable es en este caso «s» + Loop While respuesta = "s" + + End Sub + + 'Siete + Private Sub UsoBuclesFor() + 'A veces el programa debe ejecutarse solo una vez. + 'En este programa contaremos a partir de 10. + + Console.Title = "Uso de bucles «For» | Aprende X en Y minutos" + 'Declarar Variable y desde qué número debe contar en Step -1, + 'Step -2, Step -3, etc. + For i As Integer = 10 To 0 Step -1 + Console.WriteLine(i.ToString) 'Muestra el valor del contador + Next i 'Calcular el valor nuevo + Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!! + Console.ReadLine() '¡¡ZAS!! - Quizá me he emocionado bastante :) + End Sub + + 'Ocho + Private Sub DeclaracionCondicional() + Console.Title = "Declaraciones condicionales | Aprende X en Y minutos" + Dim nombredeUsuario As String = Console.ReadLine + Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario. + nombredeUsuario = Console.ReadLine() 'Almacena el nombre de usuario. + If nombredeUsuario = "Adam" Then + Console.WriteLine("Hola, Adam") + Console.WriteLine("Gracias por crear este útil sitio web") + Console.ReadLine() + Else + Console.WriteLine("Hola, " + nombredeUsuario) + Console.WriteLine("¿Has visitado www.learnxinyminutes.com?") + Console.ReadLine() 'Termina y muestra la declaración anterior. + End If + End Sub + + 'Nueve + Private Sub DeclaracionIfElse() + Console.Title = "Declaración «If / Else» | Aprende X en Y minutos" + 'A veces es importante considerar más de dos alternativas. + 'A veces, algunas de estas son mejores. + 'Cuando esto sucede, necesitaríamos más de una declaración «if». + 'Una declaración «if» es adecuada para máquinas expendedoras. + 'En las que el usuario escribe un código (A1, A2, A3) para elegir. + 'Pueden combinarse todas las elecciones en una sola declaración «if». + + Dim seleccion As String = Console.ReadLine 'Valor de la selección + Console.WriteLine("A1. para 7Up") + Console.WriteLine("A2. para Fanta") + Console.WriteLine("A3. para Dr. Pepper") + Console.WriteLine("A4. para Coca-Cola") + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") + Console.ReadLine() + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("coca-cola") + Console.ReadLine() + Else + Console.WriteLine("Selecciona un producto") + Console.ReadLine() + End If + + End Sub + +End Module + +``` + +## Referencias + +Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad. + +He creado un tutorial de Visual Basic más exhaustivo para quienes quieran saber más. + +Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa. -- cgit v1.2.3 From acc9a73c018a28a9c8ead7b108dd1fdfee7a797b Mon Sep 17 00:00:00 2001 From: ksami Date: Fri, 2 Oct 2015 22:08:27 +0800 Subject: [bash/en] Improved descriptions --- bash.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 08182c2c..d4f3d424 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -51,7 +51,7 @@ echo $Variable echo "$Variable" echo '$Variable' # When you use the variable itself — assign it, export it, or else — you write -# its name without $. If you want to use variable's value, you should use $. +# its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! # String substitution in variables @@ -70,11 +70,11 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # Builtin variables: # There are some useful builtin variables, like -echo "Last program return value: $?" +echo "Last program's return value: $?" echo "Script's PID: $$" -echo "Number of arguments: $#" -echo "Scripts arguments: $@" -echo "Scripts arguments separated in different variables: $1 $2..." +echo "Number of arguments passed to script: $#" +echo "All arguments passed to script: $@" +echo "Script's arguments separated into different variables: $1 $2..." # Reading a value from input: echo "What's your name?" @@ -108,8 +108,8 @@ fi # Expressions are denoted with the following format: echo $(( 10 + 5 )) -# Unlike other programming languages, bash is a shell — so it works in a context -# of current directory. You can list files and directories in the current +# Unlike other programming languages, bash is a shell so it works in the context +# of a current directory. You can list files and directories in the current # directory with the ls command: ls -- cgit v1.2.3 From c0b09da46f93bc1b59231c9ebd2832198bc85fcb Mon Sep 17 00:00:00 2001 From: Jesus Tinoco Date: Fri, 2 Oct 2015 16:11:23 +0200 Subject: Fixing typo in julia-es.html.markdown --- es-es/julia-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index bf035edf..e4181609 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -733,7 +733,7 @@ end # Esto significa que se construyen a partir de muchos métodos más pequeños. # Cada constructor de Leon es un método de la función genérica Leon. -# Por ejemplo, vamos a hacer métodos para para Leon, Pantera, y Tigre de una +# Por ejemplo, vamos a hacer métodos para Leon, Pantera, y Tigre de una # función genérica maullar: # acceso utilizando notación de puntos -- cgit v1.2.3 From ae86e4ebabb0c78c1bd8052e6ab5916446ef39c2 Mon Sep 17 00:00:00 2001 From: Alva Connor Waters Date: Fri, 2 Oct 2015 15:19:38 +0000 Subject: Clarify character literals --- c++.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 8a7f5a59..1cf5508a 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -53,11 +53,11 @@ int main(int argc, char** argv) // However, C++ varies in some of the following ways: -// In C++, character literals are one byte. -sizeof('c') == 1 +// In C++, character literals are chars +sizeof('c') == sizeof(char) == 1 -// In C, character literals are the same size as ints. -sizeof('c') == sizeof(10) +// In C, character literals are ints +sizeof('c') == sizeof(int) // C++ has strict prototyping -- cgit v1.2.3 From 455afa3a7bf59fc272f3439825da55659765eec0 Mon Sep 17 00:00:00 2001 From: Alva Connor Waters Date: Fri, 2 Oct 2015 15:55:05 +0000 Subject: More explanation on virtual destructors --- c++.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 1cf5508a..b59635f5 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -349,7 +349,10 @@ public: // These are called when an object is deleted or falls out of scope. // This enables powerful paradigms such as RAII // (see below) - // Destructors must be virtual to allow classes to be derived from this one. + // Destructors should be virtual if a class is to be derived from; + // if they are not virtual, then any resources allocated using RAII in + // the derived class will not be released if it destroyed through a + // base-class reference or pointer. virtual ~Dog(); }; // A semicolon must follow the class definition. -- cgit v1.2.3 From 12286a4b78f82bde3907d4bf348e20c12dd6d46f Mon Sep 17 00:00:00 2001 From: Alva Connor Waters Date: Fri, 2 Oct 2015 16:00:13 +0000 Subject: Misc. typos and formatting --- c++.html.markdown | 72 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index b59635f5..e5eceac1 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -159,9 +159,9 @@ void foo() int main() { - // Includes all symbols from `namesapce Second` into the current scope. Note - // that simply `foo()` no longer works, since it is now ambiguous whether - // we're calling the `foo` in `namespace Second` or the top level. + // Includes all symbols from namespace Second into the current scope. Note + // that simply foo() no longer works, since it is now ambiguous whether + // we're calling the foo in namespace Second or the top level. using namespace Second; Second::foo(); // prints "This is Second::foo" @@ -256,7 +256,7 @@ string tempObjectFun() { ... } string retVal = tempObjectFun(); // What happens in the second line is actually: -// - a string object is returned from `tempObjectFun` +// - a string object is returned from tempObjectFun // - a new string is constructed with the returned object as arugment to the // constructor // - the returned object is destroyed @@ -268,15 +268,15 @@ string retVal = tempObjectFun(); // code: foo(bar(tempObjectFun())) -// assuming `foo` and `bar` exist, the object returned from `tempObjectFun` is -// passed to `bar`, and it is destroyed before `foo` is called. +// assuming foo and bar exist, the object returned from tempObjectFun is +// passed to bar, and it is destroyed before foo is called. // Now back to references. The exception to the "at the end of the enclosing // expression" rule is if a temporary object is bound to a const reference, in // which case its life gets extended to the current scope: void constReferenceTempObjectFun() { - // `constRef` gets the temporary object, and it is valid until the end of this + // constRef gets the temporary object, and it is valid until the end of this // function. const string& constRef = tempObjectFun(); ... @@ -301,7 +301,7 @@ basic_string(basic_string&& other); // Idea being if we are constructing a new string from a temporary object (which // is going to be destroyed soon anyway), we can have a more efficient // constructor that "salvages" parts of that temporary string. You will see this -// concept referred to as the move semantic. +// concept referred to as "move semantics". ////////////////////////////////////////// // Classes and object-oriented programming @@ -349,10 +349,10 @@ public: // These are called when an object is deleted or falls out of scope. // This enables powerful paradigms such as RAII // (see below) - // Destructors should be virtual if a class is to be derived from; - // if they are not virtual, then any resources allocated using RAII in - // the derived class will not be released if it destroyed through a - // base-class reference or pointer. + // The destructor should be virtual if a class is to be derived from; + // if it is not virtual, then the derived class' destructor will + // not be called if the object is destroyed through a base-class reference + // or pointer. virtual ~Dog(); }; // A semicolon must follow the class definition. @@ -495,9 +495,10 @@ int main () { ///////////////////// // Templates in C++ are mostly used for generic programming, though they are -// much more powerful than generics constructs in other languages. It also -// supports explicit and partial specialization, functional-style type classes, -// and also it's Turing-complete. +// much more powerful than generic constructs in other languages. They also +// support explicit and partial specialization and functional-style type +// classes; in fact, they are a Turing-complete functional language embedded +// in C++! // We start with the kind of generic programming you might be familiar with. To // define a class or function that takes a type parameter: @@ -509,7 +510,7 @@ public: }; // During compilation, the compiler actually generates copies of each template -// with parameters substituted, and so the full definition of the class must be +// with parameters substituted, so the full definition of the class must be // present at each invocation. This is why you will see template classes defined // entirely in header files. @@ -523,13 +524,13 @@ intBox.insert(123); Box > boxOfBox; boxOfBox.insert(intBox); -// Up until C++11, you must place a space between the two '>'s, otherwise '>>' -// will be parsed as the right shift operator. +// Until C++11, you had to place a space between the two '>'s, otherwise '>>' +// would be parsed as the right shift operator. // You will sometimes see // template -// instead. The 'class' keyword and 'typename' keyword are _mostly_ -// interchangeable in this case. For full explanation, see +// instead. The 'class' keyword and 'typename' keywords are _mostly_ +// interchangeable in this case. For the full explanation, see // http://en.wikipedia.org/wiki/Typename // (yes, that keyword has its own Wikipedia page). @@ -585,12 +586,15 @@ try { // Do not allocate exceptions on the heap using _new_. throw std::runtime_error("A problem occurred"); } + // Catch exceptions by const reference if they are objects catch (const std::exception& ex) { - std::cout << ex.what(); + std::cout << ex.what(); +} + // Catches any exception not caught by previous _catch_ blocks -} catch (...) +catch (...) { std::cout << "Unknown exception caught"; throw; // Re-throws the exception @@ -600,8 +604,8 @@ catch (const std::exception& ex) // RAII /////// -// RAII stands for Resource Allocation Is Initialization. -// It is often considered the most powerful paradigm in C++, +// RAII stands for "Resource Acquisition Is Initialization". +// It is often considered the most powerful paradigm in C++ // and is the simple concept that a constructor for an object // acquires that object's resources and the destructor releases them. @@ -622,9 +626,9 @@ void doSomethingWithAFile(const char* filename) // Unfortunately, things are quickly complicated by error handling. // Suppose fopen can fail, and that doSomethingWithTheFile and // doSomethingElseWithIt return error codes if they fail. -// (Exceptions are the preferred way of handling failure, -// but some programmers, especially those with a C background, -// disagree on the utility of exceptions). +// (Exceptions are the preferred way of handling failure, +// but some programmers, especially those with a C background, +// disagree on the utility of exceptions). // We now have to check each call for failure and close the file handle // if a problem occurred. bool doSomethingWithAFile(const char* filename) @@ -744,15 +748,17 @@ class FooSub : public Foo { // 0 == false == NULL (most of the time)! bool* pt = new bool; -*pt = 0; // Sets the value points by 'pt' to false. +*pt = 0; // Sets the value points by 'pt' to false. pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings. // nullptr is supposed to fix some of that issue: int* pt2 = new int; -*pt2 = nullptr; // Doesn't compile +*pt2 = nullptr; // Doesn't compile pt2 = nullptr; // Sets pt2 to null. -// But somehow 'bool' type is an exception (this is to make `if (ptr)` compile). +// There is an exception made for bools. +// This is to allow you to test for null pointers with if(!ptr), +// but as a consequence you can assign nullptr to a bool directly! *pt = nullptr; // This still compiles, even though '*pt' is a bool! @@ -779,12 +785,12 @@ vector v; for (int i = 0; i < 10; ++i) v.push_back(Foo()); -// Following line sets size of v to 0, but destructors don't get called, +// Following line sets size of v to 0, but destructors don't get called // and resources aren't released! v.empty(); -v.push_back(Foo()); // New value is copied into the first Foo we inserted in the loop. +v.push_back(Foo()); // New value is copied into the first Foo we inserted -// Truly destroys all values in v. See section about temporary object for +// Truly destroys all values in v. See section about temporary objects for // explanation of why this works. v.swap(vector()); -- cgit v1.2.3 From c4b8281ceeed59ddfa003cc95e40944735d1c910 Mon Sep 17 00:00:00 2001 From: Alva Connor Waters Date: Fri, 2 Oct 2015 16:19:29 +0000 Subject: Add to contributors --- c++.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/c++.html.markdown b/c++.html.markdown index e5eceac1..4acc1b9d 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] lang: en --- -- cgit v1.2.3 From 0ad95b119d1f0135bf3a9fd55cebf24d63692c11 Mon Sep 17 00:00:00 2001 From: Michele Orselli Date: Fri, 2 Oct 2015 18:24:45 +0200 Subject: adds some new php operators --- php.html.markdown | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 52ea2a95..53be5391 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -215,6 +215,14 @@ assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); +// spaceship operator since PHP 7 +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + // Variables can be converted between types, depending on their usage. $integer = 1; @@ -264,6 +272,18 @@ if (false) { // ternary operator print (false ? 'Does not get printed' : 'Does'); +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + $x = 0; if ($x === '0') { print 'Does not print'; -- cgit v1.2.3 From 57ea4af17c7ab17e9c32096c2579e0a985e44781 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 2 Oct 2015 10:31:25 -0600 Subject: Updated info for Chapel 1.12.0 --- chapel.html.markdown | 196 +++++++++++++++++++++++++-------------------------- 1 file changed, 98 insertions(+), 98 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 8a88a652..1d0abe6e 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -27,7 +27,7 @@ writeln( "There are ", 3, " commas (\",\") in this line of code" ); stdout.writeln( "This goes to standard output, just like plain writeln() does"); stderr.writeln( "This goes to standard error" ); -// Variables don't have to be explicitly typed as long as +// Variables don't have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; @@ -65,9 +65,9 @@ const almostPi: real = 22.0/7.0; param compileTimeConst: int = 16; // The config modifier allows values to be set at the command line -// and is much easier than the usual getOpts debacle +// and is much easier than the usual getOpts debacle // config vars and consts can be changed through the command line at run time -config var varCmdLineArg: int = -123; +config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; // Set with --VarName=Value or --VarName Value at run time @@ -119,9 +119,9 @@ a *= thatInt; // Times-equals ( a = a * thatInt; ) b &&= thatBool; // Logical-and-equals ( b = b && thatBool; ) a <<= 3; // Left-bit-shift-equals ( a = a << 10; ) // and many, many more. -// Unlike other C family languages there are no +// Unlike other C family languages there are no // pre/post-increment/decrement operators like -// ++j, --j, j++, j-- +// ++j, --j, j++, j-- // Swap operator var old_this = thisInt; @@ -155,7 +155,7 @@ writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); // Type aliasing type chroma = int; // Type of a single hue -type RGBColor = 3*chroma; // Type representing a full color +type RGBColor = 3*chroma; // Type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); @@ -198,7 +198,7 @@ select( inputOption ){ writeln( "Chose 'otherOption'" ); writeln( "Which has a body" ); } - otherwise { + otherwise { writeln( "Any other Input" ); writeln( "the otherwise case doesn't need a do if the body is one line" ); } @@ -221,7 +221,7 @@ do{ writeln( jSum ); // For loops are much like those in python in that they iterate over a range. -// Ranges themselves are types, and can be stuffed into variables +// Ranges themselves are types, and can be stuffed into variables // (more about that later) for i in 1..10 do write( i , ", ") ; writeln( ); @@ -240,28 +240,28 @@ for x in 1..10 { } // Ranges and Domains -// For-loops and arrays both use ranges and domains to +// For-loops and arrays both use ranges and domains to // define an index set that can be iterated over. // Ranges are single dimensional -// Domains can be multi-dimensional and can +// Domains can be multi-dimensional and can // represent indices of different types as well. // They are first-class citizen types, and can be assigned into variables var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 var rangeThistoThat: range = thisInt..thatInt; // using variables -var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices +var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices -// Ranges can be unbounded -var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; +// Ranges can be unbounded +var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... -// Note: the range(boundedType= ... ) is only +// Note: the range(boundedType= ... ) is only // necessary if we explicitly type the variable var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 // Ranges can be strided using the 'by' operator. var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 -// Note: the range(stridable=true) is only +// Note: the range(stridable=true) is only // necessary if we explicitly type the variable // Use by to create a reverse range @@ -275,9 +275,9 @@ var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5 writeln( rangeCountBy ); // Can query properties of the range -// Print the first index, last index, number of indices, +// Print the first index, last index, number of indices, // stride, and ask if 2 is include in the range -writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length, +writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length, rangeCountBy.stride, rangeCountBy.member( 2 ) ) ); for i in rangeCountBy{ @@ -309,7 +309,7 @@ stringSet += "b"; stringSet += "c"; stringSet += "a"; // Redundant add "a" stringSet -= "c"; // Remove "c" -writeln( stringSet ); +writeln( stringSet ); // Both ranges and domains can be sliced to produce a range or domain with the // intersection of indices @@ -332,13 +332,13 @@ var intArray2: [{1..10}] int; //equivalent for i in 1..10 do intArray[i] = -i; writeln( intArray ); -// We cannot access intArray[0] because it exists outside +// We cannot access intArray[0] because it exists outside // of the index set, {1..10}, we defined it to have. // intArray[11] is illegal for the same reason. var realDomain: domain(2) = {1..5,1..7}; var realArray: [realDomain] real; -var realArray2: [1..5,1..7] real; // Equivalent +var realArray2: [1..5,1..7] real; // Equivalent var realArray3: [{1..5,1..7}] real; // Equivalent for i in 1..5 { @@ -350,7 +350,7 @@ for i in 1..5 { } // Arrays have domains as members that we can iterate over -for idx in realArray.domain { // Again, idx is a 2*int tuple +for idx in realArray.domain { // Again, idx is a 2*int tuple realArray[idx] = 1 / realArray[idx[1],idx[2]]; // Access by tuple and list } @@ -377,7 +377,7 @@ var thatArray : [{0..5}] int; // Simply assign one to the other. // This copies thisArray into thatArray, instead of just creating a reference. // Modifying thisArray does not also modify thatArray. -thatArray = thisArray; +thatArray = thisArray; thatArray[1] = -1; writeln( (thisArray, thatArray) ); @@ -389,12 +389,12 @@ writeln( (thisArray, thatArray) ); var thisPlusThat = thisArray + thatArray; writeln( thisPlusThat ); -// Arrays and loops can also be expressions, where loop +// Arrays and loops can also be expressions, where loop // body's expression is the result of each iteration. var arrayFromLoop = for i in 1..10 do i; writeln( arrayFromLoop ); -// An expression can result in nothing, +// An expression can result in nothing, // such as when filtering with an if-expression var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i; @@ -407,7 +407,7 @@ var evensOrFivesAgain = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; // Or over the values of the array arrayFromLoop = [ value in arrayFromLoop ] value + 1; -// Note: this notation can get somewhat tricky. For example: +// Note: this notation can get somewhat tricky. For example: // evensOrFives = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; // would break. // The reasons for this are explained in depth when discussing zipped iterators. @@ -431,7 +431,7 @@ proc addThree( n ) { doublePrint( addThree( fibonacci( 20 ) ) ); // Can also take 'unlimited' number of parameters -proc maxOf( x ...?k ) { +proc maxOf( x ...?k ) { // x refers to a tuple of one type, with k elements var maximum = x[1]; for i in 2..k do maximum = if (maximum < x[i]) then x[i] else maximum; @@ -439,7 +439,7 @@ proc maxOf( x ...?k ) { } writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); -// The ? operator is called the query operator, and is used to take +// The ? operator is called the query operator, and is used to take // undetermined values (like tuple or array sizes, and generic types). // Taking arrays as parameters. @@ -463,7 +463,7 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// Intent modifiers on the arguments convey how +// Intent modifiers on the arguments convey how // those arguments are passed to the procedure // in: copy arg in, but not out // out: copy arg out, but not in @@ -489,18 +489,18 @@ writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) ); // Similarly we can define intents on the return type // refElement returns a reference to an element of array proc refElement( array : [?D] ?T, idx ) ref : T { - return array[ idx ]; // returns a reference to + return array[ idx ]; // returns a reference to } var myChangingArray : [1..5] int = [1,2,3,4,5]; writeln( myChangingArray ); -// Store reference to element in ref variable -ref refToElem = refElement( myChangingArray, 5 ); +// Store reference to element in ref variable +ref refToElem = refElement( myChangingArray, 5 ); writeln( refToElem ); refToElem = -2; // modify reference which modifies actual value in array writeln( refToElem ); writeln( myChangingArray ); -// This makes more practical sense for class methods where references to +// This makes more practical sense for class methods where references to // elements in a data-structure are returned via a method or iterator // We can query the type of arguments to generic procedures @@ -520,7 +520,7 @@ genericProc( 1.0+2.0i, 3.0+4.0i ); // We can also enforce a form of polymorphism with the 'where' clause // This allows the compiler to decide which function to use. -// Note: that means that all information needs to be known at compile-time. +// Note: that means that all information needs to be known at compile-time. // The param modifier on the arg is used to enforce this constraint. proc whereProc( param N : int ): void where ( N > 0 ) { @@ -534,7 +534,7 @@ proc whereProc( param N : int ): void whereProc( 10 ); whereProc( -1 ); -// whereProc( 0 ) would result in a compiler error because there +// whereProc( 0 ) would result in a compiler error because there // are no functions that satisfy the where clause's condition. // We could have defined a whereProc without a where clause that would then have // served as a catch all for all the other cases (of which there is only one). @@ -543,7 +543,7 @@ whereProc( -1 ); // We can define the unary operators: // + - ! ~ // and the binary operators: -// + - * / % ** == <= >= < > << >> & | ˆ by +// + - * / % ** == <= >= < > << >> & | ˆ by // += -= *= /= %= **= &= |= ˆ= <<= >>= <=> // Boolean exclusive or operator @@ -569,14 +569,14 @@ Note: You could break everything if you get careless with your overloads. This here will break everything. Don't do it. proc +( left: int, right: int ): int{ return left - right; -} +} */ -// Iterators are a sisters to the procedure, and almost +// Iterators are a sisters to the procedure, and almost // everything about procedures also applies to iterators -// However, instead of returning a single value, +// However, instead of returning a single value, // iterators yield many values to a loop. -// This is useful when a complicated set or order of iterations is needed but +// This is useful when a complicated set or order of iterations is needed but // allows the code defining the iterations to be separate from the loop body. iter oddsThenEvens( N: int ): int { for i in 1..N by 2 do @@ -601,15 +601,15 @@ for i in absolutelyNothing( 10 ){ writeln( "Woa there! absolutelyNothing yielded ", i ); } -// We can zipper together two or more iterators (who have the same number -// of iterations) using zip() to create a single zipped iterator, where each -// iteration of the zipped iterator yields a tuple of one value yielded +// We can zipper together two or more iterators (who have the same number +// of iterations) using zip() to create a single zipped iterator, where each +// iteration of the zipped iterator yields a tuple of one value yielded // from each iterator. // Ranges have implicit iterators -for (positive, negative) in zip( 1..5, -5..-1) do +for (positive, negative) in zip( 1..5, -5..-1) do writeln( (positive, negative) ); -// Zipper iteration is quite important in the assignment of arrays, +// Zipper iteration is quite important in the assignment of arrays, // slices of arrays, and array/loop expressions. var fromThatArray : [1..#5] int = [1,2,3,4,5]; var toThisArray : [100..#5] int; @@ -629,10 +629,10 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){ } writeln( toThisArray ); -// This is all very important in undestanding why the statement +// This is all very important in undestanding why the statement // var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; // exhibits a runtime error. -// Even though the domain of the array and the loop-expression are +// Even though the domain of the array and the loop-expression are // the same size, the body of the expression can be though of as an iterator. // Because iterators can yield nothing, that iterator yields a different number // of things than the domain of the array or loop, which is not allowed. @@ -641,8 +641,8 @@ writeln( toThisArray ); // They currently lack privatization class MyClass { // Member variables - var memberInt : int; - var memberBool : bool = true; + var memberInt : int; + var memberBool : bool = true; // Classes have default constructors that don't need to be coded (see below) // Our explicitly defined constructor @@ -659,28 +659,28 @@ class MyClass { proc setMemberInt( val: int ){ this.memberInt = val; } - + proc setMemberBool( val: bool ){ this.memberBool = val; } - proc getMemberInt( ): int{ + proc getMemberInt( ): int{ return this.memberInt; } proc getMemberBool( ): bool { return this.memberBool; } - + } - + // Construct using default constructor, using default values var myObject = new MyClass( 10 ); myObject = new MyClass( memberInt = 10 ); // Equivalent writeln( myObject.getMemberInt( ) ); // ... using our values var myDiffObject = new MyClass( -1, true ); - myDiffObject = new MyClass( memberInt = -1, + myDiffObject = new MyClass( memberInt = -1, memberBool = true ); // Equivalent writeln( myDiffObject ); @@ -689,7 +689,7 @@ var myOtherObject = new MyClass( 1.95 ); myOtherObject = new MyClass( val = 1.95 ); // Equivalent writeln( myOtherObject.getMemberInt( ) ); -// We can define an operator on our class as well but +// We can define an operator on our class as well but // the definition has to be outside the class definition proc +( A : MyClass, B : MyClass) : MyClass { return new MyClass( memberInt = A.getMemberInt( ) + B.getMemberInt( ), @@ -715,46 +715,46 @@ class GenericClass { type classType; var classDomain: domain(1); var classArray: [classDomain] classType; - + // Explicit constructor proc GenericClass( type classType, elements : int ){ this.classDomain = {1..#elements}; } - + // Copy constructor - // Note: We still have to put the type as an argument, but we can + // Note: We still have to put the type as an argument, but we can // default to the type of the other object using the query (?) operator // Further, we can take advantage of this to allow our copy constructor // to copy classes of different types and cast on the fly - proc GenericClass( other : GenericClass(?otherType), + proc GenericClass( other : GenericClass(?otherType), type classType = otherType ) { this.classDomain = other.classDomain; // Copy and cast - for idx in this.classDomain do this[ idx ] = other[ idx ] : classType; + for idx in this.classDomain do this[ idx ] = other[ idx ] : classType; } - - // Define bracket notation on a GenericClass + + // Define bracket notation on a GenericClass // object so it can behave like a normal array // i.e. objVar[ i ] or objVar( i ) proc this( i : int ) ref : classType { return this.classArray[ i ]; } - - // Define an implicit iterator for the class + + // Define an implicit iterator for the class // to yield values from the array to a loop // i.e. for i in objVar do .... iter these( ) ref : classType { for i in this.classDomain do yield this[i]; } - + } var realList = new GenericClass( real, 10 ); -// We can assign to the member array of the object using the bracket +// We can assign to the member array of the object using the bracket // notation that we defined ( proc this( i: int ){ ... } ) for i in realList.classDomain do realList[i] = i + 1.0; -// We can iterate over the values in our list with the iterator +// We can iterate over the values in our list with the iterator // we defined ( iter these( ){ ... } ) for value in realList do write( value, ", " ); writeln( ); @@ -777,23 +777,23 @@ writeln( ); module OurModule { // We can use modules inside of other modules. use Time; // Time is one of the standard modules. - + // We'll use this procedure in the parallelism section. proc countdown( seconds: int ){ for i in 1..seconds by -1 { writeln( i ); sleep( 1 ); } - } - - // Submodules of OurModule + } + + // Submodules of OurModule // It is possible to create arbitrarily deep module nests. module ChildModule { proc foo(){ writeln( "ChildModule.foo()"); } } - + module SiblingModule { proc foo(){ writeln( "SiblingModule.foo()" ); @@ -806,7 +806,7 @@ module OurModule { use OurModule; // At this point we have not used ChildModule or SiblingModule so their symbols -// (i.e. foo ) are not available to us. +// (i.e. foo ) are not available to us. // However, the module names are, and we can explicitly call foo() through them. SiblingModule.foo(); // Calls SiblingModule.foo() @@ -821,13 +821,13 @@ foo(); // Less explicit call on ChildModule.foo() proc main(){ // Parallelism - // In other languages, parallelism is typically done with + // In other languages, parallelism is typically done with // complicated libraries and strange class structure hierarchies. // Chapel has it baked right into the language. - // A begin statement will spin the body of that statement off + // A begin statement will spin the body of that statement off // into one new task. - // A sync statement will ensure that the progress of the main + // A sync statement will ensure that the progress of the main // task will not progress until the children have synced back up. sync { begin { // Start of new task's body @@ -848,7 +848,7 @@ proc main(){ printFibb( 20 ); // new task printFibb( 10 ); // new task printFibb( 5 ); // new task - { + { // This is a nested statement body and thus is a single statement // to the parent statement and is executed by a single task writeln( "this gets" ); @@ -867,26 +867,26 @@ proc main(){ // NOTE! coforall should be used only for creating tasks! // Using it to iterating over a structure is very a bad idea! - // forall loops are another parallel loop, but only create a smaller number + // forall loops are another parallel loop, but only create a smaller number // of tasks, specifically --dataParTasksPerLocale=number of task forall i in 1..100 { write( i, ", "); } writeln( ); - // Here we see that there are sections that are in order, followed by + // Here we see that there are sections that are in order, followed by // a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). // This is because each task is taking on a chunk of the range 1..10 // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens // in parallel. // Your results may depend on your machine and configuration - // For both the forall and coforall loops, the execution of the + // For both the forall and coforall loops, the execution of the // parent task will not continue until all the children sync up. // forall loops are particularly useful for parallel iteration over arrays. // Lets run an experiment to see how much faster a parallel loop is use Time; // Import the Time module to use Timer objects - var timer: Timer; + var timer: Timer; var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into // Serial Experiment @@ -906,7 +906,7 @@ proc main(){ timer.stop( ); // Stop timer writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time timer.clear( ); - // You may have noticed that (depending on how many cores you have) + // You may have noticed that (depending on how many cores you have) // that the parallel loop went faster than the serial loop // The bracket style loop-expression described @@ -926,15 +926,15 @@ proc main(){ writeln( uranium.read() ); var replaceWith = 239; - var was = uranium.exchange( replaceWith ); + var was = uranium.exchange( replaceWith ); writeln( "uranium was ", was, " but is now ", replaceWith ); var isEqualTo = 235; if ( uranium.compareExchange( isEqualTo, replaceWith ) ) { - writeln( "uranium was equal to ", isEqualTo, + writeln( "uranium was equal to ", isEqualTo, " so replaced value with ", replaceWith ); } else { - writeln( "uranium was not equal to ", isEqualTo, + writeln( "uranium was not equal to ", isEqualTo, " so value stays the same... whatever it was" ); } @@ -989,14 +989,14 @@ proc main(){ } } - // Heres an example of using atomics and a synch variable to create a + // Heres an example of using atomics and a synch variable to create a // count-down mutex (also known as a multiplexer) var count: atomic int; // our counter var lock$: sync bool; // the mutex lock count.write( 2 ); // Only let two tasks in at a time. lock$.writeXF( true ); // Set lock$ to full (unlocked) - // Note: The value doesnt actually matter, just the state + // Note: The value doesnt actually matter, just the state // (full:unlocked / empty:locked) // Also, writeXF() fills (F) the sync var regardless of its state (X) @@ -1005,10 +1005,10 @@ proc main(){ do{ lock$; // Read lock$ (wait) }while ( count.read() < 1 ); // Keep waiting until a spot opens up - + count.sub(1); // decrement the counter lock$.writeXF( true ); // Set lock$ to full (signal) - + // Actual 'work' writeln( "Task #", task, " doing work." ); sleep( 2 ); @@ -1027,13 +1027,13 @@ proc main(){ // 'maxloc' gives max value and index of the max value // Note: We have to zip the array and domain together with the zip iterator - var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, + var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, listOfValues.domain); - + writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); // Scans apply the operation incrementally and return an array of the - // value of the operation at that index as it progressed through the + // value of the operation at that index as it progressed through the // array from array.domain.low to array.domain.high var runningSumOfValues = + scan listOfValues; var maxScan = max scan listOfValues; @@ -1046,14 +1046,14 @@ Who is this tutorial for? ------------------------- This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. -It won't teach you how to develop amazingly performant code, and it's not exhaustive. +It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [module documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. ### What this tutorial is lacking: - * Exposition of the standard modules + * Exposition of the [standard modules](http://chapel.cray.com/docs/latest/modules/modules.html) * Multiple Locales (distributed memory system) * Records * Parallel iterators @@ -1061,11 +1061,11 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- -The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. +The Chapel language is still in-development (version 1.12.0), so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). -If you're really interested in the development of the compiler or contributing to the project, +If you're really interested in the development of the compiler or contributing to the project, [check out the master Github repository](https://github.com/chapel-lang/chapel). It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0). @@ -1074,10 +1074,10 @@ Installing the Compiler Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) -and its as easy as +and its as easy as - 1. `tar -xvf chapel-1.11.0.tar.gz` - 2. `cd chapel-1.11.0` + 1. `tar -xvf chapel-1.12.0.tar.gz` + 2. `cd chapel-1.12.0` 3. `make` 4. `source util/setchplenv.bash # or .sh or .csh or .fish` -- cgit v1.2.3 From f35472d8d268f3e07dbbcccf953882d425a53240 Mon Sep 17 00:00:00 2001 From: Jesse Huang Date: Fri, 2 Oct 2015 14:00:54 -0400 Subject: Removed random "r" --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 352f7349..5572e38e 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -198,7 +198,7 @@ li[::-1] # => [3, 4, 2, 1] # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] -r + # You can add lists li + other_li # => [1, 2, 3, 4, 5, 6] # Note: values for li and for other_li are not modified. -- cgit v1.2.3 From 795583521a81868ac96db53533fab4dd0c6a7285 Mon Sep 17 00:00:00 2001 From: Eric McCormick Date: Fri, 2 Oct 2015 13:50:07 -0500 Subject: fixed missing ! to create an actual comment ... which was causing everything subsequently to be rendered as code block, as the triple back tick (which should be inside a comment) wasn't being escaped as part of a comment --- markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 6d19710f..acb808ea 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -160,7 +160,7 @@ def foobar end \`\`\` -<-- The above text doesn't require indenting, plus Github will use syntax + -- cgit v1.2.3 From fb43ef2942f29ece285be3e8944c91bde6306095 Mon Sep 17 00:00:00 2001 From: Dhwani Shah Date: Fri, 2 Oct 2015 14:12:15 -0500 Subject: Added example of when string concatenation can also be helpful with combination of strings with html tags as this is important to understand when templating say output code from a database transaction. --- php.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 3fcce264..86fb14e5 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -102,6 +102,8 @@ END; // String concatenation is done with . echo 'This string ' . 'is concatenated'; +// Strings concatenation can also be combined with html elements +echo 'This string is' . '' . 'bold with strong tags ' . '.' /******************************** -- cgit v1.2.3 From 8e388cd3344b90cfdc02741359850a2352a8f9b7 Mon Sep 17 00:00:00 2001 From: Dhwani Shah Date: Fri, 2 Oct 2015 14:30:45 -0500 Subject: Added section on how to declare and initialize both single varible and multiple varibles with the same value. Important concept for large structured programs. Seperated this a little bit. --- java.html.markdown | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 928eb39f..0f5b39af 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -47,10 +47,30 @@ public class LearnJava { /////////////////////////////////////// - // Types & Variables + // Variables /////////////////////////////////////// - + + /* + * Variable Declaration + */ // Declare a variable using + int fooInt; + // Declare multiple variables of same type , , + int fooInt1, fooInt2, fooInt3; + + /* + * Variable Initialization + */ + + // Initialize a variable using = + int fooInt = 1; + // Initialize multiple variables of same type with same value , , = + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Variable types + */ // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; -- cgit v1.2.3 From 231cd629cab3553d126f8cca04a034c995c4668f Mon Sep 17 00:00:00 2001 From: Dhwani Shah Date: Fri, 2 Oct 2015 14:45:25 -0500 Subject: Update java.html.markdown --- java.html.markdown | 104 ++++++++--------------------------------------------- 1 file changed, 14 insertions(+), 90 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 0f5b39af..745741f8 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,18 +1,3 @@ ---- -language: java -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Jakukyo Friel", "http://weakish.github.io"] - - ["Madison Dickson", "http://github.com/mix3d"] - - ["Simon Morgan", "http://sjm.io/"] -filename: LearnJava.java ---- - -Java is a general-purpose, concurrent, class-based, object-oriented computer -programming language. -[Read more here.](http://docs.oracle.com/javase/tutorial/java/) - -```java // Single-line comments start with // /* Multi-line comments look like this. @@ -47,30 +32,10 @@ public class LearnJava { /////////////////////////////////////// - // Variables + // Types & Variables /////////////////////////////////////// - - /* - * Variable Declaration - */ - // Declare a variable using - int fooInt; - // Declare multiple variables of same type , , - int fooInt1, fooInt2, fooInt3; - /* - * Variable Initialization - */ - - // Initialize a variable using = - int fooInt = 1; - // Initialize multiple variables of same type with same value , , = - int fooInt1, fooInt2, fooInt3; - fooInt1 = fooInt2 = fooInt3 = 1; - - /* - * Variable types - */ + // Declare a variable using // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; @@ -437,26 +402,26 @@ class PennyFarthing extends Bicycle { // Example - Food: public interface Edible { - public void eat(); // Any class that implements this interface, must + public void eat(); // Any class that implements this interface, must // implement this method. } public interface Digestible { - public void digest(); + public void digest(); } // We can now create a class that implements both of these interfaces. public class Fruit implements Edible, Digestible { @Override - public void eat() { - // ... - } + public void eat() { + // ... + } @Override - public void digest() { - // ... - } + public void digest() { + // ... + } } // In Java, you can extend only one class, but you can implement many @@ -464,51 +429,10 @@ public class Fruit implements Edible, Digestible { public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { @Override - public void InterfaceOneMethod() { - } + public void InterfaceOneMethod() { + } @Override - public void InterfaceTwoMethod() { - } + public void InterfaceTwoMethod() { + } } -``` - -## Further Reading - -The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. - -**Official Oracle Guides**: - -* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) - -* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - -* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - -* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - -* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - -* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) - -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) - -**Online Practice and Tutorials** - -* [Learneroo.com - Learn Java](http://www.learneroo.com) - -* [Codingbat.com](http://codingbat.com/java) - - -**Books**: - -* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) - -* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From c7240369b6465f2a736cb61d1bff89c971e76929 Mon Sep 17 00:00:00 2001 From: Dhwani Shah Date: Fri, 2 Oct 2015 14:47:17 -0500 Subject: Update java.html.markdown --- java.html.markdown | 80 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 68 insertions(+), 12 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 745741f8..928eb39f 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,3 +1,18 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] +filename: LearnJava.java +--- + +Java is a general-purpose, concurrent, class-based, object-oriented computer +programming language. +[Read more here.](http://docs.oracle.com/javase/tutorial/java/) + +```java // Single-line comments start with // /* Multi-line comments look like this. @@ -402,26 +417,26 @@ class PennyFarthing extends Bicycle { // Example - Food: public interface Edible { - public void eat(); // Any class that implements this interface, must + public void eat(); // Any class that implements this interface, must // implement this method. } public interface Digestible { - public void digest(); + public void digest(); } // We can now create a class that implements both of these interfaces. public class Fruit implements Edible, Digestible { @Override - public void eat() { - // ... - } + public void eat() { + // ... + } @Override - public void digest() { - // ... - } + public void digest() { + // ... + } } // In Java, you can extend only one class, but you can implement many @@ -429,10 +444,51 @@ public class Fruit implements Edible, Digestible { public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { @Override - public void InterfaceOneMethod() { - } + public void InterfaceOneMethod() { + } @Override - public void InterfaceTwoMethod() { - } + public void InterfaceTwoMethod() { + } } +``` + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +**Official Oracle Guides**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Online Practice and Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Books**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 63793af2e955f8a8abe698c4a70809cfbff63452 Mon Sep 17 00:00:00 2001 From: Dhwani Shah Date: Fri, 2 Oct 2015 14:54:09 -0500 Subject: Added section on how to declare and initialize both single varible and multiple varibles with the same value. Important concept for large structured programs. Seperated this a little bit. --- java.html.markdown | 24 ++++++++++++++++++++++-- php.html.markdown | 4 +--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 928eb39f..1aa06570 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -47,10 +47,30 @@ public class LearnJava { /////////////////////////////////////// - // Types & Variables + // Variables /////////////////////////////////////// - + + /* + * Variable Declaration + */ // Declare a variable using + int fooInt; + // Declare multiple variables of the same type , , + int fooInt1, fooInt2, fooInt3; + + /* + * Variable Initialization + */ + + // Initialize a variable using = + int fooInt = 1; + // Initialize multiple variables of same type with same value , , = + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Variable types + */ // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; diff --git a/php.html.markdown b/php.html.markdown index 86fb14e5..1c2204fd 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -101,9 +101,7 @@ $sgl_quotes END; // String concatenation is done with . -echo 'This string ' . 'is concatenated'; -// Strings concatenation can also be combined with html elements -echo 'This string is' . '' . 'bold with strong tags ' . '.' +echo 'This string ' . 'is concatenated'; /******************************** -- cgit v1.2.3 From 4e139ae2f528a08eb47427ea790bd176092e1bf0 Mon Sep 17 00:00:00 2001 From: Dhwani Shah Date: Fri, 2 Oct 2015 14:57:39 -0500 Subject: unneeded change fixed --- php.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 1c2204fd..d4131992 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -101,7 +101,7 @@ $sgl_quotes END; // String concatenation is done with . -echo 'This string ' . 'is concatenated'; +echo 'This string ' . 'is concatenated'; /******************************** @@ -689,4 +689,4 @@ If you're coming from a language with good package management, check out [Composer](http://getcomposer.org/). For common standards, visit the PHP Framework Interoperability Group's -[PSR standards](https://github.com/php-fig/fig-standards). +[PSR standards](https://github.com/php-fig/fig-standards). \ No newline at end of file -- cgit v1.2.3 From 7184d7b61d99d2de93e19edb129ea3d17809be7f Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Fri, 2 Oct 2015 17:24:36 -0400 Subject: Changed [python3/en] Compared is and ==. Noted that tuples of length 1 require an ending comma. Discussed that keys of dictionaries have to be immutable. Added that elements of a set have to be immutable. Included an explanation of returning multiple values with tuple assignments. Added some clarifying remarks to comments. --- python3.html.markdown | 51 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..d70c5462 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] filename: learnpython3.py --- @@ -36,7 +37,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 8 - 1 # => 7 10 * 2 # => 20 -# Except division which returns floats by default +# Except division which returns floats, real numbers, by default 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. @@ -51,13 +52,13 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea # Modulo operation 7 % 3 # => 1 -# Exponentiation (x to the yth power) +# Exponentiation (x**y, x to the yth power) 2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -# Boolean values are primitives +# Boolean values are primitives (Note: the capitalization) True False @@ -95,6 +96,16 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False +# (is vs. ==) is checks if two variable refer to the same object, but == checks +# if the objects pointed to have the same values. +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal + # Strings are created with " or ' "This is a string." 'This is also a string.' @@ -145,6 +156,10 @@ bool({}) #=> False # Python has a print function print("I'm Python. Nice to meet you!") +# By default the print function also prints out a newline at the end. +# Use the optional argument end to change the end character. +print("I'm Python. Nice to meet you!", end="") + # No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores some_var = 5 @@ -191,6 +206,9 @@ li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] +# Make a one layer deep copy using slices +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] @@ -213,6 +231,12 @@ tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + # You can do most of the list operations on tuples too len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) @@ -232,6 +256,12 @@ empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} +# Note keys for dictionaries have to be immutable types. This is to ensure that +# the key can be converted to a constant hash value for quick look-ups. +# Immutable types include ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. + # Look up values with [] filled_dict["one"] # => 1 @@ -278,6 +308,10 @@ empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} +# Similar to keys of a dictionary, elements of a set have to be immutable. +invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + # Can set new variables to a set filled_set = some_set @@ -299,6 +333,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} 10 in filled_set # => False + #################################################### ## 3. Control Flow and Iterables #################################################### @@ -464,6 +499,16 @@ all_the_args(*args) # equivalent to foo(1, 2, 3, 4) all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +# Returning multiple values (with tuple assignments) +def swap(x, y): + return y, x # Return multiple values as a tuple + # (Note: parenthesis have been excluded but can be included) +# return (y, x) # Just as valid as the above example. + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. # Function Scope x = 5 -- cgit v1.2.3 From 97c3800ea0ae11769c3661f3ab2cfa926e03d866 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Costa?= Date: Sat, 3 Oct 2015 16:18:03 +0100 Subject: Add pt-pt translation for Scala tutorial --- pt-pt/scala-pt.html.markdown | 651 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 651 insertions(+) create mode 100644 pt-pt/scala-pt.html.markdown diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown new file mode 100644 index 00000000..68f7b12a --- /dev/null +++ b/pt-pt/scala-pt.html.markdown @@ -0,0 +1,651 @@ +--- +language: Scala +filename: learnscala.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] +translators: + - ["João Costa", "http://joaocosta.eu"] +lang: pt-pt +filename: learn-pt.scala +--- + +Scala - a linguagem escalável + +```scala + +/* + Prepare tudo: + + 1) Faça Download do Scala - http://www.scala-lang.org/downloads + 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na + variável de ambiente `PATH` + 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer: + + scala> + + Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete). + Pode escrever qualquer expressão de Scala e o resultado será imprimido. + Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já, + vamos começar com os básicos. + +*/ + + +///////////////////////////////////////////////// +// 1. Basicos +///////////////////////////////////////////////// + +// Uma linha de comentários é marcada com duas barras + +/* + Comentários de multiplas linhas, como se pode ver neste exemplo, são assim. +*/ + +// Imprimir, forçando uma nova linha no final +println("Hello world!") +println(10) + +// Imprimir, sem forçar uma nova linha no final +print("Hello world") + +// Valores são declarados com var ou val. +// As declarações val são imutáveis, enquanto que vars são mutáveis. +// A immutabilidade é uma propriedade geralmente vantajosa. +val x = 10 // x é agora 10 +x = 20 // erro: reatribuição de um val +var y = 10 +y = 20 // y é agora 12 + +/* + Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima + não especificamos um tipo. Isto é devido a uma funcionalidade chamada + inferência de tipos. Na maior parte dos casos, o compilador de scala consegue + inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre. + Podemos declarar o tipo de uma variável da seguinte forma: +*/ +val z: Int = 10 +val a: Double = 1.0 + +// Note a conversão automática de Int para Double: o resultado é 10.0, não 10 +val b: Double = 10 + +// Valores booleanos +true +false + +// Operações booleanas +!true // false +!false // true +true == false // false +10 > 5 // true + +// A matemática funciona da maneira habitual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +// Avaliar expressões na REPL dá o tipo e valor do resultado + +1 + 7 + +/* A linha acima resulta em: + + scala> 1 + 7 + res29: Int = 8 + + Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com + o valor 8. + + Note que "res29" é um nome de uma variavel gerado sequencialmente para + armazenar os resultados das expressões que escreveu, por isso o resultado + pode ser ligeiramente diferente. +*/ + +"Strings em scala são rodeadas por aspas" +'a' // Um caracter de Scala +// 'Strings entre plicas não existem' <= Isto causa um erro + +// Strings tem os métodos de Java habituais definidos +"olá mundo".length +"olá mundo".substring(2, 6) +"olá mundo".replace("á", "é") + +// Para além disso, também possuem métodos de Scala. +// Ver: scala.collection.immutable.StringOps +"olá mundo".take(5) +"olá mundo".drop(5) + +// Interpolação de Strings: repare no prefixo "s" +val n = 45 +s"Temos $n maçãs" // => "Temos 45 maçãs" + +// Expressões dentro de Strings interpoladas também são possíveis +val a = Array(11, 9, 6) +s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos." +s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs." +s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4" + +// Strings interpoladas são formatadas com o prefixo "f" +f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25" +f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454" + +// Strings prefixadas com "raw" ignoram caracteres especiais +raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r." + +// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string: +"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown"" + +// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas +val html = """
+

Carrega aqui, Zé

+ +
""" + + +///////////////////////////////////////////////// +// 2. Funções +///////////////////////////////////////////////// + +// Funções são definidas como: +// +// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... } +// +// Se vem de linugagens mais tradicionais, repare na omissão da palavra +// return keyword. Em Scala, a ultima expressão de um bloco é o seu +// valor de retorno +def somaQuadrados(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// As { } podem ser omitidas se o corpo da função for apenas uma expressão: +def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y + +// A sintaxe para chamar funções deve ser familiar: +somaQuadrados(3, 4) // => 25 + +// Na maior parte dos casos (sendo funções recursivas a principal excepção), o +// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos +// é aplicada aos valores de retorno +def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int + +// Funções podem ter parâmetros por omissão: +def somaComOmissão(x: Int, y: Int = 5) = x + y +somaComOmissão(1, 2) // => 3 +somaComOmissão(1) // => 6 + + +// Funções anónimas são definidas da seguinte forma: +(x: Int) => x * x + +// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido +// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma +// funão que recebe Int e retorna Int. +val quadrado: Int => Int = x => x * x + +// Funcões anónimas são chamadas como funções normais: +quadrado(10) // => 100 + +// Se cada argumento de uma função anónima for usado apenas uma vez, existe +// uma forma ainda mais curta de os definir. Estas funções anónumas são +// extremamente comuns, como será visto na secção sobre estruturas de dados. +val somaUm: Int => Int = _ + 1 +val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3) + +somaUm(5) // => 6 +somaEstranha(2, 4) // => 16 + + +// O código return existe em Scala, mas apenas retorna do def mais interior +// que o rodeia. +// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros. +// Não tem qualquer efeito em funções anónimas, por exemplo: +def foo(x: Int): Int = { + val funcAnon: Int => Int = { z => + if (z > 5) + return z // Esta linha faz com que z seja o retorno de foo! + else + z + 2 // Esta linha define o retorno de funcAnon + } + funcAnon(x) // Esta linha define o valor de retorno de foo +} + + +///////////////////////////////////////////////// +// 3. Controlo de fluxo +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach(println) + +r foreach println +// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as +// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis + +(5 to 1 by -1) foreach (println) + +// Ciclos while +var i = 0 +while (i < 10) { println("i " + i); i += 1 } + +while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê? + +i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico - + // executa sequencialmente enquanto muda uma variável. Ciclos while são + // rápidos, por vezes até mais que ciclos de Java, mas combinadores e + // compreensões (usados anteriormente) são mais fáceis de entender e + // paralelizar + +// Um ciclo do while +do { + println("x ainda é menor que 10") + x = x + 1 +} while (x < 10) + +// A forma idiomática em Scala de definir acções recorrentes é através de +// recursão em cauda. +// Funções recursivas necessitam de um tipo de retorno definido explicitamente. +// Neste caso, é Unit. +def mostraNumerosEntre(a: Int, b: Int): Unit = { + print(a) + if (a < b) + mostraNumerosEntre(a + 1, b) +} +mostraNumerosEntre(1, 14) + + +// Condicionais + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. Estruturas de dados +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Lança uma excepção + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Lança uma excepção + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Veja a documentação de mapas de scala em - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * e verifique que a consegue aceder + */ + + +// Tuplos + +(1, 2) + +(4, 3, 2) + +(1, 2, "três") + +(a, 2, "três") + +// Porquê ter isto? +val divideInts = (x: Int, y: Int) => (x / y, x % y) + +divideInts(10, 3) // A função divideInts returna o resultado e o resto + +// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice +// (começado em 1) do elemento +val d = divideInts(10, 3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Programação Orientada a Objectos +///////////////////////////////////////////////// + +/* + Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples + (valores, funções, etc). Estas expressões são suficientes para executar no + interpretador da linha de comandos para testes rápidos, mas não podem existir + isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um + ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas + construções de topo permitidas são: + + - object + - class + - case class + - trait + + Vamos agora explicar o que são: +*/ + +// Classes são semelhantes a classes noutras linguagens. Os argumentos do +// construtor são declarados após o nome da classe, sendo a inicialização feita +// no corpo da classe. +class Cão(rc: String) { + // Código de construção + var raça: String = rc + + // Define um método chamado "ladra", que retorna uma String + def ladra = "Woof, woof!" + + // Valores e métodos são assumidos como públicos, mas é possivel usar + // os códigos "protected" and "private". + private def dormir(horas: Int) = + println(s"Vou dormir por $horas horas") + + // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima + // linha, a classe Cão é declarada como abstracta + // abstract class Cão(...) { ... } + // def persegue(oQue: String): String +} + +val oMeuCão = new Cão("greyhound") +println(oMeuCão.raça) // => "greyhound" +println(oMeuCão.ladra) // => "Woof, woof!" + + +// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum +// que classes de Scala possuam um "objecto companheiro", onde o comportamento +// por instância é capturado nas classes, equanto que o comportamento +// relacionado com todas as instancias dessa classe ficam no objecto. +// A diferença é semelhante a métodos de classes e métodos estáticos noutras +// linguagens. Note que objectos e classes podem ter o mesmo nome. +object Cão { + def raçasConhecidas = List("pitbull", "shepherd", "retriever") + def criarCão(raça: String) = new Cão(raça) +} + + +// Case classes são classes com funcionalidades extra incluidas. Uma questão +// comum de iniciantes de scala é quando devem usar classes e quando devem usar +// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se +// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes +// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal +// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos +// métods, sendo que estes raramente possuem efeitos secundários. +case class Pessoa(nome: String, telefone: String) + +// Cria uma nova instancia. De notar que case classes não precisam de "new" +val jorge = Pessoa("Jorge", "1234") +val cátia = Pessoa("Cátia", "4567") + +// Case classes trazem algumas vantagens de borla, como acessores: +jorge.telefone // => "1234" + +// Igualdade por campo (não é preciso fazer override do .equals) +Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false + +// Cópia simples +// outroJorge == Person("jorge", "9876") +val outroJorge = jorge.copy(telefone = "9876") + +// Entre outras. Case classes também suportam correspondência de padrões de +// borla, como pode ser visto de seguida. + + +// Traits em breve! + + +///////////////////////////////////////////////// +// 6. Correspondência de Padrões +///////////////////////////////////////////////// + +// A correspondência de padrões é uma funcionalidade poderosa e bastante +// utilizada em Scala. Eis como fazer correspondência de padrões numa case class: +// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de +// breaks, a computação termina no primeiro sucesso. + +def reconhecePessoa(pessoa: Pessoa): String = pessoa match { + // Agora, especifique os padrões: + case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel + case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel + case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel +} + +val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo. + +// A correspondência de padrões pode parecer familiar aos switches em linguagens +// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer +// correspondências com muito mais: +def correspondeTudo(obj: Any): String = obj match { + // Pode-se corresponder valores: + case "Olá mundo" => "Recebi uma string Olá mundo." + + // Corresponder por tipo: + case x: Double => "Recebi um Double: " + x + + // Corresponder tendo em conta condições especificas: + case x: Int if x > 10000 => "Recebi um número bem grande!" + + // Fazer correspondências com case classes (visto anteriormente): + case Pessoa(nome, tel) => s"Recebi o contacto para $nome!" + + // Fazer correspondência com expressões regulares: + case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio" + + // Corresponder tuplos: + case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c" + + // Corresponder estruturas de dados: + case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c" + + // Combinar padrões: + case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo" +} + +// Na realidade, é possível fazer correspondência com qualquer objecto que +// defina o método "unapply". Esta funcionalidade é tão poderosa que permite +// definir funções sob a forma de padrões: +val funcPaddrao: Pessoa => String = { + case Pessoa("Jorge", tel) => s"Número do Jorge: $tel" + case Pessoa(nome, tel) => s"Número de alguém: $tel" +} + + +///////////////////////////////////////////////// +// 7. Programação Funcional +///////////////////////////////////////////////// + +// Scala permite que funções e métodos retornem, ou recebam como parámetros, +// outras funções ou métodos + +val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int +List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento + +// Funções anónimas também podem ser usadas +List(1, 2, 3) map (x => x + 10) + +// Sendo que o símbolo _ também pode ser usado se a função anónima só receber +// um argumento. Este fica com o valor da variável +List(1, 2, 3) map (_ + 10) + +// Se tanto o bloco como a função apenas receberem um argumento, o próprio +// _ pode ser omitido +List("Dom", "Bob", "Natalia") foreach println + + +// Combinadores + +s.map(quadrado) + +val sQuadrado = s.map(quadrado) + +sQuadrado.filter(_ < 10) + +sQuadrado.reduce (_+_) + +// O método filter recebe um predicado (uma função de A => Boolean) e escolhe +// todos os elementos que satisfazem o predicado +List(1, 2, 3) filter (_ > 2) // List(3) +case class Pessoa(nome: String, idade: Int) +List( + Pessoa(nome = "Dom", idade = 23), + Pessoa(nome = "Bob", idade = 30) +).filter(_.idade > 25) // List(Pessoa("Bob", 30)) + + +// O método foreach recebe uma função de A => Unit, executando essa função em +// cada elemento da colecção +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// Compreensões For + +for { n <- s } yield quadrado(n) + +val nQuadrado2 = for { n <- s } yield quadrado(n) + +for { n <- nQuadrado2 if n < 10 } yield n + +for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado + +/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto + que uma compreensão define a relação entre dois conjuntos de dados. */ + + +///////////////////////////////////////////////// +// 8. Implicitos +///////////////////////////////////////////////// + +/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito + * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem + * resistir a tentação de usá-los até que compreendam não só como funcionam, + * mas também as melhores práticas. Apenas incluimos esta secção no tutorial + * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas + * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve + * para compreender como trabalhar com implicitos, não como declará-los. +*/ + +// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como +// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5 +// nestes exemplos + +implicit val oMeuIntImplicito = 100 +implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça) + +// Por si só, a palavra implicit não altera o comportamento de um valor, sendo +// que estes podem ser usados da forma habitual. +oMeuIntImplicito + 2 // => 102 +aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull" + +// A diferença é que estes valores podem ser utilizados quando outro pedaço de +// código "necessite" de uma valor implicito. Um exemplo são argumentos +// implicitos de funções: +def enviaCumprimentos(aQuem: String)(implicit quantos: Int) = + s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!" + +// Se dermos um valor a "quantos", a função comporta-se normalmente +enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!" + +// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é +// usado, neste caso, "oMeuInteiroImplicito" +enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!" + +// Parâmentros implicitos de funções permitem-nos simular classes de tipos de +// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação. +// As seguintes linhas representam a mesma coisa +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... + + +// Outra situação em que o compilador prouca um implicito é se encontrar uma +// expressão +// obj.método(...) +// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma +// conversão implicita A => B, onde A é o tipo de obj, e B possui um método +// chamado "método", a conversão é aplicada. Ou seja, tendo +// aMinhaFunçãoImplicita definida, podemos dizer +"Retriever".raça // => "Golden Retriever" +"Sheperd".ladra // => "Woof, woof!" + +// Neste caso, a String é primeiro convertida para Cão usando a nossa funão, +// sendo depois chamado o método apropriado. Esta é uma funcionalidade +// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade, +// ao definir a função implicita, o compilador deve lançar um aviso a insisitir +// que só deve definir a função se souber o que está a fazer. + + +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// + +// Importar coisas +import scala.collection.immutable.List + +// Importar todos os "sub pacotes" +import scala.collection.immutable._ + +// Importar multiplas classes numa linha +import scala.collection.immutable.{List, Map} + +// Renomear uma classe importada usando '=>' +import scala.collection.immutable.{List => ImmutableList} + +// Importar todas as classes excepto algumas. Set e Map são excluidos: +import scala.collection.immutable.{Map => _, Set => _, _} + +// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala +// com um método main: +object Aplicação { + def main(args: Array[String]): Unit = { + // código aqui. + } +} + +// Ficheiros podem conter várias classes o objectos. Compilar com scalac + + + + +// Input e output + +// Ler um ficheiro linha a linha +import scala.io.Source +for(linha <- Source.fromFile("ficheiro.txt").getLines()) + println(linha) + +// Escrever um ficheiro usando o PrintWriter de Java +val writer = new PrintWriter("ficheiro.txt") +writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator) +writer.write("Outra linha aqui" + util.Properties.lineSeparator) +writer.close() + +``` + +## Mais recursos + +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From 2e05ec8d955b62fef844bd460f5bb455e351d1d0 Mon Sep 17 00:00:00 2001 From: edholland Date: Fri, 2 Oct 2015 02:26:04 +0200 Subject: Add clarification on bind / match with = op in erlang. Fixes #1139 --- erlang.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 8b67a76a..d0af7f05 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -25,6 +25,7 @@ filename: learnerlang.erl %% 1. Variables and pattern matching. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% In Erlang new variables are bound with an `=` statement. Num = 42. % All variable names must start with an uppercase letter. % Erlang has single-assignment variables; if you try to assign a different @@ -32,9 +33,11 @@ Num = 42. % All variable names must start with an uppercase letter. Num = 43. % ** exception error: no match of right hand side value 43 % In most languages, `=` denotes an assignment statement. In Erlang, however, -% `=` denotes a pattern-matching operation. `Lhs = Rhs` really means this: -% evaluate the right side (`Rhs`), and then match the result against the -% pattern on the left side (`Lhs`). +% `=` denotes a pattern-matching operation. When an empty variable is used on the +% left hand side of the `=` operator to is bound (assigned), but when a bound +% varaible is used on the left hand side the following behaviour is observed. +% `Lhs = Rhs` really means this: evaluate the right side (`Rhs`), and then +% match the result against the pattern on the left side (`Lhs`). Num = 7 * 6. % Floating-point number. -- cgit v1.2.3 From 61597e603f78dc0645517a13b0b258236e5a3563 Mon Sep 17 00:00:00 2001 From: Ed Holland Date: Fri, 2 Oct 2015 01:11:10 +0100 Subject: Add section on eunit in erlang doc --- erlang.html.markdown | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/erlang.html.markdown b/erlang.html.markdown index 8b67a76a..31cdcdab 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -299,6 +299,39 @@ CalculateArea ! {circle, 2}. % 12.56000000000000049738 % The shell is also a process; you can use `self` to get the current pid. self(). % <0.41.0> +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 5. Testing with EUnit +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Unit tests can be written using EUnits's test generators and assert macros +-module(fib). + -export([fib/1]). + -include_lib("eunit/include/eunit.hrl"). + + fib(0) -> 1; + fib(1) -> 1; + fib(N) when N > 1 -> fib(N-1) + fib(N-2). + + fib_test_() -> + [?_assert(fib(0) =:= 1), + ?_assert(fib(1) =:= 1), + ?_assert(fib(2) =:= 2), + ?_assert(fib(3) =:= 3), + ?_assert(fib(4) =:= 5), + ?_assert(fib(5) =:= 8), + ?_assertException(error, function_clause, fib(-1)), + ?_assert(fib(31) =:= 2178309) + ]. + +% EUnit will automatically export to a test() fucntion to allo running the tests +% in the erlang shell +fib:test() + +% The popular erlang build tool Rebar is also compatible with EUnit +% ``` +% rebar eunit +% ``` + ``` ## References -- cgit v1.2.3 From 466b51d9fa4a223014b0d1d79d3d55709c32373d Mon Sep 17 00:00:00 2001 From: willianjusten Date: Sat, 3 Oct 2015 13:49:07 -0300 Subject: [javascript pt-br] : 5. More about Objects; Constructors and Prototypes --- pt-br/javascript-pt.html.markdown | 134 ++++++++++++++++++++------------------ 1 file changed, 69 insertions(+), 65 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 08448d0b..097a1a8e 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -340,75 +340,74 @@ function sayHelloInFiveSeconds(name){ sayHelloInFiveSeconds("Adam"); // Vai abrir um popup com "Hello, Adam!" em 5s /////////////////////////////////// -// 5. More about Objects; Constructors and Prototypes +// 5. Mais sobre Objetos; Construtores e Prototypes -// Objects can contain functions. +// Objetos podem conter funções. var myObj = { myFunc: function(){ - return "Hello world!"; + return "Olá mundo!"; } }; -myObj.myFunc(); // = "Hello world!" +myObj.myFunc(); // = "Olá mundo!" -// When functions attached to an object are called, they can access the object -// they're attached to using the `this` keyword. +// Quando uma função ligada a um objeto é chamada, ela pode acessar o objeto +// da qual foi ligada usando a palavra-chave `this`. myObj = { - myString: "Hello world!", + myString: "Olá mundo!", myFunc: function(){ return this.myString; } }; -myObj.myFunc(); // = "Hello world!" +myObj.myFunc(); // = "Olá mundo!" -// What this is set to has to do with how the function is called, not where -// it's defined. So, our function doesn't work if it isn't called in the -// context of the object. +// O `this` só funciona para dentro do escopo do objeto, portanto, se chamarmos +// um método do objeto fora de seu escopo, este não irá funcionar. var myFunc = myObj.myFunc; myFunc(); // = undefined -// Inversely, a function can be assigned to the object and gain access to it -// through `this`, even if it wasn't attached when it was defined. +// Inversamente, uma função pode ser atribuída a um objeto e ganhar a acesso +// através do `this`, até mesmo se ela não for chamada quando foi definida. var myOtherFunc = function(){ return this.myString.toUpperCase(); } myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO WORLD!" +myObj.myOtherFunc(); // = "OLÁ MUNDO!" -// We can also specify a context for a function to execute in when we invoke it -// using `call` or `apply`. +// Nós podemos também especificar um contexto onde a função irá executar, +// usando o `call` ou `apply`. var anotherFunc = function(s){ return this.myString + s; } -anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" +anotherFunc.call(myObj, " E Olá Lua!"); // = "Olá mundo! E Olá Lua!" -// The `apply` function is nearly identical, but takes an array for an argument -// list. +// A função `apply` é praticamente a mesma coisa, mas ela pega um array +// como lista de argumentos. -anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" +anotherFunc.apply(myObj, [" E Olá Sol!"]); // = "Olá mundo! E Olá Sol!" -// This is useful when working with a function that accepts a sequence of -// arguments and you want to pass an array. +// Isto é util quando trabalhamos com uma função que aceita uma sequência de +// argumentos e você quer passar um array. Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// But, `call` and `apply` are only temporary. When we want it to stick, we can -// use `bind`. +// Mas, o `call` e `apply` são somente temporários. Quando você quiser que +// permaneça sempre no escopo, use `bind`. var boundFunc = anotherFunc.bind(myObj); -boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" +boundFunc(" E Olá Saturno!"); // = "Olá mundo! E Olá Saturno!" -// `bind` can also be used to partially apply (curry) a function. +// `bind` também pode ser usado para parcialmente aplicar (curry) uma função. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// When you call a function with the `new` keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be -// called like that are called constructors. +// Quando você invoca uma função com a palavra-chave `new`, um novo objeto +// é criado, e fica disponível para a função pela palavra-chave `this`. +// Funções são desenhadas para serem invocadas como se invocam os construtores. var MyConstructor = function(){ this.myNumber = 5; @@ -416,15 +415,17 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Every JavaScript object has a 'prototype'. When you go to access a property -// on an object that doesn't exist on the actual object, the interpreter will -// look at its prototype. +// Todo objeto JavaScript possui um `prototype`. Quando você tenta acessar +// uma propriedade de um objeto que não existe no objeto atual, o interpretador +// vai olhar imediatamente para o seu prototype. + +// Algumas implementações em JS deixam você acessar o objeto prototype com a +// propriedade mágica `__proto__`. Enquanto isso é util para explicar +// prototypes, não é parte de um padrão; nós vamos falar de algumas formas de +// usar prototypes depois. -// Some JS implementations let you access an object's prototype on the magic -// property `__proto__`. While this is useful for explaining prototypes it's not -// part of the standard; we'll get to standard ways of using prototypes later. var myObj = { - myString: "Hello world!" + myString: "Olá Mundo!" }; var myPrototype = { meaningOfLife: 42, @@ -437,34 +438,36 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 // This works for functions, too. -myObj.myFunc(); // = "hello world!" +// Isto funciona para funções, também. +myObj.myFunc(); // = "olá mundo!" -// Of course, if your property isn't on your prototype, the prototype's -// prototype is searched, and so on. +// É claro, se sua propriedade não está em seu prototype, +// o prototype do prototype será procurado e por aí vai. myPrototype.__proto__ = { myBoolean: true }; myObj.myBoolean; // = true -// There's no copying involved here; each object stores a reference to its -// prototype. This means we can alter the prototype and our changes will be -// reflected everywhere. +// Não há cópia envolvida aqui; cada objeto guarda uma referência do +// prototype. Isso significa que podemos alterar o prototype e nossas mudanças +// serão refletidas em qualquer lugar. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// We mentioned that `__proto__` was non-standard, and there's no standard way to -// change the prototype of an existing object. However, there are two ways to -// create a new object with a given prototype. -// The first is Object.create, which is a recent addition to JS, and therefore -// not available in all implementations yet. +// Nós mencionamos que o `__proto__` não é uma forma padrão, e não há uma +// forma padrão de mudar o prototype de um objeto já existente. Entretanto, +// existem duas formas de se criar um objeto com um dado prototype. + +// A primeira forma é `Object.create`, que é uma adição recente do JS, +// e ainda não está disponível em todas as implementações. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 -// The second way, which works anywhere, has to do with constructors. -// Constructors have a property called prototype. This is *not* the prototype of -// the constructor function itself; instead, it's the prototype that new objects -// are given when they're created with that constructor and the new keyword. +// A segunda forma, que funciona em qualquer lugar, é feita com construtores. +// Construtores tem uma propriedade chamada prototype. Este *não* é o prototype +// do construtor em si; ao invés disso, ele é o prototype dos novos objetos +// criados pelo construtor. MyConstructor.prototype = { myNumber: 5, getMyNumber: function(){ @@ -476,42 +479,43 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 -// Built-in types like strings and numbers also have constructors that create -// equivalent wrapper objects. +// Tipos originais da linguagem como strings e números também possuem +// construtores equivalentes. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true -// Except, they aren't exactly equivalent. +// Exceto, que eles não são totalmente equivalentes. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ - // This code won't execute, because 0 is falsy. + // O código não vai executar, porque 0 é um valor falso. } if (Number(0)){ - // This code *will* execute, because Number(0) is truthy. + // O código *vai* executar, porque `Number(0)` é um valor verdadeiro. } -// However, the wrapper objects and the regular builtins share a prototype, so -// you can actually add functionality to a string, for instance. +// Entretanto, esses objetos encapsulados e as funções originais compartilham +// um mesmo prototype, portanto você pode adicionar funcionalidades a uma string, +// por exemplo. String.prototype.firstCharacter = function(){ return this.charAt(0); } "abc".firstCharacter(); // = "a" -// This fact is often used in "polyfilling", which is implementing newer -// features of JavaScript in an older subset of JavaScript, so that they can be -// used in older environments such as outdated browsers. +// Esse fato é usado para criar os chamados `polyfills`, que implementam +// uma nova característica do Javascript em uma versão mais velha, para que +// assim funcionem em ambientes mais velhos como browsers ultrapassados. -// For instance, we mentioned that Object.create isn't yet available in all -// implementations, but we can still use it with this polyfill: +// Havíamos mencionado que `Object.create` não estava ainda disponível em +// todos as implementações, mas nós podemos usá-lo com esse polyfill: if (Object.create === undefined){ // don't overwrite it if it exists Object.create = function(proto){ - // make a temporary constructor with the right prototype + // faz um construtor temporário com o prototype certo var Constructor = function(){}; Constructor.prototype = proto; - // then use it to create a new, appropriately-prototyped object + // então utiliza o new para criar um objeto prototype apropriado return new Constructor(); } } -- cgit v1.2.3 From 46d509077f10fc9b04aaf69829526d4b8297798d Mon Sep 17 00:00:00 2001 From: willianjusten Date: Sat, 3 Oct 2015 14:03:54 -0300 Subject: [javascript pt-br] : Leitura Adicional --- pt-br/javascript-pt.html.markdown | 43 ++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 097a1a8e..f4b5ed2c 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -521,30 +521,31 @@ if (Object.create === undefined){ // don't overwrite it if it exists } ``` -## Further Reading - -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides -excellent documentation for JavaScript as it's used in browsers. Plus, it's a -wiki, so as you learn more you can help others out by sharing your own -knowledge. - -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -covers much of the concepts covered here in more detail. This guide has quite -deliberately only covered the JavaScript language itself; if you want to learn -more about how to use JavaScript in web pages, start by learning about the +## Leitura Adicional + +O [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma +excelente documentação sobre Javascript e seu uso nos browsers. E mais, +é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando +os outros compartilhando do seu conhecimento. + +[Uma re-introdução do JavaScript pela MDN] +(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala +somente sobre a linguagem JavaScript em si; se você quiser aprender mais +sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. +[Aprenda Javascript por Exemplos e com Desafios](http://www.learneroo.com/modules/64/nodes/350) é uma +variação desse guia com desafios. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) é um guia +profundo de todas as partes do JavaScript. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) é o guia clássico +/ livro de referência. -In addition to direct contributors to this article, some content is adapted -from Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. +Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está +nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +da Mozilla Developer Network. -- cgit v1.2.3 From 261f7a249f13f3f13f5619f2a3202d0273010df2 Mon Sep 17 00:00:00 2001 From: DPS Date: Sat, 3 Oct 2015 20:00:47 +0200 Subject: [git/de] fixed typo --- de-de/git-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index c7b6ad86..43939129 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -48,7 +48,7 @@ Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichni ### .git-Verzeichnis (Teil des Repositorys) -Das .git-Verzeichnis enth? alle Einstellung, Logs, Branches, den HEAD und mehr. +Das .git-Verzeichnis enthält alle Einstellung, Logs, Branches, den HEAD und mehr. [Ausführliche Übersicht](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) ### Arbeitsverzeichnis (Teil des Repositorys) -- cgit v1.2.3 From 4719d4707cbda05daab4e05e1c85655ff7abf2fd Mon Sep 17 00:00:00 2001 From: DPS Date: Sat, 3 Oct 2015 20:20:03 +0200 Subject: [go/de] fixed typo --- de-de/go-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 83d59c8b..765372e0 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -312,7 +312,7 @@ Dokumentation lesen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). -Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil +Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). -- cgit v1.2.3 From 6f29bcc20175a348f3b1dd606d8a0ace5d48fe54 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Sat, 3 Oct 2015 15:39:37 -0700 Subject: Update Python-fr.html.markdown Add Link to Python3 English article. --- fr-fr/python-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 58a036ba..26cab55f 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -15,7 +15,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x -Vous pourrez bientôt trouver un article pour Python 3! +Vous pourrez bientôt trouver un article pour Python 3 an Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/). ```python # Une ligne simple de commentaire commence par un dièse -- cgit v1.2.3 From 998fdfdfcdff05cb0721841215addbcdd94d30b0 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Sat, 3 Oct 2015 15:40:41 -0700 Subject: typo --- fr-fr/python-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 26cab55f..5a03ecfc 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -15,7 +15,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x -Vous pourrez bientôt trouver un article pour Python 3 an Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/). +Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/). ```python # Une ligne simple de commentaire commence par un dièse -- cgit v1.2.3 From 0d2863186231324b14e8d3a1d25aa8e44078aa68 Mon Sep 17 00:00:00 2001 From: willianjusten Date: Sat, 3 Oct 2015 21:03:58 -0300 Subject: Sync pt with original js --- pt-br/javascript-pt.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index f4b5ed2c..e39c6c8e 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -492,9 +492,6 @@ myNumber === myNumberObj; // = false if (0){ // O código não vai executar, porque 0 é um valor falso. } -if (Number(0)){ - // O código *vai* executar, porque `Number(0)` é um valor verdadeiro. -} // Entretanto, esses objetos encapsulados e as funções originais compartilham // um mesmo prototype, portanto você pode adicionar funcionalidades a uma string, -- cgit v1.2.3 From 4206b4ccd04c8343e6becd58a2c9549e9593cbd6 Mon Sep 17 00:00:00 2001 From: David Stockton Date: Sat, 3 Oct 2015 19:35:42 -0600 Subject: Correct usage of "it's" in javascript doc --- json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/json.html.markdown b/json.html.markdown index f57b82b8..47a8cb21 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -49,7 +49,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. "alternative style": { "comment": "check this out!" - , "comma position": "doesn't matter - as long as its before the value, then its valid" + , "comma position": "doesn't matter - as long as it's before the value, then it's valid" , "another comment": "how nice" }, -- cgit v1.2.3 From eb35f7748a11e04f15cb9901a86702f881155b14 Mon Sep 17 00:00:00 2001 From: David Stockton Date: Sat, 3 Oct 2015 19:40:02 -0600 Subject: Fix usage of "it's" in example comment for chapel --- chapel.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index c8489371..05e5b867 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1074,14 +1074,14 @@ Installing the Compiler Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) -and its as easy as +and it's as easy as 1. `tar -xvf chapel-1.11.0.tar.gz` 2. `cd chapel-1.11.0` 3. `make` 4. `source util/setchplenv.bash # or .sh or .csh or .fish` -You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). +You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X @@ -1100,4 +1100,4 @@ Notable arguments: * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. * `--set =`: set config param `` to `` at compile-time. * `--main-module `: use the main() procedure found in the module `` as the executable's main. - * `--module-dir `: includes `` in the module search path. \ No newline at end of file + * `--module-dir `: includes `` in the module search path. -- cgit v1.2.3 From 2ede63f54cb59b99c0d3da712814f5556a979660 Mon Sep 17 00:00:00 2001 From: David Stockton Date: Sat, 3 Oct 2015 19:41:52 -0600 Subject: Fix incorrect "its" to "it is" in visual basic doc --- visualbasic.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index 00d61843..f9906e96 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -236,7 +236,7 @@ Module Module1 'Nine Private Sub IfElseStatement() Console.Title = "If / Else Statement | Learn X in Y Minutes" - 'Sometimes its important to consider more than two alternatives. + 'Sometimes it is important to consider more than two alternatives. 'Sometimes there are a good few others. 'When this is the case, more than one if statement would be required. 'An if statement is great for vending machines. Where the user enters a code. -- cgit v1.2.3 From 9bc553c46ce9b7154ec7c82451d71608f4beda82 Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Sun, 4 Oct 2015 10:12:55 +0530 Subject: Update c++.html.markdown Regarding issue #1216, Better explaining the Reference 'fooRef'. --- c++.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index 4acc1b9d..bbd2f9a9 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -245,7 +245,13 @@ cout << fooRef; // Prints "I am foo. Hi!" // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. +cout << &fooRef << endl; //Prints address of fooRef fooRef = bar; +cout << &fooRef << endl; //Prints address of fooRef, AGAIN +cout << fooRef; // Prints "I am bar" + +//The address of fooRef remains the same, i.e. it is still referring to foo. + const string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. -- cgit v1.2.3 From c7e552c448c5a562a3ff5f442a7ed834aec04d9e Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Sun, 4 Oct 2015 10:34:31 +0530 Subject: Variable size array, user size input added. #1170 Fixed Issue #1170 Variable size array, user size input added. --- c.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 8e631de4..36621a9e 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -130,7 +130,9 @@ int main(void) { // can be declared as well. The size of such an array need not be a compile // time constant: printf("Enter the array size: "); // ask the user for an array size - char buf[0x100]; + int size; + scanf("%d", &size); + char buf[size]; fgets(buf, sizeof buf, stdin); // strtoul parses a string to an unsigned integer -- cgit v1.2.3 From 9b00510c452a24197f7b8d30dee1a5f170e3cdee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerson=20L=C3=A1zaro?= Date: Sun, 4 Oct 2015 00:09:26 -0500 Subject: =?UTF-8?q?[c++/es]=20a=C3=B1adido?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es-es/c++-es.html.markdown | 829 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 829 insertions(+) create mode 100644 es-es/c++-es.html.markdown diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown new file mode 100644 index 00000000..bcc775e5 --- /dev/null +++ b/es-es/c++-es.html.markdown @@ -0,0 +1,829 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] +translators: + - ["Gerson Lázaro", "https://gersonlazaro.com"] +lang: es-es +--- + +C++ es un lenguaje de programación de sistemas que, +[de acuerdo a su inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +fue diseñado para + +- ser un "mejor C" +- soportar abstracción de datos +- soportar programación orientada a objetos +- soportar programación genérica + +Aunque su sintaxis puede ser más difícil o compleja que los nuevos lenguajes, +es ampliamente utilizado, ya que compila instrucciones nativas que pueden ser +directamente ejecutadas por el procesador y ofrece un estricto control sobre +el hardware (como C), mientras ofrece características de alto nivel como +genericidad, excepciones, y clases. Esta combinación de velocidad y +funcionalidad hace de C ++ uno de los lenguajes de programación más utilizados. + +```c++ +//////////////////// +// Comparación con C +//////////////////// + +// C ++ es _casi_ un superconjunto de C y comparte su sintaxis básica para las +// declaraciones de variables, tipos primitivos y funciones. + +// Al igual que en C, el punto de entrada de tu programa es una función llamada +// main con un retorno de tipo entero. +// Este valor sirve como código de salida del programa. +// Mira http://en.wikipedia.org/wiki/Exit_status para mayor información. +int main(int argc, char** argv) +{ + // Los argumentos de la línea de comandos se pasan por argc y argv de la + // misma manera que en C. + // argc indica el número de argumentos, + // y argv es un arreglo de strings de estilo C (char*) + // representando los argumentos. + // El primer argumento es el nombre con el que el programa es llamado. + // argc y argv pueden omitirse si no te preocupan los argumentos, + // dejando la definición de la función como int main () + + // Un estado de salida 0 indica éxito. + return 0; +} + +// Sin embargo, C ++ varía en algunas de las siguientes maneras: + +// En C++, los caracteres literales son caracteres +sizeof('c') == sizeof(char) == 1 + +// En C, los caracteres literales son enteros +sizeof('c') == sizeof(int) + + +// C++ tiene prototipado estricto +void func(); // función que no acepta argumentos + +// En C +void func(); // función que puede aceptar cualquier número de argumentos + +// Use nullptr en lugar de NULL en C++ +int* ip = nullptr; + +// Las cabeceras (headers) estándar de C están disponibles en C ++, +// pero tienen el prefijo "c" y no tienen sufijo .h. +#include + +int main() +{ + printf("Hola mundo!\n"); + return 0; +} + +////////////////////////// +// Sobrecarga de funciones +////////////////////////// + +// C++ soporta sobrecarga de funciones +// siempre que cada función tenga diferentes parámetros. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("Mi entero es %d", myInt); +} + +int main() +{ + print("Hello"); // Resolves to void print(const char*) + print(15); // Resolves to void print(int) +} + +//////////////////////////////////// +// Argumentos de función por defecto +//////////////////////////////////// + +// Puedes proporcionar argumentos por defecto para una función si no son +// proporcionados por quien la llama. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Hacer algo con los enteros aqui +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Los argumentos predeterminados deben estar al final de la lista de argumentos. + +void invalidDeclaration(int a = 1, int b) // Error! +{ +} + +///////////////////// +// Espacios de nombre +///////////////////// + +// Espacios de nombres proporcionan ámbitos separados para variable, función y +// otras declaraciones. +// Los espacios de nombres se pueden anidar. + +namespace First { + namespace Nested { + void foo() + { + printf("Esto es First::Nested::foo\n"); + } + } // fin del nombre de espacio Nested +} // fin del nombre de espacio First + +namespace Second { + void foo() + { + printf("Esto es Second::foo\n") + } +} + +void foo() +{ + printf("Este es global: foo\n"); +} + +int main() +{ + + // Incluye todos los símbolos del espacio de nombre Second en el ámbito + // actual. Tenga en cuenta que simplemente foo() no funciona, ya que ahora + // es ambigua si estamos llamando a foo en espacio de nombres Second o en + // el nivel superior. + using namespace Second; + + Second::foo(); // imprime "Esto es Second::foo" + First::Nested::foo(); // imprime "Esto es First::Nested::foo" + ::foo(); // imprime "Este es global: foo" +} + +///////////////// +// Entrada/Salida +///////////////// + +// La entrada y salida de C++ utiliza flujos (streams) +// cin, cout, y cerr representan a stdin, stdout, y stderr. +// << es el operador de inserción >> es el operador de extracción. + + +#include // Incluir para el flujo de entrada/salida + +using namespace std; // Los streams estan en std namespace (libreria estandar) + +int main() +{ + int myInt; + + // Imprime a la stdout (o terminal/pantalla) + cout << "Ingresa tu número favorito:\n"; + // Toma una entrada + cin >> myInt; + + // cout puede también ser formateado + cout << "Tu número favorito es " << myInt << "\n"; + // imprime "Tu número favorito es " + + cerr << "Usado para mensajes de error"; +} +//////////////////// +// Cadenas (Strings) +//////////////////// + +// Las cadenas en C++ son objetos y tienen muchas funciones +#include + +using namespace std; // Strings también estan en namespace std + +string myString = "Hola"; +string myOtherString = " Mundo"; + +// + es usado para concatenar. +cout << myString + myOtherString; // "Hola Mundo" + +cout << myString + " Tu"; // "Hola Tu" + +// Las cadenas en C++ son mutables y tienen valor semántico. +myString.append(" Perro"); +cout << myString; // "Hola Perro" + + +////////////// +// Referencias +////////////// + +// Además de punteros como los de C, +// C++ tiene _references_. +// Estos tipos de puntero no pueden ser reasignados una vez establecidos +// Y no pueden ser nulos. +// También tienen la misma sintaxis que la propia variable: +// No es necesaria * para eliminar la referencia y +// & (dirección) no se utiliza para la asignación. + +using namespace std; + +string foo = "Yo soy foo"; +string bar = "Yo soy bar"; + +string& fooRef = foo; // Crea una referencia a foo. +fooRef += ". Hola!"; // Modifica foo través de la referencia +cout << fooRef; // Imprime "Yo soy foo. Hola!" + +// No trate de reasignar "fooRef". Esto es lo mismo que "foo = bar", y +// foo == "Yo soy bar" +// después de esta linea. +fooRef = bar; + +const string& barRef = bar; // Crea una referencia constante a bar. +// Como en C, los valores constantes (y punteros y referencias) no pueden ser +// modificados. +barRef += ". Hola!"; // Error, referencia constante no puede ser modificada. + +// Sidetrack: Antes de hablar más sobre referencias, hay que introducir un +// concepto llamado objeto temporal. Supongamos que tenemos el siguiente código: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Lo que pasa en la segunda línea es en realidad: +// - Un objeto de cadena es retornado desde tempObjectFun +// - Una nueva cadena se construye con el objeto devuelto como argumento al +// constructor +// - El objeto devuelto es destruido +// El objeto devuelto se llama objeto temporal. Objetos temporales son +// creados cada vez que una función devuelve un objeto, y es destruido en el +// fin de la evaluación de la expresión que encierra (Bueno, esto es lo que la +// norma dice, pero los compiladores están autorizados a cambiar este +// comportamiento. Busca "return value optimization" para ver mas detalles). +// Así que en este código: +foo(bar(tempObjectFun())) + +// Suponiendo que foo y bar existen, el objeto retornado de tempObjectFun es +// pasado al bar, y se destruye antes de llamar foo. + +// Ahora, de vuelta a las referencias. La excepción a la regla "en el extremo +// de la expresión encerrada" es si un objeto temporal se une a una +// referencia constante, en cuyo caso su vida se extiende al ámbito actual: + +void constReferenceTempObjectFun() { + // ConstRef obtiene el objeto temporal, y es válido hasta el final de esta +  // función. + const string& constRef = tempObjectFun(); + ... +} + +// Otro tipo de referencia introducida en C ++ 11 es específicamente para +// objetos temporales. No se puede tener una variable de este tipo, pero tiene +// prioridad en resolución de sobrecarga: + +void someFun(string& s) { ... } // Referencia regular +void someFun(string&& s) { ... } // Referencia a objeto temporal + +string foo; +someFun(foo); // Llama la función con referencia regular +someFun(tempObjectFun()); // Llama la versión con referencia temporal + +// Por ejemplo, puedes ver estas dos versiones de constructores para +// std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// La idea es que si estamos construyendo una nueva cadena de un objeto temporal +// (que va a ser destruido pronto de todos modos), podemos tener un constructor +// mas eficiente que "rescata" partes de esa cadena temporal. Usted verá este +// Concepto denominado "movimiento semántico". + +//////////////////////////////////////////// +// Clases y programación orientada a objetos +//////////////////////////////////////////// + +// Primer ejemplo de clases +#include + +// Declara una clase. +// Las clases son usualmente declaradas en archivos de cabeceras (.h o .hpp) +class Dog { + // Variables y funciones de la clase son privados por defecto. + std::string name; + int weight; + +// Todos los miembros siguientes de este son públicos +// Hasta que se encuentre "private" o "protected". +// All members following this are public +// until "private:" or "protected:" is found. +public: + + // Constructor por defecto + Dog(); + + // Declaraciones de funciones de la clase (implementaciones a seguir) +    // Nota que usamos std::string aquí en lugar de colocar +    // using namespace std; +    // arriba. +    // Nunca ponga una declaración "using namespace" en un encabezado. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + // Funciones que no modifican el estado del objeto + // Deben marcarse como const. + // Esto le permite llamarlas si se envia una referencia constante al objeto. + // También tenga en cuenta que las funciones deben ser declaradas + // explícitamente como _virtual_ para que sea reemplazada en las clases + // derivadas. + // Las funciones no son virtuales por defecto por razones de rendimiento. + virtual void print() const; + + // Las funciones también se pueden definir en el interior + // del cuerpo de la clase. + // Funciones definidas como tales están entre líneas automáticamente. + void bark() const { std::cout << name << " barks!\n"; } + + // Junto a los constructores, C++ proporciona destructores. + // Estos son llamados cuando un objeto se elimina o está fuera del ámbito. + // Esto permite paradigmas potentes como RAII + // (mira abajo) + // El destructor debe ser virtual si una clase es dervada desde el; + // Si no es virtual, entonces la clase derivada destructor + // No será llamada si el objeto se destruye a través de una referencia de + // la clase base o puntero. + virtual ~Dog(); + + + +}; // Un punto y coma debe seguir la definición de clase. + +// Las funciones de una clase son normalmente implementados en archivos .cpp. +Dog::Dog() +{ + std::cout << "Un perro ha sido construido\n"; +} + +// Objetos (tales como cadenas) deben ser pasados por referencia +// Si los estas modificando o referencia constante en caso contrario. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Nota que "virtual" sólo se necesita en la declaración, no en la definición. +void Dog::print() const +{ + std::cout << "El perro es " << name << " y pesa " << weight << "kg\n"; +} + +Dog::~Dog() +{ + cout << "Adiós " << name << "\n"; +} + +int main() { + Dog myDog; // imprime "Un perro ha sido construido" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.print(); // imprime "El perro es Barkley y pesa 10 kg" + return 0; +} // imprime "Adiós Barkley" + +// Herencia: + +// Esta clase hereda todo lo público y protegido de la clase Dog +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner); + + // Reemplaza el comportamiento de la función de impresión + // de todos los OwnedDogs. Mira + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // Para una introducción más general si no está familiarizado con el + // polimorfismo de subtipo. + // La palabra clave override es opcional, pero asegura que estás + // reemplazando el método de una clase base. + void print() const override; + +private: + std::string owner; +}; + +// Mientras tanto, en el archivo .cpp correspondiente: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Llama a la función de impresión en la clase base Dog + std::cout << "El perro es de " << owner << "\n"; + // Imprime "El perro es y pesa " + // "El perro es de " +} + +//////////////////////////////////////////// +// Inicialización y sobrecarga de operadores +//////////////////////////////////////////// + +// En C ++ se puede sobrecargar el comportamiento +// de los operadores como +, -, *, /, etc. +// Esto se hace mediante la definición de una función que es llamada +// cada vez que se utiliza el operador. + +#include +using namespace std; + +class Point { +public: + // Las variables de la clase pueden dar valores por defecto de esta manera. + double x = 0; + double y = 0; + + // Define un constructor por defecto que no hace nada + // pero inicializa el punto al valor por defecto (0, 0) + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* No hace nada excepto inicializar los valores */ } + + // Sobrecarga el operador + + Point operator+(const Point& rhs) const; + + // Sobrecarga el operador += + Point& operator+=(const Point& rhs); + + // También tendría sentido añadir los operadores - y -=, +    // Pero vamos a omitirlos por razones de brevedad. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Crea un nuevo punto que es la suma de este y rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // Llama al operador + de Point + // Point llama la función + con right como parámetro + Point result = up + right; + // Prints "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////////// +// Plantillas (Templates) +///////////////////////// + +// Las plantillas en C++ se utilizan sobre todo en la programación genérica, +// a pesar de que son mucho más poderoso que los constructores genéricos +// en otros lenguajes. Ellos también soportan especialización explícita y +// parcial y clases de tipo estilo funcional; de hecho, son un lenguaje +// funcional Turing-completo incrustado en C ++! + +// Empezamos con el tipo de programación genérica que podría estar +// familiarizado. +// Para definir una clase o función que toma un parámetro de tipo: +template +class Box { +public: + // En este caso, T puede ser usado como cualquier otro tipo. + void insert(const T&) { ... } +}; + +// Durante la compilación, el compilador realmente genera copias de cada +// plantilla con parámetros sustituidos, por lo que la definición completa +// de la clase debe estar presente en cada invocación. +// Es por esto que usted verá clases de plantilla definidas +// Enteramente en archivos de cabecera. + +//Para crear una instancia de una clase de plantilla en la pila: +Box intBox; + +y puedes utilizarlo como era de esperar: +intBox.insert(123); + +// Puedes, por supuesto, anidar plantillas: +Box > boxOfBox; +boxOfBox.insert(intBox); + +// Hasta C++11, había que colocar un espacio entre los dos '>'s, +// de lo contrario '>>' serían analizados como el operador de desplazamiento +// a la derecha. + + +// A veces verás +// template +// en su lugar. La palabra clave "class" y las palabras clave "typename" son +// mayormente intercambiables en este caso. Para la explicación completa, mira +// http://en.wikipedia.org/wiki/Typename +// (sí, esa palabra clave tiene su propia página de Wikipedia). + +// Del mismo modo, una plantilla de función: +template +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// Observe que no se especifica nada acerca de los tipos de parámetros aquí. +// El compilador generará y comprobará cada invocación de la plantilla, +// por lo que la función anterior funciona con cualquier tipo "T" +// que tenga un método 'bark' constante! + + +Dog fluffy; +fluffy.setName("Fluffy") +barkThreeTimes(fluffy); // Imprime "Fluffy barks" 3 veces. + +Los parámetros de la plantilla no tienen que ser las clases: +template +void printMessage() { + cout << "Aprende C++ en " << Y << " minutos!" << endl; +} + +// Y usted puede especializar explícitamente plantillas +// para código más eficiente. +// Por supuesto, la mayor parte del mundo real que utiliza una especialización +// no son tan triviales como esta. +// Tenga en cuenta que usted todavía tiene que declarar la función (o clase) +// como plantilla incluso si ha especificado de forma explícita todos +// los parámetros. + +template<> +void printMessage<10>() { + cout << "Aprende C++ rapido en solo 10 minutos!" << endl; +} + +printMessage<20>(); // Prints "Aprende C++ en 20 minutos!" +printMessage<10>(); // Prints "Aprende C++ rapido en solo 10 minutos!" + + +///////////////////// +// Manejador de excepciones +///////////////////// + +// La biblioteca estándar proporciona algunos tipos de excepción +// (mira http://en.cppreference.com/w/cpp/error/exception) +// pero cualquier tipo puede ser lanzado como una excepción +#include +#include + +//Todas las excepciones lanzadas dentro del bloque _try_ pueden ser +// capturados por los siguientes manejadores _catch_. +try { + // No asignar excepciones en el heap usando _new_. + throw std::runtime_error("Ocurrió un problema"); +} + +// Captura excepciones por referencia const si son objetos +catch (const std::exception& ex) +{ + std::cout << ex.what(); +} +******************************************************************************** +// Captura cualquier excepción no capturada por bloques _catch_ anteriores +catch (...) +{ + std::cout << "Excepción desconocida capturada"; + throw; // Re-lanza la excepción +} + +/////// +// RAII +/////// + +// RAII significa "Resource Acquisition Is Initialization" +// (Adquisición de recursos es inicialización). +// A menudo se considera el paradigma más poderoso en C++ +// Y el concepto es simple: un constructor de un objeto +// Adquiere recursos de ese objeto y el destructor les libera. + +// Para entender cómo esto es útil, +// Considere una función que utiliza un identificador de archivo C: +void doSomethingWithAFile(const char* filename) +{ + // Para empezar, asuma que nada puede fallar. + + FILE* fh = fopen(filename, "r"); // Abre el archivo en modo lectura + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Cierra el manejador de archivos +} + +// Por desgracia, las cosas se complican rápidamente por el control de errores. +// Supongamos que fopen puede fallar, y que doSomethingWithTheFile y +// DoSomethingElseWithIt retornan códigos de error si fallan. +// (Excepciones son la mejor forma de manejar los fallos, +// pero algunos programadores, especialmente los que tienen un fondo C, +// estan en desacuerdo sobre la utilidad de las excepciones). +// Ahora tenemos que comprobar cada llamado por fallos y cerrar el manejador +// del archivo si se ha producido un problema. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abre el archivo en modo lectura + if (fh == nullptr) // El puntero retornado es nulo o falla. + return false; // Reporta el fallo a quien hizo el llamado. + + // Asume que cada función retorna falso si falla + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Cierre el manejador de archivo para que no se filtre. + return false; // Propaga el error. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Cierre el manejador de archivo para que no se filtre. + return false; // Propaga el error. + } + + fclose(fh); // Cierre el archivo. + return true; // Indica que todo funcionó correctamente. +} + +// Programadores C suelen limpiar esto un poco usando goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Cierre el archivo. + return true; // Indica que todo funcionó correctamente. + +failure: + fclose(fh); + return false; // Propagate el error +} + +// Si las funciones indican errores mediante excepciones, +// Las cosas son un poco más claras, pero pueden optimizarse mas. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abrir el archivo en modo lectura + if (fh == nullptr) + throw std::runtime_error("No puede abrirse el archivo."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Asegúrese de cerrar el archivo si se produce un error. + throw; // Luego vuelve a lanzar la excepción. + } + + fclose(fh); // Cierra el archivo +} + +// Compare esto con el uso de la clase de flujo de archivos de C++ (fstream) +// fstream utiliza su destructor para cerrar el archivo. +// Los destructores son llamados automáticamente +// cuando un objeto queda fuera del ámbito. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream es la abreviatura de el input file stream + std::ifstream fh(filename); // Abre el archivo + + // Hacer algo con el archivo + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // El archivo se cierra automáticamente aquí por el destructor + + +// Esto tiene ventajas _enormes_: +// 1. No importa lo que pase, +// El recurso (en este caso el manejador de archivo) será limpiado. +// Una vez que escribes el destructor correctamente, +// Es _imposible_ olvidar cerrar el identificador y permitir +// fugas del recurso. +// 2. Tenga en cuenta que el código es mucho más limpio. +// El destructor se encarga de cerrar el archivo detrás de cámaras +// Sin que tenga que preocuparse por ello. +// 3. El código es seguro. +// Una excepción puede ser lanzado en cualquier lugar de la función +// y la limpieza ocurrirá. + +// Todo el código idiomático C++ utiliza RAII ampliamente para todos los +// recursos. +// Otros ejemplos incluyen +// - Memoria usando unique_ptr y shared_ptr +// - Contenedores (Containers) - la biblioteca estándar linked list, +// vector (es decir, array con auto-cambio de tamaño), hash maps, etc. +// Destruimos todos sus contenidos de forma automática +// cuando quedan fuera del ámbito. +// - Mutex utilizando lock_guard y unique_lock + + +///////////////////// +// Cosas divertidas +///////////////////// + +// Aspectos de C ++ que pueden sorprender a los recién llegados +// (e incluso algunos veteranos). +// Esta sección es, por desgracia, salvajemente incompleta; +// C++ es uno de los lenguajes con los que mas facil te disparas en el pie. + +// Tu puedes sobreescribir métodos privados! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Sobreescribe Foo::bar! +}; + + +// 0 == false == NULL (La mayoria de las veces)! +bool* pt = new bool; +*pt = 0; // Establece los puntos de valor de 'pt' en falso. +pt = 0; // Establece 'pt' al apuntador nulo. Ambas lineas compilan sin error. + +// nullptr se supone que arregla un poco de ese tema: +int* pt2 = new int; +*pt2 = nullptr; // No compila +pt2 = nullptr; // Establece pt2 como null. + +// Hay una excepción para los valores bool. +// Esto es para permitir poner a prueba punteros nulos con if (!ptr), +// pero como consecuencia se puede asignar nullptr a un bool directamente! +*pt = nullptr; // Esto todavía compila, a pesar de que '*pt' es un bool! + +// '=' != '=' != '='! +// Llama Foo::Foo(const Foo&) o alguna variante (mira movimientos semanticos) +// copia del constructor. +Foo f2; +Foo f1 = f2; + +// Llama Foo::Foo(const Foo&) o variante, pero solo copia el 'Foo' parte de +// 'fooSub'. Cualquier miembro extra de 'fooSub' se descarta. Este +// comportamiento horrible se llama "Corte de objetos." +FooSub fooSub; +Foo f1 = fooSub; + +// Llama a Foo::operator=(Foo&) o variantes. +Foo f1; +f1 = f2; + + +// Cómo borrar realmente un contenedor: +class Foo { ... }; +vector v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); +// La siguiente línea establece el tamaño de v en 0, +// pero los destructores no son llamados y los recursos no se liberan! + +v.empty(); +v.push_back(Foo()); // Nuevo valor se copia en el primer Foo que insertamos + +// En verdad destruye todos los valores en v. +// Consulta la sección acerca de los objetos temporales para la +// explicación de por qué esto funciona. +v.swap(vector()); + +``` +Otras lecturas: + +Una referencia del lenguaje hasta a la fecha se puede encontrar en + + +Recursos adicionales se pueden encontrar en -- cgit v1.2.3 From 224d4e9c7f8b13da852662edcf57f83d7f78c278 Mon Sep 17 00:00:00 2001 From: Jesus Tinoco Date: Sun, 4 Oct 2015 13:17:50 +0200 Subject: Fixing typo in git-es.html.markdown --- es-es/git-es.html.markdown | 64 +++++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 73853a9d..f370aa4d 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -11,15 +11,15 @@ lang: es-es --- Git es un sistema de control de versiones distribuido diseñado para manejar -cualquier tipo de proyecto ya sea largos o pequeños, con velocidad y eficiencia. +cualquier tipo de proyect,o ya sea largo o pequeño, con velocidad y eficiencia. Git realiza esto haciendo "snapshots" del proyecto, con ello permite versionar y administrar nuestro código fuente. ## Versionamiento, conceptos. -### Que es el control de versiones? -El control de versiones es un sistema que guarda todos los cambios realizados a +### Qué es el control de versiones? +El control de versiones es un sistema que guarda todos los cambios realizados en uno o varios archivos, a lo largo del tiempo. ### Versionamiento centralizado vs Versionamiento Distribuido. @@ -31,15 +31,15 @@ uno o varios archivos, a lo largo del tiempo. + El versionamiento distribuido no tiene una estructura definida, incluso se puede mantener el estilo de los repositorios SVN con git. -[Informacion adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) +[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) -### Por que usar Git? +### Por qué usar Git? * Se puede trabajar sin conexion. * Colaborar con otros es sencillo!. -* Derivar, Crear ramas del proyecto (aka: Branching) es facil!. +* Derivar, Crear ramas del proyecto (aka: Branching) es fácil!. * Combinar (aka: Merging) -* Git es rapido. +* Git es rápido. * Git es flexible. ## Arquitectura de Git. @@ -48,10 +48,10 @@ uno o varios archivos, a lo largo del tiempo. Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: comits), y encabezados (aka: heads). Imagina que un repositorio es una clase, -y que sus atributos otorgan acceso al historial del elemento, ademas de otras +y que sus atributos otorgan acceso al historial del elemento, además de otras cosas. -Un repositorio esta compuesto por la carpeta .git y un "arbol de trabajo". +Un repositorio esta compuesto por la carpeta .git y un "árbol de trabajo". ### Directorio .git (componentes del repositorio) @@ -62,38 +62,38 @@ y mas. ### Directorio de trabajo (componentes del repositorio) -Es basicamente los directorios y archivos dentro del repositorio. La mayorioa de +Es basicamente los directorios y archivos dentro del repositorio. La mayoría de las veces se le llama "directorio de trabajo". -### Inidice (componentes del directorio .git) +### Índice (componentes del directorio .git) -El inidice es la area de inicio en git. Es basicamente la capa que separa el +El índice es el área de inicio en git. Es basicamente la capa que separa el directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores -mas poder sobre lo que envia y recibe en el repositorio. +mas poder sobre lo que envía y recibe en el repositorio. ### Commit (aka: cambios) Un commit es una captura de un conjunto de cambios, o modificaciones hechas en el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2, -estos cambios se almacenaran en un commit (aka: captura). Este commit puede ser o +estos cambios se almacenarán en un commit (aka: captura). Este commit puede ser o no ser enviado (aka: "pusheado") hacia un repositorio. ### Branch (rama) -Un "branch", es escencialmente un apuntador hacia el ultimo commit (cambio -registrado) que se ha realizado. A medida que se realizan mas commits, este -apuntador se actualizara automaticamente hacia el ultimo commit. +Un "branch", es escencialmente un apuntador hacia el último commit (cambio +registrado) que se ha realizado. A medida que se realizan más commits, este +apuntador se actualizará automaticamente hacia el ultimo commit. ### "HEAD" y "head" (component of .git dir) "HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a -cualquier commit realizado, un repositorio puede tener cualquier numero de +cualquier commit realizado, un repositorio puede tener cualquier número de "heads". ### conceptos - recursos. -* [Git para informaticos](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para informáticos](http://eagain.net/articles/git-for-computer-scientists/) * [Git para diseñadores](http://hoth.entp.com/output/git_for_designers.html) @@ -102,8 +102,8 @@ cualquier commit realizado, un repositorio puede tener cualquier numero de ### init -Crear un repositorio de git vacio. Las configuraciones, informacion almacenada y -demas son almacenadas en el directorio ".git". +Crear un repositorio de git vacio. Las configuraciones, información almacenada y +demás son almacenadas en el directorio ".git". ```bash $ git init @@ -127,7 +127,7 @@ $ git config --global user.name "nombre" ### help -Otorga un accceso rapido a una guia extremadamente detallada de cada comando en +Otorga un accceso rápido a una guía extremadamente detallada de cada comando en git. O puede ser usada simplemente como un recordatorio de estos. ```bash @@ -146,7 +146,7 @@ $ git help init ### status -Muestra las diferencias entre el archivo indice y el commit al cual apunta el +Muestra las diferencias entre el archivo índice y el commit al cual apunta el HEAD actualmente. @@ -163,7 +163,7 @@ $ git help status Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por -lo que no se incluiran en los commits (cambios). +lo que no se incluirán en los commits (cambios). ```bash # Añade un archivo en el directorio de trabajo actual. @@ -202,7 +202,7 @@ $ git branch master --edit-description ### checkout Actualiza todos los archivos en el directorio de trabajo para que sean igual que -las versiones almacenadas en el indice, o en un arbol de trabajo especificado. +las versiones almacenadas en el índice, o en un árbol de trabajo especificado. ```bash # Despachar un repositorio. - Por defecto la master branch. (la rama principal llamada 'master') @@ -215,8 +215,8 @@ $ git checkout -b jdei ### clone -Clona, o copia, una repo existente en un nuevo directorio. Tambien añada el -seguimiento hacia las ramas existentes del repo que ha sido clonada, lo que +Clona, o copia, un repositorio existente en un nuevo directorio. También añade el +seguimiento hacia las ramas existentes del repositorio que ha sido clonado, lo que permite subir (push) los archivos hacia una rama remota. ```bash @@ -226,8 +226,8 @@ $ git clone https://github.com/jquery/jquery.git ### commit -Almacena los cambios que almacenados en el indice en un nuevo "commit". Este -commit contiene los cambios hechos mas un resumen hecho por el desarrollador. +Almacena el contenido actual del índice en un nuevo "commit". Este +commit contiene los cambios hechos más un resumen proporcionado por el desarrollador. ```bash # commit with a message @@ -237,8 +237,8 @@ $ git commit -m "jedi anakin wil be - jedis.list" ### diff -Muestra las diferencias entre un archivo en el directorio de trabajo, el indice -y commits. +Muestra las diferencias entre un archivo en el directorio de trabajo, el índice +y los commits. ```bash # Muestra la diferencia entre un directorio de trabajo y el indice. @@ -253,7 +253,7 @@ $ git diff HEAD ### grep -Permite realizar una busqueda rapida en un repositorio. +Permite realizar una busqueda rápida en un repositorio. Configuracion opcionales: -- cgit v1.2.3 From f7cfb3b194ff4fb590173cb7e790c4effc1656c0 Mon Sep 17 00:00:00 2001 From: edholland Date: Sun, 4 Oct 2015 13:18:06 +0200 Subject: Fix poor formatting and typos --- erlang.html.markdown | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 64330867..48cee6ec 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -308,25 +308,25 @@ self(). % <0.41.0> % Unit tests can be written using EUnits's test generators and assert macros -module(fib). - -export([fib/1]). - -include_lib("eunit/include/eunit.hrl"). - - fib(0) -> 1; - fib(1) -> 1; - fib(N) when N > 1 -> fib(N-1) + fib(N-2). - - fib_test_() -> - [?_assert(fib(0) =:= 1), - ?_assert(fib(1) =:= 1), - ?_assert(fib(2) =:= 2), - ?_assert(fib(3) =:= 3), - ?_assert(fib(4) =:= 5), - ?_assert(fib(5) =:= 8), - ?_assertException(error, function_clause, fib(-1)), - ?_assert(fib(31) =:= 2178309) - ]. - -% EUnit will automatically export to a test() fucntion to allo running the tests +-export([fib/1]). +-include_lib("eunit/include/eunit.hrl"). + +fib(0) -> 1; +fib(1) -> 1; +fib(N) when N > 1 -> fib(N-1) + fib(N-2). + +fib_test_() -> + [?_assert(fib(0) =:= 1), + ?_assert(fib(1) =:= 1), + ?_assert(fib(2) =:= 2), + ?_assert(fib(3) =:= 3), + ?_assert(fib(4) =:= 5), + ?_assert(fib(5) =:= 8), + ?_assertException(error, function_clause, fib(-1)), + ?_assert(fib(31) =:= 2178309) + ]. + +% EUnit will automatically export to a test() function to allow running the tests % in the erlang shell fib:test() -- cgit v1.2.3 From 8aec122beaffc6d7d8e108aa4bbe4a2218062a46 Mon Sep 17 00:00:00 2001 From: Jesus Tinoco Date: Sun, 4 Oct 2015 13:19:34 +0200 Subject: Typos fixed in git-es.html.markdown --- es-es/git-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index f370aa4d..51812447 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -11,7 +11,7 @@ lang: es-es --- Git es un sistema de control de versiones distribuido diseñado para manejar -cualquier tipo de proyect,o ya sea largo o pequeño, con velocidad y eficiencia. +cualquier tipo de proyecto, ya sea largo o pequeño, con velocidad y eficiencia. Git realiza esto haciendo "snapshots" del proyecto, con ello permite versionar y administrar nuestro código fuente. -- cgit v1.2.3 From 6b6f88c64d9a4b2d26de5725dee24f3c459fb93c Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Sun, 4 Oct 2015 01:47:09 +0530 Subject: Added abstract classes --- java.html.markdown | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 928eb39f..2f41be81 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -451,6 +451,74 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, public void InterfaceTwoMethod() { } } + + +// Abstract Classes +// Abstract Class declaration syntax +// abstract extends { +// // Constants and variables +// // Method declarations +// } + +// Methods can't have bodies in an interface, unless the method is +// static. Also variables are NOT final by default, unlike an interface. +// Also abstract classes CAN have the "main" method. +// Abstract classes solve these problems. + +public abstract class Animal +{ + public abstract void makeSound(); + + // Method can have a body + public void eat() + { + System.out.println("I am an animal and I am Eating."); + // Note: We can access private variable here. + age = 30; + } + + // No need to initialise, however in an interface + // a variable is implicitly final and hence has + // to be initialised. + private int age; + + public void printAge() + { + System.out.println(age); + } + + // Abstract classes can have main function. + public static void main(String[] args) + { + System.out.println("I am abstract"); + } +} + +class Dog extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Bark"); + // age = 30; ==> ERROR! age is private to Animal + } + + // NOTE: You will get an error if you used the + // @Override annotation here, since java doesn't allow + // overriding of static methods. + // What is happening here is called METHOD HIDING. + // Check out this awesome SO post: (http://stackoverflow.com/questions/16313649/) + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + ``` ## Further Reading -- cgit v1.2.3 From f1a90a4e636616ce91a271504eee3f374bfd7094 Mon Sep 17 00:00:00 2001 From: Guntbert Reiter Date: Sun, 4 Oct 2015 16:44:24 +0200 Subject: Put demonstrative condition into ternary expression It should be made clear that the part before the ternary operator is indeed a condition, most often created as some comparison expression. --- csharp.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 479b7f01..222ba0d2 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -236,7 +236,8 @@ on a new line! ""Wow!"", the masses cried"; // Ternary operators // A simple if/else can be written as follows // ? : - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // While loop int fooWhile = 0; -- cgit v1.2.3 From ff1b91d463938a0809f4115c20c6f9fc89e24cfc Mon Sep 17 00:00:00 2001 From: David Lima Date: Sun, 4 Oct 2015 11:55:16 -0300 Subject: [hack/en] Fixed some typos --- hack.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/hack.html.markdown b/hack.html.markdown index 632fc705..b9730dc0 100644 --- a/hack.html.markdown +++ b/hack.html.markdown @@ -2,6 +2,7 @@ language: Hack contributors: - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] filename: learnhack.hh --- @@ -152,7 +153,7 @@ class ArgumentPromotion private bool $isAwesome) {} } -class WithoutArugmentPromotion +class WithoutArgumentPromotion { public string $name; @@ -169,9 +170,9 @@ class WithoutArugmentPromotion } -// Co-oprerative multi-tasking +// Co-operative multi-tasking // -// Two new keywords "async" and "await" can be used to perform mutli-tasking +// Two new keywords "async" and "await" can be used to perform multi-tasking // Note that this does not involve threads - it just allows transfer of control async function cooperativePrint(int $start, int $end) : Awaitable { -- cgit v1.2.3 From 29ea66dbef66944f59b5a7abe68b7113e1679791 Mon Sep 17 00:00:00 2001 From: David Lima Date: Sun, 4 Oct 2015 12:02:20 -0300 Subject: [hack/pt-br] Add pt-br translation --- pt-br/hack-pt.html.markdown | 316 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 316 insertions(+) create mode 100644 pt-br/hack-pt.html.markdown diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown new file mode 100644 index 00000000..3efa5f0a --- /dev/null +++ b/pt-br/hack-pt.html.markdown @@ -0,0 +1,316 @@ +--- +language: Hack +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] +translators: + - ["David Lima", "https://github.com/davelima"] +lang: pt-br +filename: learnhack.hh +--- + +Hack é uma linguagem baseada no PHP e roda numa máquina virtual chamada HHVM. +Hack é quase completamente interoperável com códigos PHP existentes e adiciona +alguns recursos úteis de linguagens estaticamente tipadas. + +Somente recursos específicos da linguagem Hack serão abordados aqui. Detalhes +sobre a sintaxe do PHP estão disponíveis no +[artigo PHP](http://learnxinyminutes.com/docs/php/) neste site. + +```php +id = $id; + } +} + + +// Funções anônimas (lambdas) +$multiplicador = 5; +array_map($y ==> $y * $multiplicador, [1, 2, 3]); + + +// Genéricos +class Caixa +{ + protected T $dados; + + public function __construct(T $dados) { + $this->dados = $dados; + } + + public function pegaDados(): T { + return $this->dados; + } +} + +function abreCaixa(Caixa $caixa) : int +{ + return $caixa->pegaDados(); +} + + +// Formas +// +// Hack adiciona o conceito de formas para definir arrays com uma estrutura +// e tipos de dados garantidos +type Point2D = shape('x' => int, 'y' => int); + +function distancia(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distancia( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Pseudônimos de tipos +// +// Hack adiciona vários recursos para criação de pseudônimos, tornando tipos complexos +// mais fáceis de entender +newtype VectorArray = array>; + +// Um tuple contendo dois inteiros +newtype Point = (int, int); + +function adicionaPontos(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +adicionaPontos( + tuple(1, 2), + tuple(5, 6) +); + + +// enums em classes +enum TipoDePista : int +{ + Estrada = 0; + Rua = 1; + Alameda = 2; + Avenida = 3; +} + +function getTipoDePista() : TipoDePista +{ + return TipoDePista::Alameda; +} + + +// Especificação de argumentos no construtor (Argument Promotion) +// +// Para evitar que propriedades sejam definidas em mais de um lugar, e +// construtores que só definem propriedades, o Hack adiciona uma sintaxe para +// definir as propriedades e o construtor ao mesmo tempo. +class ArgumentPromotion +{ + public function __construct(public string $nome, + protected int $idade, + private bool $legal) {} +} + +class SemArgumentPromotion +{ + public string $nome; + + protected int $idade; + + private bool $legal; + + public function __construct(string $nome, int $idade, bool $legal) + { + $this->nome = $nome; + $this->idade = $idade; + $this->legal = $legal; + } +} + + +// Multi-tarefas cooperativo +// +// Duas novas palavras-chave ("async" e "await") podem ser usadas para +// trabalhar com multi-tarefas. +// Obs. Isto não envolve threads - apenas permite a transferência de controle +async function printCooperativo(int $inicio, int $fim) : Awaitable +{ + for ($i = $inicio; $i <= $fim; $i++) { + echo "$i "; + + // Permite que outras tarefas façam algo + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// Imprime "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + printCooperativo(1, 3), + printCooperativo(4, 6), + printCooperativo(7, 9) +])->getWaitHandle()->join(); + + +// Atributos +// +// Atributos são uma forma de definir metadados para funções. +// Hack tem alguns atributos especiais que possuem comportamentos úteis. + +// O atributo especial __Memoize faz com que o resultado da função fique em cache +<<__Memoize>> +function tarefaDemorada() : ?string +{ + return file_get_contents('http://exemplo.com'); +} + +// O corpo da função só é executado uma vez aqui: +tarefaDemorada(); +tarefaDemorada(); + + +// O atributo especial __ConsistentConstruct faz com que o Hack certifique-se +// de que a assinatura do construtor seja a mesma em todas as subclasses +<<__ConsistentConstruct>> +class FooConsistente +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function algumMetodo() + { + // ... + } +} + +class BarConsistente extends FooConsistente +{ + public function __construct(int $x, float $y) + { + // O verificador de tipos do Hack exige que os construtores pai + // sejam chamados + parent::__construct($x, $y); + + // ... + } + + // A anotação __Override é uma anotação opcional que faz com que o + // verificador de tipos do Hack sobrescreva um método em uma classe pai + // ou um trait. Sem __Override, definir este método causará um erro, + // pois ele já foi definido na classe pai (FooConsistente): + <<__Override>> + public function algumMetodo() + { + // ... + } +} + +class SubclasseFooInvalida extends FooConsistente +{ + // Caso o construtor não combine com o construtor da classe pai, o + // verificador de tipos acusará um erro: + // + // "Este objeto é incompatível com o objeto FooConsistente porque algum(ns) + // dos seus métodos são incompatíveis" + // + public function __construct(float $x) + { + // ... + } + + // Usar a anotação __Override em um método que não existe na classe pai + // causará um erro do verificador de tipos: + // "SubclasseFooInvalida::outroMetodo() está marcada para sobrescrever; + // nenhuma definição não-privada foi encontrada ou a classe pai foi + // definida em código não-> + public function outroMetodo() + { + // ... + } +} + + +// Traits podem implementar interfaces (não suportado pelo PHP) +interface InterfaceGatinho +{ + public function brinca() : void; +} + +trait TraitGato implements GatinhoInterface +{ + public function brinca() : void + { + // ... + } +} + +class Samuel +{ + use TraitGato; +} + + +$gato = new Samuel(); +$gato instanceof GatinhoInterface === true; // True + +``` + +## Mais informações + +Visite a [documentação do Hack](http://docs.hhvm.com/manual/en/hacklangref.php) +para ver explicações detalhadas dos recursos que Hack adiciona ao PHP, ou o [site oficial do Hack](http://hanlang.org/) +para outras informações. + +Visite o [site oficial do HHVM](http://hhvm.com/) para aprender a instalar o HHVM. + +Visite [este artigo](http://docs.hhvm.com/manual/en/hack.unsupported.php) para ver +os recursos do PHP que o Hack não suporta e ver incompatibilidades entre Hack e PHP. -- cgit v1.2.3 From 09f8a34244af976f7ca29efc620a6bd51ad4ffa7 Mon Sep 17 00:00:00 2001 From: David Lima Date: Sun, 4 Oct 2015 12:05:07 -0300 Subject: [hack/pt-br] Fixed some typos --- pt-br/hack-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown index 3efa5f0a..2f9d3c1b 100644 --- a/pt-br/hack-pt.html.markdown +++ b/pt-br/hack-pt.html.markdown @@ -285,7 +285,7 @@ interface InterfaceGatinho public function brinca() : void; } -trait TraitGato implements GatinhoInterface +trait TraitGato implements InterfaceGatinho { public function brinca() : void { @@ -300,7 +300,7 @@ class Samuel $gato = new Samuel(); -$gato instanceof GatinhoInterface === true; // True +$gato instanceof InterfaceGatinho === true; // True ``` -- cgit v1.2.3 From fbd07f268cd6e64c65912ccc27f2ec9e222ec536 Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Sun, 4 Oct 2015 21:24:57 +0530 Subject: Issue #1157 Comment explaining '-p', in line 178. --- common-lisp.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index f9f64d68..e3bb61cf 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -175,7 +175,8 @@ nil ; for false - and the empty list :age 5)) *rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) -(dog-p *rover*) ; => t ;; ewww) +(dog-p *rover*) ; => true #| -p signifies "predicate". It's used to + check if *rover* is an instance of dog.|# (dog-name *rover*) ; => "rover" ;; Dog-p, make-dog, and dog-name are all created by defstruct! -- cgit v1.2.3 From c57868703a6462a0ad64b27d3887b970272ebb4d Mon Sep 17 00:00:00 2001 From: jig08 Date: Sun, 4 Oct 2015 22:14:31 +0530 Subject: Adding smalltalk tut --- ko-kr/.Rhistory | 0 smalltalk.html.markdown | 959 +++++++++++++++++++++++++++++++++++++++++++++++ smalltalk.html.markdown~ | 959 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1918 insertions(+) create mode 100644 ko-kr/.Rhistory create mode 100644 smalltalk.html.markdown create mode 100644 smalltalk.html.markdown~ diff --git a/ko-kr/.Rhistory b/ko-kr/.Rhistory new file mode 100644 index 00000000..e69de29b diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown new file mode 100644 index 00000000..61e5a94c --- /dev/null +++ b/smalltalk.html.markdown @@ -0,0 +1,959 @@ +--- +language: smalltalk +contributors: + - ["Jigyasa Grover", "https://github.com/jig08"] +--- + +- Smalltalk is an object-oriented, dynamically typed, reflective programming language. +- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." +- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s. + +Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`. + +``` + +"************************************************************************ + * Allowable characters: * + * - a-z * + * - A-Z * + * - 0-9 * + * - .+/\*~<>@%|&? * + * - blank, tab, cr, ff, lf * + * * + * Variables: * + * - variables must be declared before use * + * - shared vars must begin with uppercase * + * - local vars must begin with lowercase * + * - reserved names: nil, true, false, self, super, and Smalltalk * + * * + * Variable scope: * + * - Global: defined in Dictionary Smalltalk and accessible by all * + * objects in system * + * - Special: (reserved) Smalltalk, super, self, true, false, & nil * + * - Method Temporary: local to a method * + * - Block Temporary: local to a block * + * - Pool: variables in a Dictionary object * + * - Method Parameters: automatic local vars created as a result of * + * message call with params * + * - Block Parameters: automatic local vars created as a result of * + * value: message call * + * - Class: shared with all instances of one class & its subclasses * + * - Class Instance: unique to each instance of a class * + * - Instance Variables: unique to each instance * + ************************************************************************" +"Comments are enclosed in quotes" +"Period (.) is the statement seperator" + +"************************************************************************ + * Transcript: * + ************************************************************************" +Transcript clear. "clear to transcript window" +Transcript show: 'Hello World'. "output string in transcript window" +Transcript nextPutAll: 'Hello World'. "output string in transcript window" +Transcript nextPut: $A. "output character in transcript window" +Transcript space. "output space character in transcript window" +Transcript tab. "output tab character in transcript window" +Transcript cr. "carriage return / linefeed" +'Hello' printOn: Transcript. "append print string into the window" +'Hello' storeOn: Transcript. "append store string into the window" +Transcript endEntry. "flush the output buffer" + +"************************************************************************ + * Assignment: * + ************************************************************************" +| x y | +x _ 4. "assignment (Squeak) <-" +x := 5. "assignment" +x := y := z := 6. "compound assignment" +x := (y := 6) + 1. +x := Object new. "bind to allocated instance of a class" +x := 123 class. "discover the object class" +x := Integer superclass. "discover the superclass of a class" +x := Object allInstances. "get an array of all instances of a class" +x := Integer allSuperclasses. "get all superclasses of a class" +x := 1.2 hash. "hash value for object" +y := x copy. "copy object" +y := x shallowCopy. "copy object (not overridden)" +y := x deepCopy. "copy object and instance vars" +y := x veryDeepCopy. "complete tree copy using a dictionary" + +"************************************************************************ + * Constants: * + ************************************************************************" +| b | +b := true. "true constant" +b := false. "false constant" +x := nil. "nil object constant" +x := 1. "integer constants" +x := 3.14. "float constants" +x := 2e-2. "fractional constants" +x := 16r0F. "hex constant". +x := -1. "negative constants" +x := 'Hello'. "string constant" +x := 'I''m here'. "single quote escape" +x := $A. "character constant" +x := $ . "character constant (space)" +x := #aSymbol. "symbol constants" +x := #(3 2 1). "array constants" +x := #('abc' 2 $a). "mixing of types allowed" + +"************************************************************************ + * Booleans: * + ************************************************************************" +| b x y | +x := 1. y := 2. +b := (x = y). "equals" +b := (x ~= y). "not equals" +b := (x == y). "identical" +b := (x ~~ y). "not identical" +b := (x > y). "greater than" +b := (x < y). "less than" +b := (x >= y). "greater than or equal" +b := (x <= y). "less than or equal" +b := b not. "boolean not" +b := (x < 5) & (y > 1). "boolean and" +b := (x < 5) | (y > 1). "boolean or" +b := (x < 5) and: [y > 1]. "boolean and (short-circuit)" +b := (x < 5) or: [y > 1]. "boolean or (short-circuit)" +b := (x < 5) eqv: (y > 1). "test if both true or both false" +b := (x < 5) xor: (y > 1). "test if one true and other false" +b := 5 between: 3 and: 12. "between (inclusive)" +b := 123 isKindOf: Number. "test if object is class or subclass of" +b := 123 isMemberOf: SmallInteger. "test if object is type of class" +b := 123 respondsTo: sqrt. "test if object responds to message" +b := x isNil. "test if object is nil" +b := x isZero. "test if number is zero" +b := x positive. "test if number is positive" +b := x strictlyPositive. "test if number is greater than zero" +b := x negative. "test if number is negative" +b := x even. "test if number is even" +b := x odd. "test if number is odd" +b := x isLiteral. "test if literal constant" +b := x isInteger. "test if object is integer" +b := x isFloat. "test if object is float" +b := x isNumber. "test if object is number" +b := $A isUppercase. "test if upper case character" +b := $A isLowercase. "test if lower case character" + +"************************************************************************ + * Arithmetic expressions: * + ************************************************************************" +| x | +x := 6 + 3. "addition" +x := 6 - 3. "subtraction" +x := 6 * 3. "multiplication" +x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3" +x := 5 / 3. "division with fractional result" +x := 5.0 / 3.0. "division with float result" +x := 5.0 // 3.0. "integer divide" +x := 5.0 \\ 3.0. "integer remainder" +x := -5. "unary minus" +x := 5 sign. "numeric sign (1, -1 or 0)" +x := 5 negated. "negate receiver" +x := 1.2 integerPart. "integer part of number (1.0)" +x := 1.2 fractionPart. "fractional part of number (0.2)" +x := 5 reciprocal. "reciprocal function" +x := 6 * 3.1. "auto convert to float" +x := 5 squared. "square function" +x := 25 sqrt. "square root" +x := 5 raisedTo: 2. "power function" +x := 5 raisedToInteger: 2. "power function with integer" +x := 5 exp. "exponential" +x := -5 abs. "absolute value" +x := 3.99 rounded. "round" +x := 3.99 truncated. "truncate" +x := 3.99 roundTo: 1. "round to specified decimal places" +x := 3.99 truncateTo: 1. "truncate to specified decimal places" +x := 3.99 floor. "truncate" +x := 3.99 ceiling. "round up" +x := 5 factorial. "factorial" +x := -5 quo: 3. "integer divide rounded toward zero" +x := -5 rem: 3. "integer remainder rounded toward zero" +x := 28 gcd: 12. "greatest common denominator" +x := 28 lcm: 12. "least common multiple" +x := 100 ln. "natural logarithm" +x := 100 log. "base 10 logarithm" +x := 100 log: 10. "logarithm with specified base" +x := 100 floorLog: 10. "floor of the log" +x := 180 degreesToRadians. "convert degrees to radians" +x := 3.14 radiansToDegrees. "convert radians to degrees" +x := 0.7 sin. "sine" +x := 0.7 cos. "cosine" +x := 0.7 tan. "tangent" +x := 0.7 arcSin. "arcsine" +x := 0.7 arcCos. "arccosine" +x := 0.7 arcTan. "arctangent" +x := 10 max: 20. "get maximum of two numbers" +x := 10 min: 20. "get minimum of two numbers" +x := Float pi. "pi" +x := Float e. "exp constant" +x := Float infinity. "infinity" +x := Float nan. "not-a-number" +x := Random new next; yourself. x next. "random number stream (0.0 to 1.0) +x := 100 atRandom. "quick random number" + +"************************************************************************ + * Bitwise Manipulation: * + ************************************************************************" +| b x | +x := 16rFF bitAnd: 16r0F. "and bits" +x := 16rF0 bitOr: 16r0F. "or bits" +x := 16rFF bitXor: 16r0F. "xor bits" +x := 16rFF bitInvert. "invert bits" +x := 16r0F bitShift: 4. "left shift" +x := 16rF0 bitShift: -4. "right shift" +"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]" +x := 16r80 highbit. "position of highest bit set" +b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver" +b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver" +b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" + +"************************************************************************ + * Conversion: * + ************************************************************************" +| x | +x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" +x := 3.99 asFraction. "convert number to fraction" +x := 3 asFloat. "convert number to float" +x := 65 asCharacter. "convert integer to character" +x := $A asciiValue. "convert character to integer" +x := 3.99 printString. "convert object to string via printOn:" +x := 3.99 storeString. "convert object to string via storeOn:" +x := 15 radix: 16. "convert to string in given base" +x := 15 printStringBase: 16. +x := 15 storeStringBase: 16. + +"************************************************************************ + * Blocks: * + * - blocks are objects and may be assigned to a variable * + * - value is last expression evaluated unless explicit return * + * - blocks may be nested * + * - specification [ arguments | | localvars | expressions ] * + * - Squeak does not currently support localvars in blocks * + * - max of three arguments allowed * + * - ^expression terminates block & method (exits all nested blocks) * + * - blocks intended for long term storage should not contain ^ * + ************************************************************************" +| x y z | +x := [ y := 1. z := 2. ]. x value. "simple block usage" +x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing" +Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing" +"x := [ | z | z := 1.]. localvars not available in squeak blocks" + +"************************************************************************ + * Method calls: * + * - unary methods are messages with no arguments * + * - binary methods * + * - keyword methods are messages with selectors including colons * + * * + * standard categories/protocols: * + * - initialize-release (methods called for new instance) * + * - accessing (get/set methods) * + * - testing (boolean tests - is) * + * - comparing (boolean tests with parameter * + * - displaying (gui related methods) * + * - printing (methods for printing) * + * - updating (receive notification of changes) * + * - private (methods private to class) * + * - instance-creation (class methods for creating instance) * + ************************************************************************" +| x | +x := 2 sqrt. "unary message" +x := 2 raisedTo: 10. "keyword message" +x := 194 * 9. "binary message" +Transcript show: (194 * 9) printString; cr. "combination (chaining)" +x := 2 perform: #sqrt. "indirect method invocation" +Transcript "Cascading - send multiple messages to receiver" + show: 'hello '; + show: 'world'; + cr. +x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" + +"************************************************************************ + * Conditional Statements: * + ************************************************************************" +| x | +x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" +x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else" +x > 10 "if then else" + ifTrue: [Transcript show: 'ifTrue'; cr] + ifFalse: [Transcript show: 'ifFalse'; cr]. +x > 10 "if else then" + ifFalse: [Transcript show: 'ifFalse'; cr] + ifTrue: [Transcript show: 'ifTrue'; cr]. +Transcript + show: + (x > 10 + ifTrue: ['ifTrue'] + ifFalse: ['ifFalse']); + cr. +Transcript "nested if then else" + show: + (x > 10 + ifTrue: [x > 5 + ifTrue: ['A'] + ifFalse: ['B']] + ifFalse: ['C']); + cr. +switch := Dictionary new. "switch functionality" +switch at: $A put: [Transcript show: 'Case A'; cr]. +switch at: $B put: [Transcript show: 'Case B'; cr]. +switch at: $C put: [Transcript show: 'Case C'; cr]. +result := (switch at: $B) value. + +"************************************************************************ + * Iteration statements: * + ************************************************************************" +| x y | +x := 4. y := 1. +[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" +[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" +x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)" +1 to: x do: [:a | y := y * 2]. "for loop" +1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" +#(5 4 3) do: [:a | x := x + a]. "iterate over array elements" + +"************************************************************************ + * Character: * + ************************************************************************" +| x y | +x := $A. "character assignment" +y := x isLowercase. "test if lower case" +y := x isUppercase. "test if upper case" +y := x isLetter. "test if letter" +y := x isDigit. "test if digit" +y := x isAlphaNumeric. "test if alphanumeric" +y := x isSeparator. "test if seperator char" +y := x isVowel. "test if vowel" +y := x digitValue. "convert to numeric digit value" +y := x asLowercase. "convert to lower case" +y := x asUppercase. "convert to upper case" +y := x asciiValue. "convert to numeric ascii value" +y := x asString. "convert to string" +b := $A <= $B. "comparison" +y := $A max: $B. + +"************************************************************************ + * Symbol: * + ************************************************************************" +| b x y | +x := #Hello. "symbol assignment" +y := 'String', 'Concatenation'. "symbol concatenation (result is string)" +b := x isEmpty. "test if symbol is empty" +y := x size. "string size" +y := x at: 2. "char at location" +y := x copyFrom: 2 to: 4. "substring" +y := x indexOf: $e ifAbsent: [0]. "first position of character within string" +x do: [:a | Transcript show: a printString; cr]. "iterate over the string" +b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" +y := x select: [:a | a > $a]. "return all elements that meet condition" +y := x asString. "convert symbol to string" +y := x asText. "convert symbol to text" +y := x asArray. "convert symbol to array" +y := x asOrderedCollection. "convert symbol to ordered collection" +y := x asSortedCollection. "convert symbol to sorted collection" +y := x asBag. "convert symbol to bag collection" +y := x asSet. "convert symbol to set collection" + +"************************************************************************ + * String: * + ************************************************************************" +| b x y | +x := 'This is a string'. "string assignment" +x := 'String', 'Concatenation'. "string concatenation" +b := x isEmpty. "test if string is empty" +y := x size. "string size" +y := x at: 2. "char at location" +y := x copyFrom: 2 to: 4. "substring" +y := x indexOf: $a ifAbsent: [0]. "first position of character within string" +x := String new: 4. "allocate string object" +x "set string elements" + at: 1 put: $a; + at: 2 put: $b; + at: 3 put: $c; + at: 4 put: $e. +x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time" +x do: [:a | Transcript show: a printString; cr]. "iterate over the string" +b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" +y := x select: [:a | a > $a]. "return all elements that meet condition" +y := x asSymbol. "convert string to symbol" +y := x asArray. "convert string to array" +x := 'ABCD' asByteArray. "convert string to byte array" +y := x asOrderedCollection. "convert string to ordered collection" +y := x asSortedCollection. "convert string to sorted collection" +y := x asBag. "convert string to bag collection" +y := x asSet. "convert string to set collection" +y := x shuffled. "randomly shuffle string" + +"************************************************************************ + * Array: Fixed length collection * + * ByteArray: Array limited to byte elements (0-255) * + * WordArray: Array limited to word elements (0-2^32) * + ************************************************************************" +| b x y sum max | +x := #(4 3 2 1). "constant array" +x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" +x := Array new: 4. "allocate an array with specified size" +x "set array elements" + at: 1 put: 5; + at: 2 put: 4; + at: 3 put: 3; + at: 4 put: 2. +b := x isEmpty. "test if array is empty" +y := x size. "array size" +y := x at: 4. "get array element at index" +b := x includes: 3. "test if element is in array" +y := x copyFrom: 2 to: 4. "subarray" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within array" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the array" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum array elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in array" + ifTrue: [a] + ifFalse: [c]]. +y := x shuffled. "randomly shuffle collection" +y := x asArray. "convert to array" +"y := x asByteArray." "note: this instruction not available on Squeak" +y := x asWordArray. "convert to word array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * OrderedCollection: acts like an expandable array * + ************************************************************************" +| b x y sum max | +x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := OrderedCollection new. "allocate collection" +x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" +y := x addFirst: 5. "add element at beginning of collection" +y := x removeFirst. "remove first element in collection" +y := x addLast: 6. "add element at end of collection" +y := x removeLast. "remove last element in collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +x at: 2 put: 3. "set element at index" +y := x remove: 5 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: 2. "retrieve element at index" +y := x first. "retrieve first element in collection" +y := x last. "retrieve last element in collection" +b := x includes: 5. "test if element is in collection" +y := x copyFrom: 2 to: 3. "subcollection" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x shuffled. "randomly shuffle collection" +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * SortedCollection: like OrderedCollection except order of elements * + * determined by sorting criteria * + ************************************************************************" +| b x y sum max | +x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := SortedCollection new. "allocate collection" +x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria" +x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" +y := x addFirst: 5. "add element at beginning of collection" +y := x removeFirst. "remove first element in collection" +y := x addLast: 6. "add element at end of collection" +y := x removeLast. "remove last element in collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 5 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: 2. "retrieve element at index" +y := x first. "retrieve first element in collection" +y := x last. "retrieve last element in collection" +b := x includes: 4. "test if element is in collection" +y := x copyFrom: 2 to: 3. "subcollection" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Bag: like OrderedCollection except elements are in no * + * particular order * + ************************************************************************" +| b x y sum max | +x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := Bag new. "allocate collection" +x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" +x add: 3 withOccurrences: 2. "add multiple copies to collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 4 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +b := x includes: 3. "test if element is in collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Set: like Bag except duplicates not allowed * + * IdentitySet: uses identity test (== rather than =) * + ************************************************************************" +| b x y sum max | +x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := Set new. "allocate collection" +x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 4 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +x includes: 4. "test if element is in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Interval: * + ************************************************************************" +| b x y sum max | +x := Interval from: 5 to: 10. "create interval object" +x := 5 to: 10. +x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment" +x := 5 to: 10 by: 2. +b := x isEmpty. "test if empty" +y := x size. "number of elements" +x includes: 9. "test if element is in collection" +x do: [:k | Transcript show: k printString; cr]. "iterate over interval" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 7]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Associations: * + ************************************************************************" +| x y | +x := #myVar->'hello'. +y := x key. +y := x value. + +"************************************************************************ + * Dictionary: * + * IdentityDictionary: uses identity test (== rather than =) * + ************************************************************************" +| b x y | +x := Dictionary new. "allocate collection" +x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection" +x at: #e put: 3. "set element at index" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: #a ifAbsent: []. "retrieve element at index" +y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block" +y := x removeKey: #e ifAbsent: []. "remove element from collection" +b := x includes: 3. "test if element is in values collection" +b := x includesKey: #a. "test if element is in keys collection" +y := x occurrencesOf: 3. "number of times object in collection" +y := x keys. "set of keys" +y := x values. "bag of values" +x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection" +x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection" +x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations" +x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values" + show: aKey printString; space; + show: aValue printString; cr]. +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary" +x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary" +Transcript show: (CMRGlobal printString). "entries are directly accessible by name" +Smalltalk keys do: [ :k | "print out all classes" + ((Smalltalk at: k) isKindOf: Class) + ifFalse: [Transcript show: k printString; cr]]. +Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary" +CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary" +CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo" +CMRDictionary size. "dictionary size" +CMRDictionary keys do: [ :k | "print out keys in dictionary" + Transcript show: k printString; cr]. +CMRDictionary values do: [ :k | "print out values in dictionary" + Transcript show: k printString; cr]. +CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values" + Transcript + show: aKey printString; + space; + show: aValue printString; + cr]. +CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values" + Transcript show: aKeyValue printString; cr]. +Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary" +Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" + +"************************************************************************ + * Internal Stream: * + ************************************************************************" +| b x ios | +ios := ReadStream on: 'Hello read stream'. +ios := ReadStream on: 'Hello read stream' from: 1 to: 5. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 3. +ios position. +x := ios next. +x := ios peek. +x := ios contents. +b := ios atEnd. + +ios := ReadWriteStream on: 'Hello read stream'. +ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5. +ios := ReadWriteStream with: 'Hello read stream'. +ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10. +ios position: 0. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 6. +ios position. +ios nextPutAll: 'Chris'. +x := ios next. +x := ios peek. +x := ios contents. +b := ios atEnd. + +"************************************************************************ + * FileStream: * + ************************************************************************" +| b x ios | +ios := FileStream newFileNamed: 'ios.txt'. +ios nextPut: $H; cr. +ios nextPutAll: 'Hello File'; cr. +'Hello File' printOn: ios. +'Hello File' storeOn: ios. +ios close. + +ios := FileStream oldFileNamed: 'ios.txt'. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 3. +x := ios position. +x := ios next. +x := ios peek. +b := ios atEnd. +ios close. + +"************************************************************************ + * Date: * + ************************************************************************" +| x y | +x := Date today. "create date for today" +x := Date dateAndTimeNow. "create date from current time/date" +x := Date readFromString: '01/02/1999'. "create date from formatted string" +x := Date newDay: 12 month: #July year: 1999 "create date from parts" +x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901" +y := Date dayOfWeek: #Monday. "day of week as int (1-7)" +y := Date indexOfMonth: #January. "month of year as int (1-12)" +y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)" +y := Date daysInYear: 1996. "days in year (365|366)" +y := Date nameOfDay: 1 "weekday name (#Monday,...)" +y := Date nameOfMonth: 1. "month name (#January,...)" +y := Date leapYear: 1996. "1 if leap year; 0 if not leap year" +y := x weekday. "day of week (#Monday,...)" +y := x previous: #Monday. "date for previous day of week" +y := x dayOfMonth. "day of month (1-31)" +y := x day. "day of year (1-366)" +y := x firstDayOfMonth. "day of year for first day of month" +y := x monthName. "month of year (#January,...)" +y := x monthIndex. "month of year (1-12)" +y := x daysInMonth. "days in month (1-31)" +y := x year. "year (19xx)" +y := x daysInYear. "days in year (365|366)" +y := x daysLeftInYear. "days left in year (364|365)" +y := x asSeconds. "seconds elapsed since 1/1/1901" +y := x addDays: 10. "add days to date object" +y := x subtractDays: 10. "subtract days to date object" +y := x subtractDate: (Date today). "subtract date (result in days)" +y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date" +b := (x <= Date today). "comparison" + +"************************************************************************ + * Time: * + ************************************************************************" +| x y | +x := Time now. "create time from current time" +x := Time dateAndTimeNow. "create time from current time/date" +x := Time readFromString: '3:47:26 pm'. "create time from formatted string" +x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight" +y := Time millisecondClockValue. "milliseconds since midnight" +y := Time totalSeconds. "total seconds since 1/1/1901" +y := x seconds. "seconds past minute (0-59)" +y := x minutes. "minutes past hour (0-59)" +y := x hours. "hours past midnight (0-23)" +y := x addTime: (Time now). "add time to time object" +y := x subtractTime: (Time now). "subtract time to time object" +y := x asSeconds. "convert time to seconds" +x := Time millisecondsToRun: [ "timing facility" + 1 to: 1000 do: [:index | y := 3.14 * index]]. +b := (x <= Time now). "comparison" + +"************************************************************************ + * Point: * + ************************************************************************" +| x y | +x := 200@100. "obtain a new point" +y := x x. "x coordinate" +y := x y. "y coordinate" +x := 200@100 negated. "negates x and y" +x := (-200@-100) abs. "absolute value of x and y" +x := (200.5@100.5) rounded. "round x and y" +x := (200.5@100.5) truncated. "truncate x and y" +x := 200@100 + 100. "add scale to both x and y" +x := 200@100 - 100. "subtract scale from both x and y" +x := 200@100 * 2. "multiply x and y by scale" +x := 200@100 / 2. "divide x and y by scale" +x := 200@100 // 2. "divide x and y by scale" +x := 200@100 \\ 3. "remainder of x and y by scale" +x := 200@100 + 50@25. "add points" +x := 200@100 - 50@25. "subtract points" +x := 200@100 * 3@4. "multiply points" +x := 200@100 // 3@4. "divide points" +x := 200@100 max: 50@200. "max x and y" +x := 200@100 min: 50@200. "min x and y" +x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" + +"************************************************************************ + * Rectangle: * + ************************************************************************" +Rectangle fromUser. + +"************************************************************************ + * Pen: * + ************************************************************************" +| myPen | +Display restoreAfter: [ + Display fillWhite. + +myPen := Pen new. "get graphic pen" +myPen squareNib: 1. +myPen color: (Color blue). "set pen color" +myPen home. "position pen at center of display" +myPen up. "makes nib unable to draw" +myPen down. "enable the nib to draw" +myPen north. "points direction towards top" +myPen turn: -180. "add specified degrees to direction" +myPen direction. "get current angle of pen" +myPen go: 50. "move pen specified number of pixels" +myPen location. "get the pen position" +myPen goto: 200@200. "move to specified point" +myPen place: 250@250. "move to specified point without drawing" +myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1). +Display extent. "get display width@height" +Display width. "get display width" +Display height. "get display height" + +]. + +"************************************************************************ + * Dynamic Message Calling/Compiling: * + ************************************************************************" +| receiver message result argument keyword1 keyword2 argument1 argument2 | +"unary message" +receiver := 5. +message := 'factorial' asSymbol. +result := receiver perform: message. +result := Compiler evaluate: ((receiver storeString), ' ', message). +result := (Message new setSelector: message arguments: #()) sentTo: receiver. + +"binary message" +receiver := 1. +message := '+' asSymbol. +argument := 2. +result := receiver perform: message withArguments: (Array with: argument). +result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)). +result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver. + +"keyword messages" +receiver := 12. +keyword1 := 'between:' asSymbol. +keyword2 := 'and:' asSymbol. +argument1 := 10. +argument2 := 20. +result := receiver + perform: (keyword1, keyword2) asSymbol + withArguments: (Array with: argument1 with: argument2). +result := Compiler evaluate: + ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)). +result := (Message + new + setSelector: (keyword1, keyword2) asSymbol + arguments: (Array with: argument1 with: argument2)) + sentTo: receiver. + +"************************************************************************ + * class/meta-class: * + ************************************************************************" +| b x | +x := String name. "class name" +x := String category. "organization category" +x := String comment. "class comment" +x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc" +x := String definition. "class definition" +x := String instVarNames. "immediate instance variable names" +x := String allInstVarNames. "accumulated instance variable names" +x := String classVarNames. "immediate class variable names" +x := String allClassVarNames. "accumulated class variable names" +x := String sharedPools. "immediate dictionaries used as shared pools" +x := String allSharedPools. "accumulated dictionaries used as shared pools" +x := String selectors. "message selectors for class" +x := String sourceCodeAt: #size. "source code for specified method" +x := String allInstances. "collection of all instances of class" +x := String superclass. "immediate superclass" +x := String allSuperclasses. "accumulated superclasses" +x := String withAllSuperclasses. "receiver class and accumulated superclasses" +x := String subclasses. "immediate subclasses" +x := String allSubclasses. "accumulated subclasses" +x := String withAllSubclasses. "receiver class and accumulated subclasses" +b := String instSize. "number of named instance variables" +b := String isFixed. "true if no indexed instance variables" +b := String isVariable. "true if has indexed instance variables" +b := String isPointers. "true if index instance vars contain objects" +b := String isBits. "true if index instance vars contain bytes/words" +b := String isBytes. "true if index instance vars contain bytes" +b := String isWords. true if index instance vars contain words" +Object withAllSubclasses size. "get total number of class entries" + +"************************************************************************ + * debuging: * + ************************************************************************" +| a b x | +x yourself. "returns receiver" +String browse. "browse specified class" +x inspect. "open object inspector window" +x confirm: 'Is this correct?'. +x halt. "breakpoint to open debugger window" +x halt: 'Halt message'. +x notify: 'Notify text'. +x error: 'Error string'. "open up error window with title" +x doesNotUnderstand: #cmrMessage. "flag message is not handled" +x shouldNotImplement. "flag message should not be implemented" +x subclassResponsibility. "flag message as abstract" +x errorImproperStore. "flag an improper store into indexable object" +x errorNonIntegerIndex. "flag only integers should be used as index" +x errorSubscriptBounds. "flag subscript out of bounds" +x primitiveFailed. "system primitive failed" + +a := 'A1'. b := 'B2'. a become: b. "switch two objects" +Transcript show: a, b; cr. + +"************************************************************************ + * Misc. * + ************************************************************************" +| x | +"Smalltalk condenseChanges." "compress the change file" +x := FillInTheBlank request: 'Prompt Me'. "prompt user for input" +Utilities openCommandKeyHelp + + + + +``` + +## Ready For More? + +### Free Online + +* [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) +* [smalltalk dot org](http://www.smalltalk.org/smalltalk/learning.html) +* [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) +* [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) +* [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) +* [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) +* [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) +* [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) diff --git a/smalltalk.html.markdown~ b/smalltalk.html.markdown~ new file mode 100644 index 00000000..61e5a94c --- /dev/null +++ b/smalltalk.html.markdown~ @@ -0,0 +1,959 @@ +--- +language: smalltalk +contributors: + - ["Jigyasa Grover", "https://github.com/jig08"] +--- + +- Smalltalk is an object-oriented, dynamically typed, reflective programming language. +- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." +- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s. + +Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`. + +``` + +"************************************************************************ + * Allowable characters: * + * - a-z * + * - A-Z * + * - 0-9 * + * - .+/\*~<>@%|&? * + * - blank, tab, cr, ff, lf * + * * + * Variables: * + * - variables must be declared before use * + * - shared vars must begin with uppercase * + * - local vars must begin with lowercase * + * - reserved names: nil, true, false, self, super, and Smalltalk * + * * + * Variable scope: * + * - Global: defined in Dictionary Smalltalk and accessible by all * + * objects in system * + * - Special: (reserved) Smalltalk, super, self, true, false, & nil * + * - Method Temporary: local to a method * + * - Block Temporary: local to a block * + * - Pool: variables in a Dictionary object * + * - Method Parameters: automatic local vars created as a result of * + * message call with params * + * - Block Parameters: automatic local vars created as a result of * + * value: message call * + * - Class: shared with all instances of one class & its subclasses * + * - Class Instance: unique to each instance of a class * + * - Instance Variables: unique to each instance * + ************************************************************************" +"Comments are enclosed in quotes" +"Period (.) is the statement seperator" + +"************************************************************************ + * Transcript: * + ************************************************************************" +Transcript clear. "clear to transcript window" +Transcript show: 'Hello World'. "output string in transcript window" +Transcript nextPutAll: 'Hello World'. "output string in transcript window" +Transcript nextPut: $A. "output character in transcript window" +Transcript space. "output space character in transcript window" +Transcript tab. "output tab character in transcript window" +Transcript cr. "carriage return / linefeed" +'Hello' printOn: Transcript. "append print string into the window" +'Hello' storeOn: Transcript. "append store string into the window" +Transcript endEntry. "flush the output buffer" + +"************************************************************************ + * Assignment: * + ************************************************************************" +| x y | +x _ 4. "assignment (Squeak) <-" +x := 5. "assignment" +x := y := z := 6. "compound assignment" +x := (y := 6) + 1. +x := Object new. "bind to allocated instance of a class" +x := 123 class. "discover the object class" +x := Integer superclass. "discover the superclass of a class" +x := Object allInstances. "get an array of all instances of a class" +x := Integer allSuperclasses. "get all superclasses of a class" +x := 1.2 hash. "hash value for object" +y := x copy. "copy object" +y := x shallowCopy. "copy object (not overridden)" +y := x deepCopy. "copy object and instance vars" +y := x veryDeepCopy. "complete tree copy using a dictionary" + +"************************************************************************ + * Constants: * + ************************************************************************" +| b | +b := true. "true constant" +b := false. "false constant" +x := nil. "nil object constant" +x := 1. "integer constants" +x := 3.14. "float constants" +x := 2e-2. "fractional constants" +x := 16r0F. "hex constant". +x := -1. "negative constants" +x := 'Hello'. "string constant" +x := 'I''m here'. "single quote escape" +x := $A. "character constant" +x := $ . "character constant (space)" +x := #aSymbol. "symbol constants" +x := #(3 2 1). "array constants" +x := #('abc' 2 $a). "mixing of types allowed" + +"************************************************************************ + * Booleans: * + ************************************************************************" +| b x y | +x := 1. y := 2. +b := (x = y). "equals" +b := (x ~= y). "not equals" +b := (x == y). "identical" +b := (x ~~ y). "not identical" +b := (x > y). "greater than" +b := (x < y). "less than" +b := (x >= y). "greater than or equal" +b := (x <= y). "less than or equal" +b := b not. "boolean not" +b := (x < 5) & (y > 1). "boolean and" +b := (x < 5) | (y > 1). "boolean or" +b := (x < 5) and: [y > 1]. "boolean and (short-circuit)" +b := (x < 5) or: [y > 1]. "boolean or (short-circuit)" +b := (x < 5) eqv: (y > 1). "test if both true or both false" +b := (x < 5) xor: (y > 1). "test if one true and other false" +b := 5 between: 3 and: 12. "between (inclusive)" +b := 123 isKindOf: Number. "test if object is class or subclass of" +b := 123 isMemberOf: SmallInteger. "test if object is type of class" +b := 123 respondsTo: sqrt. "test if object responds to message" +b := x isNil. "test if object is nil" +b := x isZero. "test if number is zero" +b := x positive. "test if number is positive" +b := x strictlyPositive. "test if number is greater than zero" +b := x negative. "test if number is negative" +b := x even. "test if number is even" +b := x odd. "test if number is odd" +b := x isLiteral. "test if literal constant" +b := x isInteger. "test if object is integer" +b := x isFloat. "test if object is float" +b := x isNumber. "test if object is number" +b := $A isUppercase. "test if upper case character" +b := $A isLowercase. "test if lower case character" + +"************************************************************************ + * Arithmetic expressions: * + ************************************************************************" +| x | +x := 6 + 3. "addition" +x := 6 - 3. "subtraction" +x := 6 * 3. "multiplication" +x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3" +x := 5 / 3. "division with fractional result" +x := 5.0 / 3.0. "division with float result" +x := 5.0 // 3.0. "integer divide" +x := 5.0 \\ 3.0. "integer remainder" +x := -5. "unary minus" +x := 5 sign. "numeric sign (1, -1 or 0)" +x := 5 negated. "negate receiver" +x := 1.2 integerPart. "integer part of number (1.0)" +x := 1.2 fractionPart. "fractional part of number (0.2)" +x := 5 reciprocal. "reciprocal function" +x := 6 * 3.1. "auto convert to float" +x := 5 squared. "square function" +x := 25 sqrt. "square root" +x := 5 raisedTo: 2. "power function" +x := 5 raisedToInteger: 2. "power function with integer" +x := 5 exp. "exponential" +x := -5 abs. "absolute value" +x := 3.99 rounded. "round" +x := 3.99 truncated. "truncate" +x := 3.99 roundTo: 1. "round to specified decimal places" +x := 3.99 truncateTo: 1. "truncate to specified decimal places" +x := 3.99 floor. "truncate" +x := 3.99 ceiling. "round up" +x := 5 factorial. "factorial" +x := -5 quo: 3. "integer divide rounded toward zero" +x := -5 rem: 3. "integer remainder rounded toward zero" +x := 28 gcd: 12. "greatest common denominator" +x := 28 lcm: 12. "least common multiple" +x := 100 ln. "natural logarithm" +x := 100 log. "base 10 logarithm" +x := 100 log: 10. "logarithm with specified base" +x := 100 floorLog: 10. "floor of the log" +x := 180 degreesToRadians. "convert degrees to radians" +x := 3.14 radiansToDegrees. "convert radians to degrees" +x := 0.7 sin. "sine" +x := 0.7 cos. "cosine" +x := 0.7 tan. "tangent" +x := 0.7 arcSin. "arcsine" +x := 0.7 arcCos. "arccosine" +x := 0.7 arcTan. "arctangent" +x := 10 max: 20. "get maximum of two numbers" +x := 10 min: 20. "get minimum of two numbers" +x := Float pi. "pi" +x := Float e. "exp constant" +x := Float infinity. "infinity" +x := Float nan. "not-a-number" +x := Random new next; yourself. x next. "random number stream (0.0 to 1.0) +x := 100 atRandom. "quick random number" + +"************************************************************************ + * Bitwise Manipulation: * + ************************************************************************" +| b x | +x := 16rFF bitAnd: 16r0F. "and bits" +x := 16rF0 bitOr: 16r0F. "or bits" +x := 16rFF bitXor: 16r0F. "xor bits" +x := 16rFF bitInvert. "invert bits" +x := 16r0F bitShift: 4. "left shift" +x := 16rF0 bitShift: -4. "right shift" +"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]" +x := 16r80 highbit. "position of highest bit set" +b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver" +b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver" +b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" + +"************************************************************************ + * Conversion: * + ************************************************************************" +| x | +x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" +x := 3.99 asFraction. "convert number to fraction" +x := 3 asFloat. "convert number to float" +x := 65 asCharacter. "convert integer to character" +x := $A asciiValue. "convert character to integer" +x := 3.99 printString. "convert object to string via printOn:" +x := 3.99 storeString. "convert object to string via storeOn:" +x := 15 radix: 16. "convert to string in given base" +x := 15 printStringBase: 16. +x := 15 storeStringBase: 16. + +"************************************************************************ + * Blocks: * + * - blocks are objects and may be assigned to a variable * + * - value is last expression evaluated unless explicit return * + * - blocks may be nested * + * - specification [ arguments | | localvars | expressions ] * + * - Squeak does not currently support localvars in blocks * + * - max of three arguments allowed * + * - ^expression terminates block & method (exits all nested blocks) * + * - blocks intended for long term storage should not contain ^ * + ************************************************************************" +| x y z | +x := [ y := 1. z := 2. ]. x value. "simple block usage" +x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing" +Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing" +"x := [ | z | z := 1.]. localvars not available in squeak blocks" + +"************************************************************************ + * Method calls: * + * - unary methods are messages with no arguments * + * - binary methods * + * - keyword methods are messages with selectors including colons * + * * + * standard categories/protocols: * + * - initialize-release (methods called for new instance) * + * - accessing (get/set methods) * + * - testing (boolean tests - is) * + * - comparing (boolean tests with parameter * + * - displaying (gui related methods) * + * - printing (methods for printing) * + * - updating (receive notification of changes) * + * - private (methods private to class) * + * - instance-creation (class methods for creating instance) * + ************************************************************************" +| x | +x := 2 sqrt. "unary message" +x := 2 raisedTo: 10. "keyword message" +x := 194 * 9. "binary message" +Transcript show: (194 * 9) printString; cr. "combination (chaining)" +x := 2 perform: #sqrt. "indirect method invocation" +Transcript "Cascading - send multiple messages to receiver" + show: 'hello '; + show: 'world'; + cr. +x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" + +"************************************************************************ + * Conditional Statements: * + ************************************************************************" +| x | +x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" +x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else" +x > 10 "if then else" + ifTrue: [Transcript show: 'ifTrue'; cr] + ifFalse: [Transcript show: 'ifFalse'; cr]. +x > 10 "if else then" + ifFalse: [Transcript show: 'ifFalse'; cr] + ifTrue: [Transcript show: 'ifTrue'; cr]. +Transcript + show: + (x > 10 + ifTrue: ['ifTrue'] + ifFalse: ['ifFalse']); + cr. +Transcript "nested if then else" + show: + (x > 10 + ifTrue: [x > 5 + ifTrue: ['A'] + ifFalse: ['B']] + ifFalse: ['C']); + cr. +switch := Dictionary new. "switch functionality" +switch at: $A put: [Transcript show: 'Case A'; cr]. +switch at: $B put: [Transcript show: 'Case B'; cr]. +switch at: $C put: [Transcript show: 'Case C'; cr]. +result := (switch at: $B) value. + +"************************************************************************ + * Iteration statements: * + ************************************************************************" +| x y | +x := 4. y := 1. +[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" +[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" +x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)" +1 to: x do: [:a | y := y * 2]. "for loop" +1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" +#(5 4 3) do: [:a | x := x + a]. "iterate over array elements" + +"************************************************************************ + * Character: * + ************************************************************************" +| x y | +x := $A. "character assignment" +y := x isLowercase. "test if lower case" +y := x isUppercase. "test if upper case" +y := x isLetter. "test if letter" +y := x isDigit. "test if digit" +y := x isAlphaNumeric. "test if alphanumeric" +y := x isSeparator. "test if seperator char" +y := x isVowel. "test if vowel" +y := x digitValue. "convert to numeric digit value" +y := x asLowercase. "convert to lower case" +y := x asUppercase. "convert to upper case" +y := x asciiValue. "convert to numeric ascii value" +y := x asString. "convert to string" +b := $A <= $B. "comparison" +y := $A max: $B. + +"************************************************************************ + * Symbol: * + ************************************************************************" +| b x y | +x := #Hello. "symbol assignment" +y := 'String', 'Concatenation'. "symbol concatenation (result is string)" +b := x isEmpty. "test if symbol is empty" +y := x size. "string size" +y := x at: 2. "char at location" +y := x copyFrom: 2 to: 4. "substring" +y := x indexOf: $e ifAbsent: [0]. "first position of character within string" +x do: [:a | Transcript show: a printString; cr]. "iterate over the string" +b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" +y := x select: [:a | a > $a]. "return all elements that meet condition" +y := x asString. "convert symbol to string" +y := x asText. "convert symbol to text" +y := x asArray. "convert symbol to array" +y := x asOrderedCollection. "convert symbol to ordered collection" +y := x asSortedCollection. "convert symbol to sorted collection" +y := x asBag. "convert symbol to bag collection" +y := x asSet. "convert symbol to set collection" + +"************************************************************************ + * String: * + ************************************************************************" +| b x y | +x := 'This is a string'. "string assignment" +x := 'String', 'Concatenation'. "string concatenation" +b := x isEmpty. "test if string is empty" +y := x size. "string size" +y := x at: 2. "char at location" +y := x copyFrom: 2 to: 4. "substring" +y := x indexOf: $a ifAbsent: [0]. "first position of character within string" +x := String new: 4. "allocate string object" +x "set string elements" + at: 1 put: $a; + at: 2 put: $b; + at: 3 put: $c; + at: 4 put: $e. +x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time" +x do: [:a | Transcript show: a printString; cr]. "iterate over the string" +b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" +y := x select: [:a | a > $a]. "return all elements that meet condition" +y := x asSymbol. "convert string to symbol" +y := x asArray. "convert string to array" +x := 'ABCD' asByteArray. "convert string to byte array" +y := x asOrderedCollection. "convert string to ordered collection" +y := x asSortedCollection. "convert string to sorted collection" +y := x asBag. "convert string to bag collection" +y := x asSet. "convert string to set collection" +y := x shuffled. "randomly shuffle string" + +"************************************************************************ + * Array: Fixed length collection * + * ByteArray: Array limited to byte elements (0-255) * + * WordArray: Array limited to word elements (0-2^32) * + ************************************************************************" +| b x y sum max | +x := #(4 3 2 1). "constant array" +x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" +x := Array new: 4. "allocate an array with specified size" +x "set array elements" + at: 1 put: 5; + at: 2 put: 4; + at: 3 put: 3; + at: 4 put: 2. +b := x isEmpty. "test if array is empty" +y := x size. "array size" +y := x at: 4. "get array element at index" +b := x includes: 3. "test if element is in array" +y := x copyFrom: 2 to: 4. "subarray" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within array" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the array" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum array elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in array" + ifTrue: [a] + ifFalse: [c]]. +y := x shuffled. "randomly shuffle collection" +y := x asArray. "convert to array" +"y := x asByteArray." "note: this instruction not available on Squeak" +y := x asWordArray. "convert to word array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * OrderedCollection: acts like an expandable array * + ************************************************************************" +| b x y sum max | +x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := OrderedCollection new. "allocate collection" +x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" +y := x addFirst: 5. "add element at beginning of collection" +y := x removeFirst. "remove first element in collection" +y := x addLast: 6. "add element at end of collection" +y := x removeLast. "remove last element in collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +x at: 2 put: 3. "set element at index" +y := x remove: 5 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: 2. "retrieve element at index" +y := x first. "retrieve first element in collection" +y := x last. "retrieve last element in collection" +b := x includes: 5. "test if element is in collection" +y := x copyFrom: 2 to: 3. "subcollection" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x shuffled. "randomly shuffle collection" +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * SortedCollection: like OrderedCollection except order of elements * + * determined by sorting criteria * + ************************************************************************" +| b x y sum max | +x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := SortedCollection new. "allocate collection" +x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria" +x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" +y := x addFirst: 5. "add element at beginning of collection" +y := x removeFirst. "remove first element in collection" +y := x addLast: 6. "add element at end of collection" +y := x removeLast. "remove last element in collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 5 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: 2. "retrieve element at index" +y := x first. "retrieve first element in collection" +y := x last. "retrieve last element in collection" +b := x includes: 4. "test if element is in collection" +y := x copyFrom: 2 to: 3. "subcollection" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Bag: like OrderedCollection except elements are in no * + * particular order * + ************************************************************************" +| b x y sum max | +x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := Bag new. "allocate collection" +x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" +x add: 3 withOccurrences: 2. "add multiple copies to collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 4 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +b := x includes: 3. "test if element is in collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Set: like Bag except duplicates not allowed * + * IdentitySet: uses identity test (== rather than =) * + ************************************************************************" +| b x y sum max | +x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := Set new. "allocate collection" +x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 4 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +x includes: 4. "test if element is in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Interval: * + ************************************************************************" +| b x y sum max | +x := Interval from: 5 to: 10. "create interval object" +x := 5 to: 10. +x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment" +x := 5 to: 10 by: 2. +b := x isEmpty. "test if empty" +y := x size. "number of elements" +x includes: 9. "test if element is in collection" +x do: [:k | Transcript show: k printString; cr]. "iterate over interval" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 7]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +"************************************************************************ + * Associations: * + ************************************************************************" +| x y | +x := #myVar->'hello'. +y := x key. +y := x value. + +"************************************************************************ + * Dictionary: * + * IdentityDictionary: uses identity test (== rather than =) * + ************************************************************************" +| b x y | +x := Dictionary new. "allocate collection" +x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection" +x at: #e put: 3. "set element at index" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: #a ifAbsent: []. "retrieve element at index" +y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block" +y := x removeKey: #e ifAbsent: []. "remove element from collection" +b := x includes: 3. "test if element is in values collection" +b := x includesKey: #a. "test if element is in keys collection" +y := x occurrencesOf: 3. "number of times object in collection" +y := x keys. "set of keys" +y := x values. "bag of values" +x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection" +x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection" +x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations" +x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values" + show: aKey printString; space; + show: aValue printString; cr]. +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary" +x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary" +Transcript show: (CMRGlobal printString). "entries are directly accessible by name" +Smalltalk keys do: [ :k | "print out all classes" + ((Smalltalk at: k) isKindOf: Class) + ifFalse: [Transcript show: k printString; cr]]. +Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary" +CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary" +CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo" +CMRDictionary size. "dictionary size" +CMRDictionary keys do: [ :k | "print out keys in dictionary" + Transcript show: k printString; cr]. +CMRDictionary values do: [ :k | "print out values in dictionary" + Transcript show: k printString; cr]. +CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values" + Transcript + show: aKey printString; + space; + show: aValue printString; + cr]. +CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values" + Transcript show: aKeyValue printString; cr]. +Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary" +Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" + +"************************************************************************ + * Internal Stream: * + ************************************************************************" +| b x ios | +ios := ReadStream on: 'Hello read stream'. +ios := ReadStream on: 'Hello read stream' from: 1 to: 5. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 3. +ios position. +x := ios next. +x := ios peek. +x := ios contents. +b := ios atEnd. + +ios := ReadWriteStream on: 'Hello read stream'. +ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5. +ios := ReadWriteStream with: 'Hello read stream'. +ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10. +ios position: 0. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 6. +ios position. +ios nextPutAll: 'Chris'. +x := ios next. +x := ios peek. +x := ios contents. +b := ios atEnd. + +"************************************************************************ + * FileStream: * + ************************************************************************" +| b x ios | +ios := FileStream newFileNamed: 'ios.txt'. +ios nextPut: $H; cr. +ios nextPutAll: 'Hello File'; cr. +'Hello File' printOn: ios. +'Hello File' storeOn: ios. +ios close. + +ios := FileStream oldFileNamed: 'ios.txt'. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 3. +x := ios position. +x := ios next. +x := ios peek. +b := ios atEnd. +ios close. + +"************************************************************************ + * Date: * + ************************************************************************" +| x y | +x := Date today. "create date for today" +x := Date dateAndTimeNow. "create date from current time/date" +x := Date readFromString: '01/02/1999'. "create date from formatted string" +x := Date newDay: 12 month: #July year: 1999 "create date from parts" +x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901" +y := Date dayOfWeek: #Monday. "day of week as int (1-7)" +y := Date indexOfMonth: #January. "month of year as int (1-12)" +y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)" +y := Date daysInYear: 1996. "days in year (365|366)" +y := Date nameOfDay: 1 "weekday name (#Monday,...)" +y := Date nameOfMonth: 1. "month name (#January,...)" +y := Date leapYear: 1996. "1 if leap year; 0 if not leap year" +y := x weekday. "day of week (#Monday,...)" +y := x previous: #Monday. "date for previous day of week" +y := x dayOfMonth. "day of month (1-31)" +y := x day. "day of year (1-366)" +y := x firstDayOfMonth. "day of year for first day of month" +y := x monthName. "month of year (#January,...)" +y := x monthIndex. "month of year (1-12)" +y := x daysInMonth. "days in month (1-31)" +y := x year. "year (19xx)" +y := x daysInYear. "days in year (365|366)" +y := x daysLeftInYear. "days left in year (364|365)" +y := x asSeconds. "seconds elapsed since 1/1/1901" +y := x addDays: 10. "add days to date object" +y := x subtractDays: 10. "subtract days to date object" +y := x subtractDate: (Date today). "subtract date (result in days)" +y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date" +b := (x <= Date today). "comparison" + +"************************************************************************ + * Time: * + ************************************************************************" +| x y | +x := Time now. "create time from current time" +x := Time dateAndTimeNow. "create time from current time/date" +x := Time readFromString: '3:47:26 pm'. "create time from formatted string" +x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight" +y := Time millisecondClockValue. "milliseconds since midnight" +y := Time totalSeconds. "total seconds since 1/1/1901" +y := x seconds. "seconds past minute (0-59)" +y := x minutes. "minutes past hour (0-59)" +y := x hours. "hours past midnight (0-23)" +y := x addTime: (Time now). "add time to time object" +y := x subtractTime: (Time now). "subtract time to time object" +y := x asSeconds. "convert time to seconds" +x := Time millisecondsToRun: [ "timing facility" + 1 to: 1000 do: [:index | y := 3.14 * index]]. +b := (x <= Time now). "comparison" + +"************************************************************************ + * Point: * + ************************************************************************" +| x y | +x := 200@100. "obtain a new point" +y := x x. "x coordinate" +y := x y. "y coordinate" +x := 200@100 negated. "negates x and y" +x := (-200@-100) abs. "absolute value of x and y" +x := (200.5@100.5) rounded. "round x and y" +x := (200.5@100.5) truncated. "truncate x and y" +x := 200@100 + 100. "add scale to both x and y" +x := 200@100 - 100. "subtract scale from both x and y" +x := 200@100 * 2. "multiply x and y by scale" +x := 200@100 / 2. "divide x and y by scale" +x := 200@100 // 2. "divide x and y by scale" +x := 200@100 \\ 3. "remainder of x and y by scale" +x := 200@100 + 50@25. "add points" +x := 200@100 - 50@25. "subtract points" +x := 200@100 * 3@4. "multiply points" +x := 200@100 // 3@4. "divide points" +x := 200@100 max: 50@200. "max x and y" +x := 200@100 min: 50@200. "min x and y" +x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" + +"************************************************************************ + * Rectangle: * + ************************************************************************" +Rectangle fromUser. + +"************************************************************************ + * Pen: * + ************************************************************************" +| myPen | +Display restoreAfter: [ + Display fillWhite. + +myPen := Pen new. "get graphic pen" +myPen squareNib: 1. +myPen color: (Color blue). "set pen color" +myPen home. "position pen at center of display" +myPen up. "makes nib unable to draw" +myPen down. "enable the nib to draw" +myPen north. "points direction towards top" +myPen turn: -180. "add specified degrees to direction" +myPen direction. "get current angle of pen" +myPen go: 50. "move pen specified number of pixels" +myPen location. "get the pen position" +myPen goto: 200@200. "move to specified point" +myPen place: 250@250. "move to specified point without drawing" +myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1). +Display extent. "get display width@height" +Display width. "get display width" +Display height. "get display height" + +]. + +"************************************************************************ + * Dynamic Message Calling/Compiling: * + ************************************************************************" +| receiver message result argument keyword1 keyword2 argument1 argument2 | +"unary message" +receiver := 5. +message := 'factorial' asSymbol. +result := receiver perform: message. +result := Compiler evaluate: ((receiver storeString), ' ', message). +result := (Message new setSelector: message arguments: #()) sentTo: receiver. + +"binary message" +receiver := 1. +message := '+' asSymbol. +argument := 2. +result := receiver perform: message withArguments: (Array with: argument). +result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)). +result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver. + +"keyword messages" +receiver := 12. +keyword1 := 'between:' asSymbol. +keyword2 := 'and:' asSymbol. +argument1 := 10. +argument2 := 20. +result := receiver + perform: (keyword1, keyword2) asSymbol + withArguments: (Array with: argument1 with: argument2). +result := Compiler evaluate: + ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)). +result := (Message + new + setSelector: (keyword1, keyword2) asSymbol + arguments: (Array with: argument1 with: argument2)) + sentTo: receiver. + +"************************************************************************ + * class/meta-class: * + ************************************************************************" +| b x | +x := String name. "class name" +x := String category. "organization category" +x := String comment. "class comment" +x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc" +x := String definition. "class definition" +x := String instVarNames. "immediate instance variable names" +x := String allInstVarNames. "accumulated instance variable names" +x := String classVarNames. "immediate class variable names" +x := String allClassVarNames. "accumulated class variable names" +x := String sharedPools. "immediate dictionaries used as shared pools" +x := String allSharedPools. "accumulated dictionaries used as shared pools" +x := String selectors. "message selectors for class" +x := String sourceCodeAt: #size. "source code for specified method" +x := String allInstances. "collection of all instances of class" +x := String superclass. "immediate superclass" +x := String allSuperclasses. "accumulated superclasses" +x := String withAllSuperclasses. "receiver class and accumulated superclasses" +x := String subclasses. "immediate subclasses" +x := String allSubclasses. "accumulated subclasses" +x := String withAllSubclasses. "receiver class and accumulated subclasses" +b := String instSize. "number of named instance variables" +b := String isFixed. "true if no indexed instance variables" +b := String isVariable. "true if has indexed instance variables" +b := String isPointers. "true if index instance vars contain objects" +b := String isBits. "true if index instance vars contain bytes/words" +b := String isBytes. "true if index instance vars contain bytes" +b := String isWords. true if index instance vars contain words" +Object withAllSubclasses size. "get total number of class entries" + +"************************************************************************ + * debuging: * + ************************************************************************" +| a b x | +x yourself. "returns receiver" +String browse. "browse specified class" +x inspect. "open object inspector window" +x confirm: 'Is this correct?'. +x halt. "breakpoint to open debugger window" +x halt: 'Halt message'. +x notify: 'Notify text'. +x error: 'Error string'. "open up error window with title" +x doesNotUnderstand: #cmrMessage. "flag message is not handled" +x shouldNotImplement. "flag message should not be implemented" +x subclassResponsibility. "flag message as abstract" +x errorImproperStore. "flag an improper store into indexable object" +x errorNonIntegerIndex. "flag only integers should be used as index" +x errorSubscriptBounds. "flag subscript out of bounds" +x primitiveFailed. "system primitive failed" + +a := 'A1'. b := 'B2'. a become: b. "switch two objects" +Transcript show: a, b; cr. + +"************************************************************************ + * Misc. * + ************************************************************************" +| x | +"Smalltalk condenseChanges." "compress the change file" +x := FillInTheBlank request: 'Prompt Me'. "prompt user for input" +Utilities openCommandKeyHelp + + + + +``` + +## Ready For More? + +### Free Online + +* [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) +* [smalltalk dot org](http://www.smalltalk.org/smalltalk/learning.html) +* [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) +* [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) +* [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) +* [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) +* [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) +* [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) -- cgit v1.2.3 From d704d06976f003faf06eb68764b06508044b7500 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:15:46 +0530 Subject: Delete .Rhistory --- ko-kr/.Rhistory | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ko-kr/.Rhistory diff --git a/ko-kr/.Rhistory b/ko-kr/.Rhistory deleted file mode 100644 index e69de29b..00000000 -- cgit v1.2.3 From add1edbeb23ca058c1652b6031a3bf2f8f3c5191 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:16:17 +0530 Subject: Delete smalltalk.html.markdown~ --- smalltalk.html.markdown~ | 959 ----------------------------------------------- 1 file changed, 959 deletions(-) delete mode 100644 smalltalk.html.markdown~ diff --git a/smalltalk.html.markdown~ b/smalltalk.html.markdown~ deleted file mode 100644 index 61e5a94c..00000000 --- a/smalltalk.html.markdown~ +++ /dev/null @@ -1,959 +0,0 @@ ---- -language: smalltalk -contributors: - - ["Jigyasa Grover", "https://github.com/jig08"] ---- - -- Smalltalk is an object-oriented, dynamically typed, reflective programming language. -- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." -- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s. - -Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`. - -``` - -"************************************************************************ - * Allowable characters: * - * - a-z * - * - A-Z * - * - 0-9 * - * - .+/\*~<>@%|&? * - * - blank, tab, cr, ff, lf * - * * - * Variables: * - * - variables must be declared before use * - * - shared vars must begin with uppercase * - * - local vars must begin with lowercase * - * - reserved names: nil, true, false, self, super, and Smalltalk * - * * - * Variable scope: * - * - Global: defined in Dictionary Smalltalk and accessible by all * - * objects in system * - * - Special: (reserved) Smalltalk, super, self, true, false, & nil * - * - Method Temporary: local to a method * - * - Block Temporary: local to a block * - * - Pool: variables in a Dictionary object * - * - Method Parameters: automatic local vars created as a result of * - * message call with params * - * - Block Parameters: automatic local vars created as a result of * - * value: message call * - * - Class: shared with all instances of one class & its subclasses * - * - Class Instance: unique to each instance of a class * - * - Instance Variables: unique to each instance * - ************************************************************************" -"Comments are enclosed in quotes" -"Period (.) is the statement seperator" - -"************************************************************************ - * Transcript: * - ************************************************************************" -Transcript clear. "clear to transcript window" -Transcript show: 'Hello World'. "output string in transcript window" -Transcript nextPutAll: 'Hello World'. "output string in transcript window" -Transcript nextPut: $A. "output character in transcript window" -Transcript space. "output space character in transcript window" -Transcript tab. "output tab character in transcript window" -Transcript cr. "carriage return / linefeed" -'Hello' printOn: Transcript. "append print string into the window" -'Hello' storeOn: Transcript. "append store string into the window" -Transcript endEntry. "flush the output buffer" - -"************************************************************************ - * Assignment: * - ************************************************************************" -| x y | -x _ 4. "assignment (Squeak) <-" -x := 5. "assignment" -x := y := z := 6. "compound assignment" -x := (y := 6) + 1. -x := Object new. "bind to allocated instance of a class" -x := 123 class. "discover the object class" -x := Integer superclass. "discover the superclass of a class" -x := Object allInstances. "get an array of all instances of a class" -x := Integer allSuperclasses. "get all superclasses of a class" -x := 1.2 hash. "hash value for object" -y := x copy. "copy object" -y := x shallowCopy. "copy object (not overridden)" -y := x deepCopy. "copy object and instance vars" -y := x veryDeepCopy. "complete tree copy using a dictionary" - -"************************************************************************ - * Constants: * - ************************************************************************" -| b | -b := true. "true constant" -b := false. "false constant" -x := nil. "nil object constant" -x := 1. "integer constants" -x := 3.14. "float constants" -x := 2e-2. "fractional constants" -x := 16r0F. "hex constant". -x := -1. "negative constants" -x := 'Hello'. "string constant" -x := 'I''m here'. "single quote escape" -x := $A. "character constant" -x := $ . "character constant (space)" -x := #aSymbol. "symbol constants" -x := #(3 2 1). "array constants" -x := #('abc' 2 $a). "mixing of types allowed" - -"************************************************************************ - * Booleans: * - ************************************************************************" -| b x y | -x := 1. y := 2. -b := (x = y). "equals" -b := (x ~= y). "not equals" -b := (x == y). "identical" -b := (x ~~ y). "not identical" -b := (x > y). "greater than" -b := (x < y). "less than" -b := (x >= y). "greater than or equal" -b := (x <= y). "less than or equal" -b := b not. "boolean not" -b := (x < 5) & (y > 1). "boolean and" -b := (x < 5) | (y > 1). "boolean or" -b := (x < 5) and: [y > 1]. "boolean and (short-circuit)" -b := (x < 5) or: [y > 1]. "boolean or (short-circuit)" -b := (x < 5) eqv: (y > 1). "test if both true or both false" -b := (x < 5) xor: (y > 1). "test if one true and other false" -b := 5 between: 3 and: 12. "between (inclusive)" -b := 123 isKindOf: Number. "test if object is class or subclass of" -b := 123 isMemberOf: SmallInteger. "test if object is type of class" -b := 123 respondsTo: sqrt. "test if object responds to message" -b := x isNil. "test if object is nil" -b := x isZero. "test if number is zero" -b := x positive. "test if number is positive" -b := x strictlyPositive. "test if number is greater than zero" -b := x negative. "test if number is negative" -b := x even. "test if number is even" -b := x odd. "test if number is odd" -b := x isLiteral. "test if literal constant" -b := x isInteger. "test if object is integer" -b := x isFloat. "test if object is float" -b := x isNumber. "test if object is number" -b := $A isUppercase. "test if upper case character" -b := $A isLowercase. "test if lower case character" - -"************************************************************************ - * Arithmetic expressions: * - ************************************************************************" -| x | -x := 6 + 3. "addition" -x := 6 - 3. "subtraction" -x := 6 * 3. "multiplication" -x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3" -x := 5 / 3. "division with fractional result" -x := 5.0 / 3.0. "division with float result" -x := 5.0 // 3.0. "integer divide" -x := 5.0 \\ 3.0. "integer remainder" -x := -5. "unary minus" -x := 5 sign. "numeric sign (1, -1 or 0)" -x := 5 negated. "negate receiver" -x := 1.2 integerPart. "integer part of number (1.0)" -x := 1.2 fractionPart. "fractional part of number (0.2)" -x := 5 reciprocal. "reciprocal function" -x := 6 * 3.1. "auto convert to float" -x := 5 squared. "square function" -x := 25 sqrt. "square root" -x := 5 raisedTo: 2. "power function" -x := 5 raisedToInteger: 2. "power function with integer" -x := 5 exp. "exponential" -x := -5 abs. "absolute value" -x := 3.99 rounded. "round" -x := 3.99 truncated. "truncate" -x := 3.99 roundTo: 1. "round to specified decimal places" -x := 3.99 truncateTo: 1. "truncate to specified decimal places" -x := 3.99 floor. "truncate" -x := 3.99 ceiling. "round up" -x := 5 factorial. "factorial" -x := -5 quo: 3. "integer divide rounded toward zero" -x := -5 rem: 3. "integer remainder rounded toward zero" -x := 28 gcd: 12. "greatest common denominator" -x := 28 lcm: 12. "least common multiple" -x := 100 ln. "natural logarithm" -x := 100 log. "base 10 logarithm" -x := 100 log: 10. "logarithm with specified base" -x := 100 floorLog: 10. "floor of the log" -x := 180 degreesToRadians. "convert degrees to radians" -x := 3.14 radiansToDegrees. "convert radians to degrees" -x := 0.7 sin. "sine" -x := 0.7 cos. "cosine" -x := 0.7 tan. "tangent" -x := 0.7 arcSin. "arcsine" -x := 0.7 arcCos. "arccosine" -x := 0.7 arcTan. "arctangent" -x := 10 max: 20. "get maximum of two numbers" -x := 10 min: 20. "get minimum of two numbers" -x := Float pi. "pi" -x := Float e. "exp constant" -x := Float infinity. "infinity" -x := Float nan. "not-a-number" -x := Random new next; yourself. x next. "random number stream (0.0 to 1.0) -x := 100 atRandom. "quick random number" - -"************************************************************************ - * Bitwise Manipulation: * - ************************************************************************" -| b x | -x := 16rFF bitAnd: 16r0F. "and bits" -x := 16rF0 bitOr: 16r0F. "or bits" -x := 16rFF bitXor: 16r0F. "xor bits" -x := 16rFF bitInvert. "invert bits" -x := 16r0F bitShift: 4. "left shift" -x := 16rF0 bitShift: -4. "right shift" -"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]" -x := 16r80 highbit. "position of highest bit set" -b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver" -b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver" -b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" - -"************************************************************************ - * Conversion: * - ************************************************************************" -| x | -x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" -x := 3.99 asFraction. "convert number to fraction" -x := 3 asFloat. "convert number to float" -x := 65 asCharacter. "convert integer to character" -x := $A asciiValue. "convert character to integer" -x := 3.99 printString. "convert object to string via printOn:" -x := 3.99 storeString. "convert object to string via storeOn:" -x := 15 radix: 16. "convert to string in given base" -x := 15 printStringBase: 16. -x := 15 storeStringBase: 16. - -"************************************************************************ - * Blocks: * - * - blocks are objects and may be assigned to a variable * - * - value is last expression evaluated unless explicit return * - * - blocks may be nested * - * - specification [ arguments | | localvars | expressions ] * - * - Squeak does not currently support localvars in blocks * - * - max of three arguments allowed * - * - ^expression terminates block & method (exits all nested blocks) * - * - blocks intended for long term storage should not contain ^ * - ************************************************************************" -| x y z | -x := [ y := 1. z := 2. ]. x value. "simple block usage" -x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing" -Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing" -"x := [ | z | z := 1.]. localvars not available in squeak blocks" - -"************************************************************************ - * Method calls: * - * - unary methods are messages with no arguments * - * - binary methods * - * - keyword methods are messages with selectors including colons * - * * - * standard categories/protocols: * - * - initialize-release (methods called for new instance) * - * - accessing (get/set methods) * - * - testing (boolean tests - is) * - * - comparing (boolean tests with parameter * - * - displaying (gui related methods) * - * - printing (methods for printing) * - * - updating (receive notification of changes) * - * - private (methods private to class) * - * - instance-creation (class methods for creating instance) * - ************************************************************************" -| x | -x := 2 sqrt. "unary message" -x := 2 raisedTo: 10. "keyword message" -x := 194 * 9. "binary message" -Transcript show: (194 * 9) printString; cr. "combination (chaining)" -x := 2 perform: #sqrt. "indirect method invocation" -Transcript "Cascading - send multiple messages to receiver" - show: 'hello '; - show: 'world'; - cr. -x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" - -"************************************************************************ - * Conditional Statements: * - ************************************************************************" -| x | -x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" -x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else" -x > 10 "if then else" - ifTrue: [Transcript show: 'ifTrue'; cr] - ifFalse: [Transcript show: 'ifFalse'; cr]. -x > 10 "if else then" - ifFalse: [Transcript show: 'ifFalse'; cr] - ifTrue: [Transcript show: 'ifTrue'; cr]. -Transcript - show: - (x > 10 - ifTrue: ['ifTrue'] - ifFalse: ['ifFalse']); - cr. -Transcript "nested if then else" - show: - (x > 10 - ifTrue: [x > 5 - ifTrue: ['A'] - ifFalse: ['B']] - ifFalse: ['C']); - cr. -switch := Dictionary new. "switch functionality" -switch at: $A put: [Transcript show: 'Case A'; cr]. -switch at: $B put: [Transcript show: 'Case B'; cr]. -switch at: $C put: [Transcript show: 'Case C'; cr]. -result := (switch at: $B) value. - -"************************************************************************ - * Iteration statements: * - ************************************************************************" -| x y | -x := 4. y := 1. -[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" -[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" -x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)" -1 to: x do: [:a | y := y * 2]. "for loop" -1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" -#(5 4 3) do: [:a | x := x + a]. "iterate over array elements" - -"************************************************************************ - * Character: * - ************************************************************************" -| x y | -x := $A. "character assignment" -y := x isLowercase. "test if lower case" -y := x isUppercase. "test if upper case" -y := x isLetter. "test if letter" -y := x isDigit. "test if digit" -y := x isAlphaNumeric. "test if alphanumeric" -y := x isSeparator. "test if seperator char" -y := x isVowel. "test if vowel" -y := x digitValue. "convert to numeric digit value" -y := x asLowercase. "convert to lower case" -y := x asUppercase. "convert to upper case" -y := x asciiValue. "convert to numeric ascii value" -y := x asString. "convert to string" -b := $A <= $B. "comparison" -y := $A max: $B. - -"************************************************************************ - * Symbol: * - ************************************************************************" -| b x y | -x := #Hello. "symbol assignment" -y := 'String', 'Concatenation'. "symbol concatenation (result is string)" -b := x isEmpty. "test if symbol is empty" -y := x size. "string size" -y := x at: 2. "char at location" -y := x copyFrom: 2 to: 4. "substring" -y := x indexOf: $e ifAbsent: [0]. "first position of character within string" -x do: [:a | Transcript show: a printString; cr]. "iterate over the string" -b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" -y := x select: [:a | a > $a]. "return all elements that meet condition" -y := x asString. "convert symbol to string" -y := x asText. "convert symbol to text" -y := x asArray. "convert symbol to array" -y := x asOrderedCollection. "convert symbol to ordered collection" -y := x asSortedCollection. "convert symbol to sorted collection" -y := x asBag. "convert symbol to bag collection" -y := x asSet. "convert symbol to set collection" - -"************************************************************************ - * String: * - ************************************************************************" -| b x y | -x := 'This is a string'. "string assignment" -x := 'String', 'Concatenation'. "string concatenation" -b := x isEmpty. "test if string is empty" -y := x size. "string size" -y := x at: 2. "char at location" -y := x copyFrom: 2 to: 4. "substring" -y := x indexOf: $a ifAbsent: [0]. "first position of character within string" -x := String new: 4. "allocate string object" -x "set string elements" - at: 1 put: $a; - at: 2 put: $b; - at: 3 put: $c; - at: 4 put: $e. -x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time" -x do: [:a | Transcript show: a printString; cr]. "iterate over the string" -b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" -y := x select: [:a | a > $a]. "return all elements that meet condition" -y := x asSymbol. "convert string to symbol" -y := x asArray. "convert string to array" -x := 'ABCD' asByteArray. "convert string to byte array" -y := x asOrderedCollection. "convert string to ordered collection" -y := x asSortedCollection. "convert string to sorted collection" -y := x asBag. "convert string to bag collection" -y := x asSet. "convert string to set collection" -y := x shuffled. "randomly shuffle string" - -"************************************************************************ - * Array: Fixed length collection * - * ByteArray: Array limited to byte elements (0-255) * - * WordArray: Array limited to word elements (0-2^32) * - ************************************************************************" -| b x y sum max | -x := #(4 3 2 1). "constant array" -x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" -x := Array new: 4. "allocate an array with specified size" -x "set array elements" - at: 1 put: 5; - at: 2 put: 4; - at: 3 put: 3; - at: 4 put: 2. -b := x isEmpty. "test if array is empty" -y := x size. "array size" -y := x at: 4. "get array element at index" -b := x includes: 3. "test if element is in array" -y := x copyFrom: 2 to: 4. "subarray" -y := x indexOf: 3 ifAbsent: [0]. "first position of element within array" -y := x occurrencesOf: 3. "number of times object in collection" -x do: [:a | Transcript show: a printString; cr]. "iterate over the array" -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 2]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements" -sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum array elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in array" - ifTrue: [a] - ifFalse: [c]]. -y := x shuffled. "randomly shuffle collection" -y := x asArray. "convert to array" -"y := x asByteArray." "note: this instruction not available on Squeak" -y := x asWordArray. "convert to word array" -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -"************************************************************************ - * OrderedCollection: acts like an expandable array * - ************************************************************************" -| b x y sum max | -x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" -x := OrderedCollection new. "allocate collection" -x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" -y := x addFirst: 5. "add element at beginning of collection" -y := x removeFirst. "remove first element in collection" -y := x addLast: 6. "add element at end of collection" -y := x removeLast. "remove last element in collection" -y := x addAll: #(7 8 9). "add multiple elements to collection" -y := x removeAll: #(7 8 9). "remove multiple elements from collection" -x at: 2 put: 3. "set element at index" -y := x remove: 5 ifAbsent: []. "remove element from collection" -b := x isEmpty. "test if empty" -y := x size. "number of elements" -y := x at: 2. "retrieve element at index" -y := x first. "retrieve first element in collection" -y := x last. "retrieve last element in collection" -b := x includes: 5. "test if element is in collection" -y := x copyFrom: 2 to: 3. "subcollection" -y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" -y := x occurrencesOf: 3. "number of times object in collection" -x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 2]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" -sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" - ifTrue: [a] - ifFalse: [c]]. -y := x shuffled. "randomly shuffle collection" -y := x asArray. "convert to array" -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -"************************************************************************ - * SortedCollection: like OrderedCollection except order of elements * - * determined by sorting criteria * - ************************************************************************" -| b x y sum max | -x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" -x := SortedCollection new. "allocate collection" -x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria" -x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" -y := x addFirst: 5. "add element at beginning of collection" -y := x removeFirst. "remove first element in collection" -y := x addLast: 6. "add element at end of collection" -y := x removeLast. "remove last element in collection" -y := x addAll: #(7 8 9). "add multiple elements to collection" -y := x removeAll: #(7 8 9). "remove multiple elements from collection" -y := x remove: 5 ifAbsent: []. "remove element from collection" -b := x isEmpty. "test if empty" -y := x size. "number of elements" -y := x at: 2. "retrieve element at index" -y := x first. "retrieve first element in collection" -y := x last. "retrieve last element in collection" -b := x includes: 4. "test if element is in collection" -y := x copyFrom: 2 to: 3. "subcollection" -y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" -y := x occurrencesOf: 3. "number of times object in collection" -x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 2]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" -sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" - ifTrue: [a] - ifFalse: [c]]. -y := x asArray. "convert to array" -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -"************************************************************************ - * Bag: like OrderedCollection except elements are in no * - * particular order * - ************************************************************************" -| b x y sum max | -x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" -x := Bag new. "allocate collection" -x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" -x add: 3 withOccurrences: 2. "add multiple copies to collection" -y := x addAll: #(7 8 9). "add multiple elements to collection" -y := x removeAll: #(7 8 9). "remove multiple elements from collection" -y := x remove: 4 ifAbsent: []. "remove element from collection" -b := x isEmpty. "test if empty" -y := x size. "number of elements" -b := x includes: 3. "test if element is in collection" -y := x occurrencesOf: 3. "number of times object in collection" -x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 2]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" - ifTrue: [a] - ifFalse: [c]]. -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -"************************************************************************ - * Set: like Bag except duplicates not allowed * - * IdentitySet: uses identity test (== rather than =) * - ************************************************************************" -| b x y sum max | -x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" -x := Set new. "allocate collection" -x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" -y := x addAll: #(7 8 9). "add multiple elements to collection" -y := x removeAll: #(7 8 9). "remove multiple elements from collection" -y := x remove: 4 ifAbsent: []. "remove element from collection" -b := x isEmpty. "test if empty" -y := x size. "number of elements" -x includes: 4. "test if element is in collection" -x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 2]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" - ifTrue: [a] - ifFalse: [c]]. -y := x asArray. "convert to array" -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -"************************************************************************ - * Interval: * - ************************************************************************" -| b x y sum max | -x := Interval from: 5 to: 10. "create interval object" -x := 5 to: 10. -x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment" -x := 5 to: 10 by: 2. -b := x isEmpty. "test if empty" -y := x size. "number of elements" -x includes: 9. "test if element is in collection" -x do: [:k | Transcript show: k printString; cr]. "iterate over interval" -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 7]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" -sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" - ifTrue: [a] - ifFalse: [c]]. -y := x asArray. "convert to array" -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -"************************************************************************ - * Associations: * - ************************************************************************" -| x y | -x := #myVar->'hello'. -y := x key. -y := x value. - -"************************************************************************ - * Dictionary: * - * IdentityDictionary: uses identity test (== rather than =) * - ************************************************************************" -| b x y | -x := Dictionary new. "allocate collection" -x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection" -x at: #e put: 3. "set element at index" -b := x isEmpty. "test if empty" -y := x size. "number of elements" -y := x at: #a ifAbsent: []. "retrieve element at index" -y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block" -y := x removeKey: #e ifAbsent: []. "remove element from collection" -b := x includes: 3. "test if element is in values collection" -b := x includesKey: #a. "test if element is in keys collection" -y := x occurrencesOf: 3. "number of times object in collection" -y := x keys. "set of keys" -y := x values. "bag of values" -x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection" -x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection" -x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations" -x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values" - show: aKey printString; space; - show: aValue printString; cr]. -b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" -y := x select: [:a | a > 2]. "return collection of elements that pass test" -y := x reject: [:a | a < 2]. "return collection of elements that fail test" -y := x collect: [:a | a + a]. "transform each element for new collection" -y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" -sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" -sum := x inject: 0 into: [:a :c | a + c]. "sum elements" -max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" - ifTrue: [a] - ifFalse: [c]]. -y := x asArray. "convert to array" -y := x asOrderedCollection. "convert to ordered collection" -y := x asSortedCollection. "convert to sorted collection" -y := x asBag. "convert to bag collection" -y := x asSet. "convert to set collection" - -Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary" -x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary" -Transcript show: (CMRGlobal printString). "entries are directly accessible by name" -Smalltalk keys do: [ :k | "print out all classes" - ((Smalltalk at: k) isKindOf: Class) - ifFalse: [Transcript show: k printString; cr]]. -Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary" -CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary" -CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo" -CMRDictionary size. "dictionary size" -CMRDictionary keys do: [ :k | "print out keys in dictionary" - Transcript show: k printString; cr]. -CMRDictionary values do: [ :k | "print out values in dictionary" - Transcript show: k printString; cr]. -CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values" - Transcript - show: aKey printString; - space; - show: aValue printString; - cr]. -CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values" - Transcript show: aKeyValue printString; cr]. -Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary" -Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" - -"************************************************************************ - * Internal Stream: * - ************************************************************************" -| b x ios | -ios := ReadStream on: 'Hello read stream'. -ios := ReadStream on: 'Hello read stream' from: 1 to: 5. -[(x := ios nextLine) notNil] - whileTrue: [Transcript show: x; cr]. -ios position: 3. -ios position. -x := ios next. -x := ios peek. -x := ios contents. -b := ios atEnd. - -ios := ReadWriteStream on: 'Hello read stream'. -ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5. -ios := ReadWriteStream with: 'Hello read stream'. -ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10. -ios position: 0. -[(x := ios nextLine) notNil] - whileTrue: [Transcript show: x; cr]. -ios position: 6. -ios position. -ios nextPutAll: 'Chris'. -x := ios next. -x := ios peek. -x := ios contents. -b := ios atEnd. - -"************************************************************************ - * FileStream: * - ************************************************************************" -| b x ios | -ios := FileStream newFileNamed: 'ios.txt'. -ios nextPut: $H; cr. -ios nextPutAll: 'Hello File'; cr. -'Hello File' printOn: ios. -'Hello File' storeOn: ios. -ios close. - -ios := FileStream oldFileNamed: 'ios.txt'. -[(x := ios nextLine) notNil] - whileTrue: [Transcript show: x; cr]. -ios position: 3. -x := ios position. -x := ios next. -x := ios peek. -b := ios atEnd. -ios close. - -"************************************************************************ - * Date: * - ************************************************************************" -| x y | -x := Date today. "create date for today" -x := Date dateAndTimeNow. "create date from current time/date" -x := Date readFromString: '01/02/1999'. "create date from formatted string" -x := Date newDay: 12 month: #July year: 1999 "create date from parts" -x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901" -y := Date dayOfWeek: #Monday. "day of week as int (1-7)" -y := Date indexOfMonth: #January. "month of year as int (1-12)" -y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)" -y := Date daysInYear: 1996. "days in year (365|366)" -y := Date nameOfDay: 1 "weekday name (#Monday,...)" -y := Date nameOfMonth: 1. "month name (#January,...)" -y := Date leapYear: 1996. "1 if leap year; 0 if not leap year" -y := x weekday. "day of week (#Monday,...)" -y := x previous: #Monday. "date for previous day of week" -y := x dayOfMonth. "day of month (1-31)" -y := x day. "day of year (1-366)" -y := x firstDayOfMonth. "day of year for first day of month" -y := x monthName. "month of year (#January,...)" -y := x monthIndex. "month of year (1-12)" -y := x daysInMonth. "days in month (1-31)" -y := x year. "year (19xx)" -y := x daysInYear. "days in year (365|366)" -y := x daysLeftInYear. "days left in year (364|365)" -y := x asSeconds. "seconds elapsed since 1/1/1901" -y := x addDays: 10. "add days to date object" -y := x subtractDays: 10. "subtract days to date object" -y := x subtractDate: (Date today). "subtract date (result in days)" -y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date" -b := (x <= Date today). "comparison" - -"************************************************************************ - * Time: * - ************************************************************************" -| x y | -x := Time now. "create time from current time" -x := Time dateAndTimeNow. "create time from current time/date" -x := Time readFromString: '3:47:26 pm'. "create time from formatted string" -x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight" -y := Time millisecondClockValue. "milliseconds since midnight" -y := Time totalSeconds. "total seconds since 1/1/1901" -y := x seconds. "seconds past minute (0-59)" -y := x minutes. "minutes past hour (0-59)" -y := x hours. "hours past midnight (0-23)" -y := x addTime: (Time now). "add time to time object" -y := x subtractTime: (Time now). "subtract time to time object" -y := x asSeconds. "convert time to seconds" -x := Time millisecondsToRun: [ "timing facility" - 1 to: 1000 do: [:index | y := 3.14 * index]]. -b := (x <= Time now). "comparison" - -"************************************************************************ - * Point: * - ************************************************************************" -| x y | -x := 200@100. "obtain a new point" -y := x x. "x coordinate" -y := x y. "y coordinate" -x := 200@100 negated. "negates x and y" -x := (-200@-100) abs. "absolute value of x and y" -x := (200.5@100.5) rounded. "round x and y" -x := (200.5@100.5) truncated. "truncate x and y" -x := 200@100 + 100. "add scale to both x and y" -x := 200@100 - 100. "subtract scale from both x and y" -x := 200@100 * 2. "multiply x and y by scale" -x := 200@100 / 2. "divide x and y by scale" -x := 200@100 // 2. "divide x and y by scale" -x := 200@100 \\ 3. "remainder of x and y by scale" -x := 200@100 + 50@25. "add points" -x := 200@100 - 50@25. "subtract points" -x := 200@100 * 3@4. "multiply points" -x := 200@100 // 3@4. "divide points" -x := 200@100 max: 50@200. "max x and y" -x := 200@100 min: 50@200. "min x and y" -x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" - -"************************************************************************ - * Rectangle: * - ************************************************************************" -Rectangle fromUser. - -"************************************************************************ - * Pen: * - ************************************************************************" -| myPen | -Display restoreAfter: [ - Display fillWhite. - -myPen := Pen new. "get graphic pen" -myPen squareNib: 1. -myPen color: (Color blue). "set pen color" -myPen home. "position pen at center of display" -myPen up. "makes nib unable to draw" -myPen down. "enable the nib to draw" -myPen north. "points direction towards top" -myPen turn: -180. "add specified degrees to direction" -myPen direction. "get current angle of pen" -myPen go: 50. "move pen specified number of pixels" -myPen location. "get the pen position" -myPen goto: 200@200. "move to specified point" -myPen place: 250@250. "move to specified point without drawing" -myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1). -Display extent. "get display width@height" -Display width. "get display width" -Display height. "get display height" - -]. - -"************************************************************************ - * Dynamic Message Calling/Compiling: * - ************************************************************************" -| receiver message result argument keyword1 keyword2 argument1 argument2 | -"unary message" -receiver := 5. -message := 'factorial' asSymbol. -result := receiver perform: message. -result := Compiler evaluate: ((receiver storeString), ' ', message). -result := (Message new setSelector: message arguments: #()) sentTo: receiver. - -"binary message" -receiver := 1. -message := '+' asSymbol. -argument := 2. -result := receiver perform: message withArguments: (Array with: argument). -result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)). -result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver. - -"keyword messages" -receiver := 12. -keyword1 := 'between:' asSymbol. -keyword2 := 'and:' asSymbol. -argument1 := 10. -argument2 := 20. -result := receiver - perform: (keyword1, keyword2) asSymbol - withArguments: (Array with: argument1 with: argument2). -result := Compiler evaluate: - ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)). -result := (Message - new - setSelector: (keyword1, keyword2) asSymbol - arguments: (Array with: argument1 with: argument2)) - sentTo: receiver. - -"************************************************************************ - * class/meta-class: * - ************************************************************************" -| b x | -x := String name. "class name" -x := String category. "organization category" -x := String comment. "class comment" -x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc" -x := String definition. "class definition" -x := String instVarNames. "immediate instance variable names" -x := String allInstVarNames. "accumulated instance variable names" -x := String classVarNames. "immediate class variable names" -x := String allClassVarNames. "accumulated class variable names" -x := String sharedPools. "immediate dictionaries used as shared pools" -x := String allSharedPools. "accumulated dictionaries used as shared pools" -x := String selectors. "message selectors for class" -x := String sourceCodeAt: #size. "source code for specified method" -x := String allInstances. "collection of all instances of class" -x := String superclass. "immediate superclass" -x := String allSuperclasses. "accumulated superclasses" -x := String withAllSuperclasses. "receiver class and accumulated superclasses" -x := String subclasses. "immediate subclasses" -x := String allSubclasses. "accumulated subclasses" -x := String withAllSubclasses. "receiver class and accumulated subclasses" -b := String instSize. "number of named instance variables" -b := String isFixed. "true if no indexed instance variables" -b := String isVariable. "true if has indexed instance variables" -b := String isPointers. "true if index instance vars contain objects" -b := String isBits. "true if index instance vars contain bytes/words" -b := String isBytes. "true if index instance vars contain bytes" -b := String isWords. true if index instance vars contain words" -Object withAllSubclasses size. "get total number of class entries" - -"************************************************************************ - * debuging: * - ************************************************************************" -| a b x | -x yourself. "returns receiver" -String browse. "browse specified class" -x inspect. "open object inspector window" -x confirm: 'Is this correct?'. -x halt. "breakpoint to open debugger window" -x halt: 'Halt message'. -x notify: 'Notify text'. -x error: 'Error string'. "open up error window with title" -x doesNotUnderstand: #cmrMessage. "flag message is not handled" -x shouldNotImplement. "flag message should not be implemented" -x subclassResponsibility. "flag message as abstract" -x errorImproperStore. "flag an improper store into indexable object" -x errorNonIntegerIndex. "flag only integers should be used as index" -x errorSubscriptBounds. "flag subscript out of bounds" -x primitiveFailed. "system primitive failed" - -a := 'A1'. b := 'B2'. a become: b. "switch two objects" -Transcript show: a, b; cr. - -"************************************************************************ - * Misc. * - ************************************************************************" -| x | -"Smalltalk condenseChanges." "compress the change file" -x := FillInTheBlank request: 'Prompt Me'. "prompt user for input" -Utilities openCommandKeyHelp - - - - -``` - -## Ready For More? - -### Free Online - -* [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) -* [smalltalk dot org](http://www.smalltalk.org/smalltalk/learning.html) -* [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) -* [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) -* [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) -* [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) -* [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) -* [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) -- cgit v1.2.3 From 2cf31d970603d2fe52a2c652f889556046e3330e Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:22:53 +0530 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 63 ++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 35 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 61e5a94c..5f1e7430 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -8,41 +8,34 @@ contributors: - Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." - It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s. -Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`. - -``` - -"************************************************************************ - * Allowable characters: * - * - a-z * - * - A-Z * - * - 0-9 * - * - .+/\*~<>@%|&? * - * - blank, tab, cr, ff, lf * - * * - * Variables: * - * - variables must be declared before use * - * - shared vars must begin with uppercase * - * - local vars must begin with lowercase * - * - reserved names: nil, true, false, self, super, and Smalltalk * - * * - * Variable scope: * - * - Global: defined in Dictionary Smalltalk and accessible by all * - * objects in system * - * - Special: (reserved) Smalltalk, super, self, true, false, & nil * - * - Method Temporary: local to a method * - * - Block Temporary: local to a block * - * - Pool: variables in a Dictionary object * - * - Method Parameters: automatic local vars created as a result of * - * message call with params * - * - Block Parameters: automatic local vars created as a result of * - * value: message call * - * - Class: shared with all instances of one class & its subclasses * - * - Class Instance: unique to each instance of a class * - * - Instance Variables: unique to each instance * - ************************************************************************" -"Comments are enclosed in quotes" -"Period (.) is the statement seperator" +Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`. + + +##Allowable characters: +- a-z +- A-Z +- 0-9 +- .+/\*~<>@%|&? +- blank, tab, cr, ff, lf + +##Variables: +- variables must be declared before use +- shared vars must begin with uppercase +- local vars must begin with lowercase +- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk` + +##Variable scope: +- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` +- Method Temporary: local to a method +- Block Temporary: local to a block +- Pool: variables in a Dictionary object +- Method Parameters: automatic local vars created as a result of message call with params - Block Parameters: automatic local vars created as a result of value: message call - Class: shared with all instances of one class & its subclasses + - Class Instance: unique to each instance of a class +- Instance Variables: unique to each instance + +`"Comments are enclosed in quotes"` + +`"Period (.) is the statement seperator"` "************************************************************************ * Transcript: * -- cgit v1.2.3 From 67a2c46bca8362e8cc3c4a360f6a2065bfa7c0f1 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:23:36 +0530 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 5f1e7430..e9e5a56c 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -936,8 +936,6 @@ Utilities openCommandKeyHelp -``` - ## Ready For More? ### Free Online -- cgit v1.2.3 From 40489d4352ada61f3e788190bc07689825aedf14 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:28:20 +0530 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index e9e5a56c..2c2ee3f7 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -37,9 +37,8 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j `"Period (.) is the statement seperator"` -"************************************************************************ - * Transcript: * - ************************************************************************" +## Transcript: +``` Transcript clear. "clear to transcript window" Transcript show: 'Hello World'. "output string in transcript window" Transcript nextPutAll: 'Hello World'. "output string in transcript window" @@ -50,6 +49,7 @@ Transcript cr. "carriage return / l 'Hello' printOn: Transcript. "append print string into the window" 'Hello' storeOn: Transcript. "append store string into the window" Transcript endEntry. "flush the output buffer" +``` "************************************************************************ * Assignment: * -- cgit v1.2.3 From 5bf5f1268654e637e0fa08001396e4ea179e0ef9 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:44:20 +0530 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 254 ++++++++++++++++++++++++------------------------ 1 file changed, 128 insertions(+), 126 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 2c2ee3f7..175810d7 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -51,9 +51,8 @@ Transcript cr. "carriage return / l Transcript endEntry. "flush the output buffer" ``` -"************************************************************************ - * Assignment: * - ************************************************************************" +##Assignment: +``` | x y | x _ 4. "assignment (Squeak) <-" x := 5. "assignment" @@ -69,10 +68,10 @@ y := x copy. "copy object" y := x shallowCopy. "copy object (not overridden)" y := x deepCopy. "copy object and instance vars" y := x veryDeepCopy. "complete tree copy using a dictionary" +``` -"************************************************************************ - * Constants: * - ************************************************************************" +##Constants: +``` | b | b := true. "true constant" b := false. "false constant" @@ -90,9 +89,10 @@ x := #aSymbol. "symbol constants" x := #(3 2 1). "array constants" x := #('abc' 2 $a). "mixing of types allowed" -"************************************************************************ - * Booleans: * - ************************************************************************" +``` + +## Booleans: +``` | b x y | x := 1. y := 2. b := (x = y). "equals" @@ -128,9 +128,10 @@ b := x isNumber. "test if object is n b := $A isUppercase. "test if upper case character" b := $A isLowercase. "test if lower case character" -"************************************************************************ - * Arithmetic expressions: * - ************************************************************************" +``` + +## Arithmetic expressions: +``` | x | x := 6 + 3. "addition" x := 6 - 3. "subtraction" @@ -185,9 +186,10 @@ x := Float nan. "not-a-number" x := Random new next; yourself. x next. "random number stream (0.0 to 1.0) x := 100 atRandom. "quick random number" -"************************************************************************ - * Bitwise Manipulation: * - ************************************************************************" +``` + +##Bitwise Manipulation: +``` | b x | x := 16rFF bitAnd: 16r0F. "and bits" x := 16rF0 bitOr: 16r0F. "or bits" @@ -201,9 +203,10 @@ b := 16rFF allMask: 16r0F. "test if all bits se b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver" b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" -"************************************************************************ - * Conversion: * - ************************************************************************" +``` + +## Conversion: +``` | x | x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" x := 3.99 asFraction. "convert number to fraction" @@ -216,40 +219,39 @@ x := 15 radix: 16. "convert to string i x := 15 printStringBase: 16. x := 15 storeStringBase: 16. -"************************************************************************ - * Blocks: * - * - blocks are objects and may be assigned to a variable * - * - value is last expression evaluated unless explicit return * - * - blocks may be nested * - * - specification [ arguments | | localvars | expressions ] * - * - Squeak does not currently support localvars in blocks * - * - max of three arguments allowed * - * - ^expression terminates block & method (exits all nested blocks) * - * - blocks intended for long term storage should not contain ^ * - ************************************************************************" +``` + +## Blocks: +- blocks are objects and may be assigned to a variable +- value is last expression evaluated unless explicit return +- blocks may be nested +- specification [ arguments | | localvars | expressions ] +- Squeak does not currently support localvars in blocks +- max of three arguments allowed +- `^`expression terminates block & method (exits all nested blocks) +- blocks intended for long term storage should not contain `^` + +``` | x y z | x := [ y := 1. z := 2. ]. x value. "simple block usage" x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing" Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing" -"x := [ | z | z := 1.]. localvars not available in squeak blocks" - -"************************************************************************ - * Method calls: * - * - unary methods are messages with no arguments * - * - binary methods * - * - keyword methods are messages with selectors including colons * - * * - * standard categories/protocols: * - * - initialize-release (methods called for new instance) * - * - accessing (get/set methods) * - * - testing (boolean tests - is) * - * - comparing (boolean tests with parameter * - * - displaying (gui related methods) * - * - printing (methods for printing) * - * - updating (receive notification of changes) * - * - private (methods private to class) * - * - instance-creation (class methods for creating instance) * - ************************************************************************" +"x := [ | z | z := 1.]. *** localvars not available in squeak blocks" +``` + +## Method calls: +- unary methods are messages with no arguments +- binary methods +- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance) +- accessing (get/set methods) +- testing (boolean tests - is) +- comparing (boolean tests with parameter +- displaying (gui related methods) +- printing (methods for printing) +- updating (receive notification of changes) +- private (methods private to class) +- instance-creation (class methods for creating instance) +``` | x | x := 2 sqrt. "unary message" x := 2 raisedTo: 10. "keyword message" @@ -261,10 +263,10 @@ Transcript "Cascading - send mu show: 'world'; cr. x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" +``` -"************************************************************************ - * Conditional Statements: * - ************************************************************************" +##Conditional Statements: +``` | x | x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else" @@ -293,10 +295,10 @@ switch at: $A put: [Transcript show: 'Case A'; cr]. switch at: $B put: [Transcript show: 'Case B'; cr]. switch at: $C put: [Transcript show: 'Case C'; cr]. result := (switch at: $B) value. +``` -"************************************************************************ - * Iteration statements: * - ************************************************************************" +## Iteration statements: +``` | x y | x := 4. y := 1. [x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" @@ -305,10 +307,10 @@ x timesRepeat: [y := y * 2]. "times repear loop ( 1 to: x do: [:a | y := y * 2]. "for loop" 1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" #(5 4 3) do: [:a | x := x + a]. "iterate over array elements" +``` -"************************************************************************ - * Character: * - ************************************************************************" +## Character: +``` | x y | x := $A. "character assignment" y := x isLowercase. "test if lower case" @@ -326,9 +328,10 @@ y := x asString. "convert to string" b := $A <= $B. "comparison" y := $A max: $B. -"************************************************************************ - * Symbol: * - ************************************************************************" +``` + +## Symbol: +``` | b x y | x := #Hello. "symbol assignment" y := 'String', 'Concatenation'. "symbol concatenation (result is string)" @@ -347,10 +350,10 @@ y := x asOrderedCollection. "convert symbol to o y := x asSortedCollection. "convert symbol to sorted collection" y := x asBag. "convert symbol to bag collection" y := x asSet. "convert symbol to set collection" +``` -"************************************************************************ - * String: * - ************************************************************************" +## String: +``` | b x y | x := 'This is a string'. "string assignment" x := 'String', 'Concatenation'. "string concatenation" @@ -377,12 +380,12 @@ y := x asSortedCollection. "convert string to s y := x asBag. "convert string to bag collection" y := x asSet. "convert string to set collection" y := x shuffled. "randomly shuffle string" +``` -"************************************************************************ - * Array: Fixed length collection * - * ByteArray: Array limited to byte elements (0-255) * - * WordArray: Array limited to word elements (0-2^32) * - ************************************************************************" +## Array: Fixed length collection +## ByteArray: Array limited to byte elements (0-255) +## WordArray: Array limited to word elements (0-2^32) +``` | b x y sum max | x := #(4 3 2 1). "constant array" x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" @@ -419,10 +422,10 @@ y := x asOrderedCollection. "convert to ordered y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" +``` -"************************************************************************ - * OrderedCollection: acts like an expandable array * - ************************************************************************" +##OrderedCollection: acts like an expandable array +``` | b x y sum max | x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" x := OrderedCollection new. "allocate collection" @@ -462,11 +465,10 @@ y := x asOrderedCollection. "convert to ordered y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" +``` -"************************************************************************ - * SortedCollection: like OrderedCollection except order of elements * - * determined by sorting criteria * - ************************************************************************" +## SortedCollection: like OrderedCollection except order of elements determined by sorting criteria +``` | b x y sum max | x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" x := SortedCollection new. "allocate collection" @@ -505,11 +507,10 @@ y := x asOrderedCollection. "convert to ordered y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" +``` -"************************************************************************ - * Bag: like OrderedCollection except elements are in no * - * particular order * - ************************************************************************" +## Bag: like OrderedCollection except elements are in no particular order +``` | b x y sum max | x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" x := Bag new. "allocate collection" @@ -537,11 +538,11 @@ y := x asOrderedCollection. "convert to ordered y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" +``` -"************************************************************************ - * Set: like Bag except duplicates not allowed * - * IdentitySet: uses identity test (== rather than =) * - ************************************************************************" +## Set: like Bag except duplicates not allowed +## IdentitySet: uses identity test (== rather than =) +``` | b x y sum max | x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" x := Set new. "allocate collection" @@ -568,10 +569,10 @@ y := x asOrderedCollection. "convert to ordered y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" +``` -"************************************************************************ - * Interval: * - ************************************************************************" +## Interval: +``` | b x y sum max | x := Interval from: 5 to: 10. "create interval object" x := 5 to: 10. @@ -597,19 +598,19 @@ y := x asOrderedCollection. "convert to ordered y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" +``` -"************************************************************************ - * Associations: * - ************************************************************************" +##Associations: +``` | x y | x := #myVar->'hello'. y := x key. y := x value. +``` -"************************************************************************ - * Dictionary: * - * IdentityDictionary: uses identity test (== rather than =) * - ************************************************************************" +## Dictionary: +## IdentityDictionary: uses identity test (== rather than =) +``` | b x y | x := Dictionary new. "allocate collection" x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection" @@ -670,10 +671,10 @@ CMRDictionary associationsDo: [:aKeyValue | "another iterator fo Transcript show: aKeyValue printString; cr]. Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary" Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" +``` -"************************************************************************ - * Internal Stream: * - ************************************************************************" +## Internal Stream: +``` | b x ios | ios := ReadStream on: 'Hello read stream'. ios := ReadStream on: 'Hello read stream' from: 1 to: 5. @@ -700,10 +701,10 @@ x := ios next. x := ios peek. x := ios contents. b := ios atEnd. +``` -"************************************************************************ - * FileStream: * - ************************************************************************" +## FileStream: +``` | b x ios | ios := FileStream newFileNamed: 'ios.txt'. ios nextPut: $H; cr. @@ -721,10 +722,10 @@ x := ios next. x := ios peek. b := ios atEnd. ios close. +``` -"************************************************************************ - * Date: * - ************************************************************************" +## Date: +``` | x y | x := Date today. "create date for today" x := Date dateAndTimeNow. "create date from current time/date" @@ -755,10 +756,10 @@ y := x subtractDays: 10. "subtract days to da y := x subtractDate: (Date today). "subtract date (result in days)" y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date" b := (x <= Date today). "comparison" +``` -"************************************************************************ - * Time: * - ************************************************************************" +## Time: +``` | x y | x := Time now. "create time from current time" x := Time dateAndTimeNow. "create time from current time/date" @@ -775,10 +776,10 @@ y := x asSeconds. "convert time to sec x := Time millisecondsToRun: [ "timing facility" 1 to: 1000 do: [:index | y := 3.14 * index]]. b := (x <= Time now). "comparison" +``` -"************************************************************************ - * Point: * - ************************************************************************" +## Point: +``` | x y | x := 200@100. "obtain a new point" y := x x. "x coordinate" @@ -800,15 +801,15 @@ x := 200@100 // 3@4. "divide points" x := 200@100 max: 50@200. "max x and y" x := 200@100 min: 50@200. "min x and y" x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" +``` -"************************************************************************ - * Rectangle: * - ************************************************************************" +## Rectangle: +``` Rectangle fromUser. +``` -"************************************************************************ - * Pen: * - ************************************************************************" +## Pen: +``` | myPen | Display restoreAfter: [ Display fillWhite. @@ -832,10 +833,10 @@ Display width. "get display width" Display height. "get display height" ]. +``` -"************************************************************************ - * Dynamic Message Calling/Compiling: * - ************************************************************************" +## Dynamic Message Calling/Compiling: +``` | receiver message result argument keyword1 keyword2 argument1 argument2 | "unary message" receiver := 5. @@ -868,10 +869,10 @@ result := (Message setSelector: (keyword1, keyword2) asSymbol arguments: (Array with: argument1 with: argument2)) sentTo: receiver. +``` -"************************************************************************ - * class/meta-class: * - ************************************************************************" +## Class/Meta-class: +``` | b x | x := String name. "class name" x := String category. "organization category" @@ -901,10 +902,10 @@ b := String isBits. "true if index insta b := String isBytes. "true if index instance vars contain bytes" b := String isWords. true if index instance vars contain words" Object withAllSubclasses size. "get total number of class entries" +``` -"************************************************************************ - * debuging: * - ************************************************************************" +## Debuging: +``` | a b x | x yourself. "returns receiver" String browse. "browse specified class" @@ -924,14 +925,15 @@ x primitiveFailed. "system primitive fa a := 'A1'. b := 'B2'. a become: b. "switch two objects" Transcript show: a, b; cr. +``` -"************************************************************************ - * Misc. * - ************************************************************************" +## Misc +``` | x | "Smalltalk condenseChanges." "compress the change file" x := FillInTheBlank request: 'Prompt Me'. "prompt user for input" Utilities openCommandKeyHelp +``` -- cgit v1.2.3 From 5a0b443ef243f7a6d0568adba1d8d972d67b9a62 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:48:04 +0530 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 175810d7..2095a72e 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -383,8 +383,9 @@ y := x shuffled. "randomly shuffle st ``` ## Array: Fixed length collection -## ByteArray: Array limited to byte elements (0-255) -## WordArray: Array limited to word elements (0-2^32) +- ByteArray: Array limited to byte elements (0-255) +- WordArray: Array limited to word elements (0-2^32) + ``` | b x y sum max | x := #(4 3 2 1). "constant array" -- cgit v1.2.3 From c220cced91bd05efda5120990973ce65b0d857b2 Mon Sep 17 00:00:00 2001 From: Jigyasa Grover Date: Sun, 4 Oct 2015 22:54:24 +0530 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 2095a72e..a434a1ad 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -29,8 +29,10 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j - Method Temporary: local to a method - Block Temporary: local to a block - Pool: variables in a Dictionary object -- Method Parameters: automatic local vars created as a result of message call with params - Block Parameters: automatic local vars created as a result of value: message call - Class: shared with all instances of one class & its subclasses - - Class Instance: unique to each instance of a class +- Method Parameters: automatic local vars created as a result of message call with params +- Block Parameters: automatic local vars created as a result of value: message call +- Class: shared with all instances of one class & its subclasses +- Class Instance: unique to each instance of a class - Instance Variables: unique to each instance `"Comments are enclosed in quotes"` -- cgit v1.2.3 From 87e8e77e5fd8d84a252dbb6d6697202118378774 Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Mon, 5 Oct 2015 00:13:54 +0530 Subject: Fixed a mistake from previous commit. Better explained reference address. --- c++.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index bbd2f9a9..bd86e9e5 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -245,9 +245,9 @@ cout << fooRef; // Prints "I am foo. Hi!" // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. -cout << &fooRef << endl; //Prints address of fooRef +cout << &fooRef << endl; //Prints address of foo fooRef = bar; -cout << &fooRef << endl; //Prints address of fooRef, AGAIN +cout << &fooRef << endl; //Still prints address of foo cout << fooRef; // Prints "I am bar" //The address of fooRef remains the same, i.e. it is still referring to foo. -- cgit v1.2.3 From f72588075d0cd200d53893ad51129844df17aea7 Mon Sep 17 00:00:00 2001 From: ozgur sahin Date: Sun, 4 Oct 2015 22:01:10 +0300 Subject: swift-tr.html.markdown Translated some English sentences. --- tr-tr/swift-tr.html.markdown | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index 41835e13..c13f5ecf 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -3,16 +3,14 @@ language: swift contributors: - ["Özgür Şahin", "https://github.com/ozgurshn/"] filename: learnswift.swift +lang: tr-tr --- Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi. - -The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı. -See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift. - Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var. @@ -243,7 +241,7 @@ print("Benzin fiyatı: \(fiyat)") // Çeşitli Argümanlar func ayarla(sayilar: Int...) { - // its an array + // bu bir dizidir let sayi = sayilar[0] let argumanSAyisi = sayilar.count } -- cgit v1.2.3 From 3b246fd869564b0a7f7c847f44aecac82d318c78 Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Mon, 5 Oct 2015 00:32:34 +0530 Subject: Grammar the address --- c++.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index bd86e9e5..8ee964ca 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -245,9 +245,9 @@ cout << fooRef; // Prints "I am foo. Hi!" // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. -cout << &fooRef << endl; //Prints address of foo +cout << &fooRef << endl; //Prints the address of foo fooRef = bar; -cout << &fooRef << endl; //Still prints address of foo +cout << &fooRef << endl; //Still prints the address of foo cout << fooRef; // Prints "I am bar" //The address of fooRef remains the same, i.e. it is still referring to foo. -- cgit v1.2.3 From 68fc9b5c1f71adcbbbd53711e9a5692a8372b8cf Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Mon, 5 Oct 2015 00:35:49 +0530 Subject: fixed the comment format --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index e3bb61cf..e0597e94 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -176,7 +176,7 @@ nil ; for false - and the empty list *rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) (dog-p *rover*) ; => true #| -p signifies "predicate". It's used to - check if *rover* is an instance of dog.|# + check if *rover* is an instance of dog. |# (dog-name *rover*) ; => "rover" ;; Dog-p, make-dog, and dog-name are all created by defstruct! -- cgit v1.2.3 From 1194e9456f2f1302614f8086349c01f4797d34c0 Mon Sep 17 00:00:00 2001 From: willianjusten Date: Sun, 4 Oct 2015 16:13:11 -0300 Subject: Fixing some typos --- pt-br/javascript-pt.html.markdown | 45 +++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index e39c6c8e..406042fa 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -3,20 +3,21 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] -filename: javascript.js +translators: + - ["Willian Justen", "http://willianjusten.com.br"] +lang: pt-br --- -JavaScript foi criada por Brendan Eich, funcionário da Netscape, em 1995. Ela +JavaScript foi criada por Brendan Eich, funcionário da Netscape na época, em 1995. Ela foi originalmente criada para ser uma linguagem de script para websites, complementando o uso de Java para aplicações web mais complexas, mas a sua integração com páginas web e seu suporte nativo nos browsers fez com que ela se tornasse mais comum que Java no frontend web. -Javascript não é somente limitado a browsers web, no entanto: existe o Node.js, +Javascript não é somente limitada a browsers web, existindo o Node.js, que é um projeto que fornece um interpretador baseado no motor V8 do Google Chrome e está se tornando cada vez mais famoso. - Feedback são muito apreciados! Você me encontrar em [@adambrenecki](https://twitter.com/adambrenecki), ou [adam@brenecki.id.au](mailto:adam@brenecki.id.au). @@ -29,23 +30,23 @@ Feedback são muito apreciados! Você me encontrar em // comandos podem ser terminados com ; facaAlgo(); -// ... mas eles não precisam ser, assim como o ponto-e-vírgula é automaticamente +// ... mas eles não precisam ser, o ponto-e-vírgula é automaticamente // inserido quando há uma nova linha, exceto alguns casos. facaAlgo() -// Porque esses casos podem causar resultados inesperados, vamos continuar +// Como esses casos podem causar resultados inesperados, vamos continuar // a usar ponto-e-vírgula neste guia. /////////////////////////////////// // 1. Números, Strings e Operadores // Javascript tem um tipo de número (que é o 64-bit IEEE 754 double). -// Doublas tem uma mantissa 52-bit, que é suficiente para guardar inteiros +// Doubles tem uma mantissa 52-bit, que é suficiente para guardar inteiros // acima de 9✕10¹⁵ precisamente. 3; // = 3 1.5; // = 1.5 -// A aritmética básica funciona seria de esperar. +// A aritmética básica funciona como seria de se esperar. 1 + 1; // = 2 0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 @@ -62,7 +63,6 @@ facaAlgo() // A precedência é aplicada com parênteses. (1 + 3) * 2; // = 8 -// There are three special not-a-real-number values: // Existem três especiais valores não-é-número-real: Infinity; // resultado de 1/0 -Infinity; // resultado de -1/0 @@ -76,16 +76,15 @@ false; 'abc'; "Olá, mundo"; -// Negation uses the ! symbol // Negação usa o símbolo ! !true; // = false !false; // = true -// Igualdade é === +// Igualdade é o sinal de === 1 === 1; // = true 2 === 1; // = false -// Desigualdade é !== +// Desigualdade é o sinal de !== 1 !== 1; // = false 2 !== 1; // = true @@ -101,7 +100,7 @@ false; // e comparadas com < e > "a" < "b"; // = true -// A coerção de tipos é feita para comparações com dois iguais... +// A comparação de tipos não é feita com o uso de ==... "5" == 5; // = true null == undefined; // = true @@ -109,7 +108,7 @@ null == undefined; // = true "5" === 5; // = false null === undefined; // = false -// ...que irá resultar num comportamento estranho... +// ...isso pode resultar em comportamentos estranhos... 13 + !0; // 14 "13" + !0; // '13true' @@ -125,21 +124,21 @@ null === undefined; // = false // Existe também o `null` e o `undefined`. null; // usado para indicar um valor não considerado undefined; // usado para indicar um valor que não é a atualmente definido - // (entretando `undefined` é usado como um próprio valor + // (entretando `undefined` é considerado de fato um valor -// false, null, undefined, NaN, 0 and "" são valores falsy; -// qualquer outro valor é truthy -// Note que 0 é falsy e "0" é truthy, até mesmo 0 == "0". +// false, null, undefined, NaN, 0 and "" são valores falsos; +// qualquer outro valor é verdadeiro +// Note que 0 é falso e "0" é verdadeiro, até mesmo 0 == "0". /////////////////////////////////// // 2. Variáveis, Arrays e Objetos -// Variáveis são declarados com a palavra-chave `var`. O Javascript é +// Variáveis são declaradas com a palavra-chave `var`. O Javascript é // dinâmicamente tipado, portanto você não precisa especificar o tipo. // Atribuições usam um simples caracter de `=`. var someVar = 5; -// se você deixar de colocar a palavra-chave var, você não receber um erro... +// se você deixar de colocar a palavra-chave var, você não irá receber um erro... someOtherVar = 10; // ...mas sua variável será criada no escopo global, não no escopo em que você @@ -148,13 +147,13 @@ someOtherVar = 10; // Variáveis declaradas sem receberem um valor são definidas como `undefined`. var someThirdVar; // = undefined -// Existe um shorthad para operações matemáticas em variáveis: +// Existe um shorthand para operações matemáticas em variáveis: someVar += 5; // equivalente a someVar = someVar + 5; someVar é 10 agora someVar *= 10; // agora someVar é 100 // e um para adição e subtração de 1 -someVar++; // now someVar is 101 -someVar--; // back to 100 +someVar++; // agora someVar é 101 +someVar--; // volta para 100 // Arrays são listas ordenadas de valores, de qualquer tipo. var myArray = ["Olá", 45, true]; -- cgit v1.2.3 From 2e987df42225e6bdf824584058467aaffc73fb49 Mon Sep 17 00:00:00 2001 From: Pushkar Sharma Date: Mon, 5 Oct 2015 00:52:47 +0530 Subject: replaced scanf with fscanf. --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 36621a9e..db2ac930 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -131,7 +131,7 @@ int main(void) { // time constant: printf("Enter the array size: "); // ask the user for an array size int size; - scanf("%d", &size); + fscanf(stdin, "%d", &size); char buf[size]; fgets(buf, sizeof buf, stdin); -- cgit v1.2.3 From d2fde6512424b754e0d45ac484d86472a99da3ef Mon Sep 17 00:00:00 2001 From: David Lima Date: Sun, 4 Oct 2015 16:30:42 -0300 Subject: Including '-pt' suffix on filename --- pt-br/hack-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown index 2f9d3c1b..7c938149 100644 --- a/pt-br/hack-pt.html.markdown +++ b/pt-br/hack-pt.html.markdown @@ -6,7 +6,7 @@ contributors: translators: - ["David Lima", "https://github.com/davelima"] lang: pt-br -filename: learnhack.hh +filename: learnhack-pt.hh --- Hack é uma linguagem baseada no PHP e roda numa máquina virtual chamada HHVM. -- cgit v1.2.3 From b1984042c845a73333972715e88a3d7a2e8cfdd7 Mon Sep 17 00:00:00 2001 From: Guntbert Reiter Date: Sun, 4 Oct 2015 16:44:24 +0200 Subject: Put demonstrative condition into ternary expression It should be made clear that the part before the ternary operator is indeed a condition, most often created as some comparison expression. --- de-de/csharp-de.html.markdown | 5 +++-- fr-fr/csharp-fr.html.markdown | 3 ++- tr-tr/csharp-tr.html.markdown | 3 ++- zh-cn/csharp-cn.html.markdown | 3 ++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown index dc77dda0..8ad7d71f 100644 --- a/de-de/csharp-de.html.markdown +++ b/de-de/csharp-de.html.markdown @@ -248,7 +248,8 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; // Ternärer Operator // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben: // ? : - string isTrue = true ? "Ja" : "Nein"; + int zumVergleich = 17; + string isTrue = zumVergleich == 17 ? "Ja" : "Nein"; // while-Schleife int fooWhile = 0; @@ -886,4 +887,4 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; * [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/de-de/library/vstudio/ff926074.aspx) \ No newline at end of file +[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx) diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index e51eacc8..58b3f386 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -239,7 +239,8 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Opérateur ternaire // Un simple if/else peut s'écrire : // ? : - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // Boucle while int fooWhile = 0; diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index a68026a5..91c7c269 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -234,7 +234,8 @@ on a new line! ""Wow!"", the masses cried"; // Üçlü operatörler // Basit bir if/else ifadesi şöyle yazılabilir // ? : - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // While döngüsü int fooWhile = 0; diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown index a3cda5b3..971c1be9 100644 --- a/zh-cn/csharp-cn.html.markdown +++ b/zh-cn/csharp-cn.html.markdown @@ -232,7 +232,8 @@ on a new line! ""Wow!"", the masses cried"; // 三元表达式 // 简单的 if/else 语句可以写成: // <条件> ? <真> : <假> - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // While 循环 int fooWhile = 0; -- cgit v1.2.3 From d8efd3ba3416669177683887b2822eb5d56c157b Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Mon, 5 Oct 2015 01:38:02 +0530 Subject: Modified as said to by a Collaborator --- java.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 2f41be81..89a710ee 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -477,9 +477,9 @@ public abstract class Animal age = 30; } - // No need to initialise, however in an interface + // No need to initialize, however in an interface // a variable is implicitly final and hence has - // to be initialised. + // to be initialized. private int age; public void printAge() @@ -509,7 +509,7 @@ class Dog extends Animal // @Override annotation here, since java doesn't allow // overriding of static methods. // What is happening here is called METHOD HIDING. - // Check out this awesome SO post: (http://stackoverflow.com/questions/16313649/) + // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ public static void main(String[] args) { Dog pluto = new Dog(); -- cgit v1.2.3 From e7a50adb78d4babdf77039ee58c59f5bc7d241c4 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 4 Oct 2015 22:44:34 +0200 Subject: Fix #1289 --- id-id/xml-id.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index 8e8cdf4e..c1e985aa 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -5,6 +5,7 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rizky Luthfianto", "https://github.com/rilut"] +lang: id-id --- XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. -- cgit v1.2.3 From 82bdd1b1c8c5eaa49289d9a683bf87ed85b99be9 Mon Sep 17 00:00:00 2001 From: VeerpalB Date: Sun, 4 Oct 2015 19:41:13 -0400 Subject: Add step parameter to range function A description of the step parameter of the range function is added. An example of its use in a for loop is also given. --- python3.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..4696ae1c 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -352,6 +352,18 @@ for i in range(4, 8): print(i) """ +"range(lower, upper, step)" returns an iterable of numbers +from the lower number to the upper number, while incrementing +by step. If step is not indicated, the default value is 1. +prints: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + While loops go until a condition is no longer met. prints: 0 -- cgit v1.2.3 From 52253720456acfef35cbbcf1ea1b3d98816c0961 Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Sun, 4 Oct 2015 19:58:14 -0400 Subject: Fixed whitespaces Fixed the spacing to conform with standards. --- python3.html.markdown | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index d70c5462..7b6edae7 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] filename: learnpython3.py --- @@ -158,7 +158,7 @@ print("I'm Python. Nice to meet you!") # By default the print function also prints out a newline at the end. # Use the optional argument end to change the end character. -print("I'm Python. Nice to meet you!", end="") +print("Hello, World", end="!") # => Hello, World! # No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores @@ -501,10 +501,9 @@ all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): - return y, x # Return multiple values as a tuple - # (Note: parenthesis have been excluded but can be included) -# return (y, x) # Just as valid as the above example. - + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) + x = 1 y = 2 x, y = swap(x, y) # => x = 2, y = 1 -- cgit v1.2.3 From a009095c2f408928e3c75ed64ff31094230f0827 Mon Sep 17 00:00:00 2001 From: connorshea Date: Sun, 4 Oct 2015 18:53:55 -0600 Subject: Added some Further Reading Links for CSS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit And changed CanIUse to “Can I Use…” --- css.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/css.html.markdown b/css.html.markdown index 7224d80a..e217906f 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] - ["Marco Scannadinari", "https://github.com/marcoms"] - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] filename: learncss.css --- @@ -238,10 +239,13 @@ of what you use in CSS with your target browsers. [QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. -To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. +To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource. ## Further Reading +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) * [QuirksMode CSS](http://www.quirksmode.org/css/) * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing -- cgit v1.2.3 From 0a3bdcd6a5864bdfb6641f883d3f3e2f4545548c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ale=20Mu=C3=B1oz?= Date: Mon, 5 Oct 2015 11:50:44 +0200 Subject: Fixed some typos --- es-es/git-es.html.markdown | 108 ++++++++++++++++++++++----------------------- 1 file changed, 53 insertions(+), 55 deletions(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 51812447..18b544b4 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -11,7 +11,7 @@ lang: es-es --- Git es un sistema de control de versiones distribuido diseñado para manejar -cualquier tipo de proyecto, ya sea largo o pequeño, con velocidad y eficiencia. +cualquier tipo de proyecto, ya sea grande o pequeño, con velocidad y eficiencia. Git realiza esto haciendo "snapshots" del proyecto, con ello permite versionar y administrar nuestro código fuente. @@ -36,8 +36,8 @@ uno o varios archivos, a lo largo del tiempo. ### Por qué usar Git? * Se puede trabajar sin conexion. -* Colaborar con otros es sencillo!. -* Derivar, Crear ramas del proyecto (aka: Branching) es fácil!. +* ¡Colaborar con otros es sencillo!. +* Derivar, crear ramas del proyecto (aka: Branching) es fácil. * Combinar (aka: Merging) * Git es rápido. * Git es flexible. @@ -48,7 +48,7 @@ uno o varios archivos, a lo largo del tiempo. Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: comits), y encabezados (aka: heads). Imagina que un repositorio es una clase, -y que sus atributos otorgan acceso al historial del elemento, además de otras +y que sus atributos otorgan acceso al historial del elemento, además de otras cosas. Un repositorio esta compuesto por la carpeta .git y un "árbol de trabajo". @@ -68,13 +68,13 @@ las veces se le llama "directorio de trabajo". ### Índice (componentes del directorio .git) El índice es el área de inicio en git. Es basicamente la capa que separa el -directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores -mas poder sobre lo que envía y recibe en el repositorio. +directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores +más poder sobre lo que se envía y se recibe del repositorio. ### Commit (aka: cambios) Un commit es una captura de un conjunto de cambios, o modificaciones hechas en -el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2, +el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se eliminan 2, estos cambios se almacenarán en un commit (aka: captura). Este commit puede ser o no ser enviado (aka: "pusheado") hacia un repositorio. @@ -84,7 +84,7 @@ Un "branch", es escencialmente un apuntador hacia el último commit (cambio registrado) que se ha realizado. A medida que se realizan más commits, este apuntador se actualizará automaticamente hacia el ultimo commit. -### "HEAD" y "head" (component of .git dir) +### "HEAD" y "head" (componentes del directorio .git) "HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a @@ -115,7 +115,7 @@ Se utiliza para configurar las opciones ya sea globalmente, o solamente en el repositorio. ```bash -# Imprime y guarda algunas variables de configuracion basicas. (Globalmente) +# Imprime y guarda algunas variables de configuracion básicas. (Globalmente) $ git config --global user.email $ git config --global user.name @@ -123,7 +123,7 @@ $ git config --global user.email "corre@gmail.com" $ git config --global user.name "nombre" ``` -[Mas sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git) +[Más sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git) ### help @@ -131,7 +131,7 @@ Otorga un accceso rápido a una guía extremadamente detallada de cada comando e git. O puede ser usada simplemente como un recordatorio de estos. ```bash -# Una vista rapido de los comandos disponibles. +# Una vista rápida de los comandos disponibles. $ git help # Chequear todos los comandos disponibles @@ -151,7 +151,7 @@ HEAD actualmente. ```bash -# Mostrara el "branch", archivos sin añadir a la repo, cambios y otras +# Mostrará el "branch", archivos sin añadir al repo, cambios y otras # diferencias $ git status @@ -161,8 +161,8 @@ $ git help status ### add -Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se -utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por +Para añadir archivos al árbol (directorio, repositorio) de trabajo. Si no se +utiliza `git add`, los nuevos archivos no se añadirán al arbol de trabajo, por lo que no se incluirán en los commits (cambios). ```bash @@ -178,24 +178,24 @@ $ git add ./*.py ### branch -Administra las ramas del repositorios ("branches"). Puedes ver, editar, crear y +Administra las ramas del repositorio ("branches"). Puedes ver, editar, crear y borrar ramas ("branches"), usando este comando. ```bash # lista todas las ramas (remotas y locales) $ git branch -a -# Añada una nueva rama ("branch"). +# Añadir una nueva rama ("branch"). $ git branch branchNueva # Eliminar una rama. $ git branch -d branchFoo -# Renombra una rama. +# Renombrar una rama. # git branch -m $ git branch -m youngling padawan -# Edita la descripcion de la rama. +# Editar la descripcion de la rama. $ git branch master --edit-description ``` @@ -230,7 +230,6 @@ Almacena el contenido actual del índice en un nuevo "commit". Este commit contiene los cambios hechos más un resumen proporcionado por el desarrollador. ```bash -# commit with a message # realizar un commit y añadirle un mensaje. $ git commit -m "jedi anakin wil be - jedis.list" ``` @@ -241,13 +240,13 @@ Muestra las diferencias entre un archivo en el directorio de trabajo, el índice y los commits. ```bash -# Muestra la diferencia entre un directorio de trabajo y el indice. +# Muestra la diferencia entre un directorio de trabajo y el índice. $ git diff -# Muestra la diferencia entre el indice y los commits mas recientes. +# Muestra la diferencia entre el índice y los commits más recientes. $ git diff --cached -# Muestra la diferencia entre el directorio de trabajo y el commit mas reciente. +# Muestra la diferencia entre el directorio de trabajo y el commit más reciente. $ git diff HEAD ``` @@ -255,31 +254,32 @@ $ git diff HEAD Permite realizar una busqueda rápida en un repositorio. -Configuracion opcionales: +Configuraciones opcionales: ```bash # Gracias a Travis Jeffery por compartir lo siguiente. # Permite mostrar numeros de lineas en la salida de grep. $ git config --global grep.lineNumber true -# Realiza una busqueda mas lejible, incluyendo agrupacion. +# Realiza una búsqueda mas legible, incluyendo agrupación. $ git config --global alias.g "grep --break --heading --line-number" ``` ```bash -# Busca por "unaVariable" en todos los archivos ,java +# Busca por "unaVariable" en todos los archivos .java $ git grep 'unaVariable' -- '*.java' -# Busca por una linea que contenga "nombreArreglo" y , "agregar" o "remover" +# Busca por una línea que contenga "nombreArreglo" y "agregar" o "remover" $ git grep -e 'nombreArreglo' --and \( -e agregar -e remover \) ``` -Mas ejemplos: -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) +Más ejemplos: + +- [Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) ### log -Muestra los commits (cambios) registrados en el repositotrio. +Muestra los commits (cambios) registrados en el repositorio. ```bash # Muestra todos los commits. @@ -288,7 +288,7 @@ $ git log # Muestra un numero x de commits. $ git log -n 10 -# Muestra solo los commits que se han combinado en el hisotrial +# Muestra solo los commits que se han combinado en el historial. $ git log --merges ``` @@ -301,7 +301,7 @@ que se trabaja. # Combina la rama especificada en la rama actual. $ git merge jediMaster -# Siempre genere un solo merge commit cuando se utilizar merge. +# Siempre genere un solo merge commit cuando se utiliza merge. $ git merge --no-ff jediMaster ``` @@ -310,7 +310,7 @@ $ git merge --no-ff jediMaster Renombra o mueve un archivo ```bash -# Renombrando un archivo +# Renombrando un archivo. $ git mv HolaMundo.c AdiosMundo.c # Moviendo un archivo. @@ -322,33 +322,31 @@ $ git mv -f archivoA archivoB ### pull -Sube (Empuja) de un repositorio y lo combina en otro en una rama diferente. +Trae los cambios de un repositorio y los combina en otro en una rama diferente. ```bash -# Actualiza el repositorio local, combinando los nuevos cambios. +# Actualiza el repositorio local, combinando los nuevos cambios # de las ramas remotas "origin" y "master". -# from the remote "origin" and "master" branch. # git pull $ git pull origin master ``` ### push -Push and merge changes from a branch to a remote & branch. +Envía y combina los cambios de un repositorio local a un repositorio y rama remotos. ```bash -# Push and merge changes from a local repo to a -# Empuja y combina cambios de un repositorio local hacian un repositorio remoto +# Envía y combina cambios de un repositorio local hacia un repositorio remoto # llamados "origin" y "master", respectivamente. # git push # git push => por defecto es lo mismo que poner => git push origin master $ git push origin master ``` +### rebase Toma todos los cambios que fueron registrados en una rama, y los repite dentro -de otra rama. -*No reescribe los commits que se han empujado antes a un repositorio publico* +de otra rama. *No reescribe los commits que se han empujado antes a un repositorio público.* ```bash # Integrar ramaExperimento dentro de la rama "master" @@ -356,47 +354,47 @@ de otra rama. $ git rebase master experimentBranch ``` -[Informacion adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar) +[Información adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar) -### reset (precaucion) +### reset (precaución) -Reinicia el cabezal actual hacia un estado especificado. Esto permite desacer -combinaciones (merges), pulls, commits, adds y mas. Es un comando util, pero -tambien peligrosa si no se sabe lo que se hace. +Reinicia el HEAD actual hacia un estado especificado. Esto permite deshacer +combinaciones (merges), pulls, commits, adds y más. Es un comando útil, pero +tambien peligroso si no se sabe lo que se hace. ```bash -# Reinica el area principal, con el ultimo cambio registrado. (deja los +# Reinicia el área principal, con el último cambio registrado. (deja los # directorios sin cambios) $ git reset -# Reinica el area principal, con el ultimo cambio registrado, y reescribe el +# Reinicia el área principal, con el último cambio registrado, y reescribe el # directorio de trabajo. $ git reset --hard # Mueve la rama actual hacia el commit especificado (no realiza cambios a los -# directorios), todos los cambios aun existen el directorio. +# directorios), todos los cambios aún existen el directorio. $ git reset 31f2bb1 -# Mueve la rama actual devuelta a un commit especificado asi como el -# directorios (borra todos los cambios que no fueron registros y todos los -# cambios realizados despues del commit especificado). +# Mueve la rama actual devuelta a un commit especificado, así como el +# directorio (borra todos los cambios que no fueron registrados y todos los +# cambios realizados después del commit especificado). $ git reset --hard 31f2bb1 ``` ### rm -Lo contrario de git add, git rm remueve los archivos del directorio de trabajo +Lo contrario de git add, git rm elimina los archivos del directorio de trabajo actual. ```bash -# Remueve FooBar.c +# Elimina FooBar.c $ git rm FooBar.c -# Remueve un archivo de un directorio. +# Elimina un archivo de un directorio. $ git rm /directorio/del/archivo/FooBar.c ``` -## Informacion Adicional +## Información Adicional * [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1) -- cgit v1.2.3 From 142d33340aec0e3d85154a4feeb958f722693023 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 15:31:46 +0530 Subject: Update ruby-ru.html.markdown --- ru-ru/ruby-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index 318e0e09..69b5fb46 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -158,6 +158,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6] hash = {'color' => 'green', 'number' => 5} hash.keys #=> ['color', 'number'] +hash.values #=> ['green', 5] # Значение в хэше легко может быть найдено по ключу: hash['color'] #=> 'green' -- cgit v1.2.3 From 41d49490ba093a74d0d691538b8342682feb997f Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 15:46:46 +0530 Subject: Update python-ru.html.markdown --- ru-ru/python-ru.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index a0e2b474..162675bb 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -238,6 +238,15 @@ d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных e, d = d, e # теперь d == 5, а e == 4 +#take input of integers in a single line +#if input 1 2 3 +input = map(int,raw_input().split()) #integer + +input #=>[1, 2, 3] + +input = map(str,raw_input().split()) #string + +input #=>['1', '2', '3'] # Словари содержат ассоциативные массивы empty_dict = {} -- cgit v1.2.3 From dca1300e57600f6707d3aa3778a24d9b1626b9b9 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 17:33:38 +0530 Subject: Update python-ru.html.markdown --- ru-ru/python-ru.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 162675bb..ec4fff41 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -238,13 +238,13 @@ d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных e, d = d, e # теперь d == 5, а e == 4 -#take input of integers in a single line -#if input 1 2 3 -input = map(int,raw_input().split()) #integer +#принять ввод чисел в одной строке +#если вход 1 2 3 +input = map(int,raw_input().split()) #целое число input #=>[1, 2, 3] -input = map(str,raw_input().split()) #string +input = map(str,raw_input().split()) #строка input #=>['1', '2', '3'] -- cgit v1.2.3 From cae1960ca3a5c25d8db458234ac0a6e97ab87ed5 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 17:51:23 +0530 Subject: Reverse an array --- ruby.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 7bd28d86..4e8dcc8f 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -168,6 +168,10 @@ array[-1] #=> 5 # With a start index and length array[2, 3] #=> [3, 4, 5] +# Reverse an Array +# array = [1,2,3] +array.reverse #=> [3,2,1] + # Or with a range array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From 51e3bd21e29ac19884eca57c6f4f1defbd78ea3a Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 20:22:07 +0530 Subject: Reverse a list --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 4e8dcc8f..b6d0e44d 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -169,8 +169,8 @@ array[-1] #=> 5 array[2, 3] #=> [3, 4, 5] # Reverse an Array -# array = [1,2,3] -array.reverse #=> [3,2,1] +a=[1,2,3] +a[::-1] #=> [3,2,1] # Or with a range array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From 0beb78ac436d232ce73986848f354fc4e7210dfb Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 20:32:00 +0530 Subject: Reverse an array --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index b6d0e44d..8f23b2e6 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -170,7 +170,7 @@ array[2, 3] #=> [3, 4, 5] # Reverse an Array a=[1,2,3] -a[::-1] #=> [3,2,1] +a.reverse! #=> [3,2,1] # Or with a range array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From e1abb317dd2526a7352b59c20f9cd37c1a369f55 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Mon, 5 Oct 2015 20:44:43 +0530 Subject: String to list characters --- ru-ru/python-ru.html.markdown | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index ec4fff41..699d1393 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -167,6 +167,10 @@ li = [] # Можно сразу начать с заполненного списка other_li = [4, 5, 6] +#Строка в список +a="adambard" +list(a) #=> ['a','d','a','m','b','a','r','d'] + # Объекты добавляются в конец списка методом append li.append(1) # [1] li.append(2) # [1, 2] @@ -238,16 +242,6 @@ d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных e, d = d, e # теперь d == 5, а e == 4 -#принять ввод чисел в одной строке -#если вход 1 2 3 -input = map(int,raw_input().split()) #целое число - -input #=>[1, 2, 3] - -input = map(str,raw_input().split()) #строка - -input #=>['1', '2', '3'] - # Словари содержат ассоциативные массивы empty_dict = {} # Вот так описывается предзаполненный словарь -- cgit v1.2.3 From 62c6f95e9d161967cfffa43a3f9b3f8d73e2ef5f Mon Sep 17 00:00:00 2001 From: Sean Corrales Date: Mon, 5 Oct 2015 10:51:27 -0500 Subject: Initial work on learn Sass file. --- sass.html.markdown | 234 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 sass.html.markdown diff --git a/sass.html.markdown b/sass.html.markdown new file mode 100644 index 00000000..35af1e67 --- /dev/null +++ b/sass.html.markdown @@ -0,0 +1,234 @@ +--- +language: sass +contributors: + - ["Sean Corrales", "https://github.com/droidenator"] +filename: learnsass.scss +--- + +Sass is a CSS pre-processor. It adds several features that plain +CSS lacks such as variables, mixins, basic math, and inheritance. + +Initially, Sass was written using spacing and indention instead +of brackets and semi-colons; these files use the extension '.sass'. +Sass was later revised to use brackets and semi-colons and become +a superset of CSS3. This new version uses the extension ".scss". +Using ".scss" means that any valid CSS3 file can be converted to +Sass by simply changing the file extension to '.scss'. + +If you're already familiar with CSS3, you'll be able to pick up Sass +relatively quickly. It does not provide any new styling options but rather +the tools to write your CSS more efficiently and make maintenance much +easier. + +Sass files must be compiled into CSS. You can use any number of commandline +tools to compile Sass into CSS. Many IDEs also offer Sass compilation, as well. + + +```sass +/* Like CSS, Sass uses slash-asterisk to denote comments */ + +/* #################### + ## VARIABLES + #################### */ + +/* Sass allows you to define variables that can be used throughout + your stylesheets. Variables are defined by placing a '$' in front + of a string. Many users like to keep their variables in a single file */ +$primary-color: #0000ff; +$headline-size: 24px; + +/* Variables can be used in any CSS declaration. This allows you to change + a single value in one place. */ +a { + color: $primary-color; +} + +h1 { + color: $primary-color; + font-size: $headline-size; +} + +/* After compiling the Sass files into CSS, you'll have the following code + in your generated CSS file */ + +a { + color: #0000ff; +} + +h1 { + color: #0000ff; + font-size: 24px; +} + +/* #################### + ## NESTING + #################### */ + +/* Nesting allows you to easily group together statements and nest them + in a way that indicates their hierarchy */ +article { + font-size: 14px; + + a { + text-decoration: underline; + } + + ul { + list-style-type: disc; + + li { + text-indent: 3em; + } + } + + pre, img { + display: inline-block; + float: left; + } +} + +/* The above will compile into the following CSS */ +article { + font-size: 14px; +} + +article a { + text-decoration: underline; +} + +article ul { + list-style-type: disc; +} + +article ul li { + text-indent: 3em; +} + +article pre, +article img { + display: inline-block; + float: left; +} + +/* It is recommended to not nest too deeply as this can cause issues with + specificity and make your CSS harder to work with and maintain. Best practices + recommend going no more than 3 levels deep when nesting. */ + +/* #################### + ## MIXINS + #################### */ +/* Mixins allow you to define reusable chunks of CSS. They can take one or more + arguments to allow you to make reusable pieces of styling. */ +@mixin form-button($color, $size, $border-radius) { + color: $color; + font-size: $size; + border-radius: $border-radius; +} + +/* Mixins are invoked within a CSS declaration. */ +.user-form .submit { + @include form-button(#0000ff, 16px, 4px); + margin: 10px; +} + +/* The above mixin will compile into the following css */ +.user-form .submit { + color: #0000ff; + font-size: 16px; + border-radius: 4px; + margin: 10px; +} + +/* #################### + ## EXTEND/INHERITANCE + #################### */ + +/* #################### + ## MATH OPERATIONS + #################### */ + +``` + +## Usage + +Save any CSS you want in a file with extension `.css`. + +```xml + + + + + + + +
+
+ +``` + +## Precedence + +As you noticed an element may be targetted by more than one selector. +and may have a property set on it in more than one. +In these cases, one of the rules takes precedence over others. + +Given the following CSS: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +and the following markup: + +```xml +

+

+``` + +The precedence of style is as followed: +Remember, the precedence is for each **property**, not for the entire block. + +* `E` has the highest precedence because of the keyword `!important`. + It is recommended to avoid this unless it is strictly necessary to use. +* `F` is next, because it is inline style. +* `A` is next, because it is more "specific" than anything else. + more specific = more specifiers. here 3 specifiers: 1 tagname `p` + + class name `class1` + 1 attribute `attr='value'` +* `C` is next. although it has the same specificness as `B` + but it appears last. +* Then is `B` +* and lastly is `D`. + +## Compatibility + +Most of the features in CSS2 (and gradually in CSS3) are compatible across +all browsers and devices. But it's always vital to have in mind the compatibility +of what you use in CSS with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. + +To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. + +## Further Reading + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -- cgit v1.2.3 From 1d43bd50c3e9305abfe95eade590ef5828f9ad5c Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 12:29:08 -0400 Subject: Initial placeholder --- coldfusion.html.markdown | 1 + 1 file changed, 1 insertion(+) create mode 100644 coldfusion.html.markdown diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown new file mode 100644 index 00000000..3c0b0b06 --- /dev/null +++ b/coldfusion.html.markdown @@ -0,0 +1 @@ +Coming soon -- cgit v1.2.3 From 8b456426407997fdbb8a0befb4181a513e585231 Mon Sep 17 00:00:00 2001 From: Per Lilja Date: Mon, 5 Oct 2015 20:29:05 +0200 Subject: Added description for Double Brace Initialization --- java.html.markdown | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index e4234a39..b4757962 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -325,6 +325,33 @@ public class LearnJava { // toString returns this Object's string representation. System.out.println("trek info: " + trek.toString()); + + // Double Brace Initialization + // The Java Language has no syntax for how to create static Collections + // in an easy way. Usually you end up in the following way: + + private static final Set COUNTRIES = new HashSet(); + static { + validCodes.add("DENMARK"); + validCodes.add("SWEDEN"); + validCodes.add("FINLAND"); + } + + // But there's a nifty way to achive the same thing in an + // easier way, buy using something that is called Double Brace + // Initialization. + + private static final Set COUNTRIES = HashSet() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // The first brace is creating an new AnonymousInnerClass and the + // second one declares and instance initializer block. This block + // is called with the anonymous inner class is created. + // This does not only work for Collections, it works for all + // non-final classes. } // End main method } // End LearnJava class -- cgit v1.2.3 From 1bc457737577a01af47a8be5879904dd23bcc410 Mon Sep 17 00:00:00 2001 From: Sean Corrales Date: Mon, 5 Oct 2015 13:52:53 -0500 Subject: Finishing up documentation for additional Sass functionality. Removing CSS specific instructions from usage, compatibility, and further reading sections. --- sass.html.markdown | 300 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 232 insertions(+), 68 deletions(-) diff --git a/sass.html.markdown b/sass.html.markdown index 35af1e67..d1e0721f 100644 --- a/sass.html.markdown +++ b/sass.html.markdown @@ -25,7 +25,11 @@ tools to compile Sass into CSS. Many IDEs also offer Sass compilation, as well. ```sass -/* Like CSS, Sass uses slash-asterisk to denote comments */ +/* Like CSS, Sass uses slash-asterisk to denote comments. Slash-asterisk comments + can span multiple lines. These comments will appear in your compiled CSS */ + +// Sass also supports single line comments that use double slashes. These comments will +// not be rendered in your compiled CSS /* #################### ## VARIABLES @@ -113,12 +117,52 @@ article img { /* It is recommended to not nest too deeply as this can cause issues with specificity and make your CSS harder to work with and maintain. Best practices recommend going no more than 3 levels deep when nesting. */ + +/* ############################### + ## REFERENCE PARENT SELECTORS + ############################### */ + +/* Reference parent selectors are used when you're nesting statements and want to + reference the parent selector from within the nested statements. You can reference + a parent using & */ + +a { + text-decoration: none; + color: #ff0000; + + &:hover { + text-decoration: underline; + } + + body.noLinks & { + display: none; + } +} + +/* The above Sass will compile into the CSS below */ + +a { + text-decoration: none; + color: #ff0000; +} + +a:hover { + text-decoration: underline; +} + +body.noLinks a { + display: none; +} + /* #################### ## MIXINS #################### */ + /* Mixins allow you to define reusable chunks of CSS. They can take one or more - arguments to allow you to make reusable pieces of styling. */ + arguments to allow you to make reusable pieces of styling. Mixins can also + be very helpful when dealing with vendor prefixes. */ + @mixin form-button($color, $size, $border-radius) { color: $color; font-size: $size; @@ -126,109 +170,229 @@ article img { } /* Mixins are invoked within a CSS declaration. */ + .user-form .submit { @include form-button(#0000ff, 16px, 4px); - margin: 10px; } /* The above mixin will compile into the following css */ + .user-form .submit { color: #0000ff; font-size: 16px; border-radius: 4px; - margin: 10px; } /* #################### - ## EXTEND/INHERITANCE + ## FUNCTIONS #################### */ - + +/* Sass provides functions that can be used to accomplish a variety of tasks. Consider the following */ + +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* The above Sass will compile into the following CSS */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* You may also define your own functions. Functions are very similar to mixins. When trying to choose between + a function or a mixin, remember that functions are best for returning values while mixins are best for + generating CSS while functions are better for logic that might be used throughout your Sass code. The + examples in the Math Operators' section are ideal candidates for becoming a reusable function. */ + +/* This function will take a target size and the parent size and calculate and return the percentage */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +/* Functions can be invoked by using their name and passing in the required arguments */ + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* The above Sass will compile into the following CSS */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + /* #################### - ## MATH OPERATIONS - #################### */ + ## EXTEND/INHERITANCE + #################### */ -``` +/* Sass allows you to extend an existing CSS statement. This makes it + very easy to write CSS that does not violate DRY principles. Any + CSS statement can be extended */ + +.content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} -## Usage +.message-window { + @extend .content-window; + background-color: #0000ff; +} -Save any CSS you want in a file with extension `.css`. +.notification-window { + @extend .content-window; + background-color: #ff0000; +} -```xml - - +.settings-window { + @extend .content-window; + background-color: #ccc; +} - - +/* The above Sass will be compile into the following CSS */ - -
-
+.content-window, +.message-window, +.notification-window, +.settings-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} -``` +.message-window { + background-color: #0000ff; +} + +.notification-window { + background-color: #ff0000; +} + +.settings-window { + background-color: #ccc; +} + +/* Extending a CSS statement is preferable to creating a mixin + because of the way it groups together the classes that all share + the same base styling. If this was done with a mixin, the font-size, + padding, color, and border-radius would be duplicated for each statement + that called the mixin. While it won't affect your workflow, it will + add unnecessary bloat to the files created by the Sass compiler. */ + +/* ######################### + ## PLACEHOLDER SELECTORS + ######################### */ + +/* Placeholders are useful when creating a CSS statement to extend. If you wanted to create + a CSS statement that was exclusively used with @extend, you can do so using a placeholder. + Placeholders begin with a '%' instead of '.' or '#'. Placeholders will not appear in the + compiled CSS. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} -## Precedence +/* The above Sass would compile to the following CSS */ -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. -In these cases, one of the rules takes precedence over others. +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} -Given the following CSS: +.message-window { + background-color: #0000ff; +} + +/* #################### + ## MATH OPERATIONS + #################### */ + +/* Sass provides the following operators: +, -, *, /, and %. These can + be useful for calculating values directly in your Sass files instead + of using values that you've already calculated by hand. Below is an example + of a setting up a simple two column design. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; -```css -/*A*/ -p.class1[attr='value'] +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); -/*B*/ -p.class1 {} +body { + width: 100%; +} -/*C*/ -p.class2 {} +.main-content { + width: $main-size; +} -/*D*/ -p {} +.sidebar { + width: $sidebar-size; +} -/*E*/ -p { property: value !important; } +.gutter { + width: $gutter; +} -``` +/* The above Sass would compile to the CSS below */ -and the following markup: +body { + width: 100%; +} -```xml -

-

-``` +.main-content { + width: 62.5%; +} -The precedence of style is as followed: -Remember, the precedence is for each **property**, not for the entire block. +.sidebar { + width: 31.25%; +} -* `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. -* `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` - but it appears last. -* Then is `B` -* and lastly is `D`. +.gutter { + width: 6.25%; +} + +``` -## Compatibility +## Usage -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatibility -of what you use in CSS with your target browsers. -[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. -To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. +## Compatibility -## Further Reading -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) -* [QuirksMode CSS](http://www.quirksmode.org/css/) -* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +## Further Reading -- cgit v1.2.3 From 6611db502aafc9768254efb45495a9fb20a79c81 Mon Sep 17 00:00:00 2001 From: Ayush Date: Tue, 6 Oct 2015 00:44:05 +0530 Subject: Git: removed some clutter --- git.html.markdown | 68 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index bf8fce0c..3b83218c 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -8,17 +8,17 @@ contributors: filename: LearnGit.txt --- -Git is a distributed version control and source code management system. +Git is a distributed version control and source code management system. -It does this through a series of snapshots of your project, and it works -with those snapshots to provide you with functionality to version and +It does this through a series of snapshots of your project, and it works +with those snapshots to provide you with functionality to version and manage your source code. ## Versioning Concepts ### What is version control? -Version control is a system that records changes to a file, or set of files, over time. +Version control is a system that records changes to a file(s), over time. ### Centralized Versioning VS Distributed Versioning @@ -42,8 +42,9 @@ Version control is a system that records changes to a file, or set of files, ove ### Repository -A set of files, directories, historical records, commits, and heads. Imagine it as a source code data structure, -with the attribute that each source code "element" gives you access to its revision history, among other things. +A set of files, directories, historical records, commits, and heads. Imagine it +as a source code data structure, with the attribute that each source code +"element" gives you access to its revision history, among other things. A git repository is comprised of the .git directory & working tree. @@ -54,32 +55,33 @@ The .git directory contains all the configurations, logs, branches, HEAD, and mo ### Working Tree (component of repository) -This is basically the directories and files in your repository. It is often referred to -as your working directory. +This is basically the directories and files in your repository. It is often +referred to as your working directory. ### Index (component of .git dir) The Index is the staging area in git. It's basically a layer that separates your working tree -from the Git repository. This gives developers more power over what gets sent to the Git -repository. +from the Git repository. This gives developers more power over what gets sent +to the Git repository. ### Commit -A git commit is a snapshot of a set of changes, or manipulations to your Working Tree. -For example, if you added 5 files, and removed 2 others, these changes will be contained -in a commit (or snapshot). This commit can then be pushed to other repositories, or not! +A git commit is a snapshot of a set of changes, or manipulations to your Working +Tree. For example, if you added 5 files, and removed 2 others, these changes +will be contained in a commit (or snapshot). This commit can then be pushed to +other repositories, or not! ### Branch -A branch is essentially a pointer that points to the last commit you made. As you commit, -this pointer will automatically update and point to the latest commit. +A branch is essentially a pointer to the last commit you made. As you go on +committing, this pointer will automatically update to ooint the latest commit. ### HEAD and head (component of .git dir) HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. head is a pointer that points to any commit. A repository can have any number of heads. -###Stages of Git +### Stages of Git * Modified - Changes have been made to a file but file has not been committed to Git Database yet * Staged - Marks a modified file to go into your next commit snapshot * Committed - Files have been committed to the Git Database @@ -95,7 +97,7 @@ head is a pointer that points to any commit. A repository can have any number of ### init -Create an empty Git repository. The Git repository's settings, stored information, +Create an empty Git repository. The Git repository's settings, stored information, and more is stored in a directory (a folder) named ".git". ```bash @@ -144,8 +146,8 @@ $ git init --help ### status -To show differences between the index file (basically your working copy/repo) and the current -HEAD commit. +To show differences between the index file (basically your working copy/repo) +and the current HEAD commit. ```bash @@ -172,7 +174,8 @@ $ git add /path/to/file/HelloWorld.c $ git add ./*.java ``` -This only adds a file to the staging area/index, it doesn't commit it to the working directory/repo. +This only adds a file to the staging area/index, it doesn't commit it to the +working directory/repo. ### branch @@ -205,7 +208,8 @@ Updates all files in the working tree to match the version in the index, or spec $ git checkout # Checkout a specified branch $ git checkout branchName -# Create a new branch & switch to it, like: "git branch ; git checkout " +# Create a new branch & switch to it +# equivalent to "git branch ; git checkout " $ git checkout -b newBranch ``` @@ -268,7 +272,7 @@ $ git config --global alias.g "grep --break --heading --line-number" $ git grep 'variableName' -- '*.java' # Search for a line that contains "arrayListName" and, "add" or "remove" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) +$ git grep -e 'arrayListName' --and \( -e add -e remove \) ``` Google is your friend; for more examples @@ -303,7 +307,7 @@ $ git merge --no-ff branchName ### mv -Rename or move a file +Rename or move a file ```bash # Renaming a file @@ -338,7 +342,7 @@ $ git pull origin master --rebase Push and merge changes from a branch to a remote & branch. ```bash -# Push and merge changes from a local repo to a +# Push and merge changes from a local repo to a # remote named "origin" and "master" branch. # git push # git push => implicitly defaults to => git push origin master @@ -347,23 +351,25 @@ $ git push origin master # To link up current local branch with a remote branch, add -u flag: $ git push -u origin master # Now, anytime you want to push from that same local branch, use shortcut: -$ git push +$ git push ``` ### stash -Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time. +Stashing takes the dirty state of your working directory and saves it on a stack +of unfinished changes that you can reapply at any time. -Let's say you've been doing some work in your git repo, but you want to pull from the remote. -Since you have dirty (uncommited) changes to some files, you are not able to run `git pull`. -Instead, you can run `git stash` to save your changes onto a stack! +Let's say you've been doing some work in your git repo, but you want to pull +from the remote. Since you have dirty (uncommited) changes to some files, you +are not able to run `git pull`. Instead, you can run `git stash` to save your +changes onto a stack! ```bash $ git stash Saved working directory and index state \ "WIP on master: 049d078 added the index file" HEAD is now at 049d078 added the index file - (To restore them type "git stash apply") + (To restore them type "git stash apply") ``` Now you can pull! @@ -410,7 +416,7 @@ Now you're ready to get back to work on your stuff! [Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) -### rebase (caution) +### rebase (caution) Take all changes that were committed on one branch, and replay them onto another branch. *Do not rebase commits that you have pushed to a public repo*. -- cgit v1.2.3 From 7b7ce666b66e897c115879d505104330923919ec Mon Sep 17 00:00:00 2001 From: Ayush Date: Tue, 6 Oct 2015 00:45:40 +0530 Subject: Git: added para for gitignore --- git.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 3b83218c..c32d9c5d 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -144,6 +144,16 @@ $ git commit --help $ git init --help ``` +### ignore (set of) files + +To intentionally untrack file(s) & folder(s) from git. Typically meant for +private & temp files which would otherwise be shared in the repository. +```bash +$ echo "temp/" >> .gitignore +$ echo "private_key" >> .gitignore +``` + + ### status To show differences between the index file (basically your working copy/repo) -- cgit v1.2.3 From 037ff22ef63c5f37b6657e806695bb52f46a7ec3 Mon Sep 17 00:00:00 2001 From: Ayush Date: Tue, 6 Oct 2015 00:46:53 +0530 Subject: Git: added more clone options --- git.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index c32d9c5d..66b890c1 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -232,6 +232,10 @@ to a remote branch. ```bash # Clone learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git +# shallow clone - faster cloning that pulls only latest snapshot +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git +# clone only a specific branch +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch ``` ### commit -- cgit v1.2.3 From e75a9e031bde60fae2c1972b5f6b18571acd4d99 Mon Sep 17 00:00:00 2001 From: Ayush Date: Tue, 6 Oct 2015 00:56:08 +0530 Subject: Git: added few random things --- git.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index 66b890c1..e20a4b88 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -106,15 +106,12 @@ $ git init ### config -To configure settings. Whether it be for the repository, the system itself, or global -configurations. +To configure settings. Whether it be for the repository, the system itself, +or global configurations ( global config file is `~/.gitconfig` ). ```bash # Print & Set Some Basic Config Variables (Global) -$ git config --global user.email -$ git config --global user.name - $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" ``` @@ -249,6 +246,9 @@ $ git commit -m "Added multiplyNumbers() function to HelloWorld.c" # automatically stage modified or deleted files, except new files, and then commit $ git commit -a -m "Modified foo.php and removed bar.php" + +# change last commit (this deletes previous commit with a fresh commit) +$ git commit --amend -m "Correct message" ``` ### diff @@ -300,8 +300,8 @@ Display commits to the repository. # Show all commits $ git log -# Show X number of commits -$ git log -n 10 +# Show only commit message & ref +$ git log --oneline # Show merge commits only $ git log --merges -- cgit v1.2.3 From ab2ef777e2c73699a864e5c4869b285f3443c3f4 Mon Sep 17 00:00:00 2001 From: Rodrigo Muniz Date: Mon, 5 Oct 2015 16:34:58 -0300 Subject: Corrigidos erros de ortografia --- pt-br/brainfuck-pt.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown index c7ce55ee..9e4b458d 100644 --- a/pt-br/brainfuck-pt.html.markdown +++ b/pt-br/brainfuck-pt.html.markdown @@ -5,10 +5,11 @@ contributors: - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Rodrigo Muniz", "http://github.com/muniz95"] lang: pt-br --- -Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de +Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de programação Turing-completa extremamente simples com apenas 8 comandos. ``` @@ -18,7 +19,7 @@ Brainfuck é representado por um vetor com 30 000 células inicializadas em zero e um ponteiro de dados que aponta para a célula atual. Existem 8 comandos: -+ : Incrementa o vaor da célula atual em 1. ++ : Incrementa o valor da célula atual em 1. - : Decrementa o valor da célula atual em 1. > : Move o ponteiro de dados para a célula seguinte (célula à direita). < : Move o ponteiro de dados para a célula anterior (célula à esquerda). -- cgit v1.2.3 From 9e605ee35ced12a77f0c0c666c0019d40eaaeea6 Mon Sep 17 00:00:00 2001 From: Ayush Date: Tue, 6 Oct 2015 01:06:15 +0530 Subject: Git: fixed typo --- git.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index e20a4b88..b1347309 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -74,7 +74,7 @@ other repositories, or not! ### Branch A branch is essentially a pointer to the last commit you made. As you go on -committing, this pointer will automatically update to ooint the latest commit. +committing, this pointer will automatically update to point the latest commit. ### HEAD and head (component of .git dir) @@ -141,7 +141,7 @@ $ git commit --help $ git init --help ``` -### ignore (set of) files +### ignore files To intentionally untrack file(s) & folder(s) from git. Typically meant for private & temp files which would otherwise be shared in the repository. -- cgit v1.2.3 From e848adf9d53e8af5863497438753d704d30f7c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerson=20L=C3=A1zaro?= Date: Mon, 5 Oct 2015 15:20:35 -0500 Subject: Fix for issue #1248 [fa-ir, zh-cn, ko-kr, es-es, ru-ru, fr-fr, de-de] --- de-de/javascript-de.html.markdown | 3 --- es-es/javascript-es.html.markdown | 3 --- fa-ir/javascript.html.markdown | 3 --- fr-fr/javascript-fr.html.markdown | 3 --- ko-kr/javascript-kr.html.markdown | 3 --- ru-ru/javascript-ru.html.markdown | 3 --- zh-cn/javascript-cn.html.markdown | 3 --- 7 files changed, 21 deletions(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index a295c1c2..f3917506 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -479,9 +479,6 @@ myNumber === myNumberObj; // = false if (0){ // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist. } -if (Number(0)){ - // Dieser Teil des Codes wird ausgeführt, weil Number(0) zu wahr evaluiert. -} // Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen // Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index fd01e7b9..036d7082 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -478,9 +478,6 @@ miNumero === miNumeroObjeyo; // = false if (0){ // Este código no se ejecutara porque 0 es false. } -if (Number(0)){ - // Este código sí se ejecutara, puesto que Number(0) es true. -} // Aún así, los objetos que envuelven y los prototipos por defecto comparten // un prototipo. así que puedes agregar funcionalidades a un string de la diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown index 5c64d24a..fe3555af 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript.html.markdown @@ -499,9 +499,6 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } -if (Number(0)){ - // This code *will* execute, because Number(0) is truthy. -} ``` diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 2e18d0be..15478cdb 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -469,9 +469,6 @@ myNumber === myNumberObj; // = false if (0){ // 0 est falsy, le code ne fonctionnera pas. } -if (Number(0)){ - // Parce que Number(0) est truthy, le code fonctionnera -} // Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à // cette particularité. diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 4ca3bb5c..9561e80c 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -387,9 +387,6 @@ myNumber === myNumberObj // = false if (0){ // 0은 거짓이라서 이 코드는 실행되지 않습니다. } -if (Number(0)){ - // Number(0)은 참이라서 이 코드는 *실행됩니다*. -} // 하지만 래퍼 객체와 일반 내장 함수는 프로토타입을 공유하기 때문에 // 가령 문자열에 실제로 기능을 추가할 수 있습니다. diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 79844565..8655ae4a 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -470,9 +470,6 @@ myNumber === myNumberObj; // = false if (0) { // Этот код не выполнится, потому что 0 - это ложь. } -if (Number(0)) { - // Этот код *выполнится*, потому что Number(0) истинно. -} // Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы, // поэтому вы можете расширить функционал строк, например: diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index dfeb2012..bdef0099 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -447,9 +447,6 @@ myNumber === myNumberObj; // = false if (0){ // 这段代码不会执行,因为0代表假 } -if (Number(0)){ - // 这段代码*会*执行,因为Number(0)代表真 -} // 不过,包装类型和内置类型共享一个原型, // 所以你实际可以给内置类型也增加一些功能,例如对string: -- cgit v1.2.3 From 9d33f091701013236055b553d7eb7a8dba3df65e Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 16:52:07 -0400 Subject: Update coldfusion.html.markdown Adds variable declaration, comparison operators, and if/else control structures --- coldfusion.html.markdown | 395 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 394 insertions(+), 1 deletion(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 3c0b0b06..4c734920 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -1 +1,394 @@ -Coming soon +--- +language: ColdFusion +contributors: + - ["Wayne Boka", "http://wboka.github.io"] +filename: LearnColdFusion.cfm +--- + +ColdFusion is a scripting language for web development. +[Read more here.](http://www.adobe.com/products/coldfusion-family.html) + +```ColdFusion +" ---> + + + + + + + + + + +#myVariable# +#myNumber# + + + + + + + + + + + + + +#1 + 1# = 2 +#10 - 8# = 2 +#1 * 2# = 2 +#10 / 5# = 2 +#12 % 5# = 0 + + +#1 eq 1# +#15 neq 1# +#10 gt 8# +#1 lt 2# +#10 gte 5# +#1 lte 5# + + + + + #myCondition# + + #myCondition#. Proceed Carefully!!! + + myCondition is unknown + +``` + + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. -- cgit v1.2.3 From 1e7f639755042211ce0f10953153d6d341dbecab Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 16:52:47 -0400 Subject: Update coldfusion.html.markdown Fixes a typo --- coldfusion.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 4c734920..be08733e 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -26,7 +26,7 @@ ColdFusion is a scripting language for web development. #myVariable# -#myNumber# +#myNumber# -- cgit v1.2.3 From 8d57b90efe51c980d63abae4b5537631fb2f2eab Mon Sep 17 00:00:00 2001 From: Mariane Siqueira Machado Date: Mon, 5 Oct 2015 17:59:30 -0300 Subject: Translates another line --- pt-br/swift-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown index 72a57e4a..e840b8cf 100644 --- a/pt-br/swift-pt.html.markdown +++ b/pt-br/swift-pt.html.markdown @@ -221,7 +221,7 @@ println("Gas price: \(price)") // Número variável de argumentos func setup(numbers: Int...) { - // its an array + // é um array let number = numbers[0] let argCount = numbers.count } -- cgit v1.2.3 From c7c9ea674dbe3af1e2e1c09cffb36a40c6553e80 Mon Sep 17 00:00:00 2001 From: Chashmeet Singh Date: Tue, 6 Oct 2015 05:38:40 +0530 Subject: Update python-ru.html.markdown --- ru-ru/python-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 699d1393..3852a550 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -167,7 +167,7 @@ li = [] # Можно сразу начать с заполненного списка other_li = [4, 5, 6] -#Строка в список +# строка разделена в список a="adambard" list(a) #=> ['a','d','a','m','b','a','r','d'] -- cgit v1.2.3 From b8ad751cc020c07796832c1689cca7b84970b4e9 Mon Sep 17 00:00:00 2001 From: wboka Date: Mon, 5 Oct 2015 21:07:13 -0400 Subject: Update coldfusion.html.markdown Adds a few more examples --- coldfusion.html.markdown | 87 ++++++++++++++++++++---------------------------- 1 file changed, 37 insertions(+), 50 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index be08733e..b8fe9359 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -10,9 +10,9 @@ ColdFusion is a scripting language for web development. ```ColdFusion " ---> - @@ -25,8 +25,10 @@ ColdFusion is a scripting language for web development. -#myVariable# -#myNumber# +#myVariable#
+#myNumber#
+ +
@@ -40,19 +42,23 @@ ColdFusion is a scripting language for web development. -#1 + 1# = 2 -#10 - 8# = 2 -#1 * 2# = 2 -#10 / 5# = 2 -#12 % 5# = 0 +#1 + 1#
= 2 +#10 - 8#
= 2 +#1 * 2#
= 2 +#10 / 5#
= 2 +#12 % 5#
= 0 + +
-#1 eq 1# -#15 neq 1# -#10 gt 8# -#1 lt 2# -#10 gte 5# -#1 lte 5# +#1 eq 1#
+#15 neq 1#
+#10 gt 8#
+#1 lt 2#
+#10 gte 5#
+#1 lte 5#
+ +
@@ -63,36 +69,17 @@ ColdFusion is a scripting language for web development. myCondition is unknown -``` - + + #i#
+
+ +
+``` +" ---> - +

Simple Variables

+

Set myVariable to "myValue"

+

Set myNumber to 3.14

-#myVariable#
-#myNumber#
+

Display myVariable: #myVariable#

+

Display myNumber: #myNumber#


+

Complex Variables

+

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

+

Set myArray2 to an array of 1 dimension using function notation

+

Contents of myArray1

- +

Contents of myArray2

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

Operators

+

Arithmetic

+

1 + 1 = #1 + 1#

+

10 - 7 = #10 - 7#

+

15 * 10 = #15 * 10#

+

100 / 5 = #100 / 5#

+

120 % 5 = #120 % 5#

+

120 mod 5 = #120 mod 5#


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

Comparison

+

Standard Notation

+

Is 1 eq 1? #1 eq 1#

+

Is 15 neq 1? #15 neq 1#

+

Is 10 gt 8? #10 gt 8#

+

Is 1 lt 2? #1 lt 2#

+

Is 10 gte 5? #10 gte 5#

+

Is 1 lte 5? #1 lte 5#

+ +

Alternative Notation

+

Is 1 == 1? #1 eq 1#

+

Is 15 != 1? #15 neq 1#

+

Is 10 > 8? #10 gt 8#

+

Is 1 < 2? #1 lt 2#

+

Is 10 >= 5? #10 gte 5#

+

Is 1 <= 5? #1 lte 5#


+

Control Structures

+ + +

Condition to test for: "#myCondition#"

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

Loops

+

For Loop

- #i#
+

Index equals #i#

+
+ +

For Each Loop (Complex Variables)

+ +

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

+ + + + +

Index equals #i#

+
+ +

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

+ + + + +

Index equals #s#

+
+ +

Switch Statement

+ +

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

+ + + + + + +

#i# is a multiple of 5.

+
+ +

#i# is ninety-nine.

+
+ +

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

+
+

``` - -
@@ -186,8 +186,8 @@ This has to be avoided as much as you can. --> ## Precedence -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. +As you noticed an element may be targetted by more than one selector. +and may have a property set on it in more than one. In these cases, one of the rules takes precedence over others. Given the following CSS: @@ -217,24 +217,24 @@ and the following markup:

``` -The precedence of style is as followed: +The precedence of style is as followed: Remember, the precedence is for each **property**, not for the entire block. -* `E` has the highest precedence because of the keyword `!important`. +* `E` has the highest precedence because of the keyword `!important`. It is recommended to avoid this unless it is strictly necessary to use. * `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + +* `A` is next, because it is more "specific" than anything else. + more specific = more specifiers. here 3 specifiers: 1 tagname `p` + class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` +* `C` is next. although it has the same specificness as `B` but it appears last. * Then is `B` * and lastly is `D`. ## Compatibility -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatibility +Most of the features in CSS2 (and gradually in CSS3) are compatible across +all browsers and devices. But it's always vital to have in mind the compatibility of what you use in CSS with your target browsers. [QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. diff --git a/d.html.markdown b/d.html.markdown index daba8020..ba24b60f 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -1,6 +1,6 @@ --- -language: D -filename: learnd.d +language: D +filename: learnd.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] lang: en @@ -18,9 +18,9 @@ void main(string[] args) { } ``` -If you're like me and spend way too much time on the internet, odds are you've heard +If you're like me and spend way too much time on the internet, odds are you've heard about [D](http://dlang.org/). The D programming language is a modern, general-purpose, -multi-paradigm language with support for everything from low-level features to +multi-paradigm language with support for everything from low-level features to expressive high-level abstractions. D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool @@ -37,7 +37,7 @@ void main() { } auto n = 1; // use auto for type inferred variables - + // Numeric literals can use _ as a digit seperator for clarity while(n < 10_000) { n += n; @@ -49,7 +49,7 @@ void main() { // For and while are nice, but in D-land we prefer foreach // The .. creates a continuous range, excluding the end - foreach(i; 1..1_000_000) { + foreach(i; 1..1_000_000) { if(n % 2 == 0) writeln(i); } @@ -72,12 +72,12 @@ we can use templates to parameterize all of these on both types and values! // Here, T is a type parameter. Think from C++/C#/Java struct LinkedList(T) { T data = null; - LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think + LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think } class BinTree(T) { T data = null; - + // If there is only one template parameter, we can omit parens BinTree!T left; BinTree!T right; @@ -101,7 +101,7 @@ alias NumTree = BinTree!double; // We can create function templates as well! T max(T)(T a, T b) { - if(a < b) + if(a < b) return b; return a; @@ -114,7 +114,7 @@ void swap(T)(ref T a, ref T b) { auto temp = a; a = b; - b = temp; + b = temp; } // With templates, we can also parameterize on values, not just types @@ -145,13 +145,13 @@ class MyClass(T, U) { class MyClass(T, U) { T _data; U _other; - + // Constructors are always named `this` this(T t, U u) { data = t; other = u; } - + // getters @property T data() { return _data; @@ -161,7 +161,7 @@ class MyClass(T, U) { return _other; } - // setters + // setters @property void data(T t) { _data = t; } @@ -177,7 +177,7 @@ void main() { mc.data = 7; mc.other = "seven"; - + writeln(mc.data); writeln(mc.other); } @@ -193,7 +193,7 @@ and `override`ing methods. D does inheritance just like Java: Extend one class, implement as many interfaces as you please. We've seen D's OOP facilities, but let's switch gears. D offers -functional programming with first-class functions, `pure` +functional programming with first-class functions, `pure` functions, and immutable data. In addition, all of your favorite functional algorithms (map, filter, reduce and friends) can be found in the wonderful `std.algorithm` module! @@ -205,7 +205,7 @@ import std.range : iota; // builds an end-exclusive range void main() { // We want to print the sum of a list of squares of even ints // from 1 to 100. Easy! - + // Just pass lambda expressions as template parameters! // You can pass any old function you like, but lambdas are convenient here. auto num = iota(1, 101).filter!(x => x % 2 == 0) @@ -216,12 +216,12 @@ void main() { } ``` -Notice how we got to build a nice Haskellian pipeline to compute num? +Notice how we got to build a nice Haskellian pipeline to compute num? That's thanks to a D innovation know as Uniform Function Call Syntax. With UFCS, we can choose whether to write a function call as a method or free function call! Walter wrote a nice article on this -[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) -In short, you can call functions whose first parameter +[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +In short, you can call functions whose first parameter is of some type A on any expression of type A as a method. I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! diff --git a/dart.html.markdown b/dart.html.markdown index 34d1c6a8..f7601271 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -81,7 +81,7 @@ example5() { // Where classBody can include instance methods and variables, but also // class methods and variables. class Example6Class { - var example6InstanceVariable = "Example6 instance variable"; + var example6InstanceVariable = "Example6 instance variable"; sayIt() { print(example6InstanceVariable); } @@ -92,7 +92,7 @@ example6() { // Class methods and variables are declared with "static" terms. class Example7Class { - static var example7ClassVariable = "Example7 class variable"; + static var example7ClassVariable = "Example7 class variable"; static sayItFromClass() { print(example7ClassVariable); } @@ -111,7 +111,7 @@ example7() { // by default. But arrays and maps are not. They can be made constant by // declaring them "const". var example8A = const ["Example8 const array"], - example8M = const {"someKey": "Example8 const map"}; + example8M = const {"someKey": "Example8 const map"}; example8() { print(example8A[0]); print(example8M["someKey"]); @@ -245,7 +245,7 @@ example18() { // Strings with triple single-quotes or triple double-quotes span // multiple lines and include line delimiters. example19() { - print('''Example19 + print('''Example19 Example19 Don't can't I'm Etc Example19 '''); } @@ -272,7 +272,7 @@ example20() { class Example21 { List _names; Example21() { - _names = ["a", "b"]; + _names = ["a", "b"]; } List get names => _names; set names(List list) { diff --git a/erlang.html.markdown b/erlang.html.markdown index 4e2f1d84..d6ed7b86 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -292,7 +292,7 @@ calculateArea() -> _ -> io:format("We can only calculate area of rectangles or circles.") end. - + % Compile the module and create a process that evaluates `calculateArea` in the % shell. c(calculateGeometry). diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 49951c78..62118006 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnfsharp.fs --- -F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more. +F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more. It has a powerful type system that traps many errors at compile time, but it uses type inference so that it reads more like a dynamic language. @@ -90,7 +90,7 @@ let simplePatternMatch = | _ -> printfn "x is something else" // underscore matches anything // F# doesn't allow nulls by default -- you must use an Option type -// and then pattern match. +// and then pattern match. // Some(..) and None are roughly analogous to Nullable wrappers let validValue = Some(99) let invalidValue = None @@ -115,7 +115,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4] // into a string, similar to String.Format in C#. // ================================================ -// More on functions +// More on functions // ================================================ // F# is a true functional language -- functions are first @@ -124,30 +124,30 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4] // Modules are used to group functions together // Indentation is needed for each nested module. -module FunctionExamples = +module FunctionExamples = // define a simple adding function let add x y = x + y - + // basic usage of a function let a = add 1 2 printfn "1+2 = %i" a - + // partial application to "bake in" parameters let add42 = add 42 let b = add42 1 printfn "42+1 = %i" b - + // composition to combine functions let add1 = add 1 let add2 = add 2 let add3 = add1 >> add2 let c = add3 7 printfn "3+7 = %i" c - + // higher order functions [1..10] |> List.map add3 |> printfn "new list is %A" - + // lists of functions, and more let add6 = [add1; add2; add3] |> List.reduce (>>) let d = add6 7 @@ -158,54 +158,54 @@ module FunctionExamples = // ================================================ // There are three types of ordered collection: -// * Lists are most basic immutable collection. -// * Arrays are mutable and more efficient when needed. -// * Sequences are lazy and infinite (e.g. an enumerator). +// * Lists are most basic immutable collection. +// * Arrays are mutable and more efficient when needed. +// * Sequences are lazy and infinite (e.g. an enumerator). // // Other collections include immutable maps and sets // plus all the standard .NET collections -module ListExamples = +module ListExamples = - // lists use square brackets + // lists use square brackets let list1 = ["a";"b"] let list2 = "c" :: list1 // :: is prepending let list3 = list1 @ list2 // @ is concat - + // list comprehensions (aka generators) - let squares = [for i in 1..10 do yield i*i] + let squares = [for i in 1..10 do yield i*i] // prime number generator let rec sieve = function | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] | [] -> [] let primes = sieve [2..50] - printfn "%A" primes - + printfn "%A" primes + // pattern matching for lists - let listMatcher aList = + let listMatcher aList = match aList with - | [] -> printfn "the list is empty" - | [first] -> printfn "the list has one element %A " first - | [first; second] -> printfn "list is %A and %A" first second - | _ -> printfn "the list has more than two elements" + | [] -> printfn "the list is empty" + | [first] -> printfn "the list has one element %A " first + | [first; second] -> printfn "list is %A and %A" first second + | _ -> printfn "the list has more than two elements" listMatcher [1;2;3;4] listMatcher [1;2] listMatcher [1] - listMatcher [] + listMatcher [] // recursion using lists - let rec sum aList = + let rec sum aList = match aList with | [] -> 0 | x::xs -> x + sum xs sum [1..10] - - // ----------------------------------------- - // Standard library functions + + // ----------------------------------------- + // Standard library functions // ----------------------------------------- - + // map let add3 x = x + 3 [1..10] |> List.map add3 @@ -213,68 +213,68 @@ module ListExamples = // filter let even x = x % 2 = 0 [1..10] |> List.filter even - + // many more -- see documentation - -module ArrayExamples = + +module ArrayExamples = // arrays use square brackets with bar let array1 = [| "a";"b" |] let first = array1.[0] // indexed access using dot - + // pattern matching for arrays is same as for lists - let arrayMatcher aList = + let arrayMatcher aList = match aList with - | [| |] -> printfn "the array is empty" - | [| first |] -> printfn "the array has one element %A " first - | [| first; second |] -> printfn "array is %A and %A" first second - | _ -> printfn "the array has more than two elements" + | [| |] -> printfn "the array is empty" + | [| first |] -> printfn "the array has one element %A " first + | [| first; second |] -> printfn "array is %A and %A" first second + | _ -> printfn "the array has more than two elements" arrayMatcher [| 1;2;3;4 |] // Standard library functions just as for List - - [| 1..10 |] + + [| 1..10 |] |> Array.map (fun i -> i+3) |> Array.filter (fun i -> i%2 = 0) |> Array.iter (printfn "value is %i. ") - - -module SequenceExamples = + + +module SequenceExamples = // sequences use curly braces let seq1 = seq { yield "a"; yield "b" } - - // sequences can use yield and + + // sequences can use yield and // can contain subsequences let strange = seq { // "yield! adds one element yield 1; yield 2; - + // "yield!" adds a whole subsequence - yield! [5..10] + yield! [5..10] yield! seq { - for i in 1..10 do + for i in 1..10 do if i%2 = 0 then yield i }} - // test - strange |> Seq.toList - + // test + strange |> Seq.toList + // Sequences can be created using "unfold" // Here's the fibonacci series let fib = Seq.unfold (fun (fst,snd) -> Some(fst + snd, (snd, fst + snd))) (0,1) - // test + // test let fib10 = fib |> Seq.take 10 |> Seq.toList - printf "first 10 fibs are %A" fib10 - - + printf "first 10 fibs are %A" fib10 + + // ================================================ -// Data Types +// Data Types // ================================================ -module DataTypeExamples = +module DataTypeExamples = // All data is immutable by default @@ -282,33 +282,33 @@ module DataTypeExamples = // -- Use a comma to create a tuple let twoTuple = 1,2 let threeTuple = "a",2,true - + // Pattern match to unpack let x,y = twoTuple //sets x=1 y=2 - // ------------------------------------ - // Record types have named fields - // ------------------------------------ + // ------------------------------------ + // Record types have named fields + // ------------------------------------ // Use "type" with curly braces to define a record type type Person = {First:string; Last:string} - - // Use "let" with curly braces to create a record + + // Use "let" with curly braces to create a record let person1 = {First="John"; Last="Doe"} // Pattern match to unpack let {First=first} = person1 //sets first="john" - // ------------------------------------ + // ------------------------------------ // Union types (aka variants) have a set of choices // Only case can be valid at a time. - // ------------------------------------ + // ------------------------------------ // Use "type" with bar/pipe to define a union type - type Temp = + type Temp = | DegreesC of float | DegreesF of float - + // Use one of the cases to create one let temp1 = DegreesF 98.6 let temp2 = DegreesC 37.0 @@ -317,29 +317,29 @@ module DataTypeExamples = let printTemp = function | DegreesC t -> printfn "%f degC" t | DegreesF t -> printfn "%f degF" t - - printTemp temp1 + + printTemp temp1 printTemp temp2 - // ------------------------------------ + // ------------------------------------ // Recursive types - // ------------------------------------ + // ------------------------------------ - // Types can be combined recursively in complex ways + // Types can be combined recursively in complex ways // without having to create subclasses - type Employee = + type Employee = | Worker of Person | Manager of Employee list let jdoe = {First="John";Last="Doe"} let worker = Worker jdoe - - // ------------------------------------ + + // ------------------------------------ // Modelling with types - // ------------------------------------ - + // ------------------------------------ + // Union types are great for modelling state without using flags - type EmailAddress = + type EmailAddress = | ValidEmailAddress of string | InvalidEmailAddress of string @@ -350,40 +350,40 @@ module DataTypeExamples = // The combination of union types and record types together // provide a great foundation for domain driven design. - // You can create hundreds of little types that accurately + // You can create hundreds of little types that accurately // reflect the domain. type CartItem = { ProductCode: string; Qty: int } type Payment = Payment of float type ActiveCartData = { UnpaidItems: CartItem list } type PaidCartData = { PaidItems: CartItem list; Payment: Payment} - - type ShoppingCart = + + type ShoppingCart = | EmptyCart // no data | ActiveCart of ActiveCartData - | PaidCart of PaidCartData + | PaidCart of PaidCartData - // ------------------------------------ + // ------------------------------------ // Built in behavior for types - // ------------------------------------ + // ------------------------------------ // Core types have useful "out-of-the-box" behavior, no coding needed. // * Immutability // * Pretty printing when debugging // * Equality and comparison // * Serialization - + // Pretty printing using %A - printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" + printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" twoTuple person1 temp1 worker // Equality and comparison built in. // Here's an example with cards. type Suit = Club | Diamond | Spade | Heart - type Rank = Two | Three | Four | Five | Six | Seven | Eight - | Nine | Ten | Jack | Queen | King | Ace + type Rank = Two | Three | Four | Five | Six | Seven | Eight + | Nine | Ten | Jack | Queen | King | Ace - let hand = [ Club,Ace; Heart,Three; Heart,Ace; + let hand = [ Club,Ace; Heart,Three; Heart,Ace; Spade,Jack; Diamond,Two; Diamond,Ace ] // sorting @@ -391,27 +391,27 @@ module DataTypeExamples = List.max hand |> printfn "high card is %A" List.min hand |> printfn "low card is %A" - + // ================================================ // Active patterns // ================================================ -module ActivePatternExamples = +module ActivePatternExamples = - // F# has a special type of pattern matching called "active patterns" - // where the pattern can be parsed or detected dynamically. + // F# has a special type of pattern matching called "active patterns" + // where the pattern can be parsed or detected dynamically. // "banana clips" are the syntax for active patterns - + // for example, define an "active" pattern to match character types... - let (|Digit|Letter|Whitespace|Other|) ch = + let (|Digit|Letter|Whitespace|Other|) ch = if System.Char.IsDigit(ch) then Digit else if System.Char.IsLetter(ch) then Letter else if System.Char.IsWhiteSpace(ch) then Whitespace - else Other + else Other // ... and then use it to make parsing logic much clearer - let printChar ch = + let printChar ch = match ch with | Digit -> printfn "%c is a Digit" ch | Letter -> printfn "%c is a Letter" ch @@ -424,52 +424,52 @@ module ActivePatternExamples = // ----------------------------------- // FizzBuzz using active patterns // ----------------------------------- - + // You can create partial matching patterns as well // Just use undercore in the defintion, and return Some if matched. let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None // the main function - let fizzBuzz i = + let fizzBuzz i = match i with - | MultOf3 & MultOf5 -> printf "FizzBuzz, " - | MultOf3 -> printf "Fizz, " - | MultOf5 -> printf "Buzz, " + | MultOf3 & MultOf5 -> printf "FizzBuzz, " + | MultOf3 -> printf "Fizz, " + | MultOf5 -> printf "Buzz, " | _ -> printf "%i, " i - + // test - [1..20] |> List.iter fizzBuzz - + [1..20] |> List.iter fizzBuzz + // ================================================ -// Conciseness +// Conciseness // ================================================ -module AlgorithmExamples = +module AlgorithmExamples = - // F# has a high signal/noise ratio, so code reads + // F# has a high signal/noise ratio, so code reads // almost like the actual algorithm // ------ Example: define sumOfSquares function ------ - let sumOfSquares n = + let sumOfSquares n = [1..n] // 1) take all the numbers from 1 to n |> List.map square // 2) square each one |> List.sum // 3) sum the results - // test - sumOfSquares 100 |> printfn "Sum of squares = %A" - - // ------ Example: define a sort function ------ + // test + sumOfSquares 100 |> printfn "Sum of squares = %A" + + // ------ Example: define a sort function ------ let rec sort list = match list with - // If the list is empty - | [] -> + // If the list is empty + | [] -> [] // return an empty list - // If the list is not empty - | firstElem::otherElements -> // take the first element - let smallerElements = // extract the smaller elements + // If the list is not empty + | firstElem::otherElements -> // take the first element + let smallerElements = // extract the smaller elements otherElements // from the remaining ones - |> List.filter (fun e -> e < firstElem) + |> List.filter (fun e -> e < firstElem) |> sort // and sort them let largerElements = // extract the larger ones otherElements // from the remaining ones @@ -479,13 +479,13 @@ module AlgorithmExamples = List.concat [smallerElements; [firstElem]; largerElements] // test - sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A" + sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A" // ================================================ // Asynchronous Code // ================================================ -module AsyncExample = +module AsyncExample = // F# has built-in features to help with async code // without encountering the "pyramid of doom" @@ -495,23 +495,23 @@ module AsyncExample = open System.Net open System open System.IO - open Microsoft.FSharp.Control.CommonExtensions + open Microsoft.FSharp.Control.CommonExtensions // Fetch the contents of a URL asynchronously - let fetchUrlAsync url = - async { // "async" keyword and curly braces + let fetchUrlAsync url = + async { // "async" keyword and curly braces // creates an "async" object - let req = WebRequest.Create(Uri(url)) - use! resp = req.AsyncGetResponse() + let req = WebRequest.Create(Uri(url)) + use! resp = req.AsyncGetResponse() // use! is async assignment - use stream = resp.GetResponseStream() + use stream = resp.GetResponseStream() // "use" triggers automatic close() // on resource at end of scope - use reader = new IO.StreamReader(stream) - let html = reader.ReadToEnd() - printfn "finished downloading %s" url + use reader = new IO.StreamReader(stream) + let html = reader.ReadToEnd() + printfn "finished downloading %s" url } - + // a list of sites to fetch let sites = ["http://www.bing.com"; "http://www.google.com"; @@ -520,7 +520,7 @@ module AsyncExample = "http://www.yahoo.com"] // do it - sites + sites |> List.map fetchUrlAsync // make a list of async tasks |> Async.Parallel // set up the tasks to run in parallel |> Async.RunSynchronously // start them off @@ -529,58 +529,58 @@ module AsyncExample = // .NET compatability // ================================================ -module NetCompatibilityExamples = +module NetCompatibilityExamples = // F# can do almost everything C# can do, and it integrates // seamlessly with .NET or Mono libraries. // ------- work with existing library functions ------- - + let (i1success,i1) = System.Int32.TryParse("123"); if i1success then printfn "parsed as %i" i1 else printfn "parse failed" // ------- Implement interfaces on the fly! ------- - + // create a new object that implements IDisposable - let makeResource name = - { new System.IDisposable + let makeResource name = + { new System.IDisposable with member this.Dispose() = printfn "%s disposed" name } - let useAndDisposeResources = + let useAndDisposeResources = use r1 = makeResource "first resource" - printfn "using first resource" + printfn "using first resource" for i in [1..3] do let resourceName = sprintf "\tinner resource %d" i - use temp = makeResource resourceName - printfn "\tdo something with %s" resourceName + use temp = makeResource resourceName + printfn "\tdo something with %s" resourceName use r2 = makeResource "second resource" - printfn "using second resource" - printfn "done." + printfn "using second resource" + printfn "done." // ------- Object oriented code ------- - + // F# is also a fully fledged OO language. // It supports classes, inheritance, virtual methods, etc. // interface with generic type - type IEnumerator<'a> = + type IEnumerator<'a> = abstract member Current : 'a - abstract MoveNext : unit -> bool + abstract MoveNext : unit -> bool // abstract base class with virtual methods [] - type Shape() = + type Shape() = //readonly properties abstract member Width : int with get abstract member Height : int with get //non-virtual method member this.BoundingArea = this.Height * this.Width //virtual method with base implementation - abstract member Print : unit -> unit + abstract member Print : unit -> unit default this.Print () = printfn "I'm a shape" - // concrete class that inherits from base class and overrides - type Rectangle(x:int, y:int) = + // concrete class that inherits from base class and overrides + type Rectangle(x:int, y:int) = inherit Shape() override this.Width = x override this.Height = y @@ -590,20 +590,20 @@ module NetCompatibilityExamples = let r = Rectangle(2,3) printfn "The width is %i" r.Width printfn "The area is %i" r.BoundingArea - r.Print() + r.Print() // ------- extension methods ------- - + //Just as in C#, F# can extend existing classes with extension methods. type System.String with member this.StartsWithA = this.StartsWith "A" //test let s = "Alice" - printfn "'%s' starts with an 'A' = %A" s s.StartsWithA - + printfn "'%s' starts with an 'A' = %A" s s.StartsWithA + // ------- events ------- - + type MyButton() = let clickEvent = new Event<_>() @@ -615,11 +615,11 @@ module NetCompatibilityExamples = // test let myButton = new MyButton() - myButton.OnClick.Add(fun (sender, arg) -> + myButton.OnClick.Add(fun (sender, arg) -> printfn "Click event with arg=%O" arg) myButton.TestEvent("Hello World!") - + ``` ## More Information diff --git a/hack.html.markdown b/hack.html.markdown index b9730dc0..b3d19f8e 100644 --- a/hack.html.markdown +++ b/hack.html.markdown @@ -51,7 +51,7 @@ function identity(?string $stringOrNull) : ?string class TypeHintedProperties { public ?string $name; - + protected int $id; private float $score = 100.0; @@ -91,7 +91,7 @@ function openBox(Box $box) : int // Shapes -// +// // Hack adds the concept of shapes for defining struct-like arrays with a // guaranteed, type-checked set of keys type Point2D = shape('x' => int, 'y' => int); @@ -108,7 +108,7 @@ distance( // Type aliasing -// +// // Hack adds a bunch of type aliasing features for making complex types readable newtype VectorArray = array>; @@ -142,7 +142,7 @@ function getRoadType() : RoadType // Constructor argument promotion -// +// // To avoid boilerplate property and constructor definitions that only set // properties, Hack adds a concise syntax for defining properties and a // constructor at the same time. @@ -171,12 +171,12 @@ class WithoutArgumentPromotion // Co-operative multi-tasking -// +// // Two new keywords "async" and "await" can be used to perform multi-tasking // Note that this does not involve threads - it just allows transfer of control async function cooperativePrint(int $start, int $end) : Awaitable { - for ($i = $start; $i <= $end; $i++) { + for ($i = $start; $i <= $end; $i++) { echo "$i "; // Give other tasks a chance to do something @@ -193,9 +193,9 @@ AwaitAllWaitHandle::fromArray([ // Attributes -// +// // Attributes are a form of metadata for functions. Hack provides some -// special built-in attributes that introduce useful behaviour. +// special built-in attributes that introduce useful behaviour. // The __Memoize special attribute causes the result of a function to be cached <<__Memoize>> @@ -248,7 +248,7 @@ class ConsistentBar extends ConsistentFoo class InvalidFooSubclass extends ConsistentFoo { // Not matching the parent constructor will cause a type checker error: - // + // // "This object is of type ConsistentBaz. It is incompatible with this object // of type ConsistentFoo because some of their methods are incompatible" // @@ -259,7 +259,7 @@ class InvalidFooSubclass extends ConsistentFoo // Using the __Override annotation on a non-overriden method will cause a // type checker error: - // + // // "InvalidFooSubclass::otherMethod() is marked as override; no non-private // parent definition found or overridden parent is defined in non- COUNTRIES = new HashSet(); static { validCodes.add("DENMARK"); validCodes.add("SWEDEN"); validCodes.add("FINLAND"); } - + // But there's a nifty way to achive the same thing in an // easier way, by using something that is called Double Brace // Initialization. - + private static final Set COUNTRIES = HashSet() {{ add("DENMARK"); add("SWEDEN"); - add("FINLAND"); + add("FINLAND"); }} - - // The first brace is creating an new AnonymousInnerClass and the + + // The first brace is creating an new AnonymousInnerClass and the // second one declares and instance initializer block. This block // is called with the anonymous inner class is created. // This does not only work for Collections, it works for all @@ -500,7 +500,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, } -// Abstract Classes +// Abstract Classes // Abstract Class declaration syntax // abstract extends { // // Constants and variables @@ -512,26 +512,26 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // Also abstract classes CAN have the "main" method. // Abstract classes solve these problems. -public abstract class Animal +public abstract class Animal { public abstract void makeSound(); // Method can have a body public void eat() { - System.out.println("I am an animal and I am Eating."); + System.out.println("I am an animal and I am Eating."); // Note: We can access private variable here. age = 30; } - // No need to initialize, however in an interface + // No need to initialize, however in an interface // a variable is implicitly final and hence has // to be initialized. private int age; public void printAge() { - System.out.println(age); + System.out.println(age); } // Abstract classes can have main function. @@ -552,7 +552,7 @@ class Dog extends Animal // age = 30; ==> ERROR! age is private to Animal } - // NOTE: You will get an error if you used the + // NOTE: You will get an error if you used the // @Override annotation here, since java doesn't allow // overriding of static methods. // What is happening here is called METHOD HIDING. diff --git a/json.html.markdown b/json.html.markdown index 47a8cb21..6aff2ce2 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -16,7 +16,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. ```json { "key": "value", - + "keys": "must always be enclosed in double quotes", "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", @@ -46,7 +46,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. [0, 0, 0, 1] ] ], - + "alternative style": { "comment": "check this out!" , "comma position": "doesn't matter - as long as it's before the value, then it's valid" diff --git a/julia.html.markdown b/julia.html.markdown index 5ccd6484..66329feb 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -14,7 +14,7 @@ This is based on Julia 0.3. # Single line comments start with a hash (pound) symbol. #= Multiline comments can be written - by putting '#=' before the text and '=#' + by putting '#=' before the text and '=#' after the text. They can also be nested. =# @@ -670,7 +670,7 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 # What happens when we feed square_area an integer? -code_native(square_area, (Int32,)) +code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 # Prologue @@ -703,10 +703,10 @@ code_native(square_area, (Float64,)) # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) # pop RBP # ret - # + # # Note that julia will use floating point instructions if any of the # arguements are floats. -# Let's calculate the area of a circle +# Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 @@ -737,7 +737,7 @@ code_native(circle_area, (Float64,)) # vmulsd XMM0, XMM1, XMM0 # pop RBP # ret - # + # ``` ## Further Reading diff --git a/livescript.html.markdown b/livescript.html.markdown index e64f7719..9235f5ce 100644 --- a/livescript.html.markdown +++ b/livescript.html.markdown @@ -166,7 +166,7 @@ not false # => true ######################################################################## ## 3. Functions -######################################################################## +######################################################################## # Since LiveScript is functional, you'd expect functions to get a nice # treatment. In LiveScript it's even more apparent that functions are @@ -229,7 +229,7 @@ double-minus-one = (- 1) . (* 2) # Other than the usual `f . g` mathematical formulae, you get the `>>` # and `<<` operators, that describe how the flow of values through the -# functions. +# functions. double-minus-one = (* 2) >> (- 1) double-minus-one = (- 1) << (* 2) @@ -344,7 +344,7 @@ kitten.hug! # => "*Mei (a cat) is hugged*" ## Further reading There's just so much more to LiveScript, but this should be enough to -get you started writing little functional things in it. The +get you started writing little functional things in it. The [official website](http://livescript.net/) has a lot of information on the language, and a nice online compiler for you to try stuff out! diff --git a/make.html.markdown b/make.html.markdown index 75543dcd..563139d1 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -31,7 +31,7 @@ we are using GNU make which is the standard on Linux. file0.txt: echo "foo" > file0.txt # Even comments in these 'recipe' sections get passed to the shell. - # Try `make file0.txt` or simply `make` - first rule is the default. + # Try `make file0.txt` or simply `make` - first rule is the default. # This rule will only run if file0.txt is newer than file1.txt. @@ -49,7 +49,7 @@ file2.txt file3.txt: file0.txt file1.txt touch file2.txt touch file3.txt -# Make will complain about multiple recipes for the same rule. Empty +# Make will complain about multiple recipes for the same rule. Empty # recipes don't count though and can be used to add new dependencies. #----------------------------------------------------------------------- @@ -115,7 +115,7 @@ small/%.png: %.svg %.png: %.ps @echo this rule is not chosen if *.svg and *.ps are both present -# make already has some pattern rules built-in. For instance, it knows +# make already has some pattern rules built-in. For instance, it knows # how to turn *.c files into *.o files. # Older makefiles might use suffix rules instead of pattern rules @@ -185,7 +185,7 @@ var := hello var2 ::= $(var) hello #:= and ::= are equivalent. -# These variables are evaluated procedurely (in the order that they +# These variables are evaluated procedurely (in the order that they # appear), thus breaking with the rest of the language ! # This doesn't work diff --git a/markdown.html.markdown b/markdown.html.markdown index acb808ea..2333110f 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -70,7 +70,7 @@ I'm in paragraph three! -I end with two spaces (highlight me to see them). +I end with two spaces (highlight me to see them). There's a
above me! @@ -97,7 +97,7 @@ or + Item + One more item -or +or - Item - Item @@ -129,7 +129,7 @@ render the numbers in order, but this may not be a good idea --> Boxes below without the 'x' are unchecked HTML checkboxes. -- [ ] First task to complete. +- [ ] First task to complete. - [ ] Second task that needs done This checkbox below will be a checked HTML checkbox. - [x] This task has been completed @@ -169,7 +169,7 @@ with or without spaces. --> *** --- -- - - +- - - **************** diff --git a/matlab.html.markdown b/matlab.html.markdown index 00f4c53a..02fe5962 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -6,7 +6,7 @@ contributors: --- -MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. +MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or @@ -16,7 +16,7 @@ If you have any feedback please feel free to reach me at % Comments start with a percent sign. %{ -Multi line comments look +Multi line comments look something like this @@ -62,10 +62,10 @@ disp('text') % print "text" to the screen % Variables & Expressions myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 -a = 2; b = 3; +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 % Calling functions can be done in either of two ways: @@ -73,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 load('myFile.mat', 'y') % arguments within parantheses, spererated by commas % Command syntax: load myFile.mat y % no parentheses, and spaces instead of commas -% Note the lack of quote marks in command form: inputs are always passed as +% Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A); % this has no equivalent in command form [~,D] = eig(A); % if you only want D and not V @@ -103,7 +103,7 @@ a(2) % ans = y % Cells -a = {'one', 'two', 'three'} +a = {'one', 'two', 'three'} a(1) % ans = 'one' - returns a cell char(a(1)) % ans = one - returns a string @@ -113,7 +113,7 @@ A.c = [1 2]; A.d.e = false; % Vectors -x = [4 32 53 7 1] +x = [4 32 53 7 1] x(2) % ans = 32, indices in Matlab start 1, not 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -123,7 +123,7 @@ x = [4; 32; 53; 7; 1] % Column vector x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 % Matrices -A = [1 2 3; 4 5 6; 7 8 9] +A = [1 2 3; 4 5 6; 7 8 9] % Rows are separated by a semicolon; elements are separated with space or comma % A = @@ -132,7 +132,7 @@ A = [1 2 3; 4 5 6; 7 8 9] % 7 8 9 A(2,3) % ans = 6, A(row, column) -A(6) % ans = 8 +A(6) % ans = 8 % (implicitly concatenates columns into vector, then indexes into that) @@ -171,7 +171,7 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 -% this is the same as +% this is the same as vertcat(A,A); @@ -183,7 +183,7 @@ vertcat(A,A); % 4 5 42 4 5 42 % 7 8 9 7 8 9 -% this is the same as +% this is the same as horzcat(A,A); @@ -201,21 +201,21 @@ A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: A one -ctranspose(A) % Hermitian transpose the matrix +ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -% Element by Element Arithmetic vs. Matrix Arithmetic +% Element by Element Arithmetic vs. Matrix Arithmetic % On their own, the arithmetic operators act on whole matrices. When preceded % by a period, they act on each element instead. For example: A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B -% There are several pairs of functions, where one acts on each element, and +% There are several pairs of functions, where one acts on each element, and % the other (whose name ends in m) acts on the whole matrix. -exp(A) % exponentiate each element +exp(A) % exponentiate each element expm(A) % calculate the matrix exponential sqrt(A) % take the square root of each element sqrtm(A) % find the matrix whose square is A @@ -233,7 +233,7 @@ axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot legend('Line 1 label', 'Line 2 label') % Label curves with a legend -% Alternative method to plot multiple functions in one plot. +% Alternative method to plot multiple functions in one plot. % while 'hold' is on, commands add to existing graph rather than replacing it plot(x, y) hold on @@ -271,9 +271,9 @@ clf clear % clear current figure window, and reset most figure properties % Properties can be set and changed through a figure handle. % You can save a handle to a figure when you create it. -% The function gcf returns a handle to the current figure +% The function gcf returns a handle to the current figure h = plot(x, y); % you can save a handle to a figure when you create it -set(h, 'Color', 'r') +set(h, 'Color', 'r') % 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black set(h, 'LineStyle', '--') % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line @@ -298,8 +298,8 @@ cd /path/to/move/into % change directory % Variables can be saved to .mat files -save('myFileName.mat') % Save the variables in your Workspace -load('myFileName.mat') % Load saved variables into Workspace +save('myFileName.mat') % Save the variables in your Workspace +load('myFileName.mat') % Load saved variables into Workspace % M-file Scripts % A script file is an external file that contains a sequence of statements. @@ -312,11 +312,11 @@ load('myFileName.mat') % Load saved variables into Workspace % Also, they have their own workspace (ie. different variable scope). % Function name should match file name (so save this example as double_input.m). % 'help double_input.m' returns the comments under line beginning function -function output = double_input(x) +function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; end -double_input(6) % ans = 12 +double_input(6) % ans = 12 % You can also have subfunctions and nested functions. @@ -325,8 +325,8 @@ double_input(6) % ans = 12 % functions, and have access to both its workspace and their own workspace. % If you want to create a function without creating a new file you can use an -% anonymous function. Useful when quickly defining a function to pass to -% another function (eg. plot with fplot, evaluate an indefinite integral +% anonymous function. Useful when quickly defining a function to pass to +% another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). % Example that returns the square of it's input, assigned to to the handle sqr: sqr = @(x) x.^2; @@ -336,12 +336,12 @@ doc function_handle % find out more % User input a = input('Enter the value: ') -% Stops execution of file and gives control to the keyboard: user can examine +% Stops execution of file and gives control to the keyboard: user can examine % or change variables. Type 'return' to continue execution, or 'dbquit' to exit keyboard % Reading in data (also xlsread/importdata/imread for excel/CSV/image files) -fopen(filename) +fopen(filename) % Output disp(a) % Print out the value of variable a @@ -363,8 +363,8 @@ end for k = 1:5 disp(k) end - -k = 0; + +k = 0; while (k < 5) k = k + 1; end @@ -382,7 +382,7 @@ password = 'root'; driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ -conn = database(dbname, username, password, driver, dburl); +conn = database(dbname, username, password, driver, dburl); sql = ['SELECT * from table_name where id = 22'] % Example sql statement a = fetch(conn, sql) %a will contain your data @@ -394,7 +394,7 @@ tan(x) asin(x) acos(x) atan(x) -exp(x) +exp(x) sqrt(x) log(x) log10(x) @@ -426,7 +426,7 @@ pinv(A) % calculate the pseudo-inverse zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's diag(A) % Extracts the diagonal elements of a matrix A -diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere +diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere eye(m,n) % Identity matrix linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix A @@ -452,15 +452,15 @@ flipud(A) % Flip matrix up to down [U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order % Common vector functions -max % largest component -min % smallest component +max % largest component +min % smallest component length % length of a vector -sort % sort in ascending order -sum % sum of elements +sort % sort in ascending order +sum % sum of elements prod % product of elements mode % modal value -median % median value -mean % mean value +median % median value +mean % mean value std % standard deviation perms(x) % list all permutations of elements of x diff --git a/neat.html.markdown b/neat.html.markdown index e99d1e0e..f02461ee 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -47,18 +47,18 @@ void main(string[] args) { // There are no one-value tuples though. // So you can always use () in the mathematical sense. // (string) arg; <- is an error - + /* byte: 8 bit signed integer char: 8 bit UTF-8 byte component. short: 16 bit signed integer int: 32 bit signed integer long: 64 bit signed integer - + float: 32 bit floating point double: 64 bit floating point real: biggest native size floating point (80 bit on x86). - + bool: true or false */ int a = 5; @@ -139,14 +139,14 @@ void main(string[] args) { assert !(hewo is s); // same as assert (hewo !is s); - + // Allocate arrays using "new array length" int[] integers = new int[] 10; assert(integers.length == 10); assert(integers[0] == 0); // zero is default initializer integers = integers ~ 5; // This allocates a new array! assert(integers.length == 11); - + // This is an appender array. // Instead of (length, pointer), it tracks (capacity, length, pointer). // When you append to it, it will use the free capacity if it can. @@ -156,13 +156,13 @@ void main(string[] args) { appender ~= 2; appender ~= 3; appender.free(); // same as {mem.free(appender.ptr); appender = null;} - + // Scope variables are automatically freed at the end of the current scope. scope int[auto~] someOtherAppender; // This is the same as: int[auto~] someOtherAppender2; onExit { someOtherAppender2.free; } - + // You can do a C for loop too // - but why would you want to? for (int i = 0; i < 5; ++i) { } @@ -178,23 +178,23 @@ void main(string[] args) { assert(i == 5); break; // otherwise we'd go back up to do { } - + // This is a nested function. // Nested functions can access the surrounding function. string returnS() { return s; } writeln returnS(); - + // Take the address of a function using & // The type of a global function is ReturnType function(ParameterTypeTuple). void function() foop = &foo; - + // Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple). string delegate() returnSp = &returnS; writeln returnSp(); // Class member functions and struct member functions also fit into delegate variables. // In general, delegates are functions that carry an additional context pointer. // ("fat pointers" in C) - + // Allocate a "snapshot" with "new delegate". // Snapshots are not closures! I used to call them closures too, // but then my Haskell-using friends yelled at me so I had to stop. @@ -232,8 +232,8 @@ void main(string[] args) { auto nestfun = λ() { } // There is NO semicolon needed here! // "}" can always substitute for "};". // This provides syntactic consistency with built-in statements. - - + + // This is a class. // Note: almost all elements of Neat can be used on the module level // or just as well inside a function. @@ -268,7 +268,7 @@ void main(string[] args) { E e = E:cd; // dynamic class cast! e.doE(); writeln "$e"; // all interfaces convert to Object implicitly. - + // Templates! // Templates are parameterized namespaces, taking a type as a parameter. template Templ(T) { diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 407ba3c8..89901308 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -11,7 +11,7 @@ filename: LearnObjectiveC.m --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. -It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. +It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. ```objective_c // Single-line comments start with // @@ -41,15 +41,15 @@ int main (int argc, const char * argv[]) // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" - + /////////////////////////////////////// // Types & Variables /////////////////////////////////////// - + // Primitive declarations int myPrimitive1 = 1; long myPrimitive2 = 234554664565; - + // Object declarations // Put the * in front of the variable names for strongly-typed object declarations MyClass *myObject1 = nil; // Strong typing @@ -57,15 +57,15 @@ int main (int argc, const char * argv[]) // %@ is an object // 'description' is a convention to display the value of the Objects NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)" - + // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" // NSMutableString is a mutable version of the NSString object NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" - + // Character literals NSNumber *theLetterZNumber = @'Z'; char theLetterZ = [theLetterZNumber charValue]; // or 'Z' @@ -75,11 +75,11 @@ int main (int argc, const char * argv[]) NSNumber *fortyTwoNumber = @42; int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); - + NSNumber *fortyTwoUnsignedNumber = @42U; unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 NSLog(@"%u", fortyTwoUnsigned); - + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); @@ -87,7 +87,7 @@ int main (int argc, const char * argv[]) NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41 NSLog(@"%u", fortyOneUnsigned); - + NSNumber *fortyTwoLongNumber = @42L; long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); @@ -101,7 +101,7 @@ int main (int argc, const char * argv[]) float piFloat = [piFloatNumber floatValue]; // or 3.141592654f NSLog(@"%f", piFloat); // prints => 3.141592654 NSLog(@"%5.2f", piFloat); // prints => " 3.14" - + NSNumber *piDoubleNumber = @3.1415926535; double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); @@ -111,7 +111,7 @@ int main (int argc, const char * argv[]) NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: - [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberByAdding:twoDecNum]; [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; @@ -130,8 +130,8 @@ int main (int argc, const char * argv[]) NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" - // NSMutableArray is a mutable version of NSArray, allowing you to change - // the items in the array and to extend or shrink the array object. + // NSMutableArray is a mutable version of NSArray, allowing you to change + // the items in the array and to extend or shrink the array object. // Convenient, but not as efficient as NSArray. NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; @@ -161,7 +161,7 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Operators /////////////////////////////////////// - + // The operators works like in the C language // For example: 2 + 5; // => 7 @@ -206,13 +206,13 @@ int main (int argc, const char * argv[]) NSLog(@"I print"); } break; } - + // While loops statements int ii = 0; while (ii < 4) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value - } // prints => "0," + } // prints => "0," // "1," // "2," // "3," @@ -222,25 +222,25 @@ int main (int argc, const char * argv[]) for (jj=0; jj < 4; jj++) { NSLog(@"%d,", jj); - } // prints => "0," + } // prints => "0," // "1," // "2," // "3," - - // Foreach statements + + // Foreach statements NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { NSLog(@"%@,", value); - } // prints => "0," + } // prints => "0," // "1," // "2," // "3," // Object for loop statement. Can be used with any Objective-C object type - for (id item in values) { - NSLog(@"%@,", item); - } // prints => "0," + for (id item in values) { + NSLog(@"%@,", item); + } // prints => "0," // "1," // "2," // "3," @@ -251,7 +251,7 @@ int main (int argc, const char * argv[]) // Your statements here @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. + } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. { NSLog(@"Exception: %@", e); } @finally @@ -260,17 +260,17 @@ int main (int argc, const char * argv[]) } // prints => "Exception: File Not Found on System" // "Finally. Time to clean up." - // NSError objects are useful for function arguments to populate on user mistakes. + // NSError objects are useful for function arguments to populate on user mistakes. NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; - + /////////////////////////////////////// // Objects /////////////////////////////////////// - + // Create an object instance by allocating memory and initializing it // An object is not fully functional until both steps have been completed MyClass *myObject = [[MyClass alloc] init]; - + // The Objective-C model of object-oriented programming is based on message // passing to object instances // In Objective-C one does not simply call a method; one sends a message @@ -281,7 +281,7 @@ int main (int argc, const char * argv[]) // End of @autoreleasepool } - + // End the program return 0; } @@ -302,9 +302,9 @@ int main (int argc, const char * argv[]) @interface MyClass : NSObject // NSObject is Objective-C's base object class. { // Instance variable declarations (can exist in either interface or implementation file) - int count; // Protected access by default. + int count; // Protected access by default. @private id data; // Private access (More convenient to declare in implementation file) - NSString *name; + NSString *name; } // Convenient notation for public access variables to auto generate a setter method // By default, setter method name is 'set' followed by @property variable name @@ -314,7 +314,7 @@ int main (int argc, const char * argv[]) @property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; - + // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -336,7 +336,7 @@ int main (int argc, const char * argv[]) // To access public variables from the implementation file, @property generates a setter method // automatically. Method name is 'set' followed by @property variable name: MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance -[myClass setCount:10]; +[myClass setCount:10]; NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: [myClass lengthSet:32]; @@ -359,7 +359,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell // as a variable // SEL is the data type. @selector() returns a selector from method name provided // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass -SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method // Must put all method arguments into one object to send to performSelector function NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; @@ -383,7 +383,7 @@ distance = 18; // References "long distance" from MyClass implementation @synthesize roString = _roString; // _roString available now in @implementation // Called before calling any class methods or instantiating any objects -+ (void)initialize ++ (void)initialize { if (self == [MyClass class]) { distance = 0; @@ -393,7 +393,7 @@ distance = 18; // References "long distance" from MyClass implementation // Counterpart to initialize method. Called when an object's reference count is zero - (void)dealloc { - [height release]; // If not using ARC, make sure to release class variable objects + [height release]; // If not using ARC, make sure to release class variable objects [super dealloc]; // and call parent class dealloc } @@ -408,7 +408,7 @@ distance = 18; // References "long distance" from MyClass implementation return self; } // Can create constructors that contain arguments: -- (id)initWithDistance:(int)defaultDistance +- (id)initWithDistance:(int)defaultDistance { distance = defaultDistance; return self; @@ -419,7 +419,7 @@ distance = 18; // References "long distance" from MyClass implementation return @"Some string"; } -+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight { height = defaultHeight; return [[self alloc] init]; @@ -435,7 +435,7 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } -// Objective-C does not have private method declarations, but you can simulate them. +// Objective-C does not have private method declarations, but you can simulate them. // To simulate a private method, create the method in the @implementation but not in the @interface. - (NSNumber *)secretPrivateMethod { return @72; @@ -454,15 +454,15 @@ distance = 18; // References "long distance" from MyClass implementation // Categories /////////////////////////////////////// // A category is a group of methods designed to extend a class. They allow you to add new methods -// to an existing class for organizational purposes. This is not to be mistaken with subclasses. -// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD // functionality to an object. // Categories allow you to: // -- Add methods to an existing class for organizational purposes. // -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. -// -- Add ability to create protected and private methods to classes. -// NOTE: Do not override methods of the base class in a category even though you have the ability -// to. Overriding methods may cause compiler errors later between different categories and it +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it // ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. // Here is a simple Car base class. @@ -494,8 +494,8 @@ distance = 18; // References "long distance" from MyClass implementation @end // Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would -// be changing the functionality of the Car to behave like a truck. But lets say we want to just add -// functionality to this existing Car. A good example would be to clean the car. So we would create +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create // a category to add these cleaning methods: // @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) #import "Car.h" // Make sure to import base class to extend. @@ -519,7 +519,7 @@ distance = 18; // References "long distance" from MyClass implementation NSLog(@"Waxed."); } -@end +@end // Any Car object instance has the ability to use a category. All they need to do is import it: #import "Car+Clean.h" // Import as many different categories as you want to use. @@ -534,7 +534,7 @@ int main (int argc, const char * argv[]) { [mustang turnOn]; // Use methods from base Car class. [mustang washWindows]; // Use methods from Car's Clean category. } - return 0; + return 0; } // Objective-C does not have protected method declarations but you can simulate them. @@ -548,7 +548,7 @@ int main (int argc, const char * argv[]) { //To use protected methods, import the category, then implement the methods: #import "Car+Protected.h" // Remember, import in the @implementation file only. -@implementation Car +@implementation Car - (void)lockCar { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. @@ -571,8 +571,8 @@ int main (int argc, const char * argv[]) { // You can override numOfSides variable or getNumOfSides method to edit them with an extension: // @implementation filename: Shape.m #import "Shape.h" -// Extensions live in the same file as the class @implementation. -@interface Shape () // () after base class name declares an extension. +// Extensions live in the same file as the class @implementation. +@interface Shape () // () after base class name declares an extension. @property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly. -(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int. @@ -580,7 +580,7 @@ int main (int argc, const char * argv[]) { @end // The main @implementation: -@implementation Shape +@implementation Shape @synthesize numOfSides = _numOfSides; @@ -604,14 +604,14 @@ int main (int argc, const char * argv[]) { @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and - (void)turnOnEngine; // all defined methods. @end -// Below is an example class implementing the protocol. +// Below is an example class implementing the protocol. #import "CarUtilities.h" // Import the @protocol file. @interface Car : NSObject // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. @end -// The @implementation needs to implement the @properties and methods for the protocol. +// The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. @@ -620,14 +620,14 @@ int main (int argc, const char * argv[]) { _engineOn = YES; // how you implement a method, it just requires that you do implement it. } // You may use a protocol as data as you know what methods and variables it has implemented. -- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { [objectOfSomeKind engineOn]; // You have access to object variables - [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind turnOnEngine]; // and the methods inside. [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. } @end -// Instances of Car now have access to the protocol. +// Instances of Car now have access to the protocol. Car *carInstance = [[Car alloc] init]; [carInstance setEngineOn:NO]; [carInstance turnOnEngine]; @@ -656,10 +656,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" -@protocol Sister; // These lines stop the recursion, resolving the issue. +@protocol Sister; // These lines stop the recursion, resolving the issue. @protocol Brother - + - (void)beNiceToSister:(id )sister; @end @@ -668,24 +668,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Blocks /////////////////////////////////////// -// Blocks are statements of code, just like a function, that are able to be used as data. +// Blocks are statements of code, just like a function, that are able to be used as data. // Below is a simple block with an integer argument that returns the argument plus 4. -int (^addUp)(int n); // Declare a variable to store the block. -void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. +int (^addUp)(int n); // Declare a variable to store the block. +void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. // Blocks have access to variables in the same scope. But the variables are readonly and the -// value passed to the block is the value of the variable when the block is created. +// value passed to the block is the value of the variable when the block is created. int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17. __block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar. -addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. +addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. NSLog(@"You may have as many lines in a block as you would like."); NSSet *blockSet; // Also, you can declare local variables. mutableVar = 32; // Assigning new value to __block variable. - return n + outsideVar; // Return statements are optional. + return n + outsideVar; // Return statements are optional. } -int addUp = add(10 + 16); // Calls block code with arguments. +int addUp = add(10 + 16); // Calls block code with arguments. // Blocks are often used as arguments to functions to be called later, or for callbacks. -@implementation BlockExample : NSObject - +@implementation BlockExample : NSObject + - (void)runBlock:(void (^)(NSString))block { NSLog(@"Block argument returns nothing and takes in a NSString object."); block(@"Argument given to block to execute."); // Calling block. @@ -697,19 +697,19 @@ int addUp = add(10 + 16); // Calls block code with arguments. /////////////////////////////////////// // Memory Management /////////////////////////////////////// -/* +/* For each object used in an application, memory must be allocated for that object. When the application -is done using that object, memory must be deallocated to ensure application efficiency. -Objective-C does not use garbage collection and instead uses reference counting. As long as +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as there is at least one reference to an object (also called "owning" an object), then the object -will be available to use (known as "ownership"). +will be available to use (known as "ownership"). When an instance owns an object, its reference counter is increments by one. When the object is released, the reference counter decrements by one. When reference count is zero, -the object is removed from memory. +the object is removed from memory. -With all object interactions, follow the pattern of: -(1) create the object, (2) use the object, (3) then free the object from memory. +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. */ MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object @@ -724,11 +724,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still // Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). -// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, // you must not use retain, relase, or autorelease -MyClass *arcMyClass = [[MyClass alloc] init]; +MyClass *arcMyClass = [[MyClass alloc] init]; // ... code using arcMyClass -// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, +// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, // there is no need. It will insert this release statement for you // As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong' diff --git a/ocaml.html.markdown b/ocaml.html.markdown index b0027fea..02435e4d 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -34,13 +34,13 @@ For a source file you can use "ocamlc -i /path/to/file.ml" command to print all names and type signatures. ``` -$ cat sigtest.ml +$ cat sigtest.ml let inc x = x + 1 let add x y = x + y -let a = 1 +let a = 1 -$ ocamlc -i ./sigtest.ml +$ ocamlc -i ./sigtest.ml val inc : int -> int val add : int -> int -> int val a : int @@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;; let sqr2 = sqr (-2) ;; (* Every function must have at least one argument. - Since some funcions naturally don't take any arguments, there's + Since some funcions naturally don't take any arguments, there's "unit" type for it that has the only one value written as "()" *) let print_hello () = print_endline "hello world" ;; @@ -301,7 +301,7 @@ let l = IntList (1, EmptyList) ;; (* Pattern matching is somewhat similar to switch statement in imperative languages, but offers a lot more expressive power. - Even though it may look complicated, it really boils down to matching + Even though it may look complicated, it really boils down to matching an argument against an exact value, a predicate, or a type constructor. The type system is what makes it so powerful. *) @@ -320,7 +320,7 @@ let is_one = function ;; (* Matching predicates, aka "guarded pattern matching". *) -let abs x = +let abs x = match x with | x when x < 0 -> -x | _ -> x diff --git a/perl6.html.markdown b/perl6.html.markdown index 8d425f7d..63c0830a 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -7,11 +7,11 @@ contributors: - ["Nami-Doc", "http://github.com/Nami-Doc"] --- -Perl 6 is a highly capable, feature-rich programming language made for at +Perl 6 is a highly capable, feature-rich programming language made for at least the next hundred years. The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on -the JVM and [the MoarVM](http://moarvm.com) and +the JVM and [the MoarVM](http://moarvm.com) and [prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/), [the Parrot VM](http://parrot.org/). @@ -143,7 +143,7 @@ sub with-mandatory-named(:$str!) { say "$str !"; } with-mandatory-named(str => "My String"); #=> My String ! -with-mandatory-named; # run time error: "Required named parameter not passed" +with-mandatory-named; # run time error: "Required named parameter not passed" with-mandatory-named(3); # run time error: "Too many positional parameters passed" ## If a sub takes a named boolean argument ... @@ -290,7 +290,7 @@ for @array -> $variable { # That means you can use `when` in a `for` just like you were in a `given`. for @array { say "I've got $_"; - + .say; # This is also allowed. # A dot call with no "topic" (receiver) is sent to `$_` by default $_.say; # the above and this are equivalent. @@ -378,8 +378,8 @@ say join(' ', @array[15..*]); #=> 15 16 17 18 19 # which is equivalent to: say join(' ', @array[-> $n { 15..$n }]); -# You can use that in most places you'd expect, even assigning to an array -my @numbers = ^20; +# You can use that in most places you'd expect, even assigning to an array +my @numbers = ^20; my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99 @numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite, # only the 15 needed values will be calculated. @@ -634,14 +634,14 @@ class A { method get-value { $.field + $!private-field; } - + method set-value($n) { # $.field = $n; # As stated before, you can't use the `$.` immutable version. $!field = $n; # This works, because `$!` is always mutable. - + $.other-field = 5; # This works, because `$.other-field` is `rw`. } - + method !private-method { say "This method is private to the class !"; } @@ -660,19 +660,19 @@ $a.other-field = 10; # This, however, works, because the public field class A { has $.val; - + submethod not-inherited { say "This method won't be available on B."; say "This is most useful for BUILD, which we'll see later"; } - + method bar { $.val * 5 } } class B is A { # inheritance uses `is` method foo { say $.val; } - + method bar { $.val * 10 } # this shadows A's `bar` } @@ -699,20 +699,20 @@ role PrintableVal { # you "import" a mixin (a "role") with "does": class Item does PrintableVal { has $.val; - + # When `does`-ed, a `role` literally "mixes in" the class: # the methods and fields are put together, which means a class can access # the private fields/methods of its roles (but not the inverse !): method access { say $!counter++; } - + # However, this: # method print {} # is ONLY valid when `print` isn't a `multi` with the same dispatch. # (this means a parent class can shadow a child class's `multi print() {}`, # but it's an error if a role does) - + # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods # will be shadowed, since the compiler will consider `ROLE` to be a class. } @@ -812,7 +812,7 @@ module Foo::Bar { say "Can't access me from outside, I'm my !"; } } - + say ++$n; # lexically-scoped variables are still available } say $Foo::Bar::n; #=> 1 @@ -1075,8 +1075,8 @@ say [//] Nil, Any, False, 1, 5; #=> False # Default value examples: -say [*] (); #=> 1 -say [+] (); #=> 0 +say [*] (); #=> 1 +say [+] (); #=> 0 # meaningless values, since N*1=N and N+0=N. say [//]; #=> (Any) # There's no "default value" for `//`. @@ -1335,7 +1335,7 @@ sub MAIN($name) { say "Hello, $name !" } # This produces: # $ perl6 cli.pl # Usage: -# t.pl +# t.pl # And since it's a regular Perl 6 sub, you can haz multi-dispatch: # (using a "Bool" for the named argument so that we can do `--replace` @@ -1348,7 +1348,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # This produces: # $ perl 6 cli.pl # Usage: -# t.pl [--replace] add +# t.pl [--replace] add # t.pl remove # t.pl [--as=] import (File) # As you can see, this is *very* powerful. @@ -1400,7 +1400,7 @@ for { # (explained in details below). .say } - + if rand == 0 ff rand == 1 { # compare variables other than `$_` say "This ... probably will never run ..."; } diff --git a/php.html.markdown b/php.html.markdown index 93066284..2b1fe1dc 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -515,7 +515,7 @@ class MyClass } } -// Class constants can always be accessed statically +// Class constants can always be accessed statically echo MyClass::MY_CONST; // Outputs 'value'; echo MyClass::$staticVar; // Outputs 'static'; diff --git a/purescript.html.markdown b/purescript.html.markdown index 6bff7545..a006cdff 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -70,12 +70,12 @@ true && (9 >= 19 || 1 < 2) -- true -- Safe access return Maybe a head [1,2,3] -- Just (1) -tail [3,2,1] -- Just ([2,1]) +tail [3,2,1] -- Just ([2,1]) init [1,2,3] -- Just ([1,2]) last [3,2,1] -- Just (1) -- Random access - indexing [3,4,5,6,7] !! 2 -- Just (5) --- Range +-- Range 1..5 -- [1,2,3,4,5] length [2,2,2] -- 3 drop 3 [5,4,3,2,1] -- [2,1] @@ -129,10 +129,10 @@ first :: [Number] -> Number first (x:_) = x first [3,4,5] -- 3 second :: [Number] -> Number -second (_:y:_) = y +second (_:y:_) = y second [3,4,5] -- 4 sumTwo :: [Number] -> [Number] -sumTwo (x:y:rest) = (x+y) : rest +sumTwo (x:y:rest) = (x+y) : rest sumTwo [2,3,4,5,6] -- [5,4,5,6] -- sumTwo doesn't handle when the array is empty or just have one @@ -161,7 +161,7 @@ ecoTitle {title: "The Quantum Thief"} -- Object does not have property author -- Lambda expressions (\x -> x*x) 3 -- 9 -(\x y -> x*x + y*y) 4 5 -- 41 +(\x y -> x*x + y*y) 4 5 -- 41 sqr = \x -> x*x -- Currying @@ -187,7 +187,7 @@ foldr (+) 0 (1..10) -- 55 sum (1..10) -- 55 product (1..10) -- 3628800 --- Testing with predicate +-- Testing with predicate any even [1,2,3] -- true all even [1,2,3] -- false diff --git a/python3.html.markdown b/python3.html.markdown index 971ca0a4..acd6187c 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -96,7 +96,7 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variable refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to @@ -256,8 +256,8 @@ empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} -# Note keys for dictionaries have to be immutable types. This is to ensure that -# the key can be converted to a constant hash value for quick look-ups. +# Note keys for dictionaries have to be immutable types. This is to ensure that +# the key can be converted to a constant hash value for quick look-ups. # Immutable types include ints, floats, strings, tuples. invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. @@ -423,7 +423,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances print("We can clean up resources here") - + # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: diff --git a/r.html.markdown b/r.html.markdown index d3d725d3..93751df5 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -36,8 +36,8 @@ head(rivers) # peek at the data set length(rivers) # how many rivers were measured? # 141 summary(rivers) # what are some summary statistics? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 # make a stem-and-leaf plot (a histogram-like data visualization) stem(rivers) @@ -54,14 +54,14 @@ stem(rivers) # 14 | 56 # 16 | 7 # 18 | 9 -# 20 | +# 20 | # 22 | 25 # 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | # 36 | 1 stem(log(rivers)) # Notice that the data are neither normal nor log-normal! @@ -70,7 +70,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # The decimal point is 1 digit(s) to the left of the | # # 48 | 1 -# 50 | +# 50 | # 52 | 15578 # 54 | 44571222466689 # 56 | 023334677000124455789 @@ -85,7 +85,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # 74 | 84 # 76 | 56 # 78 | 4 -# 80 | +# 80 | # 82 | 2 # make a histogram: @@ -108,7 +108,7 @@ sort(discoveries) # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 stem(discoveries, scale=2) -# +# # The decimal point is at the | # # 0 | 000000000 @@ -122,14 +122,14 @@ stem(discoveries, scale=2) # 8 | 0 # 9 | 0 # 10 | 0 -# 11 | +# 11 | # 12 | 0 max(discoveries) # 12 summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times round(runif(7, min=.5, max=6.5)) @@ -262,7 +262,7 @@ class(NULL) # NULL parakeet = c("beak", "feathers", "wings", "eyes") parakeet # => -# [1] "beak" "feathers" "wings" "eyes" +# [1] "beak" "feathers" "wings" "eyes" parakeet <- NULL parakeet # => @@ -279,7 +279,7 @@ as.numeric("Bilbo") # => # [1] NA # Warning message: -# NAs introduced by coercion +# NAs introduced by coercion # Also note: those were just the basic data types # There are many more data types, such as for dates, time series, etc. @@ -419,10 +419,10 @@ mat %*% t(mat) mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix # Again, note what happened! diff --git a/racket.html.markdown b/racket.html.markdown index e345db8b..0fe3f030 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -285,7 +285,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' (= 3 3.0) ; => #t (= 2 1) ; => #f -;; `eq?' returns #t if 2 arguments refer to the same object (in memory), +;; `eq?' returns #t if 2 arguments refer to the same object (in memory), ;; #f otherwise. ;; In other words, it's a simple pointer comparison. (eq? '() '()) ; => #t, since there exists only one empty list in memory @@ -320,7 +320,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' (eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f ;; `equal?' supports the comparison of the following datatypes: -;; strings, byte strings, pairs, mutable pairs, vectors, boxes, +;; strings, byte strings, pairs, mutable pairs, vectors, boxes, ;; hash tables, and inspectable structures. ;; for other datatypes, `equal?' and `eqv?' return the same result. (equal? 3 3.0) ; => #f diff --git a/red.html.markdown b/red.html.markdown index f33060c4..05da3c3f 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -8,31 +8,31 @@ contributors: --- -Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks. +Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks. It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language. Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in. -Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon, -Red/System, covers the more basic needs of programming like C can, being closer to the metal. +Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon, +Red/System, covers the more basic needs of programming like C can, being closer to the metal. -Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level -from the metal to the meta without the aid of other stack tools. -Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain +Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level +from the metal to the meta without the aid of other stack tools. +Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB. Ready to learn your first Red? ``` -All text before the header will be treated as comment, as long as you avoid using the -word "red" starting with a capital "R" in this pre-header text. This is a temporary -shortcoming of the used lexer but most of the time you start your script or program -with the header itself. -The header of a red script is the capitalized word "red" followed by a +All text before the header will be treated as comment, as long as you avoid using the +word "red" starting with a capital "R" in this pre-header text. This is a temporary +shortcoming of the used lexer but most of the time you start your script or program +with the header itself. +The header of a red script is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. -The block of brackets can be filled with useful information about this script or +The block of brackets can be filled with useful information about this script or program: the author's name, the filename, the version, the license, a summary of what the program does or any other files it needs. -The red/System header is just like the red header, only saying "red/System" and +The red/System header is just like the red header, only saying "red/System" and not "red". Red [] @@ -49,21 +49,21 @@ comment { ; Your program's entry point is the first executable code that is found ; no need to restrict this to a 'main' function. -; Valid variable names start with a letter and can contain numbers, -; variables containing only capital A thru F and numbers and ending with 'h' are -; forbidden, because that is how hexadecimal numbers are expressed in Red and +; Valid variable names start with a letter and can contain numbers, +; variables containing only capital A thru F and numbers and ending with 'h' are +; forbidden, because that is how hexadecimal numbers are expressed in Red and ; Red/System. ; assign a value to a variable using a colon ":" my-name: "Red" -reason-for-using-the-colon: {Assigning values using the colon makes - the equality sign "=" exclusively usable for comparisons purposes, - exactly what "=" was intended for in the first place! +reason-for-using-the-colon: {Assigning values using the colon makes + the equality sign "=" exclusively usable for comparisons purposes, + exactly what "=" was intended for in the first place! Remember this y = x + 1 and x = 1 => y = 2 stuff from school? } is-this-name-valid?: true -; print output using print, or prin for printing without a newline or linefeed at the +; print output using print, or prin for printing without a newline or linefeed at the ; end of the printed text. prin " My name is " print my-name @@ -77,20 +77,20 @@ My name is Red ; ; Datatypes ; -; If you know Rebol, you probably have noticed it has lots of datatypes. Red -; does not have yet all those types, but as Red want to be close to Rebol it +; If you know Rebol, you probably have noticed it has lots of datatypes. Red +; does not have yet all those types, but as Red want to be close to Rebol it ; will have a lot of datatypes. -; You can recognize types by the exclamation sign at the end. But beware -; names ending with an exclamation sign are allowed. -; Some of the available types are integer! string! block! - -; Declaring variables before using them? -; Red knows by itself what variable is best to use for the data you want to use it -; for. -; A variable declaration is not always necessary. +; You can recognize types by the exclamation sign at the end. But beware +; names ending with an exclamation sign are allowed. +; Some of the available types are integer! string! block! + +; Declaring variables before using them? +; Red knows by itself what variable is best to use for the data you want to use it +; for. +; A variable declaration is not always necessary. ; It is considered good coding practise to declare your variables, ; but it is not forced upon you by Red. -; You can declare a variable and specify its type. a variable's type determines its +; You can declare a variable and specify its type. a variable's type determines its ; size in bytes. ; Variables of integer! type are usually 4 bytes or 32 bits @@ -101,7 +101,7 @@ my-integer: 0 type? my-integer integer! -; A variable can be initialized using another variable that gets initialized +; A variable can be initialized using another variable that gets initialized ; at the same time. i2: 1 + i1: 1 @@ -111,9 +111,9 @@ i2 - i1 ; result 1 i2 * i1 ; result 2 i1 / i2 ; result 0 (0.5, but truncated towards 0) -; Comparison operators are probably familiar, and unlike in other languages you +; Comparison operators are probably familiar, and unlike in other languages you ; only need a single '=' sign for comparison. -; There is a boolean like type in Red. It has values true and false, but also the +; There is a boolean like type in Red. It has values true and false, but also the ; values on/off or yes/no can be used 3 = 2 ; result false @@ -125,15 +125,15 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) ; ; Control Structures -; +; ; if -; Evaluate a block of code if a given condition is true. IF does not return any value, +; Evaluate a block of code if a given condition is true. IF does not return any value, ; so cannot be used in an expression. if a < 0 [print "a is negative"] ; either -; Evaluate a block of code if a given condition is true, else evaluate an alternative -; block of code. If the last expressions in both blocks have the same type, EITHER can +; Evaluate a block of code if a given condition is true, else evaluate an alternative +; block of code. If the last expressions in both blocks have the same type, EITHER can ; be used inside an expression. either a < 0 [ either a = 0 [ @@ -147,7 +147,7 @@ either a < 0 [ print ["a is " msg lf] -; There is an alternative way to write this +; There is an alternative way to write this ; (Which is allowed because all code paths return a value of the same type): msg: either a < 0 [ @@ -162,7 +162,7 @@ msg: either a < 0 [ print ["a is " msg lf] ; until -; Loop over a block of code until the condition at end of block, is met. +; Loop over a block of code until the condition at end of block, is met. ; UNTIL does not return any value, so it cannot be used in an expression. c: 5 until [ @@ -172,11 +172,11 @@ until [ ] ; will output: ooooo -; Note that the loop will always be evaluated at least once, even if the condition is +; Note that the loop will always be evaluated at least once, even if the condition is ; not met from the beginning. ; while -; While a given condition is met, evaluate a block of code. +; While a given condition is met, evaluate a block of code. ; WHILE does not return any value, so it cannot be used in an expression. c: 5 while [c > 0][ @@ -206,7 +206,7 @@ print twice b ; will output 6. ## Further Reading -The main source for information about Red is the [Red language homepage](http://www.red-lang.org). +The main source for information about Red is the [Red language homepage](http://www.red-lang.org). The source can be found on [github](https://github.com/red/red). @@ -218,4 +218,4 @@ Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/r Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). -You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html). +You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html). diff --git a/rust.html.markdown b/rust.html.markdown index 3157fcf4..b2854b0c 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -6,20 +6,20 @@ filename: learnrust.rs --- Rust is a programming language developed by Mozilla Research. -Rust combines low-level control over performance with high-level convenience and -safety guarantees. +Rust combines low-level control over performance with high-level convenience and +safety guarantees. -It achieves these goals without requiring a garbage collector or runtime, making +It achieves these goals without requiring a garbage collector or runtime, making it possible to use Rust libraries as a "drop-in replacement" for C. -Rust’s first release, 0.1, occurred in January 2012, and for 3 years development +Rust’s first release, 0.1, occurred in January 2012, and for 3 years development moved so quickly that until recently the use of stable releases was discouraged -and instead the general advice was to use nightly builds. +and instead the general advice was to use nightly builds. -On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward +On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward compatibility. Improvements to compile times and other aspects of the compiler are currently available in the nightly builds. Rust has adopted a train-based release -model with regular releases every six weeks. Rust 1.1 beta was made available at +model with regular releases every six weeks. Rust 1.1 beta was made available at the same time of the release of Rust 1.0. Although Rust is a relatively low-level language, Rust has some functional diff --git a/self.html.markdown b/self.html.markdown index 69524a84..9290a0c9 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -5,13 +5,13 @@ contributors: filename: learnself.self --- -Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger. +Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger. Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots. # Constructing objects -The inbuild Self parser can construct objects, including method objects. +The inbuild Self parser can construct objects, including method objects. ``` "This is a comment" @@ -38,18 +38,18 @@ The inbuild Self parser can construct objects, including method objects. x <- 20. |) -"An object which understands the method 'doubleX' which +"An object which understands the method 'doubleX' which doubles the value of x and then returns the object" (| x <- 20. doubleX = (x: x * 2. self) |) -"An object which understands all the messages -that 'traits point' understands". The parser -looks up 'traits point' by sending the messages -'traits' then 'point' to a known object called -the 'lobby'. It looks up the 'true' object by +"An object which understands all the messages +that 'traits point' understands". The parser +looks up 'traits point' by sending the messages +'traits' then 'point' to a known object called +the 'lobby'. It looks up the 'true' object by also sending the message 'true' to the lobby." (| parent* = traits point. x = 7. @@ -63,19 +63,19 @@ also sending the message 'true' to the lobby." Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace. ``` -"unary message, sends 'printLine' to the object '23' +"unary message, sends 'printLine' to the object '23' which prints the string '23' to stdout and returns the receiving object (ie 23)" 23 printLine "sends the message '+' with '7' to '23', then the message '*' with '8' to the result" -(23 + 7) * 8 +(23 + 7) * 8 "sends 'power:' to '2' with '8' returns 256" -2 power: 8 +2 power: 8 -"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. +"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. Returns 1, the index of 'e' in 'hello'." -'hello' keyOf: 'e' IfAbsent: -1 +'hello' keyOf: 'e' IfAbsent: -1 ``` # Blocks @@ -90,13 +90,13 @@ Examples of the use of a block: ``` "returns 'HELLO'" -'hello' copyMutable mapBy: [|:c| c capitalize] +'hello' copyMutable mapBy: [|:c| c capitalize] "returns 'Nah'" -'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] +'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] "returns 'HaLLO'" -'hello' copyMutable mapBy: [|:c| +'hello' copyMutable mapBy: [|:c| c = 'e' ifTrue: [c capitalize] False: ['a']] ``` @@ -105,7 +105,7 @@ Multiple expressions are separated by a period. ^ returns immediately. ``` "returns An 'E'! How icky!" -'hello' copyMutable mapBy: [|:c. tmp <- ''| +'hello' copyMutable mapBy: [|:c. tmp <- ''| tmp: c capitalize. tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!']. c capitalize @@ -119,7 +119,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t x: 15. "Repeatedly sends 'value' to the first block while the result of sending 'value' to the second block is the 'true' object" - [x > 0] whileTrue: [x: x - 1]. + [x > 0] whileTrue: [x: x - 1]. x ] value ``` @@ -130,12 +130,12 @@ Methods are like blocks but they are not within a context but instead are stored ``` "Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'. -Sending the message 'reduceXTo: 10' to this object will put +Sending the message 'reduceXTo: 10' to this object will put the object '10' in the 'x' slot and return the original object" -(| +(| x <- 50. reduceXTo: y = ( - [x > y] whileTrue: [x: x - 1]. + [x > y] whileTrue: [x: x - 1]. self) |) . diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index a434a1ad..3b388505 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -11,28 +11,28 @@ contributors: Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`. -##Allowable characters: -- a-z -- A-Z -- 0-9 +##Allowable characters: +- a-z +- A-Z +- 0-9 - .+/\*~<>@%|&? - blank, tab, cr, ff, lf ##Variables: -- variables must be declared before use -- shared vars must begin with uppercase -- local vars must begin with lowercase +- variables must be declared before use +- shared vars must begin with uppercase +- local vars must begin with lowercase - reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk` -##Variable scope: -- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` -- Method Temporary: local to a method -- Block Temporary: local to a block -- Pool: variables in a Dictionary object +##Variable scope: +- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` +- Method Temporary: local to a method +- Block Temporary: local to a block +- Pool: variables in a Dictionary object - Method Parameters: automatic local vars created as a result of message call with params - Block Parameters: automatic local vars created as a result of value: message call -- Class: shared with all instances of one class & its subclasses -- Class Instance: unique to each instance of a class +- Class: shared with all instances of one class & its subclasses +- Class Instance: unique to each instance of a class - Instance Variables: unique to each instance `"Comments are enclosed in quotes"` @@ -53,7 +53,7 @@ Transcript cr. "carriage return / l Transcript endEntry. "flush the output buffer" ``` -##Assignment: +##Assignment: ``` | x y | x _ 4. "assignment (Squeak) <-" @@ -72,7 +72,7 @@ y := x deepCopy. "copy object and ins y := x veryDeepCopy. "complete tree copy using a dictionary" ``` -##Constants: +##Constants: ``` | b | b := true. "true constant" @@ -93,7 +93,7 @@ x := #('abc' 2 $a). "mixing of types all ``` -## Booleans: +## Booleans: ``` | b x y | x := 1. y := 2. @@ -132,7 +132,7 @@ b := $A isLowercase. "test if lower case ``` -## Arithmetic expressions: +## Arithmetic expressions: ``` | x | x := 6 + 3. "addition" @@ -190,7 +190,7 @@ x := 100 atRandom. "quick random number ``` -##Bitwise Manipulation: +##Bitwise Manipulation: ``` | b x | x := 16rFF bitAnd: 16r0F. "and bits" @@ -207,7 +207,7 @@ b := 16rFF noMask: 16r0F. "test if all bits se ``` -## Conversion: +## Conversion: ``` | x | x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" @@ -223,15 +223,15 @@ x := 15 storeStringBase: 16. ``` -## Blocks: -- blocks are objects and may be assigned to a variable -- value is last expression evaluated unless explicit return -- blocks may be nested -- specification [ arguments | | localvars | expressions ] -- Squeak does not currently support localvars in blocks -- max of three arguments allowed -- `^`expression terminates block & method (exits all nested blocks) -- blocks intended for long term storage should not contain `^` +## Blocks: +- blocks are objects and may be assigned to a variable +- value is last expression evaluated unless explicit return +- blocks may be nested +- specification [ arguments | | localvars | expressions ] +- Squeak does not currently support localvars in blocks +- max of three arguments allowed +- `^`expression terminates block & method (exits all nested blocks) +- blocks intended for long term storage should not contain `^` ``` | x y z | @@ -241,18 +241,18 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu "x := [ | z | z := 1.]. *** localvars not available in squeak blocks" ``` -## Method calls: -- unary methods are messages with no arguments -- binary methods -- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance) -- accessing (get/set methods) -- testing (boolean tests - is) -- comparing (boolean tests with parameter -- displaying (gui related methods) -- printing (methods for printing) -- updating (receive notification of changes) -- private (methods private to class) -- instance-creation (class methods for creating instance) +## Method calls: +- unary methods are messages with no arguments +- binary methods +- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance) +- accessing (get/set methods) +- testing (boolean tests - is) +- comparing (boolean tests with parameter +- displaying (gui related methods) +- printing (methods for printing) +- updating (receive notification of changes) +- private (methods private to class) +- instance-creation (class methods for creating instance) ``` | x | x := 2 sqrt. "unary message" @@ -299,7 +299,7 @@ switch at: $C put: [Transcript show: 'Case C'; cr]. result := (switch at: $B) value. ``` -## Iteration statements: +## Iteration statements: ``` | x y | x := 4. y := 1. @@ -311,7 +311,7 @@ x timesRepeat: [y := y * 2]. "times repear loop ( #(5 4 3) do: [:a | x := x + a]. "iterate over array elements" ``` -## Character: +## Character: ``` | x y | x := $A. "character assignment" @@ -544,7 +544,7 @@ y := x asSet. "convert to set coll ``` ## Set: like Bag except duplicates not allowed -## IdentitySet: uses identity test (== rather than =) +## IdentitySet: uses identity test (== rather than =) ``` | b x y sum max | x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" @@ -603,7 +603,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -##Associations: +##Associations: ``` | x y | x := #myVar->'hello'. diff --git a/swift.html.markdown b/swift.html.markdown index 86a0b89a..a40e86c8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -3,7 +3,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] - - ["Joey Huang", "http://github.com/kamidox"] + - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] filename: learnswift.swift --- @@ -74,7 +74,7 @@ if someOptionalString != nil { if someOptionalString!.hasPrefix("opt") { print("has the prefix") } - + let empty = someOptionalString?.isEmpty } someOptionalString = nil @@ -99,7 +99,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." /* Comment here - + /* Nested comments are also supported */ @@ -298,7 +298,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { let names = [String]() - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -329,7 +329,7 @@ public class Shape { internal class Rect: Shape { var sideLength: Int = 1 - + // Custom getter and setter property private var perimeter: Int { get { @@ -340,11 +340,11 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) - + // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` @@ -354,19 +354,19 @@ internal class Rect: Shape { print(someIdentifier) } } - + init(sideLength: Int) { self.sideLength = sideLength // always super.init last when init custom properties super.init() } - + func shrink() { if sideLength > 0 { --sideLength } } - + override func getArea() -> Int { return sideLength * sideLength } @@ -398,13 +398,13 @@ class Circle: Shape { override func getArea() -> Int { return 3 * radius * radius } - + // Place a question mark postfix after `init` is an optional init // which can return nil init?(radius: Int) { self.radius = radius super.init() - + if radius <= 0 { return nil } @@ -458,7 +458,7 @@ enum Furniture { case Desk(height: Int) // Associate with String and Int case Chair(String, Int) - + func description() -> String { switch self { case .Desk(let height): @@ -497,7 +497,7 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 @@ -532,7 +532,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } diff --git a/tcl.html.markdown b/tcl.html.markdown index 3982807f..b90bd690 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -14,7 +14,7 @@ programming language. It can also be used as a portable C library, even in cases where no scripting capability is needed, as it provides data structures such as dynamic strings, lists, and hash tables. The C library also provides portable functionality for loading dynamic libraries, string formatting and -code conversion, filesystem operations, network operations, and more. +code conversion, filesystem operations, network operations, and more. Various features of Tcl stand out: * Convenient cross-platform networking API @@ -58,14 +58,14 @@ lighter that that of Lisp, just gets out of the way. #! /bin/env tclsh ################################################################################ -## 1. Guidelines +## 1. Guidelines ################################################################################ # Tcl is not Bash or C! This needs to be said because standard shell quoting # habits almost work in Tcl and it is common for people to pick up Tcl and try # to get by with syntax they know from another language. It works at first, # but soon leads to frustration with more complex scripts. - + # Braces are just a quoting mechanism, not a code block constructor or a list # constructor. Tcl doesn't have either of those things. Braces are used, # though, to escape special characters in procedure bodies and in strings that @@ -73,7 +73,7 @@ lighter that that of Lisp, just gets out of the way. ################################################################################ -## 2. Syntax +## 2. Syntax ################################################################################ # Every line is a command. The first word is the name of the command, and @@ -83,13 +83,13 @@ lighter that that of Lisp, just gets out of the way. # are used, they are not a string constructor, but just another escaping # character. -set greeting1 Sal +set greeting1 Sal set greeting2 ut set greeting3 ations #semicolon also delimits commands -set greeting1 Sal; set greeting2 ut; set greeting3 ations +set greeting1 Sal; set greeting2 ut; set greeting3 ations # Dollar sign introduces variable substitution @@ -126,11 +126,11 @@ puts lots\nof\n\n\n\n\n\nnewlines set somevar { This is a literal $ sign, and this \} escaped brace remains uninterpreted -} +} # In a word enclosed in double quotes, whitespace characters lose their special -# meaning +# meaning set name Neo set greeting "Hello, $name" @@ -178,7 +178,7 @@ set greeting "Hello $people::person1::name" ################################################################################ -## 3. A Few Notes +## 3. A Few Notes ################################################################################ # All other functionality is implemented via commands. From this point on, @@ -193,8 +193,8 @@ set greeting "Hello $people::person1::name" namespace delete :: -# Because of name resolution behaviour, it's safer to use the "variable" command to -# declare or to assign a value to a namespace. If a variable called "name" already +# Because of name resolution behaviour, it's safer to use the "variable" command to +# declare or to assign a value to a namespace. If a variable called "name" already # exists in the global namespace, using "set" here will assign a value to the global variable # instead of creating a new variable in the local namespace. namespace eval people { @@ -210,7 +210,7 @@ set people::person1::name Neo ################################################################################ -## 4. Commands +## 4. Commands ################################################################################ # Math can be done with the "expr" command. @@ -295,7 +295,7 @@ while {$i < 10} { # A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values -set amounts 10\ 33\ 18 +set amounts 10\ 33\ 18 set amount [lindex $amounts 1] @@ -339,7 +339,7 @@ eval {set name Neo} eval [list set greeting "Hello, $name"] -# Therefore, when using "eval", use [list] to build up a desired command +# Therefore, when using "eval", use [list] to build up a desired command set command {set name} lappend command {Archibald Sorbisol} eval $command @@ -355,7 +355,7 @@ eval $command ;# There is an error here, because there are too many arguments \ # This mistake can easily occur with the "subst" command. set replacement {Archibald Sorbisol} set command {set name $replacement} -set command [subst $command] +set command [subst $command] eval $command ;# The same error as before: too many arguments to "set" in \ {set name Archibald Sorbisol} @@ -364,12 +364,12 @@ eval $command ;# The same error as before: too many arguments to "set" in \ # command. set replacement [list {Archibald Sorbisol}] set command {set name $replacement} -set command [subst $command] +set command [subst $command] eval $command # It is extremely common to see the "list" command being used to properly -# format values that are substituted into Tcl script templates. There are +# format values that are substituted into Tcl script templates. There are # several examples of this, below. @@ -422,12 +422,12 @@ proc while {condition script} { # The "coroutine" command creates a separate call stack, along with a command # to enter that call stack. The "yield" command suspends execution in that -# stack. +# stack. proc countdown {} { #send something back to the initial "coroutine" command yield - set count 3 + set count 3 while {$count > 1} { yield [incr count -1] } @@ -435,12 +435,12 @@ proc countdown {} { } coroutine countdown1 countdown coroutine countdown2 countdown -puts [countdown 1] ;# -> 2 -puts [countdown 2] ;# -> 2 -puts [countdown 1] ;# -> 1 -puts [countdown 1] ;# -> 0 +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 puts [coundown 1] ;# -> invalid command name "countdown1" -puts [countdown 2] ;# -> 1 +puts [countdown 2] ;# -> 1 ``` diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index f9906e96..bdfdcc10 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -17,7 +17,7 @@ Module Module1 ' This navigation system is explained however as we go deeper into this ' tutorial, you'll understand what it all means. Console.Title = ("Learn X in Y Minutes") - Console.WriteLine("NAVIGATION") 'Display + Console.WriteLine("NAVIGATION") 'Display Console.WriteLine("") Console.ForegroundColor = ConsoleColor.Green Console.WriteLine("1. Hello World Output") @@ -39,13 +39,13 @@ Module Module1 Case "2" 'Hello Input Console.Clear() HelloWorldInput() - Case "3" 'Calculating Whole Numbers + Case "3" 'Calculating Whole Numbers Console.Clear() CalculatingWholeNumbers() - Case "4" 'Calculting Decimal Numbers + Case "4" 'Calculting Decimal Numbers Console.Clear() CalculatingDecimalNumbers() - Case "5" 'Working Calcculator + Case "5" 'Working Calcculator Console.Clear() WorkingCalculator() Case "6" 'Using Do While Loops @@ -74,7 +74,7 @@ Module Module1 'One - I'm using numbers to help with the above navigation when I come back 'later to build it. - 'We use private subs to seperate different sections of the program. + 'We use private subs to seperate different sections of the program. Private Sub HelloWorldOutput() 'Title of Console Application Console.Title = "Hello World Ouput | Learn X in Y Minutes" @@ -172,7 +172,7 @@ Module Module1 'program more than once. Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" Dim answer As String 'We use the variable "String" as the answer is text - Do 'We start the program with + Do 'We start the program with Console.Write("First number: ") Dim a As Double = Console.ReadLine Console.Write("Second number: ") @@ -192,7 +192,7 @@ Module Module1 Console.WriteLine(" = " + f.ToString.PadLeft(3)) Console.ReadLine() 'Ask the question, does the user wish to continue? Unfortunately it - 'is case sensitive. + 'is case sensitive. Console.Write("Would you like to continue? (yes / no)") 'The program grabs the variable and prints and starts again. answer = Console.ReadLine @@ -208,8 +208,8 @@ Module Module1 Console.Title = "Using For Loops | Learn X in Y Minutes" 'Declare Variable and what number it should count down in Step -1, - 'Step -2, Step -3 ect. - For i As Integer = 10 To 0 Step -1 + 'Step -2, Step -3 ect. + For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) 'Print the value of the counter Next i 'Calculate new value Console.WriteLine("Start") 'Lets start the program baby!! @@ -274,8 +274,8 @@ End Module ## References -I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. +I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. -I created a more indepth Visual Basic tutorial for those who would like to learn more. +I created a more indepth Visual Basic tutorial for those who would like to learn more. -The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program. +The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program. diff --git a/xml.html.markdown b/xml.html.markdown index 059ea132..d407512d 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -38,10 +38,10 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i @@ -54,8 +54,8 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i 2 - Elements -> That's pure data. That's what the parser will retrieve from the XML file. Elements appear between the open and close tags. --> - - + + computer.gif @@ -68,14 +68,14 @@ A XML document is well-formated if it is syntactically correct. However, it is possible to inject more constraints in the document, using document definitions, such as DTD and XML Schema. -A XML document which follows a document definition is called valid, -regarding that document. +A XML document which follows a document definition is called valid, +regarding that document. With this tool, you can check the XML data outside the application logic. ```xml - -- cgit v1.2.3 From e1ac6209a8d3f43e7a018d79454fb1095b3314c0 Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Wed, 7 Oct 2015 23:45:01 -0400 Subject: [c/en] Added a section for header files. Added a section for header files. Included a discussion of what belongs in a header file and what does not. --- c.html.markdown | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index db2ac930..f1201eac 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - ["Marco Scannadinari", "https://marcoms.github.io"] - + - ["Zachary Ferguson", "https://github.io/zfergus2"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -630,6 +630,54 @@ typedef void (*my_fnp_type)(char *); ``` +Header files are an important part of c as they allow for the connection of c +source files and can simplify code and definitions by seperating them into +seperate files. + +Header files are syntaxtically similar to c source files but reside in ".h" +files. They can be included in your c source file by using the precompiler +command #include "example.h", given that example.h exists in the same directory +as the c file. + +```c +/* A safe guard to prevent the header from being defined too many times. This */ +/* happens in the case of circle dependency, the contents of the header is */ +/* already defined. */ +#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */ +#define EXAMPLE_H /* Define the macro EXAMPLE_H. */ + +/* Other headers can be included in headers and therefore transitively */ +/* included into files that include this header. */ +#include + +/* Like c source files macros can be defined in headers and used in files */ +/* that include this header file. */ +#define EXAMPLE_NAME "Dennis Ritchie" +/* Function macros can also be defined. */ +#define ADD(a, b) (a + b) + +/* Structs and typedefs can be used for consistency between files. */ +typedef struct node +{ + int val; + struct node *next; +} Node; + +/* So can enumerations. */ +enum traffic_light_state {GREEN, YELLOW, RED}; + +/* Function prototypes can also be defined here for use in multiple files, */ +/* but it is bad practice to define the function in the header. Definitions */ +/* should instead be put in a c file. */ +Node createLinkedList(int *vals, int len); + +/* Beyond the above elements, other definitions should be left to a c source */ +/* file. Excessive includeds or definitions should, also not be contained in */ +/* a header file but instead put into separate headers or a c file. */ + +#endif /* End of the if precompiler directive. */ + +``` ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -- cgit v1.2.3 From 3c02fdb8e496816b0fd615e029fad4a8ed9f4585 Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Wed, 7 Oct 2015 23:49:46 -0400 Subject: Revert "[c/en] Added a section for header files." This reverts commit e1ac6209a8d3f43e7a018d79454fb1095b3314c0. --- c.html.markdown | 50 +------------------------------------------------- 1 file changed, 1 insertion(+), 49 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index f1201eac..db2ac930 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - ["Marco Scannadinari", "https://marcoms.github.io"] - - ["Zachary Ferguson", "https://github.io/zfergus2"] + --- Ah, C. Still **the** language of modern high-performance computing. @@ -630,54 +630,6 @@ typedef void (*my_fnp_type)(char *); ``` -Header files are an important part of c as they allow for the connection of c -source files and can simplify code and definitions by seperating them into -seperate files. - -Header files are syntaxtically similar to c source files but reside in ".h" -files. They can be included in your c source file by using the precompiler -command #include "example.h", given that example.h exists in the same directory -as the c file. - -```c -/* A safe guard to prevent the header from being defined too many times. This */ -/* happens in the case of circle dependency, the contents of the header is */ -/* already defined. */ -#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */ -#define EXAMPLE_H /* Define the macro EXAMPLE_H. */ - -/* Other headers can be included in headers and therefore transitively */ -/* included into files that include this header. */ -#include - -/* Like c source files macros can be defined in headers and used in files */ -/* that include this header file. */ -#define EXAMPLE_NAME "Dennis Ritchie" -/* Function macros can also be defined. */ -#define ADD(a, b) (a + b) - -/* Structs and typedefs can be used for consistency between files. */ -typedef struct node -{ - int val; - struct node *next; -} Node; - -/* So can enumerations. */ -enum traffic_light_state {GREEN, YELLOW, RED}; - -/* Function prototypes can also be defined here for use in multiple files, */ -/* but it is bad practice to define the function in the header. Definitions */ -/* should instead be put in a c file. */ -Node createLinkedList(int *vals, int len); - -/* Beyond the above elements, other definitions should be left to a c source */ -/* file. Excessive includeds or definitions should, also not be contained in */ -/* a header file but instead put into separate headers or a c file. */ - -#endif /* End of the if precompiler directive. */ - -``` ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -- cgit v1.2.3 From 7aca9100a042f3813d383f979f8c32a95ecc4bbb Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Thu, 8 Oct 2015 00:00:37 -0400 Subject: [java/en] Fixed repitions --- java.html.markdown | 59 ++---------------------------------------------------- 1 file changed, 2 insertions(+), 57 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 61478968..ba602d2e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -513,12 +513,8 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, } } -<<<<<<< HEAD -// Abstract Classes -======= - // Abstract Classes ->>>>>>> adambard/master + // Abstract Class declaration syntax // abstract extends { // // Constants and variables @@ -535,7 +531,6 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, public abstract class Animal { -<<<<<<< HEAD public abstract void makeSound(); // Method can have a body @@ -561,38 +556,10 @@ public abstract class Animal { System.out.println("I am abstract"); } -======= - public abstract void makeSound(); - - // Method can have a body - public void eat() - { - System.out.println("I am an animal and I am Eating."); - // Note: We can access private variable here. - age = 30; - } - - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. - private int age; - - public void printAge() - { - System.out.println(age); - } - - // Abstract classes can have main function. - public static void main(String[] args) - { - System.out.println("I am abstract"); - } ->>>>>>> adambard/master } class Dog extends Animal { -<<<<<<< HEAD // Note still have to override the abstract methods in the // abstract class. @Override @@ -614,32 +581,10 @@ class Dog extends Animal pluto.eat(); pluto.printAge(); } -======= - // Note still have to override the abstract methods in the - // abstract class. - @Override - public void makeSound() - { - System.out.println("Bark"); - // age = 30; ==> ERROR! age is private to Animal - } - - // NOTE: You will get an error if you used the - // @Override annotation here, since java doesn't allow - // overriding of static methods. - // What is happening here is called METHOD HIDING. - // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ - public static void main(String[] args) - { - Dog pluto = new Dog(); - pluto.makeSound(); - pluto.eat(); - pluto.printAge(); - } ->>>>>>> adambard/master } // Final Classes + // Final Class declaration syntax // final { // // Constants and variables -- cgit v1.2.3 From 707c8db171cb5239682332f14fd2098901741c63 Mon Sep 17 00:00:00 2001 From: Valentine Silvansky Date: Thu, 8 Oct 2015 10:00:13 +0300 Subject: Add generics operator in Swift --- swift.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/swift.html.markdown b/swift.html.markdown index a40e86c8..75535e43 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -574,4 +574,18 @@ print(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare print(mySquare.sideLength) // 12 + +// Operators can also be generics +infix operator <-> {} +func <-> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" ``` -- cgit v1.2.3 From 9796759379d77a848ef84f8c1019672b87b90822 Mon Sep 17 00:00:00 2001 From: himanshu81494 Date: Thu, 8 Oct 2015 14:44:10 +0530 Subject: Update c.html.markdown --- c.html.markdown | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index db2ac930..b99cfe84 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -472,7 +472,22 @@ char c[] = "This is a test."; str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ - +//as we can return return only one variable +//to change values of more than one variables we use call by reference +void swapTwoNumbers(int *a, int *b) +{ +int temp = *a; +*a = *b; +*b = temp; +} +/* +int first = 10; +int second = 20; +printf("first: %d\nsecond: %d\n", first, second); +swapTwoNumbers(&first, &second); +printf("first: %d\nsecond: %d\n", first, second); +// values will be swapped +*/ // if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { -- cgit v1.2.3 From 626ee03fc3ca27698044db118bd53f563d22ccd0 Mon Sep 17 00:00:00 2001 From: himanshu81494 Date: Thu, 8 Oct 2015 14:45:16 +0530 Subject: Update c.html.markdown --- c.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/c.html.markdown b/c.html.markdown index b99cfe84..8e1675bb 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - ["Marco Scannadinari", "https://marcoms.github.io"] + - ["himanshu", "https://github.com/himanshu81494"] --- -- cgit v1.2.3 From e8248af13431ca87786fff17a605189c69aacf15 Mon Sep 17 00:00:00 2001 From: himanshu81494 Date: Thu, 8 Oct 2015 15:31:40 +0530 Subject: Update c.html.markdown --- c.html.markdown | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 8e1675bb..29bc5a5b 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -307,7 +307,25 @@ int main(void) { exit(-1); break; } - + + // using "goto" + typedef enum { false, true } bool; + // for C don't have bool as data type :( + bool disaster = false; + int i, j; + for(i=0;i<100;++i) + for(j=0;j<100;++j) + { + if((i + j) >= 150) + disaster = true; + if(disaster) + goto error; + } + error : + printf("Error occured at i = %d & j = %d.\n", i, j); + // this will print out "Error occured at i = 52 & j = 99." + + /////////////////////////////////////// // Typecasting /////////////////////////////////////// -- cgit v1.2.3 From 617599a527a7ee9e3d01a21f11338a1cba3e1eb5 Mon Sep 17 00:00:00 2001 From: himanshu81494 Date: Thu, 8 Oct 2015 15:49:51 +0530 Subject: Update json.html.markdown --- json.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/json.html.markdown b/json.html.markdown index 6aff2ce2..f4adfc8b 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -4,6 +4,7 @@ filename: learnjson.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] --- As JSON is an extremely simple data-interchange format, this is most likely going @@ -13,6 +14,11 @@ JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. +Data types supported by JSON includes: numbers, string, boolean, array, object and null. +Supporting browsers are: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. +JSON file type for JSON files is ".json". The MIME type for JSON text is "application/json" +Drawbacks of JSON include lack of type definition and some sort of DTD. + ```json { "key": "value", -- cgit v1.2.3 From 6f2d38155930911159bfb4e169b4a4430fed2e72 Mon Sep 17 00:00:00 2001 From: Tim Heaney Date: Thu, 8 Oct 2015 07:14:24 -0400 Subject: Typo: "thought of" not "though of" --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index e20be998..7252a3e4 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -633,7 +633,7 @@ writeln( toThisArray ); // var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; // exhibits a runtime error. // Even though the domain of the array and the loop-expression are -// the same size, the body of the expression can be though of as an iterator. +// the same size, the body of the expression can be thought of as an iterator. // Because iterators can yield nothing, that iterator yields a different number // of things than the domain of the array or loop, which is not allowed. -- cgit v1.2.3 From c39264fd881d9a7e39dbba1f37ec9de15cf11eea Mon Sep 17 00:00:00 2001 From: Tim Heaney Date: Thu, 8 Oct 2015 09:00:59 -0400 Subject: Typo: "easily" rather than "easy" --- fsharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 62118006..76318d7d 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -119,7 +119,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4] // ================================================ // F# is a true functional language -- functions are first -// class entities and can be combined easy to make powerful +// class entities and can be combined easily to make powerful // constructs // Modules are used to group functions together -- cgit v1.2.3 From 4b74a7a76d5840cee8f713605347a6cad245d4bb Mon Sep 17 00:00:00 2001 From: Tom Samstag Date: Thu, 8 Oct 2015 08:46:54 -0700 Subject: fix the output of ff example --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 63c0830a..26373c28 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1429,7 +1429,7 @@ for { # A flip-flop can change state as many times as needed: for { .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", - #=> "print this printing again" + #=> "print it print again" } # you might also use a Whatever Star, -- cgit v1.2.3 From 6d3f52b7f01409818853de6148abf1d8fe57fab0 Mon Sep 17 00:00:00 2001 From: "Todd M. Guerra" Date: Thu, 8 Oct 2015 11:53:19 -0400 Subject: Fix some grammar, spelling and indentation Just some quick cleanup to make the code correctly formatted in parts and fixed some typos. --- java.html.markdown | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index fc7948d6..e020885c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -337,7 +337,7 @@ public class LearnJava { validCodes.add("FINLAND"); } - // But there's a nifty way to achive the same thing in an + // But there's a nifty way to achieve the same thing in an // easier way, by using something that is called Double Brace // Initialization. @@ -347,9 +347,9 @@ public class LearnJava { add("FINLAND"); }} - // The first brace is creating an new AnonymousInnerClass and the - // second one declares and instance initializer block. This block - // is called with the anonymous inner class is created. + // The first brace is creating a new AnonymousInnerClass and the + // second one declares an instance initializer block. This block + // is called when the anonymous inner class is created. // This does not only work for Collections, it works for all // non-final classes. @@ -476,14 +476,14 @@ public interface Digestible { // We can now create a class that implements both of these interfaces. public class Fruit implements Edible, Digestible { @Override - public void eat() { - // ... - } + public void eat() { + // awesome code goes here + } @Override - public void digest() { - // ... - } + public void digest() { + // awesome code goes here + } } // In Java, you can extend only one class, but you can implement many @@ -491,12 +491,14 @@ public class Fruit implements Edible, Digestible { public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { @Override - public void InterfaceOneMethod() { - } + public void InterfaceOneMethod() { + // awesome code goes here + } @Override - public void InterfaceTwoMethod() { - } + public void InterfaceTwoMethod() { + // awesome code goes here + } } -- cgit v1.2.3 From 79cee63879088757cdd5c05c8d51d83a725b794d Mon Sep 17 00:00:00 2001 From: Colton Kohnke Date: Thu, 8 Oct 2015 21:20:37 +0200 Subject: [matlab/en] Added simple class example to Matlab --- matlab.html.markdown | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/matlab.html.markdown b/matlab.html.markdown index 02fe5962..0cbc6f57 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -3,6 +3,7 @@ language: Matlab contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] --- @@ -464,6 +465,59 @@ mean % mean value std % standard deviation perms(x) % list all permutations of elements of x + +% Classes +% Matlab can support object-oriented programming. +% Classes must be put in a file of the class name with a .m extension. +% To begin, we create a simple class to store GPS waypoints. +% Begin WaypointClass.m +classdef WaypointClass % The class name. + properties % The properties of the class behave like Structures + latitude + longitude + end + methods + % This method that has the same name of the class is the constructor. + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Other functions that use the Waypoint object + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % If we want to add two Waypoint objects together without calling + % a special function we can overload Matlab's arithmetic like so: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End WaypointClass.m + +% We can create an object of the class using the constructor +a = WaypointClass(45.0, 45.0) + +% Class properties behave exactly like Matlab Structures. +a.latitude = 70.0 +a.longitude = 25.0 + +% Methods can be called in the same way as functions +ans = multiplyLatBy(a,3) + +% The method can also be called using dot notation. In this case, the object +% does not need to be passed to the method. +ans = a.multiplyLatBy(a,1/3) + +% Matlab functions can be overloaded to handle objects. +% In the method above, we have overloaded how Matlab handles +% the addition of two Waypoint objects. +b = WaypointClass(15.0, 32.0) +c = a + b + ``` ## More on Matlab -- cgit v1.2.3 From 25d5d07dd342dc57831785032b813b3c2b3a5a9e Mon Sep 17 00:00:00 2001 From: Sean Corrales Date: Thu, 8 Oct 2015 15:37:54 -0500 Subject: Updating function instructions. --- sass.html.markdown | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/sass.html.markdown b/sass.html.markdown index d1e0721f..9bc72478 100644 --- a/sass.html.markdown +++ b/sass.html.markdown @@ -188,7 +188,8 @@ body.noLinks a { #################### */ /* Sass provides functions that can be used to accomplish a variety of tasks. Consider the following */ - + +/* Functions can be invoked by using their name and passing in the required arguments */ body { width: round(10.25px); } @@ -207,19 +208,19 @@ body { background-color: rgba(0, 0, 0, 0.75); } -/* You may also define your own functions. Functions are very similar to mixins. When trying to choose between - a function or a mixin, remember that functions are best for returning values while mixins are best for - generating CSS while functions are better for logic that might be used throughout your Sass code. The - examples in the Math Operators' section are ideal candidates for becoming a reusable function. */ - -/* This function will take a target size and the parent size and calculate and return the percentage */ +/* You may also define your own functions. Functions are very similar to mixins. When trying + to choose between a function or a mixin, remember that functions are best for returning + values while mixins are best for generating CSS while functions are better for logic that + might be used throughout your Sass code. The examples in the Math Operators' section are + ideal candidates for becoming a reusable function. */ + +/* This function will take a target size and the parent size and calculate and return + the percentage */ @function calculate-percentage($target-size, $parent-size) { @return $target-size / $parent-size * 100%; } -/* Functions can be invoked by using their name and passing in the required arguments */ - $main-content: calculate-percentage(600px, 960px); .main-content { -- cgit v1.2.3 From c7f02d174a72f1f1d807c57e030ba3c8f066c27b Mon Sep 17 00:00:00 2001 From: Colton Kohnke Date: Thu, 8 Oct 2015 23:07:05 +0200 Subject: [latex/en] Initial latex whirlwind showcase --- latex.html.markdown | 191 +++++++++++++++++++++++++++++----------------------- 1 file changed, 106 insertions(+), 85 deletions(-) diff --git a/latex.html.markdown b/latex.html.markdown index cc1d99cb..c8f21a83 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -2,6 +2,7 @@ language: latex contributors: - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] filename: learn-latex.tex --- @@ -12,122 +13,142 @@ getting it to behave exactly the way you want can be a bit hairy. ```latex + % All comment lines start with % % There are no multi-line comments % LaTeX is NOT a ``What You See Is What You Get'' word processing software like % MS Word, or OpenOffice Writer -% Getting to the final document using LaTeX consists of the following steps: -% 1. Write the document in plain text -% 2. Compile plain text document to produce a pdf -% The compilation step looks something like this: -% $ pdflatex your-tex-file.tex your-tex-file.pdf -% A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of -% software. So, you get to see Step 1, but not Step 2 completely. -% Step 2 is still happening behind the scenes. - -% You write all your formatting information in plain text in Step 1. -% The compilation part in Step 2 takes care of producing the document in the -% format you defined in Step 1. - -% For Step 1, it is best if you get a good text editor -% On Windows, probably Notepad++ -% For Step 2, you will need to get a TeX distribution -% Windows: MikTeX -% MacOS: MacTeX -% Linux: Should be available from your package manager - -% Let's get to the final pdf document as soon as possible - -% Choose the kind of document you want to write. -% You can replace article with book, report, etc. -\documentclass{article} -% begin the document -\begin{document} -% end the document -\end{document} -% Compile to pdf -% Now, you already have a final document which of course it is empty. -% Everything that you write is between the -% \begin{document} -% \end{document} - -% Start a new document from here. -% Let's do a decent document -\documentclass{article} -% required for inserting images -\usepackage{graphicx} -% begin the document -\begin{document} -% set the title (optional) -\title{Title of the document} -% set the author (optional) -\author{Chaitanya Krishna Ande} - -% make the title (optional) +% LaTeX documents start with a defining the type of document it's compiling +% Other document types include book, report, presentations, etc. +\documentclass[12pt]{article} + +% Next we define the packages the document uses. +% I'm going to include the float and caption packages for figures. +\usepackage{caption} +\usepackage{float} + +% We can define some other document properties too! +\author{Chaitanya Krishna Ande \& Colton Kohnke} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Now we're ready to begin the document +% Everything before this line is called "The Preamble" +\begin{document} +% if we set the author, date, title fields, we can have LaTeX +% create a title page fo us. \maketitle -% start the first section \section{Introduction} +Hello, my name is Colton and together we're going to explore LaTeX ! -% write your text -This is the introduction. - -% start another section \section{Another section} -This is the text for another section. - -% another section with subsection -\section{Section with sub-section} -Text for the section. -\subsection{Sub-section} -Let's discuss the Pythagoras theorem. -\subsubsection{Pythagoras Theorm} -% for cross-reference +This is the text for another section. I think it needs a subsection. + +\subsection{This is a subsection} +I think we need another one + +\subsubsection{Pythagoras} +Much better now. \label{subsec:pythagoras} -% notice how the sections and sub-sections are automatically numbered +\section*{This is an unnumbered section} +However not all sections have to be numbered! -% Some math -% Inline math within $ $ -For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, $b$ and $c$, where $c$ is the -hypotenuse, the following holds: +\section{Some Text notes} +LaTeX is generally pretty good about placing text where it should go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to +the text. In case you haven't noticed the \textbackslash is the character +the tells the LaTeX compiler it should pay attention to what's next. + +\section{Math} + +One of the primary uses for LaTeX is to produce academic article or +technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! \\ + +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +Notice how I needed to add \$ signs before and after the symbols. This is +because when writing, we are in text-mode. However, the math symbols only exist +in math-mode. We can enter math-mode from text mode with the \$ signs. +The opposite also holds true. Variable can also be rendered in math-mode. \\ + +% We can also add references +For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, + $b$ and $c$, where $c$ is the hypotenuse, the following holds: % Display math with the equation 'environment' -\begin{equation} +\begin{equation} % enters math-mode c^2 = a^2 + b^2. % for cross-reference \label{eq:pythagoras} -\end{equation} +\end{equation} % all \begin statments must have an end statement -% Let's cross-reference the equation Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also the subject of Sec.~\ref{subsec:pythagoras}. -\subsubsection{Figure} -Let's insert a Figure. -\begin{figure} +\section{Figures} + +Let's insert a Figure. Figure placement can get a little tricky. +I definately have to lookup the placement options each time. + +\begin{figure}[H] \centering - \includegraphics[width=0.8\linewidth]{right-triangle.png} - \caption{Right triangle with sides a, b, c} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Commented out for compilation purposes. Use your imagination. + \caption{Right triangle with sides $a$, $b$, $c$} \label{fig:right-triangle} \end{figure} - -\subsubsection{Table} +\subsection{Table} Let's insert a Table. -\begin{table} -\caption{Caption for the Table.} -\begin{tabular}{ccc} -Number & Last Name & First Name \\ -\hline -1 & Biggus & Dickus \\ -2 & Monty & Python -\end{tabular} +\begin{table}[H] + \caption{Caption for the Table.} + \begin{tabular}{ccc} + Number & Last Name & First Name \\ + \hline + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} \end{table} + +\section{Compiling} + +By now you're probably wondering how to compile this fabulous document +(yes, it actually compiles). \\ +Getting to the final document using LaTeX consists of the following steps: + \begin{enumerate} % we can also created numbered lists! + \item Write the document in plain text + \item Compile plain text document to produce a pdf. + The compilation step looks something like this: \\ + % Verbatim tells the compiler to not interpret. + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +software. So, you get to see Step 1, but not Step 2 completely. +Step 2 is still happening behind the scenes. + +You write all your formatting information in plain text in Step 1. +The compilation part in Step 2 takes care of producing the document in the +format you defined in Step 1. + +\section{End} + +That's all for now! + % end the document \end{document} ``` +## More on LaTeX + +* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) + + -- cgit v1.2.3 From c3914e277bafb320a37617c4a41984462be1a20d Mon Sep 17 00:00:00 2001 From: Raphael Nascimento Date: Thu, 8 Oct 2015 18:34:03 -0300 Subject: Added for/in loop JavaScript Fixing code style --- javascript.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index f7a662a4..0e38be8f 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -221,7 +221,7 @@ for (var i = 0; i < 5; i++){ //The For/In statement loops iterates over every property across the entire prototype chain var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; -for (var x in person) { +for (var x in person){ description += person[x] + " "; } @@ -229,8 +229,8 @@ for (var x in person) { //and not its prototypes use hasOwnProperty() check var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; -for (var x in person) { - if( person.hasOwnProperty( x ) ) { +for (var x in person){ + if (person.hasOwnProperty(x)){ description += person[x] + " "; } } -- cgit v1.2.3 From 8f5f1240eb14919deed89c54f0b322bc11e1469c Mon Sep 17 00:00:00 2001 From: Heather Fenton Date: Thu, 8 Oct 2015 19:18:07 -0400 Subject: Git: Add Git Immersion tutorial as a resource --- git.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index b1347309..72079f6c 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -484,6 +484,8 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) +* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) + * [git-scm - Video Tutorials](http://git-scm.com/videos) * [git-scm - Documentation](http://git-scm.com/docs) -- cgit v1.2.3 From 16c7f5e3b1260b9ae20613ae02728bf7090b0b9f Mon Sep 17 00:00:00 2001 From: Zsolt Prontvai Date: Fri, 9 Oct 2015 02:41:08 +0200 Subject: Ruby hungarian translation --- hu-hu/ruby.html.markdown | 555 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 555 insertions(+) create mode 100644 hu-hu/ruby.html.markdown diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby.html.markdown new file mode 100644 index 00000000..169f2b8e --- /dev/null +++ b/hu-hu/ruby.html.markdown @@ -0,0 +1,555 @@ +--- +language: ruby +lang: hu-hu +filenev: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + translators: + - ["Zsolt Prontvai", "https://github.com/prozsolt"] +--- + +```ruby +# Ez egy komment + +=begin +Ez egy többsoros komment +Senki sem használja +Neked sem kellene +=end + +# Először is: Minden objektum + +# A számok objektumok + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Néhány alapvető számtani művelet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# A számtani művelet csak szintaktikus cukor +# az objektumon történő függvény hívásra +1.+(3) #=> 4 +10.* 5 #=> 50 + +# A speciális értékek objektumok +nil # Nincs itt semmi látnivaló +true # igaz +false # hamis + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Egyenlőség +1 == 1 #=> true +2 == 1 #=> false + +# Egyenlőtlenség +1 != 1 #=> false +2 != 1 #=> true + +# A false-on kívül, nil az egyetlen hamis érték + +!nil #=> true +!false #=> true +!0 #=> false + +# Még több összehasonlítás +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Logikai operátorok +true && false #=> false +true || false #=> true +!true #=> false + +# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb +# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak +# amíg egyikük igaz vagy hamis értékkel nem tér vissza. + +# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel +# tért vissza. +csinalj_valamit() and csinalj_valami_mast() +# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel +# tért vissza. +csinalj_valamit() or log_error() + + +# A sztringek objektumok + +'Én egy sztring vagyok'.class #=> String +"Én is egy sztring vagyok".class #=> String + +helykitolto = 'interpolációt használhatok' +"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem" +#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem" + +# A szimpla idézőjelet preferáljuk, ahol csak lehet, +# mert a dupla idézőjel extra számításokat végez. + +# Kombinálhatunk sztringeket, de nem számokkal +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# kiírás a kimenetre +puts "Írok" + +# Változók +x = 25 #=> 25 +x #=> 25 + +# Értékadás az adott értékkel tér vissza +# Ez azt jelenti, hogy használhatunk többszörös értékadást: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Konvencióból, snake_case változó neveket használj +snake_case = true + +# Leíró változó neveket használj +ut_a_projekt_gyokerehez = '/jo/nev/' +ut = '/rossz/nev/' + +# A szimbólumok (objektumok) +# A szimbólumok megváltoztathatatlan, újra felhasználható konstans, +# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják, +# hogy effektíven közvetítsünk konkrét, értelmes értékeket + +:fuggoben.class #=> Symbol + +statusz = :fuggoben + +statusz == :fuggoben #=> true + +statusz == 'fuggoben' #=> false + +statusz == :jovahagyott #=> false + +# Tömbök + +# Ez egy tömb +tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# A tömmbök különböző tipusú dolgokat tartalmazhat + +[1, 'hello', false] #=> [1, "hello", false] + +# Tömbök indexelhetőek +# Az elejéről +tomb[0] #=> 1 +tomb[12] #=> nil + +# Akárcsak a számtani műveletek [var] hozzáférés +# is csak szintaktikus cukor +# a [] függvény hívására az objektumon +tomb.[] 0 #=> 1 +tomb.[] 12 #=> nil + +# A végéről +tomb[-1] #=> 5 + +# Kezdőértékkel és hosszal +tomb[2, 3] #=> [3, 4, 5] + +# Tömb megfordítása +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Vagy tartománnyal +tomb[1..3] #=> [2, 3, 4] + +# Így adhatunk a tömbhöz +tomb << 6 #=> [1, 2, 3, 4, 5, 6] +# Vagy így +tomb.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Ellenőrízük, hogy a tömb tartalmaz egy elemet +tomb.include?(1) #=> true + +# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal +# Hash-eket kapcsos zárójellel jelöljük +hash = { 'szin' => 'zold', 'szam' => 5 } + +hash.keys #=> ['szin', 'szam'] + +# Hash-ekben könnyen kreshetünk a kulcs segítségével: +hash['szin'] #=> 'zold' +hash['szam'] #=> 5 + +# Nem létező kulcsra keresve nil-t kapunk: +hash['nincs itt semmi'] #=> nil + +# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot +# használunk kulcsnak + +uj_hash = { defcon: 3, action: true } + +uj_hash.keys #=> [:defcon, :action] + +# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben +uj_hash.has_key?(:defcon) #=> true +uj_hash.has_value?(3) #=> true + +# Tip: A tömbök és hash-ek is felsorolhatóak +# Sok közös függvényük van, akár az each, map, count, és több + +# Kontroll Struktúrák + +if true + 'ha állítás' +elsif false + 'különben ha, opcionális' +else + 'különben, szintén opcionális' +end + +for szamlalo in 1..5 + puts "iteracio #{szamlalo}" +end +#=> iteracio 1 +#=> iteracio 2 +#=> iteracio 3 +#=> iteracio 4 +#=> iteracio 5 + +# HOWEVER, No-one uses for loops. +# Instead you should use the "each" method and pass it a block. +# A block is a bunch of code that you can pass to a method like "each". +# It is analogous to lambdas, anonymous functions or closures in other +# programming languages. +# +# The "each" method of a range runs the block once for each element of the range. +# The block is passed a counter as a parameter. +# Calling the "each" method with a block looks like this: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# You can also surround blocks in curly brackets: +(1..5).each { |counter| puts "iteration #{counter}" } + +# The contents of data structures can also be iterated using each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +jegy = '4' + +case jegy +when '5' + puts 'Kitünő' +when '4' + puts 'Jó' +when '3' + puts 'Közepes' +when '2' + puts 'Elégsége' +when '1' + puts 'Elégtelen' +else + puts 'Alternatív értékelés, hm?' +end +#=> "Jó" + +# case-ek tartományokat is használhatnak +jegy = 82 +case jegy +when 90..100 + puts 'Hurrá!' +when 80...90 + puts 'Jó munka' +else + puts 'Megbuktál!' +end +#=> "Jó munka" + +# kivétel kezelés: +begin + # kód ami kivételt dobhat + raise NoMemoryError, 'Megtelt a memória' +rescue NoMemoryError => kivetel_valtozo + puts 'NoMemoryError-t dobott', kivetel_valtozo +rescue RuntimeError => mas_kivetel_valtozo + puts 'RuntimeError dobott most' +else + puts 'Ez akkor fut ha nem dob kivételt' +ensure + puts 'Ez a kód mindenképpen lefut' +end + +# Függvények + +def ketszeres(x) + x * 2 +end + +# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel +ketszeres(2) #=> 4 + +# Zárójelezés opcionális, ha az eredmény félreérthetetlen +ketszeres 3 #=> 6 + +ketszeres ketszeres 3 #=> 12 + +def osszeg(x, y) + x + y +end + +# Függvény argumentumait vesszővel választjuk el. +osszeg 3, 4 #=> 7 + +osszeg osszeg(3, 4), 5 #=> 12 + +# yield +# Minden függvénynek van egy implicit, opcionális block paramétere +# 'yield' kulcsszóval hívhatjuk + +def korulvesz + puts '{' + yield + puts '}' +end + +korulvesz { puts 'hello world' } + +# { +# hello world +# } + + +# Fuggvénynek átadhatunk blokkot +# "&" jelöli az átadott blokk referenciáját +def vendegek(&block) + block.call 'valami_argumentum' +end + +# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva +# Erre való a splat operátor ("*") +def vendegek(*array) + array.each { |vendeg| puts vendeg } +end + +# Osztályt a class kulcsszóval definiálhatunk +class Ember + + # Az osztály változó. Az osztály minden példánnyával megvan osztva + @@faj = 'H. sapiens' + + # Alap inicializáló + def initialize(nev, kor = 0) + # Hozzárendeli az argumentumot a "nev" példány változóhoz + @nev = nev + # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni + @kor = kor + end + + # Alap setter függvény + def nev=(nev) + @nev = nev + end + + # Alap getter függvény + def nev + @nev + end + + # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük + attr_accessor :nev + + # Getter/setter függvények egyenként is kreálhatóak + attr_reader :nev + attr_writer :nev + + # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a + # példány függvényektől + # Az osztályn hívhatóak, nem a példányon + def self.mond(uzenet) + puts uzenet + end + + def faj + @@faj + end +end + + +# Példányosítsuk az osztályt +jim = Ember.new('Jim Halpert') + +dwight = Ember.new('Dwight K. Schrute') + +# Hívjunk meg pár függvényt +jim.faj #=> "H. sapiens" +jim.nev #=> "Jim Halpert" +jim.nev = "Jim Halpert II" #=> "Jim Halpert II" +jim.nev #=> "Jim Halpert II" +dwight.faj #=> "H. sapiens" +dwight.nev #=> "Dwight K. Schrute" + +# Hívjuk meg az osztály függvényt +Ember.mond('Hi') #=> "Hi" + +# Változók szókjait az elnevezésük definiálja +# $ kezdetű változók globálisak +$var = "Én egy globális változó vagyok" +defined? $var #=> "global-variable" + +# Változók amik @-al kezdődnek példány szkópjuk van +@var = "Én egy példány változó vagyok" +defined? @var #=> "instance-variable" + +# Változók amik @@-al kezdődnek példány szkópjuk van +@@var = "Én egy osztály változó vagyok" +defined? @@var #=> "class variable" + +# Változók amik nagy betűvel kezdődnek a konstansok +Var = "Konstans vagyok" +defined? Var #=> "constant" + +# Az osztály is objetum. Tehát az osztálynak lehet példány változója +# Az osztályváltozón osztozik minden pédány és leszármazott + +# Ős osztály +class Ember + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(ertek) + @@foo = ertek + end +end + +# Leszarmazott osztály +class Dolgozo < Ember +end + +Ember.foo # 0 +Dolgozo.foo # 0 + +Ember.foo = 2 # 2 +Dolgozo.foo # 2 + +# Az osztálynak példány változóját nem látja az osztály leszármazottja. + +class Ember + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(ertek) + @bar = ertek + end +end + +class Doctor < Ember +end + +Ember.bar # 0 +Doctor.bar # nil + +module ModulePelda + def foo + 'foo' + end +end + +# Modulok include-olása a fügvényeiket az osztály példányaihoz köti. +# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti. + +class Szemely + include ModulePelda +end + +class Konyv + extend ModulePelda +end + +Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class +Szemely.new.foo # => 'foo' +Konyv.foo # => 'foo' +Konyv.new.foo # => NoMethodError: undefined method `foo' + +# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult + +module ConcernPelda + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Valami + include ConcernPelda +end + +Valami.bar # => 'bar' +Valami.qux # => NoMethodError: undefined method `qux' +Valami.new.bar # => NoMethodError: undefined method `bar' +Valami.new.qux # => 'qux' +``` + +## Egyéb források + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) -- cgit v1.2.3 From d1b75f63352338bcbb1af6731c9a47b977a6be24 Mon Sep 17 00:00:00 2001 From: Raphael Nascimento Date: Thu, 8 Oct 2015 23:39:00 -0300 Subject: translation clojure-macros to pt br --- pt-br/clojure-macros-pt.html.markdown | 154 ++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 pt-br/clojure-macros-pt.html.markdown diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown new file mode 100644 index 00000000..dbc0c25c --- /dev/null +++ b/pt-br/clojure-macros-pt.html.markdown @@ -0,0 +1,154 @@ +--- +language: clojure +filename: learnclojure-pt.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Raphael Bezerra do Nascimento"] +lang: pt-br +--- + +Como todas as Lisps, a inerente [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic) +do Clojure lhe dá acesso a toda a extensão da linguagem +para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem +às suas necessidades. + +Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas +quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado. + +Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em +[Clojure em Y Minutos](/docs/clojure/). + +```clojure +;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa +;; ser avaliada como codigo Clojure. +;; +;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World") +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; Inspecione o resultado de uma macro utilizando macroexpand or macroexpand-1. +;; +;; Note que a chamada deve utilizar aspas simples. +(macroexpand '(my-first-macro)) +;; -> (# "Hello World") + +;; Você pode avaliar o resultad de macroexpand diretamente: +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; mas você deve usar esse mais suscinto, sintax como de função: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta +;; para criar listas nas suas macros: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; Note que reverse não é mais uma função objeto, mas um simbolo. + +;; Macros podem ter argumentos. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Mas se você tentar fazer isso com uma lista entre aspas simples, você vai receber um erro, por que o +;; argumento irá entra aspas simples também. Para contornar isso, Clojure prover uma maneira de utilizar aspas simples +;; em macros: `. Dentro `, você pode usar ~ para chegar ao escopo externo. +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Você pode usar os argumentos de destruturação habituais. Expandir lista de variaveis usando ~@ +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Lembrar o do! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless) avalia e retorna seu corpo, se o primeiro argumento é falso. +;; caso contrario, retorna nil + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; Usado sem cuidados, macros podem fazer muito mal por sobreporem suas variaveis +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;;s Para evitar isso, use gensym para receber um identificador unico +(gensym 'x) ; -> x1281 (ou outra coisa) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Você pode usar # dentro de ` para produzir uma gensym para cada simbolo automaticamente +(defmacro define-x-hygenically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygenically) ; -> (2) +(list x) ; -> (4) + +;; É típico o uso de funções de auxilio com macros. Vamos criar um pouco +;; Vamos criar um pouco para nos ajudar a suportar uma sintaxe aritmética inline (estupida) +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Given args [x (+ y)], return (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; Podemos testar isso imediatamente, sem criar uma macro +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Entretanto, temos que tornar isso uma macro caso quisermos que isso seja rodado em tempo de compilação +(defmacro inline-2 [form] + (inline-2-helper form))) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com / + +### Leitura adicional + +Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/) +[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) + +Documentos oficiais +[http://clojure.org/macros](http://clojure.org/macros) + +Quando utilizar macros? +[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) -- cgit v1.2.3 From bc065831ce25467ba06d3cf6e6ad159eed16a525 Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Thu, 8 Oct 2015 23:24:25 -0400 Subject: Added suggested changes --- go.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index f9821a0c..646a5650 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -408,8 +408,8 @@ func requestServer() { The root of all things Go is the [official Go web site](http://golang.org/). There you can follow the tutorial, play interactively, and read lots. -Aside from a tour, [the docs](https://golang.org/doc/) contain how to write -clean and effective Go code, package and command docs, and release history. +Aside from a tour, [the docs](https://golang.org/doc/) contain information on +how to write clean and effective Go code, package and command docs, and release history. The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) -- cgit v1.2.3 From b4860de42f2bbf0ab97ef28085eb40accb030657 Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Thu, 8 Oct 2015 23:27:19 -0400 Subject: Suggested changes --- swift.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 46e5e6d4..9f0019d8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -58,8 +58,8 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation print("Build value: \(buildValue)") // Build value: 7 /* - Optionals are a Swift language feature that either contains a value, - or contains nil (no value) to indicate that a value is missing. + Optionals are a Swift language feature that either contains a value, + or contains nil (no value) to indicate that a value is missing. A question mark (?) after the type marks the value as optional. Because Swift requires every property to have a value, even nil must be @@ -82,9 +82,9 @@ if someOptionalString != nil { someOptionalString = nil /* - To get the underlying type from an optional, you unwrap it using the - force unwrap operator (!). Only use the unwrap operator if you're sure - the underlying value isn't nil. + Trying to use ! to access a non-existent optional value triggers a runtime + error. Always make sure that an optional contains a non-nil value before + using ! to force-unwrap its value. */ // implicitly unwrapped optional -- cgit v1.2.3 From 7fd149485e0cbef6fc57206cb1377f261ed70278 Mon Sep 17 00:00:00 2001 From: Martin N Date: Fri, 9 Oct 2015 07:39:22 +0000 Subject: Mention of trailing commas in JSON and that they should be avoided --- json.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/json.html.markdown b/json.html.markdown index 6aff2ce2..a85cecc4 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -10,8 +10,11 @@ As JSON is an extremely simple data-interchange format, this is most likely goin to be the simplest Learn X in Y Minutes ever. JSON in its purest form has no actual comments, but most parsers will accept -C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is -going to be 100% valid JSON. Luckily, it kind of speaks for itself. +C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma +(i.e. a comma after the last element of an array or the after the last property of an object), +but they should be avoided for better compatibility. + +For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. ```json { -- cgit v1.2.3 From 4c27047a9748c0d3197dc63de34cc8bebf03633f Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Fri, 9 Oct 2015 11:27:19 +0200 Subject: [json/en] Typo --- json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/json.html.markdown b/json.html.markdown index a85cecc4..a1629137 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -14,7 +14,7 @@ C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility. -For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. +For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. ```json { -- cgit v1.2.3 From ab8267f4273d6fa2c3027775e353d95e7d5f1493 Mon Sep 17 00:00:00 2001 From: payet-s Date: Thu, 8 Oct 2015 16:48:50 +0200 Subject: [yaml/fr] Fix typos --- fr-fr/yaml-fr.html.markdown | 92 +++++++++++++++++++++++---------------------- 1 file changed, 48 insertions(+), 44 deletions(-) diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index 43b1df54..1e8296d3 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -8,113 +8,117 @@ lang: fr-fr Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de représentation de données par sérialisation, conçu pour être aisément -éditable et lisible par nous même, les humains. +modifiable et lisible par nous-mêmes, les humains. -YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages. +YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le +découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont +il est un parent naturel. Toutefois, YAML emprunte également des idées et +concepts de Python, et s'intègre bien avec bon nombre de langages. +Contrairement à ce dernier, YAML interdit l'utilisation des tabulations. ```yaml -# les Commentaires sont précédés d'un signe "#", comme cette ligne. +# Les commentaires sont précédés d'un signe "#", comme cette ligne. ############# # SCALAIRES # ############# -# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections -# ( listes ou tableaux associatifs ). +# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections +# (listes ou tableaux associatifs). -# Notre objet root ( racine ), sera une map ( carte ) et englobera -# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire, +# Notre objet root (racine), sera une map (carte) et englobera +# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire, # hash ou objet dans d'autres langages. clé: valeur -aurtre_clé: une autre valeur +autre_clé: une autre valeur valeur_numérique: 100 notation_scientifique: 1e+12 -boolean: true +booléen: true valeur_null: null clé avec espaces: valeur -# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères +# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères # entre guillemets, cela reste possible, et parfois utile. toutefois: "Une chaîne, peut être contenue entre guillemets." -"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé." +"Une clé entre guillemets.": "Utile si l'on veut utiliser ':' dans la clé." -# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix, -# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ). +# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix, +# comme un "bloc littéral" (avec '|') ou bien un "bloc replié" (avec '>'). bloc_littéral: | - Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral', - avec préservation des retours à la ligne. ( chaque ligne vide à - l'intérieur du même bloc, sera remplacée par "\n\n" ) + Tout ce bloc de texte sera la valeur de la clé "bloc_littéral", + avec préservation des retours à la ligne. Le littéral continue jusqu'à ce que l'indentation soit annulée. - Toutes lignes qui serait "d'avantage indentées" conservent leur + Toutes lignes qui seraient "davantage indentées" conservent leur indentation, constituée de 4 espaces. bloc_replié: > - Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais - cette fois ci, toutes les nouvelles lignes deviendront un simple espace. + Tout ce bloc de texte sera la valeur de la clé "bloc_replié", mais + cette fois-ci, toutes les nouvelles lignes deviendront un simple espace. - Les lignes vides, comme ci-dessus, seront converties en caractère "\n". + Les lignes vides, comme ci-dessus, seront converties en caractère de + nouvelle ligne. - Les lignes 'plus-indentées' gardent leurs retours à la ligne - + Les lignes "plus-indentées" gardent leurs retours à la ligne - ce texte apparaîtra sur deux lignes. ############### # COLLECTIONS # ############### -# l'Imbrication est créée par indentation. +# L'imbrication est créée par indentation. une_map_imbriquée: clé: valeur autre_clé: autre valeur autre_map_imbriquée: bonjour: bonjour -# les Clés des Maps ne sont pas nécessairement des chaînes de caractères. -0.25: une clé de type float +# Les clés des maps ne sont pas nécessairement des chaînes de caractères. +0.25: une clé de type flottant -# les Clés peuvent également être des objets s'étendant sur plusieurs lignes, +# Les clés peuvent également être des objets s'étendant sur plusieurs lignes, # en utilisant le signe "?" pour indiquer le début de la clé. ? | - ceci est une Clé + ceci est une clé sur de multiples lignes -: et ceci est sa Valeur +: et ceci est sa valeur # YAML autorise aussi l'usage des collections à l'intérieur des clés, # mais certains langages de programmation ne le tolère pas si bien. -# les Séquences (équivalent des listes ou tableaux) ressemblent à cela: +# Les séquences (équivalent des listes ou tableaux) ressemblent à cela : une_séquence: - - Item 1 - - Item 2 + - Objet 1 + - Objet 2 - 0.5 # les séquences peuvent contenir des types variés. - - Item 4 + - Objet 4 - clé: valeur autre_clé: autre_valeur - - Ceci est une séquence - dans une autre séquence -# YAML étant un proche parent de JSON, vous pouvez écrire directement +# YAML étant un proche parent de JSON, vous pouvez écrire directement # des maps et séquences façon JSON json_map: {"clé": "valeur"} json_seq: [1, 2, 3, "soleil"] -################################# +################################ # AUTRES FONCTIONNALITÉES YAML # -################################# +################################ -# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci +# YAML possède une fonctionnalité fort utile nommée "ancres". Celle-ci # vous permet de dupliquer aisément du contenu au sein de votre document. -# Les deux clés suivantes auront la même valeur: +# Les deux clés suivantes auront la même valeur : contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés. autre_ancre: *nom_ancre -# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données. +# Avec les tags YAML, vous pouvez explicitement déclarer des types de données. chaine_explicite: !!str 0.5 -# Certains parsers implémentent des tags spécifiques à d'autres langages, -# comme par exemple le "complex number" de Python. +# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à +# d'autres langages, comme par exemple celui des nombres complexes de Python. python_complex_number: !!python/complex 1+2j ##################### @@ -122,7 +126,7 @@ python_complex_number: !!python/complex 1+2j ##################### # YAML interprète également les données formatées ISO de type date et datetime, -# pas seulement les chaînes et nombres. +# pas seulement les chaînes et nombres. datetime: 2001-12-15T02:59:43.1Z datetime_avec_espaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 @@ -135,14 +139,14 @@ fichier_gif: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML a de même un type "set", qui ressemble à cela: +# YAML a de même un type "set", semblable à ceci : set: ? item1 ? item2 ? item3 # Comme dans Python, les sets ne sont que des maps contenant des valeurs null ; -# le set précédent est l'équivalent du suivant: +# le set précédent est l'équivalent du suivant : set2: item1: null item2: null @@ -152,6 +156,6 @@ set2: Quelques références et outils : -- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*, +- Documentation officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*, - Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire, -- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. +- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. -- cgit v1.2.3 From bf7d33037f64ea9f80f106a37929e3fdf20bd24d Mon Sep 17 00:00:00 2001 From: Cameron Schermerhorn Date: Fri, 9 Oct 2015 08:14:11 -0400 Subject: Add space to comment prior to switch string + Add space to comment (after //) prior to switch on string example --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index e567b049..eb8b23e9 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -277,7 +277,7 @@ public class LearnJava { } System.out.println("Switch Case Result: " + monthString); - //Starting in Java 7 and above, switching Strings works like this: + // Starting in Java 7 and above, switching Strings works like this: String myAnswer = "maybe"; switch(myAnswer){ case "yes": -- cgit v1.2.3 From 1f68a9645573e54354d672709605ed9975e4843b Mon Sep 17 00:00:00 2001 From: wboka Date: Fri, 9 Oct 2015 08:43:12 -0400 Subject: Update coldfusion.html.markdown Adds conversion table and example of a very basic component. Adds a link to the official Adobe ColdFusion developer reference. --- coldfusion.html.markdown | 413 +++++++++++++++++++---------------------------- 1 file changed, 163 insertions(+), 250 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 6a9b69f0..e2f0737d 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -146,263 +146,176 @@ ColdFusion is a scripting language for web development.
-``` - +

Components

+ +Code for reference (Functions must return something to support IE) + +
+<cfcomponent>
+	<cfset this.hello = "Hello" />
+	<cfset this.world = "world" />
+
+	<cffunction name="sayHello">
+		<cfreturn this.hello & ", " & this.world & "!" />
+	</cffunction>
+	
+	<cffunction name="setHello">
+		<cfargument name="newHello" type="string" required="true" />
+		
+		<cfset this.hello = arguments.newHello />
+		 
+		<cfreturn true />
+	</cffunction>
+	
+	<cffunction name="setWorld">
+		<cfargument name="newWorld" type="string" required="true" />
+		
+		<cfset this.world = arguments.newWorld />
+		 
+		<cfreturn true />
+	</cffunction>
+	
+	<cffunction name="getHello">
+		<cfreturn this.hello />
+	</cffunction>
+	
+	<cffunction name="getWorld">
+		<cfreturn this.world />
+	</cffunction>
+</cfcomponent>
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +sayHello() +

#sayHello()#

+getHello() +

#getHello()#

+getWorld() +

#getWorld()#

+setHello("Hola") +

#setHello("Hola")#

+setWorld("mundo") +

#setWorld("mundo")#

+sayHello() +

#sayHello()#

+getHello() +

#getHello()#

+getWorld() +

#getWorld()#

+``` ## Further Reading The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) -- cgit v1.2.3 From c1c7a96378d79d379e68084780eecd91731fa4bb Mon Sep 17 00:00:00 2001 From: Himanshu81494 Date: Fri, 9 Oct 2015 19:57:06 +0530 Subject: typo in readme --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 774797d5..28fa5093 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ commented code and explained as they go. ... to write more inline code tutorials. Just grab an existing file from this repo and copy the formatting (don't worry, it's all very simple). -Make a new file, send a pull request, and if it passes muster I'll get it up pronto. +Make a new file, send a pull request, and if it passes master I'll get it up pronto. Remember to fill in the "contributors" fields so you get credited properly! -- cgit v1.2.3 From 1e90e7da1d042dfc46a5be11117a4e45e460bcf8 Mon Sep 17 00:00:00 2001 From: Andy B Date: Fri, 9 Oct 2015 15:32:05 +0100 Subject: [objective-c/en-fr-ru-tr-vn] Enable syntax highlighting --- fr-fr/objective-c-fr.html.markdown | 2 +- objective-c.html.markdown | 2 +- ru-ru/objective-c-ru.html.markdown | 2 +- tr-tr/objective-c-tr.html.markdown | 2 +- vi-vn/objective-c-vi.html.markdown | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 69f4d8f9..4e31c4bf 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -14,7 +14,7 @@ lang: fr-fr L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. -```objective_c +```objective-c // Les commentaires sur une seule ligne commencent par // /* diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 89901308..cf6bf780 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -13,7 +13,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```objective_c +```objective-c // Single-line comments start with // /* diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index ddff2e5c..8eac4ddb 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -17,7 +17,7 @@ Cocoa Touch. Он является объектно-ориентированным языком программирования общего назначения, который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C. -```objective_c +```objective-c // Однострочные комментарии начинаются с // /* diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown index f27cbf08..727f973e 100644 --- a/tr-tr/objective-c-tr.html.markdown +++ b/tr-tr/objective-c-tr.html.markdown @@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C programlama diline Smalltalk stilinde mesajlaşma ekler. -```objective_c +```objective-c // Tek satır yorum // işaretleri ile başlar /* diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index c97bb560..38e418e9 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C. -```objective_c +```objective-c // Chú thích dòng đơn bắt đầu với // /* -- cgit v1.2.3 From a67d9d9e0ed3d351ce0139de18a4b212b47ab9cb Mon Sep 17 00:00:00 2001 From: Andy B Date: Fri, 9 Oct 2015 15:36:51 +0100 Subject: [coffeescript/en] Fixed grammar --- coffeescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 85a5f81f..106854bd 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -7,7 +7,7 @@ filename: coffeescript.coffee --- CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime. -As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime. +As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime. See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. -- cgit v1.2.3 From e8e8b9c76fb578d3f8e90b90b3c8a1c59cf0e901 Mon Sep 17 00:00:00 2001 From: Andy B Date: Fri, 9 Oct 2015 15:48:21 +0100 Subject: [C/en] Accessing command line arguments in main --- c.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index db2ac930..345dca7f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -27,6 +27,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line... */ // ...not this one! // Constants: #define +// Constants are written in all-caps out of convention, not requirement #define DAYS_IN_YEAR 365 // Enumeration constants are also ways to declare constants. @@ -56,6 +57,15 @@ int add_two_ints(int x1, int x2); // function prototype // Your program's entry point is a function called // main with an integer return type. int main(void) { + // your program +} + +// The command line arguments used to run your program are also passed to main +// argc being the number of arguments - your program's name counts as 1 +// argv is an array of character arrays - containing the arguments themselves +// argv[0] = name of your program, argv[1] = first argument, etc. +int main (int argc, char** argv) +{ // print output using printf, for "print formatted" // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 -- cgit v1.2.3 From 53a0264029dbaaf5909110c0a390753b276ac324 Mon Sep 17 00:00:00 2001 From: Sricharan Chiruvolu Date: Fri, 9 Oct 2015 20:30:57 +0530 Subject: Update latex.html.markdown --- latex.html.markdown | 53 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/latex.html.markdown b/latex.html.markdown index c8f21a83..f0646941 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -3,6 +3,7 @@ language: latex contributors: - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] filename: learn-latex.tex --- @@ -25,12 +26,15 @@ getting it to behave exactly the way you want can be a bit hairy. \documentclass[12pt]{article} % Next we define the packages the document uses. +% If you want to include graphics, colored text or +% source code from a file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. % I'm going to include the float and caption packages for figures. \usepackage{caption} \usepackage{float} % We can define some other document properties too! -\author{Chaitanya Krishna Ande \& Colton Kohnke} +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} \date{\today} \title{Learn LaTeX in Y Minutes!} @@ -41,6 +45,16 @@ getting it to behave exactly the way you want can be a bit hairy. % create a title page fo us. \maketitle +% Most research papers have abstract, you can use the predefined commands for this. +% This should appear in its logical order, therefore, after the top matter, +% but before the main sections of the body. +% This command is available in document classes article and report. +\begin{abstract} + LaTex documentation written as LaTex! How novel and totally not my idea! +\end{abstract} + +% Section commands are intuitive. +% All the titles of the sections are added automatically to the table of contents. \section{Introduction} Hello, my name is Colton and together we're going to explore LaTeX ! @@ -69,15 +83,34 @@ One of the primary uses for LaTeX is to produce academic article or technical papers. Usually in the realm of math and science. As such, we need to be able to add special symbols to our paper! \\ -My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +Math has many symbols, far beyond what you can find on a keyboard. +Set and relation symbols, arrows, operators, Greek letters to name a few. \\ + + +Sets and relations play a vital role in many mathematical research papers. +Here's how you state all y that belong to X, $\forall$ x $\in$ X. Notice how I needed to add \$ signs before and after the symbols. This is because when writing, we are in text-mode. However, the math symbols only exist in math-mode. We can enter math-mode from text mode with the \$ signs. The opposite also holds true. Variable can also be rendered in math-mode. \\ -% We can also add references -For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, - $b$ and $c$, where $c$ is the hypotenuse, the following holds: +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. + +Operators are essential parts of a mathematical document: trigonometric functions +(sin, cos, tan), logarithms and exponentials (log, exp), limits (lim) e.t.c. have +pre-defined LaTeX commands. Let's write an equation to see how it's done: \\ + +$\cos$ (2$\theta$) = $\cos$^2 $\theta$ - $\sin$^2 $\theta$ + +Fractions(Numerator-denominators) can be written in these forms: + +% 10 / 7 +^10/_7 + +% Relatively complex fractions can be written as +% \frac{numerator}{denominator} +$\frac{n!}{k!(n - k)!}$ + % Display math with the equation 'environment' \begin{equation} % enters math-mode c^2 = a^2 + b^2. @@ -88,11 +121,17 @@ For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also the subject of Sec.~\ref{subsec:pythagoras}. +Summations and Integrals are written with sum and int commands: +\begin{equation} % enters math-mode +\sum_{i=0}^{5} f_i + +\int_0^\infty \mathrm{e}^{-x}\,\mathrm{d}x +\end{equation} \section{Figures} Let's insert a Figure. Figure placement can get a little tricky. -I definately have to lookup the placement options each time. +I definitely have to lookup the placement options each time. \begin{figure}[H] \centering @@ -115,6 +154,8 @@ Let's insert a Table. \end{tabular} \end{table} +% \section{Hyperlinks} + \section{Compiling} -- cgit v1.2.3 From bb8eeb53ef01b6bfbdf64d6f1dc067f9cf4b8f8d Mon Sep 17 00:00:00 2001 From: Andy B Date: Fri, 9 Oct 2015 16:05:21 +0100 Subject: [xml/en] Grammar fixes --- xml.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/xml.html.markdown b/xml.html.markdown index d407512d..4d33e614 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -40,13 +40,14 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i It starts with a declaration, informing some metadata (optional). XML uses a tree structure. Above, the root node is 'bookstore', which has - three child nodes, all 'books'. Those nodes has more child nodes, and so on... + three child nodes, all 'books'. Those nodes have more child nodes (or + children), and so on... - Nodes are created using open/close tags, and childs are just nodes between + Nodes are created using open/close tags, and children are just nodes between the open and close tags.--> - + - + - +
- ``` -## Precedence +## Precedence or Cascade -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. -In these cases, one of the rules takes precedence over others. +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. + +This process is called cascading, hence the name Cascading Style Sheets. Given the following CSS: ```css -/*A*/ +/* A */ p.class1[attr='value'] -/*B*/ -p.class1 {} +/* B */ +p.class1 { } -/*C*/ -p.class2 {} +/* C */ +p.class2 { } -/*D*/ -p {} +/* D */ +p { } -/*E*/ +/* E */ p { property: value !important; } - ``` and the following markup: ```xml -

-

+

``` -The precedence of style is as followed: -Remember, the precedence is for each **property**, not for the entire block. +The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. -* `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. -* `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` - but it appears last. -* Then is `B` -* and lastly is `D`. +* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage. +* `F` is next, because it is an inline style. +* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`. +* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`. +* `B` is next. +* `D` is the last one. ## Compatibility -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatibility -of what you use in CSS with your target browsers. +Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature. -[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. +## Resources -To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource. +* To run a quick compatibility check, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) ## Further Reading -* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) -* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) * [QuirksMode CSS](http://www.quirksmode.org/css/) * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) -- cgit v1.2.3 From 622d4485ab9efd265be83d16abbe8cb12da7934c Mon Sep 17 00:00:00 2001 From: Kara Kincaid Date: Sat, 10 Oct 2015 08:20:03 -0400 Subject: [css/en] Added more pseudo-classes and pseudo-elements examples --- css.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/css.html.markdown b/css.html.markdown index 811767e6..4c459f7f 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -119,6 +119,19 @@ selected:link {} /* or an input element which is focused */ selected:focus {} +/* any element that is the first child of its parent */ +selector:first-child {} + +/* any element that is the last child of its parent */ +selector:last-child {} + +/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */ + +/* matches a virtual first child of the selected element */ +selector::before {} + +/* matches a virtual last child of the selected element */ +selector::after {} /* #################### ## PROPERTIES -- cgit v1.2.3 From 7c2c4480600b6c817418d5ba04315bca3c5a400d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Costa?= Date: Sat, 10 Oct 2015 16:49:53 +0100 Subject: Fix compile errors of the English and French Scala tutorials --- fr-fr/scala.html.markdown | 9 ++++++--- scala.html.markdown | 12 ++++++------ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index a43edf16..c6d06361 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -208,6 +208,7 @@ sSquared.reduce (_+_) // La fonction filter prend un prédicat (une fonction de type A -> Booléen) et // sélectionne tous les éléments qui satisfont ce prédicat List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -217,6 +218,7 @@ List( // Scala a une méthode foreach définie pour certaines collections // qui prend en argument une fonction renvoyant Unit (une méthode void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique. // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus // facile pour comprendre et pour faire la parallélisation +i = 0 // La boucle do while do { println("x is still less then 10"); - x += 1 -} while (x < 10) + i += 1 +} while (i < 10) // La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. @@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com" "Les chaînes de caractères Scala sont entourées de doubles guillements" 'a' // Un caractère de Scala -'Les simples guillemets n'existent pas en Scala // Erreur +// 'Les simples guillemets n'existent pas en Scala' // Erreur "Les chaînes de caractères possèdent les méthodes usuelles de Java".length "Il y a aussi quelques méthodes extra de Scala.".reverse diff --git a/scala.html.markdown b/scala.html.markdown index 7189be10..7f545196 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] - ["Ha-Duong Nguyen", "http://reference-error.org"] -filename: learn.scala --- Scala - the scalable language @@ -244,10 +243,11 @@ i // Show the value of i. Note that while is a loop in the classical sense - // comprehensions above is easier to understand and parallelize // A do while loop +i = 0 do { - println("x is still less than 10") - x += 1 -} while (x < 10) + println("i is still less than 10") + i += 1 +} while (i < 10) // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. @@ -566,8 +566,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" // Implicit function parameters enable us to simulate type classes in other // functional languages. It is so often used that it gets its own shorthand. The // following two lines mean the same thing: -def foo[T](implicit c: C[T]) = ... -def foo[T : C] = ... +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... // Another situation in which the compiler looks for an implicit is if you have -- cgit v1.2.3 From ae7dee12a5fef665e9c5bb3ae1ebc9eece9c7648 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Costa?= Date: Sat, 10 Oct 2015 16:51:07 +0100 Subject: [scala-pt] Fix variable names on while cycle --- pt-pt/scala-pt.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown index 270fb01e..a4c1c02b 100644 --- a/pt-pt/scala-pt.html.markdown +++ b/pt-pt/scala-pt.html.markdown @@ -245,10 +245,11 @@ i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico - // paralelizar // Um ciclo do while +i = 0 do { - println("x ainda é menor que 10") - x = x + 1 -} while (x < 10) + println("i ainda é menor que 10") + i += 1 +} while (i < 10) // A forma idiomática em Scala de definir acções recorrentes é através de // recursão em cauda. -- cgit v1.2.3 From 77f0219cc6fd64f9c4dbd3007fa395b2242a6e49 Mon Sep 17 00:00:00 2001 From: Ratan Date: Sat, 10 Oct 2015 12:10:27 -0400 Subject: change String to AbstractString as per 0.4 spec --- julia.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 66329feb..7ca2d492 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -78,7 +78,7 @@ false 1 < 2 < 3 # => true 2 < 3 < 2 # => false -# Strings are created with " +# AbstractStrings are created with " "This is a string." # Character literals are written with ' @@ -314,7 +314,7 @@ end # For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. +# Iterable types include Range, Array, Set, Dict, and AbstractString. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") # You can use $ to interpolate variables or expression into strings @@ -550,13 +550,13 @@ super(Any) # => Any # <: is the subtyping operator type Lion <: Cat # Lion is a subtype of Cat mane_color - roar::String + roar::AbstractString end # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type -Lion(roar::String) = Lion("green",roar) +Lion(roar::AbstractString) = Lion("green",roar) # This is an outer constructor because it's outside the type definition type Panther <: Cat # Panther is also a subtype of Cat -- cgit v1.2.3 From 7281681a3e45e8103b771933b40920a292fc2818 Mon Sep 17 00:00:00 2001 From: Thibault iTech Date: Sat, 10 Oct 2015 18:58:25 +0200 Subject: Added translation in french for the HAML article --- fr-fr/haml-fr.html.markdown | 156 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 fr-fr/haml-fr.html.markdown diff --git a/fr-fr/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown new file mode 100644 index 00000000..0267a380 --- /dev/null +++ b/fr-fr/haml-fr.html.markdown @@ -0,0 +1,156 @@ +--- +language: haml +filename: learnhaml.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] + - ["Thibault", "https://github.com/iTech-"] +--- + +Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage. + +Son but est de réduire le nombre de répétitions dans le balisage en fermant des balises pour vous en se basant sur l'indentation de votre code. Finalement, le balisage est bien structuré, ne contient pas de répétition, est logique et facile à lire. + +Vous pouvez aussi utiliser Haml sur un projet indépendant de Ruby, en installant les gems de Haml et en le convertissant en html grâce aux commandes. + +$ haml fichier_entree.haml fichier_sortie.html + + +```haml +/ ------------------------------------------- +/ Indentation +/ ------------------------------------------- + +/ + A cause de l'importance de l'indentation sur la manière dont votre code sera + converti, l'indentation doit être constante à travers votre document. Un + simple changement d'indentation entrainera une erreur. En général, on utilise + deux espaces, mais ce genre de décision sur l'indentation vous appartient, du + moment que vous vous y tenez. + +/ ------------------------------------------- +/ Commentaires +/ ------------------------------------------- + +/ Ceci est un commentaire en Haml. + +/ + Pour écrire un commentaire sur plusieurs lignes, indentez votre code + commenté en le commençant par un slash + +-# Ceci est un commentaire silencieux, qui n'apparaîtra pas dans le fichier + + +/ ------------------------------------------- +/ Eléments HTML +/ ------------------------------------------- + +/ Pour écrire vos balises, utilisez un pourcentage suivi du nom de votre balise +%body + %header + %nav + +/ Remarquez qu'il n'y a aucunes balises fermées. Le code produira alors ceci + +

+ +
+ + +/ La balise div est l'élément par défaut, vous pouvez donc l'écrire comme ceci +.balise + +/ Pour ajouter du contenu à votre balise, ajoutez le texte après sa déclaration +%h1 Titre contenu + +/ Pour écrire du contenu sur plusieurs lignes, imbriquez le +%p + Ce paragraphe contient beaucoup de contenu qui pourrait + probablement tenir sur deux lignes séparées. + +/ + Vous pouvez utiliser des caractères html spéciaux en utilisant &=. Cela va + convertir les caractères comme &, /, : en leur équivalent HTML. Par exemple + +%p + &= "Oui & oui" + +/ Produira 'Oui & oui' + +/ Vous pouvez écrire du contenu html sans qu'il soit converti en utilisant != +%p + != "Voici comment écrire une balise de paragraphe

" + +/ Cela produira 'Voici comment écrire une balise de paragraphe

' + +/ Une classe CSS peut être ajouté à votre balise en chainant le nom de la classe +%div.truc.machin + +/ ou en utilisant un hash de Ruby +%div{:class => 'truc machin'} + +/ Des attributs pour n'importe quelles balises peuvent être ajoutés au hash +%a{:href => '#', :class => 'machin', :title => 'Titre machin'} + +/ Pour affecter une valeur à un booléen, utilisez 'true' +%input{:selected => true} + +/ Pour écrire des data-attributes, utilisez le :data avec la valeur d'un hash +%div{:data => {:attribute => 'machin'}} + + +/ ------------------------------------------- +/ Insérer du Ruby +/ ------------------------------------------- + +/ + Pour transférer une valeur de Ruby comme contenu d'une balise, utilisez le + signe égal suivi du code Ruby + +%h1= livre.titre + +%p + = livre.auteur + = livre.editeur + + +/ Pour lancer du code Ruby sans le convertir en HTML, utilisez un trait d'union +- livres = ['livre 1', 'livre 2', 'livre 3'] + +/ Ceci vous permet de faire des choses géniales comme des blocs Ruby +- livre.shuffle.each_with_index do |livre, index| + %h1= livre + + if livre do + %p Ceci est un livre + +/ + Encore une fois il n'est pas nécessaire d'ajouter une balise fermante, même + pour Ruby. + L'indentation le fera pour vous. + + +/ ------------------------------------------- +/ Ruby en-ligne / Interpolation en Ruby +/ ------------------------------------------- + +/ Inclure une variable Ruby dans une ligne en utilisant #{} +%p Votre meilleur score est #{record} + + +/ ------------------------------------------- +/ Filtres +/ ------------------------------------------- + +/ + Utilisez les deux points pour définir un filtre Haml, vous pouvez par exemple + utiliser un filtre :javascript pour écrire du contenu en-ligne js + +:javascript + console.log('Ceci est la balise en-ligne + + + + + +``` + + + +### Optimizar todo un proyecto usando r.js + + + +Muchas personas prefiere usar AMD para la sana organización del código durante el desarrollo, pero todavía prefiere enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. + + + +`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. + + + +Instálalo usando `npm`: + +```shell + +$ npm install requirejs -g + +``` + + + +Ahora puedes alimentarlo con un fichero de configuración: + +```shell + +$ r.js -o app.build.js + +``` + + + +Para nuestro ejemplo anterior el archivo de configuración luciría así: + +```javascript + +/* file : app.build.js */ + +({ + + name : 'main', // name of the entry point + + out : 'main-built.js', // name of the file to write the output to + + baseUrl : 'app', + + paths : { + + // `empty:` tells r.js that this should still be loaded from the CDN, using + + // the location specified in `main.js` + + jquery : 'empty:', + + coolLibFromBower : '../bower_components/cool-lib/coollib' + + } + +}) + +``` + + + +Para usar el fichero creado en producción, simplemente intercambia `data-main`: + +```html + + + +``` + + + +Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. + + + +### Tópicos no cubiertos en este tutorial + +* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) + +* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) + +* [Configuración avanzada](http://requirejs.org/docs/api.html#config) + +* [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) + +* [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) + +* [Usando almond.js para construcciones](https://github.com/jrburke/almond) + + + +### Otras lecturas: + + + +* [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) + +* [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) + +* [Definición Universal de Módulos](https://github.com/umdjs/umd) + + + +### Implementaciones: + + + +* [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) -- cgit v1.2.3 From 8dd11eee84a36ac2d81f266574b07bf603327e0e Mon Sep 17 00:00:00 2001 From: Moritz Kammerer Date: Sat, 17 Oct 2015 15:56:00 +0200 Subject: Adds german translation for LateX --- de-de/latex-de.html.markdown | 235 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 de-de/latex-de.html.markdown diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown new file mode 100644 index 00000000..2c18b8fd --- /dev/null +++ b/de-de/latex-de.html.markdown @@ -0,0 +1,235 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Moritz Kammerer", "https://github.com/phxql"] +lang: de-de +filename: latex-de.tex +--- +``` +% Alle Kommentare starten fangen mit % an +% Es gibt keine Kommentare über mehrere Zeilen + +% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% MS Word oder OpenOffice Writer + +% Jedes LateX-Kommando startet mit einem Backslash (\) + +% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% Weitere Dokumententypen sind z.B. book, report, presentations, etc. +% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall +% wollen wir einen 12 Punkte-Font verwenden. +\documentclass[12pt]{article} + +% Als nächstes definieren wir die Pakete, die wir verwenden wollen. +% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, +% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% Wir verwenden die Pakete float und caption für Bilder. +\usepackage{caption} +\usepackage{float} + +% Mit diesem Paket können leichter Umlaute getippt werden +\usepackage[utf8]{inputenc} + +% Es können durchaus noch weitere Optione für das Dokument gesetzt werden! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Nun kann's losgehen mit unserem Dokument. +% Alles vor dieser Zeile wird die Preamble genannt. +\begin{document} +% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann +% LateX für uns eine Titelseite generieren +\maketitle + +% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem +% Inhalt erscheinen. +% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. +\begin{abstract} + LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! +\end{abstract} + +% Section Befehle sind intuitiv. +% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. +\section{Einleitung} +Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! + +\section{Noch eine section} +Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. + +\subsection{Das ist eine subsection} % Subsections sind auch ziemlich intuitiv. +Ich glaube, wir brauchen noch eine. + +\subsubsection{Pythagoras} +So ist's schon viel besser. +\label{subsec:pythagoras} + +% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. +% Das funktioniert auch bei anderen Befehlen. +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle sections nummeriert sein! + +\section{Ein paar Notizen} +LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge +\textbackslash\textbackslash in den Code ein.\\ + +\section{Listen} +Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +also lass uns eine Einkaufsliste schreiben: +\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. + % \item bringt enumerate dazu, eins weiterzuzählen. + \item Salat. + \item 27 Wassermelonen. + \item einen Hasen. + % Wir können die Nummer des Eintrags durch [] überschreiben + \item[Wie viele?] Mittelgroße Wasserpistolen. + + Kein Listeneintrag, aber immer noch Teil von enumerate. + +\end{enumerate} % Alle Umgebungen müssen ein end haben. + +\section{Mathe} + +Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder +anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle +Symbole zu unserem Paper hinzuzufügen! \\ + +Mathe kennt sehr viele Symbole, viel mehr als auf einer Tastatur zu finden sind; +Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstaben, +um nur ein paar zu nennen.\\ + +Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen +Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ + +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings +% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und +% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. + +Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! + +Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Logarithmus und Exponenten ($\log$, $\exp$), +Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. +Lass uns eine Gleichung schreiben: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ + +Brüche (Zähler / Nenner) können so geschrieben werden: + +% 10 / 7 +$^{10}/_{7}$ + +% Komplexere Brüche können so geschrieben werden: +% \frac{Zähler}{Nenner} +$\frac{n!}{k!(n - k)!}$ \\ + +Wir können Gleichungen auch in einer equation Umgebung verwenden. + +% Dies zeigt Mathe in einer equation Umgebung an +\begin{equation} % Aktiviert automatisch den Mathe-Modus. + c^2 = a^2 + b^2. + \label{eq:pythagoras} % Pythagoras referenzieren +\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen + +Wir können nun unsere Gleichung referenzieren! +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: +Grafiken, Gleichungen, Sections, etc. + +Summen und Integrale können mit den sum und int Befehlen dargestellt werden: + +% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Grafiken} + +Lass uns eine Grafik einfügen. Das Platzieren von Grafiken kann etwas trickreich sein. +Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. + +\begin{figure}[H] % H ist die Platzierungsoption + \centering % Zentriert die Grafik auf der Seite + % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Auskommentiert, damit es nicht im Dokument auftaucht. + \caption{Dreieck mit den Seiten $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabellen} +Wir können Tabellen genauso wie Grafiken einfügen. + +\begin{table}[H] + \caption{Überschrift der Tabelle.} + % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. + % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. + \begin{tabular}{c|cc} + Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt + \hline % Eine horizontale Linie + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Links} % Kommen bald! + +\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll +in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden +wir eine verbatim Umgebung. + +% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) +% aber verbatim ist das simpelste. +\begin{verbatim} + print("Hello World!") + a%b; % Schau dir das an! Wir können % im verbatim verwenden! + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Kompilieren} + +Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF +verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ + +Dafür musst du folgende Schritte durchführen: + \begin{enumerate} + \item Schreibe das Dokument. (den LateX-Quelltext). + \item Kompiliere den Quelltext in ein PDF. + Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +2 wird unsichtbar im Hintergrund ausgeführt. + +Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet +dann diese Informationen und kümmert sich drum, dass das Dokument korrekt erstellt wird. + +\section{Ende} + +Das war's erst mal! + +% Dokument beenden +\end{document} +``` +## Mehr Informationen über LateX + +* Das tolle LaTeX wikibook: [https://de.wikibooks.org/wiki/LaTeX-Kompendium](https://de.wikibooks.org/wiki/LaTeX-Kompendium) +* Ein Tutorial (englisch): [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From 0768364a4d69e8b3a81fa0dcfea9d996ad2fea7f Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sat, 17 Oct 2015 15:57:07 +0200 Subject: Add myself as a translator --- it-it/java-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 0e782dd1..54602cff 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] translators: - ["Ivan Sala","http://github.com/slavni96"] + - ["Tommaso Pifferi","http://github.com/neslinesli93"] lang: it-it --- -- cgit v1.2.3 From 600483a4582713b515e1e72fd842927bbb30a613 Mon Sep 17 00:00:00 2001 From: Santhosh Kumar Srinivasan Date: Sat, 17 Oct 2015 19:38:39 +0530 Subject: Fix typo on readme Just a typo. Changed `tag your issues pull requests with` to `tag your issues and pull requests with` --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 28fa5093..46408a04 100644 --- a/README.markdown +++ b/README.markdown @@ -18,7 +18,7 @@ All contributions are welcome, from the tiniest typo to a brand new article. Tra in all languages are welcome (or, for that matter, original articles in any language). Send a pull request or open an issue any time of day or night. -**Please tag your issues pull requests with [language/lang-code] at the beginning** +**Please tag your issues and pull requests with [language/lang-code] at the beginning** **(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. -- cgit v1.2.3 From df1f9fdb9ea25953820209d3a4ef547f8afa8dce Mon Sep 17 00:00:00 2001 From: Gloria Dwomoh Date: Sat, 17 Oct 2015 18:22:55 +0300 Subject: Update racket-gr.html.markdown --- el-gr/racket-gr.html.markdown | 72 +++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 4c4576bb..589adfeb 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -31,12 +31,12 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την ;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να -;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging +;; κάνουμε σχόλια κάποιες εκφράσεις κατά τη διάρκεια του debugging #; (αυτή η έκφραση δεν θα εκτελεστεί) ;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε -;; πολύ συντομα!) +;; πολύ σύντομα!) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -57,8 +57,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; όπου το f είναι η συνάρτηση και τα x y z ;; είναι οι όροι που η συνάρτηση δέχεται ;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε -;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα, -;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να +;; μια λίστα στην κυριολεξία από δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε από το να ;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: '(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη ;; Τώρα , ας κάνουμε μερικές πράξεις @@ -88,15 +88,15 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής -"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήρες διαφυγής της C, ; σε Unicode "λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες -;; Μπορούμε να εννώσουμε αλφαριθμητικά! +;; Μπορούμε να ενώσουμε αλφαριθμητικά! (string-append "Hello " "world!") ; => "Hello world!" -;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε -;; όπως και μια λίστα απο χαρακτήρες +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοποιήσουμε +;; όπως και μια λίστα από χαρακτήρες (string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο ;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για @@ -117,18 +117,18 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ some-var ; => 5 ;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. -(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? +(define ⊆ subset?) ;; Εδώ ουσιαστικά δίνουμε στη ήδη υπάρχουσα συνάρτηση subset? ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. (⊆ (set 3 2) (set 1 2 3)) ; => #t -;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πριν π.χ. (printf name) ;; θα πάρουμε το παρακάτω μήνυμα ;name: undefined; ; cannot reference undefined identifier ; context...: -;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...) +;; Η τοπική δέσμευση : `me' δεσμεύεται με το "Bob" μόνο μέσα στο (let ...) (let ([me "Bob"]) "Alice" me) ; => "Bob" @@ -156,7 +156,7 @@ my-pet ; => # ;;; Λίστες ;; Οι λίστες είναι linked-list δομές δεδομένων, -;; που έχουν δημιουργηθεί απο ζευγάρια 'cons' +;; που έχουν δημιουργηθεί από ζευγάρια 'cons' ;; και τελειώνουν με 'null' (ή αλλιώς '()) για να ;; δηλώσουν ότι αυτό είναι το τέλος της λίστας (cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) @@ -191,12 +191,12 @@ my-pet ; => # ;; Τα διανύσματα είναι πίνακες σταθερού μήκους #(1 2 3) ; => '#(1 2 3) -;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα +;; Χρησιμοποιούμε το `vector-append' για να προσθέσουμε διανύσματα (vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) ;;; Σύνολα -;; Δημιουργούμε ένα σύνολο απο μία λίστα +;; Δημιουργούμε ένα σύνολο από μία λίστα (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) ;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' @@ -214,10 +214,10 @@ my-pet ; => # ;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού (define m (hash 'a 1 'b 2 'c 3)) -;; Παίρνουμε μια τιμή απο τον πίνακα +;; Παίρνουμε μια τιμή από τον πίνακα (hash-ref m 'a) ; => 1 -;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση +;; Αν ζητήσουμε μια τιμή που δεν υπάρχει παίρνουμε μία εξαίρεση ; (hash-ref m 'd) => no value found for key ;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν @@ -234,7 +234,7 @@ m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε -;; κλειδία +;; κλειδιά (hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -247,12 +247,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' (λ () "Hello World") ; => Ίδια συνάρτηση -;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; Χρησιμοποιούμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις ;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' ((lambda () "Hello World")) ; => "Hello World" ((λ () "Hello World")) ; => "Hello World" -;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση +;; Εκχωρούμε σε μια μεταβλητή την συνάρτηση (define hello-world (lambda () "Hello World")) (hello-world) ; => "Hello World" @@ -302,7 +302,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (lambda (name . args) (format "Hello ~a, you passed ~a extra args" name (length args)))) -;; Και με λέξεις κλειδία +;; Και με λέξεις κλειδιά (define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) (format "~a ~a, ~a extra args" g name (length args))) (hello-k) ; => "Hello World, 0 extra args" @@ -347,7 +347,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f -;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων +;; Το `eqv?' υποστηρίζει την σύγκριση αριθμών αλλά και χαρακτήρων ;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. (eqv? 3 3.0) ; => #f (eqv? (expt 2 100) (expt 2 100)) ; => #t @@ -365,12 +365,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (equal? (list 3) (list 3)) ; => #t ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. Έλεχγος Ροής +;; 5. Έλεγχος Ροής ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Συνθήκες (conditionals) -(if #t ; έκφραση ελέχγου +(if #t ; έκφραση ελέγχου "this is true" ; έκφραση then "this is false") ; έκφραση else ; => "this is true" @@ -483,7 +483,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (values i (number->string i))) ; => '#hash((1 . "1") (2 . "2") (3 . "3")) -;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε +;; Υπάρχουν πολλά είδη από προϋπάρχοντες τρόπους για να συλλέγουμε ;; τιμές από τους βρόχους (for/sum ([i 10]) (* i i)) ; => 285 @@ -491,7 +491,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t (for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t -;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε +;; Και για να χρησιμοποιήσουμε ένα αυθαίρετο συνδυασμό χρησιμοποιούμε ;; το 'for/fold' (for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 @@ -524,17 +524,17 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (set! n (add1 n)) n ; => 6 -;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή -;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της) +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβλητή +;; θα είναι mutable (θα μπορεί να αλλάξει η τιμή της) ;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες (define n* (box 5)) (set-box! n* (add1 (unbox n*))) (unbox n*) ; => 6 -;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι π.χ. τα ζεύγη, οι ;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή -;; πχ αλφαριθμητικά, διανύσματα κτλ +;; π.χ. αλφαριθμητικά, διανύσματα κτλ. (define vec (vector 2 2 3 4)) (define wall (make-vector 100 'bottle-of-beer)) ;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια @@ -579,7 +579,7 @@ vec ; => #(1 2 3 4) (printf fmt (make-string n ch)) (newline))) -;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα +;; Χρησιμοποιουμε το 'require' για να πάρουμε όλα τα ;; παρεχόμενα ονόματα από μία ενότητα (require 'cake) ; το ' είναι για τοπική υποενότητα (print-cake 3) @@ -634,7 +634,7 @@ vec ; => #(1 2 3 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε -;; το συντακτικό μιάς γλώσσας. +;; το συντακτικό μιας γλώσσας. ;; Ας προσθέσουμε έναν βρόχο while (define-syntax-rule (while condition body ...) @@ -664,20 +664,20 @@ vec ; => #(1 2 3 4) ;; (set! tmp other) ;; (set! other tmp_1)) -;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ: +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ.: (define-syntax-rule (bad-while condition body ...) (when condition body ... (bad-while condition body ...))) -;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουργεί ατέρμονα βρόχο ;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής -;; θα μπεί στον ατέρμονα βρόχο. +;; θα μπει στον ατέρμονα βρόχο. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 10. Συμβόλαια (Contracts) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται +;; Τα συμβόλαια βάζουν περιορισμούς σε τιμές που προέρχονται ;; από ενότητες (modules) (module bank-account racket (provide (contract-out @@ -719,7 +719,7 @@ vec ; => #(1 2 3 4) (displayln "Hola mundo" out-port) (close-output-port out-port) -;; Διαβάζουμε απο αρχείο ξανά +;; Διαβάζουμε από αρχείο ξανά (define in-port (open-input-file "/tmp/tmp.txt")) (displayln (read-line in-port)) ; => "Hello World" -- cgit v1.2.3 From 1ae02fc6cf7642911125e088ec5e7ce15552b95d Mon Sep 17 00:00:00 2001 From: Persa Zula Date: Sat, 17 Oct 2015 11:25:05 -0400 Subject: Adds more string operations to ruby doc --- ruby.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 0e798706..f4de8038 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,7 +12,8 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - - ["Gabriel Halley", https://github.com/ghalley"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] --- ```ruby @@ -107,6 +108,12 @@ placeholder = 'use string interpolation' 'hello ' + 3 #=> TypeError: can't convert Fixnum into String 'hello ' + 3.to_s #=> "hello 3" +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello" + +# Append to string +'hello' << ' world' #=> "hello world" + # print to the output with a newline at the end puts "I'm printing!" #=> I'm printing! @@ -284,7 +291,7 @@ end #=> iteration 4 #=> iteration 5 -# There are a bunch of other helpful looping functions in Ruby, +# There are a bunch of other helpful looping functions in Ruby, # for example "map", "reduce", "inject", the list goes on. Map, # for instance, takes the array it's looping over, does something # to it as defined in your block, and returns an entirely new array. -- cgit v1.2.3 From c030e8aab18e2d63a40eb1321b21a62471094bc0 Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 21:17:09 +0530 Subject: CSS Translation En to Tamil --- ta_in/css.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 ta_in/css.html.markdown diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown new file mode 100644 index 00000000..b55ab363 --- /dev/null +++ b/ta_in/css.html.markdown @@ -0,0 +1,261 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss.css +lang:in-ta +--- + + +இணையத்தின் ஆரம்ப காலத்தில் முழுமையாக உரைகளை மட்டுமே கொண்டிருந்தன. +ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் +கூடிய இணையதளங்கள் உருவாகின. + +CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page. +CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. + +ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. + + +This guide has been written for CSS 2, though CSS 3 is fast becoming popular. +இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. + +**குறிப்பு:** +CSS ஆனது முற்று முழுதாக visual(காட்சி) மாற்றங்களை தருவதால் அதை நீங்கள் முயற்சிக்க +இதை உபயோகபடுத்தலாம் [dabblet](http://dabblet.com/). +இந்த வழிகாட்டியின் பிரதான நோக்கம் CSS இன் syntax மற்றும் மேலும் சில வழிமுறைகளை +உங்களுக்கு கற்று தருவதாகும் + +```css +/* css இல் குறிப்புகளை இப்படி இடலாம் */ + +/* #################### + ## SELECTORS + #################### */ + +/* ஒரு HTML பக்கத்தில் இருக்கும் உறுப்பை நாம் selector மூலம் தெரிவு செய்யலாம் +selector { property: value; /* more properties...*/ } + +/* +கிழே ஒரு உதாரணம் காட்டப்பட்டுள்ளது: + +
+*/ + +/* நீங்கள் அந்த உறுப்பை அதன் CSS class மூலம் தெரியலாம் */ +.class1 { } + +/* அல்லது இவ்வாறு இரண்டு class மூலம் தெரியலாம்! */ +.class1.class2 { } + +/* அல்லது அதன் பெயரை பாவித்து தெரியலாம் */ +div { } + +/* அல்லது அதன் id ஐ பயன்படுத்தி தெரியலாம்*/ +#anID { } + +/* அல்லது ஒரு உறுப்பின் பண்பு ஒன்றின் மூலம்! */ +[attr] { font-size:smaller; } + +/* அல்லது அந்த பண்பு ஒரு குறிப்பிட்ட பெறுமானத்தை கொண்டு இருப்பின் */ +[attr='value'] { font-size:smaller; } + +/* ஒரு பெறுமதியுடன் ஆரம்பமாகும் போது (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* அல்லது ஒரு பெறுமதியுடன் முடிவடையும் போது (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* அல்லது காற்புள்ளியால் பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின் */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* அல்லது `-` பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின், உ.ம்:-, "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* நாம் இரண்டு selectors ஐ ஒன்றாக உபயோகித்தும் ஒரு உறுப்பை அணுக முடியும் , +அவற்றுக்கு இடயே இடைவெளி காணப்படகூடாது + */ +div.some-class[attr$='ue'] { } + +/*அல்லது ஒரு உறுப்பினுள் இருக்கும் இன்னொரு உறுப்பை (child element) அணுக */ +div.some-parent > .class-name { } + +/* ஒரு ஒரு பிரதான உறுப்பில் உள்ள உப உறுப்புகளை அணுக*/ +div.some-parent .class-name { } + +/* மேலே குறிபிட்ட அணுகுமுறையில் இடைவெளி காணப்படாது விடின் + அந்த selector வேலை செய்யாது + */ +div.some-parent.class-name { } + +/* அல்லது ஒரு உறுப்புக்கு அடுத்துள்ள */ +.i-am-just-before + .this-element { } + +/* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ +.i-am-any-element-before ~ .this-element { } + +/* There are some selectors called pseudo classes that can be used to select an + element when it is in a particular state + சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை + குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் + */ + +/* உதாரணமாக நாம் ஒரு உறுப்பின் மீதாக cursor ஐ நகர்த்தும் போது */ +selector:hover { } + +/* அல்லது ஒரு +பார்வையிட்ட இணைப்பு */ +selector:visited { } + +/* அல்லது ஒரு பார்வையிடபடாத இணைப்பு */ +selected:link { } + +/* அல்லது ஒரு element ஐ focus செய்யும் போது */ +selected:focus { } + +/* + எல்லா elementகளையும் ஒரே நேரத்தில் அணுக `*` +*/ +* { } /* all elements */ +.parent * { } /* all descendants */ +.parent > * { } /* all children */ + +/* #################### + ## பண்புகள் + #################### */ + +selector { + + /* நீளத்தின் அலகுகள் absolute அல்லது relative ஆக இருக்கலாம். */ + + /* Relative units */ + width: 50%; /* percentage of parent element width */ + font-size: 2em; /* multiples of element's original font-size */ + font-size: 2rem; /* or the root element's font-size */ + font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ + font-size: 2vh; /* or its height */ + font-size: 2vmin; /* whichever of a vh or a vw is smaller */ + font-size: 2vmax; /* or greater */ + + /* Absolute units */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimeters */ + min-width: 50mm; /* millimeters */ + max-width: 5in; /* inches */ + + + /* Colors */ + color: #F6E; /* short hex format */ + color: #FF66EE; /* long hex format */ + color: tomato; /* a named color */ + color: rgb(255, 255, 255); /* as rgb values */ + color: rgb(10%, 20%, 50%); /* as rgb percentages */ + color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */ + color: transparent; /* equivalent to setting the alpha to 0 */ + color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */ + + /* Images as backgrounds of elements */ + background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ + + /* Fonts */ + font-family: Arial; + /* if the font family name has a space, it must be quoted */ + font-family: "Courier New"; + /* if the first one is not found, the browser uses the next, and so on */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Usage + +ஒரு css file ஐ save செய்ய `.css`. + +```xml + + + + + + + +
+
+``` + +## Precedence or Cascade + +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. + +This process is called cascading, hence the name Cascading Style Sheets. + +ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் +ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன +இது Cascading Style Sheets என அழைக்கபடுகிறது. + + +கிழே தரப்பட்டுள்ள css இன் படி: + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்: + +```xml +

+``` + +The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. +css முன்னுரிமை பின்வருமாறு +* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் +* `F` இது இரண்டாவது காரணம் இது inline style. +* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`. +* `C` இது அடுத்த நிலையில் உள்ளது கடைசி. +* `B` இது அடுத்தது. +* `D` இதுவே கடைசி . + +## css அம்சங்களின் பொருந்தகூடிய தன்மை + +பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. + +## வளங்கள் + +* To run a quick compatibility check, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) + +## மேலும் வாசிக்க + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) -- cgit v1.2.3 From 19a5714600892bedda76b4b4562d961fc579a890 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sat, 17 Oct 2015 18:02:47 +0200 Subject: Added lang tag --- it-it/json-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown index 51bc9fc8..379bad73 100644 --- a/it-it/json-it.html.markdown +++ b/it-it/json-it.html.markdown @@ -7,6 +7,7 @@ contributors: translators: - ["Robert Margelli", "http://github.com/sinkswim/"] - ["Christian Grasso", "http://chris54721.net"] +lang: it-it --- JSON è un formato per l'interscambio di dati estremamente semplice, per cui questo sarà -- cgit v1.2.3 From 0f003ef3e9fc00c33741303e4979a44f285f5e05 Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Sat, 17 Oct 2015 11:35:56 -0430 Subject: Spanish translation version 1 --- es-es/amd-es.html.markdown | 241 +++------------------------------------------ 1 file changed, 16 insertions(+), 225 deletions(-) diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown index 3de23a6c..7a59ddd6 100644 --- a/es-es/amd-es.html.markdown +++ b/es-es/amd-es.html.markdown @@ -1,423 +1,214 @@ --- category: tool - tool: amd - contributors: - - ["Frederik Ring", "https://github.com/m90"] translators: - - ["Damaso Sanoja", "https://github.com/damasosanoja"] - filename: learnamd-es.js - lang: es-es - --- - - ## Iniciando con AMD - - -El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos - -JavaScript de manera que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso cruzado de dominios. - - +El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios. ### Conceptos básicos - ```javascript - -// El API básico de AMD consiste en nada más que dos métodos: `define` y `require` - +// El API básico de AMD consiste en tan solo dos métodos: `define` y `require` // y se basa en la definición y consumo de los módulos: - -// `define(id?, dependencies?, factory)` define un módulo - -// `require(dependencies, callback)` importa un conjunto de dependencias y - -// las consume en el callback invocado - - +// `define(id?, dependencias?, fábrica)` define un módulo +// `require(dependencias, callback)` importa un conjunto de dependencias y +// las consume al invocar el callback // Comencemos usando define para definir un nuevo módulo - // que no posee dependencias. Lo haremos enviando un nombre - -// y una función factoría para definirla: - +// y una función fábrica para definirla: define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - - // El valor que regresa de la función factoría del módulo es - - // aquello que los otros módulos o llamados require reciben cuando - - // solicitan nuestro módulo `awesomeAMD`. - + // El valor que regresa la función fábrica del módulo será + // lo que los otros módulos o llamados require recibirán cuando + // soliciten nuestro módulo `awesomeAMD`. // El valor exportado puede ser cualquier cosa, funciones (constructores), - // objetos, primitivos, incluso indefinidos (aunque eso no ayuda mucho). - return isAMDAwesome; - }); - - // Ahora definamos otro módulo que dependa de nuestro módulo `awesomeAMD`. - // Observe que ahora hay un argumento adicional que define - // las dependencias de nuestro módulo: - define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ - - // las dependencias serán enviadas a los argumentos de la factoría - + // las dependencias serán enviadas a los argumentos de la fábrica // en el orden que sean especificadas - var tellEveryone = function(){ - if (awesomeAMD()){ - alert('This is sOoOo rad!'); - } else { - alert('Pretty dull, isn\'t it?'); - } - }; - return tellEveryone; - }); - - // Como ya sabemos utilizar define usemos ahora `require` para poner en marcha - // nuestro programa. La firma de `require` es `(arrayOfDependencies, callback)`. - require(['loudmouth'], function(loudmouth){ - loudmouth(); - }); - - // Para hacer que este tutorial corra código, vamos a implementar una - // versión muy básica (no-asíncrona) de AMD justo aquí: - function define(name, deps, factory){ - // observa como son manejados los módulos sin dependencias - define[name] = require(factory ? deps : [], factory || deps); - } - - function require(deps, callback){ - var args = []; - // primero recuperemos todas las dependencias que necesita - // el llamado require - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // satisfacer todas las dependencias del callback - return callback.apply(null, args); - } - // puedes ver este código en acción aquí: http://jsfiddle.net/qap949pd/ - ``` - - ### Uso en el mundo real con require.js - - En contraste con el ejemplo introductorio, `require.js` (la librería AMD más popular) implementa la **A** de **AMD**, permitiéndote cargar los módulos y sus dependencias asincrónicamente via XHR: - - ```javascript - /* file: app/main.js */ - require(['modules/someClass'], function(SomeClass){ - // el callback es diferido hasta que la dependencia sea cargada - var thing = new SomeClass(); - }); - console.log('So here we are, waiting!'); // esto correrá primero - ``` - - -Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` es asumido que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: - - +Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` asumimos que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: * app/ - * main.js - * modules/ - * someClass.js - * someHelpers.js - * ... - * daos/ - * things.js - * ... - - Esto significa que podemos definir `someClass` sin especificar su id de módulo: - - ```javascript - /* file: app/modules/someClass.js */ - define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ - // definición de módulo, por supuesto, ocurrirá también asincrónicamente - function SomeClass(){ - this.method = function(){/**/}; - // ... - } - return SomeClass; - }); - ``` Para alterar el comportamiento del mapeo de ruta usa `requirejs.config(configObj)` en tu `main.js`: - - ```javascript - /* file: main.js */ - requirejs.config({ - baseUrl : 'app', - paths : { - // también puedes cargar módulos desde otras ubicaciones - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } - }); - require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ - // un fichero `main` necesita llamar a require al menos una vez, - // de otra forma jamás correrá el código - coolLib.doFancyStuffWith(helpers.transform($('#foo'))); - }); - ``` - Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página: - - ```html - - - - Cien etiquetas de script? Nunca más! - - - - - - ``` - - ### Optimizar todo un proyecto usando r.js - - -Muchas personas prefiere usar AMD para la sana organización del código durante el desarrollo, pero todavía prefiere enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. - - +Muchas personas prefieren usar AMD para la organización del código durante el desarrollo, pero quieren enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. `require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. - - Instálalo usando `npm`: - ```shell - $ npm install requirejs -g - ``` - - Ahora puedes alimentarlo con un fichero de configuración: - ```shell - $ r.js -o app.build.js - ``` - - Para nuestro ejemplo anterior el archivo de configuración luciría así: - ```javascript - /* file : app.build.js */ - ({ - - name : 'main', // name of the entry point - - out : 'main-built.js', // name of the file to write the output to - + name : 'main', // nombre del punto de entrada + out : 'main-built.js', // nombre del fichero donde se escribirá la salida baseUrl : 'app', - paths : { - - // `empty:` tells r.js that this should still be loaded from the CDN, using - - // the location specified in `main.js` - + // `empty:` le dice a r.js que esto aún debe ser cargado desde el CDN, usando + // la ubicación especificada en `main.js` jquery : 'empty:', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } - }) - ``` - - Para usar el fichero creado en producción, simplemente intercambia `data-main`: - ```html - - ``` - - Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. - - ### Tópicos no cubiertos en este tutorial - * [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) - * [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) - * [Configuración avanzada](http://requirejs.org/docs/api.html#config) - * [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) - * [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) - * [Usando almond.js para construcciones](https://github.com/jrburke/almond) - - ### Otras lecturas: - - * [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) - * [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) - * [Definición Universal de Módulos](https://github.com/umdjs/umd) - - ### Implementaciones: - - * [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) -- cgit v1.2.3 From a1939d8e89716378d4dd76c824a6908bf21bfe88 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:13:47 +0800 Subject: Update latex.html.markdown Add opening tex tag --- latex.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/latex.html.markdown b/latex.html.markdown index e180e622..9b7b4feb 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,6 +6,8 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] filename: learn-latex.tex --- + +```tex % All comment lines start with % % There are no multi-line comments @@ -225,6 +227,7 @@ That's all for now! % end the document \end{document} ``` + ## More on LaTeX * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) -- cgit v1.2.3 From a875e6d589b7e6e8a396417adc001bc0f88e82fd Mon Sep 17 00:00:00 2001 From: Persa Date: Sat, 17 Oct 2015 12:16:14 -0400 Subject: Fixes output on combining strings and operators --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index f4de8038..4e9f8aee 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -109,7 +109,7 @@ placeholder = 'use string interpolation' 'hello ' + 3.to_s #=> "hello 3" # Combine strings and operators -'hello ' * 3 #=> "hello hello hello" +'hello ' * 3 #=> "hello hello hello " # Append to string 'hello' << ' world' #=> "hello world" -- cgit v1.2.3 From 85fa357b8a3e441e5c160f18ca6d19cdea7d0160 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:26:19 +0800 Subject: Update clojure-fr.html.markdown --- fr-fr/clojure-fr.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index 25911ea8..1cedda1d 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -276,12 +276,14 @@ ressemblent à toutes les autres formes: (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") -; Utilisez les Threading Macros (-> et ->>) pour exprimer plus clairement vos transformations, en y pensant de manière multi-niveaux: -; La "flèche simple" ou "Thread-first", insère, à chaque niveau de la transformation, la forme courante en la seconde position de la forme suivante, constituant à chaque fois un nouvel étage de transformation.Par exemple: +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus clairement vos transformations, en y pensant de manière multi-niveaux. + +; La "flèche simple" ou "Thread-first", insère, à chaque niveau de la transformation, la forme courante en la seconde position de la forme suivante, constituant à chaque fois un nouvel étage de transformation. Par exemple: (-> {:a 1 :b 2} (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) + ; Cette expression est ré-écrite en: (dissoc (assoc {:a 1 :b 2} :c 3) :b) et est évaluée en : {:a 1 :c 3} ; La "flèche double" ou "Thread-last" procède de la même manière que "->", mais insère le résultat de la réécriture de chaque étage en dernière position. Par exemple: (->> -- cgit v1.2.3 From 085bc20c1afc7bb45aae9d269c12df06ba804a1e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:27:50 +0800 Subject: Fix spacing. --- fr-fr/clojure-fr.html.markdown | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index 1cedda1d..63bc25b5 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -276,16 +276,25 @@ ressemblent à toutes les autres formes: (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") -; Utilisez les Threading Macros (-> et ->>) pour exprimer plus clairement vos transformations, en y pensant de manière multi-niveaux. +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus +; clairement vos transformations, en y pensant de manière multi-niveaux. -; La "flèche simple" ou "Thread-first", insère, à chaque niveau de la transformation, la forme courante en la seconde position de la forme suivante, constituant à chaque fois un nouvel étage de transformation. Par exemple: +; La "flèche simple" ou "Thread-first", insère, à chaque niveau +; de la transformation, la forme courante en la seconde position +; de la forme suivante, constituant à chaque fois un nouvel étage +; de transformation. Par exemple: (-> {:a 1 :b 2} (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) -; Cette expression est ré-écrite en: (dissoc (assoc {:a 1 :b 2} :c 3) :b) et est évaluée en : {:a 1 :c 3} -; La "flèche double" ou "Thread-last" procède de la même manière que "->", mais insère le résultat de la réécriture de chaque étage en dernière position. Par exemple: +; Cette expression est ré-écrite en: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; et est évaluée en : {:a 1 :c 3} + +; La "flèche double" ou "Thread-last" procède de la même manière +; que "->", mais insère le résultat de la réécriture de chaque +; étage en dernière position. Par exemple: (->> (range 10) (map inc) ;=> Génère ici (map inc (range 10) -- cgit v1.2.3 From aea4d998b446185ab66a0800e470bc36c132362a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:31:19 +0800 Subject: Copy arrow docs from french. --- clojure.html.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/clojure.html.markdown b/clojure.html.markdown index a125d18f..58e835c9 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -264,6 +264,31 @@ keymap ; => {:a 1, :b 2, :c 3} (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Use the threading macros (-> and ->>) to express transformations of +; data more clearly. + +; The "Thread-first" macro (->) inserts into each form the result of +; the previous, as the first argument (second item) +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; This expression could be written as: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; and evaluates to {:a 1 :c 3} + +; The double arrow does the same thing, but inserts the result of +; each line at the *end* of the form. This is useful for collection +; operations in particular: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; -- cgit v1.2.3 From 30413639edaa382a4667cc0411aca8d2752c508c Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:33:27 +0800 Subject: Update ruby-de.html.markdown --- de-de/ruby-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown index 560d3958..bdeaa30b 100644 --- a/de-de/ruby-de.html.markdown +++ b/de-de/ruby-de.html.markdown @@ -13,7 +13,7 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] -filename: ruby-de.html.markdown +filename: ruby-de.rb lang: de-de --- -- cgit v1.2.3 From 0ddc0b743d5512494df23a27a967c2c27b9873ca Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:33:54 +0800 Subject: Update scala-de.html.markdown --- de-de/scala-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown index 42808580..7fd299b4 100644 --- a/de-de/scala-de.html.markdown +++ b/de-de/scala-de.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Ha-Duong Nguyen", "http://reference-error.org"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] -filename: scala-de.html.markdown +filename: learnscala-de.scala lang: de-de --- @@ -813,4 +813,4 @@ writer.close() * [The scala documentation](http://docs.scala-lang.org/) * [Try Scala in your browser](http://scalatutorials.com/tour/) * [Neophytes Guide to Scala](http://danielwestheide.com/scala/neophytes.html) -* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) \ No newline at end of file +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From 978c8fb15cc2ee89a4eedcb8c7955eb90bea5bfc Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:34:14 +0800 Subject: Update ruby-ecosystem-de.html.markdown --- de-de/ruby-ecosystem-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown index e1f3c5e7..a7e1f75f 100644 --- a/de-de/ruby-ecosystem-de.html.markdown +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Rafal Chmiel", "http://github.com/rafalchmiel"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] -filename: ruby-ecosystem-de.html.markdown +filename: ruby-ecosystem-de.txt lang: de-de --- -- cgit v1.2.3 From 9ecbf76fe4c89ae3ca577a42cbf41a4b3e3497f0 Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Sat, 17 Oct 2015 13:18:27 -0430 Subject: tmux spanish translation --- es-es/tmux-es.html.markdown | 253 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 es-es/tmux-es.html.markdown diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From 8d809eac2e621daf92c609ed2cff6edeeedc983e Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:44:41 +0530 Subject: Updated translation --- ta_in/css.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index b55ab363..3a46816c 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -197,10 +197,6 @@ selector { ## Precedence or Cascade -An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. - -This process is called cascading, hence the name Cascading Style Sheets. - ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன இது Cascading Style Sheets என அழைக்கபடுகிறது. -- cgit v1.2.3 From 4143b1d87ed465eb8f0dffa07d299ebe82566d45 Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:46:03 +0530 Subject: removed EN Tamil translated added removed EN from markdown --- ta_in/css.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index 3a46816c..1e3aa9b0 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -102,8 +102,7 @@ div.some-parent.class-name { } /* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ .i-am-any-element-before ~ .this-element { } -/* There are some selectors called pseudo classes that can be used to select an - element when it is in a particular state +/* சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் */ -- cgit v1.2.3 From 29e35f633534fe81d478694c53585718c350b632 Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:47:25 +0530 Subject: updated removed white spaces and removed old EN translation --- ta_in/css.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index 1e3aa9b0..93c29bae 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -17,13 +17,11 @@ lang:in-ta ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் கூடிய இணையதளங்கள் உருவாகின. -CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page. + CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. - -This guide has been written for CSS 2, though CSS 3 is fast becoming popular. இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. **குறிப்பு:** @@ -226,7 +224,7 @@ p { property: value !important; }

``` -The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. + css முன்னுரிமை பின்வருமாறு * `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் * `F` இது இரண்டாவது காரணம் இது inline style. -- cgit v1.2.3 From 6b2fa0cd2b3f49d60e15207d288d58c4a0ba72ad Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:49:43 +0530 Subject: Commited translation ta --- ta_in/css.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index 93c29bae..56f94ed0 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -192,7 +192,7 @@ selector {

``` -## Precedence or Cascade +## Precedence அல்லது Cascade ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன -- cgit v1.2.3 From c245b7528501003a07fe7a88c23abfed480d12a5 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sat, 17 Oct 2015 20:20:33 +0200 Subject: Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: 7bc99fcaf4329b3c25cca671f62a03b67aa4d46e 8b7a2fff9a71b8fa8754947434b8b1f184ed2de1 e4c261567533921f35ce4e65ebfe6621a128992b 8909457ae46dc8fb151ef146acb3f6b8402f3407 de676b62b83fcaaa9977cca9adb9c38383b64f35 acc9a73c018a28a9c8ead7b108dd1fdfee7a797b 960ee4a1856db8eadb96277bb2422edfa8f2a81c f4022052471d6dc0a9c2fb8794e1352253b4c5ad --- it-it/bash-it.html.markdown | 72 ++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 30 deletions(-) diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index f892845f..af8823c4 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -13,13 +13,14 @@ contributors: filename: LearnBash.sh translators: - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] lang: it-it --- Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X. Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell. -[Per saperne di piu'.](http://www.gnu.org/software/bash/manual/bashref.html) +[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash @@ -34,32 +35,34 @@ echo Ciao mondo! echo 'Questa è la prima riga'; echo 'Questa è la seconda riga' # Per dichiarare una variabile: -VARIABILE="Una stringa" +Variabile="Una stringa" # Ma non così: -VARIABILE = "Una stringa" -# Bash stabilirà che VARIABILE è un comando da eseguire e darà un errore +Variabile = "Una stringa" +# Bash stabilirà che Variabile è un comando da eseguire e darà un errore # perchè non esiste. # Usare la variabile: -echo $VARIABILE -echo "$VARIABILE" -echo '$VARIABILE' +echo $Variabile +echo "$Variabile" +echo '$Variabile' # Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi # il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $. # Nota che ' (singolo apice) non espande le variabili! # Sostituzione di stringhe nelle variabili -echo ${VARIABILE/Una/A} +echo ${Variabile/Una/A} # Questo sostituirà la prima occorrenza di "Una" con "La" # Sottostringa di una variabile -echo ${VARIABILE:0:7} +Lunghezza=7 +echo ${Variabile:0:Lunghezza} # Questo ritornerà solamente i primi 7 caratteri # Valore di default per la variabile -echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} -# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0 +echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"} +# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0 +# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia. # Variabili builtin: # Ci sono delle variabili builtin molto utili, come @@ -71,31 +74,40 @@ echo "Argomenti dello script separati in variabili distinte: $1 $2..." # Leggere un valore di input: echo "Come ti chiami?" -read NOME # Nota che non abbiamo dovuto dichiarare una nuova variabile -echo Ciao, $NOME! +read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile +echo Ciao, $Nome! # Classica struttura if: # usa 'man test' per maggiori informazioni sulle condizionali -if [ $NOME -ne $USER ] +if [ $Nome -ne $USER ] then echo "Il tuo nome non è lo username" else echo "Il tuo nome è lo username" fi +# Nota: se $Name è vuoto, la condizione precedente viene interpretata come: +if [ -ne $USER ] +# che genera un errore di sintassi. Quindi il metodo sicuro per usare +# variabili che possono contenere stringhe vuote è il seguente: +if [ "$Name" -ne $USER ] ... +# che viene interpretato come: +if [ "" -ne $USER ] ... +# e dunque funziona correttamente. + # C'è anche l'esecuzione condizionale echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce" echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce" # Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre: -if [ $NOME == "Steve" ] && [ $ETA -eq 15 ] +if [ "$Nome" == "Steve" ] && [ "$Eta" -eq 15 ] then - echo "Questo verrà eseguito se $NOME è Steve E $ETA è 15." + echo "Questo verrà eseguito se $Nome è Steve E $Eta è 15." fi -if [ $NOME == "Daniya" ] || [ $NOME == "Zach" ] +if [ "$Nome" == "Daniya" ] || [ "$Nome" == "Zach" ] then - echo "Questo verrà eseguito se $NAME è Daniya O Zach." + echo "Questo verrà eseguito se $Nome è Daniya O Zach." fi # Le espressioni sono nel seguente formato: @@ -137,7 +149,7 @@ python hello.py > /dev/null 2>&1 # se invece vuoi appendere usa ">>": python hello.py >> "output.out" 2>> "error.err" -# Sovrascrivi output.txt, appendi a error.err, e conta le righe: +# Sovrascrivi output.out, appendi a error.err, e conta le righe: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err @@ -145,7 +157,7 @@ wc -l output.out error.err # vedi: man fd echo <(echo "#ciaomondo") -# Sovrascrivi output.txt con "#helloworld": +# Sovrascrivi output.out con "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out @@ -164,7 +176,7 @@ echo "Ci sono $(ls | wc -l) oggetti qui." echo "Ci sono `ls | wc -l` oggetti qui." # Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++: -case "$VARIABILE" in +case "$Variabile" in #Lista di pattern per le condizioni che vuoi soddisfare 0) echo "C'è uno zero.";; 1) echo "C'è un uno.";; @@ -172,10 +184,10 @@ case "$VARIABILE" in esac # I cicli for iterano per ogni argomento fornito: -# I contenuti di $VARIABILE sono stampati tre volte. -for VARIABILE in {1..3} +# I contenuti di $Variabile sono stampati tre volte. +for Variabile in {1..3} do - echo "$VARIABILE" + echo "$Variabile" done # O scrivilo con il "ciclo for tradizionale": @@ -186,16 +198,16 @@ done # Possono essere usati anche per agire su file.. # Questo eseguirà il comando 'cat' su file1 e file2 -for VARIABILE in file1 file2 +for Variabile in file1 file2 do - cat "$VARIABILE" + cat "$Variabile" done # ..o dall'output di un comando # Questo eseguirà cat sull'output di ls. -for OUTPUT in $(ls) +for Output in $(ls) do - cat "$OUTPUT" + cat "$Output" done # while loop: @@ -223,7 +235,7 @@ bar () } # Per chiamare la funzione -foo "Il mio nome è" $NOME +foo "Il mio nome è" $Nome # Ci sono un sacco di comandi utili che dovresti imparare: # stampa le ultime 10 righe di file.txt @@ -245,7 +257,7 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # se vuoi letteralmente cercare la stringa, # e non la regex, usa fgrep (o grep -F) -fgrep "^foo.*bar$" file.txt +fgrep "^foo.*bar$" file.txt # Leggi la documentazione dei builtin di bash con il builtin 'help' di bash: -- cgit v1.2.3 From a1217767d3dceb40dba35159abb523b233cf0005 Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Sat, 17 Oct 2015 14:05:01 -0430 Subject: tmux spanish translation --- es-es/tmux-es.html.markdown | 253 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 es-es/tmux-es.html.markdown diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From ba4f6d2bfb2f09ecc2892ab4dc0b8b35bb21fc1b Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sun, 18 Oct 2015 00:11:56 +0530 Subject: XML commits --- ta_in/xml.html.markdown | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/ta_in/xml.html.markdown b/ta_in/xml.html.markdown index 3ec0ab70..a9bfa9cd 100644 --- a/ta_in/xml.html.markdown +++ b/ta_in/xml.html.markdown @@ -42,15 +42,7 @@ HTML போல் அன்றி , XML ஆனது தகவலை மட் - - + - + -- cgit v1.2.3 From 989615be41c78eee9bfe5d7f3786dd5a90a40565 Mon Sep 17 00:00:00 2001 From: Gloria Dwomoh Date: Sun, 18 Oct 2015 00:02:18 +0300 Subject: Update scala-gr.html.markdown --- el-gr/scala-gr.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown index e29c7e70..415fda5c 100644 --- a/el-gr/scala-gr.html.markdown +++ b/el-gr/scala-gr.html.markdown @@ -40,7 +40,7 @@ Scala - Η επεκτάσιμη γλώσσα /* Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε - να δείτε , φαίνοται κάπως έτσι. + να δείτε , φαίνονται κάπως έτσι. */ // Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση @@ -59,12 +59,12 @@ var y = 10 y = 20 // το y είναι τώρα 20 /* - Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω + Η Scala είναι στατικού τύπου γλώσσα, εν τούτοις προσέξτε ότι στις παραπάνω δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να - μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε - αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: + μαντέψει ποιος είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιας μεταβλητής ως εξής: */ val z: Int = 10 val a: Double = 1.0 @@ -85,7 +85,7 @@ false true == false // false 10 > 5 // true -// Η αριθμιτική είναι όπως τα συνηθισμένα +// Η αριθμητική είναι όπως τα συνηθισμένα 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 @@ -117,14 +117,14 @@ true == false // false "Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" 'a' // Ένας χαρακτήρας στην Scala // res30: Char = a -// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. +// Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. // Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") -// Έχουν επίσης μερικές επιπλένον μεθόδους Scala. +// Έχουν επίσης μερικές επιπλέον μεθόδους Scala. // Δείτε επίσης : scala.collection.immutable.StringOps "hello world".take(5) "hello world".drop(5) @@ -253,7 +253,7 @@ r foreach println var i = 0 while (i < 10) { println("i " + i); i+=1 } -while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί; +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβη; Γιατί; i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή @@ -268,8 +268,8 @@ do { } while (x < 10) // Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα -// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί -// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γραφτεί +// ρητά ο τύπος που θα επιστρέψουν, αλλιώς ο μεταγλωττιστής δεν μπορεί // αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -332,7 +332,7 @@ s(1) val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα - // της ακαίρεας διαίρεσης και το υπόλοιπο. + // της ακέραιας διαίρεσης και το υπόλοιπο. // Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n // όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. @@ -349,7 +349,7 @@ d._2 /* Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις - (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις + (τιμές, συναρτήσεις, κτλ.). Αυτές οι εκφράσεις βολεύουν όταν τις γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα @@ -394,7 +394,7 @@ println(mydog.bark) // => "Woof, woof!" // αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances // της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις // μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. -// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +// Προσέξτε ότι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. object Dog { def allKnownBreeds = List("pitbull", "shepherd", "retriever") def createDog(breed: String) = new Dog(breed) @@ -402,7 +402,7 @@ object Dog { // Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον // λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην -// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις. +// Scala είναι πότε να χρησιμοποιούνται κλάσεις και πότε case κλάσεις. // Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον // πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις // τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. @@ -411,7 +411,7 @@ object Dog { // έχουν παρενέργειες. case class Person(name: String, phoneNumber: String) -// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes +// Δημιουργία ενός instance. Παρατηρήστε ότι τα case classes // δεν χρειάζονται την λέξη "new" . val george = Person("George", "1234") val kate = Person("Kate", "4567") @@ -419,7 +419,7 @@ val kate = Person("Kate", "4567") // Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: george.phoneNumber // => "1234" -// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// Ελέγχεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να // κάνουμε override στο .equals) Person("George", "1234") == Person("Kate", "1236") // => false @@ -509,7 +509,7 @@ List(1, 2, 3) map (x => x + 10) // ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. List(1, 2, 3) map (_ + 10) -// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// Αν το μπλοκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται // (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα // μπορείτε να παραλείψετε την κάτω παύλα. List("Dom", "Bob", "Natalia") foreach println -- cgit v1.2.3 From 3253734d4c03f93aa9b6a59d62733f0a3b683392 Mon Sep 17 00:00:00 2001 From: Lucas Moreira Date: Sat, 17 Oct 2015 19:53:33 -0300 Subject: =?UTF-8?q?Corre=C3=A7=C3=A3o=20de=20palavra.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/json-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fc63b126..e4f10a61 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -35,7 +35,7 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5], "outro objeto": { - "ccomentário": "Estas coisas podem ser aninhadas, muito úteis." + "comentário": "Estas coisas podem ser aninhadas, muito úteis." } }, -- cgit v1.2.3 From 65f951d87c80deff6c447faa4690dcfe1bb4d36a Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Sat, 17 Oct 2015 19:37:47 -0400 Subject: Added documentation on receive do blocks in Elixir. --- elixir.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/elixir.html.markdown b/elixir.html.markdown index 9fdf37e9..60f0b01c 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -369,6 +369,13 @@ spawn(f) #=> #PID<0.40.0> # messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is # achieved with the `receive` mechanism: + +# The `receive do` block is used to listen for messages and process +# them when they are received. A `receive do` block will only +# process one received message. In order to process multiple +# messages, a function with a `receive do` block must recursively +# call itself to get into the `receive do` block again. + defmodule Geometry do def area_loop do receive do -- cgit v1.2.3 From 9f510f3044138429ce616c390e42d8e0b6ceb2df Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Sat, 17 Oct 2015 19:50:09 -0400 Subject: Fixed indentation in csharp file. --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 59f3e42b..31c0417e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -395,8 +395,8 @@ on a new line! ""Wow!"", the masses cried"; ref int maxCount, // Pass by reference out int count) { - //the argument passed in as 'count' will hold the value of 15 outside of this function - count = 15; // out param must be assigned before control leaves the method + //the argument passed in as 'count' will hold the value of 15 outside of this function + count = 15; // out param must be assigned before control leaves the method } // GENERICS -- cgit v1.2.3 From c613e3bc6a3c59214faaa6e6273cb98ab8a97c1d Mon Sep 17 00:00:00 2001 From: Romin Irani Date: Sun, 18 Oct 2015 06:19:24 +0530 Subject: Added Git and Github Tutorial Link --- git.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 72079f6c..e9d62b69 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -499,3 +499,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + -- cgit v1.2.3 From 07e04e7a2d0f2b7269e4495c338b039a30f70e64 Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Sat, 17 Oct 2015 20:49:58 -0400 Subject: Fixed spacing with Elixir comment. --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 60f0b01c..eedeb227 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -391,7 +391,7 @@ end # Compile the module and create a process that evaluates `area_loop` in the shell pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> -#Alternatively +# Alternatively pid = spawn(Geometry, :area_loop, []) # Send a message to `pid` that will match a pattern in the receive statement -- cgit v1.2.3 From 24f9fd6ba53213568192f5dbb61fc7b66f457841 Mon Sep 17 00:00:00 2001 From: Romin Irani Date: Sun, 18 Oct 2015 06:27:36 +0530 Subject: Added tmuxinator in References --- tmux.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tmux.html.markdown b/tmux.html.markdown index c11da5fc..49d1bba6 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -249,3 +249,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) + + -- cgit v1.2.3 From 53366ebdbeecb502131c2768979e4b6ed9d59d9f Mon Sep 17 00:00:00 2001 From: venegu Date: Sat, 17 Oct 2015 22:21:25 -0400 Subject: Adding modulo division to JavaScript article --- javascript.html.markdown | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 34ba9b47..937354eb 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -54,6 +54,11 @@ doStuff() // Including uneven division. 5 / 2; // = 2.5 +// And modulo division. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 @@ -104,7 +109,7 @@ null == undefined; // = true // ...unless you use === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...which can result in some weird behaviour... 13 + !0; // 14 @@ -220,15 +225,15 @@ for (var i = 0; i < 5; i++){ //The For/In statement loops iterates over every property across the entire prototype chain var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; } -//If only want to consider properties attached to the object itself, +//If only want to consider properties attached to the object itself, //and not its prototypes use hasOwnProperty() check var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ if (person.hasOwnProperty(x)){ description += person[x] + " "; -- cgit v1.2.3 From 0c227ddf87f8ea4bd849dbd98886a815178affad Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sun, 18 Oct 2015 11:35:38 +0530 Subject: json values translated to tamil --- ta_in/json.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ta_in/json.html.markdown b/ta_in/json.html.markdown index 777dfaeb..d85e0d82 100644 --- a/ta_in/json.html.markdown +++ b/ta_in/json.html.markdown @@ -42,29 +42,29 @@ Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. ```json { - "key": "value", + "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ", - "keys": "must always be enclosed in double quotes", + "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்", "numbers": 0, - "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".", "has bools?": true, "nothingness": null, "big number": 1.2e+100, "objects": { - "comment": "Most of your structure will come from objects.", + "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன", - "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5], "another object": { - "comment": "These things can be nested, very useful." + "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்" } }, "silliness": [ { - "sources of potassium": ["bananas"] + "sources of potassium": ["வாழைபழம்"] }, [ [1, 0, 0, 0], @@ -75,12 +75,12 @@ Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. ], "alternative style": { - "comment": "check this out!" + "comment": "இதை பார்க்கவும்" , "comma position": "doesn't matter - as long as it's before the value, then it's valid" , "another comment": "how nice" }, - "that was short": "And, you're done. You now know everything JSON has to offer." + "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்" } ``` -- cgit v1.2.3 From 10d0865214928a396bdb9d2ef187ed90b48a975c Mon Sep 17 00:00:00 2001 From: Saurabh Sandav Date: Sun, 18 Oct 2015 13:21:31 +0530 Subject: [whip/en] Fix typos --- whip.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/whip.html.markdown b/whip.html.markdown index 3faee98a..61c301a5 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -2,6 +2,7 @@ language: whip contributors: - ["Tenor Biel", "http://github.com/L8D"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] author: Tenor Biel author_url: http://github.com/L8D filename: whip.lisp @@ -93,13 +94,13 @@ null ; used to indicate a deliberate non-value undefined ; user to indicate a value that hasn't been set ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Vairbles, Lists, and Dicts +; 2. Variables, Lists, and Dicts ; Variables are declared with the `def` or `let` functions. ; Variables that haven't been set will be `undefined`. (def some_var 5) ; `def` will keep the variable in the global context. -; `let` will only have the variable inside its context, and has a wierder syntax. +; `let` will only have the variable inside its context, and has a weirder syntax. (let ((a_var 5)) (+ a_var 5)) ; => 10 (+ a_var 5) ; = undefined + 5 => undefined @@ -163,7 +164,7 @@ undefined ; user to indicate a value that hasn't been set (my_function 10 10) ; = (+ (+ 10 10) 10) => 30 -; Obiously, all lambdas by definition are anonymous and +; Obviously, all lambdas by definition are anonymous and ; technically always used anonymously. Redundancy. ((lambda (x) x) 10) ; => 10 @@ -191,7 +192,7 @@ undefined ; user to indicate a value that hasn't been set (slice (.. 1 5) 2) ; => (3 4 5) (\ (.. 0 100) -5) ; => (96 97 98 99 100) -; `append` or `<<` is self expanatory +; `append` or `<<` is self explanatory (append 4 (1 2 3)) ; => (1 2 3 4) (<< "bar" ("foo")) ; => ("foo" "bar") -- cgit v1.2.3 From 35b921505b38ff3686c79826aadde9847e9b2f53 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 11:42:37 +0200 Subject: [c++/it] Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: 462ac892179d64437b1124263402378a6054e50b 3db1042157204ad05484d6b42140261f849040cc cea52ca43490b74316781c23779654fd46aaeab4 47d3cea47e8c5203efa857070a00dcfbff67b019 894792e1e17173823a5d50de24439427c69d63f4 06889be239622266d9c36c750f7ee755ccdae05d 97b97408eab97fbe322df4266cda9ab2ed21fceb 1d1def16a5d7925bb8f7fba7dc49182e33359e85 a230d76307ecbc0f53c4b359cdb90628720f915e fc9ae44e4887500634bf3a87343d687b4d7d4e3c 85f6ba0b57b9d894c694df66449b1e1c555c625b 8eb410208a8d9b0a42f6c52411455ace04c78101 ae86e4ebabb0c78c1bd8052e6ab5916446ef39c2 455afa3a7bf59fc272f3439825da55659765eec0 12286a4b78f82bde3907d4bf348e20c12dd6d46f 9bc553c46ce9b7154ec7c82451d71608f4beda82 87e8e77e5fd8d84a252dbb6d6697202118378774 3b246fd869564b0a7f7c847f44aecac82d318c78 9d64b532f8ccdfd95c2417dcf65257385956353a e32eb715ef41e411da0a91b40e6e35f150a9c2eb ca435fbb0dd09cdc9c70fe945a891ae3e6c19ab2 --- it-it/c++-it.html.markdown | 211 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 185 insertions(+), 26 deletions(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index e7e1d89e..92ebc165 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -4,6 +4,8 @@ filename: learncpp-it.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] translators: - ["Robert Margelli", "http://github.com/sinkswim/"] lang: it-it @@ -54,11 +56,11 @@ int main(int argc, char** argv) // Tuttavia, il C++ varia nei seguenti modi: -// In C++, i caratteri come letterali sono da un byte. -sizeof('c') == 1 +// In C++, i caratteri come letterali sono dei char. +sizeof('c') == sizeof(char) == 1 -// In C, i caratteri come letterali sono della stessa dimensione degli interi. -sizeof('c') == sizeof(10) +// In C, i caratteri come letterali sono degli interi. +sizeof('c') == sizeof(int) // C++ ha prototipizzazione rigida @@ -160,11 +162,14 @@ void foo() int main() { - // Assume che tutto venga dal namespace "Secondo" - // a meno che non venga dichiarato altrimenti. + // Include tutti i simboli del namespace Secondo nello scope attuale. + // Osserva che chiamare semplicemente foo() non va più bene perché è ambiguo: + // bisogna specificare se vogliamo chiamare foo definita nel namespace Secondo + // o foo definita nel livello principale del programma. + using namespace Secondo; - foo(); // stampa "Questa è Secondo::foo" + Secondo::foo(); // stampa "Questa è Secondo::foo" Primo::Annidato::foo(); // stampa "Questa è Primo::Annidato::foo" ::foo(); // stampa "Questa è foo globale" } @@ -244,12 +249,137 @@ cout << fooRef; // Stampa "Io sono foo. Ciao!" // Non riassegna "fooRef". Questo è come scrivere "foo = bar", e // foo == "Io sono bar" // dopo questa riga. +cout << &fooRef << endl; // Stampa l'indirizzo di foo fooRef = bar; +cout << &fooRef << endl; // Stampa lo stesso l'indirizzo di foo +cout << fooRef; // Stampa "Io sono bar" + +// L'indirizzo di fooRef rimane lo stesso, ovvero si riferisce ancora a foo. + const string& barRef = bar; // Crea un riferimento const a bar. // Come in C, i valori const (i puntatori e i riferimenti) non possono essere modificati. barRef += ". Ciao!"; // Errore, i riferimenti const non possono essere modificati. +// Facciamo un piccolo excursus: prima di approfondire ancora i riferimenti, è necessario +// introdurre il concetto di oggetto temporaneo. Supponiamo di avere il seguente codice: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Nella seconda riga si ha che: +// - un oggetto di tipo stringa viene ritornato da tempObjectFun +// - viene costruita una nuova stringa, utilizzando l'oggetto ritornato come +// argomento per il costruttore +// - l'oggetto ritornato da tempObjectFun viene distrutto +// L'oggetto ritornato da tempObjectFun viene detto oggetto temporaneo. +// Un oggetto temporaneo viene creato quando una funzione ritorna un oggetto, e viene +// distrutto quando l'espressione che lo racchiude termina la sua esecuzione - questo +// comportamento viene definito dallo standard, ma i compilatori possono modificarlo +// a piacere. Cerca su google "return value optimization" se vuoi approfondire. +// Dunque nel seguente codice: +foo(bar(tempObjectFun())) + +// dando per scontato che foo e bar esistano, l'oggetto ritornato da tempObjectFun +// è passato a bar ed è distrutto prima dell'invocazione di foo. + +// Tornando ai riferimenti, c'è un'eccezione a quanto appena detto. +// Infatti un oggetto temporaneo "viene distrutto quando l'espressione +// che lo racchiude termina la sua esecuzione", tranne quando è legato ad un +// riferimento di tipo const. In tal caso la sua vita viene estesa per tutto +// lo scope attuale: + +void constReferenceTempObjectFun() { + // constRef riceve l'oggetto temporaneo, che non viene distrutto fino + // alla fine di questa funzione. + const string& constRef = tempObjectFun(); + ... +} + +// Un altro tipo di riferimento introdotto nel C++11 è specifico per gli +// oggetti temporanei. Non puoi dichiarare una variabile di quel tipo, ma +// ha la precedenza nella risoluzione degli overload: + +void someFun(string& s) { ... } // Riferimento normale +void someFun(string&& s) { ... } // Riferimento ad un oggetto temporaneo + +string foo; +someFun(foo); // Chiama la versione con il riferimento normale +someFun(tempObjectFun()); // Chiama la versione con il riferimento temporaneo + +// Ad esempio potrai vedere questi due costruttori per std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// L'idea è che se noi costruiamo una nuova stringa a partire da un oggetto temporaneo +// (che in ogni caso verrà distrutto), possiamo avere un costruttore più efficiente +// che in un certo senso "recupera" parti di quella stringa temporanea. +// Ci si riferisce a questo concetto come "move semantics". + +///////////////////// +// Enum +///////////////////// + +// Gli enum sono un modo per assegnare un valore ad una costante, e sono +// principalmente usati per rendere il codice più leggibile. +enum ETipiMacchine +{ + AlfaRomeo, + Ferrari, + SUV, + Panda +}; + +ETipiMacchine GetPreferredCarType() +{ + return ETipiMacchine::Ferrari; +} + +// Dal C++11 in poi c'è un modo molto semplice per assegnare un tipo ad un enum, +// che può essere utile per la serializzazione dei dati o per convertire gli enum +// tra il tipo desiderato e le rispettive costanti. +enum ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // L'enum viene implicitamente convertito ad un uint8_t poiché + // è stato dichiarato come tale + WriteByteToFile(InputCarType); +} + +// D'altro canto potresti voler evitare che un enum venga accidentalmente convertito +// in un intero o in un altro tipo, quindi è possibile create una classe enum che +// impedisce la conversione implicita. +enum class ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // Il compilatore darà errore anche se ETipiMacchine è un uint8_t: questo + // perchè abbiamo dichiarato l'enum come "enum class"! + WriteByteToFile(InputCarType); +} + ////////////////////////////////////////////////// // Classi e programmazione orientata agli oggetti ///////////////////////////////////////////////// @@ -296,13 +426,16 @@ public: // Questi sono chiamati quando un oggetto è rimosso o esce dalla visibilità. // Questo permette paradigmi potenti come il RAII // (vedi sotto) - // I distruttori devono essere virtual per permettere a classi di essere derivate da questa. + // I distruttori devono essere virtual per permettere a classi di essere + // derivate da questa; altrimenti, il distruttore della classe derivata + // non viene chiamato se l'oggetto viene distrutto tramite un riferimento alla + // classe da cui ha ereditato o tramite un puntatore. virtual ~Dog(); }; // Un punto e virgola deve seguire la definizione della funzione // Le funzioni membro di una classe sono generalmente implementate in files .cpp . -void Cane::Cane() +Cane::Cane() { std::cout << "Un cane è stato costruito\n"; } @@ -325,7 +458,7 @@ void Cane::print() const std::cout << "Il cane è " << nome << " e pesa " << peso << "kg\n"; } -void Cane::~Cane() +Cane::~Cane() { cout << "Ciao ciao " << nome << "\n"; } @@ -340,10 +473,12 @@ int main() { // Ereditarietà: -// Questa classe eredita tutto ciò che è public e protected dalla classe Cane +// Questa classe eredita tutto ciò che è public e protected dalla classe Cane, +// ma anche ciò che privato: tuttavia non potrà accedere direttamente a membri/metodi +// privati se non c'è un metodo pubblico o privato che permetta di farlo. class MioCane : public Cane { - void impostaProprietario(const std::string& proprietarioCane) + void impostaProprietario(const std::string& proprietarioCane); // Sovrascrivi il comportamento della funzione print per tutti i MioCane. Vedi // http://it.wikipedia.org/wiki/Polimorfismo_%28informatica%29 @@ -447,6 +582,7 @@ int main () { // definire una classe o una funzione che prende un parametro di un dato tipo: template class Box { +public: // In questa classe, T può essere usato come qualsiasi tipo. void inserisci(const T&) { ... } }; @@ -519,19 +655,23 @@ printMessage<10>(); // Stampa "Impara il C++ più velocemente in soli 10 minuti // (vedi http://en.cppreference.com/w/cpp/error/exception) // ma ogni tipo può essere lanciato come eccezione #include +#include // Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi // handlers _catch_. try { // Non allocare eccezioni nello heap usando _new_. - throw std::exception("È avvenuto un problema"); + throw std::runtime_error("C'è stato un problema."); } + // Cattura le eccezioni come riferimenti const se sono oggetti catch (const std::exception& ex) { - std::cout << ex.what(); + std::cout << ex.what(); +} + // Cattura ogni eccezioni non catturata dal blocco _catch_ precedente -} catch (...) +catch (...) { std::cout << "Catturata un'eccezione sconosciuta"; throw; // Rilancia l'eccezione @@ -541,7 +681,7 @@ catch (const std::exception& ex) // RAII /////// -// RAII sta per Resource Allocation Is Initialization. +// RAII sta per "Resource Allocation Is Initialization". // Spesso viene considerato come il più potente paradigma in C++. // È un concetto semplice: un costruttore di un oggetto // acquisisce le risorse di tale oggetto ed il distruttore le rilascia. @@ -563,9 +703,9 @@ void faiQualcosaConUnFile(const char* nomefile) // Sfortunatamente, le cose vengono complicate dalla gestione degli errori. // Supponiamo che fopen fallisca, e che faiQualcosaConUnFile e // faiQualcosAltroConEsso ritornano codici d'errore se falliscono. -// (Le eccezioni sono la maniera preferita per gestire i fallimenti, -// ma alcuni programmatori, specialmente quelli con un passato in C, -// non sono d'accordo con l'utilità delle eccezioni). +// (Le eccezioni sono la maniera preferita per gestire i fallimenti, +// ma alcuni programmatori, specialmente quelli con un passato in C, +// non sono d'accordo con l'utilità delle eccezioni). // Adesso dobbiamo verificare che ogni chiamata per eventuali fallimenti e chiudere il gestore di file // se un problema è avvenuto. bool faiQualcosaConUnFile(const char* nomefile) @@ -615,7 +755,7 @@ void faiQualcosaConUnFile(const char* nomefile) { FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura if (fh == nullptr) - throw std::exception("Non è stato possibile aprire il file."). + throw std::runtime_error("Errore nell'apertura del file."); try { faiQualcosaConIlFile(fh); @@ -678,26 +818,29 @@ class Foo { virtual void bar(); }; class FooSub : public Foo { - virtual void bar(); // sovrascrive Foo::bar! + virtual void bar(); // Sovrascrive Foo::bar! }; // 0 == false == NULL (la maggior parte delle volte)! bool* pt = new bool; -*pt = 0; // Setta il valore puntato da 'pt' come falso. +*pt = 0; // Setta il valore puntato da 'pt' come falso. pt = 0; // Setta 'pt' al puntatore null. Entrambe le righe vengono compilate senza warnings. // nullptr dovrebbe risolvere alcune di quei problemi: int* pt2 = new int; -*pt2 = nullptr; // Non compila +*pt2 = nullptr; // Non compila pt2 = nullptr; // Setta pt2 a null. -// Ma in qualche modo il tipo 'bool' è una eccezione (questo è per rendere compilabile `if (ptr)`. -*pt = nullptr; // Questo compila, anche se '*pt' è un bool! +// C'è un'eccezione per i bool. +// Questo permette di testare un puntatore a null con if(!ptr), ma +// come conseguenza non puoi assegnare nullptr a un bool direttamente! +*pt = nullptr; // Questo compila, anche se '*pt' è un bool! // '=' != '=' != '='! -// Chiama Foo::Foo(const Foo&) o qualche variante del costruttore di copia. +// Chiama Foo::Foo(const Foo&) o qualche variante (vedi "move semantics") +// del costruttore di copia. Foo f2; Foo f1 = f2; @@ -711,6 +854,22 @@ Foo f1 = fooSub; Foo f1; f1 = f2; + +// Come deallocare realmente le risorse all'interno di un vettore: +class Foo { ... }; +vector v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// La riga seguente riduce la dimensione di v a 0, ma il distruttore non +// viene chiamato e dunque le risorse non sono deallocate! +v.empty(); +v.push_back(Foo()); // Il nuovo valore viene copiato nel primo Foo che abbiamo inserito + +// Distrugge realmente tutti i valori dentro v. Vedi la sezione riguardante gli +// oggetti temporanei per capire come mai funziona così. +v.swap(vector()); + ``` Letture consigliate: -- cgit v1.2.3 From c23bba2b6010e659d518f144d689102d0e9fb147 Mon Sep 17 00:00:00 2001 From: Cameron Wood Date: Sun, 18 Oct 2015 05:46:35 -0400 Subject: [javascript/en] Small typo fix Just a simple 1-word typo fix --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 937354eb..9c4f06fc 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -324,7 +324,7 @@ i; // = 5 - not undefined as you'd expect in a block-scoped language // scope. (function(){ var temporary = 5; - // We can access the global scope by assiging to the "global object", which + // We can access the global scope by assigning to the "global object", which // in a web browser is always `window`. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; -- cgit v1.2.3 From 1aaf79b6e56b7d4947335dd60613f8096b66b0d9 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 13:26:58 +0200 Subject: [coffeescript/it] Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: 7afadb01811e1fb97a928a0e2d8b1a3b7a3a42f6 960ee4a1856db8eadb96277bb2422edfa8f2a81c a67d9d9e0ed3d351ce0139de18a4b212b47ab9cb d115a86ac8602c680a059e7a53d227cbccdf157a ef40704f9b66ae85d7a8a6853abbbf8810af3b90 --- it-it/coffeescript-it.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index 16eb9bd4..d30ba819 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -59,34 +59,34 @@ matematica = quadrato: quadrato cubo: (x) -> x * quadrato x #=> var matematica = { -# "radice": Math.sqrt, -# "quadrato": quadrato, -# "cubo": function(x) { return x * quadrato(x); } -#} +# "radice": Math.sqrt, +# "quadrato": quadrato, +# "cubo": function(x) { return x * quadrato(x); } +# } # Splats: gara = (vincitore, partecipanti...) -> print vincitore, partecipanti #=>gara = function() { -# var partecipanti, vincitore; -# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; -# return print(vincitore, partecipanti); -#}; +# var partecipanti, vincitore; +# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vincitore, partecipanti); +# }; # Esistenza: alert "Lo sapevo!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); } # Comprensione degli Array: -cubi = (matematica.cubo num for num in lista) +cubi = (matematica.cubo num for num in lista) #=>cubi = (function() { -# var _i, _len, _results; -# _results = []; -# for (_i = 0, _len = lista.length; _i < _len; _i++) { -# num = lista[_i]; -# _results.push(matematica.cubo(num)); -# } -# return _results; +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lista.length; _i < _len; _i++) { +# num = lista[_i]; +# _results.push(matematica.cubo(num)); +# } +# return _results; # })(); cibi = ['broccoli', 'spinaci', 'cioccolato'] -- cgit v1.2.3 From ade3e872abaa21bb00bc0eaafdabce8bc5039399 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 13:34:40 +0200 Subject: [elixir/it] Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: d8001da79909734d333de31079ca2f4d884a6b21 65f951d87c80deff6c447faa4690dcfe1bb4d36a 07e04e7a2d0f2b7269e4495c338b039a30f70e64 --- it-it/elixir-it.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown index f5d0c172..d4a7ab54 100644 --- a/it-it/elixir-it.html.markdown +++ b/it-it/elixir-it.html.markdown @@ -379,6 +379,12 @@ spawn(f) #=> #PID<0.40.0> # Per passare messaggi si usa l'operatore `send`. # Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, # oltre ad inviarli. Questo è realizzabile con `receive`: + +# Il blocco `receive do` viene usato per mettersi in ascolto di messaggi +# ed elaborarli quando vengono ricevuti. Un blocco `receive do` elabora +# un solo messaggio ricevuto: per fare elaborazione multipla di messaggi, +# una funzione con un blocco `receive do` al suo intero dovrà chiamare +# ricorsivamente sé stessa per entrare di nuovo nel blocco `receive do`. defmodule Geometria do def calcolo_area do receive do @@ -394,6 +400,8 @@ end # Compila il modulo e crea un processo che esegue `calcolo_area` nella shell pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0> +# Alternativamente +pid = spawn(Geometria, :calcolo_area, []) # Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive send pid, {:rettangolo, 2, 3} -- cgit v1.2.3 From 90334770b6ffe4e690aedc20f678be95a93177d4 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 13:36:42 +0200 Subject: Add myself as a translator --- it-it/coffeescript-it.html.markdown | 2 ++ it-it/elixir-it.html.markdown | 2 ++ 2 files changed, 4 insertions(+) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index d30ba819..31973369 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Luca 'Kino' Maroni", "http://github.com/kino90"] - ["Tenor Biel", "http://github.com/L8D"] - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: coffeescript-it.coffee lang: it-it --- diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown index d4a7ab54..60301b1a 100644 --- a/it-it/elixir-it.html.markdown +++ b/it-it/elixir-it.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Luca 'Kino' Maroni", "https://github.com/kino90"] - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: learnelixir-it.ex lang: it-it --- -- cgit v1.2.3 From 670e71c4990aefe739f108e15bf707eaf795f922 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sun, 18 Oct 2015 13:47:03 +0200 Subject: [git/en] Fixed 'git pull' documentation While translating git.html.markdown to Italian, I found a mistake: `git pull` does not default to `git pull origin master`. By default, it updates the current branch by merging changes from its remote-tracking branch. --- git.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index f678f9d1..ed9aec15 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -371,9 +371,12 @@ Pulls from a repository and merges it with another branch. # Update your local repo, by merging in new changes # from the remote "origin" and "master" branch. # git pull -# git pull => implicitly defaults to => git pull origin master $ git pull origin master +# By default, git pull will update your current branch +# by merging in new changes from its remote-tracking branch +$ git pull + # Merge in changes from remote branch and rebase # branch commits onto your local repo, like: "git pull , git rebase " $ git pull origin master --rebase -- cgit v1.2.3 From 6d20f58cbd3022fb8990ace8f88f8f4c15591a88 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sun, 18 Oct 2015 13:54:06 +0200 Subject: [git/en] Fixed 'git push' documentation The 'git push' documentation had the same problem of the 'git pull' one I just fixed. --- git.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index ed9aec15..bedc9853 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -390,9 +390,12 @@ Push and merge changes from a branch to a remote & branch. # Push and merge changes from a local repo to a # remote named "origin" and "master" branch. # git push -# git push => implicitly defaults to => git push origin master $ git push origin master +# By default, git push will push and merge changes from +# the current branch to its remote-tracking branch +$ git push + # To link up current local branch with a remote branch, add -u flag: $ git push -u origin master # Now, anytime you want to push from that same local branch, use shortcut: -- cgit v1.2.3 From ada99b909743220fd7df2f379dbdb4859e4e5c2a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 18 Oct 2015 11:56:16 -0500 Subject: Update ColdFusion header --- coldfusion.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index e2f0737d..70804a1e 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -1,14 +1,14 @@ --- -language: ColdFusion +language: coldfusion +filename: learncoldfusion.cfm contributors: - ["Wayne Boka", "http://wboka.github.io"] -filename: LearnColdFusion.cfm --- ColdFusion is a scripting language for web development. [Read more here.](http://www.adobe.com/products/coldfusion-family.html) -```ColdFusion +```html HTML tags have been provided for output readability -- cgit v1.2.3 From 3a968a826b621c0e484268532d6b96a7b2865c8a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 18 Oct 2015 12:22:33 -0500 Subject: Fix issue with calling block code. Fixes https://github.com/adambard/learnxinyminutes-docs/issues/1598 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 30bb8843..f130ea0c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -688,7 +688,7 @@ addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any pa mutableVar = 32; // Assigning new value to __block variable. return n + outsideVar; // Return statements are optional. } -int addUp = add(10 + 16); // Calls block code with arguments. +int addUp = addUp(10 + 16); // Calls block code with arguments. // Blocks are often used as arguments to functions to be called later, or for callbacks. @implementation BlockExample : NSObject -- cgit v1.2.3