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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 001a99b13a6dad47937d475e5b960728d9baf9a6 Mon Sep 17 00:00:00 2001 From: Tim Heaney Date: Mon, 5 Oct 2015 21:18:50 -0400 Subject: Typo: should be variable, not varaible --- erlang.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 48cee6ec..4e2f1d84 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -35,7 +35,7 @@ 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. 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. +% variable 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. -- cgit v1.2.3 From 5e11d06a4f131302956334e76c989fb935ad9709 Mon Sep 17 00:00:00 2001 From: Tim Heaney Date: Mon, 5 Oct 2015 22:19:59 -0400 Subject: Typo: should be advice, not advise. --- rust.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index 4fbd6144..3157fcf4 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -14,7 +14,7 @@ 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. +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 compatibility. Improvements to compile times and other aspects of the compiler are -- cgit v1.2.3 From 57ad6d412d829be6ebedfffaf0ea16341cc12cd1 Mon Sep 17 00:00:00 2001 From: Tim Heaney Date: Mon, 5 Oct 2015 22:46:03 -0400 Subject: Typo: "too many" rather than "to many" --- tcl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index af2911c9..3982807f 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -356,7 +356,7 @@ eval $command ;# There is an error here, because there are too many arguments \ set replacement {Archibald Sorbisol} set command {set name $replacement} set command [subst $command] -eval $command ;# The same error as before: to many arguments to "set" in \ +eval $command ;# The same error as before: too many arguments to "set" in \ {set name Archibald Sorbisol} -- cgit v1.2.3 From ca85ca56da67faacb06dee27c19b9e465c987538 Mon Sep 17 00:00:00 2001 From: Pascal Boutin Date: Tue, 6 Oct 2015 00:13:29 -0400 Subject: first draft of the french version of the PHP manual --- fr-fr/php.html.markdown | 690 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 690 insertions(+) create mode 100644 fr-fr/php.html.markdown diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown new file mode 100644 index 00000000..b7b41ebe --- /dev/null +++ b/fr-fr/php.html.markdown @@ -0,0 +1,690 @@ +--- +language: PHP +contributors: + - ["Pascal Boutin", "http://pboutin.net/"] +filename: learnphp.php +lang: fr-fr +--- + +This document describes PHP 5+. + +```php + // Le code PHP doit être placé à l'intérieur de tags '' + +// Deux barres obliques amorcent un commentaire simple. + +# Le dièse également, bien que les barres obliques soient plus courantes + +/* + Les barres obliques et les astérisques peuvent être utilisés + pour faire un commentaire multi-ligne. +*/ + +// Utilisez "echo" ou "print" afficher une sortie +print('Hello '); // Affiche "Hello " sans retour à la ligne + +// Les parenthèses sont facultatives pour print et echo +echo "World\n"; // Affiche "World" avec un retour à la ligne +// tout les instructions doivent se terminer par un point-virgule + +// Tout ce qui se trouve en dehors des est automatiquement +// affiché en sortie +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (un 0 devant la valeur désigne une valeur octale) +$int4 = 0x0F; // => 15 (un 0x devant la valeur désigne une valeur hexadécimale) + +// Réels (floats, doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Suppression d'une variable +unset($int1); + +// Arithmétique +$sum = 1 + 1; // 2 (addition) +$difference = 2 - 1; // 1 (soustraction) +$product = 2 * 2; // 4 (produit) +$quotient = 2 / 1; // 2 (division) + +// Arithmétique (raccourcis) +$number = 0; +$number += 2; // Incrémente $number de 2 +echo $number++; // Affiche 1 (incrémente après l'évaluation) +echo ++$number; // Affiche 3 (incrémente après l'évaluation) +$number /= $float; // Divise et assigne le quotient à $number + +// Les chaînes de caractères (strings) doivent être à +// l'intérieur d'une paire d'apostrophes +$sgl_quotes = '$String'; // => '$String' + +// Évitez les guillemets sauf pour inclure le contenu d'une autre variable +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Les caractères spéciaux sont seulement échappé avec des guillemets +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// En cas de besoins, placez la variable dans des accolades +$money = "I have $${number} in the bank."; + +// Depuis PHP 5.3, nowdocs peut être utilisé pour faire des chaînes +// multi-lignes non-interprétées +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs peut être utilisé pour faire des chaînes multi-lignes interprétées +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 a introduit une nouvelle syntaxe +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // affiche 1 + +// Dans une liste simple, l'index est automatiquement attribué en tant que clé +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Ajoute un élément à la fin du tableau +$array[] = 'Four'; + +// Retrait d'un élément d'un tableau +unset($array[3]); + +/******************************** + * Affichage + */ + +echo('Hello World!'); +// Affiche Hello World! dans stdout. +// Stdout est la page web si on exécute depuis un navigateur. + +print('Hello World!'); // Pareil à "écho" + +// Pour écho, vous n'avez pas besoin des parenthèses +echo 'Hello World!'; +print 'Hello World!'; // Pour print non plus + +$paragraph = 'paragraph'; + +echo 100; // Affichez un scalaire directement +echo $paragraph; // ou des variables + +// Si le raccourci de sortie est configuré, ou si votre version de PHP est +// 5.4.0+, vous pouvez utiliser ceci: +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Affiche le type et la valeur de la variable dans stdout +var_dump($z); // prints int(0) + +// Affiche la variable dans stdout dans un format plus accessible +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logique + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert affiche un avertissement dans son argument n'est pas vrai + +// Ces comparaisons vont toujours être vrais, même si leurs +// types ne sont pas les mêmes. +assert($a == $b); // égalité +assert($c != $a); // inégalité +assert($c <> $a); // inégalité (moins courant) +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Ces comparaisons vont seulement être vrais si les types concordent. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Opérateur 'spaceship' depuis PHP 7 +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 car ils sont égaux +echo $a <=> $b; // -1 car $a < $b +echo $b <=> $a; // 1 car $b > $a + +// Les variables peuvent être transtypées dépendant de leur usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 + +$string = 'one'; +echo $string + $string; // => 0 +// Donne 0 car l'opérateur + ne peut pas transtyper la chaîne 'one' en un nombre + +// On peut également transtyper manuellement pour utiliser +// une variable dans un autre type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// Il y a également des fonctions dédiées pour transtyper +$integer = 5; +$string = strval($integer); + +$var = null; // Valeur Null + + +/******************************** + * Structures de contrôle + */ + +if (true) { + print 'Je suis affiché'; +} + +if (false) { + print 'Je ne le suis pas'; +} else { + print 'Je suis affiché'; +} + +if (false) { + print 'Je ne suis pas affiché'; +} elseif (true) { + print 'Je le suis'; +} + +// Opérateur ternaire +print (false ? 'N\'est pas affiché' : 'L\'est'); + +// Opérateur ternaire depuis PHP 5.3 +// équivalent de $x ? $x : 'Does' +$x = false; +print($x ?: 'Does'); + +// depuis PHP 7, on peut facilement vérifier si une valeur est nulle +$a = null; +$b = 'Hello World'; +echo $a ?? 'a is not set'; // Affiche 'a is not set' +echo $b ?? 'b is not set'; // Affiche 'Hello World' + + +$x = 0; +if ($x === '0') { + print 'Pas affiché'; +} elseif($x == '1') { + print 'Pas affiché'; +} else { + print 'Affiché'; +} + + +// Cette syntaxe alternative est particulièrement utile avec du HTML: +?> + + +

