diff options
64 files changed, 6033 insertions, 512 deletions
diff --git a/c++.html.markdown b/c++.html.markdown index 8d1c7a26..4113d5f4 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -71,10 +71,16 @@ void func(); // function which may accept any number of arguments // Use nullptr instead of NULL in C++ int* ip = nullptr; -// C standard headers are available in C++, -// but are prefixed with "c" and have no .h suffix. +// C standard headers are available in C++. +// C headers end in .h, while +// C++ headers are prefixed with "c" and have no ".h" suffix. + +// The C++ standard version: #include <cstdio> +//The C standard version: +#include <stdio.h> + int main() { printf("Hello, world!\n"); @@ -1051,6 +1057,8 @@ cout << ST.size(); // will print the size of set ST // Output: 0 // NOTE: for duplicate elements we can use multiset +// NOTE: For hash sets, use unordered_set. They are more efficient but +// do not preserve order. unordered_set is available since C++11 // Map // Maps store elements formed by a combination of a key value @@ -1078,6 +1086,8 @@ cout << it->second; // Output: 26 +// NOTE: For hash maps, use unordered_map. They are more efficient but do +// not preserve order. unordered_map is available since C++11. /////////////////////////////////// // Logical and Bitwise operators @@ -1127,7 +1137,6 @@ compl 4 // Performs a bitwise not ``` Further Reading: -An up-to-date language reference can be found at -<http://cppreference.com/w/cpp> - -Additional resources may be found at <http://cplusplus.com> +* An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp). +* Additional resources may be found at [CPlusPlus](http://cplusplus.com). +* A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/c.html.markdown b/c.html.markdown index bf93dcf5..7975a1c2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -605,6 +605,14 @@ static int j = 0; //other files using testFunc2() cannot access variable j void testFunc2() { extern int j; } +// The static keyword makes a variable inaccessible to code outside the +// compilation unit. (On almost all systems, a "compilation unit" is a .c +// file.) static can apply both to global (to the compilation unit) variables, +// functions, and function-local variables. When using static with +// function-local variables, the variable is effectively global and retains its +// value across function calls, but is only accessible within the function it +// is declared in. Additionally, static variables are initialized to 0 if not +// declared with some other starting value. //**You may also declare functions as static to make them private** /////////////////////////////////////// diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 28b5173b..b12e50ca 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -181,8 +181,8 @@ nil ; false; also, the empty list: () ;;; You can also use unicode characters. (defparameter *AΛB* nil) -;;; Accessing a previously unbound variable is an undefined behavior, but -;;; possible. Don't do it. +;;; Accessing a previously unbound variable results in an UNBOUND-VARIABLE +;;; error, however it is defined behavior. Don't do it. ;;; You can create local bindings with LET. In the following snippet, `me` is ;;; bound to "dance with you" only within the (let ...). LET always returns @@ -284,7 +284,8 @@ nil ; false; also, the empty list: () ;;; To access the element at 1, 1, 1: (aref (make-array (list 2 2 2)) 1 1 1) ; => 0 - +;;; This value is implementation-defined: +;;; NIL on ECL, 0 on SBCL and CCL. ;;; Adjustable vectors diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index cbf7687e..c05a9138 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -9,33 +9,28 @@ lang: cs-cz filename: javascript-cz.js --- -JavaScript byl vytvořen Brendan Eichem v roce 1995 pro Netscape. Byl původně -zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk Javy, -která byla zamýšlena pro více komplexní webové aplikace, ale jeho úzké propojení -s webovými stránkami a vestavěná podpora v prohlížečích způsobila, že se stala -více běžná ve webovém frontendu než Java. +JavaScript byl vytvořen Brendanem Eichem v roce 1995 pro Netscape. Původně byl +zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk +Javy, která byla zamýšlena pro komplexnější webové aplikace. Úzké propojení +JavaScriptu s webovými stránkami a vestavěná podpora v prohlížečích způsobila, +že se stal ve webovém frontendu běžnějším než Java. - -JavaScript není omezen pouze na webové prohlížeče, např. projekt Node.js, -který zprostředkovává samostatně běžící prostředí V8 JavaScriptového enginu z -Google Chrome se stává více a více oblíbený pro serverovou část webových aplikací. - -Zpětná vazba je velmi ceněná. Autora článku můžete kontaktovat (anglicky) na -[@adambrenecki](https://twitter.com/adambrenecki), nebo -[adam@brenecki.id.au](mailto:adam@brenecki.id.au), nebo mě, jakožto překladatele, -na [martinek@ludis.me](mailto:martinek@ludis.me). +JavaScript není omezen pouze na webové prohlížeče. Např. projekt Node.js, +který zprostředkovává samostatně běžící prostředí V8 JavaScriptového jádra z +Google Chrome se stává stále oblíbenější i pro serverovou část webových +aplikací. ```js -// Komentáře jsou jako v zayku C. Jednořádkové komentáře začínájí dvojitým lomítkem, +// Jednořádkové komentáře začínají dvojitým lomítkem, /* a víceřádkové komentáře začínají lomítkem s hvězdičkou a končí hvězdičkou s lomítkem */ -// Vyrazu můžou být spuštěny pomocí ; +// Příkazy mohou být ukončeny středníkem ; delejNeco(); -// ... ale nemusí, středníky jsou automaticky vloženy kdekoliv, -// kde končí řádka, kromě pár speciálních případů -delejNeco() +// ... ale nemusí, protože středníky jsou automaticky vloženy kdekoliv, +// kde končí řádka, kromě pár speciálních případů. +delejNeco(); // Protože tyto případy můžou způsobit neočekávané výsledky, budeme // středníky v našem návodu používat. @@ -44,12 +39,12 @@ delejNeco() // 1. Čísla, řetězce a operátory // JavaScript má jeden číselný typ (čímž je 64-bitový IEEE 754 double). -// Double má 52-bit přesnost, což je dostatečně přesné pro ukládání celých čísel -// do 9✕10¹⁵. +// Double má 52-bitovou přesnost, což je dostatečně přesné pro ukládání celých +// čísel až do 9✕10¹⁵. 3; // = 3 1.5; // = 1.5 -// Základní matematické operace fungují, jak byste očekávali +// Základní matematické operace fungují tak, jak byste očekávali 1 + 1; // = 2 0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 @@ -65,30 +60,30 @@ delejNeco() 18.5 % 7; // = 4.5 // Bitové operace také fungují; když provádíte bitové operace, desetinné číslo -// (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů +// (float) se převede na celé číslo (int) se znaménkem *až do* 32 bitů 1 << 2; // = 4 // Přednost se vynucuje závorkami. (1 + 3) * 2; // = 8 -// Existují 3 hodnoty mimo obor reálných čísel +// Existují 3 hodnoty mimo obor reálných čísel: Infinity; // + nekonečno; výsledek např. 1/0 -Infinity; // - nekonečno; výsledek např. -1/0 NaN; // výsledek např. 0/0, znamená, že výsledek není číslo ('Not a Number') -// Také existují hodnoty typu bool +// Také existují hodnoty typu boolean. true; // pravda false; // nepravda -// Řetězce znaků jsou obaleny ' nebo ". +// Řetězce znaků jsou obaleny ' nebo ". 'abc'; -"Ahoj světe!"; +"Hello, world"; -// Negace se tvoří pomocí ! +// Negace se tvoří pomocí znaku ! !true; // = false !false; // = true -// Rovnost se porovnává === +// Rovnost se porovnává pomocí === 1 === 1; // = true 2 === 1; // = false @@ -103,16 +98,16 @@ false; // nepravda 2 >= 2; // = true // Řetězce znaků se spojují pomocí + -"Ahoj " + "světe!"; // = "Ahoj světe!" +"Hello " + "world!"; // = "Hello world!" -// ... což funguje nejenom s řetězci +// ... což funguje nejen s řetězci "1, 2, " + 3; // = "1, 2, 3" -"Ahoj " + ["světe", "!"] // = "Ahoj světe,!" +"Hello " + ["world", "!"]; // = "Hello world,!" // a porovnávají se pomocí < nebo > "a" < "b"; // = true -// Rovnost s převodem typů se dělá pomocí == ... +// Rovnost s převodem typů se dělá za pomoci dvojitého rovnítka... "5" == 5; // = true null == undefined; // = true @@ -124,24 +119,24 @@ null === undefined; // = false 13 + !0; // 14 "13" + !0; // '13true' -// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí charAt` +// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí `charAt` "Toto je řetězec".charAt(0); // = 'T' -// ...nebo použít `substring` k získání podřetězce -"Ahoj světe".substring(0, 4); // = "Ahoj" +// ...nebo použít `substring` k získání podřetězce. +"Hello world".substring(0, 5); // = "Hello" -// `length` znamená délka a je to vlastnost, takže nepoužívejte () -"Ahoj".length; // = 4 +// `length` znamená délka a je to vlastnost, takže nepoužívejte (). +"Hello".length; // = 5 // Existují také typy `null` a `undefined`. -null; // značí, že žádnou hodnotu -undefined; // značí, že hodnota nebyla definovaná (ikdyž +null; // obvykle označuje něco záměrně bez hodnoty +undefined; // obvykle označuje, že hodnota není momentálně definovaná (ačkoli // `undefined` je hodnota sama o sobě) -// false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní -// vrací pravdu (true).. -// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, ikdyž 0 == "0" -// vrací pravdu +// false, null, undefined, NaN, 0 a "" vrací nepravdu (false). Všechno ostatní +// vrací pravdu (true). +// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, i když 0 == "0" +// vrací pravdu. /////////////////////////////////// // 2. Proměnné, pole a objekty @@ -151,11 +146,11 @@ undefined; // značí, že hodnota nebyla definovaná (ikdyž // znak `=`. var promenna = 5; -// když vynecháte slůvko 'var' nedostanete chybovou hlášku... +// Když vynecháte slůvko 'var', nedostanete chybovou hlášku... jinaPromenna = 10; -// ...ale vaše proměnná bude vytvořena globálně, bude vytvořena v globálním -// oblasti působnosti, ne jenom v lokálním tam, kde jste ji vytvořili +// ...ale vaše proměnná bude vytvořena globálně. Bude vytvořena v globální +// oblasti působnosti, tedy nejenom v lokální tam, kde jste ji vytvořili. // Proměnné vytvořené bez přiřazení obsahují hodnotu undefined. var dalsiPromenna; // = undefined @@ -163,114 +158,136 @@ var dalsiPromenna; // = undefined // Pokud chcete vytvořit několik proměnných najednou, můžete je oddělit čárkou var someFourthVar = 2, someFifthVar = 4; -// Existuje kratší forma pro matematické operace na proměnné +// Existuje kratší forma pro matematické operace nad proměnnými promenna += 5; // se provede stejně jako promenna = promenna + 5; -// promenna je ted 10 +// promenna je teď 10 promenna *= 10; // teď je promenna rovna 100 // a tohle je způsob, jak přičítat a odečítat 1 promenna++; // teď je promenna 101 promenna--; // zpět na 100 -// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu -var mojePole = ["Ahoj", 45, true]; +// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu. +var myArray = ["Ahoj", 45, true]; // Jednotlivé hodnoty jsou přístupné přes hranaté závorky. // Členové pole se začínají počítat na nule. myArray[1]; // = 45 -// Pole je proměnlivé délky a členové se můžou měnit -myArray.push("Světe"); +// Pole je proměnlivé délky a členové se můžou měnit. +myArray.push("World"); myArray.length; // = 4 // Přidání/změna na specifickém indexu myArray[3] = "Hello"; -// JavaScriptové objekty jsou stejné jako asociativní pole v jinných programovacích +// Přidání nebo odebrání člena ze začátku nebo konce pole +myArray.unshift(3); // Přidej jako první člen +someVar = myArray.shift(); // Odstraň prvního člena a vrať jeho hodnotu +myArray.push(3); // Přidej jako poslední člen +someVar = myArray.pop(); // Odstraň posledního člena a vrať jeho hodnotu + +// Spoj všechny členy pole středníkem +var myArray0 = [32,false,"js",12,56,90]; +myArray0.join(";") // = "32;false;js;12;56;90" + +// Vrať část pole s elementy od pozice 1 (včetně) do pozice 4 (nepočítaje) +myArray0.slice(1,4); // = [false,"js",12] + +// Odstraň čtyři členy od pozice 2, vlož následující +// "hi","wr" and "ld"; vrať odstraněné členy +myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90] +// myArray0 === [32,false,"hi","wr","ld"] + +// JavaScriptové objekty jsou stejné jako asociativní pole v jiných programovacích // jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota. -var mujObjekt = {klic1: "Ahoj", klic2: "světe"}; +var mujObjekt = {klic1: "Hello", klic2: "World"}; -// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní -// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu- +// Klíče jsou řetězce, ale nemusí mít povinné uvozovky, pokud jsou validními +// JavaScriptovými identifikátory. Hodnoty můžou být jakéhokoliv typu. var mujObjekt = {klic: "mojeHodnota", "muj jiny klic": 4}; // K hodnotám můžeme přistupovat opět pomocí hranatých závorek -myObj["muj jiny klic"]; // = 4 +mujObjekt["muj jiny klic"]; // = 4 // ... nebo pokud je klíč platným identifikátorem, můžeme přistupovat k // hodnotám i přes tečku mujObjekt.klic; // = "mojeHodnota" // Objekty jsou měnitelné, můžeme upravit hodnoty, nebo přidat nové klíče. -myObj.mujDalsiKlic = true; +mujObjekt.mujDalsiKlic = true; -// Pokud se snažíte přistoupit ke klíči, který není nastaven, dostanete undefined -myObj.dalsiKlic; // = undefined +// Pokud se snažíte přistoupit ke klíči, který neexistuje, dostanete undefined. +mujObjekt.dalsiKlic; // = undefined /////////////////////////////////// // 3. Řízení toku programu -// Syntaxe pro tuto sekci je prakticky stejná jako pro Javu - -// `if` (když) funguje, jak byste čekali. +// Funkce `if` funguje, jak byste čekali. var pocet = 1; if (pocet == 3){ // provede, když se pocet rovná 3 } else if (pocet == 4){ // provede, když se pocet rovná 4 } else { - // provede, když je pocet cokoliv jinného + // provede, když je pocet cokoliv jiného } -// Stejně tak cyklus while +// Stejně tak cyklus `while`. while (true){ - // nekonečný cyklus + // nekonečný cyklus! } -// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou +// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou. var vstup; do { vstup = nactiVstup(); } while (!jeValidni(vstup)) -// Cyklus for je stejný jako v Javě nebo jazyku C +// Cyklus `for` je stejný jako v Javě nebo jazyku C: // inicializace; podmínka pro pokračování; iterace. -for (var i = 0; i < 3; i++){ - // provede třikrát +for (var i = 0; i < 5; i++){ + // provede se pětkrát } -// Cyklus For-in iteruje přes každo vlastnost prototypu -var popis = ""; -var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; -for (var x in osoba){ - popis += osoba[x] + " "; +// Opuštění cyklu s návěštím je podobné jako v Javě +outer: +for (var i = 0; i < 10; i++) { + for (var j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // opustí vnější (outer) cyklus místo pouze vnitřního (inner) cyklu + } + } } -//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou -//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty() +// Cyklus For-in iteruje přes každou vlastnost prototypu var popis = ""; -var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18}; +var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; for (var x in osoba){ - if (osoba.hasOwnProperty(x)){ - popis += osoba[x] + " "; - } -} + popis += osoba[x] + " "; +} // popis = 'Paul Ken 18 ' -// for-in by neměl být použit pro pole, pokud záleží na pořadí indexů. -// Neexistuje jistota, že for-in je vrátí ve správném pořadí. +// Příkaz for/of umožňuje iterovat iterovatelné objekty (včetně vestavěných typů +// String, Array, například polím podobným argumentům nebo NodeList objektům, +// TypeArray, Map a Set, či uživatelsky definované iterovatelné objekty). +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets = 'cat dog hamster hedgehog ' // && je logické a, || je logické nebo if (dum.velikost == "velký" && dum.barva == "modrá"){ dum.obsahuje = "medvěd"; } if (barva == "červená" || barva == "modrá"){ - // barva je červená nebo modtrá + // barva je červená nebo modrá } // && a || jsou praktické i pro nastavení základních hodnot var jmeno = nejakeJmeno || "default"; - // `switch` zkoumá přesnou rovnost (===) // Používejte 'break;' po každé možnosti, jinak se provede i možnost za ní. znamka = 'B'; @@ -289,8 +306,9 @@ switch (znamka) { break; } + //////////////////////////////////////////////////////// -// 4. Funckce, Oblast platnosti (scope) a Vnitřní funkce +// 4. Funkce, Oblast platnosti (scope) a Vnitřní funkce // JavaScriptové funkce jsou definovány slůvkem `function`. function funkce(text){ @@ -302,12 +320,9 @@ funkce("něco"); // = "NĚCO" // jako slůvko return, jinak se vrátí 'undefined', kvůli automatickému vkládání // středníků. Platí to zejména pro Allmanův styl zápisu. -function funkce() -{ +function funkce(){ return // <- zde je automaticky vložen středník - { - tohleJe: "vlastnost objektu" - } + { tohleJe: "vlastnost objektu"}; } funkce(); // = undefined @@ -327,9 +342,9 @@ function myFunction(){ setInterval(myFunction, 5000); // Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako -// ananymní funkci přímo vloženou jako argument +// anonymní funkci přímo vloženou jako argument setTimeout(function(){ - // tento kód bude zavolán za 5 vteřin + // tento kód bude zavolán za 5 vteřin }, 5000); // JavaScript má oblast platnosti funkce, funkce ho mají, ale jiné bloky ne @@ -339,21 +354,21 @@ if (true){ i; // = 5 - ne undefined, jak byste očekávali v jazyku, kde mají bloky svůj // rámec působnosti -// Toto je běžný model,který chrání před únikem dočasných proměnných do +// Toto je běžný model, který chrání před únikem dočasných proměnných do //globální oblasti (function(){ var docasna = 5; - // Můžeme přistupovat k globálního oblasti přes přiřazování globalním + // Můžeme přistupovat ke globálního oblasti přes přiřazování globálním // objektům. Ve webovém prohlížeči je to vždy 'window`. Globální objekt - // může mít v jiných prostředích jako Node.js jinné jméno. + // může mít v jiných prostředích jako Node.js jiné jméno. window.trvala = 10; })(); docasna; // způsobí ReferenceError trvala; // = 10 -// Jedna z nejvice mocných vlastnosti JavaScriptu je vnitřní funkce. Je to funkce -// definovaná v jinné funkci, vnitřní funkce má přístup ke všem proměnným ve -// vnější funkci, dokonce i poté, co funkce skončí +// Jedna z nejmocnějších vlastností JavaScriptu je vnitřní funkce. Je to funkce +// definovaná v jiné funkci. Vnitřní funkce má přístup ke všem proměnným ve +// vnější funkci, dokonce i poté, co vnější funkce skončí. function ahojPoPetiVterinach(jmeno){ var prompt = "Ahoj, " + jmeno + "!"; // Vnitřní funkce je dána do lokální oblasti platnosti, jako kdyby byla @@ -362,33 +377,33 @@ function ahojPoPetiVterinach(jmeno){ alert(prompt); } setTimeout(vnitrni, 5000); - // setTimeout je asynchronní, takže funkce ahojPoPetiVterinach se ukončí - // okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak protože - // vnitrni je definována přes ahojPoPetiVterinach, má pořád přístup k + // setTimeout je asynchronní, takže se funkce ahojPoPetiVterinach ukončí + // okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak + // vnitrni je definována přes ahojPoPetiVterinach a má pořád přístup k // proměnné prompt, když je konečně zavolána. } ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s /////////////////////////////////////////////////// -// 5. Více o objektech, konstuktorech a prototypech +// 5. Více o objektech, konstruktorech a prototypech -// Objekty můžou obsahovat funkce +// Objekty můžou obsahovat funkce. var mujObjekt = { mojeFunkce: function(){ - return "Ahoj světe!"; + return "Hello world!"; } }; -mujObjekt.mojeFunkce(); // = "Ahoj světe!" +mujObjekt.mojeFunkce(); // = "Hello world!" // Když jsou funkce z objektu zavolány, můžou přistupovat k objektu přes slůvko // 'this'' var mujObjekt = { - text: "Ahoj světe!", + text: "Hello world!", mojeFunkce: function(){ return this.text; } }; -mujObjekt.mojeFunkce(); // = "Ahoj světe!" +mujObjekt.mojeFunkce(); // = "Hello world!" // Slůvko this je nastaveno k tomu, kde je voláno, ne k tomu, kde je definováno // Takže naše funkce nebude fungovat, když nebude v kontextu objektu. @@ -396,23 +411,23 @@ var mojeFunkce = mujObjekt.mojeFunkce; mojeFunkce(); // = undefined // Opačně, funkce může být přiřazena objektu a může přistupovat k objektu přes -// this, i když nebyla přímo v definici- +// this, i když nebyla přímo v definici. var mojeDalsiFunkce = function(){ return this.text.toUpperCase(); } mujObjekt.mojeDalsiFunkce = mojeDalsiFunkce; -mujObjekt.mojeDalsiFunkce(); // = "AHOJ SVĚTE!" +mujObjekt.mojeDalsiFunkce(); // = "HELLO WORLD!" // Můžeme také specifikovat, v jakém kontextu má být funkce volána pomocí // `call` nebo `apply`. var dalsiFunkce = function(s){ return this.text + s; -} -dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Ahoj světe! A ahoj měsíci!" +}; +dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Hello world! A ahoj měsíci!" -// Funkce `apply`je velmi podobná, akorát bere jako druhý argument pole argumentů -dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Ahoj světe! A ahoj slunce!" +// Funkce `apply`je velmi podobná, pouze bere jako druhý argument pole argumentů +dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Hello world! A ahoj slunce!" // To je praktické, když pracujete s funkcí, která bere sekvenci argumentů a // chcete předat pole. @@ -425,38 +440,42 @@ Math.min.apply(Math, [42, 6, 27]); // = 6 // použijte `bind`. var pripojenaFunkce = dalsiFunkce.bind(mujObjekt); -pripojenaFunkce(" A ahoj Saturne!"); // = "Ahoj světe! A ahoj Saturne!" +pripojenaFunkce(" A ahoj Saturne!"); // = "Hello world! A ahoj Saturne!" -// `bind` může být použito čatečně částečně i k používání +// `bind` může být použito částečně k provázání funkcí -var nasobeni = function(a, b){ return a * b; } +var nasobeni = function(a, b){ return a * b; }; var zdvojeni = nasobeni.bind(this, 2); zdvojeni(8); // = 16 // Když zavoláte funkci se slůvkem 'new', vytvoří se nový objekt a // a udělá se dostupný funkcím skrz slůvko 'this'. Funkcím volaným takto se říká -// konstruktory +// konstruktory. var MujKonstruktor = function(){ this.mojeCislo = 5; -} +}; mujObjekt = new MujKonstruktor(); // = {mojeCislo: 5} mujObjekt.mojeCislo; // = 5 -// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlasnosti -// objektu, který neexistuje na objektu, tak se JS koukne do prototypu. +// Na rozdíl od nejznámějších objektově orientovaných jazyků, JavaScript nezná +// koncept instancí vytvořených z tříd. Místo toho Javascript kombinuje +// vytváření instancí a dědění do konceptu zvaného 'prototyp'. + +// Každý JavaScriptový objekt má prototyp. Když budete přistupovat k vlastnosti +// objektu, který neexistuje na objektu, tak se JS podívá do prototypu. // Některé JS implementace vám umožní přistupovat k prototypu přes magickou // vlastnost '__proto__'. I když je toto užitečné k vysvětlování prototypů, není -// to součást standardu, ke standartní způsobu k používání prototypu se dostaneme -// později. +// to součást standardu. Ke standardnímu způsobu používání prototypu se +// dostaneme později. var mujObjekt = { - mujText: "Ahoj svete!" + mujText: "Hello world!" }; var mujPrototyp = { smyslZivota: 42, mojeFunkce: function(){ - return this.mujText.toLowerCase() + return this.mujText.toLowerCase(); } }; @@ -464,7 +483,7 @@ mujObjekt.__proto__ = mujPrototyp; mujObjekt.smyslZivota; // = 42 // Toto funguje i pro funkce -mujObjekt.mojeFunkce(); // = "Ahoj světe!" +mujObjekt.mojeFunkce(); // = "Hello world!" // Samozřejmě, pokud není vlastnost na vašem prototypu, tak se hledá na // prototypu od prototypu atd. @@ -474,21 +493,41 @@ mujPrototyp.__proto__ = { mujObjekt.mujBoolean; // = true -// Zde neni žádné kopírování; každý objekt ukládá referenci na svůj prototyp -// Toto znamená, že můžeme měnit prototyp a změny se projeví všude +// Zde není žádné kopírování; každý objekt ukládá referenci na svůj prototyp +// Toto znamená, že můžeme měnit prototyp a změny se projeví všude. mujPrototyp.smyslZivota = 43; -mujObjekt.smyslZivota // = 43 +mujObjekt.smyslZivota; // = 43 + +// Příkaz for/in umožňuje iterovat vlastnosti objektu až do úrovně null +// prototypu. +for (var x in myObj){ + console.log(myObj[x]); +} +///Vypíše: +// Hello world! +// 43 +// [Function: myFunc] + +// Pro výpis pouze vlastností patřících danému objektu a nikoli jeho prototypu, +// použijte kontrolu pomocí `hasOwnProperty()`. +for (var x in myObj){ + if (myObj.hasOwnProperty(x)){ + console.log(myObj[x]); + } +} +///Vypíše: +// Hello world! // Zmínili jsme již předtím, že '__proto__' není ve standardu a není cesta, jak // měnit prototyp existujícího objektu. Avšak existují možnosti, jak vytvořit -// nový objekt s daným prototypem +// nový objekt s daným prototypem. // První je Object.create, což je nedávný přídavek do JS a není dostupný zatím // ve všech implementacích. var mujObjekt = Object.create(mujPrototyp); -mujObjekt.smyslZivota // = 43 +mujObjekt.smyslZivota; // = 43 -// Druhý způsob, který funguje všude je pomocí konstuktoru. Konstruktor má +// Druhý způsob, který funguje všude, je pomocí konstruktoru. Konstruktor má // vlastnost jménem prototype. Toto *není* prototyp samotného konstruktoru, ale // prototyp nového objektu. MujKonstruktor.prototype = { @@ -499,10 +538,10 @@ MujKonstruktor.prototype = { }; var mujObjekt2 = new MujKonstruktor(); mujObjekt2.ziskejMojeCislo(); // = 5 -mujObjekt2.mojeCislo = 6 +mujObjekt2.mojeCislo = 6; mujObjekt2.ziskejMojeCislo(); // = 6 -// Vestavěnné typy jako čísla nebo řetězce mají také konstruktory, které vytváří +// Vestavěné typy jako čísla nebo řetězce mají také konstruktory, které vytváří // ekvivalentní obalovací objekty (wrappery). var mojeCislo = 12; var mojeCisloObj = new Number(12); @@ -521,7 +560,7 @@ if (new Number(0)){ // a objekty jsou vždy pravdivé } -// Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže +// Avšak, obalovací objekty a normální vestavěné typy sdílejí prototyp, takže // můžete přidat funkcionalitu k řetězci String.prototype.prvniZnak = function(){ return this.charAt(0); @@ -530,45 +569,60 @@ String.prototype.prvniZnak = function(){ // Tento fakt je často používán v polyfillech, což je implementace novějších // vlastností JavaScriptu do starších variant, takže je můžete používat třeba -// ve starých prohlížečích +// ve starých prohlížečích. -// Pro příkklad, zmínili jsme, že Object.create není dostupný ve všech -// implementacích, můžeme si avšak přidat pomocí polyfillu +// Na příklad jsme zmínili, že Object.create není dostupný ve všech +// implementacích, ale můžeme si ho přidat pomocí polyfillu: if (Object.create === undefined){ // nebudeme ho přepisovat, když existuje Object.create = function(proto){ // vytvoříme dočasný konstruktor var Constructor = function(){}; Constructor.prototype = proto; - // ten použijeme k vytvoření nového s prototypem + // ten použijeme k vytvoření nového objektu s prototypem return new Constructor(); - } + }; } ``` ## Kam dál -[Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) obsahuje -perfektní dokumentaci pro JavaScript, který je používaný v prohlížečích. Navíc -je to i wiki, takže jakmile se naučíte více, můžete pomoci ostatním, tím, že -přispějete svými znalostmi. +[Mozilla Developer Network][1] obsahuje perfektní dokumentaci pro JavaScript, +který je používaný v prohlížečích. Navíc je to i wiki, takže jakmile se naučíte +více, můžete pomoci ostatním tím, že přispějete svými znalostmi. -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +MDN's [A re-introduction to JavaScript][2] pojednává o konceptech vysvětlených zde v mnohem větší hloubce. Tento návod -pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit více, jak se používá -na webových stránkách, začněte tím, že se kouknete na [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit, jak se používá +na webových stránkách, začněte tím, že se podíváte na [DOM][3] + +[Learn Javascript by Example and with Challenges][4] +je varianta tohoto návodu i s úkoly. + +[JavaScript Garden][5] je sbírka příkladů těch nejnepředvídatelnějších částí +tohoto jazyka. + +[JavaScript: The Definitive Guide][6] je klasická výuková kniha. + +[Eloquent Javascript][8] od Marijn Haverbeke je výbornou JS knihou/e-knihou. -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto -návodu i s úkoly- +[Javascript: The Right Way][10] je průvodcem JavaScriptem pro začínající +vývojáře i pomocníkem pro zkušené vývojáře, kteří si chtějí prohloubit své +znalosti. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) je sbírka -příkladů těch nejvíce nepředvídatelných částí tohoto jazyka. +[Javascript:Info][11] je moderním JavaScriptovým průvodcem, který pokrývá +základní i pokročilé témata velice výstižným výkladem. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) -je klasická výuková kniha. +Jako dodatek k přímým autorům tohoto článku byly na těchto stránkách části +obsahu převzaty z Pythonního tutoriálu Louiho Dinha, a tak0 z [JS Tutorial][7] +na stránkách Mozilla Developer Network. -Jako dodatek k přímým autorům tohoto článku, některý obsah byl přizpůsoben z -Pythoního tutoriálu od Louie Dinh na této stráce, a z [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -z Mozilla Developer Network. +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[10]: http://jstherightway.org/ +[11]: https://javascript.info/ diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown index 801d2514..afa9a17c 100644 --- a/de-de/dynamic-programming-de.html.markdown +++ b/de-de/dynamic-programming-de.html.markdown @@ -68,9 +68,9 @@ for i=0 to n-1 ### Einige bekannte DP Probleme -- Floyd Warshall Algorithm - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) -- Integer Knapsack Problem - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) -- Longest Common Subsequence - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Ressourcen diff --git a/de-de/hq9+-de.html.markdown b/de-de/hq9+-de.html.markdown new file mode 100644 index 00000000..b343201a --- /dev/null +++ b/de-de/hq9+-de.html.markdown @@ -0,0 +1,43 @@ +--- +language: HQ9+ +filename: hq9+.html +contributors: + - ["Alexey Nazaroff", "https://github.com/rogaven"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +HQ9+ ist eine Parodie auf esoterische Programmiersprachen und wurde von Cliff Biffle kreiert. +Die Sprache hat nur vier Befehle und ist nicht Turing-vollständig. + +``` +Es gibt nur vier Befehle, die durch die folgenden vier Zeichen dargestellt werden +H: druckt "Hello, world!" +Q: druckt den Quellcode des Programms (ein Quine) +9: druckt den Liedtext von "99 Bottles of Beer" ++: erhöhe den Akkumulator um Eins (Der Wert des Akkumulators kann nicht gelesen werden) +Jedes andere Zeichen wird ignoriert. + +Ok. Lass uns ein Programm schreiben: + HQ + +Ergebnis: + Hello world! + HQ + +HQ9+ ist zwar sehr simpel, es erlaubt aber dir Sachen zu machen, die in +anderen Sprachen sehr schwierig sind. Zum Beispiel druckt das folgende Programm +drei Mal Kopien von sich selbst auf den Bildschirm: + QQQ +Dies druckt: + QQQ + QQQ + QQQ +``` + +Und das ist alles. Es gibt sehr viele Interpreter für HQ9+. +Unten findest du einen von ihnen. + ++ [One of online interpreters](https://almnet.de/esolang/hq9plus.php) ++ [HQ9+ official website](http://cliffle.com/esoterica/hq9plus.html) diff --git a/de-de/opencv-de.html.markdown b/de-de/opencv-de.html.markdown new file mode 100644 index 00000000..2d9a2c4e --- /dev/null +++ b/de-de/opencv-de.html.markdown @@ -0,0 +1,153 @@ +--- +category: tool +tool: OpenCV +filename: learnopencv.py +contributors: + - ["Yogesh Ojha", "http://github.com/yogeshojha"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- +### Opencv + +OpenCV (Open Source Computer Vision) ist eine Bibliothek von Programmierfunktionen, +die hauptsächlich auf maschinelles Sehen in Echtzeit ausgerichtet ist. +Ursprünglich wurde OpenCV von Intel entwickelt. Später wurde es von von +Willow Garage und dann Itseez (das später von Intel übernommen wurde) unterstützt. +OpenCV unterstützt derzeit eine Vielzahl von Sprachen, wie C++, Python, Java uvm. + +#### Installation + +Bitte lese diese Artikel für die Installation von OpenCV auf deinen Computer. + +* Windows Installationsanleitung: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() +* Mac Installationsanleitung (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() +* Linux Installationsanleitung (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() + +### Hier werden wir uns auf die Pythonimplementierung von OpenCV konzentrieren. + +```python +# Bild in OpenCV lesen +import cv2 +img = cv2.imread('Katze.jpg') + +# Bild darstellen +# Die imshow() Funktion wird verwendet um das Display darzustellen. +cv2.imshow('Image',img) +# Das erste Argument ist der Titel des Fensters und der zweite Parameter ist das Bild +# Wenn du den Fehler Object Type None bekommst ist eventuell dein Bildpfad falsch. +# Bitte überprüfe dann den Pfad des Bildes erneut. +cv2.waitKey(0) +# waitKey() ist eine Tastaturbindungsfunktion, sie nimmt Argumente in +# Millisekunden an. Für GUI Ereignisse MUSST du die waitKey() Funktion verwenden. + +# Ein Bild schreiben +cv2.imwrite('graueKatze.png',img) +# Das erste Arkument ist der Dateiname und das Zweite ist das Bild + +# Konveriere das Bild zu Graustufen +gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +# Videoaufnahme von der Webcam +cap = cv2.VideoCapture(0) +# 0 ist deine Kamera, wenn du mehrere Kameras hast musst du deren Id eingeben +while(True): + # Erfassen von Einzelbildern + _, frame = cap.read() + cv2.imshow('Frame',frame) + # Wenn der Benutzer q drückt -> beenden + if cv2.waitKey(1) & 0xFF == ord('q'): + break +# Die Kamera muss wieder freigegeben werden +cap.release() + +# Wiedergabe von Videos aus einer Datei +cap = cv2.VideoCapture('film.mp4') +while(cap.isOpened()): + _, frame = cap.read() + # Das Video in Graustufen abspielen + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + cv2.imshow('frame',gray) + if cv2.waitKey(1) & 0xFF == ord('q'): + break +cap.release() + +# Zeichne eine Linie in OpenCV +# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +cv2.line(img,(0,0),(511,511),(255,0,0),5) + +# Zeichne ein Rechteck +# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# thickness = -1 wird zum Füllen des Rechtecks verwendet +cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) + +# Zeichne ein Kreis +cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img,(200,90), 100, (0,0,255), -1) + +# Zeichne eine Ellipse +cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) + +# Text auf Bildern hinzufügen +cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) + +# Bilder zusammenfüggen +img1 = cv2.imread('Katze.png') +img2 = cv2.imread('openCV.jpg') +dst = cv2.addWeighted(img1,0.5,img2,0.5,0) + +# Schwellwertbild +# Binäre Schwellenwerte +_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) +# Anpassbare Schwellenwerte +adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) + +# Weichzeichnung von einem Bild +# Gausßscher Weichzeichner +blur = cv2.GaussianBlur(img,(5,5),0) +# Rangordnungsfilter +medianBlur = cv2.medianBlur(img,5) + +# Canny-Algorithmus +img = cv2.imread('Katze.jpg',0) +edges = cv2.Canny(img,100,200) + +# Gesichtserkennung mit Haarkaskaden +# Lade die Haarkaskaden von https://github.com/opencv/opencv/blob/master/data/haarcascades/ herunter +import cv2 +import numpy as np +face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') +eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') + +img = cv2.imread('Mensch.jpg') +gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +aces = face_cascade.detectMultiScale(gray, 1.3, 5) +for (x,y,w,h) in faces: + cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) + roi_gray = gray[y:y+h, x:x+w] + roi_color = img[y:y+h, x:x+w] + eyes = eye_cascade.detectMultiScale(roi_gray) + for (ex,ey,ew,eh) in eyes: + cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + +cv2.imshow('img',img) +cv2.waitKey(0) + +cv2.destroyAllWindows() +# destroyAllWindows() zerstört alle Fenster +# Wenn du ein bestimmtes Fenter zerstören möchtest musst du den genauen Namen des +# von dir erstellten Fensters übergeben. +``` + +### Weiterführende Literatur: +* Lade Kaskade hier herunter [https://github.com/opencv/opencv/blob/master/data/haarcascades]() +* OpenCV Zeichenfunktionen [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() +* Eine aktuelle Sprachenreferenz kann hier gefunden werden [https://opencv.org]() +* Zusätzliche Ressourcen können hier gefunden werden [https://en.wikipedia.org/wiki/OpenCV]() +* Gute OpenCV Tutorials + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() + * [https://realpython.com/python-opencv-color-spaces]() + * [https://pyimagesearch.com]() + * [https://www.learnopencv.com]() + * [https://docs.opencv.org/master/]() diff --git a/de-de/paren-de.html.markdown b/de-de/paren-de.html.markdown new file mode 100644 index 00000000..0d914c05 --- /dev/null +++ b/de-de/paren-de.html.markdown @@ -0,0 +1,200 @@ +--- + +language: Paren +filename: learnparen.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] + - ["Claudson Martins", "https://github.com/claudsonm"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +[Paren](https://bitbucket.org/ktg/paren) ist ein Dialekt von Lisp. +Es ist als eingebettete Sprache konzipiert. + +Manche Beispiele sind von <http://learnxinyminutes.com/docs/racket/>. + +```scheme +;;; Kommentare +# Kommentare + +;; Einzeilige Kommentare starten mit einem Semikolon oder einem Hashtag + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Primitive Datentypen und Operatoren +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Zahlen +123 ; int +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : int +(double 123) ; => 123 : double + +;; Funktionsapplikationen werden so geschrieben: (f x y z ...) +;; Dabei ist f eine Funktion und x, y, z sind die Operatoren. +;; Wenn du eine Literalliste von Daten erstelllen möchtest, +;; verwende (quote) um zu verhindern, dass sie ausgewertet zu werden. +(quote (+ 1 2)) ; => (+ 1 2) +;; Nun einige arithmetische Operationen +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Wahrheitswerte +true ; for Wahr +false ; for Falsch +(! true) ; => Falsch +(&& true false (prn "doesn't get here")) ; => Falsch +(|| false true (prn "doesn't get here")) ; => Wahr + +;;; Zeichen sind Ints. +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Zeichenketten sind ein Array von Zahlen mit fester Länge. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; Backslash ist ein Escape-Zeichen +"Foo\tbar\r\n" ; beinhaltet C Escapes: \t \r \n + +;; Zeichenketten können auch verbunden werden! +(strcat "Hello " "world!") ; => "Hello world!" + +;; Eine Zeichenketten kann als Liste von Zeichen behandelt werden +(char-at "Apple" 0) ; => 65 + +;; Drucken ist ziemlich einfach +(pr "Ich bin" "Paren. ") (prn "Schön dich zu treffen!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variablen +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Du kannst Variablen setzen indem du (set) verwedest +;; eine Variable kann alle Zeichen besitzen außer: ();#" +(set some-var 5) ; => 5 +some-var ; => 5 + +;; Zugriff auf eine zuvor nicht zugewiesene Variable erzeugt eine Ausnahme +; x ; => Unknown variable: x : nil + +;; Lokale Bindung: Verwende das Lambda Calculus! 'a' und 'b' +;; sind nur zu '1' und '2' innerhalb von (fn ...) gebunden. +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Sammlungen +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Listen + +;; Listen sind Vektrorartige Datenstrukturen. (Zufälliger Zugriff ist O(1). +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; 'list' ist ein komfortabler variadischer Konstruktor für Listen +(list 1 2 3) ; => (1 2 3) +;; und ein quote kann als literaler Listwert verwendet werden +(quote (+ 1 2)) ; => (+ 1 2) + +;; Du kannst 'cons' verwenden um ein Element an den Anfang einer Liste hinzuzufügen. +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Listen sind ein sehr einfacher Typ, daher gibt es eine Vielzahl an Funktionen +;; für Sie. Ein paar Beispiele: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funktionen +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Verwende 'fn' um Funktionen zu erstellen. +;; eine Funktion gibt immer den Wert ihres letzten Ausdrucks zurück +(fn () "Hello World") ; => (fn () Hello World) : fn + +;; Verwende Klammern um alle Funktionen aufzurufen, inklusive Lambda Ausdrücke +((fn () "Hello World")) ; => "Hello World" + +;; Zuweisung einer Funktion zu einer Variablen +(set hello-world (fn () "Hello World")) +(hello-world) ; => "Hello World" + +;; Du kannst dies mit syntaktischen Zucker für die Funktionsdefinition verkürzen: +(defn hello-world2 () "Hello World") + +;; Die () von oben ist eine Liste von Argumente für die Funktion. +(set hello + (fn (name) + (strcat "Hello " name))) +(hello "Steve") ; => "Hello Steve" + +;; ... oder gleichwertig, unter Verwendung mit syntaktischen Zucker: +(defn hello2 (name) + (strcat "Hello " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Gleichheit +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Für Zahlen verwende '==' +(== 3 3.0) ; => wahr +(== 2 1) ; => falsch + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Kontrollfluss +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Bedingungen + +(if true ; test Ausdruck + "this is true" ; then Ausdruck + "this is false") ; else Ausdruck +; => "this is true" + +;;; Schleifen + +;; for Schleifen ist für Zahlen +;; (for SYMBOL START ENDE SCHRITT AUSDRUCK ..) +(for i 0 10 2 (pr i "")) ; => schreibt 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => schreibt 0 2.5 5 7.5 10 + +;; while Schleife +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => schreibt 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutation +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Verwende 'set' um einer Variablen oder einer Stelle einen neuen Wert zuzuweisen. +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Makros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Makros erlauben es dir die Syntax der Sprache zu erweitern. +;; Parens Makros sind einfach. +;; Tatsächlich ist (defn) ein Makro. +(defmacro setfn (name ...) (set name (fn ...))) +(defmacro defn (name ...) (def name (fn ...))) + +;; Lass uns eine Infix Notation hinzufügen +;; Let's add an infix notation +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Makros sind nicht hygenisch, Du kannst bestehende Variablen überschreiben! +;; Sie sind Codetransformationenen. +``` diff --git a/de-de/rst-de.html.markdown b/de-de/rst-de.html.markdown new file mode 100644 index 00000000..bcfe21bd --- /dev/null +++ b/de-de/rst-de.html.markdown @@ -0,0 +1,119 @@ +--- +language: restructured text (RST) +filename: restructuredtext.rst +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +RST ist ein Dateiformat, das von der Python Community entwickelt wurde, + +um Dokumentation zu schreiben (und ist somit Teil von Docutils). + +RST-Dateien sind simple Textdateien mit einer leichtgewichtigen Syntax (im Vergleich zu HTML). + + +## Installation + +Um Restructured Text zu vewenden musst du [Python](http://www.python.org) + +installieren und das `docutils` Packet installieren. `docutils` kann mit dem folgenden + +Befehl auf der Kommandozeile installiert werden: + +```bash +$ easy_install docutils +``` + +Wenn auf deinem System `pip` installiert kannst du es statdessen auch verwenden: + +```bash +$ pip install docutils +``` + + +## Dateisyntax + +Ein einfaches Beispiel für die Dateisyntax: + +``` +.. Zeilen, die mit zwei Punkten starten sind spezielle Befehle. + +.. Wenn kein Befehl gefunden wird, wird die Zeile als Kommentar gewertet. + +============================================================================ +Haupttitel werden mit Gleichheitszeichen darüber und darunter gekennzeichnet +============================================================================ + +Beachte das es genau so viele Gleichheitszeichen, wie Hauptitelzeichen +geben muss. + +Titel werden auch mit Gleichheitszeichen unterstrichen +====================================================== + +Untertitel werden mit Strichen gekennzeichnet +--------------------------------------------- + +Text in *kursiv* oder in **fett**. Du kannst Text als Code "makieren", wenn +du doppelte Backquotes verwendest ``: ``print()``. + +Listen sind so einfach wie in Markdown: + +- Erstes Element +- Zweites Element + - Unterelement + +oder + +* Erstes Element +* Zweites Element + * Unterelement + +Tabellen sind einfach zu schreiben: + +=========== ========== +Land Hauptstadt +=========== ========== +Frankreich Paris +Japan Tokyo +=========== ======== + +Komplexere Tabellen (zusammengeführte Spalten und Zeilen) können einfach +erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu lesen :) + +Es gibt mehrere Möglichkeiten um Links zu machen: + +- Wenn man einen Unterstrich hinter einem Wort hinzufügt: Github_ Zusätzlich +muss man die Zielurl nach dem Text hinzufügen. +(Dies hat den Vorteil, dass man keine unnötigen Urls in lesbaren Text einfügt. +- Wenn man die vollständige Url eingibt : https://github.com/ +(Dies wird automatisch in ein Link konvertiert.) +- Wenn man es mehr Markdown ähnlich eingibt: `Github <https://github.com/>`_ . + +.. _Github https://github.com/ + +``` + + +## Wie man es verwendet + +RST kommt mit docutils, dort hast du den Befehl `rst2html`, zum Beispiel: + +```bash +$ rst2html myfile.rst output.html +``` + +*Anmerkung : Auf manchen Systemen könnte es rst2html.py sein* + +Es gibt komplexere Anwendungen, die das RST Format verwenden: + +- [Pelican](http://blog.getpelican.com/), ein statischer Websitengenerator +- [Sphinx](http://sphinx-doc.org/), Ein Dokumentationsgenerator +- und viele Andere + +## Zum Lesen + +- [Offizielle Schnellreferenz](http://docutils.sourceforge.net/docs/user/rst/quickref.html) diff --git a/de-de/shutit-de.html.markdown b/de-de/shutit-de.html.markdown new file mode 100644 index 00000000..f66ed906 --- /dev/null +++ b/de-de/shutit-de.html.markdown @@ -0,0 +1,330 @@ +--- +category: tool +filename: learnshutit.html +tool: ShutIt +contributors: + - ["Ian Miell", "http://ian.meirionconsulting.tk"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +## ShutIt + +ShuIt ist eine Shellautomationsframework, welches für eine einfache +Handhabung entwickelt wurde. + +Er ist ein Wrapper, der auf einem Python expect Klon (pexpect) basiert. + +Es ist damit ein 'expect ohne Schmerzen'. + +Es ist verfügbar als pip install. + +## Hello World + +Starten wir mit dem einfachsten Beispiel. Erstelle eine Datei names example.py + +```python + +import shutit +session = shutit.create_session('bash') +session.send('echo Hello World', echo=True) +``` + +Führe es hiermit aus: + +```bash +python example.py +``` + +gibt aus: + +```bash +$ python example.py +echo "Hello World" +echo "Hello World" +Hello World +Ians-MacBook-Air.local:ORIGIN_ENV:RhuebR2T# +``` + +Das erste Argument zu 'send' ist der Befehl, den du ausführen möchtest. +Das 'echo' Argument gibt die Terminalinteraktion aus. ShuIt ist standardmäßig leise. + +'Send' kümmert sich um die nervige Arbeiten mit den Prompts und macht +alles was du von 'expect' erwarten würdest. + + +## Logge dich auf einen Server ein + +Sagen wir du möchtest dich auf einen Server einloggen und einen Befehl ausführen. +Ändere dafür example.py folgendermaßen: + +```python +import shutit +session = shutit.create_session('bash') +session.login('ssh you@example.com', user='du', password='meinpassword') +session.send('hostname', echo=True) +session.logout() +``` + +Dies erlaubt dir dich auf deinen Server einzuloggen +(ersetze die Details mit deinen Eigenen) und das Programm gibt dir deinen Hostnamen aus. + +``` +$ python example.py +hostname +hostname +example.com +example.com:cgoIsdVv:heDa77HB# +``` + + +Es ist klar das das nicht sicher ist. Stattdessen kann man Folgendes machen: + +```python +import shutit +session = shutit.create_session('bash') +password = session.get_input('', ispass=True) +session.login('ssh you@example.com', user='du', password=password) +session.send('hostname', echo=True) +session.logout() +``` + +Dies zwingt dich dein Passwort einzugeben: + +``` +$ python example.py +Input Secret: +hostname +hostname +example.com +example.com:cgoIsdVv:heDa77HB# +``` + + +Die 'login' Methode übernimmt wieder das veränderte Prompt für den Login. +Du übergibst ShutIt den User und das Passwort, falls es benötigt wird, +mit den du dich einloggen möchtest. ShutIt übernimmt den Rest. + +'logout' behandelt das Ende von 'login' und übernimmt alle Veränderungen des +Prompts für dich. + +## Einloggen auf mehrere Server + +Sagen wir, dass du eine Serverfarm mit zwei Servern hast und du dich in +beide Server einloggen möchtest. Dafür musst du nur zwei Session und +Logins erstellen und kannst dann Befehle schicken: + +```python +import shutit +session1 = shutit.create_session('bash') +session2 = shutit.create_session('bash') +password1 = session1.get_input('Password für server1', ispass=True) +password2 = session2.get_input('Password für server2', ispass=True) +session1.login('ssh you@one.example.com', user='du', password=password1) +session2.login('ssh you@two.example.com', user='du', password=password2) +session1.send('hostname', echo=True) +session2.send('hostname', echo=True) +session1.logout() +session2.logout() +``` + +Gibt aus: + +```bash +$ python example.py +Password for server1 +Input Secret: + +Password for server2 +Input Secret: +hostname +hostname +one.example.com +one.example.com:Fnh2pyFj:qkrsmUNs# hostname +hostname +two.example.com +two.example.com:Gl2lldEo:D3FavQjA# +``` + +## Beispiel: Überwachen mehrerer Server + +Wir können das obige Programm in ein einfaches Überwachungstool bringen indem +wir Logik hinzufügen um die Ausgabe von einem Befehl zu betrachten. + +```python +import shutit +capacity_command="""df / | awk '{print $5}' | tail -1 | sed s/[^0-9]//""" +session1 = shutit.create_session('bash') +session2 = shutit.create_session('bash') +password1 = session.get_input('Passwort für Server1', ispass=True) +password2 = session.get_input('Passwort für Server2', ispass=True) +session1.login('ssh you@one.example.com', user='du', password=password1) +session2.login('ssh you@two.example.com', user='du', password=password2) +capacity = session1.send_and_get_output(capacity_command) +if int(capacity) < 10: + print(kein Platz mehr auf Server1!') +capacity = session2.send_and_get_output(capacity_command) +if int(capacity) < 10: + print(kein Platz mehr auf Server2!') +session1.logout() +session2.logout() +``` + +Hier kannst du die 'send\_and\_get\_output' Methode verwenden um die Ausgabe von dem +Kapazitätsbefehl (df) zu erhalten. + +Es gibt elegantere Wege als oben (z.B. kannst du ein Dictionary verwenden um über +die Server zu iterieren), aber es hängt and dir wie clever das Python sein muss. + + +## kompliziertere IO - Expecting + +Sagen wir du hast eine Interaktion mit einer interaktiven Kommandozeilenprogramm, +die du automatisieren möchtest. Hier werden wir Telnet als triviales Beispiel verwenden: + +```python +import shutit +session = shutit.create_session('bash') +session.send('telnet', expect='elnet>', echo=True) +session.send('open google.com 80', expect='scape character', echo=True) +session.send('GET /', echo=True, check_exit=False) +session.logout() +``` + +Beachte das 'expect' Argument. Du brauchst nur ein Subset von Telnets +Eingabeaufforderung um es abzugleichen und fortzufahren. + +Beachte auch das neue Argument 'check\_exit'. Wir werden nachher nochmal +darauf zurückkommen. Die Ausgabe von oben ist: + +```bash +$ python example.py +telnet +telnet> open google.com 80 +Trying 216.58.214.14... +Connected to google.com. +Escape character is '^]'. +GET / +HTTP/1.0 302 Found +Cache-Control: private +Content-Type: text/html; charset=UTF-8 +Referrer-Policy: no-referrer +Location: http://www.google.co.uk/?gfe_rd=cr&ei=huczWcj3GfTW8gfq0paQDA +Content-Length: 261 +Date: Sun, 04 Jun 2017 10:57:10 GMT + +<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> +<TITLE>302 Moved</TITLE></HEAD><BODY> +<H1>302 Moved</H1> +The document has moved +<A HREF="http://www.google.co.uk/?gfe_rd=cr&ei=huczWcj3GfTW8gfq0paQDA"> +here +</A>. +</BODY></HTML> +Connection closed by foreign host. +``` + +Nun zurück zu 'check\_exit=False'. Da das Telnet Programm einen Fehler mit +Fehlercode (1) zurückgibt und wir nicht möchten das das Skript fehlschlägt +kannst du 'check\_exit=False' setzen und damit ShuIt wissen lassen, dass +der Ausgabecode dich nicht interessiert. + +Wenn du das Argument nicht mitgegeben hättest, dann hätte dir ShutIt +ein interaktives Terminal zurückgegeben, falls es ein Terminal zum +kommunizieren gibt. Dies nennt sich ein 'Pause point'. + + +## Pause Points + +Du kannst jederzeit 'pause point' auslösen, wenn du Folgendes in deinem Skript aufrufst: + +```python +[...] +session.pause_point('Das ist ein pause point') +[...] +``` + +Danach kannst du das Skript fortführen, wenn du CTRL und ']' zur selben Zeit drückst. +Dies ist gut für Debugging: Füge ein Pause Point hinzu und schaue dich um. +Danach kannst du das Programm weiter ausführen. Probiere folgendes aus: + +```python +import shutit +session = shutit.create_session('bash') +session.pause_point('Schaue dich um!') +session.send('echo "Hat dir der Pause point gefallen?"', echo=True) +``` + +Dies würde folgendes ausgeben: + +```bash +$ python example.py +Schaue dich um! + +Ians-Air.home:ORIGIN_ENV:I00LA1Mq# bash +imiell@Ians-Air:/space/git/shutit ⑂ master + +CTRL-] caught, continuing with run... +2017-06-05 15:12:33,577 INFO: Sending: exit +2017-06-05 15:12:33,633 INFO: Output (squashed): exitexitIans-Air.home:ORIGIN_ENV:I00LA1Mq# [...] +echo "Hat dir der Pause point gefallen?" +echo "Hat dir der Pause point gefallen?" +Hat dir der Pause point gefallen? +Ians-Air.home:ORIGIN_ENV:I00LA1Mq# +``` + + +## noch kompliziertere IO - Hintergrund + +Kehren wir zu unseren Beispiel mit dem Überwachen von mehreren Servern zurück. +Stellen wir uns vor, dass wir eine langlaufende Aufgabe auf jedem Server durchführen möchten. +Standardmäßig arbeitet ShutIt seriell, was sehr lange dauern würde. +Wir können jedoch die Aufgaben im Hintergrund laufen lassen um sie zu beschleunigen. + +Hier ist ein Beispiel, welches du ausprobieren kannst. +Es verwendet den trivialen Befehl: 'sleep'. + + +```python +import shutit +import time +long_command="""sleep 60""" +session1 = shutit.create_session('bash') +session2 = shutit.create_session('bash') +password1 = session1.get_input('Password for server1', ispass=True) +password2 = session2.get_input('Password for server2', ispass=True) +session1.login('ssh you@one.example.com', user='du', password=password1) +session2.login('ssh you@two.example.com', user='du', password=password2) +start = time.time() +session1.send(long_command, background=True) +session2.send(long_command, background=True) +print('Es hat: ' + str(time.time() - start) + ' Sekunden zum Starten gebraucht') +session1.wait() +session2.wait() +print('Es hat:' + str(time.time() - start) + ' Sekunden zum Vollenden gebraucht') +``` + +Mein Computer meint, dass er 0.5 Sekunden gebraucht hat um die Befehle zu starten +und dann nur etwas über eine Minute gebraucht um sie zu beenden +(mit Verwendung der 'wait' Methode). + + +Das alles ist trivial, aber stelle dir vor das du hunderte an Servern so managen +kannst und man kann nun das Potential sehen, die in ein paar Zeilen Code und ein Python +import liegen können. + + +## Lerne mehr + +Es gibt noch viel mehr, was mit ShutIt erreicht werden kann. + +Um mehr zu erfahren, siehe: + +[ShutIt](https://ianmiell.github.io/shutit/) +[GitHub](https://github.com/ianmiell/shutit/blob/master/README.md) + +Es handelt sich um ein breiteres Automatiesierungsframework, und das oben +genannte ist der sogennante 'standalone Modus'. + +Feedback, feature requests, 'Wie mache ich es' sind herzlich willkommen! Erreiche mit unter +[@ianmiell](https://twitter.com/ianmiell) diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown index 4db8e92e..aed169fc 100644 --- a/dynamic-programming.html.markdown +++ b/dynamic-programming.html.markdown @@ -42,9 +42,9 @@ for i=0 to n-1 ### Some Famous DP Problems -- Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -- Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Resources diff --git a/elixir.html.markdown b/elixir.html.markdown index a74baa38..e82509e7 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -287,7 +287,11 @@ end PrivateMath.sum(1, 2) #=> 3 # PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) -# Function declarations also support guards and multiple clauses: +# Function declarations also support guards and multiple clauses. +# When a function with multiple clauses is called, the first function +# that satisfies the clause will be invoked. +# Example: invoking area({:circle, 3}) will call the second area +# function defined below, not the first: defmodule Geometry do def area({:rectangle, w, h}) do w * h diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown index bd1ad07c..2c3762d5 100644 --- a/es-es/c++-es.html.markdown +++ b/es-es/c++-es.html.markdown @@ -823,7 +823,6 @@ v.swap(vector<Foo>()); ``` Otras lecturas: -Una referencia del lenguaje hasta a la fecha se puede encontrar en -<http://cppreference.com/w/cpp> - -Recursos adicionales se pueden encontrar en <http://cplusplus.com> +* Una referencia del lenguaje hasta a la fecha se puede encontrar en [CPP Reference](http://cppreference.com/w/cpp). +* Recursos adicionales se pueden encontrar en [[CPlusPlus]](http://cplusplus.com). +* Un tutorial que cubre los conceptos básicos del lenguaje y la configuración del entorno de codificación está disponible en [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FF). diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown index 05fd7065..3236e73a 100644 --- a/es-es/python3-es.html.markdown +++ b/es-es/python3-es.html.markdown @@ -14,8 +14,6 @@ Es básicamente pseudocódigo ejecutable. ¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] -Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3! - ```python # Comentarios de una línea comienzan con una almohadilla (o signo gato) @@ -39,6 +37,8 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl # Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) 35 / 5 # => 7.0 +# Sin embargo también tienes disponible división entera +34 // 5 # => 6 # Cuando usas un float, los resultados son floats 3 * 2.0 # => 6.0 @@ -87,11 +87,14 @@ not False # => True # .format puede ser usaro para darle formato a los strings, así: "{} pueden ser {}".format("strings", "interpolados") -# Puedes repetir los argumentos de formateo para ahorrar tipeos. +# Puedes reutilizar los argumentos de formato si estos se repiten. "{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" # Puedes usar palabras claves si no quieres contar. -"{nombre} quiere comer {comida}".format(nombre="Bob", food="lasaña") #=> "Bob quiere comer lasaña" - +"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña" +# También puedes interpolar cadenas usando variables en el contexto +nombre = 'Bob' +comida = 'Lasaña' +f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña" # None es un objeto None # => None @@ -101,12 +104,13 @@ None # => None "etc" is None #=> False None is None #=> True -# None, 0, y strings/listas/diccionarios vacíos(as) todos se evalúan como False. +# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False. # Todos los otros valores son True bool(0) # => False bool("") # => False bool([]) #=> False bool({}) #=> False +bool(set()) #=> False #################################################### @@ -170,7 +174,7 @@ lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan # Concatenar listas con 'extend' lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] -# Chequea la existencia en una lista con 'in' +# Verifica la existencia en una lista con 'in' 1 in lista #=> True # Examina el largo de una lista con 'len' @@ -196,7 +200,7 @@ d, e, f = 4, 5, 6 e, d = d, e # d ahora es 5 y e ahora es 4 -# Diccionarios almacenan mapeos +# Diccionarios relacionan llaves y valores dicc_vacio = {} # Aquí está un diccionario prellenado dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} @@ -213,7 +217,7 @@ list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] list(dicc_lleno.values()) #=> [3, 2, 1] # Nota - Lo mismo que con las llaves, no se garantiza el orden. -# Chequea la existencia de una llave en el diccionario con 'in' +# Verifica la existencia de una llave en el diccionario con 'in' "uno" in dicc_lleno #=> True 1 in dicc_lleno #=> False @@ -253,7 +257,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} # Haz diferencia de conjuntos con - {1,2,3,4} - {2,3,5} #=> {1, 4} -# Chequea la existencia en un conjunto con 'in' +# Verifica la existencia en un conjunto con 'in' 2 in conjunto_lleno #=> True 10 in conjunto_lleno #=> False @@ -262,7 +266,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} ## 3. Control de Flujo #################################################### -# Let's just make a variable +# Creemos una variable para experimentar some_var = 5 # Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! @@ -275,18 +279,17 @@ else: # Esto también es opcional. print("una_variable es de hecho 10.") """ -For itera sobre listas +For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...) imprime: perro es un mamifero gato es un mamifero raton es un mamifero """ for animal in ["perro", "gato", "raton"]: - # Puedes usar % para interpolar strings formateados print("{} es un mamifero".format(animal)) """ -`range(número)` retorna una lista de números +`range(número)` retorna un generador de números desde cero hasta el número dado imprime: 0 @@ -323,7 +326,7 @@ except IndexError as e: dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} nuestro_iterable = dicc_lleno.keys() -print(nuestro_iterable) #=> range(1,10). Este es un objeto que implementa nuestra interfaz Iterable +print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable Podemos recorrerla. for i in nuestro_iterable: @@ -420,6 +423,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # Podemos usar listas por comprensión para mapeos y filtros agradables [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# también hay diccionarios +{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4} +# y conjuntos por comprensión +{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'} #################################################### ## 5. Classes diff --git a/factor.html.markdown b/factor.html.markdown index 79596d83..53c692df 100644 --- a/factor.html.markdown +++ b/factor.html.markdown @@ -9,7 +9,7 @@ Factor is a modern stack-based language, based on Forth, created by Slava Pestov Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. -``` +```factor ! This is a comment ! Like Forth, all programming is done by manipulating the stack. diff --git a/fr-fr/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown index acbaed58..863162f7 100644 --- a/fr-fr/c++-fr.html.markdown +++ b/fr-fr/c++-fr.html.markdown @@ -910,7 +910,6 @@ v.swap(vector<Foo>()); ``` Lecture complémentaire : -Une référence à jour du langage est disponible à -<http://cppreference.com/w/cpp> - -Des ressources supplémentaires sont disponibles à <http://cplusplus.com> +* Une référence à jour du langage est disponible à [CPP Reference](http://cppreference.com/w/cpp). +* Des ressources supplémentaires sont disponibles à [CPlusPlus](http://cplusplus.com). +* Un tutoriel couvrant les bases du langage et la configuration d'un environnement de codage est disponible à l'adresse [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown index b3660ac9..54cca001 100644 --- a/fr-fr/dynamic-programming-fr.html.markdown +++ b/fr-fr/dynamic-programming-fr.html.markdown @@ -42,9 +42,9 @@ Le même concept peut être appliqué pour trouver le chemin le plus long dans u ### Problèmes classiques de programmation dynamique -- L'algorithme de Floyd Warshall(EN)) - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- Problème du sac à dos(EN) - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -- Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence +- L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Problème du sac à dos(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Resources diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 8518f35c..2955fd14 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -6,52 +6,69 @@ filename: markdown-fr.md lang: fr-fr --- + Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe -facile à lire et à écrire, aisément convertible en HTML - (et beaucoup d'autres formats aussi à présent). +facile à lire et à écrire, aisément convertible en HTML (et dans beaucoup +d'autres formats aussi). + +Les implémentations du Markdown varient d'un analyseur syntaxique à un autre. +Ce guide va essayer de clarifier quand une fonctionnalité est universelle ou +quand elle est specifique à un certain analyseur syntaxique. + +- [Balises HTML](#balises-html) +- [En-têtes](#en-tetes) +- [Styles de texte basiques](#style-de-text-basiques) +- [Paragraphes](#paragraphes) +- [Listes](#listes) +- [Blocs de code](#blocs-de-code) +- [Séparateur horizontal](#separateur-horizontal) +- [Liens hypertextes](#liens-hypertextes) +- [Images](#images) +- [Divers](#divers) -Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" -et envoyer des pull request! +## Balises HTML +Markdown est un sur-ensemble du HTML, donc tout fichier HTML est un ficher +Markdown valide. ```md -<!-- Markdown est une sorte de cousin du HTML, si bien que tout document HTML -est un document Markdown valide. Autrement dit, vous pouvez utiliser des -balises HTML dans un fichier Markdown, comme la balise commentaire dans -laquelle nous sommes à présent, car celle-ci ne sera pas affectée par -le parser( analyseur syntaxique ) Markdown. --> +<!-- Ce qui veut dire que vous pouvez utiliser des balises HTML dans un fichier +Markdown, comme la balise commentaire dans laquelle nous sommes à présent, car +celle-ci ne sera pas affectée par l'analyseur syntaxique du Markdown. +Toutefois, si vous voulez créer une balise HTML dans un fichier Markdown, +vous ne pourrez pas utiliser du Markdown à l'intérieur de cette derniere. --> +``` -<!-- Toutefois, si vous voulez créer un élément HTML dans un fichier Markdown, - vous ne pourrez pas utiliser du Markdown à l'intérieur de ce dernier. --> +## En-têtes -<!-- Le Markdown est implémenté de différentes manières, selon le parser. -Ce guide va alors tenter de trier les fonctionnalités universelles de celles -spécifiques à un parser. --> +Vous pouvez facilement créer des balises HTML `<h1>` à `<h6>` en précédant le +texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon +le niveau de titre souhaité. -<!-- Headers ( En-têtes ) --> -<!-- Vous pouvez facilement créer des éléments HTML <h1> à <h6> en précédant - le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, - selon le niveau de titre souhaité. --> +```md # Ceci est un <h1> ## Ceci est un <h2> ### Ceci est un <h3> #### Ceci est un <h4> ##### Ceci est un <h5> ###### Ceci est un <h6> +``` -<!-- -Markdown fournit également une façon alternative de marquer les h1 et h2 ---> +Markdown fournit également une façon alternative de marquer les h1 et h2. +```md Ceci est un h1 ============= Ceci est un h2 ------------- +``` + +## Styles de texte basiques -<!-- Styles basiques pour du texte --> -<!-- On peut facilement rendre un texte "gras" ou "italique" en Markdown --> +On peut facilement rendre un texte "gras" ou "italique" en Markdown. +```md *Ce texte est en italique.* _Celui-ci aussi._ @@ -61,15 +78,21 @@ __Celui-là aussi.__ ***Ce texte a les deux styles.*** **_Pareil ici_** *__Et là!__* +``` -<!-- Dans le "GitHub Flavored Markdown", utilisé pour interpréter le Markdown -sur GitHub, on a également le strikethrough ( texte barré ) : --> +Dans le "GitHub Flavored Markdown", utilisé pour interpréter le Markdown sur +GitHub, on a également le texte barré. -~~Ce texte est barré avec strikethrough.~~ +```md +~~Ce texte est barré.~~ +``` + +## Paragraphes -<!-- Les Paragraphes sont représentés par une ou plusieurs lignes de texte -séparées par une ou plusieurs lignes vides. --> +Les paragraphes sont représentés par une ou plusieurs lignes de texte séparées +par une ou plusieurs lignes vides. +```md Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? Maintenant je suis dans le paragraphe 2. @@ -77,21 +100,23 @@ Je suis toujours dans le paragraphe 2! Puis là, eh oui, le paragraphe 3! +``` -<!-- -Si jamais vous souhaitez insérer une balise HTML <br />, vous pouvez ajouter -un ou plusieurs espaces à la fin de votre paragraphe, et en commencer -un nouveau. ---> +Si jamais vous souhaitez insérer une balise HTML `<br />`, vous pouvez ajouter +un ou plusieurs espaces à la fin de votre paragraphe, et en commencer un +nouveau. -J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). +```md +J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un <br /> au dessus de moi! +``` -<!-- Les 'Blocs de Citations' sont générés aisément, grâce au caractère > --> +Les blocs de citations sont générés aisément, grâce au caractère >. +```md > Ceci est une superbe citation. Vous pouvez même -> revenir à la ligne quand ça vous chante, et placer un `>` +> revenir à la ligne quand ça vous chante, et placer un `>` > devant chaque bout de ligne faisant partie > de la citation. > La taille ne compte pas^^ tant que chaque ligne commence par un `>`. @@ -99,191 +124,248 @@ Bigre, il y a un <br /> au dessus de moi! > Vous pouvez aussi utiliser plus d'un niveau >> d'imbrication! > Classe et facile, pas vrai? +``` + +## Listes -<!-- les Listes --> -<!-- les Listes non ordonnées sont marquées par des asterisques, -signes plus ou signes moins. --> +Les listes non ordonnées sont marquées par des asterisques, signes plus ou +signes moins. +```md * Item * Item * Un autre item +``` ou +```md + Item + Item + Encore un item +``` ou +```md - Item - Item - Un dernier item +``` -<!-- les Listes Ordonnées sont générées via un nombre suivi d'un point --> +Les listes ordonnées sont générées via un nombre suivi d'un point. +```md 1. Item un 2. Item deux 3. Item trois +``` -<!-- Vous pouvez même vous passer de tout numéroter, et Markdown générera -les bons chiffres. Ceci dit, cette variante perd en clarté.--> +Vous pouvez même vous passer de tout numéroter, et Markdown générera les bons +chiffres. Ceci dit, cette variante perd en clarté. +```md 1. Item un 1. Item deux 1. Item trois -<!-- ( cette liste sera interprétée de la même façon que celle au dessus ) --> +``` -<!-- Vous pouvez également utiliser des sous-listes --> +(Cette liste sera interprétée de la même façon que celle au dessus) +Vous pouvez également utiliser des sous-listes. + +```md 1. Item un 2. Item deux 3. Item trois * Sub-item * Sub-item 4. Item quatre +``` -<!-- Il y a même des "listes de Taches". Elles génèrent des champs HTML -de type checkbox. --> - -Les [ ] ci dessous, n'ayant pas de [ x ], -deviendront des cases à cocher HTML non-cochées. +Il y a même des listes de taches. Elles génèrent des champs HTML de type case à +cocher. +```md +Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML +non-cochées. - [ ] Première tache à réaliser. - [ ] Une autre chose à faire. La case suivante sera une case à cocher HTML cochée. - [x] Ça ... c'est fait! +``` + +## Blocs de code -<!-- les Blocs de Code --> -<!-- Pour marquer du texte comme étant du code, il suffit de commencer -chaque ligne en tapant 4 espaces (ou un Tab) --> +Pour marquer du texte comme étant du code (qui utilise la balise `<code>`), il +suffit d'indenter chaque ligne avec 4 espaces ou une tabulation. +```md echo "Ça, c'est du Code!"; var Ça = "aussi !"; +``` -<!-- L'indentation par tab ou série de quatre espaces -fonctionne aussi à l'intérieur du bloc de code --> +L'indentation par tabulation (ou série de quatre espaces) fonctionne aussi à +l'intérieur du bloc de code. +```md my_array.each do |item| puts item end +``` -<!-- Des bouts de code en mode 'inline' s'ajoutent en les entourant de ` --> +Des bouts de code en mode en ligne s'ajoutent en utilisant le caractères +`` ` ``. +```md La fonction `run()` ne vous oblige pas à aller courir! +``` -<!-- Via GitHub Flavored Markdown, vous pouvez utiliser -des syntaxes spécifiques --> +En "GitHub Flavored Markdown", vous pouvez utiliser des syntaxes spécifiques +selon le language. -\`\`\`ruby -<!-- mais enlevez les backslashes quand vous faites ça, -gardez juste ```ruby ( ou nom de la syntaxe correspondant à votre code )--> +<pre> +<code class="highlight">```ruby def foobar -puts "Hello world!" + puts "Hello world!" end -\`\`\` <!-- pareil, pas de backslashes, juste ``` en guise de fin --> +```</code> +</pre> -<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub -va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> +Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub va +utiliser une coloration syntaxique pour le langage indiqué après les \`\`\`. -<!-- Ligne Horizontale (<hr />) --> -<!-- Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets, -avec ou sans espaces entre chaque un. --> +## Séparateur horizontal +La balise `<hr/>` peut être aisement ajoutée en utilisant trois ou plus +astérisques ou tirets, avec ou sans espaces entre chacun. + +```md *** --- - - - **************** +``` -<!-- Liens --> -<!-- Une des fonctionnalités sympathiques du Markdown est la facilité -d'ajouter des liens. Le texte du lien entre [ ], l'url entre ( ), -et voilà l'travail. ---> +## Liens hypertextes +Une des fonctionnalités sympathiques du Markdown est la facilité d'ajouter des +liens hypertextes. Le texte du lien entre crochet `` [] ``, l'url entre +parenthèses `` () ``, et voilà le travail. + +```md [Clic moi!](http://test.com/) +``` -<!-- -Pour ajouter un attribut Title, collez le entre guillemets, avec le lien. ---> +Pour ajouter un attribut titre, ajoutez le entre les parenthèses entre +guillemets apres le lien. +```md [Clic moi!](http://test.com/ "Lien vers Test.com") +``` -<!-- les Liens Relatifs marchent aussi --> +Markdown supporte aussi les liens relatifs. +```md [En avant la musique](/music/). +``` -<!-- Les liens façon "références" sont eux aussi disponibles en Markdown --> +Les liens de références sont eux aussi disponibles en Markdown. +```md [Cliquez ici][link1] pour plus d'information! [Regardez aussi par ici][foobar] si vous voulez. [link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "Alright!" +[foobar]: http://foobar.biz/ "Génial!" +``` -<!-- Le titre peut aussi être entouré de guillemets simples, -entre parenthèses ou absent. Les références peuvent être placées -un peu où vous voulez dans le document, et les identifiants -(link1, foobar, ...) quoi que ce soit tant qu'ils sont uniques --> +Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou +absent. Les références peuvent être placées où vous voulez dans le document et +les identifiants peuvent être n'importe quoi tant qu'ils sont uniques. -<!-- Il y a également le "nommage implicite" qui transforme le texte du lien - en identifiant --> +Il y a également le nommage implicite qui transforme le texte du lien en +identifiant. +```md [Ceci][] est un lien. [ceci]: http://ceciestunlien.com/ +``` + +Mais ce n'est pas beaucoup utilisé. -<!-- mais ce n'est pas beaucoup utilisé. --> +## Images -<!-- Images --> -<!-- Pour les images, la syntaxe est identique aux liens, sauf que précédée - d'un point d'exclamation! --> +Pour les images, la syntaxe est identique à celle des liens, sauf que précédée +d'un point d'exclamation! +```md ![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") +``` -<!-- Là aussi, on peut utiliser le mode "références" --> +Là aussi, on peut utiliser les références. +```md ![Ceci est l'attribut ALT de l'image][monimage] [monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." +``` + +## Divers -<!-- Divers --> -<!-- Liens Automatiques --> +### Liens hypertextes automatiques +```md <http://testwebsite.com/> est équivalent à : [http://testwebsite.com/](http://testwebsite.com/) +``` -<!-- Liens Automatiques pour emails --> +### Liens hypertextes automatiques pour emails +```md <foo@bar.com> +``` + +### Caracteres d'echappement -<!-- Escaping --> Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ -Pour taper *ce texte* entouré d'astérisques mais pas en italique : +```md +Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. +``` + +### Touches de clavier -<!-- Tableaux --> -<!-- les Tableaux ne sont disponibles que dans le GitHub Flavored Markdown - et c'est ce n'est pas super agréable d'utilisation. - Mais si vous en avez besoin : - --> +Avec le "Github Flavored Markdown", vous pouvez utiliser la balise `<kdb>` +pour représenter une touche du clavier. +```md +Ton ordinateur a planté? Essayer de taper : +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> +``` + +### Tableaux + +Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et +ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin : + +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Alignement Gauche | Centé | Alignement Droite | | bla | bla | bla | +``` -<!-- ou bien, pour un résultat équivalent : --> +ou bien, pour un résultat équivalent : +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ough que c'est moche | svp | arrêtez - -<!-- Fin! --> - ``` -Pour plus d'information : - consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. +Pour plus d'information, consultez le post officiel de Jhon Gruber à propos de +la syntaxe [ici](http://daringfireball.net/projects/markdown/syntax) et la +superbe fiche pense-bête de Adam Pritchard [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/git.html.markdown b/git.html.markdown index 582f8863..aa96c90a 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -26,11 +26,11 @@ Version control is a system that records changes to a file(s), over time. ### Centralized Versioning vs. Distributed Versioning -* Centralized version control focuses on synchronizing, tracking, and backing +* Centralized version control focuses on synchronizing, tracking, and backing up files. -* Distributed version control focuses on sharing changes. Every change has a +* Distributed version control focuses on sharing changes. Every change has a unique id. -* Distributed systems have no defined structure. You could easily have a SVN +* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git. [Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -57,7 +57,7 @@ A git repository is comprised of the .git directory & working tree. ### .git Directory (component of repository) -The .git directory contains all the configurations, logs, branches, HEAD, and +The .git directory contains all the configurations, logs, branches, HEAD, and more. [Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) @@ -68,15 +68,15 @@ 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 +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. ### 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 +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 @@ -91,13 +91,13 @@ functionality to mark release points (v1.0, and so on) ### HEAD and head (component of .git dir) -HEAD is a pointer that points to the current branch. A repository only has 1 -*active* HEAD. -head is a pointer that points to any commit. A repository can have any number +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 -* Modified - Changes have been made to a file but file has not been committed +* 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 @@ -111,7 +111,7 @@ to Git Database yet ### init -Create an empty Git repository. The Git repository's settings, stored +Create an empty Git repository. The Git repository's settings, stored information, and more is stored in a directory (a folder) named ".git". ```bash @@ -179,7 +179,7 @@ $ git help status ### add -To add files to the staging area/index. If you do not `git add` new files to +To add files to the staging area/index. If you do not `git add` new files to the staging area/index, they will not be included in commits! ```bash @@ -201,7 +201,7 @@ working directory/repo. ### branch -Manage your branches. You can view, edit, create, delete branches using this +Manage your branches. You can view, edit, create, delete branches using this command. ```bash @@ -250,7 +250,7 @@ $ git push origin --tags ### checkout -Updates all files in the working tree to match the version in the index, or +Updates all files in the working tree to match the version in the index, or specified tree. ```bash @@ -269,7 +269,7 @@ $ git checkout -b newBranch ### clone Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you +remote-tracking branches for each branch in the cloned repo, which allows you to push to a remote branch. ```bash @@ -285,7 +285,7 @@ $ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git - ### commit -Stores the current contents of the index in a new "commit." This commit +Stores the current contents of the index in a new "commit." This commit contains the changes made and a message created by the user. ```bash @@ -401,11 +401,11 @@ Pulls from a repository and merges it with another branch. $ git pull origin master # By default, git pull will update your current branch -# by merging in new changes from its remote-tracking branch +# by merging in new changes from its remote-tracking branch $ git pull # Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git fetch <remote> <branch>, git +# branch commits onto your local repo, like: "git fetch <remote> <branch>, git # rebase <remote>/<branch>" $ git pull origin master --rebase ``` @@ -421,7 +421,7 @@ Push and merge changes from a branch to a remote & branch. $ git push origin master # By default, git push will push and merge changes from -# the current branch to its remote-tracking branch +# the current branch to its remote-tracking branch $ git push # To link up current local branch with a remote branch, add -u flag: @@ -432,7 +432,7 @@ $ git push ### stash -Stashing takes the dirty state of your working directory and saves it on a +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 @@ -464,7 +464,7 @@ nothing to commit, working directory clean ``` You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top. ```bash @@ -495,7 +495,7 @@ Now you're ready to get back to work on your stuff! ### rebase (caution) -Take all changes that were committed on one branch, and replay them onto +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*. @@ -510,7 +510,7 @@ $ git rebase master experimentBranch ### reset (caution) Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you +pulls, commits, adds, and more. It's a great command but also dangerous if you don't know what you are doing. ```bash @@ -535,7 +535,7 @@ $ git reset --hard 31f2bb1 Reflog will list most of the git commands you have done for a given time period, default 90 days. -This give you the chance to reverse any git commands that have gone wrong +This give you the chance to reverse any git commands that have gone wrong (for instance, if a rebase has broken your application). You can do this: @@ -558,8 +558,8 @@ ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) ### revert -Revert can be used to undo a commit. It should not be confused with reset which -restores the state of a project to a previous point. Revert will add a new +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new commit which is the inverse of the specified commit, thus reverting it. ```bash @@ -604,3 +604,5 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Pro Git](http://www.git-scm.com/book/en/v2) * [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + +* [The New Boston tutorial to Git covering basic commands and workflow](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx) diff --git a/go.html.markdown b/go.html.markdown index df677894..ae99535b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -277,7 +277,8 @@ func sentenceFactory(mystring string) func(before, after string) string { } func learnDefer() (ok bool) { - // Deferred statements are executed just before the function returns. + // A defer statement pushes a function call onto a list. The list of saved + // calls is executed AFTER the surrounding function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // Defer is commonly used to close a file, so the function closing the diff --git a/hre.csv b/hre.csv new file mode 100644 index 00000000..eab43cc4 --- /dev/null +++ b/hre.csv @@ -0,0 +1 @@ +Ix,Dynasty,Name,Birth,Death,Coronation 1,Coronation 2,Ceased to be Emperor
N/A,Carolingian,Charles I,2 April 742,28 January 814,25 December 800,N/A,28 January 814
N/A,Carolingian,Louis I,778,20 June 840,11 September 813,5 October 816,20 June 840
N/A,Carolingian,Lothair I,795,29 September 855,5 April 823,N/A,29 September 855
N/A,Carolingian,Louis II,825,12 August 875,15 June 844,18 May 872,12 August 875
N/A,Carolingian,Charles II,13 June 823,6 October 877,29 December 875,N/A,6 October 877
N/A,Carolingian,Charles III,13 June 839,13 January 888,12 February 881,N/A,11 November 887
N/A,Widonid,Guy III,835,12 December 894,21 February 891,N/A,12 December 894
N/A,Widonid,Lambert I,880,15 October 898,30 April 892,N/A,15 October 898
N/A,Carolingian,Arnulph,850,8 December 899,22 February 896,N/A,8 December 899
N/A,Bosonid,Louis III,880,5 June 928,22 February 901,N/A,21 July 905
N/A,Unruoching,Berengar I,845,7 April 924,December 915,N/A,7 April 924
1,Ottonian,Otto I,23 November 912,7 May 973,2 February 962,N/A,7 May 973
2,Ottonian,Otto II,955,7 December 983,25 December 967,N/A,7 December 983
3,Ottonian,Otto III,980,23 January 1002,21 May 996,N/A,23 January 1002
4,Ottonian,Henry II,6 May 973,13 July 1024,14 February 1014,N/A,13 July 1024
5,Salian,Conrad II,990,4 June 1039,26 March 1027,N/A,4 June 1039
6,Salian,Henry III,29 October 1017,5 October 1056,25 December 1046,N/A,5 October 1056
7,Salian,Henry IV,11 November 1050,7 August 1106,31 March 1084,N/A,December 1105
8,Salian,Henry V,8 November 1086,23 May 1125,13 April 1111,N/A,23 May 1125
9,Supplinburg,Lothair III,9 June 1075,4 December 1137,4 June 1133,N/A,4 December 1137
10,Staufen,Frederick I,1122,10 June 1190,18 June 1155,N/A,10 June 1190
11,Staufen,Henry VI,November 1165,28 September 1197,14 April 1191,N/A,28 September 1197
12,Welf,Otto IV,1175,19 May 1218,4 October 1209,N/A,1215
13,Staufen,Frederick II,26 December 1194,13 December 1250,22 November 1220,N/A,13 December 1250
14,Luxembourg,Henry VII,1275,24 August 1313,29 June 1312,N/A,24 August 1313
15,Wittelsbach,Louis IV,1 April 1282,11 October 1347,17 January 1328,N/A,11 October 1347
16,Luxembourg,Charles IV,14 May 1316,29 November 1378,5 April 1355,N/A,29 November 1378
17,Luxembourg,Sigismund,14 February 1368,9 December 1437,31 May 1433,N/A,9 December 1437
18,Habsburg,Frederick III,21 September 1415,19 August 1493,19 March 1452,N/A,19 August 1493
19,Habsburg,Maximilian I,22 March 1459,12 January 1519,N/A,N/A,12 January 1519
20,Habsburg,Charles V,24 February 1500,21 September 1558,February 1530,N/A,16 January 1556
21,Habsburg,Ferdinand I,10 March 1503,25 July 1564,N/A,N/A,25 July 1564
22,Habsburg,Maximilian II,31 July 1527,12 October 1576,N/A,N/A,12 October 1576
23,Habsburg,Rudolph II,18 July 1552,20 January 1612,30 June 1575,N/A,20 January 1612
24,Habsburg,Matthias,24 February 1557,20 March 1619,23 January 1612,N/A,20 March 1619
25,Habsburg,Ferdinand II,9 July 1578,15 February 1637,10 March 1619,N/A,15 February 1637
26,Habsburg,Ferdinand III,13 July 1608,2 April 1657,18 November 1637,N/A,2 April 1657
27,Habsburg,Leopold I,9 June 1640,5 May 1705,6 March 1657,N/A,5 May 1705
28,Habsburg,Joseph I,26 July 1678,17 April 1711,1 May 1705,N/A,17 April 1711
29,Habsburg,Charles VI,1 October 1685,20 October 1740,22 December 1711,N/A,20 October 1740
30,Wittelsbach,Charles VII,6 August 1697,20 January 1745,12 February 1742,N/A,20 January 1745
31,Lorraine,Francis I,8 December 1708,18 August 1765,N/A,N/A,18 August 1765
32,Habsburg-Lorraine,Joseph II,13 March 1741,20 February 1790,19 August 1765,N/A,20 February 1790
33,Habsburg-Lorraine,Leopold II,5 May 1747,1 March 1792,N/A,N/A,1 March 1792
34,Habsburg-Lorraine,Francis II,12 February 1768,2 March 1835,4 March 1792,N/A,6 August 1806
\ No newline at end of file diff --git a/it-it/asciidoc-it.html.markdown b/it-it/asciidoc-it.html.markdown new file mode 100644 index 00000000..47a57349 --- /dev/null +++ b/it-it/asciidoc-it.html.markdown @@ -0,0 +1,135 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/"] + - ["Abel Salgado Romero", "https://twitter.com/abelsromero"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +filename: asciidoc-it.md +--- + +AsciiDoc è un linguaggio di markup simile a Markdown e può essere usato per qualsiasi cosa, dai libri ai blog. Creato nel 2002 da Stuart Rackman, questo linguaggio è semplice ma permette un buon numero di personalizzazioni. + +Intestazione Documento + +Le intestazioni sono opzionali e possono contenere linee vuote. Deve avere almeno una linea vuota rispetto al contenuto. + +Solo titolo + +``` += Titolo documento + +Prima frase del documento. +``` + +Titolo ed Autore + +``` += Titolo documento +Primo Ultimo <first.last@learnxinyminutes.com> + +Inizio del documento +``` + +Autori multipli + +``` += Titolo Documento +John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com> + +Inizio di un documento con autori multipli. +``` + +Linea di revisione (richiede una linea autore) + +``` += Titolo documento V1 +Potato Man <chip@crunchy.com> +v1.0, 2016-01-13 + +Questo articolo sulle patatine sarà divertente. +``` + +Paragrafi + +``` +Non hai bisogno di nulla di speciale per i paragrafi. + +Aggiungi una riga vuota tra i paragrafi per separarli. + +Per creare una riga vuota aggiungi un + +e riceverai una interruzione di linea! +``` + +Formattazione Testo + +``` +_underscore crea corsivo_ +*asterischi per il grassetto* +*_combinali per maggiore divertimento_* +`usa i ticks per indicare il monospazio` +`*spaziatura fissa in grassetto*` +``` + +Titoli di sezione + +``` += Livello 0 (può essere utilizzato solo nell'intestazione del documento) + +== Livello 1 <h2> + +=== Livello 2 <h3> + +==== Livello 3 <h4> + +===== Livello 4 <h5> + +``` + +Liste + +Per creare un elenco puntato, utilizzare gli asterischi. + +``` +* foo +* bar +* baz +``` + +Per creare un elenco numerato usa i periodi. + +``` +. item 1 +. item 2 +. item 3 +``` + +È possibile nidificare elenchi aggiungendo asterischi o periodi aggiuntivi fino a cinque volte. + +``` +* foo 1 +** foo 2 +*** foo 3 +**** foo 4 +***** foo 5 + +. foo 1 +.. foo 2 +... foo 3 +.... foo 4 +..... foo 5 +``` + +## Ulteriori letture + +Esistono due strumenti per elaborare i documenti AsciiDoc: + +1. [AsciiDoc](http://asciidoc.org/): implementazione Python originale, disponibile nelle principali distribuzioni Linux. Stabile e attualmente in modalità di manutenzione. +2. [Asciidoctor](http://asciidoctor.org/): implementazione alternativa di Ruby, utilizzabile anche da Java e JavaScript. In fase di sviluppo attivo, mira ad estendere la sintassi AsciiDoc con nuove funzionalità e formati di output. + +I seguenti collegamenti sono relativi all'implementazione di `Asciidoctor`: + +* [Markdown - AsciiDoc comparazione sintassi](http://asciidoctor.org/docs/user-manual/#comparison-by-example): confronto affiancato di elementi di Markdown e AsciiDoc comuni. +* [Per iniziare](http://asciidoctor.org/docs/#get-started-with-asciidoctor): installazione e guide rapide per il rendering di documenti semplici. +* [Asciidoctor Manuale Utente](http://asciidoctor.org/docs/user-manual/): manuale completo con riferimento alla sintassi, esempi, strumenti di rendering, tra gli altri. diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index b4f9c50e..449aebfb 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -1130,7 +1130,6 @@ compl 4 // Effettua il NOT bit-a-bit ``` Letture consigliate: -Un riferimento aggiornato del linguaggio può essere trovato qui -<http://cppreference.com/w/cpp> - -Risorse addizionali possono essere trovate qui <http://cplusplus.com> +* Un riferimento aggiornato del linguaggio può essere trovato qui [CPP Reference](http://cppreference.com/w/cpp). +* Risorse addizionali possono essere trovate qui [CPlusPlus](http://cplusplus.com). +* Un tutorial che copre le basi del linguaggio e l'impostazione dell'ambiente di codifica è disponibile su [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/it-it/dynamic-programming-it.html.markdown b/it-it/dynamic-programming-it.html.markdown new file mode 100644 index 00000000..9c7bd9b6 --- /dev/null +++ b/it-it/dynamic-programming-it.html.markdown @@ -0,0 +1,55 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +# Programmazione dinamica + +## Introduzione + +La programmazione dinamica è una tecnica potente utilizzata per risolvere una particolare classe di problemi, come vedremo. L'idea è molto semplice, se hai risolto un problema con l'input dato, salva il risultato come riferimento futuro, in modo da evitare di risolvere nuovamente lo stesso problema. + +Ricordate sempre! +"Chi non ricorda il passato è condannato a ripeterlo" + +## Modi per risolvere questi problemi + +1. *Top-Down* : Inizia a risolvere il problema specifico suddividendolo. Se vedi che il problema è già stato risolto, rispondi semplicemente con la risposta già salvata. Se non è stato risolto, risolvilo e salva la risposta. Di solito è facile da pensare e molto intuitivo. Questo è indicato come Memoization. + +2. *Bottom-Up* : Analizza il problema e vedi l'ordine in cui i sotto-problemi sono risolti e inizia a risolvere dal sottoproblema banale, verso il problema dato. In questo processo, è garantito che i sottoproblemi vengono risolti prima di risolvere il problema. Si parla di programmazione dinamica. + +## Esempio di programmazione dinamica + +Il problema di "Longest Increasing Subsequence" consiste nel trovare la sottosequenza crescente più lunga di una determinata sequenza. Data una sequenza `S= {a1 , a2 , a3, a4, ............., an-1, an }` dobbiamo trovare il sottoinsieme più lungo tale che per tutti gli `j` e gli `i`, `j<i` nel sotto-insieme `aj<ai`. +Prima di tutto dobbiamo trovare il valore delle sottosequenze più lunghe (LSi) ad ogni indice i con l'ultimo elemento della sequenza che è ai. Quindi il più grande LSi sarebbe la sottosequenza più lunga nella sequenza data. Per iniziare LSi viene inizializzato ad 1, dato che ai è un element della sequenza (Ultimo elemento). Quindi per tutti gli `j` tale che `j<i` e `aj<ai`, troviamo il più grande LSj e lo aggiungiamo a LSi. Quindi l'algoritmo richiede un tempo di *O(n2)*. + +Pseudo-codice per trovare la lunghezza della sottosequenza crescente più lunga: +Questa complessità degli algoritmi potrebbe essere ridotta usando una migliore struttura dei dati piuttosto che una matrice. La memorizzazione dell'array predecessore e della variabile come `largest_sequences_so_far` e il suo indice farebbero risparmiare molto tempo. + +Un concetto simile potrebbe essere applicato nel trovare il percorso più lungo nel grafico aciclico diretto. + +```python +for i=0 to n-1 + LS[i]=1 + for j=0 to i-1 + if (a[i] > a[j] and LS[i]<LS[j]) + LS[i] = LS[j]+1 +for i=0 to n-1 + if (largest < LS[i]) +``` + +### Alcuni famosi problemi DP + +- Floyd Warshall Algorithm - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() + + +## Risorse online + +* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index e49ccd79..797f6b0b 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -270,12 +270,13 @@ func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { } func imparaDefer() (ok bool) { - // Le istruzioni dette "deferred" (rinviate) sono eseguite - // appena prima che la funzione abbia termine. + // La parola chiave "defer" inserisce una funzione in una lista. + // La lista contenente tutte le chiamate a funzione viene eseguita DOPO + // il return finale della funzione che le circonda. defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") defer fmt.Println("\nQuesta riga viene stampata per prima perché") // defer viene usato di solito per chiudere un file, così la funzione che - // chiude il file viene messa vicino a quella che lo apre. + // chiude il file, preceduta da "defer", viene messa vicino a quella che lo apre. return true } diff --git a/it-it/html-it.html.markdown b/it-it/html-it.html.markdown index 471019a1..8f7391a2 100644 --- a/it-it/html-it.html.markdown +++ b/it-it/html-it.html.markdown @@ -1,6 +1,6 @@ --- language: html -filename: learnhtml-it.html +filename: learnhtml-it.txt contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: @@ -112,7 +112,7 @@ Questo articolo riguarda principalmente la sintassi HTML ed alcuni suggerimenti ## Uso -HTML è scritto in files che finiscono con `.html`. +HTML è scritto in files che finiscono con `.html` o `.htm`. Il "MIME type" è `text/html`. ## Per saperne di più diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 54602cff..1669816e 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -17,14 +17,14 @@ concorrente, basato su classi e adatto a svariati scopi. ```java // I commenti su singola linea incominciano con // /* -I commenti su piu' linee invece sono cosi' +I commenti su più linee invece sono così */ /** -I commenti per la documentazione JavaDoc si fanno cosi'. +I commenti per la documentazione JavaDoc si fanno così. Vengono usati per descrivere una classe o alcuni suoi attributi. */ -// Per importare la classe ArrayList conenuta nel package java.util +// Per importare la classe ArrayList contenuta nel package java.util import java.util.ArrayList; // Per importare tutte le classi contenute nel package java.security import java.security.*; @@ -48,7 +48,7 @@ public class LearnJava { System.out.print("Ciao "); System.out.print("Mondo "); - // Per stampare del testo formattato, si puo' usare System.out.printf + // Per stampare del testo formattato, si può usare System.out.printf System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159 /////////////////////////////////////// @@ -60,7 +60,7 @@ public class LearnJava { */ // Per dichiarare una variabile basta fare <tipoDato> <nomeVariabile> int fooInt; - // Per dichiarare piu' di una variabile dello lo stesso tipo si usa: + // Per dichiarare più di una variabile dello lo stesso tipo si usa: // <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> int fooInt1, fooInt2, fooInt3; @@ -71,7 +71,7 @@ public class LearnJava { // Per inizializzare una variabile si usa // <tipoDato> <nomeVariabile> = <valore> int fooInt = 1; - // Per inizializzare piu' di una variabile dello lo stesso tipo + // Per inizializzare più di una variabile dello lo stesso tipo // si usa <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore> int fooInt1, fooInt2, fooInt3; fooInt1 = fooInt2 = fooInt3 = 1; @@ -94,7 +94,7 @@ public class LearnJava { // Long - intero con segno a 64 bit (in complemento a 2) // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; - // L viene usato per indicare che il valore e' di tipo Long; + // L viene usato per indicare che il valore è di tipo Long; // altrimenti il valore viene considerato come intero. // Nota: Java non dispone di interi senza segno. @@ -102,14 +102,14 @@ public class LearnJava { // Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754) // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f o F indicano the la variabile e' di tipo float; + // f o F indicano the la variabile è di tipo float; // altrimenti il valore viene considerato come double. // Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754) // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; - // Boolean - Puo' assumere il valore vero (true) o falso (false) + // Boolean - Può assumere il valore vero (true) o falso (false) boolean fooBoolean = true; boolean barBoolean = false; @@ -118,26 +118,26 @@ public class LearnJava { // Le variabili precedute da final possono essere inizializzate una volta sola, final int HOURS_I_WORK_PER_WEEK = 9001; - // pero' e' possibile dichiararle e poi inizializzarle in un secondo momento. + // però è possibile dichiararle e poi inizializzarle in un secondo momento. final double E; E = 2.71828; // BigInteger - Interi a precisione arbitraria // - // BigInteger e' un tipo di dato che permette ai programmatori di - // gestire interi piu' grandi di 64 bit. Internamente, le variabili + // BigInteger è un tipo di dato che permette ai programmatori di + // gestire interi più grandi di 64 bit. Internamente, le variabili // di tipo BigInteger vengono memorizzate come un vettore di byte e // vengono manipolate usando funzioni dentro la classe BigInteger. // - // Una variabile di tipo BigInteger puo' essere inizializzata usando + // Una variabile di tipo BigInteger può essere inizializzata usando // un array di byte oppure una stringa. BigInteger fooBigInteger = new BigDecimal(fooByteArray); // BigDecimal - Numero con segno, immutabile, a precisione arbitraria // - // Una variabile di tipo BigDecimal e' composta da due parti: un intero + // Una variabile di tipo BigDecimal è composta da due parti: un intero // a precisione arbitraria detto 'non scalato', e un intero a 32 bit // che rappresenta la 'scala', ovvero la potenza di 10 con cui // moltiplicare l'intero non scalato. @@ -158,9 +158,9 @@ public class LearnJava { // Stringhe String fooString = "Questa e' la mia stringa!"; - // \n e' un carattere di escape che rappresenta l'andare a capo + // \n è un carattere di escape che rappresenta l'andare a capo String barString = "Stampare su una nuova riga?\nNessun problema!"; - // \t e' un carattere di escape che aggiunge un tab + // \t è un carattere di escape che aggiunge un tab String bazString = "Vuoi aggiungere un tab?\tNessun problema!"; System.out.println(fooString); System.out.println(barString); @@ -168,7 +168,7 @@ public class LearnJava { // Vettori // La dimensione di un array deve essere decisa in fase di - // istanziazione. Per dichiarare un array si puo' fare in due modi: + // istanziazione. Per dichiarare un array si può fare in due modi: // <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>]; // <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>]; int[] intArray = new int[10]; @@ -189,8 +189,8 @@ public class LearnJava { System.out.println("intArray @ 1: " + intArray[1]); // => 1 // Ci sono altri tipo di dato interessanti. - // ArrayList - Simili ai vettori, pero' offrono altre funzionalita', - // e la loro dimensione puo' essere modificata. + // ArrayList - Simili ai vettori, però offrono altre funzionalità, + // e la loro dimensione può essere modificata. // LinkedList - Si tratta di una lista linkata doppia, e come tale // implementa tutte le operazioni del caso. // Map - Un insieme di oggetti che fa corrispondere delle chiavi @@ -207,7 +207,7 @@ public class LearnJava { int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea - // L'aritmetica e' lineare. + // L'aritmetica è lineare. System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 @@ -253,7 +253,7 @@ public class LearnJava { /////////////////////////////////////// System.out.println("\n->Strutture di controllo"); - // La dichiarazione dell'If e'' C-like. + // La dichiarazione dell'If è C-like. int j = 10; if (j == 10){ System.out.println("Io vengo stampato"); @@ -328,18 +328,18 @@ public class LearnJava { System.out.println("Risultato del costrutto switch: " + stringaMese); // Condizioni brevi - // Si puo' usare l'operatore '?' per un rapido assegnamento + // Si può usare l'operatore '?' per un rapido assegnamento // o per operazioni logiche. // Si legge: - // Se (condizione) e' vera, usa <primo valore>, altrimenti usa <secondo valore> + // Se (condizione) è vera, usa <primo valore>, altrimenti usa <secondo valore> int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println("Se la condizione e' vera stampa A: "+bar); - // Stampa A, perche' la condizione e' vera. + // Stampa A, perché la condizione è vera. ///////////////////////////////////////// - // Convertire i tipi di tati e Typcasting + // Convertire i tipi di dati e Typecasting ///////////////////////////////////////// // Convertire tipi di dati @@ -397,16 +397,16 @@ class Bicicletta { // Variabili della bicicletta public int cadenza; - // Public: Puo' essere richiamato da qualsiasi classe + // Public: Può essere richiamato da qualsiasi classe private int velocita; - // Private: e'' accessibile solo dalla classe dove e'' stato inizializzato + // Private: è accessibile solo dalla classe dove è stato inizializzato protected int ingranaggi; - // Protected: e'' visto sia dalla classe che dalle sottoclassi + // Protected: è visto sia dalla classe che dalle sottoclassi String nome; - // default: e'' accessibile sono all'interno dello stesso package + // default: è accessibile sono all'interno dello stesso package // I costruttori vengono usati per creare variabili - // Questo e'' un costruttore + // Questo è un costruttore public Bicicletta() { ingranaggi = 1; cadenza = 50; @@ -414,7 +414,7 @@ class Bicicletta { nome = "Bontrager"; } - // Questo e'' un costruttore che richiede parametri + // Questo è un costruttore che richiede parametri public Bicicletta(int cadenza, int velocita, int ingranaggi, String nome) { this.ingranaggi = ingranaggi; this.cadenza = cadenza; @@ -469,7 +469,7 @@ class Bicicletta { } } // Fine classe bicicletta -// PennyFarthing e'' una sottoclasse della bicicletta +// PennyFarthing è una sottoclasse della bicicletta class PennyFarthing extends Bicicletta { // (Sono quelle biciclette con un unica ruota enorme // Non hanno ingranaggi.) @@ -481,7 +481,7 @@ class PennyFarthing extends Bicicletta { // Bisogna contrassegnre un medodo che si sta riscrivendo // con una @annotazione - // Per saperne di piu' sulle annotazioni + // Per saperne di più sulle annotazioni // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setIngranaggi(int ingranaggi) { @@ -518,8 +518,8 @@ class Frutta implements Commestibile, Digestibile { } } -//In Java si puo' estendere solo una classe, ma si possono implementare -//piu' interfaccie, per esempio: +//In Java si può estendere solo una classe, ma si possono implementare +//più interfaccie, per esempio: class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { public void MetodoPrimaInterfaccia() { diff --git a/it-it/jquery-it.html.markdown b/it-it/jquery-it.html.markdown new file mode 100644 index 00000000..811c5c3a --- /dev/null +++ b/it-it/jquery-it.html.markdown @@ -0,0 +1,131 @@ +--- +category: tool +tool: jquery +contributors: + - ["Sawyer Charles", "https://github.com/xssc"] +filename: jquery-it.js +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +jQuery è una libreria JavaScript che ti aiuta a "fare di più, scrivendo meno". Rende molte attività comuni di JavaScript più facili da scrivere. jQuery è utilizzato da molte grandi aziende e sviluppatori in tutto il mondo. Rende AJAX, gestione degli eventi, manipolazione dei documenti e molto altro, più facile e veloce. + +Visto che jQuery è una libreria JavaScript dovresti prima [imparare JavaScript](https://learnxinyminutes.com/docs/javascript/) + +```js + + +/////////////////////////////////// +// 1. Selettori + +// I selettori in jQuery vengono utilizzati per selezionare un elemento +var page = $(window); // Seleziona l'intera finestra + +// I selettori possono anche essere selettori CSS +var paragraph = $('p'); // Seleziona tutti gli elementi del paragrafo +var table1 = $('#table1'); // Seleziona elemento con id 'table1' +var squares = $('.square'); // Seleziona tutti gli elementi con la classe 'square' +var square_p = $('p.square') // Seleziona i paragrafi con la classe 'square' + + +/////////////////////////////////// +// 2. Eventi ed effetti +// jQuery è molto bravo a gestire ciò che accade quando un evento viene attivato +// Un evento molto comune è l'evento "pronto" sul documento +// Puoi usare il metodo 'ready' per aspettare che l'elemento abbia finito di caricare +$(document).ready(function(){ + // Il codice non verrà eseguito fino a quando il documento non verrà caricato +}); +// Puoi anche usare funzioni definite +function onAction() { + // Questo viene eseguito quando l'evento viene attivato +} +$('#btn').click(onAction); // Invoca onAction al click + +// Alcuni altri eventi comuni sono: +$('#btn').dblclick(onAction); // Doppio click +$('#btn').hover(onAction); // Al passaggio del mouse +$('#btn').focus(onAction); // Al focus +$('#btn').blur(onAction); // Focus perso +$('#btn').submit(onAction); // Al submit +$('#btn').select(onAction); // Quando un elemento è selezionato +$('#btn').keydown(onAction); // Quando un tasto è premuto (ma non rilasciato) +$('#btn').keyup(onAction); // Quando viene rilasciato un tasto +$('#btn').keypress(onAction); // Quando viene premuto un tasto +$('#btn').mousemove(onAction); // Quando il mouse viene spostato +$('#btn').mouseenter(onAction); // Il mouse entra nell'elemento +$('#btn').mouseleave(onAction); // Il mouse lascia l'elemento + + +// Questi possono anche innescare l'evento invece di gestirlo +// semplicemente non passando alcun parametro +$('#btn').dblclick(); // Innesca il doppio click sull'elemento + +// Puoi gestire più eventi mentre usi il selettore solo una volta +$('#btn').on( + {dblclick: myFunction1} // Attivato con doppio clic + {blur: myFunction1} // Attivato al blur +); + +// Puoi spostare e nascondere elementi con alcuni metodi di effetto +$('.table').hide(); // Nascondi gli elementi + +// Nota: chiamare una funzione in questi metodi nasconderà comunque l'elemento +$('.table').hide(function(){ + // Elemento nascosto quindi funzione eseguita +}); + +// È possibile memorizzare selettori in variabili +var tables = $('.table'); + +// Alcuni metodi di manipolazione dei documenti di base sono: +tables.hide(); // Nascondi elementi +tables.show(); // Mostra elementi +tables.toggle(); // Cambia lo stato nascondi/mostra +tables.fadeOut(); // Fades out +tables.fadeIn(); // Fades in +tables.fadeToggle(); // Fades in o out +tables.fadeTo(0.5); // Dissolve in opacità (tra 0 e 1) +tables.slideUp(); // Scorre verso l'alto +tables.slideDown(); // Scorre verso il basso +tables.slideToggle(); // Scorre su o giù + +// Tutti i precedenti prendono una velocità (millisecondi) e la funzione di callback +tables.hide(1000, myFunction); // nasconde l'animazione per 1 secondo quindi esegue la funzione + +// fadeTo ha un'opacità richiesta come secondo parametro +tables.fadeTo(2000, 0.1, myFunction); // esegue in 2 sec. il fade sino ad una opacità di 0.1 opacity e poi la funzione + +// Puoi ottenere un effetti più avanzati con il metodo animate +tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction); +// Il metodo animate accetta un oggetto di css e valori con cui terminare, +// parametri opzionali per affinare l'animazione, +// e naturalmente la funzione di callback + +/////////////////////////////////// +// 3. Manipolazione + +// Questi sono simili agli effetti ma possono fare di più +$('div').addClass('taming-slim-20'); // Aggiunge la classe taming-slim-20 a tutti i div + +// Metodi di manipolazione comuni +$('p').append('Hello world'); // Aggiunge alla fine dell'elemento +$('p').attr('class'); // Ottiene l'attributo +$('p').attr('class', 'content'); // Imposta l'attributo +$('p').hasClass('taming-slim-20'); // Restituisce vero se ha la classe +$('p').height(); // Ottiene l'altezza dell'elemento o imposta l'altezza + + +// Per molti metodi di manipolazione, ottenere informazioni su un elemento +// restituirà SOLO il primo elemento corrispondente +$('p').height(); // Ottiene solo la prima altezza del tag 'p' + +// È possibile utilizzare each per scorrere tutti gli elementi +var heights = []; +$('p').each(function() { + heights.push($(this).height()); // Aggiunge tutte le altezze del tag 'p' all'array +}); + + +``` diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown new file mode 100644 index 00000000..855a0c75 --- /dev/null +++ b/it-it/pyqt-it.html.markdown @@ -0,0 +1,85 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*. + + +Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192 +), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità +che avrebbero se fossero fatte usando pyqt! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Crea un oggetto applicazione + app = QtGui.QApplication(sys.argv) + # Crea un widget in cui verrà inserita la nostra etichetta + w = QtGui.QWidget() + # Aggiungi un'etichetta al widget + b = QtGui.QLabel(w) + # Imposta del testo per l'etichetta + b.setText("Ciao Mondo!") + # Fornisce informazioni su dimensioni e posizionamento + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Dai alla nostra finestra un bel titolo + w.setWindowTitle("PyQt") + # Visualizza tutto + w.show() + # Esegui ciò che abbiamo chiesto, una volta che tutto è stato configurato + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi. +Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Crea un pulsante e allegalo al widget w + b = QPushButton(w) + b.setText("Premimi") + b.move(50, 50) + # Indica a b di chiamare questa funzione quando si fa clic + # notare la mancanza di "()" sulla chiamata di funzione + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# Questa funzione dovrebbe creare una finestra di dialogo con un pulsante +# che aspetta di essere cliccato e quindi esce dal programma +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # Questa modalità dice al popup di bloccare il genitore, mentre è attivo + d.setWindowModality(Qt.ApplicationModal) + # Al click vorrei che l'intero processo finisse + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` diff --git a/it-it/qt-it.html.markdown b/it-it/qt-it.html.markdown new file mode 100644 index 00000000..4543818f --- /dev/null +++ b/it-it/qt-it.html.markdown @@ -0,0 +1,161 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +translators: + - ["Ale46", "https://gihub.com/ale46"] +lang: it-it +--- + +**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*, ci sono diversi porting in altri linguaggi: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** è ottimo per la creazione di applicazioni con interfaccia utente grafica (GUI). Questo tutorial descrive come farlo in *C++*. + +```c++ +/* + * Iniziamo classicamente + */ + +// tutte le intestazioni dal framework Qt iniziano con la lettera maiuscola 'Q' +#include <QApplication> +#include <QLineEdit> + +int main(int argc, char *argv[]) { + // crea un oggetto per gestire le risorse a livello di applicazione + QApplication app(argc, argv); + + // crea un widget di campo di testo e lo mostra sullo schermo + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // avvia il ciclo degli eventi dell'applicazione + return app.exec(); +} +``` + +La parte relativa alla GUI di **Qt** riguarda esclusivamente *widget* e le loro *connessioni*. + +[LEGGI DI PIÙ SUI WIDGET](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Creiamo un'etichetta e un pulsante. + * Un'etichetta dovrebbe apparire quando si preme un pulsante. + * + * Il codice Qt parla da solo. + */ + +#include <QApplication> +#include <QDialog> +#include <QVBoxLayout> +#include <QPushButton> +#include <QLabel> + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // add vertical layout + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Grazie per aver premuto quel pulsante"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Premimi"); + layout.addWidget(&button); + + // mostra l'etichetta nascosta quando viene premuto il pulsante + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Si noti la parte relativa a *QObject::connect*. Questo metodo viene utilizzato per connettere *SEGNALI* di un oggetto agli *SLOTS* di un altro. + +**I SEGNALI** vengono emessi quando certe cose accadono agli oggetti, come il segnale *premuto* che viene emesso quando l'utente preme sull'oggetto QPushButton. + +**Gli slot** sono *azioni* che potrebbero essere eseguite in risposta ai segnali ricevuti. + +[LEGGI DI PIÙ SU SLOT E SEGNALI](http://doc.qt.io/qt-5/signalsandslots.html) + + +Successivamente, impariamo che non possiamo solo usare i widget standard, ma estendere il loro comportamento usando l'ereditarietà. Creiamo un pulsante e contiamo quante volte è stato premuto. A tale scopo definiamo la nostra classe *CounterLabel*. Deve essere dichiarato in un file separato a causa dell'architettura Qt specifica. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include <QLabel> + +class CounterLabel : public QLabel { + Q_OBJECT // Macro definite da Qt che devono essere presenti in ogni widget personalizzato + +public: + CounterLabel() : counter(0) { + setText("Il contatore non è stato ancora aumentato"); // metodo di QLabel + } + +public slots: + // azione che verrà chiamata in risposta alla pressione del pulsante + void increaseCounter() { + setText(QString("Valore contatore: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Quasi uguale all'esempio precedente + +#include <QApplication> +#include <QDialog> +#include <QVBoxLayout> +#include <QPushButton> +#include <QString> +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Premimi ancora una volta"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +Questo è tutto! Ovviamente, il framework Qt è molto più grande della parte che è stata trattata in questo tutorial, quindi preparatevi a leggere e fare pratica. + +## Ulteriori letture + +- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html) +- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html) + +Buona fortuna e buon divertimento! diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown new file mode 100644 index 00000000..295bf28a --- /dev/null +++ b/it-it/ruby-it.html.markdown @@ -0,0 +1,653 @@ +--- +language: ruby +filename: learnruby-it.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] + - ["Corey Ward", "https://github.com/coreyward"] +translators: + - ["abonte", "https://github.com/abonte"] +lang: it-it +--- + +```ruby +# Questo è un commento + +# In Ruby, (quasi) tutto è un oggetto. +# Questo include i numeri... +3.class #=> Integer + +# ...stringhe... +"Hello".class #=> String + +# ...e anche i metodi! +"Hello".method(:class).class #=> Method + +# Qualche operazione aritmetica di base +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2 ** 5 #=> 32 +5 % 3 #=> 2 + +# Bitwise operators +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# L'aritmetica è solo zucchero sintattico +# per chiamare il metodo di un oggetto +1.+(3) #=> 4 +10.* 5 #=> 50 +100.methods.include?(:/) #=> true + +# I valori speciali sono oggetti +nil # equivalente a null in altri linguaggi +true # vero +false # falso + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Uguaglianza +1 == 1 #=> true +2 == 1 #=> false + +# Disuguaglianza +1 != 1 #=> false +2 != 1 #=> true + +# nil è l'unico valore, oltre a false, che è considerato 'falso' +!!nil #=> false +!!false #=> false +!!0 #=> true +!!"" #=> true + +# Altri confronti +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Operatori di confronto combinati (ritorna '1' quando il primo argomento è più +# grande, '-1' quando il secondo argomento è più grande, altrimenti '0') +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Operatori logici +true && false #=> false +true || false #=> true + +# Ci sono versioni alternative degli operatori logici con meno precedenza. +# Sono usati come costrutti per il controllo di flusso per concatenare +# insieme statement finché uno di essi ritorna true o false. + +# `do_something_else` chiamato solo se `do_something` ha successo. +do_something() and do_something_else() +# `log_error` è chiamato solo se `do_something` fallisce. +do_something() or log_error() + +# Interpolazione di stringhe + +placeholder = 'usare l\'interpolazione di stringhe' +"Per #{placeholder} si usano stringhe con i doppi apici" +#=> "Per usare l'interpolazione di stringhe si usano stringhe con i doppi apici" + +# E' possibile combinare le stringhe usando `+`, ma non con gli altri tipi +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" +"hello #{3}" #=> "hello 3" + +# ...oppure combinare stringhe e operatori +'ciao ' * 3 #=> "ciao ciao ciao " + +# ...oppure aggiungere alla stringa +'ciao' << ' mondo' #=> "ciao mondo" + +# Per stampare a schermo e andare a capo +puts "Sto stampando!" +#=> Sto stampando! +#=> nil + +# Per stampare a schermo senza andare a capo +print "Sto stampando!" +#=> Sto stampando! => nil + +# Variabili +x = 25 #=> 25 +x #=> 25 + +# Notare che l'assegnamento ritorna il valore assegnato. +# Questo significa che è possibile effettuare assegnamenti multipli: +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Per convenzione si usa lo snake_case per i nomi delle variabili +snake_case = true + +# Usare nomi delle variabili descrittivi +path_to_project_root = '/buon/nome/' +m = '/nome/scadente/' + +# I simboli sono immutabili, costanti riusabili rappresentati internamente da +# un valore intero. Sono spesso usati al posto delle stringhe per comunicare +# specifici e significativi valori. + +:pendente.class #=> Symbol + +stato = :pendente + +stato == :pendente #=> true + +stato == 'pendente' #=> false + +stato == :approvato #=> false + +# Le stringhe possono essere convertite in simboli e viceversa: +status.to_s #=> "pendente" +"argon".to_sym #=> :argon + +# Arrays + +# Questo è un array +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Gli array possono contenere diversi tipi di elementi +[1, 'hello', false] #=> [1, "hello", false] + +# Gli array possono essere indicizzati +# Dall'inizio... +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + + +# ...o dalla fine... +array[-1] #=> 5 +array.last #=> 5 + +# With a start index and length +# ...o con un indice di inzio e la lunghezza... +array[2, 3] #=> [3, 4, 5] + +# ...oppure con un intervallo. +array[1..3] #=> [2, 3, 4] + +# Invertire l'ordine degli elementi di un array +a = [1,2,3] +a.reverse! #=> [3,2,1] + +# Come per l'aritmetica, l'accesso tramite [var] +# è solo zucchero sintattico +# per chiamare il metodo '[]'' di un oggetto +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Si può aggiungere un elemento all'array così +array << 6 #=> [1, 2, 3, 4, 5, 6] +# oppure così +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Controllare se un elemento esiste in un array +array.include?(1) #=> true + +# Hash è un dizionario con coppie di chiave e valore +# Un hash è denotato da parentesi graffe: +hash = { 'colore' => 'verde', 'numero' => 5 } + +hash.keys #=> ['colore', 'numero'] + +# E' possibile accedere all'hash tramite chiave: +hash['colore'] #=> 'verde' +hash['numero'] #=> 5 + +# Accedere all'hash con una chiave che non esiste ritorna nil: +hash['nothing here'] #=> nil + +# Quando si usano simboli come chiavi di un hash, si possono utilizzare +# queste sintassi: + +hash = { :defcon => 3, :action => true } +hash.keys #=> [:defcon, :action] +# oppure +hash = { defcon: 3, action: true } +hash.keys #=> [:defcon, :action] + +# Controllare l'esistenza di una chiave o di un valore in un hash +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true + +# Suggerimento: sia gli array che gli hash sono enumerabili! +# Entrambi possiedono metodi utili come each, map, count e altri. + +# Strutture di controllo + +#Condizionali +if true + 'if statement' +elsif false + 'else if, opzionale' +else + 'else, opzionale' +end + +#Cicli +# In Ruby, i tradizionali cicli `for` non sono molto comuni. Questi semplici +# cicli, invece, sono implementati con un enumerable, usando `each`: +(1..5).each do |contatore| + puts "iterazione #{contatore}" +end + +# Esso è equivalente a questo ciclo, il quale è inusuale da vedere in Ruby: +for contatore in 1..5 + puts "iterazione #{contatore}" +end + +# Il costrutto `do |variable| ... end` è chiamato 'blocco'. I blocchi +# sono simili alle lambda, funzioni anonime o closure che si trovano in altri +# linguaggi di programmazione. Essi possono essere passati come oggetti, +# chiamati o allegati come metodi. +# +# Il metodo 'each' di un intervallo (range) esegue il blocco una volta +# per ogni elemento dell'intervallo. +# Al blocco è passato un contatore come parametro. + +# E' possibile inglobare il blocco fra le parentesi graffe +(1..5).each { |contatore| puts "iterazione #{contatore}" } + +# Il contenuto delle strutture dati può essere iterato usando "each". +array.each do |elemento| + puts "#{elemento} è parte dell'array" +end +hash.each do |chiave, valore| + puts "#{chiave} è #{valore}" +end + +# If you still need an index you can use 'each_with_index' and define an index +# variable +# Se comunque si vuole un indice, si può usare "each_with_index" e definire +# una variabile che contiene l'indice +array.each_with_index do |elemento, indice| + puts "#{elemento} è il numero #{index} nell'array" +end + +contatore = 1 +while contatore <= 5 do + puts "iterazione #{contatore}" + contatore += 1 +end +#=> iterazione 1 +#=> iterazione 2 +#=> iterazione 3 +#=> iterazione 4 +#=> iterazione 5 + +# Esistono in Ruby ulteriori funzioni per fare i cicli, +# come per esempio 'map', 'reduce', 'inject' e altri. +# Nel caso di 'map', esso prende l'array sul quale si sta iterando, esegue +# le istruzioni definite nel blocco, e ritorna un array completamente nuovo. +array = [1,2,3,4,5] +doubled = array.map do |elemento| + elemento * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + +# Costrutto "case" +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# 'case' può usare anche gli intervalli +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Gestione delle eccezioni +begin + # codice che può sollevare un eccezione + raise NoMemoryError, 'Esaurita la memoria.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError è stato sollevato.', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError è stato sollvato.' +else + puts 'Questo viene eseguito se nessuna eccezione è stata sollevata.' +ensure + puts 'Questo codice viene sempre eseguito a prescindere.' +end + +# Metodi + +def double(x) + x * 2 +end + +# Metodi (e blocchi) ritornano implicitamente il valore dell'ultima istruzione +double(2) #=> 4 + +# Le parentesi sono opzionali dove l'interpolazione è inequivocabile +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Gli argomenit dei metodi sono separati dalla virgola +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Tutti i metodi hanno un implicito e opzionale parametro del blocco. +# Esso può essere chiamato con la parola chiave 'yield'. + +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + +# I blocchi possono essere convertiti in 'proc', il quale racchiude il blocco +# e gli permette di essere passato ad un altro metodo, legato ad uno scope +# differente o modificato. Questo è molto comune nella lista parametri del +# metodo, dove è frequente vedere il parametro '&block' in coda. Esso accetta +# il blocco, se ne è stato passato uno, e lo converte in un 'Proc'. +# Qui la denominazione è una convenzione; funzionerebbe anche con '&ananas'. +def guests(&block) + block.class #=> Proc + block.call(4) +end + +# Il metodo 'call' del Proc è simile allo 'yield' quando è presente un blocco. +# Gli argomenti passati a 'call' sono inoltrati al blocco come argomenti: + +guests { |n| "You have #{n} guests." } +# => "You have 4 guests." + +# L'operatore splat ("*") converte una lista di argomenti in un array +def guests(*array) + array.each { |guest| puts guest } +end + +# Destrutturazione + +# Ruby destruttura automaticamente gli array in assegnamento +# a variabili multiple: +a, b, c = [1, 2, 3] +a #=> 1 +b #=> 2 +c #=> 3 + +# In alcuni casi si usa l'operatore splat ("*") per destrutturare +# un array in una lista. +classifica_concorrenti = ["John", "Sally", "Dingus", "Moe", "Marcy"] + +def migliore(primo, secondo, terzo) + puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}." +end + +migliore *classifica_concorrenti.first(3) +#=> I vincitori sono John, Sally, e Dingus. + +# The splat operator can also be used in parameters: +def migliore(primo, secondo, terzo, *altri) + puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}." + puts "C'erano altri #{altri.count} partecipanti." +end + +migliore *classifica_concorrenti +#=> I vincitori sono John, Sally, e Dingus. +#=> C'erano altri 2 partecipanti. + +# Per convenzione, tutti i metodi che ritornano un booleano terminano +# con un punto interrogativo +5.even? #=> false +5.odd? #=> true + +# Per convenzione, se il nome di un metodo termina con un punto esclamativo, +# esso esegue qualcosa di distruttivo. Molti metodi hanno una versione con '!' +# per effettuare una modifiche, e una versione senza '!' che ritorna +# una versione modificata. +nome_azienda = "Dunder Mifflin" +nome_azienda.upcase #=> "DUNDER MIFFLIN" +nome_azienda #=> "Dunder Mifflin" +# Questa volta modifichiamo nome_azienda +nome_azienda.upcase! #=> "DUNDER MIFFLIN" +nome_azienda #=> "DUNDER MIFFLIN" + +# Classi + +# Definire una classe con la parola chiave class +class Umano + + # Una variabile di classe. E' condivisa da tutte le istance di questa classe. + @@specie = 'H. sapiens' + + # Inizializzatore di base + def initialize(nome, eta = 0) + # Assegna il valore dell'argomento alla variabile dell'istanza "nome" + @nome = nome + # Se l'età non è fornita, verrà assegnato il valore di default indicato + # nella lista degli argomenti + @eta = eta + end + + # Metodo setter di base + def nome=(nome) + @nome = nome + end + + # Metodo getter di base + def nome + @nome + end + + # Le funzionalità di cui sopra posso essere incapsulate usando + # il metodo attr_accessor come segue + attr_accessor :nome + + # Getter/setter possono anche essere creati individualmente + attr_reader :nome + attr_writer :nome + + # Un metodo della classe usa 'self' per distinguersi dai metodi dell'istanza. + # Può essere richimato solo dalla classe, non dall'istanza. + def self.say(msg) + puts msg + end + + def specie + @@specie + end +end + + +# Instanziare una classe +jim = Umano.new('Jim Halpert') + +dwight = Umano.new('Dwight K. Schrute') + +# Chiamiamo qualche metodo +jim.specie #=> "H. sapiens" +jim.nome #=> "Jim Halpert" +jim.nome = "Jim Halpert II" #=> "Jim Halpert II" +jim.nome #=> "Jim Halpert II" +dwight.specie #=> "H. sapiens" +dwight.nome #=> "Dwight K. Schrute" + +# Chiamare un metodo della classe +Umano.say('Ciao') #=> "Ciao" + +# La visibilità della variabile (variable's scope) è determinata dal modo +# in cui le viene assegnato il nome. +# Variabili che iniziano con $ hanno uno scope globale +$var = "Sono una variabile globale" +defined? $var #=> "global-variable" + +# Variabili che inziano con @ hanno a livello dell'istanza +@var = "Sono una variabile dell'istanza" +defined? @var #=> "instance-variable" + +# Variabili che iniziano con @@ hanno una visibilità a livello della classe +@@var = "Sono una variabile della classe" +defined? @@var #=> "class variable" + +# Variabili che iniziano con una lettera maiuscola sono costanti +Var = "Sono una costante" +defined? Var #=> "constant" + +# Anche una classe è un oggetto in ruby. Quindi la classe può avere +# una variabile dell'istanza. Le variabili della classe sono condivise +# fra la classe e tutti i suoi discendenti. + +# Classe base +class Umano + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Classe derivata +class Lavoratore < Umano +end + +Umano.foo #=> 0 +Lavoratore.foo #=> 0 + +Umano.foo = 2 #=> 2 +Lavoratore.foo #=> 2 + +# La variabile dell'istanza della classe non è condivisa dai discendenti. + +class Umano + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Dottore < Umano +end + +Umano.bar #=> 0 +Dottore.bar #=> nil + +module EsempioModulo + def foo + 'foo' + end +end + +# Includere moduli vincola i suoi metodi all'istanza della classe. +# Estendere moduli vincola i suoi metodi alla classe stessa. +class Persona + include EsempioModulo +end + +class Libro + extend EsempioModulo +end + +Persona.foo #=> NoMethodError: undefined method `foo' for Person:Class +Persona.new.foo #=> 'foo' +Libro.foo #=> 'foo' +Libro.new.foo #=> NoMethodError: undefined method `foo' + +# Callbacks sono eseguiti quand si include o estende un modulo +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar #=> 'bar' +Something.qux #=> NoMethodError: undefined method `qux' +Something.new.bar #=> NoMethodError: undefined method `bar' +Something.new.qux #=> 'qux' +``` + +## Ulteriori risorse + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Una variante di questa guida con esercizi nel browser. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Imparare Ruby attraverso una serie di tutorial interattivi. +- [Official Documentation](http://ruby-doc.org/core) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una passata [edizione libera](http://ruby-doc.com/docs/ProgrammingRuby/) è disponibile online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser. diff --git a/it-it/toml-it.html.markdown b/it-it/toml-it.html.markdown new file mode 100644 index 00000000..99082048 --- /dev/null +++ b/it-it/toml-it.html.markdown @@ -0,0 +1,276 @@ +---
+language: toml
+filename: learntoml-it.toml
+contributors:
+ - ["Alois de Gouvello", "https://github.com/aloisdg"]
+translators:
+ - ["Christian Grasso", "https://grasso.io"]
+lang: it-it
+---
+
+TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la
+serializzazione di dati, progettato per i file di configurazione.
+
+È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile
+per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza
+semplice nella maggior parte dei linguaggi di programmazione, in quanto è
+progettato per essere tradotto senza ambiguità in una hash table.
+
+Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è
+ancora stabile. Questo documento utilizza TOML 0.4.0.
+
+```toml
+# I commenti in TOML sono fatti così.
+
+################
+# TIPI SCALARI #
+################
+
+# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa,
+# anche chiamata dizionario, hash o oggetto in altri linguaggi.
+
+# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga,
+# eccetto per alcuni tipi di valori.
+key = "value"
+stringa = "ciao"
+numero = 42
+float = 3.14
+boolean = true
+data = 1979-05-27T07:32:00-08:00
+notazScientifica = 1e+12
+"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure '
+"la key può contenere" = "lettere, numeri, underscore e trattini"
+
+############
+# Stringhe #
+############
+
+# Le stringhe possono contenere solo caratteri UTF-8 validi.
+# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze
+# di escape compatte. Ad esempio, \t corrisponde al TAB.
+stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"."
+
+stringaMultiriga = """
+Racchiusa da tre virgolette doppie all'inizio e
+alla fine - consente di andare a capo."""
+
+stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.'
+
+stringaMultirigaLiteral = '''
+Racchiusa da tre virgolette singole all'inizio e
+alla fine - consente di andare a capo.
+Anche in questo caso non si può fare escape.
+Il primo ritorno a capo viene eliminato.
+ Tutti gli altri spazi aggiuntivi
+ vengono mantenuti.
+'''
+
+# Per i dati binari è consigliabile utilizzare Base64 e
+# gestirli manualmente dall'applicazione.
+
+##########
+# Interi #
+##########
+
+## Gli interi possono avere o meno un segno (+, -).
+## Non si possono inserire zero superflui all'inizio.
+## Non è possibile inoltre utilizzare valori numerici
+## non rappresentabili con una sequenza di cifre.
+int1 = +42
+int2 = 0
+int3 = -21
+
+## Puoi utilizzare gli underscore per migliorare la leggibilità.
+## Fai attenzione a non inserirne due di seguito.
+int4 = 5_349_221
+int5 = 1_2_3_4_5 # VALIDO, ma da evitare
+
+#########
+# Float #
+#########
+
+# I float permettono di rappresentare numeri decimali.
+flt1 = 3.1415
+flt2 = -5e6
+flt3 = 6.626E-34
+
+###########
+# Boolean #
+###########
+
+# I valori boolean (true/false) devono essere scritti in minuscolo.
+bool1 = true
+bool2 = false
+
+############
+# Data/ora #
+############
+
+data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC)
+data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset
+
+######################
+# TIPI DI COLLECTION #
+######################
+
+#########
+# Array #
+#########
+
+array1 = [ 1, 2, 3 ]
+array2 = [ "Le", "virgole", "sono", "delimitatori" ]
+array3 = [ "Non", "unire", "tipi", "diversi" ]
+array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ]
+array5 = [
+ "Gli spazi vuoti", "sono", "ignorati"
+]
+
+###########
+# Tabelle #
+###########
+
+# Le tabelle (o hash table o dizionari) sono collection di coppie key/value.
+# Iniziano con un nome tra parentesi quadre su una linea separata.
+# Le tabelle vuote (senza alcun valore) sono valide.
+[tabella]
+
+# Tutti i valori che si trovano sotto il nome della tabella
+# appartengono alla tabella stessa (finchè non ne viene creata un'altra).
+# L'ordine di questi valori non è garantito.
+[tabella-1]
+key1 = "una stringa"
+key2 = 123
+
+[tabella-2]
+key1 = "un'altra stringa"
+key2 = 456
+
+# Utilizzando i punti è possibile creare delle sottotabelle.
+# Ogni parte suddivisa dai punti segue le regole delle key per il nome.
+[tabella-3."sotto.tabella"]
+key1 = "prova"
+
+# Ecco l'equivalente JSON della tabella precedente:
+# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } }
+
+# Gli spazi non vengono considerati, ma è consigliabile
+# evitare di usare spazi superflui.
+[a.b.c] # consigliato
+[ d.e.f ] # identico a [d.e.f]
+
+# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella.
+# [x] queste
+# [x.y] non
+# [x.y.z] servono
+[x.y.z.w] # per creare questa tabella
+
+# Se non è stata già creata prima, puoi anche creare
+# una tabella superiore più avanti.
+[a.b]
+c = 1
+
+[a]
+d = 2
+
+# Non puoi definire una key o una tabella più di una volta.
+
+# ERRORE
+[a]
+b = 1
+
+[a]
+c = 2
+
+# ERRORE
+[a]
+b = 1
+
+[a.b]
+c = 2
+
+# I nomi delle tabelle non possono essere vuoti.
+[] # NON VALIDO
+[a.] # NON VALIDO
+[a..b] # NON VALIDO
+[.b] # NON VALIDO
+[.] # NON VALIDO
+
+##################
+# Tabelle inline #
+##################
+
+tabelleInline = { racchiuseData = "{ e }", rigaSingola = true }
+punto = { x = 1, y = 2 }
+
+####################
+# Array di tabelle #
+####################
+
+# Un array di tabelle può essere creato utilizzando due parentesi quadre.
+# Tutte le tabelle con questo nome saranno elementi dell'array.
+# Gli elementi vengono inseriti nell'ordine in cui si trovano.
+
+[[prodotti]]
+nome = "array di tabelle"
+sku = 738594937
+tabelleVuoteValide = true
+
+[[prodotti]]
+
+[[prodotti]]
+nome = "un altro item"
+sku = 284758393
+colore = "grigio"
+
+# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie
+# parentesi quadre apparterranno alla tabella più vicina sopra di esse.
+
+[[frutta]]
+ nome = "mela"
+
+ [frutto.geometria]
+ forma = "sferica"
+ nota = "Sono una proprietà del frutto"
+
+ [[frutto.colore]]
+ nome = "rosso"
+ nota = "Sono un oggetto di un array dentro mela"
+
+ [[frutto.colore]]
+ nome = "verde"
+ nota = "Sono nello stesso array di rosso"
+
+[[frutta]]
+ nome = "banana"
+
+ [[frutto.colore]]
+ nome = "giallo"
+ nota = "Anche io sono un oggetto di un array, ma dentro banana"
+```
+
+Ecco l'equivalente JSON dell'ultima tabella:
+
+```json
+{
+ "frutta": [
+ {
+ "nome": "mela",
+ "geometria": { "forma": "sferica", "nota": "..."},
+ "colore": [
+ { "nome": "rosso", "nota": "..." },
+ { "nome": "verde", "nota": "..." }
+ ]
+ },
+ {
+ "nome": "banana",
+ "colore": [
+ { "nome": "giallo", "nota": "..." }
+ ]
+ }
+ ]
+}
+```
+
+### Altre risorse
+
++ [Repository ufficiale di TOML](https://github.com/toml-lang/toml)
diff --git a/jquery.html.markdown b/jquery.html.markdown index 9326c74b..a1673c10 100644 --- a/jquery.html.markdown +++ b/jquery.html.markdown @@ -104,7 +104,7 @@ tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction); // 3. Manipulation // These are similar to effects but can do more -$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div +$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div // Common manipulation methods $('p').append('Hello world'); // Adds to end of element @@ -126,3 +126,7 @@ $('p').each(function() { ``` + +## Further Reading + +* [Codecademy - jQuery](https://www.codecademy.com/learn/learn-jquery) A good introduction to jQuery in a "learn by doing it" format. diff --git a/json.html.markdown b/json.html.markdown index cd42d42d..322c7a47 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -81,3 +81,5 @@ Supported data types: ## Further Reading * [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics. + +* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) A concise introduction to JSON. diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown index 72ed78ba..3d080de7 100644 --- a/lambda-calculus.html.markdown +++ b/lambda-calculus.html.markdown @@ -55,7 +55,7 @@ Although lambda calculus traditionally supports only single parameter functions, we can create multi-parameter functions using a technique called [currying](https://en.wikipedia.org/wiki/Currying). -- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = x(y(z))` +- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = ((x y) z)` Sometimes `λxy.<body>` is used interchangeably with: `λx.λy.<body>` @@ -87,7 +87,7 @@ Using `IF`, we can define the basic boolean logic operators: `a NOT b` is equivalent to: `λa.IF a F T` -*Note: `IF a b c` is essentially saying: `IF(a(b(c)))`* +*Note: `IF a b c` is essentially saying: `IF((a b) c)`* ## Numbers: diff --git a/latex.html.markdown b/latex.html.markdown index c9b1d8fb..253c8139 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -26,8 +26,8 @@ filename: learn-latex.tex % Next we define the packages the document uses. % If you want to include graphics, colored text, or -% source code from another language file into your document, -% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. % I'm going to include the float and caption packages for figures % and hyperref package for hyperlinks \usepackage{caption} @@ -42,14 +42,14 @@ Svetlana Golubeva} % Now we're ready to begin the document % Everything before this line is called "The Preamble" -\begin{document} -% if we set the author, date, title fields, we can have LaTeX +\begin{document} +% if we set the author, date, title fields, we can have LaTeX % create a title page for us. \maketitle % If we have sections, we can create table of contents. We have to compile our % document twice to make it appear in right order. -% It is a good practice to separate the table of contents form the body of the +% It is a good practice to separate the table of contents form the body of the % document. To do so we use \newpage command \newpage \tableofcontents @@ -58,14 +58,14 @@ Svetlana Golubeva} % Most research papers have abstract, you can use the predefined commands for this. % This should appear in its logical order, therefore, after the top matter, -% but before the main sections of the body. +% but before the main sections of the body. % This command is available in the document classes article and report. \begin{abstract} \LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not my idea! \end{abstract} -% Section commands are intuitive. +% Section commands are intuitive. % All the titles of the sections are added automatically to the table of contents. \section{Introduction} Hello, my name is Colton and together we're going to explore \LaTeX! @@ -81,16 +81,16 @@ Much better now. \label{subsec:pythagoras} % By using the asterisk we can suppress LaTeX's inbuilt numbering. -% This works for other LaTeX commands as well. -\section*{This is an unnumbered section} +% This works for other LaTeX commands as well. +\section*{This is an unnumbered section} However not all sections have to be numbered! \section{Some Text notes} %\section{Spacing} % Need to add more information about space intervals \LaTeX \hspace{1pt} is generally pretty good about placing text where it should -go. If -a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash -\hspace{1pt} to the source code. \\ +go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash +\hspace{1pt} to the source code. \\ \section{Lists} Lists are one of the easiest things to create in \LaTeX! I need to go shopping @@ -110,7 +110,7 @@ tomorrow, so let's make a grocery list. \section{Math} One of the primary uses for \LaTeX \hspace{1pt} is to produce academic articles -or technical papers. Usually in the realm of math and science. As such, +or technical papers. Usually in the realm of math and science. As such, we need to be able to add special symbols to our paper! \\ Math has many symbols, far beyond what you can find on a keyboard; @@ -118,9 +118,9 @@ Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ Sets and relations play a vital role in many mathematical research papers. Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\ -% Notice how I needed to add $ signs before and after the symbols. This is -% because when writing, we are in text-mode. -% However, the math symbols only exist in math-mode. +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. % We can enter math-mode from text mode with the $ signs. % The opposite also holds true. Variable can also be rendered in math-mode. % We can also enter math mode with \[\] @@ -131,12 +131,12 @@ My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know about! \\ -Operators are essential parts of a mathematical document: -trigonometric functions ($\sin$, $\cos$, $\tan$), -logarithms and exponentials ($\log$, $\exp$), -limits ($\lim$), etc. -have per-defined LaTeX commands. -Let's write an equation to see how it's done: +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc. +have per-defined LaTeX commands. +Let's write an equation to see how it's done: $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ Fractions (Numerator-denominators) can be written in these forms: @@ -156,31 +156,31 @@ We can also insert equations in an ``equation environment''. \label{eq:pythagoras} % for referencing \end{equation} % all \begin statements must have an end statement -We can then reference our new equation! +We can then reference our new equation! Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also -the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: figures, equations, sections, etc. Summations and Integrals are written with sum and int commands: % Some LaTeX compilers will complain if there are blank lines % In an equation environment. -\begin{equation} +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Figures} -Let's insert a Figure. Figure placement can get a little tricky. +Let's insert a Figure. Figure placement can get a little tricky. I definitely have to lookup the placement options each time. -\begin{figure}[H] % H here denoted the placement option. +\begin{figure}[H] % H here denoted the placement option. \centering % centers the figure on the page % Inserts a figure scaled to 0.8 the width of the page. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Commented out for compilation purposes. Please use your imagination. \caption{Right triangle with sides $a$, $b$, $c$} \label{fig:right-triangle} @@ -193,7 +193,7 @@ We can also insert Tables in the same way as figures. \caption{Caption for the Table.} % the {} arguments below describe how each row of the table is drawn. % Again, I have to look these up. Each. And. Every. Time. - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Number & Last Name & First Name \\ % Column rows are separated by & \hline % a horizontal line 1 & Biggus & Dickus \\ @@ -204,34 +204,34 @@ We can also insert Tables in the same way as figures. \section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)} Let's say we want to include some code into our \LaTeX \hspace{1pt} document, we would then need \LaTeX \hspace{1pt} to not try and interpret that text and -instead just print it to the document. We do this with a verbatim -environment. +instead just print it to the document. We do this with a verbatim +environment. % There are other packages that exist (i.e. minty, lstlisting, etc.) % but verbatim is the bare-bones basic one. -\begin{verbatim} +\begin{verbatim} print("Hello World!") - a%b; % look! We can use % signs in verbatim. + a%b; % look! We can use % signs in verbatim. random = 4; #decided by fair random dice roll \end{verbatim} -\section{Compiling} +\section{Compiling} -By now you're probably wondering how to compile this fabulous document +By now you're probably wondering how to compile this fabulous document and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf. (yes, this document actually does compile). \\ -Getting to the final document using \LaTeX \hspace{1pt} consists of the following +Getting to the final document using \LaTeX \hspace{1pt} consists of the following steps: \begin{enumerate} \item Write the document in plain text (the ``source code''). - \item Compile source code to produce a pdf. + \item Compile source code to produce a pdf. The compilation step looks like this (in Linux): \\ - \begin{verbatim} + \begin{verbatim} > pdflatex learn-latex.tex \end{verbatim} \end{enumerate} -A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the +A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the same piece of software. So, you get to see Step 1, but not Step 2 completely. Step 2 is still happening behind the scenes\footnote{In cases, where you use references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2 @@ -245,17 +245,17 @@ format you defined in Step 1. \section{Hyperlinks} We can also insert hyperlinks in our document. To do so we need to include the package hyperref into preamble with the command: -\begin{verbatim} +\begin{verbatim} \usepackage{hyperref} \end{verbatim} There exists two main types of links: visible URL \\ -\url{https://learnxinyminutes.com/docs/latex/}, or +\url{https://learnxinyminutes.com/docs/latex/}, or \href{https://learnxinyminutes.com/docs/latex/}{shadowed by text} -% You can not add extra-spaces or special symbols into shadowing text since it +% You can not add extra-spaces or special symbols into shadowing text since it % will cause mistakes during the compilation -This package also produces list of thumbnails in the output pdf document and +This package also produces list of thumbnails in the output pdf document and active links in the table of contents. \section{End} @@ -267,7 +267,7 @@ That's all for now! \begin{thebibliography}{1} % similar to other lists, the \bibitem command can be used to list items % each entry can then be cited directly in the body of the text - \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em + \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em https://en.wikibooks.org/wiki/LaTeX} \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} \end{thebibliography} @@ -280,3 +280,4 @@ https://en.wikibooks.org/wiki/LaTeX} * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) * An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) +* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes) diff --git a/nl-nl/dynamic-programming-nl.html.markdown b/nl-nl/dynamic-programming-nl.html.markdown new file mode 100644 index 00000000..5186a3bf --- /dev/null +++ b/nl-nl/dynamic-programming-nl.html.markdown @@ -0,0 +1,55 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +translators: + - ["Jasper Haasdijk", "https://github.com/jhaasdijk"] +lang: nl-nl +--- + +# Dynamisch Programmeren + +## Introductie + +Dynamisch programmeren is een krachtige techniek die, zoals we zullen zien, gebruikt kan worden om een bepaalde klasse van problemen op te lossen. Het idee is eenvoudig. Als je een oplossing hebt voor een probleem met een bepaalde input, sla dit resultaat dan op. Hiermee kan je voorkomen dat je in de toekomst nog een keer hetzelfde probleem moet gaan oplossen omdat je het resultaat vergeten bent. + +Onthoud altijd! +"Zij die het verleden niet kunnen herinneren, zijn gedoemd het te herhalen." + +## Verschillende aanpakken + +1. *Top-Down* : Oftewel, van boven naar beneden. Begin je oplossing met het afbreken van het probleem in kleine stukken. Kom je een stukje tegen dat je eerder al hebt opgelost, kijk dan enkel naar het opgeslagen antwoord. Kom je een stukje tegen dat je nog niet eerder hebt opgelost, los het op en sla het antwoord op. Deze manier is voor veel mensen de makkelijke manier om erover na te denken, erg intuitief. Deze methode wordt ook wel Memoization genoemd. + +2. *Bottom-Up* : Oftewel, van beneden naar boven. Analyseer het probleem en bekijk de volgorde waarin de sub-problemen opgelost kunnen worden. Begin met het oplossen van de triviale gevallen en maak zodoende de weg naar het gegeven probleem. In dit process is het gegarandeerd dat de sub-problemen eerder worden opgelost dan het gegeven probleem. Deze methode wordt ook wel Dynamisch Programmeren genoemd. + +## Voorbeeld van Dynamisch Programmeren + +Het langst stijgende sequentie probleem is het probleem waarbij je binnen een bepaalde reeks op zoek bent naar het langste aaneengesloten stijgende stuk. Gegeven een reeks `S = {a1 , a2 , a3, a4, ............., an-1, an }` zijn we op zoek naar het langst aaneengesloten stuk zodanig dat voor alle `j` en `i`, `j<i` in de reeks `aj<ai`. + +Ten eerste moeten we de waarde van de langste subreeksen(LSi) op elke index i vinden waar het laatste element van de reeks ai is. Daarna zal LSi het langste subreeks in de gegeven reeks zijn. Om te beginnen heeft LSi de waarde 1 omdat ai een element van de reeks(laatste element) is. Daarna zal voor alle `j` zodanig dat `j<i` en `aj<ai` de grootste LSj gevonden en toegevoegd worden aan LSi. Het algoritme duurt *O(n2)* tijd. + +Pseudo-code voor het vinden van de lengte van de langst stijgende subreeks: +De complexiteit van het algoritme kan worden vermindert door het gebruik van een betere data structuur dan een simpele lijst. Het opslaan van een voorgangers lijst en een variabele als `langste_reeks_dusver` en de index daarvan, kan ook een hoop tijd schelen. + +Een soortgelijk concept kan worden toegepast in het vinden van het langste pad in een gerichte acyclische graaf. + +```python +for i=0 to n-1 + LS[i]=1 + for j=0 to i-1 + if (a[i] > a[j] and LS[i]<LS[j]) + LS[i] = LS[j]+1 +for i=0 to n-1 + if (langste < LS[i]) +``` + +### Enkele beroemde DP problemen + +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() + +## Online Bronnen + +* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) diff --git a/nl-nl/vim-nl.html.markdown b/nl-nl/vim-nl.html.markdown new file mode 100644 index 00000000..a69c031c --- /dev/null +++ b/nl-nl/vim-nl.html.markdown @@ -0,0 +1,272 @@ +--- +category: tool +tool: vim +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Rick Haan", "https://github.com/RickHaan"] +filename: learnvim-nl.yaml +lang: nl-nl +--- + +# Vim in het Nederlands + +[Vim](http://www.vim.org) +(Vi IMproved) is een kopie van de populaire vi editor voor Unix. Het is +ontworpen voor snelheid, verhoogde productiviteit en is beschikbaar in de meeste +unix-gebaseerde systemen. Het heeft verscheidene toetscombinaties voor snelle +navigatie en aanpassingen in het doelbestand. + +## De Basis van het navigeren in Vim + +``` Vim + vim <bestandsnaam> # Open <bestandsnaam> in vim + :help <onderwerp> # Open ingebouwde documentatie over <onderwerp> als + deze bestaat + :q # Vim afsluiten + :w # Huidig bestand opslaan + :wq # Huidig bestand opslaan en vim afsluiten + ZZ # Huidig bestand opslaan en vim afsluiten + :x # Huidig bestand opslaan en vim afsluiten, verkorte versie + :q! # Afsluiten zonder opslaan + # ! *forceert* het normale afsluiten met :q + + u # Ongedaan maken + CTRL+R # Opnieuw doen + + h # Ga 1 karakter naar links + j # Ga 1 regel naar beneden + k # Ga 1 regel omhoog + l # Ga 1 karakter naar rechts + + Ctrl+B # Ga 1 volledig scherm terug + Ctrl+F # Ga 1 volledig scherm vooruit + Ctrl+D # Ga 1/2 scherm vooruit + Ctrl+U # Ga 1/2 scherm terug + + # Verplaatsen over de regel + + 0 # Verplaats naar het begin van de regel + $ # Verplaats naar het eind van de regel + ^ # Verplaats naar het eerste niet-lege karakter op de regel + + # Zoeken in de tekst + + /word # Markeert alle voorvallen van 'word' na de cursor + ?word # Markeert alle voorvallen van 'word' voor de cursor + n # Verplaatst de cursor naar het volgende voorval van + de zoekopdracht + N # Verplaatst de cursor naar het vorige voorval van + de zoekopdracht + + :%s/foo/bar/g # Verander 'foo' naar 'bar' op elke regel van het bestand + :s/foo/bar/g # Verander 'foo' naar 'bar' op de huidge regel in + het bestand + :%s/\n/\r/g # Vervang nieuwe regel karakters met nieuwe regel karakters + + # Spring naar karakters + + f<character> # Spring vooruit en land op <character> + t<character> # Spring vooruit en land net voor <character> + + # Bijvoorbeeld, + f< # Spring vooruit en land op < + t< # Spring vooruit en land net voor < + + # Verplaatsen per woord + + w # Ga 1 woord vooruit + b # Ga 1 woord achteruit + e # Ga naar het einde van het huidige woord + + # Andere karakters om mee te verplaatsen + + gg # Ga naar de bovenkant van het bestand + G # Ga naar de onderkant van het bestand + :NUM # Ga naar regel NUM (NUM is elk nummer) + H # Ga naar de bovenkant van het scherm + M # Ga naar het midden van het scherm + L # Ga naar de onderkant van het scherm +``` + +## Help documentatie + +Vim heeft ingebouwde help documentatie dat benaderd kan worden met +`:help <onderwerp>`. Bijvoorbeeld `:help navigation` geeft documentatie weer hoe +door vim te navigeren. `:help` kan ook gebruikt worden zonder onderwerp. Dan wordt de standaard documentatie weergeven die bedoelt is om vim toegankelijker te maken. + +## Modus + +Vim is gebaseerd op het concept van **modus**. + +* Command (opdracht) modus - Vim wordt opgestart in deze mode. Deze mode wordt +gebruikt om opdrachten te geven en te navigeren +* Insert (invoer) modus - Wordt gebruikt voor het aanpassen van het bestand +* Zichtbare (Visual) modus - Wordt gebruikt voor het markeren en bewerken van +tekst +* Ex modus - Wordt gebruikt voor het uitvoeren van opdrachten met `:` + +``` Vim + i # Zet vim in de Command modus voor de cursor positie + a # Zet vim in de Insert modus na de cursor positie (append) + v # Zet vim in de Visual modus + : # Zet vim in de ex modus + <esc> # 'Escapes' vanuit elke modus naar de Command modus + + # Het kopiëren en plakken van tekst + + y # Yank (kopieer) wat geselecteerd is + yy # Yank (kopieer) de huidige regel + d # Verwijder wat geselecteerd is + dd # Verwijder de huidige regel + p # Plak de huidige tekst op de cursor positie + P # Plak de huidige tekst voor de cursor positie + x # Verwijder karakter op cursor positie +``` + +## De 'gramatica' van vim + +Vim kan aangeleerd worden als een set van acties in het 'Verb-Modifier-Noun' +formaat waar: + +Verb (werkwoord) - De uit te voeren actie +Modifier (bijwoord) - Hoe de actie uitgevoerd dient te worden +Noun - Het object waarop de actie uitgevoerd wordt + +Een paar belangrijke voorbeelden van 'Verbs', 'Modifiers', en 'Nouns' zijn: + +``` Vim + # 'Verbs' + + d # Verwijder + c # Verander + y # Kopieer + v # Zichtbaar selecteren + + # 'Modifiers' + + i # Binnen + a # Rondom + NUM # Elk nummer + f # Zoekt iets en selecteerd het + t # Zoekt iets en selecteerd het karakter voor het + / # Vindt een combinatie van tekens vanaf de cursor + ? # Vindt een combinatie van tekens voor de cursor + + # 'Nouns' + + w # Woord + s # Zin + p # Paragraaf + b # Blok + + # Voorbeeld 'zinnen' of opdrachten + + d2w # Verwijder twee woorden + cis # Verander in de zin + yip # Kopiereer in de paragraaf + ct< # Verander naar haakje openen + # Verander de tekst vanaf de huidige positie tot het volgende haakje + openen + d$ # Verwijder tot het einde van de regel +``` + +## Een aantal afkortingen en trucs + +``` Vim + > # Verspring de selectie met 1 blok + < # Verspring de selectie met 1 blok terug + :earlier 15 # Zet het document terug naar de situatie van 15 minuten + geleden + :later 15 # Zet het document in de situatie 15 minuten in de toekomst + (omgekeerde van de vorige opdracht) + ddp # Wissel de positie van opeenvolgende regels. dd daarna p + . # Herhaal de vorige opdracht + :w !sudo tee% # Sla het huidige bestand op als root + :set syntax=c # Stel syntax uitlichten in op 'c' + :sort # Sorteer alle regels + :sort! # Sorteer alle regels omgekeerd + :sort u # Sorteer alle regels en verwijder duplicaten + ~ # Stel letter case in voor geselecteerde tekst + u # Verander de geselecteerde tekst naar kleine letters + U # Verander de geselecteerde tekst naar hoofdletters + + # Fold text + zf # Creeer een vouw op de geslecteerde tekst + zo # Open huidige vouw + zc # Sluit huidige vouw + zR # Open alle vouwen + zM # Sluit alle vouwen +``` + +## Macro's + +Macro's zijn opgeslagen opdrachten. Wanneer je begint met het opnemen van een +macro dan worden **alle** acties opgenomen, totdat je stopt met opnemen. Als de +macro uitgevoerd wordt, worden alle acties in de zelfde volgorde als tijdens het +opnemen uitgevoerd. + +``` Vim + qa # Start met het opnemen van de makro genaamd 'a' + q # Stop met opnemen + @a # Gebruik macro 'a' +``` + +## Configureren van .vimrc + +Het .vimrc bestand kan gebruikt worden voor het opslaan van een +standaardconfiguratie van Vim. Het bestand wordt opgeslagen in de home map van de gebruiker. Hieronder staat een voorbeeld van een .vimrc bestand. + +``` Vim +" Voorbeeld ~/.vimrc +" 2015.10 + +" In te stellen dat Vim niet samenwerkt met Vi +set nocompatible + +" Stel in dat Vim kijkt naar de bestandstype voor syntax uitlichting en +automatish inspringen +filetype indent plugin on + +" Zet inspringen aan +syntax on + +" Betere opdracht regel aanvulling +set wildmenu + +" Gebruik niet hoofdlettergevoelig zoeken. +set ignorecase +set smartcase + +" Gebruik automatisch inspringen +set autoindent + +" Geef regelnummers weer +set number + +" Het aantal zichtbare spatie's per TAB +set tabstop=4 + +" Het aantal spatie's tijdens het aanpassen +set softtabstop=4 + +" Aantal spatie's wanneer (>> en <<) worden gebruikt + +" Maak van TAB's spatie's +set expandtab + +" Gebruik slimme tabs spatie's voor inspringen en uitlijnen +set smarttab +``` + +## Referenties (Engels) + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
\ No newline at end of file diff --git a/opencv.html.markdown b/opencv.html.markdown new file mode 100644 index 00000000..f8763b35 --- /dev/null +++ b/opencv.html.markdown @@ -0,0 +1,144 @@ +--- +category: tool +tool: OpenCV +filename: learnopencv.py +contributors: + - ["Yogesh Ojha", "http://github.com/yogeshojha"] +--- +### Opencv + +OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. +Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). +Opencv currently supports wide variety of languages like, C++, Python, Java etc + +#### Installation +Please refer to these articles for installation of OpenCV on your computer. + +* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() +* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() +* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() + +### Here we will be focusing on python implementation of OpenCV + +```python +# Reading image in OpenCV +import cv2 +img = cv2.imread('cat.jpg') + +# Displaying the image +# imshow() function is used to display the image +cv2.imshow('Image',img) +# Your first arguement is the title of the window and second parameter is image +# If you are getting error, Object Type None, your image path may be wrong. Please recheck the pack to the image +cv2.waitKey(0) +# waitKey() is a keyboard binding function and takes arguement in milliseconds. For GUI events you MUST use waitKey() function. + +# Writing an image +cv2.imwrite('catgray.png',img) +# first arguement is the file name and second is the image + +# Convert image to grayscale +gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +# Capturing Video from Webcam +cap = cv2.VideoCapture(0) +#0 is your camera, if you have multiple camera, you need to enter their id +while(True): + # Capturing frame-by-frame + _, frame = cap.read() + cv2.imshow('Frame',frame) + # When user presses q -> quit + if cv2.waitKey(1) & 0xFF == ord('q'): + break +# Camera must be released +cap.release() + +# Playing Video from file +cap = cv2.VideoCapture('movie.mp4') +while(cap.isOpened()): + _, frame = cap.read() + # Play the video in grayscale + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + cv2.imshow('frame',gray) + if cv2.waitKey(1) & 0xFF == ord('q'): + break +cap.release() + +# Drawing The Line in OpenCV +# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +cv2.line(img,(0,0),(511,511),(255,0,0),5) + +# Drawing Rectangle +# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# thickness = -1 used for filling the rectangle +cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) + +# Drawing Circle +cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img,(200,90), 100, (0,0,255), -1) + +# Drawing Ellipse +cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) + +# Adding Text On Images +cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) + +# Blending Images +img1 = cv2.imread('cat.png') +img2 = cv2.imread('openCV.jpg') +dst = cv2.addWeighted(img1,0.5,img2,0.5,0) + +# Thresholding image +# Binary Thresholding +_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) +# Adaptive Thresholding +adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) + +# Blur Image +# Gaussian Blur +blur = cv2.GaussianBlur(img,(5,5),0) +# Median Blur +medianBlur = cv2.medianBlur(img,5) + +# Canny Edge Detection +img = cv2.imread('cat.jpg',0) +edges = cv2.Canny(img,100,200) + +# Face Detection using Haar Cascades +# Download Haar Cascades from https://github.com/opencv/opencv/blob/master/data/haarcascades/ +import cv2 +import numpy as np +face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') +eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') + +img = cv2.imread('human.jpg') +gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +aces = face_cascade.detectMultiScale(gray, 1.3, 5) +for (x,y,w,h) in faces: + cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) + roi_gray = gray[y:y+h, x:x+w] + roi_color = img[y:y+h, x:x+w] + eyes = eye_cascade.detectMultiScale(roi_gray) + for (ex,ey,ew,eh) in eyes: + cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + +cv2.imshow('img',img) +cv2.waitKey(0) + +cv2.destroyAllWindows() +# destroyAllWindows() destroys all windows. +# If you wish to destroy specific window pass the exact name of window you created. +``` + +### Further Reading: + +* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]() +* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() +* An up-to-date language reference can be found at [https://opencv.org]() +* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV]() +* Good OpenCv Tutorials + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() + * [https://realpython.com/python-opencv-color-spaces]() + * [https://pyimagesearch.com]() + * [https://www.learnopencv.com]() diff --git a/pascal.html.markdown b/pascal.html.markdown index 4144f900..28dcc10f 100644 --- a/pascal.html.markdown +++ b/pascal.html.markdown @@ -25,6 +25,10 @@ to compile and run a pascal program you could use a free pascal compiler. [Downl //name of the program program learn_pascal; //<-- dont forget a semicolon +const + { + this is where you should declare constant values + } type { this is where you should delcare a custom @@ -55,17 +59,71 @@ var //or this var a,b : integer; ``` + ```pascal program Learn_More; //Lets learn about data types and their operations +const + PI = 3.141592654; + GNU = 'GNU's Not Unix'; + // constants are conventionally named using CAPS + // their values are fixed and cannot be changed during runtime + // holds any standard data type (integer, real, boolean, char, string) + +type + ch_array : array [0..255] of char; + // arrays are new 'types' specifying the length and data type + // this defines a new data type that contains 255 characters + // (this is functionally equivalent to a string[256] variable) + md_array : array of array of integer; + // nested arrays are equivalent to multidimensional arrays + // can define zero (0) length arrays that are dynamically sized + // this is a 2-dimensional array of integers + //Declaring variables -var - int : integer; // a variable that contains an integer number data types - ch : char; // a variable that contains a character data types - str : string; // a variable that contains a string data types - r : real; // a variable that contains a real number data types - bool : boolean; //a variables that contains a Boolean(True/False) value data types +var + int, c, d : integer; + // three variables that contain integer numbers + // integers are 16-bits and limited to the range [-32,768..32,767] + r : real; + // a variable that contains a real number data types + // reals can range between [3.4E-38..3.4E38] + bool : boolean; + // a variable that contains a Boolean(True/False) value + ch : char; + // a variable that contains a character value + // char variables are stored as 8-bit data types so no UTF + str : string; + // a non-standard variable that contains a string value + // strings are an extension included in most Pascal compilers + // they are stored as an array of char with default length of 255. + s : string[50]; + // a string with maximum length of 50 chars. + // you can specify the length of the string to minimize memory usage + my_str: ch_array; + // you can declare variables of custom types + my_2d : md_array; + // dynamically sized arrays need to be sized before they can be used. + + // additional integer data types + b : byte; // range [0..255] + shi : shortint; // range [-128..127] + smi : smallint; // range [-32,768..32,767] (standard Integer) + w : word; // range [0..65,535] + li : longint; // range [-2,147,483,648..2,147,483,647] + lw : longword; // range [0..4,294,967,295] + c : cardinal; // longword + i64 : int64; // range [-9223372036854775808..9223372036854775807] + qw : qword; // range [0..18,446,744,073,709,551,615] + + // additional real types + rr : real; // range depends on platform (i.e., 8-bit, 16-bit, etc.) + rs : single; // range [1.5E-45..3.4E38] + rd : double; // range [5.0E-324 .. 1.7E308] + re : extended; // range [1.9E-4932..1.1E4932] + rc : comp; // range [-2E64+1 .. 2E63-1] + Begin int := 1;// how to assign a value to a variable r := 3.14; @@ -76,19 +134,28 @@ Begin //arithmethic operation int := 1 + 1; // int = 2 overwriting the previous assignment int := int + 1; // int = 2 + 1 = 3; - int := 4 div 2; //int = 2 a division operation which the result will be floored + int := 4 div 2; //int = 2 division operation where result will be floored int := 3 div 2; //int = 1 int := 1 div 2; //int = 0 bool := true or false; // bool = true bool := false and true; // bool = false bool := true xor true; // bool = false - + r := 3 / 2; // a division operator for real - r := int; // you can assign an integer to a real variable but not the otherwise + r := int; // can assign an integer to a real variable but not the reverse c := str[1]; // assign the first letter of str to c str := 'hello' + 'world'; //combining strings + + my_str[0] := 'a'; // array assignment needs an index + + setlength(my_2d,10,10); // initialize dynamically sized arrays: 10×10 array + for c := 0 to 9 do // arrays begin at 0 and end at length-1 + for d := 0 to 9 do // for loop counters need to be declared variables + my_2d[c,d] := c * d; + // address multidimensional arrays with a single set of brackets + End. ``` @@ -136,3 +203,4 @@ Begin // main program block End. ``` + diff --git a/php.html.markdown b/php.html.markdown index 6542035f..3b18aa60 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -794,7 +794,7 @@ But I'm ChildClass /********************** * Magic constants -* +* */ // Get current class name. Must be used inside a class declaration. @@ -826,7 +826,7 @@ echo "Current trait is " . __TRAIT__; /********************** * Error Handling -* +* */ // Simple error handling can be done with try catch block @@ -871,6 +871,9 @@ and community input. If you're interested in up-to-date best practices, visit [PHP The Right Way](http://www.phptherightway.com/). +A tutorial covering basics of language, setting up coding environment and making +few practical projects at [Codecourse - PHP Basics](https://www.youtube.com/playlist?list=PLfdtiltiRHWHjTPiFDRdTOPtSyYfz3iLW). + If you're coming from a language with good package management, check out [Composer](http://getcomposer.org/). diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 2c15e92c..42a29991 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -609,7 +609,6 @@ h=sum<double>(f,g); ``` Leitura Adicional: -Uma referência atualizada da linguagem pode ser encontrada em -<http://cppreference.com/w/cpp> - -Uma fonte adicional pode ser encontrada em <http://cplusplus.com> +* Uma referência atualizada da linguagem pode ser encontrada em [CPP Reference](http://cppreference.com/w/cpp). +* Uma fonte adicional pode ser encontrada em [CPlusPlus](http://cplusplus.com). +* Um tutorial cobrindo o básico da linguagem e configurando o ambiente de codificação está disponível em [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/pt-br/cmake-pt.html.markdown b/pt-br/cmake-pt.html.markdown new file mode 100644 index 00000000..bc3e7050 --- /dev/null +++ b/pt-br/cmake-pt.html.markdown @@ -0,0 +1,178 @@ +--- +language: cmake +contributors: + - ["Bruno Alano", "https://github.com/brunoalano"] +filename: CMake +translators: + - ["Lucas Pugliesi", "https://github.com/fplucas"] +lang: pt-br +--- + +CMake é um programa de compilação open-source e multiplataforma. Essa ferramenta +permitirá testar, compilar e criar pacotes a partir do seu código fonte. + +O problema que o CMake tenta resolver são os problemas de configurar os Makefiles +e Autoconfigure (diferente dos interpretadores make que tem comandos diferentes) +e sua facilidade de uso envolvendo bibliotecas terceiras. + +CMake é um sistema open-source extensível que gerencia o processo de build em um +sistema operacional e um método independente de compilador. Diferente de sistemas +multiplataformas, CMake é designado a usar em conjunto ao ambiente de compilação +nativo. Seus simples arquivos de configuração localizados em seus diretórios +(chamados arquivos CMakeLists.txt) que são usados para gerar padrões de arquivos +de compilação (ex: makefiles no Unix e projetos em Windows MSVC) que são usados +de maneira simples. + +```cmake +# No CMake, isso é um comentário + +# Para rodar nosso código, iremos utilizar esses comandos: +# - mkdir build && cd build +# - cmake .. +# - make +# +# Com esses comandos, iremos seguir as melhores práticas para compilar em um +# subdiretório e na segunda linha pediremos ao CMake para gerar um novo Makefile +# independente de sistema operacional. E finalmente, rodar o comando make. + +#------------------------------------------------------------------------------ +# Básico +#------------------------------------------------------------------------------ +# +# O arquivo CMake deve ser chamado de "CMakeLists.txt". + +# Configura a versão mínima requerida do CMake para gerar o Makefile +cmake_minimum_required (VERSION 2.8) + +# Exibe FATAL_ERROR se a versão for menor que 2.8 +cmake_minimum_required (VERSION 2.8 FATAL_ERROR) + +# Configuramos o nome do nosso projeto. Mas antes disso, iremos alterar alguns +# diretórios em nome da convenção gerada pelo CMake. Podemos enviar a LANG do +# código como segundo parâmetro +project (learncmake C) + +# Configure o diretório do código do projeto (somente convenção) +set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} ) +set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} ) + +# Isso é muito útil para configurar a versão do nosso código no sistema de compilação +# usando um estilo `semver` +set (LEARN_CMAKE_VERSION_MAJOR 1) +set (LEARN_CMAKE_VERSION_MINOR 0) +set (LEARN_CMAKE_VERSION_PATCH 0) + +# Envie as variáveis (número da versão) para o cabeçalho de código-fonte +configure_file ( + "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in" + "${PROJECT_BINARY_DIR}/TutorialConfig.h" +) + +# Inclua Diretórios +# No GCC, isso irá invocar o comando "-I" +include_directories( include ) + +# Onde as bibliotecas adicionais estão instaladas? Nota: permite incluir o path +# aqui, na sequência as checagens irão resolver o resto +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Condições +if ( CONDICAO ) + # reposta! + + # Informação incidental + message(STATUS "Minha mensagem") + + # Aviso CMake, continua processando + message(WARNING "Minha mensagem") + + # Aviso (dev) CMake, continua processando + message(AUTHOR_WARNING "Minha mensagem") + + # Erro CMake, continua processando, mas pula a geração + message(SEND_ERROR "Minha mensagem") + + # Erro CMake, para o processamento e a geração + message(FATAL_ERROR "Minha mensagem") +endif() + +if( CONDICAO ) + +elseif( CONDICAO ) + +else( CONDICAO ) + +endif( CONDICAO ) + +# Loops +foreach(loop_var arg1 arg2 ...) + COMANDO1(ARGS ...) + COMANDO2(ARGS ...) + ... +endforeach(loop_var) + +foreach(loop_var RANGE total) +foreach(loop_var RANGE start stop [step]) + +foreach(loop_var IN [LISTS [list1 [...]]] + [ITEMS [item1 [...]]]) + +while(condicao) + COMANDO1(ARGS ...) + COMANDO2(ARGS ...) + ... +endwhile(condicao) + + +# Operações Lógicas +if(FALSE AND (FALSE OR TRUE)) + message("Não exiba!") +endif() + +# Configure um cache normal, ou uma variável de ambiente com o dado valor. +# Se a opção PARENT_SCOPE for informada em uma variável que será setada no escopo +# acima do escopo corrente. +# `set(<variavel> <valor>... [PARENT_SCOPE])` + +# Como refencia variáveis dentro de aspas ou não, argumentos com strings vazias +# não serão setados +${nome_da_variavel} + +# Listas +# Configure a lista de arquivos código-fonte +set( LEARN_CMAKE_SOURCES + src/main.c + src/imagem.c + src/pather.c +) + +# Chama o compilador +# +# ${PROJECT_NAME} referencia ao Learn_CMake +add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} ) + +# Linka as bibliotecas +target_link_libraries( ${PROJECT_NAME} ${LIBS} m ) + +# Onde as bibliotecas adicionais serão instaladas? Nota: nos permite incluir o path +# aqui, em seguida os testes irão resolver o restante +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Condição do compilador (gcc ; g++) +if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" ) + message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" ) + add_definitions( --std=c99 ) +endif() + +# Checa o Sistema Operacional +if( UNIX ) + set( LEARN_CMAKE_DEFINITIONS + "${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" ) +endif() +``` + +### Mais Recursos + ++ [cmake tutorial](https://cmake.org/cmake-tutorial/) ++ [cmake documentation](https://cmake.org/documentation/) ++ [mastering cmake](http://amzn.com/1930934319/) diff --git a/pt-br/cypher-pt.html.markdown b/pt-br/cypher-pt.html.markdown new file mode 100644 index 00000000..7cfd8dcd --- /dev/null +++ b/pt-br/cypher-pt.html.markdown @@ -0,0 +1,250 @@ +--- +language: cypher +filename: LearnCypher.cql +contributors: + - ["Théo Gauchoux", "https://github.com/TheoGauchoux"] + +lang: pt-br +--- + +O Cypher é a linguagem de consulta do Neo4j para manipular gráficos facilmente. Ela reutiliza a sintaxe do SQL e a mistura com o tipo de ascii-art para representar gráficos. Este tutorial pressupõe que você já conheça conceitos de gráficos como nós e relacionamentos. + +[Leia mais aqui.](https://neo4j.com/developer/cypher-query-language/) + + +Nós +--- + +**Representa um registro em um gráfico.** + +`()` +É um *nó* vazio, para indicar que existe um *nó*, mas não é relevante para a consulta. + +`(n)` +É um *nó* referido pela variável **n**, reutilizável na consulta. Começa com minúsculas e usa o camelCase. + +`(p:Person)` +Você pode adicionar um *label* ao seu nó, aqui **Person**. É como um tipo / uma classe / uma categoria. Começa com maiúsculas e usa o camelCase. + +`(p:Person:Manager)` +Um nó pode ter muitos *labels*. + +`(p:Person {name : 'Théo Gauchoux', age : 22})` +Um nó pode ter algumas *propriedades*, aqui **name** e **age**. Começa com minúsculas e usa o camelCase. + +Os tipos permitidos nas propriedades: + + - Numeric + - Boolean + - String + - Lista de tipos primitivos anteriores + +*Aviso: não há propriedade datetime no Cypher! Você pode usar String com um padrão específico ou um Numeric a partir de uma data específica.* + +`p.name` +Você pode acessar uma propriedade com o estilo de ponto. + + +Relacionamentos (ou Arestas) +--- + +**Conecta dois nós** + +`[:KNOWS]` +É um *relacionamento* com o *label* **KNOWS**. É um *label* como um rótulo do nó. Começa com maiúsculas e usa UPPER_SNAKE_CASE. + +`[k:KNOWS]` +O mesmo *relacionamento*, referido pela variável **k**, reutilizável na consulta, mas não é necessário. + +`[k:KNOWS {since:2017}]` +O mesmo *relacionamento*, com *propriedades* (como *nó*), aqui **since**. + +`[k:KNOWS*..4]` +É uma informação estrutural para usar em um *path* (visto posteriormente). Aqui, **\*..4** diz, “Corresponda o padrão, com a relação **k** que é repetida de 1 a 4 vezes. + + +Paths +--- + +**A maneira de misturar nós e relacionamentos.** + +`(a:Person)-[:KNOWS]-(b:Person)` +Um path descrevendo que **a** e **b** se conhecem. + +`(a:Person)-[:MANAGES]->(b:Person)` +Um path pode ser direcionado. Este path descreve que **a** é o gerente de **b**. + +`(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)` +Você pode encadear vários relacionamentos. Este path descreve o amigo de um amigo. + +`(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)` +Uma encadeamento também pode ser direcionada. Este path descreve que **a** é o chefe de **b** e o grande chefe de **c**. + +Padrões frequentemente usados (do Neo4j doc) : + +``` +// Amigo de um amigo +(user)-[:KNOWS]-(friend)-[:KNOWS]-(foaf) + +// Path mais curto +path = shortestPath( (user)-[:KNOWS*..5]-(other) ) + +// Filtragem colaborativa +(user)-[:PURCHASED]->(product)<-[:PURCHASED]-()-[:PURCHASED]->(otherProduct) + +// Navegação de árvore +(root)<-[:PARENT*]-(leaf:Category)-[:ITEM]->(data:Product) + +``` + + +Crie consultas +--- + +Create a new node +``` +CREATE (a:Person {name:"Théo Gauchoux"}) +RETURN a +``` +*`RETURN` permite ter um resultado após a consulta. Pode ser múltiplo, como `RETURN a, b`.* + +Crie um novo relacionamento (com 2 novos nós) +``` +CREATE (a:Person)-[k:KNOWS]-(b:Person) +RETURN a,k,b +``` + +Consultas que casam +--- + +Casam todos os nós +``` +MATCH (n) +RETURN n +``` + +Casam nós por label +``` +MATCH (a:Person) +RETURN a +``` + +Casam nós por label e propriedade +``` +MATCH (a:Person {name:"Théo Gauchoux"}) +RETURN a +``` + +Casam nós de acordo com os relacionamentos (não direcionados) +``` +MATCH (a)-[:KNOWS]-(b) +RETURN a,b +``` + +Casam nós de acordo com os relacionamentos (direcionados) +``` +MATCH (a)-[:MANAGES]->(b) +RETURN a,b +``` + +Casam nós com um cláusula `WHERE` +``` +MATCH (p:Person {name:"Théo Gauchoux"})-[s:LIVES_IN]->(city:City) +WHERE s.since = 2015 +RETURN p,state +``` + +Você pode usa a cláusula `MATCH WHERE` com a cláusula `CREATE` +``` +MATCH (a), (b) +WHERE a.name = "Jacquie" AND b.name = "Michel" +CREATE (a)-[:KNOWS]-(b) +``` + + +Atualizar consultas +--- + +Atualizar uma propriedade específica de um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p.age = 23 +``` + +Substituir todas as propriedades de um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p = {name: "Michel", age: 23} +``` + +Adicionar nova propriedade a um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p + = {studies: "IT Engineering"} +``` + +Adicione um label a um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p:Internship +``` + + +Excluir consultas +--- + +Excluir um nó específico (os relacionamentos vinculados devem ser excluídos antes) +``` +MATCH (p:Person)-[relationship]-() +WHERE p.name = "Théo Gauchoux" +DELETE relationship, p +``` + +Remover uma propriedade em um nó específico +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +REMOVE p.age +``` +*Prestar atenção à palavra chave `REMOVE`, não é `DELETE` !* + +Remover um label de um nó específico +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +DELETE p:Person +``` + +Excluir o banco de dados inteiro +``` +MATCH (n) +OPTIONAL MATCH (n)-[r]-() +DELETE n, r +``` +*Sério, é o `rm -rf /` do Cypher !* + + +Outras cláusulas úteis +--- + +`PROFILE` +Antes de uma consulta, mostre o plano de execução dela. + +`COUNT(e)` +Contar entidades (nós ou relacionamentos) que casam com **e**. + +`LIMIT x` +Limite o resultado aos primeiros x resultados. + + +Dicas Especiais +--- + +- Há apenas comentários de uma linha no Cypher, com barras duplas : // Comentários +- Você pode executar um script Cypher armazenado em um arquivo **.cql** diretamente no Neo4j (é uma importação). No entanto, você não pode ter várias instruções neste arquivo (separadas por **;**). +- Use o shell Neo4j para escrever Cypher, é realmente incrível. +- O Cypher será a linguagem de consulta padrão para todos os bancos de dados de gráficos (conhecidos como **OpenCypher**). diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 84b055d9..518660a3 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -63,13 +63,11 @@ grafo acíclico dirigido. ``` ## Alguns Problemas Famosos de Programação Dinâmica -``` -Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code - -Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence -``` +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() + ## Recursos Online (EN) diff --git a/pt-br/factor-pt.html.markdown b/pt-br/factor-pt.html.markdown new file mode 100644 index 00000000..e3c8f4a9 --- /dev/null +++ b/pt-br/factor-pt.html.markdown @@ -0,0 +1,184 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor + +lang: pt-br +--- + +Factor é uma linguagem moderna baseada em pilha, baseado em Forth, criada por Slava Pestov. + +Código neste arquivo pode ser digitado em Fator, mas não importado diretamente porque o cabeçalho de vocabulário e importação faria o início completamente confuso. + +```factor +! Este é um comentário + +! Como Forth, toda a programação é feita manipulando a pilha. +! A indicação de um valor literal o coloca na pilha. +5 2 3 56 76 23 65 ! Nenhuma saída, mas a pilha é impressa no modo interativo + +! Esses números são adicionados à pilha, da esquerda para a direita. +! .s imprime a pilha de forma não destrutiva. +.s ! 5 2 3 56 76 23 65 + +! A aritmética funciona manipulando dados na pilha. +5 4 + ! Sem saída + +! `.` mostra o resultado superior da pilha e o imprime. +. ! 9 + +! Mais exemplos de aritmética: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! Várias palavras são fornecidas para manipular a pilha, coletivamente conhecidas como palavras embaralhadas. + +3 dup - ! duplica o primeiro item (1st agora igual a 2nd): 3 - 3 +2 5 swap / ! troca o primeiro com o segundo elemento: 5 / 2 +4 0 drop 2 / ! remove o primeiro item (não imprima na tela): 4 / 2 +1 2 3 nip .s ! remove o segundo item (semelhante a drop): 1 3 +1 2 clear .s ! acaba com toda a pilha +1 2 3 4 over .s ! duplica o segundo item para o topo: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplica o terceiro item para o topo: 1 2 3 4 2 3 + +! Criando Palavras +! O `:` conjuntos de palavras do Factor no modo de compilação até que ela veja a palavra `;`. +: square ( n -- n ) dup * ; ! Sem saída +5 square . ! 25 + +! Podemos ver o que as palavra fazem também. +! \ suprime a avaliação de uma palavra e coloca seu identificador na pilha. +\ square see ! : square ( n -- n ) dup * ; + +! Após o nome da palavra para criar, a declaração entre parênteses dá o efeito da pilha. +! Podemos usar os nomes que quisermos dentro da declaração: +: weirdsquare ( camel -- llama ) dup * ; + +! Contanto que sua contagem corresponda ao efeito da pilha da palavra: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Além disso Ok + +! Onde Factor difere do Forth é no uso de citações. +! Uma citação é um bloco de código que é colocado na pilha como um valor. +! [ inicia o modo de citação; ] termina. +[ 2 + ] ! A citação que adiciona 2 é deixada na pilha +4 swap call . ! 6 + +! E assim, palavras de ordem mais alta. TONS de palavras de ordem superior. +2 3 [ 2 + ] dip .s ! Retira valor do topo da pilha, execute citação, empurre de volta: 4 3 +3 4 [ + ] keep .s ! Copie o valor do topo da pilha, execute a citação, envie a cópia: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Executar cada citação no valor do topo, empurrar os dois resultados: 3 4 +4 3 1 [ + ] [ + ] bi .s ! As citações em um bi podem extrair valores mais profundos da pilha: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Executar a citação no primeiro e segundo valores +2 [ + ] curry ! Injeta o valor fornecido no início da citação: [ 2 + ] é deixado na pilha + +! Condicionais +! Qualquer valor é verdadeiro, exceto o valor interno f. +! m valor interno não existe, mas seu uso não é essencial. +! Condicionais são palavras de maior ordem, como com os combinadores acima. + +5 [ "Five is true" . ] when ! Cinco é verdadeiro +0 [ "Zero is true" . ] when ! Zero é verdadeiro +f [ "F is true" . ] when ! Sem saída +f [ "F is false" . ] unless ! F é falso +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two é verdadeiro + +! Por padrão, as condicionais consomem o valor em teste, mas variantes com asterisco +! deixe sozinho se é verdadeiro: + +5 [ . ] when* ! 5 +f [ . ] when* ! Nenhuma saída, pilha vazia, f é consumida porque é falsa + + +! Laços +! Você adivinhou .. estas são palavras de ordem mais elevada também. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Aqui está uma lista: +{ 2 4 6 8 } [ 1 + . ] each ! Exibe 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Sai { 3 5 7 9 } na pilha + +! Reduzir laços ou criar listas: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Mantém apenas membros da lista para os quais a citação é verdadeira: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Como "fold" em linguagens funcionais: exibe 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Como reduzir, mas mantém os valores intermediários em uma lista: exibe { 0 2 6 12 } então 20 +1 5 [ 2 * dup ] replicate . ! Repete a citação 5 vezes e coleta os resultados em uma lista: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Repete a segunda citação até que a primeira retorne como falsa e colete os resultados: { 2 4 8 16 32 64 128 } + +! Se tudo mais falhar, uma finalidade geral, enquanto repete: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Exibe "Hello" 10 vezes + ! Sim, é difícil de ler + ! Isso é o que todos esses loops variantes são para + +! Variáveis +! Normalmente, espera-se que os programas Factor mantenham todos os dados na pilha. +! Usar variáveis nomeadas torna a refatoração mais difícil (e é chamada de Factor por um motivo) +! Variáveis globais, se você precisar: + +SYMBOL: name ! Cria o nome como uma palavra identificadora +"Bob" name set-global ! Sem saída +name get-global . ! "Bob" + +! Variáveis locais nomeadas são consideradas uma extensão, mas estão disponíveis +! Em uma citação .. +[| m n ! A citação captura os dois principais valores da pilha em m e n + | m n + ] ! Leia-os + +! Ou em uma palavra.. +:: lword ( -- ) ! Note os dois pontos duplos para invocar a extensão da variável lexica + 2 :> c ! Declara a variável imutável c para manter 2 + c . ; ! Imprima isso + +! Em uma palavra declarada dessa maneira, o lado de entrada da declaração de pilha +! torna-se significativo e fornece os valores das variáveis em que os valores da pilha são capturados +:: double ( a -- result ) a 2 * ; + +! Variáveis são declaradas mutáveis ao terminar seu nome com um ponto de exclamação +:: mword2 ( a! -- x y ) ! Capture o topo da pilha na variável mutável a + a ! Empurrar a + a 2 * a! ! Multiplique por 2 e armazene o resultado em a + a ; ! Empurre novo valor de a +5 mword2 ! Pilha: 5 10 + +! Listas e Sequências +! Vimos acima como empurrar uma lista para a pilha + +0 { 1 2 3 4 } nth ! Acessar um membro específico de uma lista: 1 +10 { 1 2 3 4 } nth ! Error: índice de sequência fora dos limites +1 { 1 2 3 4 } ?nth ! O mesmo que nth se o índice estiver dentro dos limites: 2 +10 { 1 2 3 4 } ?nth ! Nenhum erro se estiver fora dos limites: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! E se você quiser obter meta, as citações são seqüências e podem ser desmontadas.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Pronto para mais? + +* [Documentação do Factor](http://docs.factorcode.org/content/article-help.home.html) diff --git a/pt-br/html-pt.html.markdown b/pt-br/html-pt.html.markdown new file mode 100644 index 00000000..5a4bc3bc --- /dev/null +++ b/pt-br/html-pt.html.markdown @@ -0,0 +1,125 @@ +--- +language: html +filename: learnhtml.txt +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] +lang: pt-br +--- + +HTML é um acrônimo de HyperText Markup Language(Linguagem de Marcação de HiperTexto). +É uma linguagem que nos permite escrever páginas para a "world wide web". +É uma linguagem de marcação, nos permite escrever páginas na web usando código +para indicar como o texto e os dados serão ser exibidos. +De fato, arquivos HTML são simples arquivos de texto. +O que seria marcação? É um método de organização dos dados da página envolvidos +por abertura e fechamento de tags. +Essa marcação serve para dar significado ao texto que envolve. +Assim como outras linguagens, o HTML tem diversas versões. Aqui falaremos sobre o HTML5. + +**NOTA :** Você pode testar diferentes tags e elementos conforme progride os +tutoriais em sites como [codepen](http://codepen.io/pen/) podendo ver seus efeitos, +entendendo como funcionam e se familiarizando com a linguagem. +Esse artigo tem seu foco principal na sintaxe do HTML e algumas dicas úteis. + + +```html +<!-- Comentários são envolvidos conforme essa linha! --> + +<!-- #################### As Tags #################### --> + +<!-- Aqui está um exemplo de arquivo HTML que iremos analisar. --> + +<!doctype html> + <html> + <head> + <title>Meu Site</title> + </head> + <body> + <h1>Olá, mundo!</h1> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Venha ver como isso aparece</a> + <p>Esse é um parágrafo.</p> + <p>Esse é um outro parágrafo.</p> + <ul> + <li>Esse é um item de uma lista não enumerada (bullet list)</li> + <li>Esse é um outro item</li> + <li>E esse é o último item da lista</li> + </ul> + </body> + </html> + +<!-- Um arquivo HTML sempre inicia indicando ao navegador que é uma página HTML. --> +<!doctype html> + +<!-- Após isso, inicia abrindo a tag <html>. --> +<html> + +<!-- Essa tag deverá ser fechada ao final do arquivo com </html>. --> +</html> + +<!-- Não deverá haver nada após o fechamento desta tag. --> + +<!-- Entre a abertura e o fechamento das tags <html></html>, nós encontramos: --> + +<!-- Um cabeçalho definido por <head> (deverá ser fechado com </head>). --> +<!-- O cabeçalho contém uma descrição e algumas informações adicionais que não serão exibidas; chamam-se metadados. --> + +<head> + <title>Meu Site</title><!-- Essa tag <title> indica ao navegador o título a ser exibido na barra de títulos e no nome da aba. --> +</head> + +<!-- Após a seção <head>, nós encontramos a tag - <body> --> +<!-- Até esse ponto, nada descrito irá aparecer na janela do browser. --> +<!-- Nós deveremos preencher o body(corpo) com o conteúdo a ser exibido. --> + +<body> + <h1>Olá, mundo!</h1> <!-- A tag h1 cria um título. --> + <!-- Há também subtítulos do <h1>, o mais importante, aos mais precisos (h6). --> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Venha ver o que isso exibe</a> <!-- Um hiperlink ao endereço preenchido no atributo href="" --> + <p>Esse é um parágrafo.</p> <!-- A tag <p> permite incluir um texto na página. --> + <p>Esse é um outro parágrafo.</p> + <ul> <!-- A tag <ul> cria uma lista de marcação. --> + <!-- Para criar uma lista ordenada, devemos usar <ol>, exibindo 1. para o primeiro elemento, 2. para o segundo, etc. --> + <li>Esse é um item de uma lista não-enumerada.</li> + <li>Esse é um outro item</li> + <li>E esse é o último item da lista</li> + </ul> +</body> + +<!-- E é isso, criar um arquivo HTML pode ser bem simples. --> + +<!-- Também é possível adicionar alguns outros tipos de tags HTML. --> + +<!-- Para inserir uma imagem. --> +<img src="http://i.imgur.com/XWG0O.gif"/> <!-- O caminho da imagem deve ser indicado usando o atributo src="" --> +<!-- O caminho da imagem pode ser uma URL ou até mesmo o caminho do arquivo no seu computador. --> + +<!-- Também é possível criar uma tabela. --> + +<table> <!-- Iniciamos a tabela com a tag <table>. --> + <tr> <!-- <tr> nos permite criar uma linha. --> + <th>Primeiro cabeçalho</th> <!-- <th> nos permite criar o título de uma coluna. --> + <th>Segundo cabeçalho</th> + </tr> + <tr> + <td>Primeira linha, primeira coluna</td> <!-- <td> nos permite criar uma célula da tabela. --> + <td>Primeira linha, segunda coluna</td> + </tr> + <tr> + <td>Segunda linha, primeira coluna</td> + <td>Segunda linha, segunda coluna</td> + </tr> +</table> + +``` + +## Uso + +HTML é escrito em arquivos com a extensão `.html` ou `.htm`. Seu mime type é `text/html`. + +## Para aprender mais + +* [wikipedia](https://en.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) diff --git a/pt-br/less-pt.html.markdown b/pt-br/less-pt.html.markdown new file mode 100644 index 00000000..679a2ed2 --- /dev/null +++ b/pt-br/less-pt.html.markdown @@ -0,0 +1,390 @@ +--- +language: less +filename: learnless.less +contributors: + - ["Saravanan Ganesh", "http://srrvnn.me"] + +lang: pt-br +--- + +Less é um pré-processador de CSS, que adiciona recursos como variáveis, aninhamento, mixins e muito mais. +Less (e outros pré-processadores, como o [Sass](http://sass-lang.com/)) ajudam os desenvolvedores a escreverem código que pode ser mantido e DRY (não se repita). + +```css + + +//Comentários de linha única são removidos quando Less é compilado para CSS. + +/*Comentários de várias linhas são preservados.*/ + + + +/* Variáveis +==============================*/ + + +/* Você pode armazenar um valor de CSS (como uma cor) em uma variável. + Use o símbolo '@' para criar uma variável. */ + +@primary-color: #a3a4ff; +@secondary-color: #51527f; +@body-font: 'Roboto', sans-serif; + +/* Você pode usar as variáveis em toda a sua folha de estilo. + Agora, se você quiser alterar uma cor, só precisa fazer a alteração uma vez. */ + +body { + background-color: @primary-color; + color: @secondary-color; + font-family: @body-font; +} + +/* Isso compilará para: */ + +body { + background-color: #a3a4ff; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Isso é muito mais sustentável do que ter que mudar a cor + cada vez que aparece em toda a sua folha de estilo. */ + + + +/* Mixins +==============================*/ + + +/* Se você achar que está escrevendo o mesmo código para mais de um + elemento, você pode querer reutilizá-lo facilmente. */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Você pode usar o mixin simplesmente adicionando o seletor como um estilo. */ + +div { + .center; + background-color: @primary-color; +} + +/* Que compilaria para: */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + +/* Você pode omitir o código mixin de ser compilado adicionando parênteses + depois do seletor. */ + +.center() { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +div { + .center; + background-color: @primary-color; +} + +/* Que compilaria para: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + + + +/* Aninhamento +==============================*/ + + +/* Less permite aninhar seletores nos seletores. */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #f00; + } +} + +/* '&' será substituído pelo seletor pai. */ +/* Você também pode aninhar pseudo-classes. */ +/* Tenha em mente que o aninhamento excessivo tornará seu código menos sustentável. + As melhores práticas recomendam não ultrapassar 3 níveis de profundidade ao aninhar. + Por exemplo: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compila para: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Functions +==============================*/ + + +/* Less fornece funções que podem ser usadas para realizar uma variedade de + tarefas. Considere o seguinte: */ + +/* Funções podem ser invocadas usando seu nome e passando os + argumentos requeridos. */ + +body { + width: round(10.25px); +} + +.header { + background-color: lighten(#000, 0.5); +} + +.footer { + background-color: fadeout(#000, 0.25) +} + +/* Compila para: */ + +body { + width: 10px; +} + +.header { + background-color: #010101; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Você também pode definir suas próprias funções. Funções são muito semelhantes às + mixins. Ao tentar escolher entre uma função ou a um mixin, lembre-se + que mixins são melhores para gerar CSS, enquanto as funções são melhores para + lógica que pode ser usada em todo o seu código Less. Os exemplos na + seção 'Operadores Matemáticos' são candidatos ideais para se tornarem funções reutilizáveis. */ + +/* Esta função calcula a média de dois números: */ + +.average(@x, @y) { + @average-result: ((@x + @y) / 2); +} + +div { + .average(16px, 50px); // "chama" o mixin + padding: @average-result; // use seu valor de "retorno" +} + +/* Compila para: */ + +div { + padding: 33px; +} + + + +/* Estender (herança) +==============================*/ + + +/* Estender é uma maneira de compartilhar as propriedades de um seletor com outro. */ + +.display { + height: 50px; +} + +.display-success { + &:extend(.display); + border-color: #22df56; +} + +/* Compila para: */ + +.display, +.display-success { + height: 50px; +} +.display-success { + border-color: #22df56; +} + +/* Estender uma instrução CSS é preferível para criar um mixin + por causa da maneira como agrupa as classes que compartilham + o mesmo estilo base. Se isso foi feito com um mixin, as propriedades + seriam duplicadas para cada declaração que + chamou o mixin. Embora isso não afete o seu fluxo de trabalho, + adicione o inchaço desnecessário aos arquivos criados pelo compilador Less. */ + + + +/* Parciais e Importações +==============================*/ + + +/* Less permite criar arquivos parciais. Isso pode ajudar a manter o seu + código Less modularizado. Arquivos parciais convencionalmente começam com um '_', + por exemplo. _reset.less. e são importados para um arquivo less principal que recebe + o css compilado. */ + +/* Considere o seguinte CSS que vamos colocar em um arquivo chamado _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Less disponibiliza @import que podem ser usadas para importar parciais em um arquivo. + Isso difere da declaração tradicional CSS @import que faz + outra solicitação HTTP para buscar o arquivo importado. Less leva o + arquivo importado e combina com o código compilado. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compila para: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Operações Matemáticas +==============================*/ + + +/* Less fornece os seguintes operadores: +, -, *, / e %. Estes podem + ser úteis para calcular valores diretamente nos seus arquivos Less + para usar valores que você já calculou manualmente. Abaixo está um exemplo + de como configurar um design simples de duas colunas. */ + +@content-area: 960px; +@main-content: 600px; +@sidebar-content: 300px; + +@main-size: @main-content / @content-area * 100%; +@sidebar-size: @sidebar-content / @content-area * 100%; +@gutter: 100% - (@main-size + @sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: @main-size; +} + +.sidebar { + width: @sidebar-size; +} + +.gutter { + width: @gutter; +} + +/* Compila para: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + +## Pratique Less + +Se você quiser praticar com Less no seu navegador, confira: * [Codepen](http://codepen.io/) * [LESS2CSS](http://lesscss.org/less-preview/) + +## Compatibilidade + +Less pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo em CSS. Você deseja verificar +se o CSS que você está usando é compatível com seus navegadores de destino. + +[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificar a compatibilidade. + +## Leitura adicional +* [Documentação Oficial](http://lesscss.org/features/) +* [Less CSS - Guia do iniciante](http://www.hongkiat.com/blog/less-basic/) diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown new file mode 100644 index 00000000..8e7603cc --- /dev/null +++ b/pt-br/make-pt.html.markdown @@ -0,0 +1,242 @@ +---
+language: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+ - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
+filename: Makefile
+
+lang: pt-br
+---
+
+Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas.
+
+Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux.
+
+```make
+
+# Comentários podem ser escritos assim.
+
+# O arquivo deve ser nomeado Makefile e então pode ser executado como `make <alvo>`.
+# Caso contrário, nós usamos `make -f "nome-do-arquivo" <alvo>`.
+
+# Aviso - use somente TABS para identar em Makefiles, nunca espaços!
+
+#-----------------------------------------------------------------------
+# Noções básicas
+#-----------------------------------------------------------------------
+
+# Regras são do formato
+# alvo: <pré-requisito>
+# onde os pré-requisitos são opcionais.
+
+# Uma regra - esta regra só será executada se o arquivo0.txt não existir.
+arquivo0.txt:
+ echo "foo" > arquivo0.txt
+ # Mesmo os comentários nestas seções da 'receita' são passados para o shell.
+ # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão.
+
+# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt.
+arquivo1.txt: arquivo0.txt
+ cat arquivo0.txt > arquivo1.txt
+ # se as mesmas regras de citação do shell.
+ @cat arquivo0.txt >> arquivo1.txt
+ # @ pára o comando de ser ecoado para stdout.
+ -@echo 'hello'
+ # - significa que make continuará em caso de erro.
+ # Experimentar `make arquivo1.txt` na linha de comando.
+
+# Uma regra pode ter vários alvos e vários pré-requisitos
+arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt
+ touch arquivo2.txt
+ touch arquivo3.txt
+
+# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar
+# receitas não contam e podem ser usadas para adicionar novas dependências.
+
+#-----------------------------------------------------------------------
+# Alvos falsos
+#-----------------------------------------------------------------------
+
+# Um alvo falso. Qualquer alvo que não seja um arquivo.
+# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo.
+all: maker process
+
+# Podemos declarar as coisas fora de ordem.
+maker:
+ touch ex0.txt ex1.txt
+
+# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome
+.PHONY: all maker process
+# Este é um alvo especial. Existem vários outros.
+
+# Uma regra com dependência de um alvo falso sempre será executada
+ex0.txt ex1.txt: maker
+
+# Alvos falsos comuns são: todos fazem instalação limpa ...
+
+#-----------------------------------------------------------------------
+# Variáveis Automáticas e Curingas
+#-----------------------------------------------------------------------
+
+process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos
+ @echo $^ # $^ é uma variável que contém a lista de pré-requisitos
+ @echo $@ # imprime o nome do alvo
+ #(fpara várias regras alvo, $@ é o que causou a execução da regra)
+ @echo $< # o primeiro pré-requisito listado
+ @echo $? # somente as dependências que estão desatualizadas
+ @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal)
+ #@echo $| # todos os pré-requisitos 'somente pedidos'
+
+# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los
+process: ex1.txt arquivo0.txt
+# ex1.txt será encontrado, mas arquivo0.txt será desduplicado.
+
+#-----------------------------------------------------------------------
+# Padrões
+#-----------------------------------------------------------------------
+
+# Pode ensinar make a converter certos arquivos em outros arquivos.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# As regras padrões só farão qualquer coisa se decidirem criar o alvo.
+
+# Os caminhos de diretório são normalmente ignorados quando as regras de
+# padrões são correspondentes. Mas make tentará usar a regra mais
+# apropriada disponível.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# make utilizará a última versão para uma regra de padrão que encontrar.
+%.png: %.svg
+ @echo esta regra é escolhida
+
+# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo
+%.png: %.ps
+ @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes
+
+# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe
+# como transformar arquivos *.c em arquivos *.o.
+
+# Makefiles antigos podem usar regras de sufixo em vez de regras padrões
+.png.ps:
+ @echo essa regra é semelhante a uma regra de padrão.
+
+# make sobre a regra de sufixo
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variáveis
+#-----------------------------------------------------------------------
+# aka. macros
+
+# As variáveis são basicamente todos os tipos de string
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # Isso não funcionará, tratado como $ (n)ame.
+ @echo $(name3) # Variáveis desconhecidas são tratadas como strings vazias.
+
+# Existem 4 lugares para definir variáveis.
+# Em ordem de prioridade, do maior para o menor:
+# 1: argumentos de linha de comando
+# 2: Makefile
+# 3: variáveis de ambiente do shell - faça importações automaticamente.
+# 4: make tem algumas variáveis predefinidas
+
+name4 ?= Jean
+# Somente defina a variável se a variável de ambiente ainda não estiver definida.
+
+override name5 = David
+# Pára os argumentos da linha de comando de alterar essa variável.
+
+name4 +=grey
+# Anexar valores à variável (inclui um espaço).
+
+# Valores variáveis específicos de padrões (extensão GNU).
+echo: name2 = Sara # Verdadeiro dentro da regra de correspondência
+ # e também dentro de suas recursivas dependências
+ # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!)
+
+# Algumas variáveis definidas automaticamente pelo make
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX}
+ echo $(FC)
+ echo ${CFLAGS}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variáveis 2
+#-----------------------------------------------------------------------
+
+# O primeiro tipo de variáveis é avaliado a cada vez que elas são usadas.
+# TIsso pode ser caro, então existe um segundo tipo de variável que é
+# avaliado apenas uma vez. (Esta é uma extensão do GNU make)
+
+var := hello
+var2 ::= $(var) hello
+#:= e ::= são equivalentes.
+
+# Essas variáveis são avaliadas procedimentalmente (na ordem em que
+# aparecem), quebrando assim o resto da línguagem!
+
+# Isso não funciona
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Funções
+#-----------------------------------------------------------------------
+
+# make tem muitas funções disponíveis.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# O formato é $(func arg0,arg1,arg2...)
+
+# Alguns exemplos
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Diretivas
+#-----------------------------------------------------------------------
+
+# Inclua outros makefiles, úteis para código específico da plataforma
+include foo.mk
+
+sport = tennis
+# Compilação condicional
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# Há também ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+### More Resources
+
++ [documentação gnu make](https://www.gnu.org/software/make/manual/)
++ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/)
++ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
diff --git a/python3.html.markdown b/python3.html.markdown index b378a8c6..7683bc60 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -139,9 +139,11 @@ len("This is a string") # => 16 # still use the old style of formatting: "%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" -# You can also format using f-strings or formatted string literals +# You can also format using f-strings or formatted string literals (in Python 3.6+) name = "Reiko" f"She said her name is {name}." # => "She said her name is Reiko" +# You can basically put any Python statement inside the braces and it will be output in the string. +f"{name} is {len(name)} characters long." # None is an object diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 2440d859..4cff3535 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -146,7 +146,7 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") """ # load some data on Holy Roman Emperors -url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +url = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/hre.csv" r = requests.get(url) fp = "hre.csv" with open(fp, "wb") as f: @@ -156,26 +156,19 @@ hre = pd.read_csv(fp) hre.head() """ - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN + Ix Dynasty Name Birth Death +0 NaN Carolingian Charles I 2 April 742 28 January 814 +1 NaN Carolingian Louis I 778 20 June 840 +2 NaN Carolingian Lothair I 795 29 September 855 +3 NaN Carolingian Louis II 825 12 August 875 +4 NaN Carolingian Charles II 13 June 823 6 October 877 + + Coronation 1 Coronation 2 Ceased to be Emperor +0 25 December 800 NaN 28 January 814 +1 11 September 813 5 October 816 20 June 840 +2 5 April 823 NaN 29 September 855 +3 Easter 850 18 May 872 12 August 875 +4 29 December 875 NaN 6 October 877 """ # clean the Birth and Death columns @@ -193,6 +186,8 @@ rx = re.compile(r'\d+$') # match trailing digits - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html """ +from functools import reduce + def extractYear(v): return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int)) diff --git a/rst.html.markdown b/rst.html.markdown index fbf9a069..01595fe4 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -47,7 +47,7 @@ Title are underlined with equals signs too Subtitles with dashes --------------------- -You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``: ``print()``. +You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``. Lists are as simple as in Markdown: @@ -70,7 +70,7 @@ France Paris Japan Tokyo =========== ======== -More complex tabless can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) +More complex tables can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) There are multiple ways to make links: diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index b9704fc3..35994749 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -886,7 +886,6 @@ v.swap(vector<Foo>()); ``` ## Дальнейшее чтение: -Наиболее полное и обновленное руководство по С++ можно найти на -<http://cppreference.com/w/cpp> - -Дополнительные ресурсы могут быть найдены на <http://cplusplus.com> +* Наиболее полное и обновленное руководство по С++ можно найти на [CPP Reference](http://cppreference.com/w/cpp). +* Дополнительные ресурсы могут быть найдены на [CPlusPlus](http://cplusplus.com). +* Учебник, посвященный основам языка и настройке среды кодирования, доступен в [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/ru-ru/crystal-ru.html.markdown b/ru-ru/crystal-ru.html.markdown new file mode 100644 index 00000000..87d12f23 --- /dev/null +++ b/ru-ru/crystal-ru.html.markdown @@ -0,0 +1,584 @@ +--- +language: crystal +filename: learncrystal-ru.cr +contributors: + - ["Vitalii Elenhaupt", "http://veelenga.com"] + - ["Arnaud Fernandés", "https://github.com/TechMagister/"] +translators: + - ["Den Patin", "https://github.com/denpatin"] +lang: ru-ru +--- + +```crystal +# — так начинается комментарий + + +# Всё является объектом +nil.class #=> Nil +100.class #=> Int32 +true.class #=> Bool + +# Возвращают false только nil, false и пустые указатели +!nil #=> true : Bool +!false #=> true : Bool +!0 #=> false : Bool + + +# Целые числа + +1.class #=> Int32 + +# Четыре типа целых чисел со знаком +1_i8.class #=> Int8 +1_i16.class #=> Int16 +1_i32.class #=> Int32 +1_i64.class #=> Int64 + +# Четыре типа целых чисел без знака +1_u8.class #=> UInt8 +1_u16.class #=> UInt16 +1_u32.class #=> UInt32 +1_u64.class #=> UInt64 + +2147483648.class #=> Int64 +9223372036854775808.class #=> UInt64 + +# Двоичные числа +0b1101 #=> 13 : Int32 + +# Восьмеричные числа +0o123 #=> 83 : Int32 + +# Шестнадцатеричные числа +0xFE012D #=> 16646445 : Int32 +0xfe012d #=> 16646445 : Int32 + +# Числа с плавающей точкой + +1.0.class #=> Float64 + +# Два типа чисел с плавающей запятой +1.0_f32.class #=> Float32 +1_f32.class #=> Float32 + +1e10.class #=> Float64 +1.5e10.class #=> Float64 +1.5e-7.class #=> Float64 + + +# Символьные литералы + +'a'.class #=> Char + +# Восьмеричный код символа +'\101' #=> 'A' : Char + +# Код символа Unicode +'\u0041' #=> 'A' : Char + + +# Строки + +"s".class #=> String + +# Строки неизменяемы +s = "hello, " #=> "hello, " : String +s.object_id #=> 134667712 : UInt64 +s += "Crystal" #=> "hello, Crystal" : String +s.object_id #=> 142528472 : UInt64 + +# Поддерживается интерполяция строк +"sum = #{1 + 2}" #=> "sum = 3" : String + +# Поддерживается многострочность +"This is + multiline string" + +# Строка с двойными кавычками +%(hello "world") #=> "hello \"world\"" + + +# Символы — константы без значения, определяемые только именем. Часто +# используются вместо часто используемых строк для лучшей производительности. +# На внутреннем уровне они представлены как Int32. + +:symbol.class #=> Symbol + +sentence = :question? # :"question?" : Symbol + +sentence == :question? #=> true : Bool +sentence == :exclamation! #=> false : Bool +sentence == "question?" #=> false : Bool + + +# Массивы + +[1, 2, 3].class #=> Array(Int32) +[1, "hello", 'x'].class #=> Array(Int32 | String | Char) + +# При объявлении пустого массива необходимо указать тип его элементов +[] # Syntax error: for empty arrays use '[] of ElementType' +[] of Int32 #=> [] : Array(Int32) +Array(Int32).new #=> [] : Array(Int32) + +# Элементы внутри массива имеют свои индексы +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] : Array(Int32) +array[0] #=> 1 : Int32 +array[10] # raises IndexError +array[-6] # raises IndexError +array[10]? #=> nil : (Int32 | Nil) +array[-6]? #=> nil : (Int32 | Nil) + +# Можно получать элементы по индексу с конца +array[-1] #=> 5 + +# С начала и с указанием размера итогового массива +array[2, 3] #=> [3, 4, 5] + +# Или посредством указания диапазона +array[1..3] #=> [2, 3, 4] + +# Добавление в массив +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Удаление элемента из конца массива +array.pop #=> 6 +array #=> [1, 2, 3, 4, 5] + +# Удаление элемента из начала массива +array.shift #=> 1 +array #=> [2, 3, 4, 5] + +# Проверка на наличие элемента в массиве +array.includes? 3 #=> true + +# Синтаксический сахар для массива строк и символов +%w(one two three) #=> ["one", "two", "three"] : Array(String) +%i(one two three) #=> [:one, :two, :three] : Array(Symbol) + +# Массивоподобный синтаксис используется и для других типов, только если для +# них определены методы .new и #<< +set = Set{1, 2, 3} #=> [1, 2, 3] +set.class #=> Set(Int32) + +# Вышеприведенное эквивалентно следующему +set = Set(typeof(1, 2, 3)).new +set << 1 +set << 2 +set << 3 + + +# Хэши + +{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32) +{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32) + +# При объявлении пустого хэша необходимо указать типы ключа и значения +{} # Syntax error +{} of Int32 => Int32 # {} +Hash(Int32, Int32).new # {} + +# Значения в хэше легко найти по ключу +hash = {"color" => "green", "number" => 5} +hash["color"] #=> "green" +hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError) +hash["no_such_key"]? #=> nil + +# Проверка наличия ключа в хэше +hash.has_key? "color" #=> true + +# Синтаксический сахар для символьных и строковых ключей +{key1: 'a', key2: 'b'} # {:key1 => 'a', :key2 => 'b'} +{"key1": 'a', "key2": 'b'} # {"key1" => 'a', "key2" => 'b'} + +# Хэшеподобный синтаксис используется и для других типов, только если для них +# определены методы .new и #[]= +class MyType + def []=(key, value) + puts "do stuff" + end +end + +MyType{"foo" => "bar"} + +# Вышеприведенное эквивалентно следующему +tmp = MyType.new +tmp["foo"] = "bar" +tmp + + +# Диапазоны + +1..10 #=> Range(Int32, Int32) +Range.new(1, 10).class #=> Range(Int32, Int32) + +# Включающий и исключающий диапазоны +(3..5).to_a #=> [3, 4, 5] +(3...5).to_a #=> [3, 4] + +# Проверка на вхождение в диапазон +(1..8).includes? 2 #=> true + + +# Кортежи +# Неизменяемые последовательности фиксированного размера, содержащие, +# как правило, элементы разных типов + +{1, "hello", 'x'}.class #=> Tuple(Int32, String, Char) + +# Доступ к элементам осуществляется по индексу +tuple = {:key1, :key2} +tuple[1] #=> :key2 +tuple[2] #=> syntax error : Index out of bound + +# Элементы кортежей можно попарно присвоить переменным +a, b, c = {:a, 'b', "c"} +a #=> :a +b #=> 'b' +c #=> "c" + + +# Процедуры +# Указатели на функцию с необязательным содержимым (замыкание). +# Обычно создаётся с помощью специального литерала -> + +proc = ->(x : Int32) { x.to_s } +proc.class # Proc(Int32, String) +# Или посредством метода .new +Proc(Int32, String).new { |x| x.to_s } + +# Вызываются посредством метода .call +proc.call 10 #=> "10" + + +# Управляющие операторы + +if true + "if statement" +elsif false + "else-if, optional" +else + "else, also optional" +end + +puts "if as a suffix" if true + +# if как часть выражения +a = if 2 > 1 + 3 + else + 4 + end + +a #=> 3 + +# Тернарный if +a = 1 > 2 ? 3 : 4 #=> 4 + +# Оператор выбора +cmd = "move" + +action = case cmd + when "create" + "Creating..." + when "copy" + "Copying..." + when "move" + "Moving..." + when "delete" + "Deleting..." +end + +action #=> "Moving..." + + +# Циклы + +index = 0 +while index <= 3 + puts "Index: #{index}" + index += 1 +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +index = 0 +until index > 3 + puts "Index: #{index}" + index += 1 +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +# Но лучше использовать each +(1..3).each do |index| + puts "Index: #{index}" +end +# Index: 1 +# Index: 2 +# Index: 3 + +# Тип переменной зависит от типа выражения +if a < 3 + a = "hello" +else + a = true +end +typeof a #=> (Bool | String) + +if a && b + # здесь гарантируется, что и a, и b — не nil +end + +if a.is_a? String + a.class #=> String +end + + +# Методы + +def double(x) + x * 2 +end + +# Методы (а также любые блоки) всегда возвращают значение последнего выражения +double(2) #=> 4 + +# Скобки можно опускать, если вызов метода не вносит двусмысленности +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Параметры методов перечисляются через запятую +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + + +# yield + +# У всех методов есть неявный необязательный параметр блока, который можно +# вызвать ключевым словом yield + +def surround + puts '{' + yield + puts '}' +end + +surround { puts "hello world" } + +# { +# hello world +# } + +# Методу можно передать блок +# & — ссылка на переданный блок +def guests(&block) + block.call "some_argument" +end + +# Методу можно передать список параметров, доступ к ним будет как к массиву +# Для этого используется оператор * +def guests(*array) + array.each { |guest| puts guest } +end + +# Если метод возвращает массив, можно попарно присвоить значение каждого из его +# элементов переменным +def foods + ["pancake", "sandwich", "quesadilla"] +end +breakfast, lunch, dinner = foods +breakfast #=> "pancake" +dinner #=> "quesadilla" + +# По соглашению название методов, возвращающих булево значение, должно +# оканчиваться вопросительным знаком +5.even? # false +5.odd? # true + +# Если название метода оканчивается восклицательным знаком, по соглашению это +# означает, что метод делает что-то необратимое, например изменяет получателя. +# Некоторые методы имеют две версии: "опасную" версию с !, которая что-то +# меняет, и "безопасную", которая просто возвращает новое значение +company_name = "Dunder Mifflin" +company_name.gsub "Dunder", "Donald" #=> "Donald Mifflin" +company_name #=> "Dunder Mifflin" +company_name.gsub! "Dunder", "Donald" +company_name #=> "Donald Mifflin" + + +# Классы +# Определяются с помощью ключевого слова class + +class Human + + # Переменная класса является общей для всех экземпляров этого класса + @@species = "H. sapiens" + + # Объявление типа переменной name экземпляра класса + @name : String + + # Базовый конструктор + # Значением первого параметра инициализируем переменную @name. + # То же делаем и со вторым параметром — переменная @age. В случае, если мы + # не передаём второй параметр, для инициализации @age будет взято значение + # по умолчанию (в данном случае — 0) + def initialize(@name, @age = 0) + end + + # Базовый метод установки значения переменной + def name=(name) + @name = name + end + + # Базовый метод получения значения переменной + def name + @name + end + + # Синтаксический сахар одновременно для двух методов выше + property :name + + # А также по отдельности + getter :name + setter :name + + # Метод класса определяется ключевым словом self, чтобы его можно было + # различить с методом экземпляра класса. Такой метод можно вызвать только + # на уровне класса, а не экземпляра. + def self.say(msg) + puts msg + end + + def species + @@species + end +end + + +# Создание экземпляра класса +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# Вызов методов экземпляра класса +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Вызов метода класса +Human.say("Hi") #=> выведет "Hi" и вернёт nil + +# Переменные экземпляра класса (@) видно только в пределах экземпляра +class TestClass + @var = "I'm an instance var" +end + +# Переменные класса (@) видны как в экземплярах класса, так и в самом классе +class TestClass + @@var = "I'm a class var" +end + +# Переменные с большой буквы — это константы +Var = "I'm a constant" +Var = "can't be updated" # Error: already initialized constant Var + +# Примеры + +# Базовый класс +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Класс-потомок +class Worker < Human +end + +Human.foo #=> 0 +Worker.foo #=> 0 + +Human.foo = 2 #=> 2 +Worker.foo #=> 0 + +Worker.foo = 3 #=> 3 +Human.foo #=> 2 +Worker.foo #=> 3 + +module ModuleExample + def foo + "foo" + end +end + +# Подключение модуля в класс добавляет его методы в экземпляр класса +# Расширение модуля добавляет его методы в сам класс + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => undefined method 'foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => undefined method 'foo' for Book + + +# Обработка исключений + +# Создание пользовательского типа исключения +class MyException < Exception +end + +# Ещё одного +class MyAnotherException < Exception; end + +ex = begin + raise MyException.new +rescue ex1 : IndexError + "ex1" +rescue ex2 : MyException | MyAnotherException + "ex2" +rescue ex3 : Exception + "ex3" +rescue ex4 # без указания конкретного типа исключения будут "отлавливаться" все + "ex4" +end + +ex #=> "ex2" + +``` + +## Дополнительная информация + +### На русском + +- [Официальная документация](http://ru.crystal-lang.org/docs/) + +### На английском + +- [Official Documentation](http://crystal-lang.org/) diff --git a/ruby.html.markdown b/ruby.html.markdown index 2635309b..2595d1d5 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -377,7 +377,7 @@ sum sum(3, 4), 5 #=> 12 # yield # All methods have an implicit, optional block parameter. -# Tt can be called with the 'yield' keyword. +# It can be called with the 'yield' keyword. def surround puts '{' yield diff --git a/solidity.html.markdown b/solidity.html.markdown index 004c225e..c0074b33 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -111,6 +111,7 @@ contract SimpleBank { // CapWords /// @return The balance of the user // 'constant' prevents function from editing state variables; // allows function to run locally/off blockchain + // NOTE: 'constant' on functions is an alias to 'view', but this is deprecated and is planned to be dropped in version 0.5.0. function balance() constant public returns (uint) { return balances[msg.sender]; } diff --git a/swift.html.markdown b/swift.html.markdown index 516debed..f834f373 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -13,9 +13,9 @@ filename: learnswift.swift Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+. -The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. +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/DevelopiOSAppsSwift/), which has a complete tutorial on Swift. +Another great reference is _About Swift_ on Swift's [website](https://docs.swift.org/swift-book/). ```swift // import a module diff --git a/tcl.html.markdown b/tcl.html.markdown index f48d5271..3d23870b 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learntcl.tcl --- -Tcl was created by [John Ousterhout](https://wiki.tcl.tk/John%20Ousterout) as a +Tcl was created by [John Ousterhout](https://wiki.tcl-lang.org/page/John+Ousterhout) as a reusable scripting language for circuit design tools that he authored. In 1997 he was awarded the [ACM Software System Award](https://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl @@ -283,7 +283,7 @@ set c [expr {$a + $b}] # Since "expr" performs variable substitution on its own, brace the expression # to prevent Tcl from performing variable substitution first. See -# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. +# "https://wiki.tcl-lang.org/page/Brace+your+expr-essions" for details. # "expr" understands variable and script substitution: @@ -581,8 +581,8 @@ a ## Reference -[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) +[Official Tcl Documentation](https://www.tcl-lang.org) -[Tcl Wiki](http://wiki.tcl.tk) +[Tcl Wiki](https://wiki.tcl-lang.org) [Tcl Subreddit](http://www.reddit.com/r/Tcl) diff --git a/textile.html.markdown b/textile.html.markdown new file mode 100644 index 00000000..2b81674a --- /dev/null +++ b/textile.html.markdown @@ -0,0 +1,505 @@ +--- +language: textile +contributors: + - ["Keith Miyake", "https://github.com/kaymmm"] +filename: learn-textile.textile +--- + + +Textile is a lightweight markup language that uses a text formatting syntax to +convert plain text into structured HTML markup. The syntax is a shorthand +version of HTML that is designed to be easy to read and write. Textile is used +for writing articles, forum posts, readme documentation, and any other type of +written content published online. + +- [Comments](#comments) +- [Paragraphs](#paragraphs) +- [Headings](#headings) +- [Simple Text Styles](#simple-text-styles) +- [Lists](#lists) +- [Code blocks](#code-blocks) +- [Horizontal rule](#horizontal-rule) +- [Links](#links) +- [Images](#images) +- [Footnotes and Endnotes](#footnotes-and-endnotes) +- [Tables](#tables) +- [Character Conversions](#character-conversions) +- [CSS](#css) +- [Spans and Divs](#spans-and-divs) +- [Additional Info](#additional-info) + +## Comments + +``` +###. Comments begin with three (3) '#' signs followed by a full-stop period '.'. +Comments can span multiple lines until a blank line is reached. + +###.. +Multi-line comments (including blank lines) are indicated by three (3) '#' +signs followed by two (2) full-stop periods '..'. + +This line is also part of the above comment. + +The comment continues until the next block element is reached + +p. This line is not commented + +<!-- HTML comments are also… + +respected --> + +``` + +## Paragraphs + +``` +###. Paragraphs are a one or multiple adjacent lines of text separated by one or +multiple blank lines. They can also be indicated explicitly with a 'p. ' + +This is a paragraph. I'm typing in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! +Line breaks without blank spaces are equivalent to a <br /> in XHTML. + +p. I'm an explicitly defined paragraph + + Lines starting with a blank space are not wrapped in <p>..</p> tags. + +###. Paragraphs (and all block elements) can be aligned using shorthand: + +p<. Left aligned paragraph (default). + +p>. Right aligned paragraph. + +p=. Centered paragraph. + +p<>. Justified paragraph. + +h3>. Right aligned <h3> + + +###. Paragraphs can be indented using a parentheses for each em +Indentation utilizes padding-[left/right] css styles. + +p(. Left indent 1em. + +p((. Left indent 2em. + +p))). Right indent 3em. + +h2). This is equivalent to <h2 style="padding-right: 1em;">..</h2> + + +###. Block quotes use the tag 'bq.' + +bq. This is a block quote. + +bq.:http://someurl.com You can include a citation URL immediately after the '.' + +bq.. Multi-line blockquotes containing + +blank lines are indicated using two periods + +p. Multi-line blockquotes continue until a new block element is reached. + +bq. You can add a footer to a blockquote using html: +<footer>citation text</footer> + + +###. Preformatted text blocks: + +pre. This text is preformatted. <= those two spaces will carry through. + +pre.. This is a multi-line preformatted… + +…text block that includes blank lines + +p. End a multi-line preformatted text block with a new block element. + +``` + +## Headings + +You can create HTML elements `<h1>` through `<h6>` easily by prepending the +text you want to be in that element by 'h#.' where # is the level 1-6. +A blank line is required after headings. + + +``` +h1. This is an <h1> + +h2. This is an <h2> + +h3. This is an <h3> + +h4. This is an <h4> + +h5. This is an <h5> + +h6. This is an <h6> + +``` + + +## Simple text styles + +``` +###. Bold and strong text are indicated using asterisks: + +*This is strong text* +**This is bold text** +This is [*B*]old text within a word. + +*Strong* and **Bold** usually display the same in browsers +but they use different HTML markup, thus the distinction. + +###. Italics and emphasized text are indicated using underscores. + +_This is Emphasized text_ +__This is Italics text__ +This is It[_al_]ics within a word. + +_Emphasized_ and __Italics__ text typically display the same in browsers, +but again, they use different HTML markup and thus the distinction. + +###. Superscripts and Subscripts use carats and tildes: + +Superscripts are 2 ^nd^ to none, but subscripts are CO ~2~ L too. +Note the spaces around the superscripts and subscripts. + +To avoid the spaces, add square brackets around them: +2[^nd^] and CO[~2~]L + +###. Insertions and deletions are indicated using -/+ symbols: +This is -deleted- text and this is +inserted+ text. + +###. Citations are indicated using double '?': + +??This is a cool citation?? + +``` + +## Lists + +``` +###. Unordered lists can be made using asterisks '*' to indicate levels: + +* Item +** Sub-Item +* Another item +** Another sub-item +** Yet another sub-item +*** Three levels deep + +###. Ordered lists are done with a pound sign '#': + +# Item one +# Item two +## Item two-a +## Item two-b +# Item three +** Mixed unordered list within ordered list + +###. Ordered lists can start above 1 and can continue after another block: + +#5 Item 5 +# Item 6 + +additional paragraph + +#_ Item 7 continued from above +# Item 8 + +###. Definition lists are indicated with a dash and assignment: + +- First item := first item definition +- Second := second def. +- Multi-line := +Multi-line +definition =: +``` + +## Code blocks + +``` +Code blocks use the 'bc.' shorthand: + +bc. This is code + So is this + +This is outside of the code block + +bc.. This is a multi-line code block + +Blank lines are included in the multi-line code block + +p. End a multi-line code block with any block element + +p. Indicate @inline code@ using the '@' symbol. + +``` + +## Horizontal rule + +Horizontal rules (`<hr/>`) are easily added with two hyphens + +``` +-- +``` + +## Links + +``` +###. Link text is in quotes, followed by a colon and the URL: + +"Link text":http://linkurl.com/ plain text. + +"Titles go in parentheses at the end of the link text"(mytitle):http://url.com +###. produces <a href... title="mytitle">...</a> + +###. Use square brackets when the link text or URL might be ambiguous: +["Textile on Wikipedia":http://en.wikipedia.org/wiki/Textile_(markup_language)] + +###. Named links are useful if the same URL is referenced multiple times. +Multiple "references":txstyle to the "txstyle":txstyle website. + +[txstyle]https://txstyle.org/ + +``` + +## Images + +``` +###. Images can be included by surrounding its URL with exclamation marks (!) +Alt text is included in parenthesis after the URL, and they can be linked too: + +!http://imageurl.com! + +!http://imageurl.com(image alt-text)! + +!http://imageurl.com(alt-text)!:http://image-link-url.com + +``` + +## Footnotes and Endnotes + +``` +A footnote is indicated with the reference id in square brackets.[1] + +fn1. Footnote text with a "link":http://link.com. + +A footnote without a link.[2!] + +fn2. The corresponding unlinked footnote. + +A footnote with a backlink from the footnote back to the text.[3] + +fn3^. This footnote links back to the in-text citation. + + +Endnotes are automatically numbered[#first] and are indicated using square[#second] +brackets and a key value[#first]. They can also be unlinked[#unlinkednote!] + +###. Give the endnotes text: + +note#first. This is the first endnote text. + +note#second. This is the second text. + +note#unlinkednote. This one isn't linked from the text. + +### Use the notelist block to place the list of notes in the text: +This list will start with #1. Can also use alpha or Greeks. +notelist:1. ###. start at 1 (then 2, 3, 4...) +notelist:c. ###. start at c (then d, e, f...) +notelist:α. ###. start at α (then β, γ, δ...) + +###. The notelist syntax is as follows: + +notelist. Notes with backlinks to every citation made to them. +notelist+. Notes with backlinks to every citation made to them, + followed by the unreferenced notes. +notelist^. Notes with one backlink to the first citation made to each note. +notelist^+. Notes with one backlink to the first citation made to each note, + followed by unreferenced notes. +notelist!. Notes with no backlinks to the citations. +notelist!+. Notes with no backlinks to the citations, followed by + unreferenced notes. +``` + +## Tables + + +``` +###. Tables are simple to define using the pipe '|' symbol + +| A | simple | table | row | +| And | another | table | row | +| With an | | empty | cell | + +###. Headers are preceded by '|_.' +|_. First Header |_. Second Header | +| Content Cell | Content Cell | + +###. The <thead> tag is added when |^. above and |-. below the heading are used. + +|^. +|_. First Header |_. Second Header | +|-. +| Content Cell | Content Cell | +| Content Cell | Content Cell | + +###. The <tfoot> tag is added when |~. above and |-. below the footer are used. + +|~. +|\2=. A footer, centered & across two columns | +|-. +| Content Cell | Content Cell | +| Content Cell | Content Cell | + +###. Attributes are be applied either to individual cells, rows, or to +the entire table. Cell attributes are placed within each cell: + +|a|{color:red}. styled|cell| + +###. Row attributes are placed at the beginning of a row, +followed by a dot and a space: + +(rowclass). |a|classy|row| + +###. Table attributes are specified by placing the special 'table.' block +modifier immediately before the table: + +table(tableclass). +|a|classy|table| +|a|classy|table| + +###. Spanning rows and colums: +A backslash \ is used for a column span: + +|\2. spans two cols | +| col 1 | col 2 | + +###. A forward slash / is used for a row span: + +|/3. spans 3 rows | row a | +| row b | +| row c | + +###. Vertical alignments within a table cell: + +|^. top alignment| +|-. middle alignment| +|~. bottom alignment| + +###. Horizontal alignments within a table cell + +|:\1. |400| +|=. center alignment | +| no alignment | +|>. right alignment | + +``` +or, for the same results + +``` +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop +``` + + +## Character Conversions + +### Registered, Trademark, Copyright Symbols + +``` +RegisteredTrademark(r), Trademark(tm), Copyright (c) +``` + +### Acronyms + +``` +###. Acronym definitions can be provided in parentheses: + +EPA(Environmental Protection Agency) and CDC(Center for Disease Control) +``` + +### Angle Brackets and Ampersand + +``` +### Angled brackets < and > and ampersands & are automatically escaped: +< => < +> => > +& => & +``` + +### Ellipses + +``` +p. Three consecutive periods are translated into ellipses...automatically +``` + +### Em and En dashes + +``` +###. En dashes (short) is a hyphen surrounded by spaces: + +This line uses an en dash to separate Oct - Nov 2018. + +###. Em dashes (long) are two hyphens with or without spaces: + +This is an em dash--used to separate clauses. +But we can also use it with spaces -- which is a less-used convention. +That last hyphen between 'less' and 'used' is not converted between words. +``` + +## Fractions and other Math Symbols + +``` +One quarter: (1/4) => ¼ +One half: (1/2) => ½ +Three quarters: (3/4) => ¾ +Degree: (o) => ° +Plus/minus: (+/-) => ± +``` +### Multiplication/Dimension + +``` +p. Numbers separated by the letter 'x' translate to the multiplication +or dimension symbol '×': +3 x 5 => 3 × 5 +``` + +### Quotes and Apostrophes + +``` +###. Straight quotes and apostrophes are automatically converted to +their curly equivalents: + +"these", 'these', and this'n are converted to their HTML entity equivalents. +Leave them straight using '==' around the text: =="straight quotes"==. +``` + +## CSS + +``` +p{color:blue}. CSS Styles are enclosed in curly braces '{}' +p(my-class). Classes are enclosed in parenthesis +p(#my-id). IDs are enclosed in parentheses and prefaced with a pound '#'. +``` + +## Spans and Divs + +``` +%spans% are enclosed in percent symbols +div. Divs are indicated by the 'div.' shorthand +``` +--- + +## For More Info + +* TxStyle Textile Documentation: [https://txstyle.org/](https://txstyle.org/) +* promptworks Textile Reference Manual: [https://www.promptworks.com/textile](https://www.promptworks.com/textile) +* Redmine Textile Formatting: [http://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile](http://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile) diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index 2c841456..9d65cf9c 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -1071,7 +1071,6 @@ compl 4 // Bit seviyesinde değil işlemini gerçekleştirir ``` İleri okuma: -Güncel bir referans -<http://cppreference.com/w/cpp> adresinde bulunabilir - -Ek kaynaklar <http://cplusplus.com> adresinde bulunabilir +* Güncel bir referans [CPP Reference](http://cppreference.com/w/cpp) adresinde bulunabilir. +* Ek kaynaklar [CPlusPlus](http://cplusplus.com) adresinde bulunabilir. +* Dilin temellerini ve kodlama ortamını belirleyen bir öğretici [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb) adresinde bulunabilir. diff --git a/tr-tr/dynamic-programming-tr.html.markdown b/tr-tr/dynamic-programming-tr.html.markdown index 606ecf04..e6a734a7 100644 --- a/tr-tr/dynamic-programming-tr.html.markdown +++ b/tr-tr/dynamic-programming-tr.html.markdown @@ -8,24 +8,28 @@ translators: lang: tr-tr --- -Dinamik Programlama -Giriş +# Dinamik Programlama + +## Giriş + Dinamik Programlama, göreceğimiz gibi belirli bir problem sınıfını çözmek için kullanılan güçlü bir tekniktir. Fikir çok basittir, verilen girdiyle ilgili bir sorunu çözdüyseniz, aynı sorunun tekrar çözülmesini önlemek için sonucunu gelecekte referans olarak kaydedilmesine dayanır. Her zaman hatırla! "Geçmiş hatırlayamayanlar, aynı şeyleri tekrar yaşamaya mahkumlardır!" -Bu tür sorunların çözüm yolları +## Bu tür sorunların çözüm yolları -1-Yukarıdan aşağıya: +1. Yukarıdan aşağıya: Verilen problemi çözerek çözmeye başlayın. Sorunun zaten çözüldüğünü görürseniz, kaydedilen cevabı döndürmeniz yeterlidir. Çözülmemişse, çözünüz ve cevabı saklayınız. Bu genellikle düşünmek kolaydır ve çok sezgiseldir. Buna Ezberleştirme denir. -2-Aşağıdan yukarıya: +2. Aşağıdan yukarıya: Sorunu analiz edin ve alt problemlerin çözülme sırasını görün ve önemsiz alt sorundan verilen soruna doğru başlayın. Bu süreçte, problemi çözmeden önce alt problemlerin çözülmesi gerekmektedir. Buna Dinamik Programlama denir. -Örnek -En Uzun Artan Subsequence problemi belirli bir dizinin en uzun artan alt dizini bulmaktır. S = {a1, a2, a3, a4, ............., an-1} dizisi göz önüne alındığında, en uzun bir alt kümeyi bulmak zorundayız, böylece tüm j ve i, j için <I, aj <ai alt kümesinde. Her şeyden önce, en son alt dizgenin (LSi) değerini dizinin son elemanı olan ai'nin her indeksinde bulmalıyız. Daha sonra en büyük LSi, verilen dizideki en uzun alt dizin olacaktır. Başlamak için, ai, dizinin elemanı olduğundan (Son öğe) LSi atanır. Sonra tüm j için j <i ve aj <ai gibi, En Büyük LSj'yi buluruz ve LSi'ye ekleriz. Sonra algoritma O (n2) zaman alır. +## Örnek + +En Uzun Artan Subsequence problemi belirli bir dizinin en uzun artan alt dizini bulmaktır. `S = {a1, a2, a3, a4, ............., an-1}` dizisi göz önüne alındığında, en uzun bir alt kümeyi bulmak zorundayız, böylece tüm j ve i, `j<I` için , `aj<ai` alt kümesinde. Her şeyden önce, en son alt dizgenin (LSi) değerini dizinin son elemanı olan ai'nin her indeksinde bulmalıyız. Daha sonra en büyük LSi, verilen dizideki en uzun alt dizin olacaktır. Başlamak için, ai, dizinin elemanı olduğundan (Son öğe) LSi atanır. Sonra tüm j için `j<i` ve `aj<ai` gibi, En Büyük LSj'yi buluruz ve LSi'ye ekleriz. Sonra algoritma `O(n2)` zaman alır. -En uzun artan alt dizinin uzunluğunu bulmak için sözde kod: Bu algoritmaların karmaşıklığı dizi yerine daha iyi veri yapısı kullanılarak azaltılabilir. Büyük dizin ve dizin gibi selefi dizi ve değişkeni saklama çok zaman kazandıracaktır. +En uzun artan alt dizinin uzunluğunu bulmak için sözde kod: +Bu algoritmaların karmaşıklığı dizi yerine daha iyi veri yapısı kullanılarak azaltılabilir. Büyük dizin ve dizin gibi selefi dizi ve değişkeni saklama çok zaman kazandıracaktır. Yönlendirilmiş asiklik grafiğinde en uzun yolu bulmak için benzer bir kavram uygulanabilir. @@ -40,10 +44,12 @@ for i=0 to n-1 ``` -Bazı Ünlü Dinamik Programlama Problemleri --Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs—floyd-warshall-algorithm-with-c-program-source-code --Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—the-integer-knapsack-problem --Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—longest-common-subsequence +### Bazı Ünlü Dinamik Programlama Problemleri + +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() + +## Online Kaynaklar -Online Kaynaklar -https://www.codechef.com/wiki/tutorial-dynamic-programming +- [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) diff --git a/typescript.html.markdown b/typescript.html.markdown index db6579e2..9158f123 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -113,6 +113,13 @@ class Point { static origin = new Point(0, 0); } +// Classes can be explicitly marked as implementing an interface. +// Any missing properties will then cause an error at compile-time. +class PointPerson implements Person { + name: string + move() {} +} + let p1 = new Point(10, 20); let p2 = new Point(25); //y will be 0 diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index df642f73..40d56988 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -592,7 +592,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // Позначення класу як абстрактного означає, що оголошені у ньому методи мають // бути реалізовані у дочірніх класах. Подібно до інтерфейсів, не можна створити екземпляри // абстракних класів, але їх можна успадковувати. Нащадок зобов’язаний реалізувати всі абстрактні -// методи. на відміну від інтерфейсів, абстрактні класи можуть мати як визначені, +// методи. На відміну від інтерфейсів, абстрактні класи можуть мати як визначені, // так і абстрактні методи. Методи в інтерфейсах не мають тіла, // за винятком статичних методів, а змінні неявно мають модифікатор final, на відміну від // абстрактного класу. Абстрактні класи МОЖУТЬ мати метод «main». diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 87951bc3..e0d6b6fe 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -567,6 +567,6 @@ void doSomethingWithAFile(const std::string& filename) ```
扩展阅读:
-<http://cppreference.com/w/cpp> 提供了最新的语法参考。
-
-可以在 <http://cplusplus.com> 找到一些补充资料。
+* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。
+* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。
+* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。
|