diff options
-rw-r--r-- | haxe.html.markdown | 426 | ||||
-rw-r--r-- | julia.html.markdown | 2 | ||||
-rw-r--r-- | matlab.html.markdown | 260 | ||||
-rw-r--r-- | php.html.markdown | 5 | ||||
-rw-r--r-- | python.html.markdown | 34 | ||||
-rw-r--r-- | ru-ru/erlang-ru.html.markdown | 255 | ||||
-rw-r--r-- | tr-tr/python-tr.html.markdown | 502 |
7 files changed, 1405 insertions, 79 deletions
diff --git a/haxe.html.markdown b/haxe.html.markdown index 90b2e250..f4694fcb 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -16,40 +16,62 @@ references. Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org This is an executable tutorial. You can compile and run it using the haxe compiler, while in the same directory as LearnHaxe.hx: - haxe -main LearnHaxe3 -x out - */ + $> haxe -main LearnHaxe3 -x out -// Let's start with comments... this is a single line comment + Look for the slash-star marks surrounding these paragraphs. We are inside + a "Multiline comment". We can leave some notes here that will get ignored + by the compiler. + + Multiline comments are also used to generate javadoc-style documentation for + haxedoc. They will be used for haxedoc if they immediately precede a class, + class function, or class variable. -/* - And this is multiline. Multiline comments are also used to generate - javadoc-style documentation for haxedoc. They will be used if they precede - a class, class function, or class variable. */ +// Double slashes like this will give a single-line comment + + /* - A package declaration isn't necessary, but it's useful if you want to - organize your code into modules later on. Also worth mentioning, all - expressions in Haxe must end in a semicolon: + This is your first actual haxe code coming up, it's declaring an empty + package. A package isn't necessary, but it's useful if you want to create a + namespace for your code (e.g. org.module.ClassName). */ package; // empty package, no namespace. - -// if you import code from other files, it must be declared before the rest of -// the code. +/* + Packages define modules for your code. Each module (e.g. org.module) must + be lower case, and should exist as a folder structure containing the class. + Class (and type) names must be capitalized. E.g, the class "org.module.Foo" + should have the folder structure org/module/Foo.hx, as accessible from the + compiler's working directory or class path. + + If you import code from other files, it must be declared before the rest of + the code. Haxe provides a lot of common default classes to get you started: + */ import haxe.ds.ArraySort; // you can import many classes/modules at once with "*" import haxe.ds.*; -// you can also import classes in a special way, enabling them to extend the -// functionality of other classes. More on this later. +/* + You can also import classes in a special way, enabling them to extend the + functionality of other classes like a "mixin". More on 'using' later. + */ using StringTools; -// Haxe files typically define classes, although they can also define other -// types of code... more on that later. +/* + Typedefs are like variables... for types. They must be declared before any + code. More on this later. + */ +typedef FooString = String; +// Typedefs can also reference "structural" types, more on that later as well. +typedef FooObject = { foo: String }; +/* + Here's the class definition. It's the main class for the file, since it has + the same name (LearnHaxe3). + */ class LearnHaxe3{ /* If you want certain code to run automatically, you need to put it in @@ -58,6 +80,7 @@ class LearnHaxe3{ arguments above. */ static function main(){ + /* Trace is the default method of printing haxe expressions to the screen. Different targets will have different methods of @@ -67,8 +90,6 @@ class LearnHaxe3{ Finally, It's possible to prevent traces from showing by using the "--no-traces" argument on the compiler. */ - - trace("Hello World, with trace()!"); /* @@ -76,16 +97,11 @@ class LearnHaxe3{ a representation of the expression as best it can. You can also concatenate strings with the "+" operator: */ - trace( - " Integer: " + 10 + - " Float: " + 3.14 + - " Boolean: " + true - ); - + trace( " Integer: " + 10 + " Float: " + 3.14 + " Boolean: " + true); /* - Remember what I said about expressions needing semicolons? You - can put more than one expression on a line if you want. + In Haxe, it's required to separate expressions in the same block with + semicolons. But, you can put two expressions on one line: */ trace('two expressions..'); trace('one line'); @@ -99,7 +115,6 @@ class LearnHaxe3{ You can save values and references to data structures using the "var" keyword: */ - var an_integer:Int = 1; trace(an_integer + " is the value for an_integer"); @@ -111,7 +126,6 @@ class LearnHaxe3{ the haxe compiler is inferring that the type of another_integer should be "Int". */ - var another_integer = 2; trace(another_integer + " is the value for another_integer"); @@ -137,8 +151,14 @@ class LearnHaxe3{ var a_string = "some" + 'string'; // strings can have double or single quotes trace(a_string + " is the value for a_string"); + /* + Strings can be "interpolated" by inserting variables into specific + positions. The string must be single quoted, and the variable must + be preceded with "$". Expressions can be enclosed in ${...}. + */ var x = 1; var an_interpolated_string = 'the value of x is $x'; + var another_interpolated_string = 'the value of x + 1 is ${x + 1}'; /* Strings are immutable, instance methods will return a copy of @@ -149,6 +169,12 @@ class LearnHaxe3{ trace(a_sub_string + " is the value for a_sub_string"); /* + Regexes are also supported, but there's not enough space to go into + much detail. + */ + trace((~/foobar/.match('foo')) + " is the value for (~/foobar/.match('foo')))"); + + /* Arrays are zero-indexed, dynamic, and mutable. Missing values are defined as null. */ @@ -191,7 +217,7 @@ class LearnHaxe3{ trace(m3 + " is the value for m3"); /* - Haxe has many more common datastructures in the haxe.ds module, such as + Haxe has some more common datastructures in the haxe.ds module, such as List, Stack, and BalancedTree */ @@ -199,7 +225,6 @@ class LearnHaxe3{ ////////////////////////////////////////////////////////////////// // Operators ////////////////////////////////////////////////////////////////// - trace("***OPERATORS***"); // basic arithmetic @@ -218,7 +243,7 @@ class LearnHaxe3{ trace((3 >= 2) + " is the value for 3 >= 2"); trace((3 <= 2) + " is the value for 3 <= 2"); - //bitwise operators + // standard bitwise operators /* ~ Unary bitwise complement << Signed left shift @@ -252,6 +277,27 @@ class LearnHaxe3{ trace("also not printed."); } + // there is also a "ternary" if: + (j == 10) ? trace("equals 10") : trace("not equals 10"); + + /* + Finally, there is another form of control structures that operates + at compile time: conditional compilation. + */ +#if neko + trace('hello from neko'); +#elseif js + trace('hello from js'); +#else + trace('hello from another platform!'); +#end + /* + The compiled code will change depending on the platform target. + Since we're compiling for neko (-x or -neko), we only get the neko + greeting. + */ + + trace("Looping and Iteration"); // while loop @@ -310,13 +356,14 @@ class LearnHaxe3{ generalized algebraic data types in enums (more on enums later). Here's some basic value examples for now: */ - var my_dog_name = 'fido'; - var favorite_thing = ''; + var my_dog_name = "fido"; + var favorite_thing = ""; switch(my_dog_name){ - case "fido" : favorite_thing = 'bone'; - case "rex" : favorite_thing = 'shoe'; - case "spot" : favorite_thing = 'tennis ball'; - case _ : favorite_thing = 'some unknown treat'; + case "fido" : favorite_thing = "bone"; + case "rex" : favorite_thing = "shoe"; + case "spot" : favorite_thing = "tennis ball"; + default : favorite_thing = "some unknown treat"; + // case _ : "some unknown treat"; // same as default } // The "_" case above is a "wildcard" value // that will match anything. @@ -345,10 +392,10 @@ class LearnHaxe3{ trace("K equals ", k); // outputs 10 var other_favorite_thing = switch(my_dog_name) { - case "fido" : 'teddy'; - case "rex" : 'stick'; - case "spot" : 'football'; - case _ : 'some unknown treat'; + case "fido" : "teddy"; + case "rex" : "stick"; + case "spot" : "football"; + default : "some unknown treat"; } trace("My dog's name is" + my_dog_name @@ -358,6 +405,7 @@ class LearnHaxe3{ ////////////////////////////////////////////////////////////////// // Converting Value Types ////////////////////////////////////////////////////////////////// + trace("***CONVERTING VALUE TYPES***"); // You can convert strings to ints fairly easily. @@ -372,33 +420,93 @@ class LearnHaxe3{ true + ""; // returns "true"; // See documentation for parsing in Std for more details. + + ////////////////////////////////////////////////////////////////// + // Dealing with Types + ////////////////////////////////////////////////////////////////// + + /* + + As mentioned before, Haxe is a statically typed language. All in + all, static typing is a wonderful thing. It enables + precise autocompletions, and can be used to thoroughly check the + correctness of a program. Plus, the Haxe compiler is super fast. + + *HOWEVER*, there are times when you just wish the compiler would let + something slide, and not throw a type error in a given case. + + To do this, Haxe has two separate keywords. The first is the + "Dynamic" type: + */ + var dyn: Dynamic = "any type of variable, such as this string"; + + /* + All that you know for certain with a Dynamic variable is that the + compiler will no longer worry about what type it is. It is like a + wildcard variable: You can pass it instead of any variable type, + and you can assign any variable type you want. + + The other more extreme option is the "untyped" keyword: + */ + + untyped { + var x:Int = 'foo'; // this can't be right! + var y:String = 4; // madness! + } + + /* + The untyped keyword operates on entire *blocks* of code, skipping + any type checks that might be otherwise required. This keyword should + be used very sparingly, such as in limited conditionally-compiled + situations where type checking is a hinderance. + + In general, skipping type checks is *not* recommended. Use the + enum, inheritance, or structural type models in order to help ensure + the correctness of your program. Only when you're certain that none + of the type models work should you resort to "Dynamic" or "untyped". + */ + ////////////////////////////////////////////////////////////////// // Basic Object Oriented Programming ////////////////////////////////////////////////////////////////// trace("***BASIC OBJECT ORIENTED PROGRAMMING***"); - // create an instance of FooClass. The classes for this are at the - // end of the file. - var instance = new FooClass(3); + /* + Create an instance of FooClass. The classes for this are at the + end of the file. + */ + var foo_instance = new FooClass(3); // read the public variable normally - trace(instance.public_any + " is the value for instance.public_any"); + trace(foo_instance.public_any + " is the value for foo_instance.public_any"); // we can read this variable - trace(instance.public_read + " is the value for instance.public_read"); + trace(foo_instance.public_read + " is the value for foo_instance.public_read"); // but not write it - // instance.public_write = 4; // this will throw an error if uncommented: - // trace(instance.public_write); // as will this. + // foo_instance.public_write = 4; // this will throw an error if uncommented: + // trace(foo_instance.public_write); // as will this. + + trace(foo_instance + " is the value for foo_instance"); // calls the toString method + trace(foo_instance.toString() + " is the value for foo_instance.toString()"); // same thing - trace(instance + " is the value for instance"); // calls the toString method - trace(instance.toString() + " is the value for instance.toString()"); // same thing + /* + The foo_instance has the "FooClass" type, while acceptBarInstance + has the BarClass type. However, since FooClass extends BarClass, it + is accepted. + */ + BarClass.acceptBarInstance(foo_instance); + + /* + The classes below have some more advanced examples, the "example()" + method will just run them here. + */ + SimpleEnumTest.example(); + ComplexEnumTest.example(); + TypedefsAndStructuralTypes.example(); + UsingExample.example(); - // instance has the "FooClass" type, while acceptBaseFoo has the - // BaseFooClass type. However, since FooClass extends BaseFooClass, - // it is accepted. - BaseFooClass.acceptBaseFoo(instance); } } @@ -406,7 +514,7 @@ class LearnHaxe3{ /* This is the "child class" of the main LearnHaxe3 Class */ -class FooClass extends BaseFooClass implements BaseFooInterface{ +class FooClass extends BarClass implements BarInterface{ public var public_any:Int; // public variables are accessible anywhere public var public_read (default,null): Int; // use this style to only enable public read public var public_write (null, default): Int; // or public write @@ -418,7 +526,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ // a public constructor public function new(arg:Int){ - super(); // call the constructor of the parent object, since we extended BaseFooClass + super(); // call the constructor of the parent object, since we extended BarClass this.public_any= 0; this._private = arg; @@ -442,7 +550,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ } // this class needs to have this function defined, since it implements - // the BaseFooInterface interface. + // the BarInterface interface. public function baseFunction(x: Int) : String{ // convert the int to string automatically return x + " was passed into baseFunction!"; @@ -452,21 +560,217 @@ class FooClass extends BaseFooClass implements BaseFooInterface{ /* A simple class to extend */ -class BaseFooClass { +class BarClass { var base_variable:Int; public function new(){ base_variable = 4; } - public static function acceptBaseFoo(b:BaseFooClass){ + public static function acceptBarInstance(b:BarClass){ } } /* A simple interface to implement */ -interface BaseFooInterface{ +interface BarInterface{ public function baseFunction(x:Int):String; } +////////////////////////////////////////////////////////////////// +// Enums and Switch Statements +////////////////////////////////////////////////////////////////// + +/* + Enums in Haxe are very powerful. In their simplest form, enums + are a type with a limited number of states: + */ + +enum SimpleEnum { + Foo; + Bar; + Baz; +} + +// Here's a class that uses it: + +class SimpleEnumTest{ + public static function example(){ + var e_explicit:SimpleEnum = SimpleEnum.Foo; // you can specify the "full" name + var e = Foo; // but inference will work as well. + switch(e){ + case Foo: trace("e was Foo"); + case Bar: trace("e was Bar"); + case Baz: trace("e was Baz"); // comment this line to throw an error. + } + + /* + This doesn't seem so different from simple value switches on strings. + However, if we don't include *all* of the states, the compiler will + complain. You can try it by commenting out a line above. + + You can also specify a default for enum switches as well: + */ + switch(e){ + case Foo: trace("e was Foo again"); + default : trace("default works here too"); + } + } +} + +/* + Enums go much further than simple states, we can also enumerate + *constructors*, but we'll need a more complex enum example + */ +enum ComplexEnum{ + IntEnum(i:Int); + MultiEnum(i:Int, j:String, k:Float); + SimpleEnumEnum(s:SimpleEnum); + ComplexEnumEnum(c:ComplexEnum); +} +// Note: The enum above can include *other* enums as well, including itself! + +class ComplexEnumTest{ + public static function example(){ + var e1:ComplexEnum = IntEnum(4); // specifying the enum parameter + /* + Now we can switch on the enum, as well as extract any parameters + it might of had. + */ + switch(e1){ + case IntEnum(x) : trace('$x was the parameter passed to e1'); + default: trace("Shouldn't be printed"); + } + + // another parameter here that is itself an enum... an enum enum? + var e2 = SimpleEnumEnum(Foo); + switch(e2){ + case SimpleEnumEnum(s): trace('$s was the parameter passed to e2'); + default: trace("Shouldn't be printed"); + } + + // enums all the way down + var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); + switch(e3){ + // You can look for certain nested enums by specifying them explicitly: + case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : { + trace('$i, $j, and $k were passed into this nested monster'); + } + default: trace("Shouldn't be printed"); + } + /* + Check out "generalized algebraic data types" (GADT) for more details + on why these are so great. + */ + } +} + +class TypedefsAndStructuralTypes { + public static function example(){ + /* + Here we're going to use typedef types, instead of base types. + At the top we've declared the type "FooString" to mean a "String" type. + */ + var t1:FooString = "some string"; + + /* + We can use typedefs for "structural types" as well. These types are + defined by their field structure, not by class inheritance. Here's + an anonymous object with a String field named "foo": + */ + + var anon_obj = { foo: 'hi' }; + + /* + The anon_obj variable doesn't have a type declared, and is an + anonymous object according to the compiler. However, remember back at + the top where we declared the FooObj typedef? Since anon_obj matches + that structure, we can use it anywhere that a "FooObject" type is + expected. + */ + + var f = function(fo:FooObject){ + trace('$fo was passed in to this function'); + } + f(anon_obj); // call the FooObject signature function with anon_obj. + + /* + Note that typedefs can have optional fields as well, marked with "?" + + typedef OptionalFooObj = { + ?optionalString: String, + requiredInt: Int + } + */ + + /* + Typedefs work well with conditional compilation. For instance, + we could have included this at the top of the file: + +#if( js ) + typedef Surface = js.html.CanvasRenderingContext2D; +#elseif( nme ) + typedef Surface = nme.display.Graphics; +#elseif( !flash9 ) + typedef Surface = flash8.MovieClip; +#elseif( java ) + typedef Surface = java.awt.geom.GeneralPath; +#end + + That would give us a single "Surface" type to work with across + all of those platforms. + */ + } +} + +class UsingExample { + public static function example() { + + /* + The "using" import keyword is a special type of class import that + alters the behavior of any static methods in the class. + + In this file, we've applied "using" to "StringTools", which contains + a number of static methods for dealing with String types. + */ + trace(StringTools.endsWith("foobar", "bar") + " should be true!"); + + /* + With a "using" import, the first argument type is extended with the + method. What does that mean? Well, since "endsWith" has a first + argument type of "String", that means all String types now have the + "endsWith" method: + */ + trace("foobar".endsWith("bar") + " should be true!"); + + /* + This technique enables a good deal of expression for certain types, + while limiting the scope of modifications to a single file. + + Note that the String instance is *not* modified in the run time. + The newly attached method is not really part of the attached + instance, and the compiler still generates code equivalent to a + static method. + */ + } + +} + ``` +We're still only scratching the surface here of what Haxe can do. For a formal +overiew of all Haxe features, checkout the [online +manual](http://haxe.org/manual), the [online api](http://api.haxe.org/), and +"haxelib", the [haxe library repo] (http://lib.haxe.org/). + +For more advanced topics, consider checking out: + +* [Abstract types](http://haxe.org/manual/abstracts) +* [Macros](http://haxe.org/manual/macros), and [Compiler Macros](http://haxe.org/manual/macros_compiler) +* [Tips and Tricks](http://haxe.org/manual/tips_and_tricks) + + +Finally, please join us on [the mailing list](https://groups.google.com/forum/#!forum/haxelang), on IRC [#haxe on +freenode](http://webchat.freenode.net/), or on +[Google+](https://plus.google.com/communities/103302587329918132234). + + diff --git a/julia.html.markdown b/julia.html.markdown index 1023e303..cf3a464b 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -147,7 +147,7 @@ push!(a,3) #=> [1,2,4,3] append!(a,b) #=> [1,2,4,3,4,5,6] # Remove from the end with pop -pop!(a) #=> 6 and b is now [4,5] +pop!(b) #=> 6 and b is now [4,5] # Let's put it back push!(b,6) # b is now [4,5,6] again. diff --git a/matlab.html.markdown b/matlab.html.markdown new file mode 100644 index 00000000..507e9c85 --- /dev/null +++ b/matlab.html.markdown @@ -0,0 +1,260 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] +--- + +Matlab stands for Matrix Laboratory. It is a powerful numerical computing language commonly used in engineering and mathematics. + +If you have any feedback please feel free to reach me at +[@the_ozzinator](https://twitter.com/the_ozzinator), or +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```Matlab + + + +% Comments start with a percent sign. + +%{ Multi line comments look +something +like +this %} + +clear % Erases all your variables from memory +clc % Erases the writing on your Command Window +who % Displays all variables in memory +diary % History of session +ctrl-c % Abort current computation + +help command % Displays documentation for command in Command Window +lookfor command % Searches for a given command + + +% Output formatting +format short % 4 decimals in a floating number +format long % 15 decimals +fprintf + +% Variables & Expressions +myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4; % Semi colon suppresses output to the Command Window +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% Logicals +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Strings +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Cells +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - returns a cell +char(a(1)) % ans = one - returns a string + + +% Vectors +x = [4 32 53 7 1] +x(2) % ans = 32, indices in Matlab start 1, not 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Column vector + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrices +A = [1 2 3; 4 5 6; 7 8 9] +% Rows are seperated with a semi colon, each element is seperated with space or comma +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(2,3) = 42 % Update row 2 col 3 with 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Creates a new matrix from the old one +%ans = + +% 5 42 +% 8 9 + +A(:,1) % All rows in column 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % All columns in row 1 +%ans = + +% 1 2 3 + +A(:, [3 1 2]) %Rearrange the columns of original matrix +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +A(1, :) =[] %Delete the first row of the matrix + +size(A) % ans = 3 3 + +A' % Transpose the matrix + +[A ; A] % Concatenation of matrices +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + + +%Element by Element Arithmetic VS Matrix Arithmetic +A * B % Matrix multiplication +A .* B % Multiple each element in A by its corresponding element in B + + +%Plotting +x = 0:.10:2*pi % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +y = sin(x) +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 +plot(x,y1,’-’,x,y2,’--’,x,y3,’:’) % For multiple functions on one plot + + +% .mat files +% Save the variables in your Workspace + +%M-file Scripts +%A script file is an external file that contains a sequence of statements. +%Better than typing your code in the Command Window +%Have .m extensions + + +%M-file Functions +%Programs that accept inputs and return an output +%Have .m extensions +% double_input.m - naming your ,m file the same as you call it in the file is required +function output = double_input(x) + %double_input(x) returns twice the value of x + output = 2*x; +end +double_input(6) % ans = 12 + +%User input +a = input('Enter the value: ') + +%Reading in data +fopen(filename) + +%Output +disp(a) % Print out the value of variable a +disp('Hello World') % Print out a string +fprintf % More control display to Command Window + +%Conditional statements +if a > 15 + disp('Greater than 15') +elseif a == 23 + disp('a is 23') +else + disp('neither condition met') +end + +%Looping +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + + +%Connecting to a MySQL Database +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] %Example sql statement +a = fetch(conn, sql) %a will contain your data + + +% Common math functions +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand +randi + +% Common constants +pi +NaN +inf + +% Common matrix functions +zeros(m,n) % m x n matrix of 0's +ones(m,n) % m x n matrix of 1's +diag(A) % Extracts the diagonal elements of a matrix +eye(m,n) % Indentity matrix +inv(A) % Inverse of matrix A +det(A) % Determinant of A +eig(A) %Eigenvalues and eigenvectors of A +isempty(A) % Tests if array is empty +isequal(A, B) %Tests equality of two arrays +numel(A) %Number of elements in matrix + + + +``` + +## More on Matlab + +* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) diff --git a/php.html.markdown b/php.html.markdown index 083574ee..1cc6d2c5 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -176,6 +176,11 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 +// Dumps type and value of variable to stdout +var_dumb($z); // prints int(0) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) /******************************** * Logic diff --git a/python.html.markdown b/python.html.markdown index f0b74d08..bad9a360 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -93,8 +93,8 @@ not False #=> True # None is an object None #=> None -# Don't use the equality `==` symbol to compare objects to None -# Use `is` instead +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead "etc" is None #=> False None is None #=> True @@ -158,19 +158,19 @@ li[2:] #=> [4, 3] # Omit the end li[:3] #=> [1, 2, 4] -# Remove arbitrary elements from a list with del +# Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] # You can add lists li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone -# Concatenate lists with extend +# Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] -# Check for existence in a list with in +# Check for existence in a list with "in" 1 in li #=> True -# Examine the length with len +# Examine the length with "len()" len(li) #=> 6 @@ -201,37 +201,37 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] #=> 1 -# Get all keys as a list +# Get all keys as a list with "keys()" filled_dict.keys() #=> ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. -# Get all values as a list +# Get all values as a list with "values()" filled_dict.values() #=> [3, 2, 1] # Note - Same as above regarding key ordering. -# Check for existence of keys in a dictionary with in +# Check for existence of keys in a dictionary with "in" "one" in filled_dict #=> True 1 in filled_dict #=> False # Looking up a non-existing key is a KeyError filled_dict["four"] # KeyError -# Use get method to avoid the KeyError +# Use "get()" method to avoid the KeyError filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 -# Setdefault method is a safe way to add new key-value pair into dictionary +# "setdefault()" method is a safe way to add new key-value pair into dictionary filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 # Sets store ... well sets empty_set = set() -# Initialize a set with a bunch of values +# Initialize a "set()" with a bunch of values some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) # Since Python 2.7, {} can be used to declare a set @@ -284,7 +284,7 @@ for animal in ["dog", "cat", "mouse"]: print "%s is a mammal" % animal """ -`range(number)` returns a list of numbers +"range(number)" returns a list of numbers from zero to the given number prints: 0 @@ -312,7 +312,7 @@ while x < 4: # Works on Python 2.6 and up: try: - # Use raise to raise an error + # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: pass # Pass is just a no-op. Usually you would do recovery here. @@ -322,7 +322,7 @@ except IndexError as e: ## 4. Functions #################################################### -# Use def to create new functions +# Use "def" to create new functions def add(x, y): print "x is %s and y is %s" % (x, y) return x + y # Return values with a return statement @@ -359,7 +359,7 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# When calling functions, you can do the opposite of varargs/kwargs! +# When calling functions, you can do the opposite of args/kwargs! # Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} @@ -402,7 +402,7 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument + # An instance method. All methods take "self" as the first argument def say(self, msg): return "%s: %s" % (self.name, msg) diff --git a/ru-ru/erlang-ru.html.markdown b/ru-ru/erlang-ru.html.markdown new file mode 100644 index 00000000..88d07c09 --- /dev/null +++ b/ru-ru/erlang-ru.html.markdown @@ -0,0 +1,255 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] + - ["Nikita Kalashnikov", "https://root.yuuzukiyo.net/"] +filename: learnerlang-ru.erl +lang: ru-ru +--- + +```erlang +% Символ процента предваряет однострочный комментарий. + +%% Два символа процента обычно используются для комментариев к функциям. + +%%% Три символа процента используются для комментариев к модулям. + +% Пунктуационные знаки, используемые в Erlang: +% Запятая (`,`) разделяет аргументы в вызовах функций, структурах данных и +% образцах. +% Точка (`.`) (с пробелом после них) разделяет функции и выражения в +% оболочке. +% Точка с запятой (`;`) разделяет выражения в следующих контекстах: +% формулы функций, выражения `case`, `if`, `try..catch` и `receive`. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. Переменные и сопоставление с образцом. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Num = 42. % Все названия переменных начинаются с большой буквы. + +% Erlang использует единичное присваивание переменным. Если вы попытаетесь +% присвоить другое значение переменной `Num`, вы получите ошибку. +Num = 43. % ** exception error: no match of right hand side value 43 + +% В большинстве языков `=` обозначает операцию присвоения. В отличие от них, в +% Erlang `=` — операция сопоставления с образцом. `Lhs = Rhs` на самом +% деле подразумевает «вычисли правую часть выражения (Rhs) и затем сопоставь +% результат с образцом слева (Lhs)». +Num = 7 * 6. + +% Числа с плавающей точкой. +Pi = 3.14159. + +% Атомы используются для представления различных нечисловых констант. Названия +% атомов начинаются с буквы в нижнем регистре, за которой могут следовать другие +% буквы английского алфавита, цифры, символ подчёркивания (`_`) или «собака» +% (`@`). +Hello = hello. +OtherNode = example@node. + +% Если в имени атома нужно использовать другие символы, кроме допустимых, +% имя атома необходимо взять в одинарные кавычки (`'`). +AtomWithSpace = 'some atom with space'. + +% Кортежы подобны структурам в языке C. +Point = {point, 10, 45}. + +% Если нужно извлечь определённые данные из кортежа, используется оператор +% сопоставления с образцом — `=`. +{point, X, Y} = Point. % X = 10, Y = 45 + +% Символ `_` может использоваться как «заполнитель» для переменных, значения +% которых в текущем выражении нас не интересуют. Он называется анонимной +% переменной. В отличие от остальных переменных, множественные использования +% `_` в одном образце не требуют, чтобы все значения, присваевыемые этой +% переменной, были идентичными. +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% Список создаётся путём заключения его элементов в квадратные скобки и +% разделения их запятыми. Отдельные элементы списка могут быть любого типа. +% Первый элемент списка называется головой списка. Список, получающийся в +% результате отделения головы, называется хвостом списка. +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% Если `T` — список, то `[H|T]` — тоже список, где `H` является головой, а `T` — +% хвостом. Вертикальная черта (`|`) разделяет голову и хвост списка. +% `[]` — пустой список. +% Мы можем извлекать элементы из списка с помощью сопоставления с образцом. +% Если у нас есть непустой список `L`, тогда выражение `[X|Y] = L`, где `X` и +% `Y` — свободные (не связанные с другими значениям) переменные, извлечёт голову +% списка в `X` и его хвост в `Y`. +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = {pears, 6}, {milk, 3} + +% В Erlang нет строк как отдельного типа. Все используемые в программах строки +% являются обычным списком целых чисел. Строковые значения всегда должны быть в +% двойных кавычках (`"`). +Name = "Hello". +[72, 101, 108, 108, 111] = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. Последовательное программирование. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Модуль — основная единица кода в Erlang. В них пишутся и сохраняются все +% функции. Модули хранятся в файлах с расширением `.erl`. +% Модули должны быть скомпилированы перед тем, как использовать код из них. +% Скомпилированный файл модуля имеет разрешение `.beam`. +-module(geometry). +-export([area/1]). % список функций, экспортируемых из модуля. + +% Функция `area` состоит из двух формул (clauses). Формулы отделяются друг от +% друга точкой с запятой, после последнего определения должна стоять точка с +% пробелом после неё. +% Каждое определение имеет заголовок и тело. Заголовок состоит из названия +% функции и образца (в скобках); тело состоит из последовательных выражений, +% вычисляемых, когда аргументы функции совпадают с образцом в заголовке. +% Сопоставление с образцами в заголовках происходит в том порядке, в котором +% они перечислены в определении функции. +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% Компиляция файла с исходным кодом geometry.erl. +c(geometry). % {ok,geometry} + +% Необходимо указывать имя модуля вместе с именем функции для определения, какую +% именно фукнцию мы хотим вызвать. +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% В Erlang две функции с разной арностью (числом аргументов) в пределах одного +% модуля представляются как две разные функции. +-module(lib_misc). +-export([sum/1]). % экспорт функции `sum` с арностью 1, принимающую один аргумент. +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% Fun'ы — анонимные функции, называемые так по причине отсутствия имени. Зато +% их можно присваивать переменным. +Double = fun(X) -> 2*X end. % `Double` указывает на анонимную функцию с идентификатором: #Fun<erl_eval.6.17052888> +Double(2). % 4 + +% Функции могут принимать fun'ы как параметры и возвращать их в качестве +% результата вычислений. +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% Выделения списоков (list comprehensions) — выражения, создающие списки без +% применения анонимных функций, фильтров или map'ов. +% Запись `[F(X) || X <- L]` значит «список `F(X)`, где `X` последовательно +% выбирается из списка `L`». +L = [1,2,3,4,5]. +[2*X || X <- L]. % [2,4,6,8,10] +% В выделениях списков могут быть генераторы и фильтры для отделения подмножеств +% генерируемых значений. +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% Охранные выражения используются для простых проверок переменных в образцах, +% что значительно расширяет возможности сопоставления. Они могут использоваться +% в заголовках определений функций, предварённые ключевым словом `when`, а также +% в условных конструкциях. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% Охранные выражения можно группировать, разделяя запятой. +% Последовательность `GuardExpr1, GuardExpr2, ..., GuardExprN` является истинной +% только в том случае, когда все выражения, которые она содержат, являются +% истинными. +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% Последовательность охранных выражений, разделённых точками с запятой, является +% истинной в том случае, если хотя бы одно выражение из списка `G1; G2; ...; Gn` +% является истинным. +is_pet(A) when is_dog(A); is_cat(A) -> true; +is_pet(A) -> false. + +% Записи предоставляют возможность именования определённых элементов в кортежах. +% Определения записей могут быть включены в исходный код модулей Erlang или же +% в заголовочные файлы с расширением `.hrl`. +-record(todo, { + status = reminder, % Значение по умолчанию. + who = joe, + text +}). + +% Для чтения определений записей из файлов в оболочке можно использовать команду +% `rr`. +rr("records.hrl"). % [todo] + +% Создание и изменение записей. +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done,who = joe,text = "Fix errata in book"} + +% Условное выражение `case`. +% Функция `filter` возвращет список всех элементов `X` из списка `L`, для +% которых выражение `P(X)` является истинным. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% Условное выражение `if`. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil; + end. + +% Внимание: в выражении `if` должно быть как минимум одно охранное выраженние, +% вычисляющееся в true, иначе возникнет исключение. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. Обработка исключений. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Исключения возникают в случае внутренних ошибок системы или вызываются +% непосредственно из кода программы с помощью вызовов `throw(Exception)`, +% `exit(Exception)` или `erlang:error(Exception)`. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% В Erlang есть два способа обработки исключений. Первый заключается в +% использовании выражения `try..catch` в функции, в которой возможен выброс +% исключения. +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% Второй способ заключается в использовании `catch`. Во время поимки исключения +% оно преобразуется в кортеж с информацией об ошибке. +catcher(N) -> catch generate_exception(N). + +``` + +## Ссылки: + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown new file mode 100644 index 00000000..01285080 --- /dev/null +++ b/tr-tr/python-tr.html.markdown @@ -0,0 +1,502 @@ +--- +language: python +filename: learnpython-tr.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- +Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda +varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python +dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir +pseudocode'dur. + +Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh) +adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz. + +Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci) +adresine yapabilirsiniz. + +Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de +uygulanabilir. Python 3 için başka bir zaman tekrar bakınız. + + +```python +# Tek satır yorum hash işareti ile başlar. +""" Çoklu satır diziler üç tane çift tırnak + arasında yazılır. Ve yorum olarak da + kullanılabilir +""" + + +#################################################### +## 1. İlkel Veri Tipleri ve Operatörler +#################################################### + +# Sayılar +3 #=> 3 + +# Matematik beklediğiniz gibi +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız +# sonuç otomatik olarak kırpılır. +5 / 2 #=> 2 + +# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir. +2.0 # Bu bir kayan noktalı sayı +11.0 / 4.0 #=> 2.75 ahhh...daha iyi + +# İşlem önceliğini parantezler ile sağlayabilirsiniz. +(1 + 3) * 2 #=> 8 + +# Boolean değerleri bilindiği gibi +True +False + +# not ile nagatif(mantıksal) değerini alma +not True #=> False +not False #=> True + +# Eşitlik == +1 == 1 #=> True +2 == 1 #=> False + +# Eşitsizlik != +1 != 1 #=> False +2 != 1 #=> True + +# Daha fazla karşılaştırma +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Karşılaştırma zincirleme yapılabilir! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Karakter dizisi " veya ' ile oluşturulabilir +"This is a string." +'This is also a string.' + +# Karakter dizileri birbirleri ile eklenebilir +"Hello " + "world!" #=> "Hello world!" + +# A string can be treated like a list of characters +# Bir string'e karakter listesi gibi davranabilirsiniz. +"This is a string"[0] #=> 'T' + +# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi: +"%s can be %s" % ("strings", "interpolated") + +# String'leri formatlamanın yeni bir yöntem ise format metodudur. +# Bu metod tercih edilen yöntemdir. +"{0} can be {1}".format("strings", "formatted") +# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None bir objedir +None #=> None + +# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın. +# Onun yerine "is" kullanın. +"etc" is None #=> False +None is None #=> True + +# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler +# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır. + +# None, 0 ve boş string/list'ler False olarak değerlendirilir. +# Tüm eşitlikler True döner +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Değişkenler ve Kolleksiyonlar +#################################################### + +# Ekrana yazdırma oldukça kolaydır. +print "I'm Python. Nice to meet you!" + + +# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur. +some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi + # kullanmaktır. +some_var #=> 5 + +# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye +# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla +# bilgi için kontrol akışı kısmına göz atınız. +some_other_var # isim hatası fırlatılır + +# isterseniz "if"i bir ifade gibi kullanabilirsiniz. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listeler +li = [] +# Önceden değerleri tanımlanmış listeler +other_li = [4, 5, 6] + +# Bir listenin sonuna birşeyler eklemek +li.append(1) #li şu anda [1] +li.append(2) #li şu anda [1, 2] +li.append(4) #li şu anda [1, 2, 4] +li.append(3) #li şu anda [1, 2, 4, 3] +# pop ile sondan birşeyler silmek +li.pop() #=> 3 and li is now [1, 2, 4] +# Tekrar sonuna eklemek +li.append(3) # li is now [1, 2, 4, 3] again. + +# Dizi gibi listenin elemanlarına erişmek +li[0] #=> 1 +# Son elemanın değerine ulaşmak +li[-1] #=> 3 + +# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası +# fırlatılır +li[4] # IndexError fırlatılır + +# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz. +# (Açık ve kapalı aralıklıdır.) +li[1:3] #=> [2, 4] +# Başlangıcı ihmal etme +li[2:] #=> [4, 3] +# Sonu ihmal etme +li[:3] #=> [1, 2, 4] + +# "del" ile istenilen bir elemanı listeden silmek +del li[2] # li is now [1, 2, 3] + +# Listeleri birbiri ile birleştirebilirsiniz. +li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır + +# extend ile listeleri birleştirmek +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# bir değerin liste içerisinde varlığını "in" ile kontrol etmek +1 in li #=> True + +# "len" ile listenin uzunluğunu bulmak +len(li) #=> 6 + +# Tüpler listeler gibidir sadece değişmezler(immutable) +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # TypeError fırlatılır. + +# Litelerde yapılanların hepsini tüplerde de yapılabilir +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere +# atanabilir +a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3 +# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur +d, e, f = 4, 5, 6 +# şimdi iki değeri değiş tokuş etmek çok kolaydır. +e, d = d, e # d şimdi 5 ve e şimdi 4 + + +# Sözlükler (Dictionaries) key-value saklanır. +empty_dict = {} +# Sözlüklere önceden değer atama örneği +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Değere ulaşmak için [] kullanılır +filled_dict["one"] #=> 1 + +# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır +filled_dict.keys() #=> ["three", "two", "one"] +# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir +# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir + +# Tüm değerleri almak için "values()" kullanabilirsiniz. +filled_dict.values() #=> [3, 2, 1] +# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir. + +# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Olmayan bir anahtar çağrıldığında KeyError fırlatılır. +filled_dict["four"] # KeyError + +# "get()" metodu KeyError fırlatılmasını önler +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama +# imknaı sağlar. +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin +# güvenli bir yoludur. +filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 + + +# Sets store ... well sets +empty_set = set() +# Bir demek değer ile bir "set" oluşturmak +some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) + +# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Bir set'e daha fazla eleman eklemek +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# "&" işareti ile iki set'in kesişimlerini alınabilir +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# | işareti ile +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# "-" işareti ile iki set'in farkları alınabilir +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Akış Denetimi +#################################################### + +# Bir değişken oluşturmak +some_var = 5 + +# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir! +# "some_var is smaller than 10" yazdırılır. +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # elif ifadesi isteğe bağlıdır + print "some_var is smaller than 10." +else: # Bu da isteğe bağlıdır. + print "some_var is indeed 10." + + +""" +For döngüleri listeler üzerinde iterasyon yapar +Ekrana yazdırılan: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz + print "%s is a mammal" % animal + +""" +"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner +Ekrana yazdırılan: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While döngüsü koşul sağlanmayana kadar devam eder +Ekrana yazdırılan: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# try/except bloğu ile hatalar ayıklanabilir + +# Python 2.6 ve üstü için çalışacaktır: +try: + # "raise" bir hata fırlatmak için kullanılabilir + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. + + +#################################################### +## 4. Fonksiyonlar +#################################################### + + +# Yeni bir fonksiyon oluşturmak için "def" kullanılır +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # Return values with a return statement + +# Fonksiyonu parametre ile çağırmak +add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11 + +# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak +add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir + +# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + +# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da +# tanımlayabilirsiniz. +def keyword_args(**kwargs): + return kwargs + +# Şu şekilde kullanılacaktır +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Eğer isterseniz ikisini aynı anda da yapabilirsiniz +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz! +# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # foo(1, 2, 3, 4) ile eşit +all_the_args(**kwargs) # foo(a=3, b=4) ile eşit +all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit + +# Python first-class fonksiyonlara sahiptir +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Anonymous fonksiyonlar da vardır +(lambda x: x > 2)(3) #=> True + +# Dahili yüksek seviye fonksiyonlar vardır +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz. +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + + +#################################################### +## 5. Sınıflar +#################################################### + +# We subclass from object to get a class. +class Human(object): + + # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır. + species = "H. sapiens" + + # Basic initializer + def __init__(self, name): + # Metoda gelen argümanın değerini sınıfın elemanı olan "name" + # değişkenine atama + self.name = name + + # Bir instance metodu. Tüm metodlar ilk argüman olarak "self" + # parametresini alır + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Bir sınıf metodu tüm "instance"lar arasında paylaşılır + # İlk argüman olarak sınıfı çağırarak çağrılırlar + @classmethod + def get_species(cls): + return cls.species + + # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır + @staticmethod + def grunt(): + return "*grunt*" + + +# Bir sınıf örneği oluşturmak +i = Human(name="Ian") +print i.say("hi") # "Ian: hi" çıktısı verir + +j = Human("Joel") +print j.say("hello") # "Joel: hello" çıktısı verir + +# Sınıf metodunu çağıralım +i.get_species() #=> "H. sapiens" + +# Paylaşılan sınıf özellik değiştirelim. +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Statik metodu çağırma +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modüller +#################################################### + +# Modülleri sayfaya dahil edebilirsiniz +import math +print math.sqrt(16) #=> 4 + +# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Modüldeki tüm fonksiyonları dahil edebilirsiniz +# Uyarı: bu önerilmez +from math import * + +# Modülün adını kısaltabilirsiniz +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül +# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı +# aynı olmalıdır. + +# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz. +import math +dir(math) + + + +``` + +## Daha fazlası için hazır mısınız? + +### Ücretsiz Dökümanlar + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) |