Ceci est affiché si $x est vrai

+ +

Sinon ce sera ceci

+ + + 2, 'car' => 4]; + +// Les boucles 'foreach' sont utiles pour parcourir les tableaux +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Affiche "24" + +echo "\n"; + +// Il est également possible d'accéder aux clés du tableau +foreach ($wheels as $vehicle => $wheel_count) { + echo "Le $vehicle a $wheel_count roues"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Permet d'arrêter la boucle + } + echo $i++; +} // Affiche "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Permet de passer imédiatement à l'itération suivante + } + echo $i; +} // Affiche "0124" + + +/******************************** + * Fonctions + */ + +// On peut déclarer une fonction avec le mot clé 'function' +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// Un nom de fonction valide doit débuter par une lettre ou un souligné, +// suivi de n'importe, quelles lettres, nombres ou soulignés. + +function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result n'est pas accessible en dehors de la fonction +// print $result; // Retourne un avertissement + +// Depuis PHP 5.3 on peut déclarer des fonctions anonymes +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Une fonction peut retourner une fonction +function bar ($x, $y) { + // On peut utiliser 'use' pour passer des variables externes + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Affiche "A - B - C" + +// On peut exécuter une fonction par son nom en chaîne de caractères +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Utile pour déterminer par programmation quelle fonction exécuter. + +// On peut également utiliser +call_user_func(callable $callback [, $parameter [, ... ]]); + +/******************************** + * Insertions + */ + +instanceProp = $instanceProp; + } + + // Les méthodes sont déclarés par des fonctions au sein de la classe + public function myMethod() + { + print 'MyClass'; + } + + // le mot clé 'final' rend la function impossible à surcharger + final function youCannotOverrideMe() + { + } + +/* + * Les attributs et méthodes statiques peuvent être accédés sans devoir + * instancier la classe. Les attributs statiques ne sont pas accessibles depuis + * une instance, même si les méthodes statiques le sont. + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Les constantes d'une classe peuvent toujours être utilisé de façon statique +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Retourne 'static'; +MyClass::myStaticMethod(); // Retourne 'I am static'; + +// On peut instancier une classe en utilisant le mot clé 'new' +$my_class = new MyClass('An instance property'); + +// On peut accéder aux attributs/méthodes d'une instance avec -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// On peut hériter d'une classe en utilisant 'extends' +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Surcharge d'une méthode + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Retourne "protected" +$my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// On peut utiliser des "méthodes magiques" pour se faire des accesseurs +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Va utiliser la méthode __get() +$x->property = 'Something'; // Va utiliser la méthode __set() + +// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou +// elle peuvent implémenter une interface (en utilisant le mot clé 'implement'). + +// Une interface peut être déclarée avec le mot clé 'interface' + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// Les interfaces peuvent hériter d'autres interfaces +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Les classes peuvent implémenter plusieurs interfaces à la fois +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + +/******************************** + * Espaces de noms (namespaces) + */ + +// Cette section est séparée, car une déclaration d'espace de nom doit être +// la première chose que l'on retrouve dans un fichier PHP, +// imaginons que c'est le cas + + Date: Tue, 6 Oct 2015 09:25:12 +0200 Subject: Update python-fr.html.markdown Fix 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 5a03ecfc..3f6dcabb 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -19,7 +19,7 @@ Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le mom ```python # Une ligne simple de commentaire commence par un dièse -""" Les lignes de commenatires multipes peuvent être écrites +""" Les lignes de commentaires multipes peuvent être écrites en utilisant 3 guillemets ("), et sont souvent utilisées pour les commentaires """ -- cgit v1.2.3 From 58c24258b23fe51cf30aa49329a89f84718f18d2 Mon Sep 17 00:00:00 2001 From: Carlos Date: Tue, 6 Oct 2015 16:08:41 +0200 Subject: Ruby 1.9.x is also retired Ruby 1.9.3 reached end of life in Feb 2015 as is stated in https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/ Is good to anyone to know that 2.x.x are the only rubies which get official security patches --- 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 d8a02d36..1fbcc752 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -42,7 +42,7 @@ The three major version of Ruby in use are: * 2.0.0 - Released in February 2013. Most major libraries and frameworks support 2.0.0. * 1.9.3 - Released in October 2011. This is the version most rubyists use - currently. + currently. Also [retired](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) * 1.8.7 - Ruby 1.8.7 has been [retired](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). -- cgit v1.2.3 From 9b0877f7ebb7a73deed0c6aea40102f4abec586d Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 6 Oct 2015 09:36:03 -0500 Subject: Update java en file to fix small typo `buy` to `by` --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index b4757962..478ec683 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -338,7 +338,7 @@ public class LearnJava { } // But there's a nifty way to achive the same thing in an - // easier way, buy using something that is called Double Brace + // easier way, by using something that is called Double Brace // Initialization. private static final Set COUNTRIES = HashSet() {{ -- cgit v1.2.3 From d810a71b76892aef7404293d6fe4bec3b9dbb31e Mon Sep 17 00:00:00 2001 From: Ribeiro Date: Tue, 6 Oct 2015 15:09:29 -0300 Subject: Added The Elvis Operator to Groovy docs --- groovy.html.markdown | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 519f36ce..c80fcc89 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -200,6 +200,14 @@ def y = 10 def x = (y > 1) ? "worked" : "failed" assert x == "worked" +//Groovy supports 'The Elvis Operator' too! +//Instead of using the ternary operator: + +displayName = user.name ? user.name : 'Anonymous' + +//We can write like this: +displayName = user.name ?: 'Anonymous' + //For loop //Iterate over a range def x = 0 @@ -422,6 +430,3 @@ Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) [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 08ba654955824ae6daecd169608a6ff645b18d39 Mon Sep 17 00:00:00 2001 From: Pascal Boutin Date: Tue, 6 Oct 2015 15:11:34 -0400 Subject: Quick review for the fr-fr php page --- fr-fr/php.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown index b7b41ebe..6574a36f 100644 --- a/fr-fr/php.html.markdown +++ b/fr-fr/php.html.markdown @@ -2,7 +2,6 @@ language: PHP contributors: - ["Pascal Boutin", "http://pboutin.net/"] -filename: learnphp.php lang: fr-fr --- @@ -16,11 +15,11 @@ This document describes PHP 5+. // Deux barres obliques amorcent un commentaire simple. -# Le dièse également, bien que les barres obliques soient plus courantes +# Le dièse aussi, bien que les barres obliques soient plus courantes /* Les barres obliques et les astérisques peuvent être utilisés - pour faire un commentaire multi-ligne. + pour faire un commentaire multi-lignes. */ // Utilisez "echo" ou "print" afficher une sortie @@ -28,6 +27,7 @@ print('Hello '); // Affiche "Hello " sans retour à la ligne // Les parenthèses sont facultatives pour print et echo echo "World\n"; // Affiche "World" avec un retour à la ligne + // tout les instructions doivent se terminer par un point-virgule // Tout ce qui se trouve en dehors des est automatiquement @@ -248,7 +248,7 @@ $boolean = (boolean) $zero; // => false $integer = 5; $string = strval($integer); -$var = null; // Valeur Null +$var = null; // Valeur nulle /******************************** @@ -353,7 +353,7 @@ echo "\n"; // Il est également possible d'accéder aux clés du tableau foreach ($wheels as $vehicle => $wheel_count) { - echo "Le $vehicle a $wheel_count roues"; + echo "The $vehicle have $wheel_count wheels"; } echo "\n"; -- cgit v1.2.3 From 35ba352668f67de95e0dca7c2f1a284f5fa453b2 Mon Sep 17 00:00:00 2001 From: Geovanny Ribeiro Date: Tue, 6 Oct 2015 16:49:21 -0300 Subject: Update groovy.html.markdown --- groovy.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index c80fcc89..492c1ba2 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -99,7 +99,7 @@ technologies.sort() // To sort without mutating original, you can do: sortedTechnologies = technologies.sort( false ) -/*** Manipulating Lists ***/ +/*** Manipulating Lists ***/e //Replace all elements in the list Collections.replaceAll(technologies, 'Gradle', 'gradle') @@ -205,7 +205,7 @@ assert x == "worked" displayName = user.name ? user.name : 'Anonymous' -//We can write like this: +//We can write it: displayName = user.name ?: 'Anonymous' //For loop -- cgit v1.2.3 From 7ffea42953466151202155d3979f17b6b9b76bb1 Mon Sep 17 00:00:00 2001 From: pboutin Date: Tue, 6 Oct 2015 17:18:10 -0400 Subject: fixed grammar errors following the comments of vendethiel --- fr-fr/php.html.markdown | 57 ++++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown index 6574a36f..1c8db89a 100644 --- a/fr-fr/php.html.markdown +++ b/fr-fr/php.html.markdown @@ -1,6 +1,6 @@ --- language: PHP -contributors: +translators: - ["Pascal Boutin", "http://pboutin.net/"] lang: fr-fr --- @@ -8,10 +8,10 @@ lang: fr-fr This document describes PHP 5+. ```php - // Le code PHP doit être placé à l'intérieur de tags '' +// généralement recommandé de ne pas fermer la balise '?>' // Deux barres obliques amorcent un commentaire simple. @@ -28,7 +28,7 @@ print('Hello '); // Affiche "Hello " sans retour à la ligne // Les parenthèses sont facultatives pour print et echo echo "World\n"; // Affiche "World" avec un retour à la ligne -// tout les instructions doivent se terminer par un point-virgule +// toutes les instructions doivent se terminer par un point-virgule // Tout ce qui se trouve en dehors des est automatiquement // affiché en sortie @@ -42,7 +42,7 @@ Hello World Again! // Les noms de variables débutent par le symbole $ // Un nom de variable valide commence par une lettre ou un souligné, -// suivi de n'importe quelle lettre, nombre ou soulignés. +// suivi de n'importe quelle lettre, nombre ou de soulignés. // Les valeurs booléenes ne sont pas sensibles à la casse $boolean = true; // ou TRUE ou True @@ -71,8 +71,8 @@ $quotient = 2 / 1; // 2 (division) // Arithmétique (raccourcis) $number = 0; $number += 2; // Incrémente $number de 2 -echo $number++; // Affiche 1 (incrémente après l'évaluation) -echo ++$number; // Affiche 3 (incrémente après l'évaluation) +echo $number++; // Affiche 2 (incrémente après l'évaluation) +echo ++$number; // Affiche 4 (incrémente avant l'évaluation) $number /= $float; // Divise et assigne le quotient à $number // Les chaînes de caractères (strings) doivent être à @@ -82,21 +82,21 @@ $sgl_quotes = '$String'; // => '$String' // Évitez les guillemets sauf pour inclure le contenu d'une autre variable $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' -// Les caractères spéciaux sont seulement échappé avec des guillemets +// Les caractères spéciaux sont seulement échappés avec des guillemets $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; -// En cas de besoins, placez la variable dans des accolades +// En cas de besoin, placez la variable dans des accolades $money = "I have $${number} in the bank."; -// Depuis PHP 5.3, nowdocs peut être utilisé pour faire des chaînes +// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes // multi-lignes non-interprétées $nowdoc = <<<'END' Multi line string END; -// Heredocs peut être utilisé pour faire des chaînes multi-lignes interprétées +// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées $heredoc = << 1, 'Two' => 2, 'Three' => 3); // PHP 5.4 a introduit une nouvelle syntaxe @@ -142,7 +142,7 @@ echo $array[0]; // => "One" // Ajoute un élément à la fin du tableau $array[] = 'Four'; -// Retrait d'un élément d'un tableau +// Retrait d'un élément du tableau unset($array[3]); /******************************** @@ -187,7 +187,7 @@ echo $z; // => 0 // Affiche le type et la valeur de la variable dans stdout var_dump($z); // prints int(0) -// Affiche la variable dans stdout dans un format plus accessible +// Affiche la variable dans stdout dans un format plus convivial print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) /******************************** @@ -200,7 +200,7 @@ $d = '1'; // assert affiche un avertissement dans son argument n'est pas vrai -// Ces comparaisons vont toujours être vrais, même si leurs +// Ces comparaisons vont toujours être vraies, même si leurs // types ne sont pas les mêmes. assert($a == $b); // égalité assert($c != $a); // inégalité @@ -210,7 +210,7 @@ assert($c > $b); assert($a <= $b); assert($c >= $d); -// Ces comparaisons vont seulement être vrais si les types concordent. +// Ces comparaisons vont seulement être vraies si les types concordent. assert($c === $d); assert($a !== $d); assert(1 === '1'); @@ -224,7 +224,7 @@ echo $a <=> $a; // 0 car ils sont égaux echo $a <=> $b; // -1 car $a < $b echo $b <=> $a; // 1 car $b > $a -// Les variables peuvent être transtypées dépendant de leur usage. +// Les variables peuvent être transtypées dépendamment de leur usage. $integer = 1; echo $integer + $integer; // => 2 @@ -302,7 +302,7 @@ if ($x === '0') {

