diff options
-rw-r--r-- | angularjs.html.markdown | 8 | ||||
-rw-r--r-- | csharp.html.markdown | 6 | ||||
-rw-r--r-- | elixir.html.markdown | 4 | ||||
-rw-r--r-- | es-es/amd-es.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/ruby-ecosystem-fr.html.markdown | 25 | ||||
-rw-r--r-- | fr-fr/ruby-fr.html.markdown | 49 | ||||
-rw-r--r-- | java.html.markdown | 127 | ||||
-rw-r--r-- | json.html.markdown | 1 | ||||
-rw-r--r-- | lfe.html.markdown | 459 | ||||
-rw-r--r-- | perl6.html.markdown | 5 | ||||
-rw-r--r-- | php.html.markdown | 4 | ||||
-rw-r--r-- | red.html.markdown | 12 | ||||
-rw-r--r-- | standard-ml.html.markdown | 2 | ||||
-rw-r--r-- | tcsh.html.markdown | 790 | ||||
-rw-r--r-- | zh-cn/java-cn.html.markdown | 4 |
15 files changed, 1378 insertions, 120 deletions
diff --git a/angularjs.html.markdown b/angularjs.html.markdown index 737b99c7..9156490e 100644 --- a/angularjs.html.markdown +++ b/angularjs.html.markdown @@ -699,10 +699,10 @@ app.controller('myCtrl', function($scope) { **Examples** -- http://www.w3schools.com/angular/angular_examples.asp +- [http://www.w3schools.com/angular/angular_examples.asp](http://www.w3schools.com/angular/angular_examples.asp) **References** -- http://www.w3schools.com/angular/angular_ref_directives.asp -- http://www.w3schools.com/angular/default.asp -- https://teamtreehouse.com/library/angular-basics/ +- [http://www.w3schools.com/angular/angular_ref_directives.asp](http://www.w3schools.com/angular/angular_ref_directives.asp) +- [http://www.w3schools.com/angular/default.asp](http://www.w3schools.com/angular/default.asp) +- [https://teamtreehouse.com/library/angular-basics/](https://teamtreehouse.com/library/angular-basics/) diff --git a/csharp.html.markdown b/csharp.html.markdown index cca99fb0..78f9db34 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -593,7 +593,7 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(bikeSummary.Name); // ASPARALLEL - // And this is where things get wicked - combines linq and parallel operations + // And this is where things get wicked - combine linq and parallel operations var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); // this will happen in parallel! Threads will automagically be spun up and the // results divvied amongst them! Amazing for large datasets when you have lots of @@ -613,7 +613,7 @@ on a new line! ""Wow!"", the masses cried"; .ThenBy(b => b.Name) .Select(b => b.Name); // still no query run - // Now the query runs, but opens a reader, so only populates are you iterate through + // Now the query runs, but opens a reader, so only populates as you iterate through foreach (string bike in query) Console.WriteLine(result); @@ -711,7 +711,7 @@ on a new line! ""Wow!"", the masses cried"; // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell public BikeAccessories Accessories { get; set; } - // Static members belong to the type itself rather then specific object. + // Static members belong to the type itself rather than specific object. // You can access them without a reference to any object: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); public static int BicyclesCreated { get; set; } diff --git a/elixir.html.markdown b/elixir.html.markdown index 9dfffc41..a74baa38 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Ryan Plant", "https://github.com/ryanplant-au"] + - ["Ev Bogdanov", "https://github.com/evbogdanov"] filename: learnelixir.ex --- @@ -127,7 +128,8 @@ rem(10, 3) #=> 1 # These operators expect a boolean as their first argument. true and true #=> true false or true #=> true -# 1 and true #=> ** (ArgumentError) argument error +# 1 and true +#=> ** (BadBooleanError) expected a boolean on left-side of "and", got: 1 # Elixir also provides `||`, `&&` and `!` which accept arguments of any type. # All values except `false` and `nil` will evaluate to true. diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown index 7a59ddd6..40aa6647 100644 --- a/es-es/amd-es.html.markdown +++ b/es-es/amd-es.html.markdown @@ -190,7 +190,7 @@ Para usar el fichero creado en producción, simplemente intercambia `data-main`: Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. -### Tópicos no cubiertos en este tutorial +### Temas no cubiertos en este tutorial * [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) * [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) * [Configuración avanzada](http://requirejs.org/docs/api.html#config) diff --git a/fr-fr/ruby-ecosystem-fr.html.markdown b/fr-fr/ruby-ecosystem-fr.html.markdown index 9b52069a..edc69068 100644 --- a/fr-fr/ruby-ecosystem-fr.html.markdown +++ b/fr-fr/ruby-ecosystem-fr.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Rafal Chmiel", "http://github.com/rafalchmiel"] translators: - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] + - ["Sylvain Abélard", "http://github.com/abelards"] lang: fr-fr --- @@ -17,9 +18,9 @@ dépendances des gems. ## Ruby Managers Quelques plateformes possèdent Ruby pré-installé ou disponible en tant que -paquet. La plupart des rubyists ne les utilisent pas, ou si c'est le cas, ne -les utilise que pour faire démarrer un autre installateur ou implémentation de -Ruby. Les rubyists tendent plutôt à installer un manager Ruby pour installer +paquet. La plupart des rubyistes ne les utilisent pas, ou si c'est le cas, ne +les utilisent que pour faire démarrer un autre installateur ou implémentation de +Ruby. Les rubyistes tendent plutôt à installer un gestionnaire en Ruby pour installer et changer entre les différentes et nombreuses versions de Ruby et les environnements de leurs projets Ruby. @@ -47,14 +48,14 @@ Implementation). Les trois versions majeures de Ruby actuellement utilisées sont : -* 2.0.0 - Sortie en février 2013. La plupart des librairies et frameworks +* 2.0.0 - Sortie en février 2013. La plupart des bibliothèques et frameworks gèrent la versions 2.0.0. * 1.9.3 - Sortie en octobre 2011. Il s'agit de la version que la majorité des rubyists utilisent actuellement. [Fin de vie](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) * 1.8.7 - Sortie en juin 2006. [Fin de vie](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). -Les changements entre 1.8.7 à 1.9.x sont bien plus grands qu'entre 1.9.3 -jusqu'à 2.0.0. Par exemple, les versions 1.9 ont introduit le support des +Les changements entre 1.8.7 et 1.9.x sont bien plus grands qu'entre 1.9.3 +et 2.0.0. Par exemple, les versions 1.9 ont introduit le support des encodages et d'une VM bytecode ([YARV](https://fr.wikipedia.org/wiki/YARV)). Il y a toujours des projets sur 1.8.7, mais ils deviennent minoritaires, étant donné que la majorité de la communauté a migré vers au moins 1.9.2 ou 1.9.3. @@ -89,7 +90,7 @@ Mpyennement mature/compatible: * [Maglev](http://maglev.github.io/) - Basée sur Gemstone, une VM Smalltalk. Smalltalk possède quelques outils impressionnants, et ce projet tente de les apporter dans le développement Ruby. -* [RubyMotion](http://www.rubymotion.com/) - Ruby pour développement iOS. +* [RubyMotion](http://www.rubymotion.com/) - Ruby pour développement iOS et Android. * [Opal](http://opalrb.org/) - Compile le Ruby en Javascript Les implémentations de Ruby peuvent avoir leurs propres numéros de versions, @@ -122,17 +123,17 @@ l(es) auteur(s) et la/les licence(s). ## Bundler -[Bundler](http://bundler.io/) est un résolveur de dépendances des gems. Il -utilise le Gemfile d'un projet ppur trouver les dépendances, et récupère +[Bundler](http://bundler.io/) est un outil de résolution de dépendances des gems. Il +utilise le Gemfile d'un projet pour en trouver les dépendances, et récupère ensuite les dépendances de ces dépendances récursivement. Il déroule cet algorithme jusqu'à ce que toutes les dépendances soient résolues et téléchargées, ou s'arrête si un conflit est trouvé. Bundler lèvera une erreur s'il trouve des conflits de dépendances. Par exemple, si la gem A recquiert la version 3 ou plus de gem Z, mais que gem B recquiert -seulement la version 2, Bundler vous notifiera ce conflict. Cela devient +seulement la version 2 de la même gem Z, Bundler vous notifiera ce conflit. Cela devient extrêmement utile, étant donné que beaucoup de gems font référence à d'autres -gems (qui se réfèrent à d'autres gems), ce qui peut former un large graphe de +gems (qui se réfèrent à d'autres gems et ainsi de suite), ce qui peut former un large graphe de dépendance à résoudre. # Les tests @@ -151,4 +152,4 @@ différents. La communauté Ruby est fière d'être une communauté ouverte, riche et accueillante. Matz lui-même est extrêmement sociable, et la générosité des -rubyists est généralement remarquable. +rubyistes est généralement remarquable. diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 1564d2b6..6b487a07 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -7,9 +7,11 @@ contributors: - ["Luke Holder", "http://twitter.com/lukeholder"] - ["Tristan Hume", "http://thume.ca/"] - ["Nick LaMuro", "https://github.com/NickLaMuro"] + translators: - ["Geoffrey Roguelon", "https://github.com/GRoguelon"] - ["Nami-Doc", "https://github.com/Nami-Doc"] + - ["Sylvain Abélard", "http://github.com/abelards"] lang: fr-fr --- @@ -22,19 +24,23 @@ Personne ne les utilise Vous devriez en faire de même =end -# Tout d'abord : Tout est un objet. +# Tout d'abord : tout est un objet. # Les nombres sont des objets -3.class #=> Fixnum +3.class #=> Fixnum # on voit que c'est une classe Ruby et non un "type spécial" -3.to_s #=> "3" +3.to_s #=> "3" # on peut appeler des méthodes sur ces objets, comme `to_s` (transforme en texte) # Les opérateurs de base 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 -35 / 5 #=> 7 +22 / 7 #=> 3 # si les deux éléments sont entiers, c'est une division entière +22.0 / 7 #=> 3.142857142857143 +22 / 7.0 #=> 3.142857142857143 +2**10 #=> 1024 # exposant +1024 % 10 #=> 4 # modulo (reste de la division euclidienne) # Les opérateurs sont juste des raccourcis # pour appeler une méthode sur un objet @@ -42,9 +48,9 @@ Vous devriez en faire de même 10.* 5 #=> 50 # Les valeurs spéciales sont des objets -nil # Nul -true # Vrai -false # Faux +nil # nul, vide ou indéfini +true # vrai +false # faux nil.class #=> NilClass true.class #=> TrueClass @@ -60,8 +66,7 @@ false.class #=> FalseClass !true #=> false !false #=> true -# à part false lui-même, nil est la seule autre valeur 'false' - +# à part false lui-même, nil est la seule autre valeur "considérée comme fausse" !nil #=> true !false #=> true !0 #=> false @@ -73,7 +78,6 @@ false.class #=> FalseClass 2 >= 2 #=> true # Les chaînes de caractères sont des objets - 'Je suis une chaîne de caractères'.class #=> String "Je suis également une chaîne de caractères".class #=> String @@ -84,6 +88,15 @@ placeholder = "utiliser l'interpolation de chaîne de caractères" # Affichez un message puts "J'affiche à l'écran!" +# Il y a quelques autres raccourcis pour les chaînes de caractères +rb = "Ruby" +interpolation = "Bonjour Ruby" # s'écrit aussi %Q[Bonjour #{rb}] %Q{Bonjour #{rb}} avec l'interpolation +literal = "Bonjour \#{rb}" # avec le backslash, le dièse est un "vrai dièse" (le slash ne s'affiche que pour le debug) +literal == %q[Bonjour #{rb}] # le Q majuscule fait l'interpolation, le q minuscule ne la fait pas +multi = %Q[Cette chaîne +est sur plusieurs +lignes] # => "Cette chaîne\nest sur plusieurs\nlignes" # le caractère \n signifie retour à la ligne + # Variables x = 25 #=> 25 x #=> 25 @@ -131,7 +144,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] [1, "hello", false] #=> [1, "hello", false] # Les tableaux peuvent être indexés -# Du début +# Trouver la valeur en donnant la position en partant du début (le premier élément est à l'index 0) array[0] #=> 1 array[12] #=> nil @@ -140,13 +153,13 @@ array[12] #=> nil array.[] 0 #=> 1 array.[] 12 #=> nil -# Depuis la fin +# On peut compter en partant de la fin avec un index négatif (le dernier élément est à l'index -1) array[-1] #=> 5 -# Avec un index de début et de fin -array[2, 4] #=> [3, 4, 5] +# Avec un index de début et un nombre d'éléments [position, nombre] +array[1, 3] #=> [2, 3, 4] -# Ou avec un intervalle +# Ou avec un intervalle [index de début .. index de fin] array[1..3] #=> [2, 3, 4] # Ajoutez un élément au tableau comme ceci @@ -180,11 +193,11 @@ new_hash.keys #=> [:defcon, :action] # Structures de contrôle if true - "si instruction" + "si l'instruction est vraie" elsif false - "autrement si, facultatif" + "si l'instruction de départ n'était pas vraie, et que cette nouvelle condition est vraie (facultatif)" else - "autrement, également facultatif" + "tous les autres cas (il est également facultatif de faire une clause else)" end for compteur in 1..5 diff --git a/java.html.markdown b/java.html.markdown index e8c15234..a27a68ca 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -48,9 +48,9 @@ import java.security.*; // as the file. public class LearnJava { - // In order to run a java program, it must have a main method as an entry + // In order to run a java program, it must have a main method as an entry // point. - public static void main (String[] args) { + public static void main(String[] args) { /////////////////////////////////////// // Input/Output @@ -109,7 +109,7 @@ public class LearnJava { */ // Declare a variable using <type> <name> int fooInt; - // Declare multiple variables of the same + // Declare multiple variables of the same // type <type> <name1>, <name2>, <name3> int fooInt1, fooInt2, fooInt3; @@ -119,8 +119,9 @@ public class LearnJava { // Initialize a variable using <type> <name> = <val> int barInt = 1; - // Initialize multiple variables of same type with same - // value <type> <name1>, <name2>, <name3> = <val> + // Initialize multiple variables of same type with same + // value <type> <name1>, <name2>, <name3> + // <name1> = <name2> = <name3> = <val> int barInt1, barInt2, barInt3; barInt1 = barInt2 = barInt3 = 1; @@ -130,7 +131,7 @@ public class LearnJava { // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; - + // If you would like to interpret a byte as an unsigned integer // then this simple operation can help int unsignedIntLessThan256 = 0xff & fooByte; @@ -184,12 +185,12 @@ public class LearnJava { // integers longer than 64-bits. Integers are stored as an array of // of bytes and are manipulated using functions built into BigInteger // - // BigInteger can be initialized using an array of bytes or a string. + // BigInteger can be initialized using an array of bytes or a string. BigInteger fooBigInteger = new BigInteger(fooByteArray); // BigDecimal - Immutable, arbitrary-precision signed decimal number // - // A BigDecimal takes two parts: an arbitrary precision integer + // A BigDecimal takes two parts: an arbitrary precision integer // unscaled value and a 32-bit integer scale // // BigDecimal allows the programmer complete control over decimal @@ -199,7 +200,7 @@ public class LearnJava { // BigDecimal can be initialized with an int, long, double or String // or by initializing the unscaled value (BigInteger) and scale (int). BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); - + // Be wary of the constructor that takes a float or double as // the inaccuracy of the float/double will be copied in BigDecimal. // Prefer the String constructor when you need an exact value. @@ -231,13 +232,13 @@ public class LearnJava { builderConcatenated.append("You "); builderConcatenated.append("can use "); builderConcatenated.append("the StringBuilder class."); - System.out.println(builderConcatenated.toString()); // only now is the string built + System.out.println(builderConcatenated.toString()); // only now is the string built // Output: You can use the StringBuilder class. - + // StringBuilder is efficient when the fully constructed String is not required until the end of some processing. StringBuilder stringBuilder = new StringBuilder(); String inefficientString = ""; - for(int i = 0 ; i < 10; i++){ + for (int i = 0 ; i < 10; i++) { stringBuilder.append(i).append(" "); inefficientString += i + " "; } @@ -246,12 +247,12 @@ public class LearnJava { // inefficientString requires a lot more work to produce, as it generates a String on every loop iteration. // Simple concatenation with + is compiled to a StringBuilder and toString() // Avoid string concatenation in loops. - + // #3 - with String formatter // Another alternative way to create strings. Fast and readable. String.format("%s may prefer %s.", "Or you", "String.format()"); // Output: Or you may prefer String.format(). - + // Arrays // The array size must be decided upon instantiation // The following formats work for declaring an array @@ -387,7 +388,7 @@ public class LearnJava { // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + // Nested For Loop Exit with Label outer: for (int i = 0; i < 10; i++) { @@ -398,7 +399,7 @@ public class LearnJava { } } } - + // For Each Loop // The for loop is also able to iterate over arrays as well as objects // that implement the Iterable interface. @@ -416,6 +417,7 @@ public class LearnJava { // It also works with enumerated types (discussed in Enum Types), the // String class, and a few special classes that wrap primitive types: // Character, Byte, Short, and Integer. + // Starting in Java 7 and above, we can also use the String type. int month = 3; String monthString; switch (month) { @@ -429,38 +431,21 @@ public class LearnJava { break; } System.out.println("Switch Case Result: " + monthString); - - // Starting in Java 7 and above, switching Strings works like this: - String myAnswer = "maybe"; - switch(myAnswer) { - case "yes": - System.out.println("You answered yes."); - break; - case "no": - System.out.println("You answered no."); - break; - case "maybe": - System.out.println("You answered maybe."); - break; - default: - System.out.println("You answered " + myAnswer); - break; - } - - + + // Try-with-resources (Java 7+) // Try-catch-finally statements work as expected in Java but in Java 7+ // the try-with-resources statement is also available. Try-with-resources // simplifies try-catch-finally statements by closing resources // automatically. - + // In order to use a try-with-resources, include an instance of a class // in the try statement. The class must implement java.lang.AutoCloseable. - try(BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) { + try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) { // You can attempt to do something that could throw an exception. System.out.println(br.readLine()); // In Java 7, the resource will always be closed, even if it throws - // an Exception. + // an Exception. } catch (Exception ex) { //The resource will be closed before the catch statement executes. System.out.println("readLine() failed."); @@ -470,18 +455,22 @@ public class LearnJava { // a finally statement might not be called. // To learn more: // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html - - + + // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. // Reads as "If (statement) is true, use <first value>, otherwise, use // <second value>" int foo = 5; String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Prints A, because the statement is true + System.out.println("bar : " + bar); // Prints "bar : A", because the + // statement is true. + // Or simply + System.out.println("bar : " + (foo < 10 ? "A" : "B")); + //////////////////////////////////////// - // Converting Data Types And Typecasting + // Converting Data Types //////////////////////////////////////// // Converting data @@ -497,11 +486,6 @@ public class LearnJava { // Long // String - // Typecasting - // You can also cast Java objects, there's a lot of details and deals - // with some more intermediate concepts. Feel free to check it out here: - // https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - /////////////////////////////////////// // Classes And Functions /////////////////////////////////////// @@ -566,10 +550,10 @@ class Bicycle { String name; // default: Only accessible from within this package static String className; // Static class variable - // Static block + // Static block // Java has no implementation of static constructors, but - // has a static block that can be used to initialize class variables - // (static variables). + // has a static block that can be used to initialize class variables + // (static variables). // This block will be called when the class is loaded. static { className = "Bicycle"; @@ -652,6 +636,14 @@ class PennyFarthing extends Bicycle { } } +// Object casting +// Since the PennyFarthing class is extending the Bicycle class, we can say +// a PennyFarthing is a Bicycle and write : +// Bicycle bicycle = new PennyFarthing(); +// This is called object casting where an object is taken for another one. There +// are lots of details and deals with some more intermediate concepts here: +// https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + // Interfaces // Interface declaration syntax // <access-level> interface <interface-name> extends <super-interfaces> { @@ -667,10 +659,10 @@ public interface Edible { public interface Digestible { public void digest(); - // In Java 8, interfaces can have default method. - // public void digest() { - // System.out.println("digesting ..."); - // } + // Since Java 8, interfaces can have default method. + public void defaultMethod() { + System.out.println("Hi from default method ..."); + } } // We can now create a class that implements both of these interfaces. @@ -703,14 +695,15 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // Abstract Classes // Abstract Class declaration syntax -// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> { +// <access-level> abstract class <abstract-class-name> extends +// <super-abstract-classes> { // // Constants and variables // // Method declarations // } -// Marking a class as abstract means that it contains abstract methods that -// must be defined in a child class. Similar to interfaces, abstract classes -// cannot be instantiated, but instead must be extended and the abstract +// Marking a class as abstract means that it contains at least one abstract +// method that must be defined in a child class. Similar to interfaces, abstract +// classes cannot be instantiated, but instead must be extended and the abstract // methods defined. Different from interfaces, abstract classes can contain a // mixture of concrete and abstract methods. Methods in an interface cannot // have a body, unless the method is static, and variables are final by default, @@ -734,7 +727,7 @@ public abstract class Animal public void printAge() { - System.out.println(age); + System.out.println(age); } // Abstract classes can have main function. @@ -816,18 +809,18 @@ public abstract class Mammal() // you would specify a days-of-the-week enum type as: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, - THURSDAY, FRIDAY, SATURDAY + THURSDAY, FRIDAY, SATURDAY } // We can use our enum Day like that: public class EnumTest { // Variable Enum Day day; - + public EnumTest(Day day) { this.day = day; } - + public void tellItLikeItIs() { switch (day) { case MONDAY: @@ -835,17 +828,17 @@ public class EnumTest { break; case FRIDAY: System.out.println("Fridays are better."); - break; - case SATURDAY: + break; + case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); - break; + break; default: System.out.println("Midweek days are so-so."); break; } } - + public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); // => Mondays are bad. @@ -854,7 +847,7 @@ public class EnumTest { } } -// Enum types are much more powerful than we show above. +// Enum types are much more powerful than we show above. // The enum body can include methods and other fields. // You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html diff --git a/json.html.markdown b/json.html.markdown index a612cffe..cd42d42d 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -11,6 +11,7 @@ contributors: JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate. A piece of JSON must represent either: + * A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence. an array/list/sequence (`[ ]`) or a dictionary/object/associated array (`{ }`). diff --git a/lfe.html.markdown b/lfe.html.markdown new file mode 100644 index 00000000..413de36e --- /dev/null +++ b/lfe.html.markdown @@ -0,0 +1,459 @@ +--- + +language: "Lisp Flavoured Erlang(LFE)" +filename: lispflavourederlang.lfe +contributors: + - ["Pratik Karki", "https://github.com/prertik"] +--- + +Lisp Flavoured Erlang(LFE) is a functional, concurrent, general-purpose programming +language and Lisp dialect(Lisp-2) built on top of Core Erlang and the Erlang Virtual Machine(BEAM). + +LFE can be obtained from [LFE](https://github.com/rvirding/lfe) + +The classic starting point is [LFE DOCS.](http://docs.lfe.io) + +Another new site is being built to replace it.[LFE DEV.](http://docs.lfe.io/dev) + + + +```lisp + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. Syntax +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; General form. + +;; Lisp comprises of two syntax called: the ATOM and the S-expression. +;; `forms` are known as grouped S-expressions. + +8 ; an atom; it evaluates to itself + +:ERLANG ;Atom; evaluates to the symbol :ERLANG. + +t ; another atom which denotes true. + +(* 2 21) ; an S- expression + +'(8 :foo t) ;another one + + +;;; Comments + +;; Single line comments start with a semicolon; use two for normal +;; comments, three for section comments, and four fo file-level +;; comments. + +;; Block Comment + + #| comment text |# + +;;; Environment + +;; LFE is the de-facto standard. + +;; Libraries can be used directly from the Erlang ecosystem. Rebar3 is the build tool. + +;; LFE is usually developed with a text editor(preferably Emacs) and a REPL +;; (Read Evaluate Print Loop) running at the same time. The REPL +;; allows for interactive exploration of the program as it is "live" +;; in the system. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. Literals and Special Syntactic Rules +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Integers + +1234 -123 ; Regular decimal notation +#b0 #b10101 ; Binary notation +#0 #10101 ; Binary notation (alternative form) +#o377 #o-111 ; Octal notation +#d123456789 #d+123 ; Explicitly decimal notation +#xc0ffe 0x-01 ; Hexadecimal notation +#2r1010 #8r377 ;Notation with explicit base (up to 36) +#\a #$ #\ä #\🐭 ;Character notation (the value is the Unicode code point of the character) +#\x1f42d; ;Character notation with the value in hexadecimal + +;;; Floating point numbers +1.0 +2.0 -1.5 1.0e10 1.111e-10 + +;;; Strings + +"any text between double quotes where \" and other special characters like \n can be escaped". +; List String +"Cat: \x1f639;" ; writing unicode in string for regular font ending with semicolon. + +#"This is a binary string \n with some \"escaped\" and quoted (\x1f639;) characters" +; Binary strings are just strings but function different in the VM. +; Other ways of writing it are: #B("a"), #"a", and #B(97). + + +;;; Character escaping + +\b ; => Backspace +\t ; => Tab +\n ; => Newline +\v ; => Vertical tab +\f ; => Form Feed +\r ; => Carriage Return +\e ; => Escape +\s ; => Space +\d ; => Delete + +;;; Binaries +;; It is used to create binaries with any contents. +#B((#"a" binary) (#"b" binary)) ; #"ab" (Evaluated form) + +;;; Lists are: () or (foo bar baz) + +;;; Tuples are written in: #(value1 value2 ...). Empty tuple #() is also valid. + +;;; Maps are written as: #M(key1 value1 key2 value2 ...). Empty map #M() is also valid. + +;;; Symbols: Things that cannot be parsed. Eg: foo, Foo, foo-bar, :foo +| foo | ; explicit construction of symbol by wrapping vertical bars. + +;;; Evaluation + +;; #.(... some expression ...). E.g. '#.(+ 1 1) will evaluate the (+ 1 1) while it ;; reads the expression and then be effectively '2. + +;; List comprehension in LFE REPL + +lfe> (list-comp + ((<- x '(0 1 2 3))) + (trunc (math:pow 3 x))) + (1 3 9 27) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Core forms +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; These forms are same as those found at Common Lisp and Scheme. + +(quote e) +(cons head tail) +(car e) +(cdr e) +(list e ... ) +(tuple e ... ) +(binary seg ... ) +(map key val ...), (map-get m k), (map-set m k v ...), (map-update m k v ...) + +(lambda (arg ...) ...) + (match-lambda + ((arg ... ) {{(when e ...)}} ...) ; Matches clauses + ... ) +(let ((pat {{(when e ...)}} e) + ...) + ... ) +(let-function ((name lambda|match-lambda) ; Only define local + ... ) ; functions + ... ) +(letrec-function ((name lambda|match-lambda) ; Only define local + ... ) ; functions + ... ) +(let-macro ((name lambda-match-lambda) ; Only define local + ...) ; macros + ...) +(progn ... ) +(if test true-expr {{false-expr}}) +(case e + (pat {{(when e ...)}} ...) + ... )) +(receive + (pat {{(when e ...)}} ... ) + ... + (after timeout ... )) +(catch ... ) +(try + e + {{(case ((pat {{(when e ...)}} ... ) + ... ))}} + {{(catch + ; Next must be tuple of length 3! + (((tuple type value ignore) {{(when e ...)}} + ... ) + ... )}} + {{(after ... )}}) + +(funcall func arg ... ) +(call mod func arg ... ) - Call to Erlang Mod:Func(Arg, ... ) +(define-module name declaration ... ) +(extend-module declaration ... ) - Define/extend module and declarations. +(define-function name lambda|match-lambda) +(define-macro name lambda|match-lambda) - Define functions/macros at top-level. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros are part of the language to allow you to create abstractions +;; on top of the core language and standard library that move you closer +;; toward being able to directly express the things you want to express. + +;; Top-level function + +(defun name (arg ...) ...) + +;; Adding comments in functions + +(defun name + "Toplevel function with pattern-matching arguments" + ((argpat ...) ...) + ...) + +;; Top-level macro + +(defmacro name (arg ...) ...) +(defmacro name arg ...) + +;; Top-level macro with pattern matching arguments + +(defmacro name + ((argpat ...) ...) + ...) + +;; Top-level macro using Scheme inspired syntax-rules format + +(defsyntax name + (pat exp) + ...) + +;;; Local macros in macro or syntax-rule format + +(macrolet ((name (arg ... ) ... ) + ... ) + ... ) + +(syntaxlet ((name (pat exp) ...) + ...) + ...) + +;; Like CLISP + +(prog1 ...) +(prog2 ...) + +;; Erlang LFE module + +(defmodule name ...) + +;; Erlang LFE record + +(defrecord name ...) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Patterns and Guards +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Using patterns in LFE compared to that of Erlang + +;; Erlang ;; LFE +;; {ok, X} (tuple 'ok x) +;; error 'error +;; {yes, [X|Xs]} (tuple 'yes (cons x xs)) +;; <<34,F/float>> (binary 34 (f float)) +;; [P|Ps]=All (= (cons p ps) all) + + _ ; => is don't care while pattern matching + + (= pattern1 pattern2) ; => easier, better version of pattern matching + +;; Guards + +;; Whenever pattern occurs(let, case, receive, lc, etc) it can be followed by an optional +;; guard which has the form (when test ...). + +(progn gtest ...) ;; => Sequence of guard tests +(if gexpr gexpr gexpr) +(type-test e) +(guard-bif ...) ;; => Guard BIFs, arithmetic, boolean and comparison operators + +;;; REPL + +lfe>(set (tuple len status msg) #(8 ok "Trillian")) + #(8 ok "Trillian") +lfe>msg + "Trillian" + +;;; Program illustrating use of Guards + +(defun right-number? + ((x) (when (orelse (== x 42) (== x 276709))) + 'true) + ((_) 'false)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Functions +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; A simple function using if. + +(defun max (x y) + "The max function." + (if (>= x y) x y)) + +;; Same function using more clause + +(defun max + "The max function." + ((x y) (when (>= x y)) x) + ((x y) y)) + +;; Same function using similar style but using local functions defined by flet or fletrec + +(defun foo (x y) + "The max function." + (flet ((m (a b) "Local comment." + (if (>= a b) a b))) + (m x y))) + +;; LFE being Lisp-2 has separate namespaces for variables and functions +;; Both variables and function/macros are lexically scoped. +;; Variables are bound by lambda, match-lambda and let. +;; Functions are bound by top-level defun, flet and fletrec. +;; Macros are bound by top-level defmacro/defsyntax and by macrolet/syntaxlet. + +;; (funcall func arg ...) like CL to call lambdas/match-lambdas +;; (funs) bound to variables are used. + +;; separate bindings and special for apply. +apply _F (...), +apply _F/3 ( a1, a2, a3 ) + +;; Cons'ing in function heads +(defun sum (l) (sum l 0)) + (defun sum + (('() total) total) + (((cons h t) total) (sum t (+ h total)))) + +;; ``cons`` literal instead of constructor form + (defun sum (l) (sum l 0)) + (defun sum + (('() total) total) + ((`(,h . ,t) total) (sum t (+ h total)))) + +;; Matching records in function heads + +(defun handle_info + (('ping (= (match-state remote-pid 'undefined) state)) + (gen_server:cast (self) 'ping) + `#(noreply ,state)) + (('ping state) + `#(noreply ,state))) + +;; Receiving Messages + (defun universal-server () + (receive + ((tuple 'become func) + (funcall func)))) + +;; another way for receiving messages + + (defun universal-server () + (receive + (`#(become ,func) + (funcall func)))) + +;; Composing a complete function for specific tasks + +(defun compose (f g) + (lambda (x) + (funcall f + (funcall g x)))) + +(defun check () + (let* ((sin-asin (compose #'sin/1 #'asin/1)) + (expected (sin (asin 0.5))) + (compose-result (funcall sin-asin 0.5))) + (io:format "Expected answer: ~p~n" (list expected)) + (io:format "Answer with compose: ~p~n" (list compose-result)))) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Concurrency +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Message passing as done by Erlang's light-weight "processes". + +(defmodule messenger-back + (export (print-result 0) (send-message 2))) + +(defun print-result () + (receive + ((tuple pid msg) + (io:format "Received message: '~s'~n" (list msg)) + (io:format "Sending message to process ~p ...~n" (list pid)) + (! pid (tuple msg)) + (print-result)))) + +(defun send-message (calling-pid msg) + (let ((spawned-pid (spawn 'messenger-back 'print-result ()))) + (! spawned-pid (tuple calling-pid msg)))) + +;; Multiple simultaneous HTTP Requests: + +(defun parse-args (flag) + "Given one or more command-line arguments, extract the passed values. + + For example, if the following was passed via the command line: + + $ erl -my-flag my-value-1 -my-flag my-value-2 + + One could then extract it in an LFE program by calling this function: + + (let ((args (parse-args 'my-flag))) + ... + ) + In this example, the value assigned to the arg variable would be a list + containing the values my-value-1 and my-value-2." + (let ((`#(ok ,data) (init:get_argument flag))) + (lists:merge data))) + +(defun get-pages () + "With no argument, assume 'url parameter was passed via command line." + (let ((urls (parse-args 'url))) + (get-pages urls))) + +(defun get-pages (urls) + "Start inets and make (potentially many) HTTP requests." + (inets:start) + (plists:map + (lambda (x) + (get-page x)) urls)) + +(defun get-page (url) + "Make a single HTTP request." + (let* ((method 'get) + (headers '()) + (request-data `#(,url ,headers)) + (http-options ()) + (request-options '(#(sync false)))) + (httpc:request method request-data http-options request-options) + (receive + (`#(http #(,request-id #(error ,reason))) + (io:format "Error: ~p~n" `(,reason))) + (`#(http #(,request-id ,result)) + (io:format "Result: ~p~n" `(,result)))))) + + +;; Check out Erlang's documentation for more concurrency and OTP docs. +``` + +## Further Reading + +* [LFE DOCS](http://docs.lfe.io) +* [LFE GitBook](https://lfe.gitbooks.io/reference-guide/index.html) +* [LFE Wiki](https://en.wikipedia.org/wiki/LFE_(programming_language)) + +## Extra Info +* [LFE PDF](http://www.erlang-factory.com/upload/presentations/61/Robertvirding-LispFlavouredErlang.pdf) +* [LFE mail](https://groups.google.com/d/msg/lisp-flavoured-erlang/XA5HeLbQQDk/TUHabZCHXB0J) + +## Credits + +Lots of thanks to Robert Virding for creating LFE, Duncan McGreggor for documenting it and other LFE contributors who made LFE awesome. + diff --git a/perl6.html.markdown b/perl6.html.markdown index d0ccdc9a..44960347 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -54,10 +54,11 @@ my $forced-bool = so $str; # And you can use the prefix `so` operator # which turns its operand into a Bool ``` -### Lists +### Arrays and Lists ```perl6 -# Lists represent multiple values. Their name start with `@`. +# Arrays represent multiple values. Their name start with `@`. +# Lists are similar but are an immutable type my @array = 'a', 'b', 'c'; # equivalent to : diff --git a/php.html.markdown b/php.html.markdown index f247ba77..ac9b45a8 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -132,9 +132,7 @@ echo 'This outputs ' . FOO; // Returns 'This ouputs something' * Arrays */ -// All arrays in PHP are associative arrays (hashmaps), - -// Associative arrays, known as hashmaps in some languages. +// All arrays in PHP are associative arrays (hashmaps in some languages) // Works with all PHP versions $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); diff --git a/red.html.markdown b/red.html.markdown index 0c979ce1..5f6ffc86 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -136,14 +136,14 @@ if a < 0 [print "a is negative"] ; Evaluate a block of code if a given condition is true, else evaluate an ; alternative block of code. If the last expressions in both blocks have the ; same type, EITHER can be used inside an expression. -either a < 0 [ +either a > 0 [ + msg: "positive" +][ either a = 0 [ msg: "zero" ][ msg: "negative" ] -][ - msg: "positive" ] print ["a is " msg lf] @@ -151,14 +151,14 @@ print ["a is " msg lf] ; There is an alternative way to write this ; (Which is allowed because all code paths return a value of the same type): -msg: either a < 0 [ +msg: either a > 0 [ + "positive" +][ either a = 0 [ "zero" ][ "negative" ] - ][ - "positive" ] print ["a is " msg lf] diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index c9eb2a2e..c286366b 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -385,7 +385,7 @@ fun calculate_interest(n) = if n < 0.0 (* Exceptions can be caught using "handle" *) val balance = calculate_interest ~180.0 - handle Domain => ~180.0 (* x now has the value ~180.0 *) + handle Domain => ~180.0 (* balance now has the value ~180.0 *) (* Some exceptions carry extra information with them *) (* Here are some examples of built-in exceptions *) diff --git a/tcsh.html.markdown b/tcsh.html.markdown new file mode 100644 index 00000000..a95a84b0 --- /dev/null +++ b/tcsh.html.markdown @@ -0,0 +1,790 @@ +--- +language: tcsh +filename: LearnTCSH.csh +contributors: + - ["Nicholas Christopoulos", "https://github.com/nereusx"] +lang: en +--- +tcsh ("tee-see-shell") is a Unix shell based on and compatible with the C shell (csh). +It is essentially the C shell with programmable command-line completion, command-line editing, +and a few other features. +It is the native root shell for BSD-based systems such as FreeBSD. + +Almost all Linux distros and BSD today use tcsh instead of the original csh. In +most cases csh is a symbolic link that points to tcsh. +This is because tcsh is backward compatible with csh, and the last +is not maintained anymore. + +- [TCSH Home](http://www.tcsh.org/) +- [TCSH Wikipedia](https://en.wikipedia.org/wiki/Tcsh) +- [TCSH manual page](http://www.tcsh.org/tcsh.html/top.html) +- [“An Introduction to the C shell”, William Joy](https://docs.freebsd.org/44doc/usd/04.csh/paper.html) +- [TCSH Bug reports and/or features requests](https://bugs.gw.com/) + +Some more files: +[tcsh help command (for 132x35 terminal size)](https://github.com/nereusx/dotfiles/blob/master/csh-help), +[my ~/.tcshrc](https://github.com/nereusx/dotfiles/blob/master/.tcshrc) + +```tcsh +#!/bin/tcsh +# First line of the script is shebang which tells the system how to execute the +# script: http://en.wikipedia.org/wiki/Shebang_(Unix) +# TCSH emulates the shebang on systems which don't understand it. + +# In most cases you'll use `#!/bin/tcsh -f', because `-f' option does not load +# any resource or start-up files, or perform any command hashing, and thus +# starts faster. + +# --- the echo command -------------------------------------------------------- +# The `echo' writes each word to the shell's standard output, separated by +# spaces and terminated with a newline. The echo_style shell variable may be +# set to emulate (or not) the flags and escape sequences. + +# Display the value of echo_style +echo $echo_style + +# Enable `echo' to support backslashed characters and `-n' option (no new line) +# This is the default for tcsh, but your distro may change it. Slackware has +# done so. +set echo_style = both + +# Prints "Hello world" +echo Hello world +echo "Hello world" +echo 'Hello world' +echo `echo Hello world` + +# This prints "twonlines" in one line +echo two\nlines + +# Prints the two lines +echo "two\nlines" +echo 'two\nlines' + +# --- Basic Syntax ------------------------------------------------------------ + +# A special character (including a blank or tab) may be prevented from having +# its special meaning by preceding it with a backslash `\'. +# this will display the last history commands +echo !! +# this will not +echo \!\! + +# Single quotes prevents expanding special characters too, but some +# characters like `!' and backslash have higher priority +# `$' (variable value) will not expands +echo '$1 tip' +# `!' (history) will expands +echo '!!' + +# Strings enclosed by back-quotes will be executed and replaced by the result. +echo `ls` + +# Semi-colon separate commands +echo 'first line'; echo 'second line' + +# There is also conditional execution +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# Parenthesised commands are always executed in a subshell, + +# example: create a project and then informs you that it finished while +# it does the installation. +make && ( espeak "BOSS, compilation finished"; make install ) + +# prints the home directory but leaving you where you were +(cd; pwd); pwd + +# Read tcsh man-page documentation +man tcsh + +# --- Variables --------------------------------------------------------------- +# The shell maintains a list of variables, each of which has as value a list of +# zero or more words. The values of shell variables can be displayed and +# changed with the `set' and `unset' commands. +# The system maintains its own list of ``environment'' variables. +# These can be displayed and changed with `printenv', `setenv' and `unsetenv'. +# The syntax of setenv is similar to POSIX sh. + +# Assign a value or nothing will create a variable +# Assign nothing +set var +# Assign a numeric value +# the '@' denotes the expression is arithmetic; it works similar to 'set' but +# the right value can be a numeric expression. +@ var = 1 + 2 +# Assign a string value +set var = "Hello, I am the contents of 'var' variable" +# Assign the output of a program +set var = `ls` + +# Remove a variable +unset var +# Prints 1 (true) if the variable `var' exists otherwise prints 0 (false) +echo $?var +# Print all variables and their values +set + +# Prints the contents of 'var' +echo $var; +echo "$var"; +# Prints the string `$var' +echo \$var +echo '$var' +# braces can be used to separate variable from the rest when its needed +set num = 12; echo "There ${num}th element" + +# Prints the number of characters of the value: 6 +set var = '123456'; echo $%var + +### LISTs +# Assign a list of values +set var = ( one two three four five ) +# Print all the elements: one two three four five +echo $var +echo $var[*] +# Print the count of elements: 5 +echo $#var +# Print indexed element; prints the second element: two +echo $var[2] +# Print range of elements; prints 2nd up to 3rd: two, three +echo $var[2-3] +# Prints all elements starting from the 3rd: three four five +echo $var[3-] +# Prints print all up to 3rd element: one two three +echo $var[-3] + +### Special Variables +# $argv list of command-line arguments +# $argv[0] this file-name (the file of the script file) +# $# $0, $n, $* are the same as $#argv, $argv[0], $argv[n], $argv[*] +# $status, $? the exit code of the last command that executed +# $_ the previous command line +# $! the PID of the last background process started by this shell +# $$ script's PID + +# $path, $PATH the list of directories that will search for executable to run +# $home, $HOME user's home directory, also the `~' can be used instead +# $uid user's login ID +# $user user's login name +# $gid the user's group ID +# $group the user's group-name +# $cwd, $PWD the Current/Print Working Directory +# $owd the previous working directory +# $tcsh tcsh version +# $tty the current tty; ttyN for linux console, pts/N for terminal +# emulators under X +# $term the terminal type +# $verbose if set, causes the words of each command to be printed. +# can be set by the `-v' command line option too. +# $loginsh if set, it is a login shell + +# TIP: $?0 is always false in interactive shells +# TIP: $?prompt is always false in non-interactive shells +# TIP: if `$?tcsh' is unset; you run the original `csh' or something else; +# try `echo $shell' +# TIP: $verbose this is useful to debugging scripts +# NOTE: $PWD and $PATH are synchronised with $cwd and $pwd automatically. + +# --- Variable modifiers ------------------------------------------------------ +# Syntax: ${var}:m[:mN] +# Where <m> is: +# h : the directory t : the filenane r : remove extension e : the extension +# u : uppercase the first lowercase letter +# l : lowercase the first uppercase letter +# p : print but do not execute it (hist) +# q : quote the substituted words, preventing further substitutions +# x : like q, but break into words at white spaces +# g : apply the following modifier once to each word +# a : apply the following modifier as many times as possible to single word +# s/l/r/ : search for `l' and replace with `r', not regex; the `&' in the r is +# replaced by l +# & : Repeat the previous substitution + +# start with this file +set f = ~/Documents/Alpha/beta.txt +# prints ~/Documents/Alpha/beta +echo $f:r +# prints ~/Documents/Alpha +echo $f:h +# prints beta.txt +echo $f:t +# prints txt +echo $f:e +# prints beta +echo $f:t:r +# prints Beta +echo $f:t:r:u +# prints Biota +echo $f:t:r:u:s/eta/iota/ + +# --- Redirection ------------------------------------------------------------- + +# Create file.txt and write the standard output to it +echo 'this string' > file.txt +# Create file.txt and write the standard output and standard error to it +echo 'this string' >& file.txt +# Append the standard output to file.txt +echo 'this string' >> file.txt +# Append the standard output and standard error to file.txt +echo 'this string' >>& file.txt +# Redirect the standard input from file.txt +cat < file.txt +# Input from keyboard; this stores the input line to variable `x' +set x = $< +# Document here; +cat << LABEL +...text here... +LABEL + +# TIP: this is how to get standard error separated: +(grep 'AGP' /usr/src/linux/Documentation/* > output-file.txt) >& error-file.txt + +# example: read a name from standard input and display a greetings message +echo -n "Enter your name? " +set name = $< +echo "Greetings $name" + +# --- Expressions ------------------------------------------------------------ + +# Operators: +# == equal != not equal ! not +# > greater than < less than >= greater or equal <= less or equal +# && logical AND || logical OR + +if ( $name != $user ) then + echo "Your name isn't your username" +else + echo "Your name is your username" +endif + +# single-line form +if ( $name != $user ) echo "Your name isn't your username" + +# NOTE: if $name is empty, tcsh sees the above condition as: +# if ( != $user ) ... +# which is invalid syntax +# so the "safe" way to use potentially empty variables in tcsh is: +# if ( "$name" != $user ) ... +# which, when $name is empty, is seen by tcsh as: +# if ( "" != $user ) ... +# which works as expected + +# There is also conditional execution +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# To use && and || with if statements, you don't need multiple pairs of +# square brackets: +if ( "$name" == "Steve" && "$age" == 15 ) then + echo "This will run if $name is Steve AND $age is 15." +endif + +if ( "$name" == "Daniya" || "$name" == "Zach" ) then + echo "This will run if $name is Daniya OR Zach." +endif + +# String matching operators ( `=~' and `!~' ) +# The ‘==’ ‘!=’ ‘=~’ and ‘!~’ operators compare their arguments as strings; +# all others operate on numbers. The operators ‘=~’ and ‘!~’ are like ‘!=’ +# and ‘==’ except that the right hand side is a glob-pattern against which +# the left hand operand is matched. + +if ( $user =~ ni[ck]* ) echo "Greetings Mr. Nicholas." +if ( $user !~ ni[ck]* ) echo "Hey, get out of Nicholas PC." + +# Arithmetic expressions are denoted with the following format: +@ result = 10 + 5 +echo $result + +# Arithmetic Operators +# +, -, *, /, % +# +# Arithmetic Operators which must be parenthesised +# !, ~, |, &, ^, ~, <<, >>, +# Compare and logical operators +# +# All operators are same as in C. + +# It is non so well documented that numeric expressions require spaces +# in-between; Also, `@' has its own parser, it seems that work well when the +# expression is parenthesised otherwise the primary parser seems it is active. +# Parenthesis require spaces around, this is documented. + +# wrong +@ x = $y+1 +@ x = 0644 & 022; echo $x +@ x = (0644 & 022) +1; echo $x +@ x = (0644 & 022)+ 1; echo $x +@ x = ( ~077 ); echo $x + +# correct +@ x = $y + 1 +@ x = ( 0644 & 022 ) + 1; echo $x +@ x = ( ~ 077 ); echo $x +@ x = ( ~ 077 | 022 ); echo $x +@ x = ( ! 0 ); echo $x + +# C's operators ++ and -- are supported if there is not assignment +@ result ++ + +# None shell created to do mathematics; +# Except for the basic operations, use an external command with backslashes. +# +# I suggest the calc as the best option. +# (http://www.isthe.com/chongo/tech/comp/calc/) +# +# The standard Unix's bc as second option +# (https://www.gnu.org/software/bc/manual/html_mono/bc.html) +# +# The standard Unix's AWK as third option +# (https://www.gnu.org/software/gawk/manual/gawk.html) + +# You can also use `perl', `php' or even several BASICs, but prefer the +# above utilities for faster load-and-run results. + +# real example: (that I answer in StackExchange) +# REQ: x := 1001b OR 0110b + +# in `tcsh' expression (by using octal) +@ x = ( 011 | 06 ); echo $x + +# the same by using `calc' (and using binary as the original req) +set x = `calc '0b1001 | 0b110'`; echo $x + +# --- File Inquiry Operators -------------------------------------------------- +# NOTE: The builtin `filetest' command do the same thing. + +#### Boolean operators +# -r read access -w write access -x execute access -e existence +# -f plain file -d directory -l symbolic link -p named pipe +# -S socket file +# -o ownership -z zero size -s non-zero size +# -u SUID is set -g SGID is set -k sticky is set +# -b block device -c char device +# -t file (digit) is an open file descriptor for a terminal device + +# if the file `README' exists, displays a message +if ( -e README ) echo "I have already README file" + +# if the `less' program is installed, use this instead of `more' +if ( -e `where less` ) then + alias more 'less' +endif + +#### Non-boolean operators +# -Z returns the file size in bytes +# -M returns the modification time (mtime) -M: returns mtime string +# -A returns the lass access time (atime) -A: returns atime string +# -U returns the owners user ID -U: returns the owners user-name +# -G returns the group ID -G: returns the group-name +# -P returns the permissions as octal number -Pmode returns perm. AND mode + +# this will display the date as Unix-time integer: 1498511486 +filetest -M README.md + +# This will display "Tue Jun 27 00:11:26 2017" +filetest -M: README.md + +# --- Basic Commands ---------------------------------------------------------- + +# Navigate though file system with `chdir' (cd) +cd path # change working directory +cd # change to home directory +cd - # change to previous directory +cd .. # go up one directory + +# Examples: +cd ~/Downloads # go to my `Downloads' directory + +# Use `mkdir` to create new directories. +mkdir newdir +# The `-p` flag causes new intermediate directories to be created as necessary. +mkdir -p ~/.backup/saves + +# which & where +# find if csh points to tcsh +ls -lha `which csh` +# find if csh is installed on more than one directory +where csh + +# --- Pipe-lines -------------------------------------------------------------- +# A pipeline is a sequence of processes chained together by their standard +# streams, so that the output of each process (stdout) feeds directly as input +# (stdin) to the next one. This `pipes' are created with the `|' special +# character and it is one of the most powerful characteristics of Unix. + +# example: +ls -l | grep key | less +# "ls -l" produces a process, the output (stdout) of which is piped to the +# input (stdin) of the process for "grep key"; and likewise for the process +# for "less". + +# the `ls', the `grep' and the `less' are programs of Unix and they have their +# own man-page. The `pipe' mechanism is part of the kernel but the syntax +# and the control is job of the shell, the tcsh in our case. + +# NOTE: `pipe' mechanism has Windows too, but it is buggy and I sign it for all +# versions until Windows XP SP3 API32 which was the last one that I worked on. +# Microsoft still denied it but is well known bug since it is a common method +# for inter-process communication. For small I/O it will work well. +# tcsh, along with grep, gcc and perl is one of the first Unix programs that +# ported to DOS (with EMX DOS extender) and later to Windows (1998). + +# example: this will convert tcsh to PostScript and will show it with okular +zcat /usr/man/man1/tcsh.1.gz | groff -Tps -man | okular - + +# a better version +zcat `locate -b -n 1 '\tcsh.1.gz'` | groff -Tps -man | okular - + +# even better +set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz"); + zcat `eval $loc` | groff -Tps -man | okular - + +# the same, modified to create man page pdf +set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz"); + zcat `eval $loc` | groff -Tps -man | ps2pdf - ${page}.pdf + +# the same, but now shows the ${page}.pdf too +set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz"); + zcat `eval $loc` | groff -Tps -man | ps2pdf - ${page}.pdf && okular tcsh.pdf + +# NOTE: `okular' is the default application of KDE environment and it shows +# postcript and pdf files. You can replace it with your lovely pdf viewer. +# zcat, locate, groff, are common programs in all Unices. `ps2pdf' program +# is part of `ghostscript' package that is widely used. + +# --- Control Flow ------------------------------------------------------------ + +#### IF-THEN-ELSE-ENDIF +# Syntax: +# if ( expr ) then +# ... +# [else if ( expr2 ) then +# ...] +# [else +# ...] +# endif +# +# If the specified expr is true then the commands to the first else are +# executed; otherwise if expr2 is true then the commands to the second else +# are executed, etc. +# Any number of else-if pairs are possible; only one endif is needed. +# +# Single-line form: +# +# if ( expr ) command +# +# If `expr' evaluates true, then command is executed. +# `command' must be a simple command, not an alias, a pipeline, a command list +# or a parenthesized command list. With few words, avoid to use it. +# +# BUG: Input/output redirection occurs even if expr is false and command is +# thus not executed. +# + +# check if we are in non-interactive shell and quit if true +if ( $?USER == 0 || $?prompt == 0 ) exit + +# check if we are a login shell +if ( $?loginsh ) then + # check if you are on linux console (not X's terminal) + if ( $tty =~ tty* ) then + # enable keypad application keys (man console_codes) + echo '\033=' + endif +endif + +#### SWITCH-ENDSW +# Syntax: +# switch ( expr ) +# case pattern: +# ... +# [breaksw] +# [default: +# ...] +# endsw +# +# tcsh uses a case statement that works similarly to switch in C. +# Each case label is successively matched, against the specified string which +# is first command and filename expanded. The file metacharacters `*', `?' +# and `[...]' may be used in the case labels. If none of the labels match the +# execution begins after the default label if its defined. +# The command `breaksw' causes execution to continue after the endsw. Otherwise +# control may fall through case labels and default labels as in C. + +switch ( $var ) +case *.[1-9]: +case *.[1-9].gz: + echo "$var is a man-page." + breaksw +case *gz: + echo "$var is gzipped" + breaksw +default: + file $var +endsw + +#### FOREACH-END +# Syntax: +# foreach name ( wordlist ) +# ... +# [break | continue] +# end +# +# Successively sets the variable `name' to each member of `wordlist' and +# executes the sequence of commands between this command and the matching +# `end' keyword. The `continue' keyword jump to the next element back to +# top; and the `break' keyword terminates the loop. +# +# BUG: `foreach' doesn't ignore here documents when looking for its end. + +# example: counting 1 to 10 +foreach i ( `seq 1 10` ) + echo $i +end + +# example: type all files in the list +foreach f ( a.txt b.txt c.txt ) + cat $f +end + +# example: convert wma to ogg +foreach f ( *.wma ) + ffmpeg -i "$f" "$f:r".ogg +end + +#### WHILE-END +# while ( expr ) +# ... +# [break | continue] +# end +# +# Executes the commands between the `while' and the matching `end' while `expr' +# evaluates non-zero. `break' and `continue' may be used to terminate or +# continue the loop prematurely. + +# count from 1 to 10 +set num = 1 +while ( $num <= 10 ) + echo $num + @ num ++ +end + +# print all directories of CWD +set lst = ( * ) +while ( $#lst ) + if ( -d $lst[1] ) echo $lst[1] is directory + shift lst +end + +# separate command-line arguments to options or parameters +set options +set params +set lst = ( $* ) +while ( $#lst ) + if ( "$lst[1]" =~ '-*' ) then + set options = ( $options $lst[1] ) + else + set params = ( $params $lst[1] ) + endif + shift lst +end +echo 'options =' $options +echo 'paramaters =' $params + +#### REPEAT +# Syntax: repeat count command +# +# The specified command, which is subject to the same restrictions as the +# command in the one line if statement above, is executed count times. +# I/O redirections occur exactly once, even if count is 0. +# +# TIP: in most cases prefer `while' + +repeat 3 echo "ding dong" + +# --- Functions --------------------------------------------------------------- +# tcsh has no functions but its expression syntax is advanced enough to use +# `alias' as functions. Another method is recursion + +# Alias argument selectors; the ability to define an alias to take arguments +# supplied to it and apply them to the commands that it refers to. +# Tcsh is the only shell that provides this feature. +# +# \!# argument selector for all arguments, including the alias/command +# itself; arguments need not be supplied. +# \!* argument selector for all arguments, excluding the alias/command; +# arguments need not be supplied. +# \!$ argument selector for the last argument; argument need not be supplied, +# but if none is supplied, the alias name is considered to be the +# last argument. +# \!^ argument selector for first argument; argument MUST be supplied. +# \!:n argument selector for the nth argument; argument MUST be supplied; +# n=0 refers to the alias/command name. +# \!:m-n argument selector for the arguments from the mth to the nth; +# arguments MUST be supplied. +# \!:n-$ argument selector for the arguments from the nth to the last; +# at least argument n MUST be supplied. + +# Alias the cd command so that when you change directories, the contents +# are immediately displayed. +alias cd 'cd \!* && ls' + +# --- Recursion method --- begin --- +#!/bin/tcsh -f +set todo = option1 +if ( $#argv > 0 ) then + set todo = $argv[1] +endif + +switch ( $todo ) +case option1: +# ... + $0 results + breaksw +case option2: +# ... + $0 results + breaksw +case results: + echo "print the results here" +# ... + breaksw +default: + echo "Unknown option: $todo" +# exit 0 +endsw +# --- Recursion method --- end --- + +# --- examples ---------------------------------------------------------------- + +# this script prints available power-states if no argument is set; +# otherwise it set the state of the $argv[1] +# --- power-state script --- begin -------------------------------------------- +#!/bin/tcsh -f +# get parameter ("help" for none) +set todo = help +if ( $#argv > 0 ) then + set todo = $argv[1] +endif +# available options +set opts = `cat /sys/power/state` +# is known? +foreach o ( $opts ) + if ( $todo == $o ) then + # found; execute it + echo -n $todo > /sys/power/state + break + endif +end +# print help and exit +echo "usage: $0 [option]" +echo "available options on kernel: $opts" +# --- power-state script --- end ---------------------------------------------- + +# Guess the secret number game +# --- secretnum.csh --- begin ------------------------------------------------- +#!/bin/tcsh -f +set secret=`shuf -i1-100 -n1` +echo "I have a secret number from 1 up to 100" +while ( 1 ) + echo -n "Guess: " + set guess = $< + if ( $secret == $guess ) then + echo "You found it" + exit 1 + else + if ( $secret > $guess ) then + echo "its greater" + else if ( $secret < $guess ) then + echo "its lesser" + endif + endif + endif +end +# --- secretnum.csh --- end --------------------------------------------------- + +# ----------------------------------------------------------------------------- +# Appendices + +#### About [T]CSH: +# * CSH is notorious about its bugs; +# * It was also famous about its advanced interactive mode. +# * TCSH is famous that have the most advanced completition subsystem. +# * TCSH is famous that have the most advanced aliases subsystem; aliases +# can take parameters and often used as functions! +# * TCSH is well known that preferred by people (me too) because of better +# syntax. All shells are using Thomson's syntax with exception of [t]csh, +# fish and plan9's shells (rc, ex). +# * It is smaller and consume far less memory than bash, zsh even mksh! +# (memusage reports) +# * TCSH still has bugs; less but have; if you write readable clean code you'll +# find none; well almost none... This has to do with the implementation of +# csh; that no means the other shells has good implementation. +# * no one well known shell is capable for regular programming; if your script +# getting big, use a programming language, or at least PHP or Perl (good +# script languages). +# +# Advises: +# 1. Do not use redirection in single-line if (it is well documented bug) +# In most cases avoid to use single-line IFs. +# 2. Do not mess up with other shells code, c-shell is not compatible with +# other shells and has different abilities and priorities. +# 3. Use spaces as you'll use them to write readable code in any language. +# A bug of csh was `set x=1' worked, `set x = 1' worked, `set x =1' did not! +# 4. It is well documented that numeric expressions require spaces in-between; +# also parenthesise all bit-wise and unary operators. +# 5. Do not write a huge weird expression with several quotes, backslashes etc +# It is bad practice for generic programming, it is dangerous in any shell. +# 6. Help tcsh, report the bug here <https://bugs.gw.com/> +# 7. Read the man page, `tcsh' has huge number of options, and variables. +# +# I suggest the following options enabled by default +# -------------------------------------------------- +# Even in non-interactive shells +# set echo_style=both +# set backslash_quote +# set parseoctal +# unset noclobber +# +# Whatever... +# set inputmode=insert +# set autolist +# set listjobs +# set padhour +# set color +# set colorcat +# set nobeep +# set cdtohome +# +# set histdup +# set histlit +# set nohistclop +# +# unset compat_expr +# unset noglob +# unset autologout +# unset time +# unset tperiod +# +# NOTE: If the `backslash_quote' is set, it may create compatibility issues +# with other tcsh scripts which was written without it. +# +# NOTE: The same for `parseoctal', but it is better to fix the problematic +# scripts. +# +# NOTE: **for beginners only** +# This enable automatically rescan `path' directories if need to. (like bash) +# set autorehash + +#### common aliases +# alias hist 'history 20' +# alias ll 'ls --color -lha' +# alias today "date '+%d%h%y' +# alias ff 'find . -name ' + +#### a nice prompt +# set prompt = "%B%{\033[35m%}%t %{\033[32m%}%n@%m%b %C4 %# " +``` diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index 1e9c38f6..27003f3e 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -108,7 +108,7 @@ public class LearnJava { boolean [] booleanArray = new boolean[100]; // 声明并初始化数组也可以这样: - int [] y = {9000, 1000, 1337}; + int [] intArray = {9000, 1000, 1337}; // 随机访问数组中的元素 System.out.println("intArray @ 0: " + intArray[0]); @@ -309,7 +309,7 @@ class Bicycle { name = "Bontrager"; } - // 一下是一个含有参数的构造函数 + // 以下是一个含有参数的构造函数 public Bicycle(int startCadence, int startSpeed, int startGear, String name) { this.gear = startGear; this.cadence = startCadence; |