Ceci est affiché si $x est vrai

-

Sinon ce sera ceci

+

Ceci est affiché si $x est faux

"Hello" -// Un nom de fonction valide doit débuter par une lettre ou un souligné, -// suivi de n'importe, quelles lettres, nombres ou soulignés. + +// Les noms de fonction débutent par le symbole $ +// Un nom de variable valide commence par une lettre ou un souligné, +// suivi de n'importe quelle lettre, nombre ou de soulignés. function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 $result = $x + $y; @@ -435,7 +437,7 @@ call_user_func(callable $callback [, $parameter [, ... ]]); printProtectedProperty(); // => Retourne "protected" $my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass" +// On peut empêcher qu'une classe soit héritée final class YouCannotExtendMe { } @@ -678,13 +681,13 @@ $cls = new SomeOtherNamespace\MyClass(); ## Pour plus d'informations -Visitez la [documentation officielle](http://www.php.net/manual/fr).. +Visitez la [documentation officielle](http://www.php.net/manual/fr). -Si vous êtes intéressé aux bonnes pratiques, visitez +Si vous êtes intéressé par les bonnes pratiques, visitez [PHP The Right Way](http://www.phptherightway.com/) (anglais seulement). -Si vous êtes habitué d'utiliser de bons gestionaires de dépendances, regardez +Si vous êtes habitué à utiliser de bons gestionaires de dépendances, regardez [Composer](http://getcomposer.org/). -Pour les standards, visitez "the PHP Framework Interoperability Group's" +Pour consulter les standards, visitez "the PHP Framework Interoperability Groups" [PSR standards](https://github.com/php-fig/fig-standards). -- cgit v1.2.3 From 9d64b532f8ccdfd95c2417dcf65257385956353a Mon Sep 17 00:00:00 2001 From: George Gognadze Date: Wed, 7 Oct 2015 01:27:12 +0400 Subject: Update c++.html.markdown spelling error --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 8ee964ca..6f4d0562 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -264,7 +264,7 @@ 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 +// - a new string is constructed with the returned object as argument to the // constructor // - the returned object is destroyed // The returned object is called a temporary object. Temporary objects are -- cgit v1.2.3 From d540d1c67bb123f8e7dc3233be957e29d8983e4b Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Tue, 6 Oct 2015 22:25:38 -0400 Subject: Original link directs to page that can't be found. Changed to represent new location of the Apple Developer tutorial on swift. --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 509c9d2f..86a0b89a 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -12,7 +12,7 @@ Swift is a programming language for iOS and OS X development created by Apple. D The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. -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. +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), which has a complete tutorial on Swift. ```swift // import a module -- cgit v1.2.3 From f53f50aad135025cae04ff9b28f6bf11c8e45bfd Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Tue, 6 Oct 2015 23:06:21 -0400 Subject: Added additional reading for both iOS and OS X for Objective-C from Apple Developer site. Added contribution line. --- objective-c.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 91b84b47..407ba3c8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] - ["Levi Bostian", "https://github.com/levibostian"] + - ["Clayton Walker", "https://github.com/cwalk"] filename: LearnObjectiveC.m --- @@ -747,4 +748,8 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not se [Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) +[Programming with Objective-C for iOS](https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html) + +[Programming with Objective-C for Mac OSX](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) + [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From d6f45adb94a3e7a16896c5301199baf8a96f6754 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 7 Oct 2015 08:35:54 +0200 Subject: fix contributors, #13699 --- fr-fr/php.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown index 1c8db89a..f4eaf396 100644 --- a/fr-fr/php.html.markdown +++ b/fr-fr/php.html.markdown @@ -1,5 +1,8 @@ --- language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["Pascal Boutin", "http://pboutin.net/"] lang: fr-fr -- cgit v1.2.3