├── .gitattributes ├── .gitignore ├── License ├── Module 1 ├── Chapter01 │ ├── args.jl │ ├── fizzbuzz.jl │ ├── hello.jl │ └── main.jl ├── Chapter02 │ ├── Old │ │ ├── arrays.jl │ │ ├── constants.jl │ │ ├── dates.jl │ │ ├── formatting.jl │ │ ├── formatting_strings.jl │ │ ├── regexp.jl │ │ ├── scope_constants.jl │ │ └── strings_arrays.jl │ ├── arrays.jl │ ├── constants.jl │ ├── dates.jl │ ├── formatting.jl │ ├── regexp.jl │ ├── scope.jl │ └── strings_arrays.jl ├── Chapter03 │ ├── Old │ │ ├── anonymous.jl │ │ ├── arguments.jl │ │ ├── first_class.jl │ │ ├── functions101.jl │ │ ├── generic_functions.jl │ │ ├── map_filters.jl │ │ └── quadratic │ │ │ ├── derivative.jl │ │ │ ├── main.jl │ │ │ └── quadratic.jl │ ├── anonymous.jl │ ├── arguments.jl │ ├── first_class.jl │ ├── functions101.jl │ ├── generic_functions.jl │ └── map_filters.jl ├── Chapter04 │ ├── Old │ │ ├── conditional.jl │ │ ├── errors.jl │ │ ├── repetitions.jl │ │ ├── scope.jl │ │ └── tasks.jl │ ├── conditional.jl │ ├── errors.jl │ ├── file1.txt │ ├── repetitions.jl │ ├── scope.jl │ └── tasks.jl ├── Chapter05 │ ├── Old │ │ ├── Old │ │ │ ├── dicts.jl │ │ │ ├── matrices.jl │ │ │ ├── results_words1.txt │ │ │ ├── results_words2.txt │ │ │ ├── sets.jl │ │ │ ├── tuples.jl │ │ │ ├── word_frequency.jl │ │ │ ├── words1.txt │ │ │ └── words2.txt │ │ ├── dicts.jl │ │ ├── matrices.jl │ │ ├── results_words1.txt │ │ ├── results_words2.txt │ │ ├── sets.jl │ │ ├── sets_v3.jl │ │ ├── tuples.jl │ │ ├── word_frequency.jl │ │ ├── words1.txt │ │ └── words2.txt │ ├── dicts.jl │ ├── matrices.jl │ ├── results_words1.txt │ ├── results_words2.txt │ ├── sets.jl │ ├── sets_v3.jl │ ├── tuples.jl │ ├── word_frequency.jl │ ├── words1.txt │ └── words2.txt ├── Chapter06 │ ├── Old │ │ ├── conversions.jl │ │ ├── file1.jl │ │ ├── file2.jl │ │ ├── inner_constructors.jl │ │ ├── modules.jl │ │ ├── modules_ext.jl │ │ ├── parametric.jl │ │ ├── type_hierarchy.jl │ │ ├── unions.jl │ │ └── user_defined.jl │ ├── conversions.jl │ ├── file1.jl │ ├── file2.jl │ ├── inner_constructors.jl │ ├── modules.jl │ ├── modules_ext.jl │ ├── parametric.jl │ ├── temperature_converter.jl │ ├── type_hierarchy.jl │ ├── unions.jl │ ├── user_defined.jl │ └── using_module.jl ├── Chapter07 │ ├── Old │ │ ├── built_in_macros.jl │ │ ├── eval.jl │ │ ├── expressions.jl │ │ ├── macros.jl │ │ └── reflection.jl │ ├── built_in_macros.jl │ ├── eval.jl │ ├── expressions.jl │ ├── macros.jl │ └── reflection.jl ├── Chapter08 │ ├── Old │ │ ├── csv_files.jl │ │ ├── dataarrays.jl │ │ ├── dataframes.jl │ │ ├── distrib_arrays.jl │ │ ├── echoserver.jl │ │ ├── example.dat │ │ ├── example2.dat │ │ ├── io.jl │ │ ├── odbc.jl │ │ ├── parallel.jl │ │ ├── parallel_loops_maps.jl │ │ ├── partial.dat │ │ ├── savetuple.csv │ │ ├── tcpserver.jl │ │ ├── tuple_csv.jl │ │ └── winequality.csv │ ├── csv_files.jl │ ├── dataarrays.jl │ ├── dataframes.jl │ ├── defs.jl │ ├── distrib_arrays.jl │ ├── echoserver.jl │ ├── example.dat │ ├── example2.dat │ ├── functions.jl │ ├── io.jl │ ├── odbc.jl │ ├── parallel.jl │ ├── partial.dat │ ├── savetuple.csv │ ├── tcpserver.jl │ ├── tuple_csv.jl │ └── winequality.csv ├── Chapter09 │ ├── Old │ │ ├── array_product_benchmark.jl │ │ ├── callc.jl │ │ ├── file1.txt │ │ ├── performance.jl │ │ ├── shell.jl │ │ ├── test.txt │ │ └── tosort.txt │ ├── array_product_benchmark.jl │ ├── callc.jl │ ├── file1.txt │ ├── file2.txt │ ├── performance.jl │ ├── shell.jl │ ├── test.txt │ └── tosort.txt └── Chapter10 │ ├── Old │ ├── gadfly.jl │ ├── gadfly.png │ ├── gadfly.svg │ ├── medical.csv │ ├── medical.jl │ ├── medical.pdf │ ├── stlib.jl │ ├── winequality.csv │ ├── winston.jl │ └── winston.svg │ ├── gadfly.jl │ ├── gadfly.png │ ├── gadfly.svg │ ├── medical.csv │ ├── medical.jl │ ├── medical.pdf │ ├── stlib.jl │ ├── winequality.csv │ ├── winston.jl │ └── winston.svg ├── Module 2 ├── Chapter01 │ └── p1.jl ├── Chapter02 │ └── testf.jl ├── Chapter03 │ ├── ConcrertePoint.jl │ ├── ParametricPoint.jl │ ├── PointWithAbstract.jl │ ├── arr_sumsqr.jl │ ├── immutable.jl │ ├── pixel.jl │ ├── point.jl │ ├── stringzero.jl │ ├── stringzero_stable.jl │ ├── sumsqr.jl │ ├── sumsqrtn(n).jl │ ├── sumsqrtn_fixed(n).jl │ ├── testfunc.jl │ ├── trunc.jl │ ├── trunc_fixed.jl │ ├── truncomp.jl │ └── tyoepixe.jl ├── Chapter04 │ ├── @prod_dim.jl │ ├── @prod_dim_gen.jl │ ├── F(x).jl │ ├── f_inline.jl │ ├── macro_horner.jl │ ├── muladd.jl │ ├── poly_horner.jl │ ├── poly_naive.jl │ ├── pow_Array.jl │ ├── pow_Array2.jl │ ├── prod_tim.jl │ └── sqrt_sin.jl ├── Chapter05 │ ├── Timestep.jl │ ├── fastmath_mac.jl │ └── myadd.jl ├── Chapter06 │ ├── Prealloaction.jl │ ├── SIMD.jl │ ├── allocations.jl │ ├── anynomous.jl │ ├── array_views.jl │ ├── array_views_ad.jl │ ├── bound_check.jl │ ├── col_iter.jl │ ├── gui.jl │ ├── inbound_SIMD.jl │ ├── linear.jl │ ├── mysum_in.jl │ └── mysum_index.jl └── Chapter07 │ ├── parallel_for.jl │ └── shared_array.jl ├── Module 3 ├── Chapter01 │ ├── asian-asciiplot.jl │ ├── asian-option.jl │ ├── asian-winstonplot.jl │ └── estimate-pi.jl ├── Chapter02 │ ├── bacs.jl │ ├── jmain.jl │ ├── jset.jl │ ├── julia.pgm │ ├── m3.txt │ ├── mouse.jl │ └── pgmfile.jl ├── Chapter03 │ ├── Vectors3D.jl │ ├── hailstone.jl │ ├── queens.jl │ ├── vehicles-ex.jl │ └── vehicles.jl ├── Chapter04 │ ├── Alice │ │ ├── README.1st │ │ ├── aged-aged-man.txt │ │ ├── father-william.txt │ │ ├── hunting-the-snark.log │ │ ├── hunting-the-snark.txt │ │ ├── jabber4.txt │ │ ├── jabberwocky.rev │ │ ├── jabberwocky.txt │ │ ├── lobster-quadrille.txt │ │ ├── mad-gardeners-song.txt │ │ ├── voice-of-the-lobster.txt │ │ ├── walrus-amd-carpenter.out │ │ ├── walrus-and-carpenter.out │ │ └── walrus-and-carpenter.txt │ ├── call_curl.jl │ ├── compute_dot.jl │ ├── enum.jl │ └── simple-mr.jl ├── Chapter05 │ ├── aapl-stats.jl │ ├── data │ │ ├── AAPL-Short.csv │ │ ├── AAPL.csv │ │ ├── Gcsemv.rda │ │ ├── books.xml │ │ ├── gasoline.csv │ │ ├── guImmun.rda │ │ ├── juliaset.pgm │ │ └── negative.pgm │ ├── jsetcolor.ppm │ ├── kdensity.jl │ ├── light-xml.jl │ ├── main.jl │ ├── mainols.jl │ ├── netpbm.jl │ ├── ols.jl │ └── quotes.db ├── Chapter06 │ ├── Exothem.ipynb │ ├── bank-teller.jl │ ├── banky.jl │ ├── digfilts.ipynb │ ├── dogs.wsv │ ├── exotherm1.jl │ ├── knapsack.jl │ ├── lena.jl │ ├── lena.pgm │ ├── lenaX.pgm │ ├── linalg.ipynb │ ├── lotka-volterra.jl │ ├── main-dsp.jl │ ├── main-nlopt.jl │ ├── mcmc-dogs.jl │ └── sinusoids.jl ├── Chapter07 │ ├── cairo-stroke.jl │ ├── gaston-ex1.jl │ ├── gaston-ex2.jl │ ├── plotly-ex1.jl │ ├── plotly-ex2.jl │ ├── sierp1.svg │ ├── sierp3.svg │ ├── sierp5.svg │ ├── sierpinski.jl │ ├── stroke.png │ ├── winston-graph.jl │ └── xkcd-graph.jl ├── Chapter08 │ ├── Quotes │ │ ├── build.sql │ │ ├── etl.jl │ │ ├── loader.sql │ │ ├── q.sql │ │ ├── qload.js │ │ ├── qloader.sql │ │ ├── quotes.db │ │ ├── quotes.js │ │ ├── quotes.tsv │ │ └── quotes.xlsx │ ├── build.sql │ ├── chinook-odbc.jl │ ├── couchdb-books.jl │ ├── etl.jl │ ├── mysql-dbi.jl │ ├── postgres-dbi.jl │ ├── redis-quandl.jl │ └── rest-books.jl ├── Chapter09 │ ├── apt.jl │ ├── echos.jl │ ├── eliza.jl │ ├── epipe.jl │ ├── esendex.jl │ ├── para_jset.jl │ ├── py-email.jl │ ├── qserver.jl │ ├── quotes-srv.jl │ ├── quotes.db │ └── quotes.txt └── Chapter10 │ ├── MyMod.jl │ ├── asian-debug.jl │ ├── asian-lint.jl │ ├── asian-opt.jl │ ├── cl-mmul.jl │ ├── cl-platforms.jl │ ├── main-fitsio.jl │ └── pisqd.c └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /License: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Module 1/Chapter01/args.jl: -------------------------------------------------------------------------------- 1 | for arg in ARGS 2 | println(arg) 3 | end -------------------------------------------------------------------------------- /Module 1/Chapter01/fizzbuzz.jl: -------------------------------------------------------------------------------- 1 | # fizzbuzz 2 | for i=1:100 3 | if mod(i,15)==0 println("FizzBuzz") 4 | elseif mod(i,5)==0 println("Buzz") 5 | elseif mod(i,3)==0 println("Fizz") 6 | else println(i) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /Module 1/Chapter01/hello.jl: -------------------------------------------------------------------------------- 1 | println("Hello, Julia World!") 2 | -------------------------------------------------------------------------------- /Module 1/Chapter01/main.jl: -------------------------------------------------------------------------------- 1 | include("hello.jl") 2 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/arrays.jl: -------------------------------------------------------------------------------- 1 | search("Julia","uli") #=> 2:4 2 | typeof(1:1000) #=> UnitRange{Int64} 3 | 4 | a = split("A,B,C,D",",") 5 | typeof(a) #=> Array{SubString{ASCIIString},1} 6 | show(a) #=> SubString{ASCIIString}["A","B","C","D"] 7 | 8 | arr = [100, 25, 37] 9 | arr[1] #=> 100 10 | arr[end] #=> 37 11 | # arr[6] #=> BoundsError 12 | println(eltype(arr)) #=> Int64 13 | println(length(arr)) #=> 3 14 | println(ndims(arr)) #=> 1 15 | println(size(arr,1)) #=> 3 16 | println(size(arr)) #=> (3,) 17 | 18 | arr2 = Array(Int, 5) 19 | show arr2 #=> [0,0,0,0,0] 20 | sizehint(arr2, 10^5) 21 | 22 | a = Float64[] #=> 0-element Array{Float64,1} 23 | b = [1:7] #=> 7-element Array{Int64,1}: [1,2,3,4,5,6,7] 24 | join(b, ", ") #=> "1, 2, 3, 4, 5, 6, 7" 25 | matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] 26 | 27 | b[1:3] # => [1, 2, 3] 28 | b[2:end] # => [2, 3, 4, 5, 6, 7] , b[2:] is deprecated 29 | c = [100,200,300] 30 | append!(b,c) # Now b is [1, 2, 3, 4, 5, 6, 7, 100, 200, 300] 31 | pop!(b) #=> 300, b is now [1, 2, 3, 4, 5, 6, 7, 100, 200] 32 | push!(b, 42) # b is now [1, 2, 3, 4, 5, 6, 7, 100, 200, 42] 33 | shift!(b) #=> 1, b is now [2, 3, 4, 5, 6, 7, 100, 200, 42] 34 | unshift!(b, 42) # b is now [42, 2, 3, 4, 5, 6, 7, 100, 200, 42] 35 | splice!(b,8) #=> 100, b is now [42, 2, 3, 4, 5, 6, 7, 200, 42] 36 | in(42, b) #=> true 37 | in(43, b) #=> false 38 | sort(b) #=> [2,3,4,5,6,7,42,42,200], b is not changed 39 | sort!(b) #=> b is now changed to [2,3,4,5,6,7,42,42,200] 40 | 41 | arr = [1, 5, 3] 42 | # looping 43 | for e in arr 44 | print("$e ") 45 | end # prints 1 5 3 46 | arr + 2 #=> [3, 7, 5] 47 | arr * 2 #=> [2, 10, 6] 48 | 49 | ma1 = rand(3, 5) 50 | ndims(ma1) #=> 2 51 | size(ma1) #=> (3, 5) 52 | size(ma1,1) #=> 3 53 | size(ma1,2) #=> 5 54 | length(ma1) #=> 15 55 | 56 | idm = eye(3) 57 | zeros(5) 58 | ones(4) 59 | ones(3, 2) 60 | eqa = linspace(0, 10, 5) 61 | show(eqa) #=> [0.0,2.5,5.0,7.5,10.0] 62 | fill!(arr, 42) #=> [42,42,42] 63 | 64 | A = [1,2,4,6] 65 | A0 = A 66 | show(A0) 67 | A[4] = 0 68 | show(A) #=> [1,2,4,0] 69 | show(A0) #=> [1,2,4,0] 70 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/constants.jl: -------------------------------------------------------------------------------- 1 | const GC = 6.67e-11 # gravitational constant in m3/kg s2 2 | 3 | GC = 3.14 #=> Warning: redefining constant GC 4 | GC = 10 #=> ERROR: invalid redefinition of constant GC 5 | 6 | julia> const ARR = [4,7,1] 7 | julia> ARR[1] = 9 8 | julia> show(ARR) #=> [9,7,1] 9 | julia> ARR = [1, 2, 3] #=> Warning: redefining constant ARR 10 | 11 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/dates.jl: -------------------------------------------------------------------------------- 1 | # !!! this script needs Julia v 0.4 or greater !!! 2 | # constructing: 3 | d = Date(2014,9,1) #=> 2014-09-01 4 | dt = DateTime(2014,9,1,12,30,59,1) #=> 2014-09-01T12:30:59.001 5 | # accessors: 6 | Dates.year(d) 7 | Dates.month(d) 8 | Dates.week(d) 9 | Dates.day(d) 10 | # functions: 11 | Dates.isleapyear(d) 12 | Dates.dayofyear(d) 13 | Dates.monthname(d) 14 | Dates.daysinmonth(d) 15 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/formatting.jl: -------------------------------------------------------------------------------- 1 | # d for integers: 2 | @printf "%d\n" 1e5 #> 100000 3 | x = 7.35679 4 | # f = float format, rounded if needed: 5 | @printf "x = %0.3f\n" x #> 7.357 6 | aa = 1.5231071779744345 7 | bb = 33.976886930000695 8 | @printf("%.2f %.2f\n", aa, bb) #=> 1.52 33.98 9 | # or to create another string: 10 | str = @sprintf("%0.3f", x) 11 | show(str) #> "7.357" 12 | println() 13 | # e = scientific format with e: 14 | @printf "%0.6e\n" x #> 7.356790e+00 15 | # c = for characters: 16 | @printf "output: %c\n" 'α' #> output: α 17 | # s for strings: 18 | @printf "%s\n" "I like Julia" 19 | # right justify: 20 | @printf "%50s\n" "width 25, text right justified!" 21 | # p for pointers: 22 | @printf "a pointer: %p\n" 1e10 #> a pointer: 0x00000002540be400 23 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/formatting_strings.jl: -------------------------------------------------------------------------------- 1 | # d for integers: 2 | @printf "%d\n" 1e5 #> 100000 3 | x = 7.35679 4 | # f = float format, rounded if needed: 5 | @printf "x = %0.3f\n" x #> 7.357 6 | # or to create another string: 7 | str = @sprintf("%0.3f", x) 8 | show(str) #> "7.357" 9 | println() 10 | # e = scientific format with e: 11 | @printf "%0.6e\n" x #> 7.356790e+00 12 | # c = for characters: 13 | @printf "output: %c\n" 'α' #> output: α 14 | # s for strings: 15 | @printf "%s\n" "I like Julia" 16 | # right justify: 17 | @printf "%50s\n" "width 25, text right justified!" 18 | # p for pointers: 19 | @printf "a pointer: %p\n" 1e10 #> a pointer: 0x00000002540be400 20 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/regexp.jl: -------------------------------------------------------------------------------- 1 | visa = r"^(?:4[0-9]{12}(?:[0-9]{3})?)$"; 2 | input = "4457418557635128"; 3 | 4 | ismatch(visa, input) #=> true 5 | if ismatch(visa, input) 6 | println("credit card found") 7 | m = match(visa, input) 8 | println(m.match) #=> 4457418557635128 9 | println(m.captures) #=> nothing 10 | println(m.offset) #=> 1 11 | println(m.offsets) #=> [] 12 | end 13 | 14 | m = match(r"(ju|l)(i)?(a)", "Julia") 15 | println(m.match) #=> "lia" 16 | println(m.captures) #=> l - i - a 17 | println(m.offset) #=> 3 18 | println(m.offsets) #=> 3 - 4 - 5 19 | 20 | str = "The sky is blue" 21 | reg = r"[\w]{3,}" 22 | # matchall returns an array with a RegexMatche for each match 23 | r = matchall(reg, str) 24 | show(r) #=> ["The","sky","blue"] 25 | # eachmatch returns an iterator over all the matches 26 | iter = eachmatch(reg, str) 27 | for i in iter 28 | println("\"$(i.match)\" ") 29 | end 30 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/scope_constants.jl: -------------------------------------------------------------------------------- 1 | # type annotations and scope: 2 | x = 1.0 # x is Float64 3 | x = 1 # now x is Int 4 | # y::Float64 = 1.0 # LoadError: "y is not defined" 5 | 6 | function scopetst() 7 | y::Float64 = 1.0 # y must be Float64, not possible in global scope 8 | # y = 1 9 | end 10 | 11 | # compound expressions: 12 | x = begin 13 | a = 5 14 | 2 * a 15 | end # after: x = 10 16 | println(a) #=> a = 5 17 | x = (a = 5; 2 * a) 18 | 19 | const GC = 6.67e-11 # gravitational constant in m3/kg s2 20 | 21 | GC = 3.14 #=> Warning: redefining constant GC 22 | # GC = 10 #=> ERROR: invalid redefinition of constant GC 23 | 24 | julia> const ARR = [4,7,1] 25 | julia> ARR[1] = 9 26 | julia> show(ARR) #=> [9,7,1] 27 | julia> ARR = [1, 2, 3] #=> Warning: redefining constant ARR 28 | 29 | -------------------------------------------------------------------------------- /Module 1/Chapter02/Old/strings_arrays.jl: -------------------------------------------------------------------------------- 1 | # a newspaper headline: 2 | str = "The Gold and Blue Loses a Bit of Its Luster" 3 | println(str) 4 | nchars = length(str) 5 | println("The headline counts $nchars characters") # 43 6 | str2 = replace(str, "Blue", "Red") 7 | # strings are immutable 8 | println(str) # The Gold and Blue Loses a Bit of Its Luster 9 | println(str2) 10 | println("Here are the characters at position 25 to 30:") 11 | subs = str[25:30] 12 | print("-$(lowercase(subs))-") # "-a bit -" 13 | println("Here are all the characters:") 14 | for c in str 15 | println(c) 16 | end 17 | arr = split(str,' ') 18 | show(arr) # ["The","Gold","and","Blue","Loses","a","Bit","of","Its","Luster"] 19 | nwords = length(arr) 20 | println("The headline counts $nwords words") # 10 21 | println("Here are all the words:") 22 | for word in arr 23 | println(word) 24 | end 25 | arr[4] = "Red" 26 | show(arr) # arrays are mutable 27 | println("Convert back to a sentence:") 28 | nstr = join(arr, ' ') 29 | println(nstr) # The Gold and Red Loses a Bit of Its Luster 30 | -------------------------------------------------------------------------------- /Module 1/Chapter02/constants.jl: -------------------------------------------------------------------------------- 1 | const GC = 6.67e-11 # gravitational constant in m3/kg s2 2 | 3 | GC = 3.14 #> Warning: redefining constant GC 4 | # GC = 10 #> ERROR: invalid redefinition of constant GC 5 | 6 | const ARR = [4,7,1] 7 | ARR[1] = 9 8 | show(ARR) #> [9,7,1] 9 | println() 10 | ARR = [1, 2, 3] #> Warning: redefining constant ARR -------------------------------------------------------------------------------- /Module 1/Chapter02/dates.jl: -------------------------------------------------------------------------------- 1 | # !!! this script needs Julia v 0.4 or higher !!! 2 | # constructing: 3 | start_time = time() 4 | # long computation 5 | time_elapsed = time() - start_time 6 | println("Time elapsed: $time_elapsed") #> 0.0010001659393310547 7 | 8 | d = Date(2014,9,1) #> 2014-09-01 9 | dt = DateTime(2014,9,1,12,30,59,1) #> 2014-09-01T12:30:59.001 10 | # accessors: 11 | Dates.year(d) 12 | Dates.month(d) 13 | Dates.week(d) 14 | Dates.day(d) 15 | # functions: 16 | Dates.isleapyear(d) 17 | Dates.dayofyear(d) 18 | Dates.monthname(d) 19 | Dates.daysinmonth(d) 20 | -------------------------------------------------------------------------------- /Module 1/Chapter02/formatting.jl: -------------------------------------------------------------------------------- 1 | # d for integers: 2 | @printf("%d\n", 1e5) #> 100000 3 | x = 7.35679 4 | # f = float format, rounded if needed: 5 | @printf("x = %0.3f\n", x) #> 7.357 6 | aa = 1.5231071779744345 7 | bb = 33.976886930000695 8 | @printf("%.2f %.2f\n", aa, bb) #> 1.52 33.98 9 | # or to create another string: 10 | str = @sprintf("%0.3f", x) 11 | show(str) #> "7.357" 12 | println() 13 | # e = scientific format with e: 14 | @printf("%0.6e\n", x) #> 7.356790e+00 15 | # c = for characters: 16 | @printf("output: %c\n", 'α') #> output: α 17 | # s for strings: 18 | @printf("%s\n", "I like Julia") 19 | # right justify: 20 | @printf("%50s\n", "text right justified!") 21 | # p for pointers: 22 | @printf("a pointer: %p\n", 1e10) #> a pointer: 0x00000002540be400 23 | -------------------------------------------------------------------------------- /Module 1/Chapter02/regexp.jl: -------------------------------------------------------------------------------- 1 | email_pattern = r".+@.+" 2 | input = "john.doe@mit.edu" 3 | println(ismatch(email_pattern, input)) #> true 4 | 5 | visa = r"^(?:4[0-9]{12}(?:[0-9]{3})?)$" 6 | input = "4457418557635128" 7 | 8 | ismatch(visa, input) #> true 9 | if ismatch(visa, input) 10 | println("credit card found") 11 | m = match(visa, input) 12 | println(m.match) #> 4457418557635128 13 | # println(m.captures) #> nothing 14 | println(m.offset) #> 1 15 | println(m.offsets) #> [] 16 | end 17 | 18 | email_pattern = r"(.+)@(.+)" 19 | input = "john.doe@mit.edu" 20 | m = match(email_pattern, input) 21 | println(m.captures) #> ["john.doe","mit.edu"] 22 | 23 | m = match(r"(ju|l)(i)?(a)", "Julia") 24 | println(m.match) #> "lia" 25 | println(m.captures) #> l - i - a 26 | println(m.offset) #> 3 27 | println(m.offsets) #> 3 - 4 - 5 28 | 29 | str = "The sky is blue" 30 | reg = r"[\w]{3,}" 31 | # matchall returns an array with a RegexMatche for each match 32 | r = matchall(reg, str) 33 | show(r) #> ["The","sky","blue"] 34 | # eachmatch returns an iterator over all the matches 35 | iter = eachmatch(reg, str) 36 | for i in iter 37 | println("\"$(i.match)\" ") 38 | end -------------------------------------------------------------------------------- /Module 1/Chapter02/scope.jl: -------------------------------------------------------------------------------- 1 | # type annotations and scope: 2 | x = 1.0 # x is Float64 3 | x = 1 # now x is Int 4 | # y::Float64 = 1.0 # LoadError: "y is not defined" 5 | 6 | function scopetest() 7 | println(x) 8 | y::Float64 = 1.0 # y must be Float64, this is not possible in global scope 9 | # y = 1 10 | end 11 | 12 | scopetest() #> 1 13 | # println(y) #> ERROR: y not defined 14 | 15 | # compound expressions: 16 | x = begin 17 | a = 5 18 | 2 * a 19 | end # after: x is 10 20 | println(a) #> a is 5 21 | x = (a = 5; 2 * a) -------------------------------------------------------------------------------- /Module 1/Chapter02/strings_arrays.jl: -------------------------------------------------------------------------------- 1 | # a newspaper headline: 2 | str = "The Gold and Blue Loses a Bit of Its Luster" 3 | println(str) 4 | nchars = length(str) 5 | println("The headline counts $nchars characters") # 43 6 | str2 = replace(str, "Blue", "Red") 7 | # strings are immutable 8 | println(str) # The Gold and Blue Loses a Bit of Its Luster 9 | println(str2) 10 | println("Here are the characters at position 25 to 30:") 11 | subs = str[25:30] 12 | print("-$(lowercase(subs))-") # "-a bit -" 13 | println("Here are all the characters:") 14 | for c in str 15 | println(c) 16 | end 17 | arr = split(str,' ') 18 | show(arr) # ["The","Gold","and","Blue","Loses","a","Bit","of","Its","Luster"] 19 | nwords = length(arr) 20 | println("The headline counts $nwords words") # 10 21 | println("Here are all the words:") 22 | for word in arr 23 | println(word) 24 | end 25 | arr[4] = "Red" 26 | show(arr) # arrays are mutable 27 | println("Convert back to a sentence:") 28 | nstr = join(arr, ' ') 29 | println(nstr) # The Gold and Red Loses a Bit of Its Luster 30 | # working with arrays: 31 | println("arrays: calculates the sum, mean and standard deviation ") 32 | arr = [1:100] 33 | typeof(arr) #> 34 | println(sum(arr)) #> 5050 35 | println(mean(arr)) #> 50.5 36 | println(std(arr)) #> 29.011491975882016 -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/anonymous.jl: -------------------------------------------------------------------------------- 1 | f = (x, y) -> x^3 – y + x * y 2 | (x, y) -> x^3 – y + x * y 3 | 4 | function (x) 5 | x + 2 6 | end 7 | 8 | (x) -> x + 2 9 | x -> x + 2 10 | () -> x * 5 11 | 12 | (x, y, z) -> 3x + 2y - z 13 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/arguments.jl: -------------------------------------------------------------------------------- 1 | # optional arguments: 2 | f(a, b = 5) = a + b 3 | f(1) #=> 6 4 | f(2, 5) #=> 7 5 | f(3) #=> 8 6 | # f() #=> ERROR: `f` has no method matching f() 7 | # f(1, 2, 3) 8 | #=> ERROR: `f` has no method matching f(::Int64, ::Int64, # ::Int64) 9 | 10 | # keyword arguments: 11 | k(x; a1 = 1, a2 = 2) = x * (a1 + a2) 12 | k(3, a2 = 3) #=> 12 13 | k(3, a2 = 3, a1 = 0) #=> 9 14 | k(3) #=> 9 15 | 16 | # combine all kinds of arguments in the same function 17 | function allargs(normal_arg, optional_positional_arg=2; keyword_arg="ABC") 18 | print("normal arg: $normal_arg -") 19 | print("optional arg: $optional_positional_arg -") 20 | print("keyword arg: $keyword_arg") 21 | end 22 | 23 | allargs(1, 3, keyword_arg=4) 24 | # prints: normal arg: 1 - optional arg: 3 - keyword arg: 4 25 | 26 | function varargs2(;args...) 27 | args 28 | end 29 | varargs2(k1="name1", k2="name2", k3=7) 30 | #=> 3-element Array{Any,1} with elements: 31 | # (:k1,"name1") (:k2,"name2") (:k3,7) 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/first_class.jl: -------------------------------------------------------------------------------- 1 | mult(x, y) = x * y 2 | typeof(mult) #=> Function 3 | 4 | plustwo = function (x) 5 | x + 2 6 | end 7 | plustwo(3) #=> 5 8 | 9 | function quadratic(f) 10 | # calculations (for full code see end of chapter) 11 | return (-b + sqrt(b^2 -4a*c + 0im)) / 2a, (-b - sqrt(b^2 -4a*c + 0im)) / 2a 12 | end 13 | r1, r2 = quadratic(x -> 2x^2 + 30x + 9) 14 | 15 | function derivative(f) 16 | return function(x) 17 | # definiton of anonymous function calculating derivative 18 | end 19 | end 20 | 21 | # nested: 22 | function a(x) 23 | z = x * 2 24 | function b(z) 25 | z += 1 26 | end 27 | b(z) 28 | end 29 | 30 | d = 5 31 | a(d) #=> 11 32 | 33 | # closure: 34 | function counter() 35 | n = 0 36 | () -> n +=1, () -> n = 0 37 | end 38 | (addOne, reset) = counter() 39 | addOne() 40 | addOne() 41 | addOne() 42 | reset() 43 | 44 | 45 | 46 | # recursive: 47 | sum(n) = n > 1 ? sum(n-1) + n : n 48 | sum(100) #=> 5050 49 | fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) 50 | fib(1000) #=> 51 | 52 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/functions101.jl: -------------------------------------------------------------------------------- 1 | # n = mult(3, 4) #=> ErrorException("mult not defined")) 2 | function mult(x, y) 3 | println("x is $x and y is $y") 4 | x * y 5 | end 6 | 7 | n = mult(3, 4) #=> 12 8 | # one-line assignment syntax: 9 | mult(x, y) = x * y 10 | f(x,y) = x^3-y+x*y 11 | println(f(3,2) ) # 31 12 | 13 | function mult(x, y) 14 | println("x is $x and y is $y") 15 | if x == 1 return y end 16 | x * y 17 | end 18 | 19 | function mult(x::Float64, y::Float64) 20 | println("x is $x and y is $y") 21 | x * y 22 | end 23 | # following gives error: 24 | # mult(5, 6) 25 | # ERROR: `mult` has no method matching mult(::Int64, ::Int64) 26 | 27 | function multi(n,m) 28 | n*m, div(n,m), n%m 29 | end 30 | x, y, z = multi(8, 2) 31 | 32 | function varargs(n, m, args...) 33 | println("arguments: $n $m $args") 34 | end 35 | varargs(1, 2, 3, 4) # n is 1, m is 2, and args has value (3, 4) 36 | 37 | x = (3, 4) 38 | varargs2(1, 2, x...) # args is (1,2,3,4) 39 | x = [10, 11, 12] 40 | varargs2(1, 2, x...) # args is (1,2,10,11,12) 41 | varargs2(k1="name1", k2="name2, k3=7) 42 | 43 | apply(mult, 3, 4) #=> 12 44 | 45 | ∑(x,y) = x + y 46 | ∑(3, 4) #=> 7 47 | 48 | # anonymous functions: 49 | function (x) 50 | x + 2 51 | end 52 | 53 | g = (x, y) -> x^3-y+x*y 54 | println(g(3,2) ) # 31 55 | 56 | x -> x + 2 57 | () -> x * 5 58 | 59 | 3+4 #=> 7 60 | +(3,4) #=> 7 61 | 62 | m = mult 63 | m(6, 6) #=> 36 64 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/generic_functions.jl: -------------------------------------------------------------------------------- 1 | # multiple dispatch: 2 | f(n, m) = "base case" 3 | f(n::Number, m::Number) = "n and m are both numbers" 4 | f(n::Number, m) = "n is a number" 5 | f(n, m::Number) = "m is a number" 6 | f(n::Integer, m::Integer) = "n and m are both integers" 7 | #=> f (generic function with 5 methods) 8 | f(1.5, 2) #=> "n and m are both numbers" 9 | f(1, "bar") #=> "n is a number" 10 | f(1, 2) #=> "n and m are both integers" 11 | f("foo", [1,2]) #=> "base case" 12 | f(n::Float64, m::Integer) = "n is a float and m is an integer" 13 | #=> f (generic function with 6 methods) 14 | f(1.5, 2) #=> "n is a float and m is an integer" 15 | 16 | # methods: 17 | methods(+) 18 | methods(sort) 19 | methodswith(String) 20 | 21 | # measuring execution: 22 | fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) 23 | @time fib(35) 24 | @elapsed fib(35) 25 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/map_filters.jl: -------------------------------------------------------------------------------- 1 | # maps: 2 | map((x) -> x * 10, [1, 2, 3]) #=> [10, 20, 30] 3 | map(*, [1, 2, 3], [4, 5, 6]) #=> [4, 10, 18] 4 | cubes = map((x)-> x*x*x, [1:5]) #=> [1, 8, 27, 64, 125] 5 | 6 | # do block: 7 | map( x-> begin 8 | if x == 0 return 0 9 | elseif iseven(x) return 2 10 | elseif isodd(x) return 1 11 | end 12 | end, 13 | [-3:3]) #=> [1,2,1,0,1,2,1] 14 | 15 | map([-3:3]) do x 16 | if x == 0 return 0 17 | elseif iseven(x) return 2 18 | elseif isodd(x) return 1 19 | end 20 | end #=> [1,2,1,0,1,2,1] 21 | 22 | # filter: 23 | filter( n -> iseven(n), [1:10]) #=> [2, 4, 6, 8, 10] 24 | filter( (n) -> n % 2 == 0, [1:10]) #=> [2, 4, 6, 8, 10] 25 | 26 | # comprehensions: 27 | arr = [n for n in 1:1000] #=> [1,2,...,1000] 28 | arr2 = Float64[x^2 for x in 1:4] #=> [1.0,4.0,9.0,16.0] 29 | cubes = [x*x*x for x in [1:5]] #=> [1, 8, 27, 64, 125] 30 | table10 = [x*y for x=1:10, y=1:10] #=> 31 | #= 32 | #1 2 3 4 5 6 7 8 9 10 33 | #2 4 6 8 10 12 14 16 18 20 34 | #3 6 9 12 15 18 21 24 27 30 35 | #4 8 12 16 20 24 28 32 36 40 36 | #5 10 15 20 25 30 35 40 45 50 37 | #6 12 18 24 30 36 42 48 54 60 38 | #7 14 21 28 35 42 49 56 63 70 39 | #8 16 24 32 40 48 56 64 72 80 40 | #9 18 27 36 45 54 63 72 81 90 41 | #10 20 30 40 50 60 70 80 90 100 42 | =# 43 | mat1 = [x + y for x in 1:2, y in 1:3] 44 | #=> 2 3 4 45 | #=> 3 4 5 46 | 47 | arrany = { i * 2 for i = 1:5 } #=> [2,4,6,8,10] 48 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/quadratic/derivative.jl: -------------------------------------------------------------------------------- 1 | function derivative(fn) 2 | return function(x) 3 | # pick a small value for h 4 | h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x 5 | # floating point arithmetic gymnastics 6 | xph = x + h 7 | dx = xph - x 8 | # evaluate f at x + h 9 | f1 = fn(xph) 10 | # evaluate f at x 11 | f0 = fn(x) 12 | # divide the difference by h 13 | # return (fn(xph) - fn(x)) / dx 14 | return (f1 - f0) / dx 15 | end 16 | 17 | # 1st approximation: 18 | # return function(x) 19 | # h = 0.00001 20 | # f1 = fn(x + h) 21 | # f0 = fn(x) 22 | # return (f1 - f0)/h 23 | # end 24 | end 25 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/quadratic/main.jl: -------------------------------------------------------------------------------- 1 | include("quadratic.jl") 2 | 3 | println(quadratic(x -> 2x^2 + 30x + 9)) 4 | # results: 5 | # 1st approximation: 6 | # -0.3062524369827744 + 0.0im,-14.693907564071102 - 0.0im) 7 | # with eps: 8 | # -0.30625271503092044 + 0.0im,-14.69374728496908 - 0 9 | -------------------------------------------------------------------------------- /Module 1/Chapter03/Old/quadratic/quadratic.jl: -------------------------------------------------------------------------------- 1 | include("derivative.jl") 2 | 3 | function quadratic(f) 4 | # Compute the first derivative of f 5 | f1 = derivative(f) 6 | 7 | # Get the y intercept (explictly passing a floating point number) 8 | c = f(0.0) 9 | 10 | # Get the y intercept of the first derivative 11 | b = f1(0.0) 12 | 13 | a = f(1.0) - b - c 14 | 15 | # Our old friend the quadratic formula 16 | # Notice how Julia lets you return multiple values 17 | # Multiple values should be separated by a comma and 18 | # are returned as a tuple 19 | # return (-b + sqrt(b^2 -4a*c)) / 2a, (-b - sqrt(b^2 -4a*c)) / 2a 20 | return (-b + sqrt(b^2 -4a*c + 0im)) / 2a, (-b - sqrt(b^2 -4a*c + 0im)) / 2a 21 | end 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Module 1/Chapter03/anonymous.jl: -------------------------------------------------------------------------------- 1 | # anonymous functions: 2 | (x, y) -> x^3 - y + x * y 3 | f = (x, y) -> x^3 - y + x * y 4 | println(f(3, 2) ) # 31 5 | 6 | function (x) 7 | x + 2 8 | end 9 | 10 | (x) -> x + 2 11 | x -> x + 2 # lambda syntax 12 | () -> println("hello, Julia") 13 | (x, y, z) -> 3x + 2y - z -------------------------------------------------------------------------------- /Module 1/Chapter03/arguments.jl: -------------------------------------------------------------------------------- 1 | # optional arguments: 2 | f(a, b = 5) = a + b 3 | f(1) #> 6 4 | f(2, 5) #> 7 5 | f(3) #> 8 6 | # f() #> ERROR: `f` has no method matching f() 7 | # f(1, 2, 3) 8 | #> ERROR: `f` has no method matching f(::Int64, ::Int64, # ::Int64) 9 | # f(2, b = 5) #> ERROR: function f does not accept keyword arguments 10 | 11 | # keyword arguments: 12 | k(x; a1 = 1, a2 = 2) = x * (a1 + a2) 13 | k(3, a2 = 3) #> 12 14 | k(3, a2 = 3, a1 = 0) #> 9 15 | k(3) #> 9 16 | 17 | # combine all kinds of arguments in the same function 18 | function allargs(normal_arg, optional_positional_arg=2; keyword_arg="ABC") 19 | print("normal arg: $normal_arg -") 20 | print("optional arg: $optional_positional_arg -") 21 | print("keyword arg: $keyword_arg") 22 | end 23 | 24 | allargs(1, 3, keyword_arg=4) 25 | # prints: normal arg: 1 - optional arg: 3 - keyword arg: 4 26 | 27 | function varargs2(;args...) 28 | args 29 | end 30 | varargs2(k1="name1", k2="name2", k3=7) 31 | #> 3-element Array{Any,1} with elements: 32 | # (:k1,"name1") (:k2,"name2") (:k3,7) -------------------------------------------------------------------------------- /Module 1/Chapter03/first_class.jl: -------------------------------------------------------------------------------- 1 | mult(x, y) = x * y 2 | typeof(mult) #> Function 3 | m = mult 4 | m(6, 6) #> 36 5 | 6 | plustwo = function (x) 7 | x + 2 8 | end 9 | plustwo(3) #> 5 10 | 11 | 3+4 #> 7 12 | +(3,4) #> 7 13 | 14 | function numerical_derivative(f, x, dx=0.01) 15 | derivative = (f(x+dx) - f(x-dx))/(2*dx) 16 | return derivative 17 | end 18 | 19 | f = x -> 2x^2 + 30x + 9 20 | println(numerical_derivative(f, 1, 0.001)) #> 33.99999999999537 21 | 22 | function derivative(f) 23 | return function(x) 24 | # pick a small value for h 25 | h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x 26 | xph = x + h 27 | dx = xph - x 28 | f1 = f(xph) # evaluate f at x + h 29 | f0 = f(x) # evaluate f at x 30 | return (f1 - f0) / dx # divide by h 31 | end 32 | end 33 | 34 | # closure: 35 | function counter() 36 | n = 0 37 | () -> n += 1, () -> n = 0 38 | end 39 | 40 | (addOne, reset) = counter() 41 | addOne() 42 | addOne() 43 | addOne() 44 | reset() 45 | 46 | # currying: 47 | function add(x) 48 | return function f(y) 49 | return x + y 50 | end 51 | end 52 | add(1)(2) #> 3 53 | add(x) = f(y) = x + y 54 | add(x) = y -> x + y 55 | 56 | # nested: 57 | function afun(x) 58 | z = x * 2 59 | function b(z) 60 | z += 1 61 | end 62 | b(z) 63 | end 64 | 65 | d = 5 66 | afun(d) #> 11 67 | 68 | # recursive: 69 | sum(n) = n > 1 ? sum(n-1) + n : n 70 | sum(100) #> 5050 71 | fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) 72 | println(fib(25)) #> 75025 -------------------------------------------------------------------------------- /Module 1/Chapter03/functions101.jl: -------------------------------------------------------------------------------- 1 | # n = mult(3, 4) #> ErrorException("mult not defined")) 2 | function mult(x, y) 3 | println("x is $x and y is $y") 4 | x * y 5 | end 6 | 7 | n = mult(3, 4) #> 12 8 | 9 | function mult(x, y) 10 | println("x is $x and y is $y") 11 | if x == 1 12 | return y 13 | end 14 | x * y 15 | end 16 | 17 | function multi(n, m) 18 | n * m, div(n, m), n % m 19 | end 20 | x, y, z = multi(8, 2) #> (16,4,0) 21 | 22 | # variable number of arguments: 23 | function varargs(n, m, args...) 24 | println("arguments: $n $m $args") 25 | end 26 | varargs(1, 2, 3, 4) # n is 1, m is 2, and args has value (3, 4) 27 | 28 | function varargs2(args...) 29 | println("arguments2: $args") 30 | end 31 | 32 | x = (3, 4) 33 | varargs2(1, 2, x...) # args is (1,2,3,4) 34 | x = [10, 11, 12] 35 | varargs2(1, 2, x...) # args is (1,2,10,11,12) 36 | 37 | function insert_elem(arr) 38 | push!(arr, -10) 39 | end 40 | 41 | arr = [ 2, 3, 4] 42 | insert_elem(arr) 43 | println("arr is now $arr") #> arr is now [ 2, 3, 4, -10 ] 44 | 45 | # typing the arguments: 46 | function mult(x::Float64, y::Float64) 47 | println("x is $x and y is $y") 48 | x * y 49 | end 50 | # following gives error: 51 | # mult(5, 6) 52 | # ERROR: `mult` has no method matching mult(::Int64, ::Int64) 53 | 54 | # one-line assignment syntax: 55 | mult(x, y) = x * y 56 | f(x, y) = x^3 - y + x*y 57 | println(f(3,2) ) # 31 58 | 59 | ∑(x,y) = x + y 60 | ∑(3, 4) #> 7 -------------------------------------------------------------------------------- /Module 1/Chapter03/generic_functions.jl: -------------------------------------------------------------------------------- 1 | # multiple dispatch: 2 | f(n, m) = "base case" 3 | f(n::Number, m::Number) = "n and m are both numbers" 4 | f(n::Number, m) = "n is a number" 5 | f(n, m::Number) = "m is a number" 6 | f(n::Integer, m::Integer) = "n and m are both integers" 7 | #> f (generic function with 5 methods) 8 | f(1.5, 2) #> "n and m are both numbers" 9 | f(1, "bar") #> "n is a number" 10 | f(1, 2) #> "n and m are both integers" 11 | f("foo", [1,2]) #> "base case" 12 | f(n::Float64, m::Integer) = "n is a float and m is an integer" 13 | #> f (generic function with 6 methods) 14 | f(1.5, 2) #> "n is a float and m is an integer" 15 | 16 | # methods: 17 | methods(+) 18 | methods(sort) 19 | methodswith(String) 20 | 21 | # measuring execution: 22 | fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) 23 | @time fib(35) 24 | @elapsed fib(35) #> elapsed time: 0.115853481 seconds (45144 bytes allocated) -------------------------------------------------------------------------------- /Module 1/Chapter03/map_filters.jl: -------------------------------------------------------------------------------- 1 | # maps: 2 | map(x -> x * 10, [1, 2, 3]) #> [10, 20, 30] 3 | cubes = map(x-> x^3, [1:5]) #> [1, 8, 27, 64, 125] 4 | map(*, [1, 2, 3], [4, 5, 6]) #> [4, 10, 18] 5 | 6 | # do block: 7 | map( x -> begin 8 | if x == 0 return 0 9 | elseif iseven(x) return 2 10 | elseif isodd(x) return 1 11 | end 12 | end, 13 | [-3:3]) #> [1,2,1,0,1,2,1] 14 | 15 | map([-3:3]) do x 16 | if x == 0 return 0 17 | elseif iseven(x) return 2 18 | elseif isodd(x) return 1 19 | end 20 | end #> [1,2,1,0,1,2,1] 21 | 22 | # filter: 23 | filter( n -> iseven(n), [1:10]) #> [2, 4, 6, 8, 10] 24 | filter( n -> n % 2 == 0, [1:10]) #> [2, 4, 6, 8, 10] 25 | 26 | # comprehensions: 27 | arr0 = [n for n in 1:1000] #> [1,2,...,1000] 28 | # better write it as arr0 = [1:1000] 29 | arr = Float64[x^2 for x in 1:4] #> [1.0,4.0,9.0,16.0] 30 | cubes = [x^3 for x in [1:5]] #> [1, 8, 27, 64, 125] 31 | table10 = [x*y for x=1:10, y=1:10] #> 32 | #= 33 | #1 2 3 4 5 6 7 8 9 10 34 | #2 4 6 8 10 12 14 16 18 20 35 | #3 6 9 12 15 18 21 24 27 30 36 | #4 8 12 16 20 24 28 32 36 40 37 | #5 10 15 20 25 30 35 40 45 50 38 | #6 12 18 24 30 36 42 48 54 60 39 | #7 14 21 28 35 42 49 56 63 70 40 | #8 16 24 32 40 48 56 64 72 80 41 | #9 18 27 36 45 54 63 72 81 90 42 | #10 20 30 40 50 60 70 80 90 100 43 | =# 44 | mat1 = [x + y for x in 1:2, y in 1:3] 45 | #> 2 3 4 46 | #> 3 4 5 47 | 48 | arrany = Any[i * 2 for i in 1:5] #> [2,4,6,8,10] 49 | [ sqrt(exp(i))-j for i = 1:8, j = 1:8] 50 | # 8x8 Array{Float64,2}: 51 | # 0.648721 -0.351279 -1.35128 … -4.35128 -5.35128 -6.35128 52 | # 1.71828 0.718282 -0.281718 -3.28172 -4.28172 -5.28172 53 | # 3.48169 2.48169 1.48169 -1.51831 -2.51831 -3.51831 54 | # 6.38906 5.38906 4.38906 1.38906 0.389056 -0.610944 55 | # 11.1825 10.1825 9.18249 6.18249 5.18249 4.18249 56 | # 19.0855 18.0855 17.0855 … 14.0855 13.0855 12.0855 57 | # 32.1155 31.1155 30.1155 27.1155 26.1155 25.1155 58 | # 53.5982 52.5982 51.5982 48.5982 47.5982 46.5982 -------------------------------------------------------------------------------- /Module 1/Chapter04/Old/conditional.jl: -------------------------------------------------------------------------------- 1 | var = 7 2 | if var > 10 3 | println("var has value $var and is bigger than 10.") 4 | elseif var < 10 # This elseif clause is optional. 5 | println("var has value $var and is smaller than 10.") 6 | else # The else clause is optional too. 7 | println("var has value $var and is 10.") 8 | end 9 | # => prints "var has value 7 and is smaller than 10." 10 | 11 | # if 0 print("ok") end 12 | # ERROR: type: non-boolean (Int64) used in boolean context 13 | 14 | a = 10 15 | b = 15 16 | z = if a > b a 17 | else b 18 | end 19 | println(z) #=> 15 20 | z = a > b ? a : b # with ternary operator 21 | 22 | var = 7 23 | varout = "var has value $var" 24 | cond = var > 10 ? "and is bigger than 10." : var < 10 ? "and is smaller than 10" : "and is 10." 25 | println("$varout $cond") # var has value 7 and is smaller than 10 26 | 27 | function sqroot(n::Int) 28 | n >= 0 || error("n must be non-negative") 29 | n == 0 && return 0 30 | sqrt(n) 31 | end 32 | sqroot(4) #=> 2.0 33 | sqroot(0) #=> 0.0 34 | sqroot(-6) #=> ERROR: n must be non-negative 35 | -------------------------------------------------------------------------------- /Module 1/Chapter04/Old/errors.jl: -------------------------------------------------------------------------------- 1 | arr = [1,2,3] 2 | # arr[0] #=> causes a program stop with: ERROR: BoundsError() 3 | # sqrt(-3) #=> causes an ERROR: DomainError: sqrt will only 4 | sqrt(complex(-3)) #=> 0.0 + 1.7320508075688772im 5 | 6 | type CustomException <: Exception end 7 | 8 | # throw: 9 | codes = ["AO", "ZD", "SG", "EZ"] 10 | code = "AR" 11 | if in(code, codes) 12 | println("This is an acceptable code") 13 | else 14 | throw(DomainError()) 15 | end 16 | 17 | # error: 18 | function sqroot(n::Int) 19 | n >= 0 || error("n must be non-negative") 20 | n == 0 && return 0 21 | sqrt(n) 22 | end 23 | sqroot(4) #=> 2.0 24 | sqroot(0) #=> 0.0 25 | # sqroot(-6) #=> ERROR: n must be non-negative 26 | 27 | warn("Something is not right here") 28 | info("Did you know this?") 29 | 30 | type CustomException <: Exception 31 | end 32 | 33 | # try / catch 34 | a = [] 35 | try 36 | pop!(a) 37 | catch ex 38 | println(typeof(ex)) #=> ErrorException 39 | backtrace() 40 | showerror(STDOUT, ex) #=> array must be non-empty 41 | end 42 | 43 | try 44 | # try this code 45 | catch ex 46 | if isa(ex, DomainError) 47 | # do this 48 | elseif isa(ex, BoundsError) 49 | # do this 50 | end 51 | end 52 | 53 | ret = try 54 | a = 4 * 2 55 | catch ex 56 | end 57 | println(ret) #=> 8 58 | 59 | # finally 60 | f = open("file1.txt") #=> IOStream() 61 | try 62 | # operate on file f 63 | finally 64 | close(f) 65 | end 66 | -------------------------------------------------------------------------------- /Module 1/Chapter04/Old/repetitions.jl: -------------------------------------------------------------------------------- 1 | coll = [1:50] 2 | for e in coll 3 | # process(e) executed for every element e in coll 4 | end 5 | 6 | for n = 1:10 println(n^3) end 7 | # prints: 8 | #1 9 | #8 10 | #27 11 | #64 12 | #125 13 | #216 14 | #343 15 | #512 16 | #729 17 | #1000 18 | 19 | # iterate over index: 20 | arr = [x^2 for x in 1:10] 21 | #10-element Array{Int64,1}: 22 | # 1 23 | # 4 24 | # 9 25 | # 16 26 | # 25 27 | # 36 28 | # 49 29 | # 64 30 | # 81 31 | # 100 32 | 33 | for i = 1:length(arr) 34 | println("the $i-th element is $(arr[i])") 35 | end 36 | # the 1-th element is 1 37 | # the 2-th element is 4 38 | # the 3-th element is 9 39 | # the 4-th element is 16 40 | # the 5-th element is 25 41 | # the 6-th element is 36 42 | # the 7-th element is 49 43 | # the 8-th element is 64 44 | # the 9-th element is 81 45 | # the 10-th element is 100 46 | 47 | for n = 1:5, m = 1:5 48 | println("$n * $m = $(n * m)") 49 | end 50 | # 51 | #1 * 1 = 1 52 | #1 * 2 = 2 53 | #1 * 3 = 3 54 | #1 * 4 = 4 55 | #1 * 5 = 5 56 | #2 * 1 = 2 57 | #2 * 2 = 4 58 | #2 * 3 = 6 59 | #2 * 4 = 8 60 | #2 * 5 = 10 61 | #3 * 1 = 3 62 | #3 * 2 = 6 63 | #3 * 3 = 9 64 | #3 * 4 = 12 65 | #3 * 5 = 15 66 | #4 * 1 = 4 67 | #4 * 2 = 8 68 | #4 * 3 = 12 69 | #4 * 4 = 16 70 | #4 * 5 = 20 71 | #5 * 1 = 5 72 | #5 * 2 = 10 73 | #5 * 3 = 15 74 | #5 * 4 = 20 75 | #5 * 5 = 25 76 | 77 | # while loop: 78 | a = 10 79 | b = 15 80 | while a < b 81 | # process(a) 82 | println(a) 83 | a += 1 84 | end 85 | # prints: 86 | #10 87 | #11 88 | #12 89 | #13 90 | #14 91 | 92 | # loop over array that is changing in the loop: 93 | arr = [1,2,3,4] 94 | while !isempty(arr) 95 | print(pop!(arr), ", ") 96 | end 97 | # => 4, 3, 2, 1, 98 | # julia> arr 99 | # 0-element Array{Int64,1} 100 | 101 | # break: 102 | a = 10 103 | b = 150 104 | while a < b 105 | # process(a) 106 | println(a) 107 | a += 1 108 | if a >= 50 109 | break 110 | end 111 | end 112 | 113 | # continue: 114 | for n in 1:10 115 | if 3 <= n <= 6 116 | continue # skip one iteration 117 | end 118 | println(x) 119 | end 120 | 121 | -------------------------------------------------------------------------------- /Module 1/Chapter04/Old/scope.jl: -------------------------------------------------------------------------------- 1 | # variant 1: 2 | x = 9 3 | function funscope(n) 4 | x = 0 5 | for i = 1:n 6 | local x 7 | x = i + 1 8 | if (x == 7) 9 | println("This is the local x in for: $x") #=> 7 10 | end 11 | end 12 | x 13 | println("This is the local x in funscope: $x") #=> 0 14 | global x = 15 15 | end 16 | funscope(10) 17 | println("This is the global x: $x") #=> 15 18 | 19 | # variant 2: 20 | x = 9 21 | function funscope(n) 22 | x = 0 23 | for i = 1:n 24 | x = i + 1 25 | if (x == 7) 26 | println("This is the local x in funscope: $x") #=> 7 27 | end 28 | end 29 | x 30 | println("This is the local x in funscope: $x") #=> 11 31 | global x = 15 32 | end 33 | funscope(10) 34 | println("This is the global x: $x") #=> 15 35 | 36 | # variant 3: 37 | x = 9 38 | function funscope(n) 39 | x = 0 40 | for i = 1:n 41 | x = i + 1 42 | if (x == 7) 43 | println("This is the local x in for: $x") #=> 7 44 | end 45 | end 46 | x 47 | println("This is the local x in funscope: $x") #=> 11 48 | end 49 | funscope(10) 50 | println("This is the global x: $x") #=> 9 51 | 52 | # without let: 53 | anon = cell(2) 54 | for i = 1:2 55 | anon[i] = ()-> println(i) 56 | i += 1 57 | end 58 | anon[1]() #=> 2 59 | anon[2]() #=> 3 60 | 61 | # with let: 62 | anon = cell(2) 63 | for i = 1:2 64 | let i = i 65 | anon[i] = ()-> println(i) 66 | end 67 | i += 1 68 | end 69 | anon[1]() #=> 1 70 | anon[2]() #=> 2 71 | 72 | # combined with begin: 73 | begin 74 | local x = 1 75 | let 76 | local x = 2 77 | println(x) #=> 2 78 | end 79 | x 80 | println(x) #=> 1 81 | end 82 | 83 | # for-loops and comprehensions: 84 | i = 0 85 | for i = 1:10 86 | end 87 | println(i) #=> 10 88 | 89 | i = 0 90 | [i for i = 1:10 ] 91 | println(i) #=> 0 92 | -------------------------------------------------------------------------------- /Module 1/Chapter04/Old/tasks.jl: -------------------------------------------------------------------------------- 1 | function fib(n) 2 | a, b = (0, 1) 3 | produce(1) 4 | for i = 1:n 5 | produce(b) 6 | a, b = (b, a + b) 7 | end 8 | end 9 | 10 | tsk1 = Task( () -> fib(10) ) # Task (runnable) @0x0000000005696180 11 | 12 | consume(tsk1) #=> 1 13 | consume(tsk1) #=> 1 14 | consume(tsk1) #=> 1 15 | consume(tsk1) #=> 2 16 | consume(tsk1) #=> 3 17 | consume(tsk1) #=> 5 18 | consume(tsk1) #=> 8 19 | consume(tsk1) #=> 13 20 | consume(tsk1) #=> 21 21 | consume(tsk1) #=> 34 22 | consume(tsk1) #=> 55 23 | consume(tsk1) #=> nothing # Task (done) @0x0000000005696180 24 | 25 | for n in tsk1 26 | println(n) 27 | end 28 | #=> 1 1 1 2 3 5 8 13 21 34 55 29 | tsk1 = @task fib(10) # Task (runnable) @0x0000000005696d80 30 | -------------------------------------------------------------------------------- /Module 1/Chapter04/conditional.jl: -------------------------------------------------------------------------------- 1 | var = 7 2 | if var > 10 3 | println("var has value $var and is bigger than 10.") 4 | elseif var < 10 # This elseif clause is optional. 5 | println("var has value $var and is smaller than 10.") 6 | else # The else clause is optional too. 7 | println("var has value $var and is 10.") 8 | end 9 | #> prints "var has value 7 and is smaller than 10." 10 | 11 | # if 0 print("ok") end 12 | # ERROR: type: non-boolean (Int64) used in boolean context 13 | 14 | a = 10 15 | b = 15 16 | z = if a > b a 17 | else b 18 | end 19 | println(z) #> 15 20 | z = a > b ? a : b # with ternary operator 21 | 22 | var = 7 23 | varout = "var has value $var" 24 | cond = var > 10 ? "and is bigger than 10." : var < 10 ? "and is smaller than 10" : "and is 10." 25 | println("$varout $cond") # var has value 7 and is smaller than 10 26 | 27 | function sqroot(n::Int) 28 | n >= 0 || error("n must be non-negative") 29 | n == 0 && return 0 30 | sqrt(n) 31 | end 32 | sqroot(4) #> 2.0 33 | sqroot(0) #> 0.0 34 | # sqroot(-6) #> ERROR: n must be non-negative -------------------------------------------------------------------------------- /Module 1/Chapter04/errors.jl: -------------------------------------------------------------------------------- 1 | arr = [1,2,3] 2 | # arr[0] #> causes a program stop with: ERROR: BoundsError() 3 | # sqrt(-3) #> causes an ERROR: DomainError: sqrt will only 4 | sqrt(complex(-3)) #> 0.0 + 1.7320508075688772im 5 | 6 | type CustomException <: Exception end 7 | 8 | # throw: 9 | codes = ["AO", "ZD", "SG", "EZ"] 10 | # code = "AR" 11 | code = "AO" 12 | if code in codes # in(code, codes) 13 | println("This is an acceptable code") 14 | else 15 | throw(DomainError()) 16 | end 17 | 18 | # error: 19 | function sqroot(n::Int) 20 | n >= 0 || error("n must be non-negative") 21 | n == 0 && return 0 22 | sqrt(n) 23 | end 24 | sqroot(4) #> 2.0 25 | sqroot(0) #> 0.0 26 | # sqroot(-6) #> ERROR: n must be non-negative 27 | 28 | warn("Something is not right here") 29 | info("Did you know this?") 30 | 31 | type CustomException <: Exception 32 | end 33 | 34 | # try / catch 35 | a = [] 36 | try 37 | pop!(a) 38 | catch ex 39 | println(typeof(ex)) #> ErrorException 40 | backtrace() 41 | showerror(STDOUT, ex) #> array must be non-empty 42 | end 43 | # push!(a,1) ERROR: [] cannot grow. Instead, initialize the array with "T[]", where T is the desired element type. 44 | 45 | try 46 | # try this code 47 | catch ex 48 | if isa(ex, DomainError) 49 | # do this 50 | elseif isa(ex, BoundsError) 51 | # do this 52 | end 53 | end 54 | 55 | ret = try 56 | a = 4 * 2 57 | catch ex 58 | end 59 | println(ret) #> 8 60 | 61 | # finally 62 | f = open("file1.txt", "w") #> IOStream() 63 | try 64 | # operate on file f 65 | catch ex 66 | finally 67 | close(f) 68 | end -------------------------------------------------------------------------------- /Module 1/Chapter04/file1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter04/file1.txt -------------------------------------------------------------------------------- /Module 1/Chapter04/tasks.jl: -------------------------------------------------------------------------------- 1 | function fib_producer(n) 2 | a, b = (0, 1) 3 | for i = 1:n 4 | produce(b) 5 | a, b = (b, a + b) 6 | end 7 | end 8 | 9 | tsk1 = Task( () -> fib_producer(10) ) # Task (runnable) @0x0000000005696180 10 | 11 | consume(tsk1) #> 1 12 | consume(tsk1) #> 1 13 | consume(tsk1) #> 2 14 | consume(tsk1) #> 3 15 | consume(tsk1) #> 5 16 | consume(tsk1) #> 8 17 | consume(tsk1) #> 13 18 | consume(tsk1) #> 21 19 | consume(tsk1) #> 34 20 | consume(tsk1) #> 55 21 | consume(tsk1) #> nothing # Task (done) @0x0000000005696180 22 | 23 | for n in tsk1 24 | println(n) 25 | end 26 | #> 1 1 1 2 3 5 8 13 21 34 55 27 | tsk1 = @task fib_producer(10) # Task (runnable) @0x0000000005696d80 -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/matrices.jl: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | [1 2 3] 3 | 4 | matrix = [1 2; 3 4] 5 | matrix[2, 1] #> 3 6 | [1 2] * [3 ; 4] 7 | 8 | ma1 = rand(3, 5) 9 | ndims(ma1) #> 2 10 | size(ma1) #> (3, 5) 11 | size(ma1,1) #> 3 12 | size(ma1,2) #> 5 13 | length(ma1) #> 15 14 | 15 | idm = eye(3) 16 | idm[1:end, 2] #> 2nd column 17 | idm[2, :] #> 2nd row 18 | idm[2:end, 2:end] 19 | #2x2 Array{Float64,2}: 20 | # 1.0 0.0 21 | # 0.0 1.0 22 | idm[2, :] = 0 23 | #julia> idm 24 | #3x3 Array{Float64,2}: 25 | # 1.0 0.0 0.0 26 | # 0.0 0.0 0.0 27 | # 0.0 0.0 1.0 28 | 29 | jarr = (Array{Int64, 1})[] 30 | push!(jarr, [1,2]) 31 | push!(jarr, [1,2,3,4]) 32 | push!(jarr, [1,2,3]) 33 | jarr #> 34 | #3-element Array{Array{Int64,1},1}: 35 | # [1,2] 36 | # [1,2,3,4] 37 | # [1,2,3] 38 | 39 | ma = [1 2; 3 4] 40 | ma' #> [1 3; 2 4] 41 | ma * ma' #> 42 | #5 11 43 | #11 25 44 | 45 | inv(ma) #> 2x2 Array{Float64,2}: 46 | # -2.0 1.0 47 | # 1.5 -0.5 48 | 49 | ma * inv(ma) #> 2x2 Array{Float64,2}: 50 | # 1.0 0.0 51 | # 8.88178e-16 1.0 52 | 53 | v = [1.,2.,3.] #> equivalent to v = [1.0,2.0,3.0] 54 | w = [2.,4.,6.] 55 | append!(v, w) 56 | #6-element Array{Float64,1}: 57 | # 1.0 58 | # 2.0 59 | # 3.0 60 | # 2.0 61 | # 4.0 62 | # 6.0 63 | v = [1.,2.,3.] 64 | hcat(v,w) 65 | # 3x2 Array{Float64,2}: 66 | # 1.0 2.0 67 | # 2.0 4.0 68 | # 3.0 6.0 69 | vcat(v,w) 70 | # 6-element Array{Float64,1}: 71 | # 1.0 72 | # 2.0 73 | # 3.0 74 | # 2.0 75 | # 4.0 76 | # 6.0 77 | arr = Int64[] 78 | sizehint(arr, 75) -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/results_words1.txt: -------------------------------------------------------------------------------- 1 | Word: frequency 2 | 3 | be: 2 4 | is: 1 5 | not: 1 6 | or: 1 7 | question: 1 8 | that: 1 9 | the: 1 10 | to: 2 -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/sets.jl: -------------------------------------------------------------------------------- 1 | s = Set({11, 14, 13, 7, 14, 11}) 2 | s = Set(11, 14, 13, 7, 14, 11) #> deprecated 3 | #> Set{Int64}({7,14,13,11}) 4 | # better: 5 | 6 | s1 = Set({11, 25}) 7 | s2 = Set({25, 3.14}) 8 | union(s1, s2) #> Set{Any}({3.14,25,11}) 9 | intersect(s1, s2) #> Set{Any}({25}) 10 | setdiff(s1, s2) #> Set{Any}({11}) 11 | setdiff(s2, s1) #> Set{Any}({ 3.14}) 12 | issubset(s1, s2) #> false 13 | issubset(s1, Set({11, 25, 36})) #> true 14 | 15 | push!(s1, 32) #> Set{Any}({25,32,11}) 16 | in(32, s1) #> true 17 | in(100, s1) #> false 18 | 19 | st = Set{(Int, Int)}() 20 | push!(st, (1,2)) 21 | #> Set{(Int64,Int64)}({(1,2)}) 22 | st2 = Set({(1, 2), (5, 6)}) #> Set{Any}({(1,2),(5,6)}) -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/tuples.jl: -------------------------------------------------------------------------------- 1 | a, b, c, d = 1, 22.0, "World", 'x' 2 | a #> 1 3 | b #> 22.0 4 | c #> "World" 5 | d #> 'x' 6 | t1 = (1,22.0,"World",'x') 7 | typeof(t1) #> (Int64,Float64,ASCIIString,Char) 8 | t2 = (1, 2, 3) 9 | typeof(t2) #> (Int64,Int64,Int64) 10 | () #> empty tuple 11 | (1,) #> one element tuple 12 | ('z', 3.14)::(Char, Float64) 13 | 14 | t3 = (5, 6, 7, 8) 15 | t3[1] #> 5 16 | t3[end] #> 8 17 | t3[2:3] #> (6, 7) 18 | # t3[5] #> BoundsError 19 | # t3[3] = 9 #> Error: 'setindex' has no matching ... 20 | for i in t3 21 | println(i) 22 | end #> 5 6 7 8 23 | 24 | #tuple unpacking: 25 | a, b = t3 #> a is 5 and b is 6 26 | -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/word_frequency.jl: -------------------------------------------------------------------------------- 1 | # 1- read in text file: 2 | str = readall("words1.txt") 3 | # println(str) #> to be or not to be that is the question 4 | # 2- replace non alfabet characters and digits from text with space: 5 | nonalfa = r"(\W\s?)" 6 | str = replace(str, nonalfa, ' ') 7 | digits = r"(\d+)" 8 | str = replace(str, digits, ' ') 9 | #> "to be or not to be that is the question " 10 | # 3- split text in words: 11 | word_list = split(str, ' ') 12 | # println(word_list) 13 | #> "to" "be" "or" "not" "to" "be" "that" "is" "the" "question" "" 14 | # 4- make a dictionary with the words and count their frequencies: 15 | word_freq = Dict{String, Int64}() 16 | for word in word_list 17 | strip(word) 18 | if isempty(word) continue end 19 | haskey(word_freq, word) ? word_freq[word] += 1 : word_freq[word] = 1 20 | end 21 | # 5- sort the words (the keys) and print out the frequencies: 22 | println("Word : frequency \n") 23 | words = sort!(collect(keys(word_freq))) 24 | for word in words 25 | println("$word : $(word_freq[word])") 26 | end 27 | -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/words1.txt: -------------------------------------------------------------------------------- 1 | to be, or not to be, that is the question! -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/Old/words2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter05/Old/Old/words2.txt -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/results_words1.txt: -------------------------------------------------------------------------------- 1 | Word: frequency 2 | 3 | be: 2 4 | is: 1 5 | not: 1 6 | or: 1 7 | question: 1 8 | that: 1 9 | the: 1 10 | to: 2 -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/sets.jl: -------------------------------------------------------------------------------- 1 | # s = Set({11, 14, 13, 7, 14, 11}) 2 | # s = Set(11, 14, 13, 7, 14, 11) #> deprecated!!! works still in v0.3 3 | s = Set(Any[11, 14, 13, 7, 14, 11]) # preferred from v0.4 onwards 4 | #> Set{Int64}({7,14,13,11}) 5 | # better: 6 | # s1 = Set({11, 25}) 7 | s1 = Set(Any[11, 25]) # preferred from v0.4 onwards 8 | # s2 = Set({25, 3.14}) 9 | s2 = Set(Any[25, 3.14]) # preferred from v0.4 onwards 10 | union(s1, s2) #> Set{Any}({3.14,25,11}) 11 | intersect(s1, s2) #> Set{Any}({25}) 12 | setdiff(s1, s2) #> Set{Any}({11}) 13 | setdiff(s2, s1) #> Set{Any}({ 3.14}) 14 | issubset(s1, s2) #> false 15 | # issubset(s1, Set({11, 25, 36})) #> true 16 | issubset(s1, Set(Any[11, 25, 36])) #> true # preferred from v0.4 onwards 17 | 18 | push!(s1, 32) #> Set{Any}({25,32,11}) 19 | in(32, s1) #> true 20 | in(100, s1) #> false 21 | 22 | x = Set([1:100]) 23 | @time 2 in x # elapsed time 4.888e-6 seconds 24 | x2 = Set([1:1000000]) 25 | @time 2 in x2 # elapsed time 5.378e-6 seconds 26 | 27 | st = Set{(Int, Int)}() 28 | push!(st, (1,2)) 29 | #> Set{(Int64,Int64)}({(1,2)}) 30 | # st2 = Set({(1, 2), (5, 6)}) #> Set{Any}({(1,2),(5,6)}) 31 | st2 = Set(Any[(1, 2), (5, 6)]) # preferred from v0.4 onwards -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/sets_v3.jl: -------------------------------------------------------------------------------- 1 | s = Set({11, 14, 13, 7, 14, 11}) 2 | # s = Set(11, 14, 13, 7, 14, 11) #> deprecated!!! works still in v0.3 3 | #> Set{Int64}({7,14,13,11}) 4 | # better: 5 | s1 = Set({11, 25}) 6 | s2 = Set({25, 3.14}) 7 | union(s1, s2) #> Set{Any}({3.14,25,11}) 8 | intersect(s1, s2) #> Set{Any}({25}) 9 | setdiff(s1, s2) #> Set{Any}({11}) 10 | setdiff(s2, s1) #> Set{Any}({ 3.14}) 11 | issubset(s1, s2) #> false 12 | issubset(s1, Set({11, 25, 36})) #> true 13 | 14 | push!(s1, 32) #> Set{Any}({25,32,11}) 15 | in(32, s1) #> true 16 | in(100, s1) #> false 17 | 18 | x = Set([1:100]) 19 | @time 2 in x # elapsed time 4.888e-6 seconds 20 | x2 = Set([1:1000000]) 21 | @time 2 in x2 # elapsed time 5.378e-6 seconds 22 | 23 | st = Set{(Int, Int)}() 24 | push!(st, (1,2)) 25 | #> Set{(Int64,Int64)}({(1,2)}) 26 | st2 = Set({(1, 2), (5, 6)}) #> Set{Any}({(1,2),(5,6)}) -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/tuples.jl: -------------------------------------------------------------------------------- 1 | a, b, c, d = 1, 22.0, "World", 'x' 2 | a #> 1 3 | b #> 22.0 4 | c #> "World" 5 | d #> 'x' 6 | t1 = (1,22.0,"World",'x') 7 | typeof(t1) #> (Int64,Float64,ASCIIString,Char) 8 | t2 = (1, 2, 3) 9 | typeof(t2) #> (Int64,Int64,Int64) 10 | () #> empty tuple 11 | (1,) #> one element tuple 12 | ('z', 3.14)::(Char, Float64) 13 | 14 | t3 = (5, 6, 7, 8) 15 | t3[1] #> 5 16 | t3[end] #> 8 17 | t3[2:3] #> (6, 7) 18 | # t3[5] #> BoundsError 19 | # t3[3] = 9 #> Error: 'setindex' has no matching ... 20 | 21 | author = ("Ivo", "Balbaert", 59) 22 | author[2] #> "Balbaert" 23 | 24 | for i in t3 25 | println(i) 26 | end #> 5 6 7 8 27 | 28 | #tuple unpacking: 29 | a, b = t3 #> a is 5 and b is 6 30 | first_name, last_name, age = author 31 | # first_name has value "Ivo" 32 | # last_name has value "Balbaert" 33 | # age has value 59 -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/word_frequency.jl: -------------------------------------------------------------------------------- 1 | # 1- read in text file: 2 | str = readall("words1.txt") 3 | # println(str) #> to be or not to be that is the question 4 | # 2- replace non alphabet characters and digits from text with a space: 5 | nonalpha = r"(\W\s?)" 6 | str = replace(str, nonalpha, ' ') 7 | digits = r"(\d+)" 8 | str = replace(str, digits, ' ') 9 | #> "to be or not to be that is the question " 10 | # 3- split text in words: 11 | word_list = split(str, ' ') 12 | # println(word_list) 13 | #> "to" "be" "or" "not" "to" "be" "that" "is" "the" "question" "" 14 | # 4- make a dictionary with the words and count their frequencies: 15 | word_freq = Dict{String, Int64}() 16 | for word in word_list 17 | word = strip(word) 18 | if isempty(word) continue end 19 | haskey(word_freq, word) ? 20 | word_freq[word] += 1 : 21 | word_freq[word] = 1 22 | end 23 | # 5- sort the words (the keys) and print out the frequencies: 24 | println("Word : frequency \n") 25 | words = sort!(collect(keys(word_freq))) 26 | for word in words 27 | println("$word : $(word_freq[word])") 28 | end -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/words1.txt: -------------------------------------------------------------------------------- 1 | to be, or not to be, that is the question! -------------------------------------------------------------------------------- /Module 1/Chapter05/Old/words2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter05/Old/words2.txt -------------------------------------------------------------------------------- /Module 1/Chapter05/results_words1.txt: -------------------------------------------------------------------------------- 1 | Word: frequency 2 | 3 | be: 2 4 | is: 1 5 | not: 1 6 | or: 1 7 | question: 1 8 | that: 1 9 | the: 1 10 | to: 2 -------------------------------------------------------------------------------- /Module 1/Chapter05/sets.jl: -------------------------------------------------------------------------------- 1 | # s = Set({11, 14, 13, 7, 14, 11}) 2 | # s = Set(11, 14, 13, 7, 14, 11) #> deprecated!!! works still in v0.3 3 | s = Set(Any[11, 14, 13, 7, 14, 11]) # preferred from v0.4 onwards 4 | #> Set{Int64}({7,14,13,11}) 5 | # better: 6 | # s1 = Set({11, 25}) 7 | s1 = Set(Any[11, 25]) # preferred from v0.4 onwards 8 | # s2 = Set({25, 3.14}) 9 | s2 = Set(Any[25, 3.14]) # preferred from v0.4 onwards 10 | union(s1, s2) #> Set{Any}({3.14,25,11}) 11 | intersect(s1, s2) #> Set{Any}({25}) 12 | setdiff(s1, s2) #> Set{Any}({11}) 13 | setdiff(s2, s1) #> Set{Any}({ 3.14}) 14 | issubset(s1, s2) #> false 15 | # issubset(s1, Set({11, 25, 36})) #> true 16 | issubset(s1, Set(Any[11, 25, 36])) #> true # preferred from v0.4 onwards 17 | 18 | push!(s1, 32) #> Set{Any}({25,32,11}) 19 | in(32, s1) #> true 20 | in(100, s1) #> false 21 | 22 | x = Set([1:100]) 23 | @time 2 in x # elapsed time 4.888e-6 seconds 24 | x2 = Set([1:1000000]) 25 | @time 2 in x2 # elapsed time 5.378e-6 seconds 26 | 27 | st = Set{(Int, Int)}() 28 | push!(st, (1,2)) 29 | #> Set{(Int64,Int64)}({(1,2)}) 30 | # st2 = Set({(1, 2), (5, 6)}) #> Set{Any}({(1,2),(5,6)}) 31 | st2 = Set(Any[(1, 2), (5, 6)]) # preferred from v0.4 onwards -------------------------------------------------------------------------------- /Module 1/Chapter05/sets_v3.jl: -------------------------------------------------------------------------------- 1 | s = Set({11, 14, 13, 7, 14, 11}) 2 | # s = Set(11, 14, 13, 7, 14, 11) #> deprecated!!! works still in v0.3 3 | #> Set{Int64}({7,14,13,11}) 4 | # better: 5 | s1 = Set({11, 25}) 6 | s2 = Set({25, 3.14}) 7 | union(s1, s2) #> Set{Any}({3.14,25,11}) 8 | intersect(s1, s2) #> Set{Any}({25}) 9 | setdiff(s1, s2) #> Set{Any}({11}) 10 | setdiff(s2, s1) #> Set{Any}({ 3.14}) 11 | issubset(s1, s2) #> false 12 | issubset(s1, Set({11, 25, 36})) #> true 13 | 14 | push!(s1, 32) #> Set{Any}({25,32,11}) 15 | in(32, s1) #> true 16 | in(100, s1) #> false 17 | 18 | x = Set([1:100]) 19 | @time 2 in x # elapsed time 4.888e-6 seconds 20 | x2 = Set([1:1000000]) 21 | @time 2 in x2 # elapsed time 5.378e-6 seconds 22 | 23 | st = Set{(Int, Int)}() 24 | push!(st, (1,2)) 25 | #> Set{(Int64,Int64)}({(1,2)}) 26 | st2 = Set({(1, 2), (5, 6)}) #> Set{Any}({(1,2),(5,6)}) -------------------------------------------------------------------------------- /Module 1/Chapter05/tuples.jl: -------------------------------------------------------------------------------- 1 | a, b, c, d = 1, 22.0, "World", 'x' 2 | a #> 1 3 | b #> 22.0 4 | c #> "World" 5 | d #> 'x' 6 | t1 = (1,22.0,"World",'x') 7 | typeof(t1) #> (Int64,Float64,ASCIIString,Char) 8 | t2 = (1, 2, 3) 9 | typeof(t2) #> (Int64,Int64,Int64) 10 | () #> empty tuple 11 | (1,) #> one element tuple 12 | ('z', 3.14)::(Char, Float64) 13 | 14 | t3 = (5, 6, 7, 8) 15 | t3[1] #> 5 16 | t3[end] #> 8 17 | t3[2:3] #> (6, 7) 18 | # t3[5] #> BoundsError 19 | # t3[3] = 9 #> Error: 'setindex' has no matching ... 20 | 21 | author = ("Ivo", "Balbaert", 59) 22 | author[2] #> "Balbaert" 23 | 24 | for i in t3 25 | println(i) 26 | end #> 5 6 7 8 27 | 28 | #tuple unpacking: 29 | a, b = t3 #> a is 5 and b is 6 30 | first_name, last_name, age = author 31 | # first_name has value "Ivo" 32 | # last_name has value "Balbaert" 33 | # age has value 59 -------------------------------------------------------------------------------- /Module 1/Chapter05/word_frequency.jl: -------------------------------------------------------------------------------- 1 | # 1- read in text file: 2 | str = readall("words1.txt") 3 | # println(str) #> to be or not to be that is the question 4 | # 2- replace non alphabet characters and digits from text with a space: 5 | nonalpha = r"(\W\s?)" 6 | str = replace(str, nonalpha, ' ') 7 | digits = r"(\d+)" 8 | str = replace(str, digits, ' ') 9 | #> "to be or not to be that is the question " 10 | # 3- split text in words: 11 | word_list = split(str, ' ') 12 | # println(word_list) 13 | #> "to" "be" "or" "not" "to" "be" "that" "is" "the" "question" "" 14 | # 4- make a dictionary with the words and count their frequencies: 15 | word_freq = Dict{String, Int64}() 16 | for word in word_list 17 | word = strip(word) 18 | if isempty(word) continue end 19 | haskey(word_freq, word) ? 20 | word_freq[word] += 1 : 21 | word_freq[word] = 1 22 | end 23 | # 5- sort the words (the keys) and print out the frequencies: 24 | println("Word : frequency \n") 25 | words = sort!(collect(keys(word_freq))) 26 | for word in words 27 | println("$word : $(word_freq[word])") 28 | end -------------------------------------------------------------------------------- /Module 1/Chapter05/words1.txt: -------------------------------------------------------------------------------- 1 | to be, or not to be, that is the question! -------------------------------------------------------------------------------- /Module 1/Chapter05/words2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter05/words2.txt -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/conversions.jl: -------------------------------------------------------------------------------- 1 | # (31+42)::Float64 #> TypeError(:typeassert,"",Float64,73) 2 | # convert(Int64, 7.01) #> ERROR: InexactError() 3 | convert(Int64, 7.0) #> 7 4 | int64(7.0) #> 7 5 | int64(7.01) #> 7 6 | # convert(Int64, "CV") 7 | # ERROR: `convert` has no method matching convert(::Type{Int64}, ::ASCIIString) 8 | # convert(Int64, "123") # same ERROR as above 9 | 10 | promote(1, 2.5, 3//4) #> (1.0,2.5,0.75) 11 | promote(1.5, im) #> (1.5 + 0.0im,0.0 + 1.0im) 12 | promote(true, 'c', 1.0) #> (1.0,99.0,1.0) 13 | 14 | promote_type(Int8, Uint16) #> Int64 -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/file1.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter06/Old/file1.jl -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/file2.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter06/Old/file2.jl -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/inner_constructors.jl: -------------------------------------------------------------------------------- 1 | type Person 2 | firstname::String 3 | lastname::String 4 | sex::Char 5 | age::Float64 6 | children::Array{String, 1} 7 | end 8 | 9 | p1 = Person("Alan", "Bates", 'M', 45.5, ["Jeff", "Stephan"]) 10 | #> Person("Alan", "Bates",'M',45.5,String["Jeff","Stephan"]) 11 | 12 | people = Person[] #> 0-element Array{Person,1} 13 | push!(people, p1) 14 | push!(people, Person("Julia", "Smith", 'F', 27, ["Viral"])) 15 | 16 | show(people) 17 | #> [Person("Alan", "Bates", 'M',45.5,String["Jeff","Stephan"]), 18 | # Person("Julia", "Smith",'F',27.0,String["Viral"])] 19 | 20 | fullname(p::Person) = "$(p.firstname) $(p.lastname)" 21 | fullname(p::Person) = string(p.firstname, " ", p.lastname) 22 | print(fullname(p1)) #> Alan Bates 23 | 24 | type Family 25 | name::String 26 | members::Array{String, 1} 27 | big::Bool 28 | Family(name::String) = new(name, String[], false) 29 | Family(name::String, members) = new(name, members, length(members) > 4) 30 | end 31 | 32 | fam = Family("Bates-Smith", ["Alan", "Julia", "Jeff", "Stephan", "Viral"]) 33 | #> Family("Bates-Smith",String["Alan","Julia","Jeff","Stephan","Viral"],true) 34 | -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/modules.jl: -------------------------------------------------------------------------------- 1 | module Package1 2 | 3 | require("modules_ext.jl") 4 | using LibA 5 | using LibB.varB 6 | using LibC: varC, funcC 7 | import LibD.funcD 8 | importall LibE 9 | 10 | export Type1, perc 11 | 12 | include("file1.jl") 13 | include("file2.jl") 14 | 15 | # code 16 | type Type1 17 | total 18 | end 19 | 20 | perc(a::Type) = a.total * 0.01 21 | 22 | end 23 | -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/modules_ext.jl: -------------------------------------------------------------------------------- 1 | module LibA 2 | end 3 | 4 | module LibB 5 | export varB 6 | varB = 42 7 | end 8 | 9 | module LibC 10 | export varC, funcC 11 | 12 | varC = "London" 13 | function funcC() 14 | # code 15 | end 16 | 17 | end 18 | 19 | module LibD 20 | export funcD 21 | function funcD() 22 | # code 23 | end 24 | end 25 | 26 | module LibE 27 | end -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/parametric.jl: -------------------------------------------------------------------------------- 1 | type Point{T} 2 | x::T 3 | y::T 4 | end 5 | 6 | Point{Int64} #> Point{Int64} (constructor with 1 method) 7 | Point{Float64} #> Point{Float64} (constructor with 1 method) 8 | Point{String} #> Point{String} (constructor with 1 method) 9 | 10 | issubtype(Point{Int64}, Point) #> true 11 | issubtype(Point{String}, Point) #> true 12 | issubtype(Point{Float64}, Point{Real}) #> false 13 | 14 | p = Point{Int64}(2, 5) #> Point{Int64}(2,5) 15 | p = Point(2, 5) #> Point{Int64}(2,5) 16 | p = Point("London", "Great-Britain") #> Point{String}("London", "Great-Britain") 17 | 18 | type PointP{T <: Real} 19 | x::T 20 | y::T 21 | end 22 | 23 | # p = PointP("London", "Great-Britain") #> ERROR: `PointP{T<:Real}` has no method 24 | # matching Point{T<:Real}(::ASCIIString, : ASCIIString) 25 | 26 | add{T}(x::T, y::T) = x + y 27 | add(2, 3) #> 5 28 | # add(2, 3.0) #> ERROR: `add` has no method matching add(::Int64, ::Float64) 29 | add{T<:Number}(x::T, y::T) = x + y 30 | 31 | function vecfloat{T <: FloatingPoint}(x::Vector{T}) 32 | # code 33 | end -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/type_hierarchy.jl: -------------------------------------------------------------------------------- 1 | typeof(2) #> Int64 2 | typeof(Int64) #> DataType 3 | typeof(Complex{Int64}) #> DataType 4 | typeof(Any) #> DataType 5 | typeof(DataType) #> DataType 6 | 7 | super(Int64) #> Signed 8 | super(Signed) #> Integer 9 | super(Integer) #> Real 10 | super(Real) #> Number 11 | super(Number) #> Any 12 | super(Any) #> Any 13 | 14 | subtypes(Integer) #> 5-element Array{Any,1}: 15 | # BigInt 16 | # Bool 17 | # Char 18 | # Signed 19 | # Unsigned 20 | subtypes(Signed) #> 5-element Array{Any,1}: 21 | # Int128 22 | # Int16 23 | # Int32 24 | # Int64 25 | # Int8 26 | subtypes(Int64) #> 0-element Array{Any,1} 27 | typeof(None) #> UnionType 28 | 29 | Bool <: Integer #> true 30 | Bool <: Any #> true 31 | Bool <: Char #> false 32 | issubtype(Bool, Integer) #> true 33 | issubtype(Float64, Integer) #> false 34 | 35 | typeof(5) #> Int64 36 | isa(5, Number) #> true 37 | -------------------------------------------------------------------------------- /Module 1/Chapter06/Old/unions.jl: -------------------------------------------------------------------------------- 1 | type Point 2 | x::Float64 3 | y::Float64 4 | end 5 | 6 | type Vector2D 7 | x::Float64 8 | y::Float64 9 | end 10 | 11 | p = Point(2, 5) #> Point(2.0,5.0) 12 | v = Vector2D(3, 2) #> Vector2D(3.0,2.0) 13 | 14 | # *(p, v) #> ERROR: `*` has no method matching *(::Point, ::Vector2D) 15 | 16 | *(p::Point, q::Point) = p.x * q.x + p.y * q.y 17 | *(u::Vector2D, v::Vector2D) = u.x * v.x + u.y * v.y 18 | *(u::Vector2D, p::Point) = u.x * p.x + u.y * p.y 19 | # *(p, v) #> ERROR: `+` has no method matching +(::Point, ::Vector2D) 20 | 21 | *(p::Point, v::Vector2D) = p.x * v.x + p.y * v.y 22 | *(p, v) #> 16.0 23 | 24 | VecOrPoint = Union(Vector2D, Point) 25 | 26 | isa(p, VecOrPoint) #> true 27 | isa(v, VecOrPoint) #> true 28 | 29 | *(u::VecOrPoint, v:: VecOrPoint) = u.x * v.x + u.y * v.y 30 | *(p, v) #> 16.0 31 | -------------------------------------------------------------------------------- /Module 1/Chapter06/conversions.jl: -------------------------------------------------------------------------------- 1 | # (31+42)::Float64 #> TypeError(:typeassert,"",Float64,73) 2 | # convert(Int64, 7.01) #> ERROR: InexactError() 3 | convert(Int64, 7.0) #> 7 4 | int64(7.0) #> 7 5 | int64(7.01) #> 7 6 | # convert(Int64, "CV") 7 | # ERROR: `convert` has no method matching convert(::Type{Int64}, ::ASCIIString) 8 | # convert(Int64, "123") # same ERROR as above 9 | 10 | promote(1, 2.5, 3//4) #> (1.0,2.5,0.75) 11 | promote(1.5, im) #> (1.5 + 0.0im,0.0 + 1.0im) 12 | promote(true, 'c', 1.0) #> (1.0,99.0,1.0) 13 | 14 | promote_type(Int8, Uint16) #> Int64 -------------------------------------------------------------------------------- /Module 1/Chapter06/file1.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter06/file1.jl -------------------------------------------------------------------------------- /Module 1/Chapter06/file2.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter06/file2.jl -------------------------------------------------------------------------------- /Module 1/Chapter06/inner_constructors.jl: -------------------------------------------------------------------------------- 1 | type Person 2 | firstname::String 3 | lastname::String 4 | sex::Char 5 | age::Float64 6 | children::Array{String, 1} 7 | end 8 | 9 | p1 = Person("Alan", "Bates", 'M', 45.5, ["Jeff", "Stephan"]) 10 | #> Person("Alan", "Bates",'M',45.5,String["Jeff","Stephan"]) 11 | 12 | people = Person[] #> 0-element Array{Person,1} 13 | push!(people, p1) 14 | push!(people, Person("Julia", "Smith", 'F', 27, ["Viral"])) 15 | 16 | show(people) 17 | #> [Person("Alan", "Bates", 'M',45.5,String["Jeff","Stephan"]), 18 | # Person("Julia", "Smith",'F',27.0,String["Viral"])] 19 | 20 | fullname(p::Person) = "$(p.firstname) $(p.lastname)" 21 | fullname(p::Person) = string(p.firstname, " ", p.lastname) 22 | print(fullname(p1)) #> Alan Bates 23 | 24 | type Family 25 | name::String 26 | members::Array{String, 1} 27 | big::Bool 28 | Family(name::String) = new(name, String[], false) 29 | Family(name::String, members) = new(name, members, length(members) > 4) 30 | end 31 | 32 | fam = Family("Bates-Smith", ["Alan", "Julia", "Jeff", "Stephan", "Viral"]) 33 | #> Family("Bates-Smith",String["Alan","Julia","Jeff","Stephan","Viral"],true) -------------------------------------------------------------------------------- /Module 1/Chapter06/modules.jl: -------------------------------------------------------------------------------- 1 | module Package1 2 | 3 | require("modules_ext.jl") 4 | using LibA 5 | using LibB.varB 6 | using LibC: varC, funcC 7 | import LibD.funcD 8 | importall LibE 9 | 10 | export Type1, perc 11 | 12 | include("file1.jl") 13 | include("file2.jl") 14 | 15 | # code 16 | type Type1 17 | total 18 | end 19 | 20 | perc(a::Type) = a.total * 0.01 21 | 22 | end -------------------------------------------------------------------------------- /Module 1/Chapter06/modules_ext.jl: -------------------------------------------------------------------------------- 1 | module LibA 2 | end 3 | 4 | module LibB 5 | export varB 6 | varB = 42 7 | end 8 | 9 | module LibC 10 | export varC, funcC 11 | 12 | varC = "London" 13 | function funcC() 14 | # code 15 | end 16 | 17 | end 18 | 19 | module LibD 20 | export funcD 21 | function funcD() 22 | # code 23 | end 24 | end 25 | 26 | module LibE 27 | end -------------------------------------------------------------------------------- /Module 1/Chapter06/parametric.jl: -------------------------------------------------------------------------------- 1 | type Point{T} 2 | x::T 3 | y::T 4 | end 5 | 6 | Point{Int64} #> Point{Int64} (constructor with 1 method) 7 | Point{Float64} #> Point{Float64} (constructor with 1 method) 8 | Point{String} #> Point{String} (constructor with 1 method) 9 | 10 | issubtype(Point{Int64}, Point) #> true 11 | issubtype(Point{String}, Point) #> true 12 | issubtype(Point{Float64}, Point{Real}) #> false 13 | 14 | p = Point{Int64}(2, 5) #> Point{Int64}(2,5) 15 | p = Point(2, 5) #> Point{Int64}(2,5) 16 | p = Point("London", "Great-Britain") #> Point{String}("London", "Great-Britain") 17 | 18 | type PointP{T <: Real} 19 | x::T 20 | y::T 21 | end 22 | 23 | # p = PointP("London", "Great-Britain") #> ERROR: `PointP{T<:Real}` has no method 24 | # matching Point{T<:Real}(::ASCIIString, : ASCIIString) 25 | 26 | add{T}(x::T, y::T) = x + y 27 | add(2, 3) #> 5 28 | # add(2, 3.0) #> ERROR: `add` has no method matching add(::Int64, ::Float64) 29 | add{T<:Number}(x::T, y::T) = x + y 30 | 31 | function vecfloat{T <: FloatingPoint}(x::Vector{T}) 32 | # code 33 | end -------------------------------------------------------------------------------- /Module 1/Chapter06/temperature_converter.jl: -------------------------------------------------------------------------------- 1 | module TemperatureConverter 2 | 3 | export as_celsius 4 | 5 | function as_celsius(temperature, unit) 6 | if unit == :Celsius 7 | return temperature 8 | elseif unit == :Kelvin 9 | return kelvin_to_celsius(temperature) 10 | end 11 | end 12 | 13 | function kelvin_to_celsius(temperature) 14 | # 'private' function 15 | return temperature + 273 16 | end 17 | 18 | end 19 | -------------------------------------------------------------------------------- /Module 1/Chapter06/type_hierarchy.jl: -------------------------------------------------------------------------------- 1 | typeof(2) #> Int64 2 | typeof(Int64) #> DataType 3 | typeof(Complex{Int64}) #> DataType 4 | typeof(Any) #> DataType 5 | typeof(DataType) #> DataType 6 | 7 | super(Int64) #> Signed 8 | super(Signed) #> Integer 9 | super(Integer) #> Real 10 | super(Real) #> Number 11 | super(Number) #> Any 12 | super(Any) #> Any 13 | 14 | subtypes(Integer) #> 5-element Array{Any,1}: 15 | # BigInt 16 | # Bool 17 | # Char 18 | # Signed 19 | # Unsigned 20 | subtypes(Signed) #> 5-element Array{Any,1}: 21 | # Int128 22 | # Int16 23 | # Int32 24 | # Int64 25 | # Int8 26 | subtypes(Int64) #> 0-element Array{Any,1} 27 | typeof(None) #> UnionType 28 | 29 | Bool <: Integer #> true 30 | Bool <: Any #> true 31 | Bool <: Char #> false 32 | issubtype(Bool, Integer) #> true 33 | issubtype(Float64, Integer) #> false 34 | 35 | typeof(5) #> Int64 36 | isa(5, Number) #> true -------------------------------------------------------------------------------- /Module 1/Chapter06/unions.jl: -------------------------------------------------------------------------------- 1 | type Point 2 | x::Float64 3 | y::Float64 4 | end 5 | 6 | type Vector2D 7 | x::Float64 8 | y::Float64 9 | end 10 | 11 | p = Point(2, 5) #> Point(2.0,5.0) 12 | v = Vector2D(3, 2) #> Vector2D(3.0,2.0) 13 | 14 | # Example with sum: 15 | # +(p, v) #> ERROR: `+` has no method matching +(::Point, ::Vector2D) 16 | +(p::Point, q::Point) = Point(p.x + q.x, p.y + q.y) 17 | +(u::Vector2D, v::Vector2D) = Point(u.x + v.x, u.y + v.y) 18 | +(u::Vector2D, p::Point) = Point(u.x + p.x, u.y + p.y) 19 | # +(p, v) ERROR: `+` has no method matching +(::Point, ::Vector2D) 20 | +(p::Point, v::Vector2D) = Point(p.x + v.x, p.y + v.y) 21 | +(p, v) #> Point(5.0,7.0) 22 | 23 | # Example with dot product: 24 | # *(p, v) #> ERROR: `*` has no method matching *(::Point, ::Vector2D) 25 | *(p::Point, q::Point) = p.x * q.x + p.y * q.y 26 | *(u::Vector2D, v::Vector2D) = u.x * v.x + u.y * v.y 27 | *(u::Vector2D, p::Point) = u.x * p.x + u.y * p.y 28 | # *(p, v) #> ERROR: `*` has no method matching *(::Point, ::Vector2D) 29 | *(p::Point, v::Vector2D) = p.x * v.x + p.y * v.y 30 | *(p, v) #> 16.0 31 | 32 | VecOrPoint = Union(Vector2D, Point) 33 | 34 | isa(p, VecOrPoint) #> true 35 | isa(v, VecOrPoint) #> true 36 | 37 | +(u::VecOrPoint, v:: VecOrPoint) = VecOrPoint(u.x + v.x, u.y + v.y) 38 | +(p, v) #> Point(5.0,7.0) 39 | 40 | *(u::VecOrPoint, v:: VecOrPoint) = u.x * v.x + u.y * v.y 41 | *(p, v) #> 16.0 -------------------------------------------------------------------------------- /Module 1/Chapter06/using_module.jl: -------------------------------------------------------------------------------- 1 | require("temperature_converter.jl") 2 | 3 | using TemperatureConverter 4 | 5 | println("$(as_celsius(100, :Celsius))") #> 100 6 | println("$(as_celsius(100, :Kelvin))") #> 373 7 | # println("$(kelvin_to_celsius(0))") #> ERROR: kelvin_to_celsius not defined -------------------------------------------------------------------------------- /Module 1/Chapter07/Old/built_in_macros.jl: -------------------------------------------------------------------------------- 1 | # Testing: 2 | # @assert 1==42 "Shouldn't this be so?" 3 | #> ERROR: assertion failed: Shouldn't this be so? 4 | using Base.Test 5 | # @test 1==3 #> ERROR: test failed: 1 == 3 6 | # @test_approx_eq 1 1.1 7 | #> ERROR: assertion failed: |1 - 1.1| <= 2.220446049250313e-12 8 | @test_approx_eq_eps 1 1.1 0.2 9 | 10 | # Debugging: 11 | arr = [1, 2] #> 2-element Array{Int64,1}: 1 2 12 | @which sort(arr) #> sort(v::AbstractArray{T,1}) at sort.jl:334 13 | 456 * 789 + (@show 2 + 3) #> 2 + 3 => 5 359789 14 | 15 | # Benchmarking: 16 | @time [x^2 for x in 1:1000] #> elapsed time: 3.911e-6 seconds (8064 bytes allocated) # 1000-element Array{Int64,1}: … 17 | @timed [x^2 for x in 1:1000] 18 | #> ([1,4,9,16,25,36,49,64,81,100 … 982081,984064,986049,988036,990025,992016,9940 19 | # 09,996004,998001,1000000],3.911e-6,8064,0.0) 20 | @elapsed [x^2 for x in 1:1000] #> 3.422e-6 21 | @allocated [x^2 for x in 1:1000] #> 8064 22 | # timing: 23 | tic() # start timer 24 | [x^2 for x in 1:1000] 25 | toc() # stop timer and print time: elapsed time: 0.024395069 seconds 26 | # toq() # stop timer and return time 27 | 28 | # starting a task: 29 | a = @async 1 + 2 30 | # Task (done) @0x000000002d70faf0 31 | consume(a) # 3 -------------------------------------------------------------------------------- /Module 1/Chapter07/Old/eval.jl: -------------------------------------------------------------------------------- 1 | exp = Expr(:call, *, 3, 4) #> :((*)(3,4)) 2 | eval(exp) #> 12 3 | 4 | # exp = Expr(:call, *, 3, a) #> ERROR: a not defined 5 | exp = Expr(:call, *, 3, :a) #> :((*)(3,a)) 6 | # eval(exp) #> ERROR: a not defined 7 | a = 4 #> 4 8 | eval(exp) #> 12 9 | 10 | # b #> ERROR: b not defined 11 | exp = :(b = 1) 12 | eval(exp) #> 1 13 | b #> 1 14 | 15 | exp1 = :(a + b) #> :(a + b) 16 | exp2 = :($a + b) #> :(4 + b) 17 | eval(exp1) #> 5 18 | eval(exp2) #> 5 -------------------------------------------------------------------------------- /Module 1/Chapter07/Old/expressions.jl: -------------------------------------------------------------------------------- 1 | typeof(2 + 3) #> Int64 2 | :(2 + 3) #> :(2 + 3) 3 | typeof(:(2 + 3)) #> Expr 4 | exp = :(2 + 3) 5 | names(exp) 6 | #3-element Array{Symbol,1}: 7 | # :head 8 | # :args 9 | # :typ 10 | exp.head #> :call 11 | exp.args #> 3-element Array{Any,1}: :+ 2 3 12 | exp.typ #> Any 13 | 2 + 3 == + (2, 3) #> true 14 | 15 | exp2 = :(2 + a * b - c) 16 | exp2.args #> 3-element Array{Any,1}: :- :(2 + a * b) :c 17 | :(2 + a * b).args #> 3-element Array{Any,1}: :+ 2 :(a * b) 18 | :(a * b).args #> 3-element Array{Any,1}: :* :a :b 19 | 20 | x = 5 #> 5 21 | :x #> :x 22 | 23 | quote 24 | a = 42 25 | b = a^2 26 | a - b 27 | end 28 | # quote # none, line 2: 29 | # a = 42 # line 3: 30 | # b = a^2 # line 4: 31 | # a - b 32 | # end 33 | :(a = 42; b = a^2; a - b) 34 | # returns: 35 | # quote 36 | # a = 42 37 | # begin 38 | # b = a^2 39 | # a - b 40 | # end 41 | # end 42 | 43 | type Expr 44 | head::Symbol 45 | args::Array{Any,1} 46 | typ 47 | end 48 | 49 | dump(:(2 + 2)) 50 | # Expr 51 | # head: Symbol call 52 | # args: Array(Any,(3,)) 53 | # 1: Symbol + 54 | # 2: Int64 2 55 | # 3: Int64 2 56 | # typ: Any 57 | 58 | dump(:(2 + a * b - c)) 59 | # Expr 60 | # head: Symbol call 61 | # args: Array(Any,(3,)) 62 | # 1: Symbol - 63 | # 2: Expr 64 | # head: Symbol call 65 | # args: Array(Any,(3,)) 66 | # 1: Symbol + 67 | # 2: Int64 2 68 | # 3: Expr 69 | # head: Symbol call 70 | # args: Array(Any,(3,)) 71 | # typ: Any 72 | # typ: Any 73 | # 3: Symbol c 74 | # typ: Any 75 | 76 | symbol('\'') #> :' 77 | symbol("'") #> :' -------------------------------------------------------------------------------- /Module 1/Chapter07/Old/reflection.jl: -------------------------------------------------------------------------------- 1 | type Person 2 | name:: String 3 | height::Float64 4 | end 5 | 6 | names(Person) #> 2-element Array{Symbol,1}: :name :height 7 | Person.types #> (String,Float64) 8 | 9 | code_lowered(+, (Int, Int)) 10 | #1-element Array{Any,1}: 11 | # :($(Expr(:lambda, {:x,:y}, {{},{{:x,:Any,0},{:y,:Any,0}},{}}, :(begin # int.jl 12 | #, line 33: 13 | # return box(Int64,add_int(unbox(Int64,x),unbox(Int64,y))) 14 | # end)))) 15 | 16 | code_typed(+, (Int, Int)) 17 | # 1-element Array{Any,1}: 18 | # :($(Expr(:lambda, {:x,:y}, {{},{{:x,Int64,0},{:y,Int64,0}},{}}, :(begin # int. 19 | # jl, line 33: 20 | # return box(Int64,add_int(x::Int64,y::Int64))::Int64 21 | # end::Int64)))) -------------------------------------------------------------------------------- /Module 1/Chapter07/built_in_macros.jl: -------------------------------------------------------------------------------- 1 | # Testing: 2 | # @assert 1==42 "Shouldn't this be so?" 3 | #> ERROR: assertion failed: Shouldn't this be so? 4 | 5 | using Base.Test 6 | # @test 1==3 #> ERROR: test failed: 1 == 3 7 | # @test_approx_eq 1 1.1 8 | #> ERROR: assertion failed: |1 - 1.1| <= 2.220446049250313e-12 9 | @test_approx_eq_eps 1 1.1 0.2 10 | 11 | # Debugging: 12 | arr = [1, 2] #> 2-element Array{Int64,1}: 1 2 13 | @which sort(arr) #> sort(v::AbstractArray{T,1}) at sort.jl:334 14 | 456 * 789 + (@show 2 + 3) #> 2 + 3 => 5 359789 15 | 16 | # Benchmarking: 17 | @time [x^2 for x in 1:1000] #> elapsed time: 3.911e-6 seconds (8064 bytes allocated) # 1000-element Array{Int64,1}: … 18 | @timed [x^2 for x in 1:1000] 19 | #> ([1,4,9,16,25,36,49,64,81,100 … 982081,984064,986049,988036,990025,992016,9940 20 | # 09,996004,998001,1000000],3.911e-6,8064,0.0) 21 | @elapsed [x^2 for x in 1:1000] #> 3.422e-6 22 | @allocated [x^2 for x in 1:1000] #> 8064 23 | # timing: 24 | tic() # start timer 25 | [x^2 for x in 1:1000] 26 | toc() # stop timer and print time: elapsed time: 0.024395069 seconds 27 | # toc() # stop timer and return time 28 | 29 | # starting a task: 30 | a = @async 1 + 2 31 | # Task (done) @0x000000002d70faf0 32 | consume(a) # 3 -------------------------------------------------------------------------------- /Module 1/Chapter07/eval.jl: -------------------------------------------------------------------------------- 1 | e1 = Expr(:call, *, 3, 4) #> :((*)(3,4)) 2 | eval(e1) #> 12 3 | 4 | # e1 = expr(:call, *, 3, a) #> ERROR: a not defined 5 | e2 = Expr(:call, *, 3, :a) #> :((*)(3,a)) 6 | # eval(e2) #> ERROR: a not defined 7 | a = 4 #> 4 8 | eval(e2) #> 12 9 | 10 | # b #> ERROR: b not defined 11 | e3 = :(b = 1) 12 | eval(e3) #> 1 13 | b #> 1 14 | 15 | e4 = :(a + b) #> :(a + b) 16 | e5 = :($a + b) #> :(4 + b) 17 | eval(e4) #> 5 18 | eval(e5) #> 5 -------------------------------------------------------------------------------- /Module 1/Chapter07/expressions.jl: -------------------------------------------------------------------------------- 1 | typeof(2 + 3) #> Int64 2 | :(2 + 3) #> :(2 + 3) 3 | typeof(:(2 + 3)) #> Expr 4 | 5 | quote 6 | a = 42 7 | b = a^2 8 | a - b 9 | end 10 | # quote # none, line 2: 11 | # a = 42 # line 3: 12 | # b = a^2 # line 4: 13 | # a - b 14 | # end 15 | :(a = 42; b = a^2; a - b) 16 | # returns: 17 | # quote 18 | # a = 42 19 | # begin 20 | # b = a^2 21 | # a - b 22 | # end 23 | # end 24 | 25 | e1 = :(2 + 3) 26 | names(e1) 27 | #3-element Array{Symbol,1}: 28 | # :head 29 | # :args 30 | # :typ 31 | e1.head #> :call 32 | e1.args #> 3-element Array{Any,1}: :+ 2 3 33 | e1.typ #> Any 34 | 2 + 3 == + (2, 3) #> true 35 | 36 | e2 = :(2 + a * b - c) 37 | e2.args #> 3-element Array{Any,1}: :- :(2 + a * b) :c 38 | :(2 + a * b).args #> 3-element Array{Any,1}: :+ 2 :(a * b) 39 | :(a * b).args #> 3-element Array{Any,1}: :* :a :b 40 | 41 | x = 5 #> 5 42 | :x #> :x 43 | 44 | type Expr 45 | head::Symbol 46 | args::Array{Any,1} 47 | typ 48 | end 49 | 50 | dump(:(2 + 2)) 51 | # Expr 52 | # head: Symbol call 53 | # args: Array(Any,(3,)) 54 | # 1: Symbol + 55 | # 2: Int64 2 56 | # 3: Int64 2 57 | # typ: Any 58 | 59 | dump(:(2 + a * b - c)) 60 | # Expr 61 | # head: Symbol call 62 | # args: Array(Any,(3,)) 63 | # 1: Symbol - 64 | # 2: Expr 65 | # head: Symbol call 66 | # args: Array(Any,(3,)) 67 | # 1: Symbol + 68 | # 2: Int64 2 69 | # 3: Expr 70 | # head: Symbol call 71 | # args: Array(Any,(3,)) 72 | # typ: Any 73 | # typ: Any 74 | # 3: Symbol c 75 | # typ: Any 76 | 77 | symbol('\'') #> :' 78 | symbol("'") #> :' -------------------------------------------------------------------------------- /Module 1/Chapter07/reflection.jl: -------------------------------------------------------------------------------- 1 | type Person 2 | name:: String 3 | height::Float64 4 | end 5 | 6 | names(Person) #> 2-element Array{Symbol,1}: :name :height 7 | Person.types #> (String,Float64) 8 | 9 | code_lowered(+, (Int, Int)) 10 | #1-element Array{Any,1}: 11 | # :($(Expr(:lambda, {:x,:y}, {{},{{:x,:Any,0},{:y,:Any,0}},{}}, :(begin # int.jl 12 | #, line 33: 13 | # return box(Int64,add_int(unbox(Int64,x),unbox(Int64,y))) 14 | # end)))) 15 | 16 | code_typed(+, (Int, Int)) 17 | # 1-element Array{Any,1}: 18 | # :($(Expr(:lambda, {:x,:y}, {{},{{:x,Int64,0},{:y,Int64,0}},{}}, :(begin # int. 19 | # jl, line 33: 20 | # return box(Int64,add_int(x::Int64,y::Int64))::Int64 21 | # end::Int64)))) -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/dataarrays.jl: -------------------------------------------------------------------------------- 1 | using DataArrays 2 | using DataFrames 3 | dv = @data([7, 3, NA, 5, 42]) 4 | #> 5-element DataArray{Int64,1}: 7 3 NA 5 42 5 | # array(dv) #> ERROR: NAException 6 | # convert(Array, dv) #> ERROR: NAException("Cannot convert DataArray with NA's to desired type") 7 | mean(dv) #> NA 8 | sum(dv) #> NA 9 | dv[5] = NA #> dv now becomes [7, 3, NA, 5, NA] 10 | 11 | # getting rid of NA's: 12 | sum(dropna(dv)) #> 15 13 | repl = -1 14 | sum(array(dv, repl)) #> 13 -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/echoserver.jl: -------------------------------------------------------------------------------- 1 | server = listen(8080) 2 | while true 3 | conn = accept(server) 4 | @async begin 5 | try 6 | while true 7 | line = readline(conn) 8 | println(line) 9 | write(conn,line) 10 | end 11 | catch ex 12 | print("connection ended with error $ex") 13 | end 14 | end # end coroutine block 15 | end -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/example.dat: -------------------------------------------------------------------------------- 1 | this is line 1. 2 | 42; 3.14 3 | this is line 3. -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/example2.dat: -------------------------------------------------------------------------------- 1 | I write myself to a file 2 | even with println! 3 | -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/io.jl: -------------------------------------------------------------------------------- 1 | # on Julia prompt: 2 | # julia> STDIN 3 | # TTY(open, 0 bytes waiting) 4 | # julia> STDOUT 5 | # TTY(open, 0 bytes waiting) 6 | 7 | read(STDIN, Char) 8 | write(STDOUT, "Julia") #> Julia5 9 | readbytes(STDIN,3) 10 | readline(STDIN) 11 | # input: # Julia 12 | # output: # "Julia\r\n" (Windows) - "Julia\n" (Linux) 13 | 14 | names(IOStream) 15 | # 4-element Array{Symbol,1}: 16 | # :handle 17 | # :ios 18 | # :name 19 | # :mark 20 | 21 | IOStream.types 22 | # (Ptr{None},Array{Uint8,1},String,Int64) 23 | 24 | # stream can be STDIN or any other input stream: 25 | for line in eachline(stream) 26 | print("Found $line") 27 | end 28 | 29 | while !eof(stream) 30 | x = read(stream, Char) 31 | println("Found: $x") 32 | end 33 | 34 | # files: 35 | # reading: 36 | fname = "example.dat" 37 | f1 = open(fname) 38 | # IOStream() 39 | 40 | data = readlines(f1) 41 | # 3-element Array{Union(ASCIIString,UTF8String),1}: 42 | # "this is line 1.\r\n" 43 | # "this is line 2.\r\n" 44 | # "this is line 3." 45 | 46 | for line in data 47 | println(line) 48 | # process line 49 | end 50 | close(f1) 51 | 52 | open(fname) do file 53 | process(file) 54 | end 55 | 56 | function process() 57 | # ... 58 | end 59 | 60 | open(fname) do file 61 | for line in eachline(file) 62 | print(line) # process line 63 | end 64 | end 65 | 66 | # writing: 67 | fname = "example2.dat" 68 | f2 = open(fname, "w") 69 | write(f2, "I write myself to a file\n") #> 24 70 | println(f2, "even with println!") 71 | close(f2) 72 | 73 | # looping over all files in a folder: 74 | for file in readdir() 75 | # process file 76 | end -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/odbc.jl: -------------------------------------------------------------------------------- 1 | using ODBC 2 | ODBC.connect("pubsODBC") 3 | # ODBC Connection Object 4 | # ---------------------- 5 | # Connection Data Source: pubsODBC 6 | # pubsODBC Connection Number: 1 7 | # Contains resultset? No 8 | results = query("select * from titles") 9 | # elapsed time: 0.189238158 seconds 10 | # 18x10 DataFrame 11 | # | Row | title_id | 12 | # |-----|----------| 13 | # | 1 | "BU1032" | 14 | # | 2 | "BU1111" | 15 | # | 3 | "BU2075" | 16 | # | 4 | "BU7832" | 17 | # | 5 | "MC2222" | 18 | # | 6 | "MC3021" | 19 | # ⋮ 20 | # | 12 | "PS2091" | 21 | # | 13 | "PS2106" | 22 | # | 14 | "PS3333" | 23 | # | 15 | "PS7777" | 24 | # | 16 | "TC3218" | 25 | # | 17 | "TC4203" | 26 | # | 18 | "TC7777" | 27 | 28 | # | Row | title | 29 | # |-----|-------------------------------------------------------------------| 30 | # | 1 | "The Busy Executive's Database Guide" | 31 | # | 2 | "Cooking with Computers: Surreptitious Balance Sheets" | 32 | # | 3 | "You Can Combat Computer Stress!" | 33 | # | 4 | "Straight Talk About Computers" | 34 | # | 5 | "Silicon Valley Gastronomic Treats" | 35 | # | 6 | "The Gourmet Microwave" | 36 | # ⋮ 37 | # Row | _type | pub_id | price | advance | royalty | ytd_sales | 38 | # -----|----------------|--------|-------|---------|---------|-----------| 39 | # 1 | "business " | "1389" | 19.99 | 5000.0 | 10 | 4095 | 40 | # 2 | "business " | "1389" | 11.95 | 5000.0 | 10 | 3876 | 41 | # 3 | "business " | "0736" | 2.99 | 10125.0 | 24 | 18722 | 42 | # 4 | "business " | "1389" | 19.99 | 5000.0 | 10 | 4095 | 43 | # 5 | "mod_cook " | "0877" | 19.99 | 0.0 | 12 | 2032 | 44 | # 6 | "mod_cook " | "0877" | 2.99 | 15000.0 | 24 | 22246 | 45 | # fname = "books.dat" 46 | # query("select * from titles", file=fname, delim = '\t') 47 | 48 | # updates: 49 | updsql = "update titles set type = 'psychology' where title_id='BU1032'" 50 | query(updsql) 51 | 52 | listdrivers() 53 | listdsns() -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/parallel.jl: -------------------------------------------------------------------------------- 1 | # julia -p n # starts n processes on the local machine 2 | # julia -p 8 # starts REPL with 8 workers 3 | workers() 4 | # 8-element Array{Int64,1}: 5 | # 2 6 | # 3 7 | # 4 8 | # 5 9 | # ⋮ 10 | # 8 11 | # 9 12 | 13 | # iterate over workers: 14 | for pid in workers() 15 | # do something with pid 16 | end 17 | myid() # 1 18 | addprocs(5) 19 | # 5-element Array{Any,1}: 20 | # 10 21 | # 11 22 | # 12 23 | # 13 24 | # 14 25 | nprocs() # 14 26 | rmprocs(3) # worker with id 3 is removed 27 | 28 | # cluster of computers: 29 | # julia --machinefile machines driver.jl 30 | # Run processes specified in driver.jl on hosts listed in machines 31 | 32 | # primitive operations with processes: 33 | r1 = remotecall(2, x -> x^2, 1000) #> RemoteRef(2,1,20) 34 | fetch(r1) #> 1000000 35 | 36 | remotecall_fetch(5, sin, 2pi) # -2.4492935982947064e-16 37 | 38 | r2 = @spawnat 4 sqrt(2) # lets worker 4 calculate sqrt(2) 39 | fetch(r2) #> 1.4142135623730951 40 | r = [@spawnat i sqrt(5) for i=1:length(workers())] 41 | # 6-element Array{Any,1}: 42 | # RemoteRef(1,1,8) 43 | # RemoteRef(2,1,9) 44 | # RemoteRef(3,1,10) 45 | # RemoteRef(4,1,11) 46 | # RemoteRef(5,1,12) 47 | # RemoteRef(6,1,13) 48 | r3 = @spawn sqrt(5) #> RemoteRef(5,1,26) 49 | fetch(r3) #> 2.23606797749979 50 | 51 | # using @everywhere to make functions available to all workers: 52 | @everywhere w = 8 53 | @everywhere println(myid()) # 1 54 | # From worker 2: 2 55 | # From worker 3: 3 56 | # From worker 4: 4 57 | # From worker 7: 7 58 | # From worker 5: 5 59 | # From worker 6: 6 60 | # From worker 8: 8 61 | # From worker 9: 9 62 | 63 | @everywhere include("defs.jl") 64 | @everywhere function fib(n) 65 | if (n < 2) then 66 | return n 67 | else return fib(n-1) + fib(n-2) 68 | end 69 | end 70 | require("functions") 71 | 72 | # broadcast data to all workers: 73 | for pid in workers() 74 | remotecall(pid, x -> (global data; data = x; nothing), data) 75 | end -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/parallel_loops_maps.jl: -------------------------------------------------------------------------------- 1 | # parallel loops: 2 | function buffon(n) 3 | hit = 0 4 | for i = 1:n 5 | mp = rand() 6 | phi = (rand() * pi) - pi / 2 7 | xright = mp + cos(phi)/2 8 | xleft = mp - cos(phi)/2 9 | # if xright >= 1 || xleft <= 0 10 | # hit += 1 11 | # end 12 | p = (xright >= 1 || xleft <= 0) ? 1 : 0 13 | hit += p 14 | end 15 | miss = n - hit 16 | piapprox = n / hit * 2 17 | end 18 | 19 | @time buffon(100000) 20 | # elapsed time: 0.005487779 seconds (96 bytes allocated) 21 | # 3.1467321186947355 22 | @time buffon(100000000) 23 | # elapsed time: 5.362294859 seconds (96 bytes allocated) 24 | # 3.1418351308191026 25 | 26 | function buffon_par(n) 27 | hit = @parallel (+) for i = 1:n 28 | mp = rand() 29 | phi = (rand() * pi) - pi / 2 30 | xright = mp + cos(phi)/2 31 | xleft = mp - cos(phi)/2 32 | (xright >= 1 || xleft <= 0) ? 1 : 0 33 | end 34 | miss = n - hit 35 | piapprox = n / hit * 2 36 | end 37 | @time buffon_par(100000) 38 | # elapsed time: 0.005903334 seconds (296920 bytes allocated) 39 | # 3.136762860727729 40 | @time buffon_par(100000000) 41 | # elapsed time: 0.849702686 seconds (300888 bytes allocated) 42 | # 3.141665751394711 43 | 44 | # arr is not correctly initialized: 45 | arr = zeros(100000) 46 | @parallel for i=1:100000 47 | arr[i] = i 48 | end 49 | #> arr only contains zeros! 50 | 51 | # parallel maps: 52 | function rank_marray() 53 | marr = [rand(1000,1000) for i=1:10] 54 | for arr in marr 55 | println(rank(arr)) 56 | end 57 | end 58 | 59 | @time rank_marray() 60 | # 1000 61 | # 1000 62 | # 1000 63 | # 1000 64 | # 1000 65 | # 1000 66 | # 1000 67 | # 1000 68 | # 1000 69 | # 1000 70 | # elapsed time: 4.351479797 seconds (166177728 bytes allocated, 1.43% gc time) 71 | 72 | function prank_marray() 73 | marr = [rand(1000,1000) for i=1:10] 74 | println(pmap(rank, marr)) 75 | end 76 | @time prank_marray() 77 | # {1000,1000,1000,1000,1000,1000,1000,1000,1000,1000} 78 | # elapsed time: 2.785466798 seconds (163955848 bytes allocated, 1.96% gc time) 79 | -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/savetuple.csv: -------------------------------------------------------------------------------- 1 | ColName A, ColName B, ColName C 2 | 0.5408481665516365,0.6693228720618509,0.05504148785408458 3 | 0.6324189848140833,0.6804137594545172,0.15783040649225932 4 | 0.31934448720249287,0.19080324109126678,0.9765157256697172 5 | 0.8500465746560666,0.2796101070428927,0.6965834811691298 6 | 0.5467798398363413,0.9249043776795531,0.3729546576537428 7 | 0.31265636271755115,0.8154212267126151,0.8564363651958093 8 | 0.09577516608781655,0.012448851421264173,0.9739111798627225 9 | 0.6217219046583027,0.6701950692829548,0.64899223575104 10 | 0.6097405923114552,0.7692071529314373,0.4113891787827846 11 | 0.25247932179208843,0.35737849136162625,0.31334010301139115 12 | -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/tcpserver.jl: -------------------------------------------------------------------------------- 1 | server = listen(8080) 2 | # TcpServer(listening) 3 | conn = accept(server) 4 | # on the client: $ nc localhost 8080 5 | # TcpSocket(connected,0 bytes waiting) 6 | line = readline(conn) 7 | # hello Julia server! 8 | # "hello Julia server!\n" 9 | write(conn, "Hello back from server to client, what can I do for you?") 10 | 56 11 | close(conn) -------------------------------------------------------------------------------- /Module 1/Chapter08/Old/tuple_csv.jl: -------------------------------------------------------------------------------- 1 | fname = "savetuple.csv" 2 | csvfile = open(fname,"w") 3 | # writing headers: 4 | write(csvfile, "ColName A, ColName B, ColName C\n") 5 | for i = 1:10 6 | tup(i) = tuple(rand(Float64,3)...) 7 | write(csvfile, join(tup(i),","), "\n") 8 | end 9 | close(csvfile) -------------------------------------------------------------------------------- /Module 1/Chapter08/dataarrays.jl: -------------------------------------------------------------------------------- 1 | using DataArrays 2 | dv = @data([7, 3, NA, 5, 42]) 3 | #> 5-element DataArray{Int64,1}: 7 3 NA 5 42 4 | # array(dv) #> ERROR: NAException 5 | # convert(Array, dv) #> ERROR: NAException("Cannot convert DataArray with NA's to desired type") 6 | mean(dv) #> NA 7 | sum(dv) #> NA 8 | dv[5] = NA #> dv now becomes [7, 3, NA, 5, NA] 9 | 10 | # getting rid of NA's: 11 | sum(dropna(dv)) #> 15 12 | repl = -1 13 | sum(array(dv, repl)) #> 13 -------------------------------------------------------------------------------- /Module 1/Chapter08/defs.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter08/defs.jl -------------------------------------------------------------------------------- /Module 1/Chapter08/echoserver.jl: -------------------------------------------------------------------------------- 1 | # start the netcat (nc) tool at the prompt to make a connection with the Julia server on port 8080: 2 | # nc localhost 8080 3 | server = listen(8080) 4 | while true 5 | conn = accept(server) 6 | @async begin 7 | try 8 | while true 9 | line = readline(conn) 10 | println(line) 11 | write(conn,line) 12 | end 13 | catch ex 14 | print("connection ended with error $ex") 15 | end 16 | end # end coroutine block 17 | end -------------------------------------------------------------------------------- /Module 1/Chapter08/example.dat: -------------------------------------------------------------------------------- 1 | this is line 1. 2 | 42; 3.14 3 | this is line 3. -------------------------------------------------------------------------------- /Module 1/Chapter08/example2.dat: -------------------------------------------------------------------------------- 1 | I write myself to a file 2 | even with println! 3 | -------------------------------------------------------------------------------- /Module 1/Chapter08/functions.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter08/functions.jl -------------------------------------------------------------------------------- /Module 1/Chapter08/io.jl: -------------------------------------------------------------------------------- 1 | # this script does not run as a whole 2 | # (they code snippets are demonstrative, and should be used on their own, and/or in the REPL 3 | # on Julia prompt: 4 | # julia> STDIN 5 | # TTY(open, 0 bytes waiting) 6 | # julia> STDOUT 7 | # TTY(open, 0 bytes waiting) 8 | 9 | # read(STDIN, Char) 10 | write(STDOUT, "Julia") #> Julia5 11 | # readbytes(STDIN,3) 12 | # readline(STDIN) 13 | # input: # Julia 14 | # output: # "Julia\r\n" (Windows) - "Julia\n" (Linux) 15 | 16 | # stream can be STDIN or any other input stream: 17 | stream = STDIN 18 | for line in eachline(stream) 19 | print("Found $line") 20 | end 21 | 22 | while !eof(stream) 23 | x = read(stream, Char) 24 | println("Found: $x") 25 | end 26 | 27 | 28 | function process(item) 29 | # do the processing 30 | end 31 | 32 | # files: 33 | names(IOStream) 34 | # 4-element Array{Symbol,1}: 35 | # :handle 36 | # :ios 37 | # :name 38 | # :mark 39 | 40 | IOStream.types 41 | # (Ptr{None},Array{Uint8,1},String,Int64) 42 | 43 | # reading: 44 | fname = "example.dat" 45 | f1 = open(fname) 46 | # IOStream() 47 | 48 | data = readlines(f1) 49 | # 3-element Array{Union(ASCIIString,UTF8String),1}: 50 | # "this is line 1.\r\n" 51 | # "this is line 2.\r\n" 52 | # "this is line 3." 53 | 54 | for line in data 55 | println(line) 56 | process(line) 57 | end 58 | close(f1) 59 | 60 | open(fname) do file 61 | process(file) 62 | end 63 | 64 | open(fname) do file 65 | for line in eachline(file) 66 | print(line) 67 | process(line) 68 | end 69 | end 70 | 71 | # writing: 72 | fname = "example2.dat" 73 | f2 = open(fname, "w") 74 | write(f2, "I write myself to a file\n") #> 24 75 | println(f2, "even with println!") 76 | close(f2) 77 | 78 | # looping over all files in a folder: 79 | for file in readdir() 80 | process(file) 81 | end -------------------------------------------------------------------------------- /Module 1/Chapter08/odbc.jl: -------------------------------------------------------------------------------- 1 | Pkg.add("ODBC") 2 | Pkg.add("Dates") 3 | using ODBC 4 | ODBC.connect("pubsODBC") 5 | # ODBC Connection Object 6 | # ---------------------- 7 | # Connection Data Source: pubsODBC 8 | # pubsODBC Connection Number: 1 9 | # Contains resultset? No 10 | results = query("select * from titles") 11 | # elapsed time: 0.189238158 seconds 12 | # 18x10 DataFrame 13 | # | Row | title_id | 14 | # |-----|----------| 15 | # | 1 | "BU1032" | 16 | # | 2 | "BU1111" | 17 | # | 3 | "BU2075" | 18 | # | 4 | "BU7832" | 19 | # | 5 | "MC2222" | 20 | # | 6 | "MC3021" | 21 | # ⋮ 22 | # | 12 | "PS2091" | 23 | # | 13 | "PS2106" | 24 | # | 14 | "PS3333" | 25 | # | 15 | "PS7777" | 26 | # | 16 | "TC3218" | 27 | # | 17 | "TC4203" | 28 | # | 18 | "TC7777" | 29 | 30 | # | Row | title | 31 | # |-----|-------------------------------------------------------------------| 32 | # | 1 | "The Busy Executive's Database Guide" | 33 | # | 2 | "Cooking with Computers: Surreptitious Balance Sheets" | 34 | # | 3 | "You Can Combat Computer Stress!" | 35 | # | 4 | "Straight Talk About Computers" | 36 | # | 5 | "Silicon Valley Gastronomic Treats" | 37 | # | 6 | "The Gourmet Microwave" | 38 | # ⋮ 39 | # Row | _type | pub_id | price | advance | royalty | ytd_sales | 40 | # -----|----------------|--------|-------|---------|---------|-----------| 41 | # 1 | "business " | "1389" | 19.99 | 5000.0 | 10 | 4095 | 42 | # 2 | "business " | "1389" | 11.95 | 5000.0 | 10 | 3876 | 43 | # 3 | "business " | "0736" | 2.99 | 10125.0 | 24 | 18722 | 44 | # 4 | "business " | "1389" | 19.99 | 5000.0 | 10 | 4095 | 45 | # 5 | "mod_cook " | "0877" | 19.99 | 0.0 | 12 | 2032 | 46 | # 6 | "mod_cook " | "0877" | 2.99 | 15000.0 | 24 | 22246 | 47 | # fname = "books.dat" 48 | # query("select * from titles", file=fname, delim = '\t') 49 | 50 | # updates: 51 | updsql = "update titles set type = 'psychology' where title_id='BU1032'" 52 | query(updsql) 53 | 54 | listdrivers() 55 | listdsns() -------------------------------------------------------------------------------- /Module 1/Chapter08/parallel.jl: -------------------------------------------------------------------------------- 1 | # start the following on the command line: 2 | # julia -p n # starts n processes on the local machine 3 | # julia -p 8 # starts REPL with 8 workers 4 | workers() 5 | # 8-element Array{Int64,1}: 6 | # 2 7 | # 3 8 | # 4 9 | # 5 10 | # ⋮ 11 | # 8 12 | # 9 13 | 14 | # iterate over workers: 15 | for pid in workers() 16 | # do something with pid 17 | end 18 | myid() # 1 19 | addprocs(5) 20 | # 5-element Array{Any,1}: 21 | # 10 22 | # 11 23 | # 12 24 | # 13 25 | # 14 26 | nprocs() # 14 27 | rmprocs(3) # worker with id 3 is removed 28 | 29 | # cluster of computers: 30 | # julia --machinefile machines driver.jl 31 | # Run processes specified in driver.jl on hosts listed in machines 32 | 33 | # primitive operations with processes: 34 | r1 = remotecall(2, x -> x^2, 1000) #> RemoteRef(2,1,20) 35 | fetch(r1) #> 1000000 36 | 37 | remotecall_fetch(5, sin, 2pi) # -2.4492935982947064e-16 38 | 39 | r2 = @spawnat 4 sqrt(2) # lets worker 4 calculate sqrt(2) 40 | fetch(r2) #> 1.4142135623730951 41 | r = [@spawnat w sqrt(5) for w in workers()] 42 | # or in a freshly started REPL: 43 | # r = [@spawnat i sqrt(5) for i=1:length(workers())] 44 | # 6-element Array{Any,1}: 45 | # RemoteRef(1,1,8) 46 | # RemoteRef(2,1,9) 47 | # RemoteRef(3,1,10) 48 | # RemoteRef(4,1,11) 49 | # RemoteRef(5,1,12) 50 | # RemoteRef(6,1,13) 51 | r3 = @spawn sqrt(5) #> RemoteRef(5,1,26) 52 | fetch(r3) #> 2.23606797749979 53 | 54 | # using @everywhere to make functions available to all workers: 55 | @everywhere w = 8 56 | @everywhere println(myid()) # 1 57 | # From worker 2: 2 58 | # From worker 3: 3 59 | # From worker 4: 4 60 | # From worker 7: 7 61 | # From worker 5: 5 62 | # From worker 6: 6 63 | # From worker 8: 8 64 | # From worker 9: 9 65 | 66 | @everywhere include("defs.jl") 67 | @everywhere function fib(n) 68 | if (n < 2) then 69 | return n 70 | else return fib(n-1) + fib(n-2) 71 | end 72 | end 73 | require("functions") 74 | 75 | # broadcast data to all workers: 76 | d = "Julia" 77 | for pid in workers() 78 | remotecall(pid, x -> (global d; d = x; nothing), d) 79 | end 80 | #= Output: 81 | 1 From worker 2: 2 82 | 83 | From worker 4: 4 84 | From worker 5: 5 85 | From worker 6: 6 86 | =# -------------------------------------------------------------------------------- /Module 1/Chapter08/savetuple.csv: -------------------------------------------------------------------------------- 1 | ColName A, ColName B, ColName C 2 | 0.5941345068695774,0.9223945973348202,0.9367321767661367 3 | 0.2624912933455108,0.8856823903004332,0.5438317267731885 4 | 0.355251654559682,0.5856256276442424,0.3755947034111027 5 | 0.9313953766773553,0.8181974242829888,0.6975620173895367 6 | 0.2888323259306014,0.36233895532266236,0.027062443498464317 7 | 0.7952668182451192,0.8456431743436466,0.6945927790008635 8 | 0.16756279194292212,0.2605613472518933,0.8861101613256326 9 | 0.490108967450557,0.11314017284031319,0.27718683819498513 10 | 0.9014522160061771,0.015950933613208207,0.7234271493834372 11 | 0.32210414767612683,0.7719357435861844,0.5700676571422016 12 | -------------------------------------------------------------------------------- /Module 1/Chapter08/tcpserver.jl: -------------------------------------------------------------------------------- 1 | server = listen(8080) 2 | # TcpServer(listening) 3 | conn = accept(server) 4 | # on the client: $ nc localhost 8080 5 | # TcpSocket(connected,0 bytes waiting) 6 | line = readline(conn) 7 | # hello Julia server! 8 | # "hello Julia server!\n" 9 | write(conn, "Hello back from server to client, what can I do for you?") 10 | 56 11 | close(conn) -------------------------------------------------------------------------------- /Module 1/Chapter08/tuple_csv.jl: -------------------------------------------------------------------------------- 1 | fname = "savetuple.csv" 2 | csvfile = open(fname,"w") 3 | # writing headers: 4 | write(csvfile, "ColName A, ColName B, ColName C\n") 5 | for i = 1:10 6 | tup(i) = tuple(rand(Float64,3)...) 7 | write(csvfile, join(tup(i),","), "\n") 8 | end 9 | close(csvfile) -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/array_product_benchmark.jl: -------------------------------------------------------------------------------- 1 | x = randn(10000000) 2 | y = randn(10000000) 3 | 4 | function inner(x, y) 5 | result = 0.0 6 | for i=1:length(x) 7 | result += x[i] * y[i] 8 | end 9 | result 10 | end 11 | 12 | # gc_disable() 13 | # tic() 14 | @time for i=1:50 result = sum(x .* y); end 15 | # timing = toc(); 16 | # println("Array operations took ", (timing / 50) * 1000, " ms") 17 | # with 1 processor: Array operations took 89.43973046 ms - avg: 90 ms 18 | # with 9 processors: elapsed time: 5.358992903 seconds (4000026400 bytes allocated, 34.95% gc time) 19 | 20 | @time for i=1:50 result = inner(x, y) end 21 | # elapsed time: 1.126870943 seconds (800 bytes allocated) 22 | 23 | x = randn(1, 10000000) 24 | y = randn(10000000, 1) 25 | #tic() 26 | @time for i=1:50 result = x * y end 27 | # elapsed time: 2.401834172 seconds (4800 bytes allocated) 28 | #timing = toc(); 29 | #println("BLAS took ", (timing / 50) * 1000, "ms") 30 | -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/callc.jl: -------------------------------------------------------------------------------- 1 | # calling a function in a shared library: 2 | lang = ccall( (:getenv, "libc"),Ptr{Uint8}, (Ptr{Uint8},), "LANGUAGE") 3 | bytestring(lang) #> "en_US" 4 | 5 | # test existence of library: 6 | find_library(["libc"]) #> "libc" -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/file1.txt: -------------------------------------------------------------------------------- 1 | This a a test for try / catch / finally -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/performance.jl: -------------------------------------------------------------------------------- 1 | # TIPS: 2 | # 1 3 | const DEFAULT = 42 4 | 5 | global x 6 | y = f(x::Int + 1) 7 | 8 | # 9 9 | function with_keyword(x; name::String = "Smith") 10 | # ... 11 | end 12 | 13 | # 16 14 | type Person 15 | name::String 16 | height::Float64 17 | weight::Float64 18 | end 19 | # instead of: 20 | type Person 21 | name 22 | height 23 | weight 24 | end 25 | 26 | # 18 27 | # Use 28 | write(file, a, " ", b) 29 | # instead of: 30 | write(file, "$a $b") 31 | 32 | # TOOLS: 33 | # @time 34 | 35 | # linter: 36 | Pkg.add("Lint") 37 | using Lint 38 | lintfile("performance.jl") 39 | # 40 | # typechecker: 41 | Pkg.add("TypeCheck") 42 | using TypeCheck 43 | foo1(x::Int) = isprime(x) ? x: false 44 | checkreturntypes(foo1) #> foo1(Int64)::Union(Bool,Int64) -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/shell.jl: -------------------------------------------------------------------------------- 1 | pwd() 2 | # cd("d:\\test\\week1") 3 | # shell mode: 4 | # ; ls 5 | # ; mkdir folder 6 | # ; cd folder 7 | 8 | cmd = `echo Julia is smart` 9 | typeof(cmd) #> Cmd (constructor with 1 method) 10 | run(cmd) #> Julia is smart 11 | run(`date`) #> Sun Oct 12 09:44:50 GMT 2014 12 | cmd = `cat file1.txt` 13 | run(cmd) #> text from file1.txt: This a a test for try / catch / finally 14 | success(cmd) #> true 15 | # interpolation: 16 | file = "file1.txt" 17 | cmd = `cat $file` 18 | run(cmd) #> text from file1.txt: This a a test for try / catch / finally 19 | cmd = `ls *.*` 20 | run(cmd) #> returns: file1.txt shell.jl test.txt 21 | # pipelining: 22 | run(`cat $file` |> "test.txt") #> text from file1.txt is written into test.txt 23 | run("test.txt" |> `cat`) 24 | run(`echo $("\nhi\nJulia")` |> `cat` |> `grep -n J`) #> 3:Julia 25 | run(`cat "tosort.txt"` |> `sort`) # returns A B C 26 | 27 | println() 28 | println("Output grep command:") 29 | run(`grep is $(readdir())`) # returns where "is" is found in text files in current dir 30 | println() 31 | 32 | # reading the output of the command: 33 | a = readall(`cat "tosort.txt"` |> `sort`) 34 | #> a has value "A\r\nB\r\nC\n" 35 | 36 | run(`cat "file1.txt"` & `cat "tosort.txt"`) 37 | # B 38 | # A 39 | # CThis a a test for try / catch / finally 40 | 41 | # platform variations: 42 | fun1 = () 43 | fun2 = () 44 | @windows ? fun1 : fun2 45 | -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/test.txt: -------------------------------------------------------------------------------- 1 | This a a test for try / catch / finally -------------------------------------------------------------------------------- /Module 1/Chapter09/Old/tosort.txt: -------------------------------------------------------------------------------- 1 | B 2 | A 3 | C -------------------------------------------------------------------------------- /Module 1/Chapter09/array_product_benchmark.jl: -------------------------------------------------------------------------------- 1 | # The following benchmarks demonstrate 2 | # that devectorising code can lead to substantial speed improvement 3 | x = randn(10000000) 4 | y = randn(10000000) 5 | 6 | function inner(x, y) 7 | result = 0.0 8 | for i=1:length(x) 9 | result += x[i] * y[i] 10 | end 11 | result 12 | end 13 | 14 | # gc_disable() 15 | # tic() 16 | @time for i=1:50 result = sum(x .* y); end 17 | # timing = toc(); 18 | # println("Array operations took ", (timing / 50) * 1000, " ms") 19 | # with 1 processor: Array operations took 89.43973046 ms - avg: 90 ms 20 | # with 9 processors: elapsed time: 5.358992903 seconds (4000026400 bytes allocated, 34.95% gc time) 21 | 22 | @time for i=1:50 result = inner(x, y) end 23 | # elapsed time: 1.126870943 seconds (800 bytes allocated) 24 | 25 | x = randn(1, 10000000) 26 | y = randn(10000000, 1) 27 | #tic() 28 | @time for i=1:50 result = x * y end 29 | # elapsed time: 2.401834172 seconds (4800 bytes allocated) 30 | #timing = toc(); 31 | #println("BLAS took ", (timing / 50) * 1000, "ms") -------------------------------------------------------------------------------- /Module 1/Chapter09/callc.jl: -------------------------------------------------------------------------------- 1 | # calling a function in a shared library: 2 | lang = ccall( (:getenv, "libc"),Ptr{Uint8}, (Ptr{Uint8},), "LANGUAGE") 3 | # ok on Linux 4 | # on Windows: ERROR: error compiling anonymous: could not load module libc: 5 | # The specified module could not be found. 6 | bytestring(lang) #> "en_US" 7 | 8 | # test existence of library: 9 | find_library(["libc"]) #> "libc" -------------------------------------------------------------------------------- /Module 1/Chapter09/file1.txt: -------------------------------------------------------------------------------- 1 | This a a test for try / catch / finally -------------------------------------------------------------------------------- /Module 1/Chapter09/file2.txt: -------------------------------------------------------------------------------- 1 | Julia RustJulia Rust -------------------------------------------------------------------------------- /Module 1/Chapter09/performance.jl: -------------------------------------------------------------------------------- 1 | # TIPS: 2 | # 1 3 | const DEFAULT = 42 4 | 5 | global x = 42 6 | function f(args) 7 | #function body 8 | end 9 | y = f(x::Int + 1) 10 | 11 | # 9 12 | function with_keyword(x; name::String = "Smith") 13 | # ... 14 | end 15 | 16 | # 16 17 | type Person 18 | name::String 19 | height::Float64 20 | weight::Float64 21 | end 22 | # instead of: 23 | # type Person 24 | # name 25 | # height 26 | # weight 27 | # end 28 | 29 | # 18 30 | # Use 31 | file = open("file2.txt", "w") 32 | a = "Julia" 33 | b = "Rust" 34 | write(file, a, " ", b) 35 | # instead of: 36 | write(file, "$a $b") 37 | 38 | # TOOLS: 39 | # @time 40 | 41 | # linter: 42 | Pkg.add("Lint") 43 | using Lint 44 | lintfile("performance.jl") 45 | # 46 | # typechecker: 47 | Pkg.add("TypeCheck") 48 | using TypeCheck 49 | foo1(x::Int) = isprime(x) ? x: false 50 | checkreturntypes(foo1) #> foo1(Int64)::Union(Bool,Int64) -------------------------------------------------------------------------------- /Module 1/Chapter09/shell.jl: -------------------------------------------------------------------------------- 1 | pwd() 2 | # cd("d:\\test\\week1") 3 | # shell mode: 4 | # ; ls 5 | # ; mkdir folder 6 | # ; cd folder 7 | 8 | cmd = `echo Julia is smart` 9 | typeof(cmd) #> Cmd (constructor with 1 method) 10 | run(cmd) #> Julia is smart 11 | run(`date`) #> Sun Oct 12 09:44:50 GMT 2014 12 | cmd = `cat file1.txt` 13 | run(cmd) #> text from file1.txt: This a a test for try / catch / finally 14 | success(cmd) #> true 15 | 16 | # interpolation: 17 | file = "file1.txt" 18 | cmd = `cat $file` 19 | run(cmd) #> text from file1.txt: This a a test for try / catch / finally 20 | # cmd = `ls *.*` # works only on Windows! not in general 21 | # https://groups.google.com/forum/#!topic/julia-users/hzBeluKU7P0 22 | # run(cmd) #> returns: file1.txt shell.jl test.txt 23 | # pipelining: 24 | run(`cat $file` |> "test.txt") #> text from file1.txt is written into test.txt 25 | run("test.txt" |> `cat`) 26 | run(`echo $("\nhi\nJulia")` |> `cat` |> `grep -n J`) #> 3:Julia 27 | run(`cat "tosort.txt"` |> `sort`) # returns A B C 28 | 29 | println() 30 | println("Output grep command:") 31 | # run(`grep is $(readdir())`) # returns where "is" is found in text files in current dir 32 | #= 33 | array_product_benchmark.jl:# gc_disable() 34 | callc.jl:# test existence of library: 35 | file1.txt:This a a test for try / catch / finally 36 | performance.jl:foo1(x::Int) = isprime(x) ? x: false 37 | shell.jl:cmd = `echo Julia is smart` 38 | shell.jl:run(cmd) #> Julia is smart 39 | shell.jl:run(cmd) #> text from file1.txt: This a a test for try / catch / finally 40 | 41 | shell.jl:run(cmd) #> text from file1.txt: This a a test for try / catch / finally 42 | 43 | shell.jl:run(`cat $file` |> "test.txt") #> text from file1.txt is written into te 44 | st.txt 45 | shell.jl:run(`grep is $(readdir())`) # returns where "is" is found in text files 46 | in current dir 47 | shell.jl:# CThis a a test for try / catch / finally 48 | test.txt:This a a test for try / catch / finally 49 | =# 50 | println() 51 | 52 | # reading the output of the command: 53 | a = readall(`cat "tosort.txt"` |> `sort`) 54 | #> a has value "A\r\nB\r\nC\n" 55 | 56 | run(`cat "file1.txt"` & `cat "tosort.txt"`) 57 | # B 58 | # A 59 | # CThis a a test for try / catch / finally 60 | 61 | # platform variations: 62 | fun1 = () 63 | fun2 = () 64 | @windows ? fun1 : fun2 -------------------------------------------------------------------------------- /Module 1/Chapter09/test.txt: -------------------------------------------------------------------------------- 1 | This a a test for try / catch / finally -------------------------------------------------------------------------------- /Module 1/Chapter09/tosort.txt: -------------------------------------------------------------------------------- 1 | B 2 | A 3 | C -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/gadfly.jl: -------------------------------------------------------------------------------- 1 | using Gadfly 2 | draw(SVG("gadfly.svg",6inch,3inch), plot([x -> x^2],0, 25)) 3 | pl = plot([x -> cos(x)/x], 5, 25) 4 | draw(PNG("gadfly.png", 300, 100), pl) -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/gadfly.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter10/Old/gadfly.png -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/gadfly.svg: -------------------------------------------------------------------------------- 1 | 2 | 12 | -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/medical.csv: -------------------------------------------------------------------------------- 1 | IX,Sex,Age,sBP,dBP,Drink,BMI 2 | 0,1,39,106,70,0,26.97 3 | 1,2,46,121,81,0,28.73 4 | 2,1,48,127.5,80,1,25.34 5 | 3,2,61,150,95,1,28.58 6 | 4,2,46,130,84,1,23.1 7 | 5,2,43,180,110,0,30.3 8 | 6,2,63,138,71,0,33.11 9 | 7,2,45,100,71,1,21.68 10 | 8,1,52,141.5,89,0,26.36 11 | 9,1,43,162,107,1,23.61 12 | 10,2,50,133,76,0,22.91 13 | 11,2,43,131,88,0,27.64 14 | 12,1,46,142,94,1,26.31 15 | 13,2,41,124,88,0,31.31 16 | 14,2,39,114,64,1,22.35 17 | 15,2,38,140,90,1,21.35 18 | 16,1,48,138,90,1,22.37 19 | 17,2,46,112,78,1,23.38 20 | 18,2,38,122,84.5,1,23.24 21 | 19,1,41,139,88,0,26.88 22 | 20,2,42,108,70.5,1,21.59 23 | 21,2,43,123.5,77.5,0,29.89 24 | 22,2,52,148,78,0,34.17 25 | 23,2,52,132,82,1,25.11 26 | 24,1,44,137.5,90,1,21.96 27 | 25,1,47,102,68,1,24.18 28 | 26,2,60,110,72.5,0,26.59 29 | 27,1,35,132,91,1,26.09 30 | 28,2,61,182,121,0,32.8 31 | 29,2,60,130,88,0,30.36 32 | 30,1,36,102,68,1,28.15 33 | 31,1,43,115,85.5,1,27.57 34 | 32,1,40,125,90,0,23.62 35 | 33,2,59,150,85,0,20.77 36 | 34,1,61,134,82.5,1,18.59 37 | 35,1,62,125,74.5,0,25.9 38 | 36,1,54,147,74,1,24.71 39 | 37,1,37,124.5,92.5,0,38.53 40 | 38,1,56,153.5,102,0,28.09 41 | 39,1,52,160,98,0,40.11 42 | 40,2,42,153,101,1,28.93 43 | 41,1,36,111,73,0,27.78 44 | 42,2,43,116.5,80,1,26.87 45 | 43,2,41,122,78,1,23.28 46 | 44,2,52,148,92,0,25.09 47 | 45,1,54,132,83.5,0,26.21 48 | 46,2,53,206,92,0,21.51 49 | 47,2,49,96,63,0,20.68 50 | 48,2,65,179.5,114,0,30.47 51 | 49,1,46,119,77.5,1,23.59 52 | -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/medical.jl: -------------------------------------------------------------------------------- 1 | using Gadfly, DataFrames 2 | df = readtable("medical.csv") 3 | print("size is ", size(df)) #> size is (50,7) 4 | df[1:3, 1:size(df,2)] 5 | # data sample: 6 | # IX Sex Age sBP dBP Drink BMI 7 | # 0 1 39 106.0 70.0 0 26.97 8 | # 1 2 46 121.0 81.0 0 28.73 9 | # 2 1 48 127.5 80.0 1 25.34 10 | 11 | # transforming the data: 12 | df[:Sex] = ifelse(df[:Sex].==1, "F", "M") 13 | df[:Drink] = ifelse(df[:Drink].==1, "Y", "N") 14 | df[1:3, 1:size(df,2)] 15 | # transformed data sample: 16 | # IX Sex Age sBP dBP Drink BMI 17 | # 0 F 39 106.0 70.0 N 26.97 18 | # 1 M 46 121.0 81.0 N 28.73 19 | # 2 F 48 127.5 80.0 Y 25.34 20 | 21 | describe(df) 22 | # IX 23 | # Min 0.0 24 | # 1st Qu. 12.25 25 | # Median 24.5 26 | # Mean 24.5 27 | # 3rd Qu. 36.75 28 | # Max 49.0 29 | # NAs 0 30 | # NA% 0.0% 31 | 32 | # Sex 33 | # Length 50 34 | # Type ASCIIString 35 | # NAs 0 36 | # NA% 0.0% 37 | # Unique 2 38 | 39 | # Age 40 | # Min 35.0 41 | # 1st Qu. 42.0 42 | # Median 46.0 43 | # Mean 47.86 44 | # 3rd Qu. 52.75 45 | # Max 65.0 46 | # NAs 0 47 | # NA% 0.0% 48 | 49 | # sBP 50 | # Min 96.0 51 | # 1st Qu. 119.5 52 | # Median 131.5 53 | # Mean 133.5 54 | # 3rd Qu. 145.75 55 | # Max 206.0 56 | # NAs 0 57 | # NA% 0.0% 58 | 59 | # dBP 60 | # Min 63.0 61 | # 1st Qu. 76.375 62 | # Median 84.25 63 | # Mean 84.86 64 | # 3rd Qu. 90.75 65 | # Max 121.0 66 | # NAs 0 67 | # NA% 0.0% 68 | 69 | # Drink 70 | # Length 50 71 | # Type ASCIIString 72 | # NAs 0 73 | # NA% 0.0% 74 | # Unique 2 75 | 76 | # BMI 77 | # Min 18.59 78 | # 1st Qu. 23.25 79 | # Median 26.15 80 | # Mean 26.374200000000002 81 | # 3rd Qu. 28.472499999999997 82 | # Max 40.11 83 | # NAs 0 84 | # NA% 0.0% 85 | 86 | # And the standard deviations 87 | ["Age" std(df["Age"]) "sBP" std(df["sBP"]) "dBP" std(df["dBP"]) "BMI" std(df["BMI"])] 88 | # 1x8 Array{Any,2}: 89 | # "Age" 8.1941 "sBP" 22.6628 "dBP" 12.5921 "BMI" 4.41216 90 | 91 | set_default_plot_size(20cm, 12cm) 92 | plot(df, x="Age", y="sBP", color="Sex", Geom.smooth, Geom.bar(position=:dodge)) 93 | pl = plot(df, x="Age", y="sBP", color="Sex", Geom.smooth, Geom.bar(position=:dodge)) 94 | draw(PDF("medical.pdf", 6inch, 3inch), pl) -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/medical.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter10/Old/medical.pdf -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/stlib.jl: -------------------------------------------------------------------------------- 1 | filter(x -> iseven(x), 1:10) 2 | # 5-element Array{Int64,1}: 3 | # 2 4 | # 4 5 | # 6 6 | # 8 7 | # 10 8 | mapreduce(x -> sqrt(x), +, 1:10) #> 22.4682781862041 9 | # equivalent to: 10 | sum(map(x -> sqrt(x), [1:10])) #> 22.4682781862041 11 | # 12 | 1:10 |> x -> sqrt(x) |> sum #> 22.4682781862041 13 | 1:5 |> exp |> sum #> 233.2041839862982 14 | 15 | # clipboard: 16 | a = 42 #> 42 17 | clipboard(a) 18 | workspace() 19 | # a #> ERROR: a not defined 20 | a = clipboard() #> "42" -------------------------------------------------------------------------------- /Module 1/Chapter10/Old/winston.jl: -------------------------------------------------------------------------------- 1 | # Winston: 2 | using Winston 3 | # optionally call figure prior to plotting to set the size 4 | figure(width=600, height=400) 5 | # plot some data 6 | pl = plot(cumsum(rand(500) - 0.5), "r", cumsum(rand(500) - 0.5), "b") 7 | # display the plot (not done automatically!) 8 | display(pl) 9 | println("Press enter to continue: ") 10 | readline(STDIN) 11 | # save the current figure 12 | savefig("winston.svg") -------------------------------------------------------------------------------- /Module 1/Chapter10/gadfly.jl: -------------------------------------------------------------------------------- 1 | using Gadfly 2 | draw(SVG("gadfly.svg",6inch,3inch), plot([x -> x^2],0, 25)) 3 | pl = plot([x -> cos(x)/x], 5, 25) 4 | draw(PNG("gadfly.png", 300, 100), pl) -------------------------------------------------------------------------------- /Module 1/Chapter10/gadfly.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter10/gadfly.png -------------------------------------------------------------------------------- /Module 1/Chapter10/gadfly.svg: -------------------------------------------------------------------------------- 1 | 2 | 12 | -------------------------------------------------------------------------------- /Module 1/Chapter10/medical.csv: -------------------------------------------------------------------------------- 1 | IX,Sex,Age,sBP,dBP,Drink,BMI 2 | 0,1,39,106,70,0,26.97 3 | 1,2,46,121,81,0,28.73 4 | 2,1,48,127.5,80,1,25.34 5 | 3,2,61,150,95,1,28.58 6 | 4,2,46,130,84,1,23.1 7 | 5,2,43,180,110,0,30.3 8 | 6,2,63,138,71,0,33.11 9 | 7,2,45,100,71,1,21.68 10 | 8,1,52,141.5,89,0,26.36 11 | 9,1,43,162,107,1,23.61 12 | 10,2,50,133,76,0,22.91 13 | 11,2,43,131,88,0,27.64 14 | 12,1,46,142,94,1,26.31 15 | 13,2,41,124,88,0,31.31 16 | 14,2,39,114,64,1,22.35 17 | 15,2,38,140,90,1,21.35 18 | 16,1,48,138,90,1,22.37 19 | 17,2,46,112,78,1,23.38 20 | 18,2,38,122,84.5,1,23.24 21 | 19,1,41,139,88,0,26.88 22 | 20,2,42,108,70.5,1,21.59 23 | 21,2,43,123.5,77.5,0,29.89 24 | 22,2,52,148,78,0,34.17 25 | 23,2,52,132,82,1,25.11 26 | 24,1,44,137.5,90,1,21.96 27 | 25,1,47,102,68,1,24.18 28 | 26,2,60,110,72.5,0,26.59 29 | 27,1,35,132,91,1,26.09 30 | 28,2,61,182,121,0,32.8 31 | 29,2,60,130,88,0,30.36 32 | 30,1,36,102,68,1,28.15 33 | 31,1,43,115,85.5,1,27.57 34 | 32,1,40,125,90,0,23.62 35 | 33,2,59,150,85,0,20.77 36 | 34,1,61,134,82.5,1,18.59 37 | 35,1,62,125,74.5,0,25.9 38 | 36,1,54,147,74,1,24.71 39 | 37,1,37,124.5,92.5,0,38.53 40 | 38,1,56,153.5,102,0,28.09 41 | 39,1,52,160,98,0,40.11 42 | 40,2,42,153,101,1,28.93 43 | 41,1,36,111,73,0,27.78 44 | 42,2,43,116.5,80,1,26.87 45 | 43,2,41,122,78,1,23.28 46 | 44,2,52,148,92,0,25.09 47 | 45,1,54,132,83.5,0,26.21 48 | 46,2,53,206,92,0,21.51 49 | 47,2,49,96,63,0,20.68 50 | 48,2,65,179.5,114,0,30.47 51 | 49,1,46,119,77.5,1,23.59 52 | -------------------------------------------------------------------------------- /Module 1/Chapter10/medical.jl: -------------------------------------------------------------------------------- 1 | using Gadfly, DataFrames 2 | df = readtable("medical.csv") 3 | print("size is ", size(df)) #> size is (50,7) 4 | df[1:3, 1:size(df,2)] 5 | # data sample: 6 | # IX Sex Age sBP dBP Drink BMI 7 | # 0 1 39 106.0 70.0 0 26.97 8 | # 1 2 46 121.0 81.0 0 28.73 9 | # 2 1 48 127.5 80.0 1 25.34 10 | 11 | # transforming the data: 12 | df[:Sex] = ifelse(df[:Sex].==1, "F", "M") 13 | df[:Drink] = ifelse(df[:Drink].==1, "Y", "N") 14 | df[1:3, 1:size(df,2)] 15 | # transformed data sample: 16 | # IX Sex Age sBP dBP Drink BMI 17 | # 0 F 39 106.0 70.0 N 26.97 18 | # 1 M 46 121.0 81.0 N 28.73 19 | # 2 F 48 127.5 80.0 Y 25.34 20 | 21 | describe(df) 22 | # IX 23 | # Min 0.0 24 | # 1st Qu. 12.25 25 | # Median 24.5 26 | # Mean 24.5 27 | # 3rd Qu. 36.75 28 | # Max 49.0 29 | # NAs 0 30 | # NA% 0.0% 31 | 32 | # Sex 33 | # Length 50 34 | # Type ASCIIString 35 | # NAs 0 36 | # NA% 0.0% 37 | # Unique 2 38 | 39 | # Age 40 | # Min 35.0 41 | # 1st Qu. 42.0 42 | # Median 46.0 43 | # Mean 47.86 44 | # 3rd Qu. 52.75 45 | # Max 65.0 46 | # NAs 0 47 | # NA% 0.0% 48 | 49 | # sBP 50 | # Min 96.0 51 | # 1st Qu. 119.5 52 | # Median 131.5 53 | # Mean 133.5 54 | # 3rd Qu. 145.75 55 | # Max 206.0 56 | # NAs 0 57 | # NA% 0.0% 58 | 59 | # dBP 60 | # Min 63.0 61 | # 1st Qu. 76.375 62 | # Median 84.25 63 | # Mean 84.86 64 | # 3rd Qu. 90.75 65 | # Max 121.0 66 | # NAs 0 67 | # NA% 0.0% 68 | 69 | # Drink 70 | # Length 50 71 | # Type ASCIIString 72 | # NAs 0 73 | # NA% 0.0% 74 | # Unique 2 75 | 76 | # BMI 77 | # Min 18.59 78 | # 1st Qu. 23.25 79 | # Median 26.15 80 | # Mean 26.374200000000002 81 | # 3rd Qu. 28.472499999999997 82 | # Max 40.11 83 | # NAs 0 84 | # NA% 0.0% 85 | 86 | # And the standard deviations 87 | ["Age" std(df["Age"]) "sBP" std(df["sBP"]) "dBP" std(df["dBP"]) "BMI" std(df["BMI"])] 88 | # 1x8 Array{Any,2}: 89 | # "Age" 8.1941 "sBP" 22.6628 "dBP" 12.5921 "BMI" 4.41216 90 | 91 | set_default_plot_size(20cm, 12cm) 92 | plot(df, x="Age", y="sBP", color="Sex", Geom.smooth, Geom.bar(position=:dodge)) 93 | pl = plot(df, x="Age", y="sBP", color="Sex", Geom.smooth, Geom.bar(position=:dodge)) 94 | draw(PDF("medical.pdf", 6inch, 3inch), pl) -------------------------------------------------------------------------------- /Module 1/Chapter10/medical.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 1/Chapter10/medical.pdf -------------------------------------------------------------------------------- /Module 1/Chapter10/stlib.jl: -------------------------------------------------------------------------------- 1 | filter(x -> iseven(x), 1:10) 2 | # 5-element Array{Int64,1}: 3 | # 2 4 | # 4 5 | # 6 6 | # 8 7 | # 10 8 | mapreduce(x -> sqrt(x), +, 1:10) #> 22.4682781862041 9 | # equivalent to: 10 | sum(map(x -> sqrt(x), [1:10])) #> 22.4682781862041 11 | # 12 | 1:10 |> x -> sqrt(x) |> sum #> 22.4682781862041 13 | 1:10 |> sqrt |> sum #> 22.4682781862041 14 | 1:5 |> exp |> sum #> 233.2041839862982 15 | 16 | # clipboard: 17 | a = 42 #> 42 18 | clipboard(a) 19 | workspace() 20 | # a #> ERROR: a not defined 21 | a = clipboard() #> "42" -------------------------------------------------------------------------------- /Module 1/Chapter10/winston.jl: -------------------------------------------------------------------------------- 1 | # Winston: 2 | Pkg.add("Winston") 3 | using Winston 4 | # optionally call figure prior to plotting to set the size 5 | figure(width=600, height=400) 6 | # plot some data 7 | pl = plot(cumsum(rand(500) - 0.5), "r", cumsum(rand(500) - 0.5), "b") 8 | # display the plot (not done automatically!) 9 | display(pl) 10 | println("Press enter to continue: ") 11 | readline(STDIN) 12 | # save the current figure 13 | savefig("winston.svg") -------------------------------------------------------------------------------- /Module 2/Chapter01/p1.jl: -------------------------------------------------------------------------------- 1 | function pisum() 2 | sum = 0.0 3 | for j = 1:500 4 | sum = 0.0 5 | for k = 1:10000 6 | sum += 1.0/(k*k) 7 | end 8 | end 9 | sum 10 | end -------------------------------------------------------------------------------- /Module 2/Chapter02/testf.jl: -------------------------------------------------------------------------------- 1 | function testfunc() 2 | x = rand(10000, 1000) 3 | y = std(x, 1) 4 | return y 5 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/ConcrertePoint.jl: -------------------------------------------------------------------------------- 1 | immutable ConcretePoint 2 | x::Float64 3 | y::Float64 4 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/ParametricPoint.jl: -------------------------------------------------------------------------------- 1 | function ParametricPoint{T <: AbstractFloat} 2 | x::T 3 | y::T 4 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/PointWithAbstract.jl: -------------------------------------------------------------------------------- 1 | immutable PointWithAbstract 2 | x::AbstractFloat 3 | y::AbstractFloat 4 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/arr_sumsqr.jl: -------------------------------------------------------------------------------- 1 | function arr_sumsqr{T <: Number}(x::Array{T}) 2 | r = zero(T) 3 | for i = 1:length(x) 4 | r = r + x[i] ^ 2 5 | end 6 | return r 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/immutable.jl: -------------------------------------------------------------------------------- 1 | immutable IPixel 2 | x::Int64 3 | y::Int64 4 | color::Int64 5 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/pixel.jl: -------------------------------------------------------------------------------- 1 | type Pixel 2 | x::Int64 3 | y::Int64 4 | color::Int64 5 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/point.jl: -------------------------------------------------------------------------------- 1 | immutable Point 2 | x 3 | y 4 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/stringzero.jl: -------------------------------------------------------------------------------- 1 | function string_zeros(s::AbstractString) 2 | x = Array(s=="Int64"?Int64:Float64, 1_000_000) 3 | for i in 1:length(x) 4 | x[i] = 0 5 | end 6 | return x 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/stringzero_stable.jl: -------------------------------------------------------------------------------- 1 | function string_zeros_stable(s::AbstractString) 2 | x = Array(s=="Int64"?Int64:Float64, 1_000_000) 3 | return fill_zeros(x) 4 | end 5 | function fill_zeros(x) 6 | for i in 1:length(x) 7 | x[i] = 0 8 | end 9 | return x 10 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/sumsqr.jl: -------------------------------------------------------------------------------- 1 | sumsqr(x, y) = x^2 + y^2 -------------------------------------------------------------------------------- /Module 2/Chapter03/sumsqrtn(n).jl: -------------------------------------------------------------------------------- 1 | function sumsqrtn(n) 2 | r = 0 3 | for i = 1:n 4 | r = r + sqrt(i) 5 | end 6 | return r 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/sumsqrtn_fixed(n).jl: -------------------------------------------------------------------------------- 1 | function sumsqrtn_fixed(n) 2 | r = 0.0 3 | for i = 1:n 4 | r = r + sqrt(i) 5 | end 6 | return r 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/testfunc.jl: -------------------------------------------------------------------------------- 1 | foo(x::Integer) = "an integer" #Declare type of function argument 2 | foo(x::ASCIIString) = "a string" 3 | function bar(a, b) 4 | x::Int64 = 0 #Declare type of local variable 5 | y = a+b #Type of variable will be inferred 6 | return y 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/trunc.jl: -------------------------------------------------------------------------------- 1 | function trunc(x) 2 | if x < 0 3 | return 0 4 | else 5 | return x 6 | end 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/trunc_fixed.jl: -------------------------------------------------------------------------------- 1 | function trunc_fixed(x) 2 | if x < 0 3 | [ 30 ] 4 | return zero(x) 5 | else 6 | return x 7 | end 8 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/truncomp.jl: -------------------------------------------------------------------------------- 1 | function trunc(x) 2 | if typeof(x) == Float64 3 | return 0.0 4 | elseif typeof(x) == Float32 5 | return Float32(0.0) 6 | elseif typeof(x) == Int64 7 | return 0 8 | end 9 | end -------------------------------------------------------------------------------- /Module 2/Chapter03/tyoepixe.jl: -------------------------------------------------------------------------------- 1 | type Pixel1{T} 2 | x::Int64 3 | y::Int64 4 | color::T 5 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/@prod_dim.jl: -------------------------------------------------------------------------------- 1 | function prod_dim_gen_impl{T, N}(x::Array{T, N}) 2 | ex = :(1) 3 | for i = 1:N 4 | ex = :(size(x, $i) * $ex) 5 | end 6 | return ex 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/@prod_dim_gen.jl: -------------------------------------------------------------------------------- 1 | function prod_dim_gen_impl{T, N}(x::Array{T, N}) 2 | ex = :(1) 3 | for i = 1:N 4 | ex = :(size(x, $i) * $ex) 5 | end 6 | return ex 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/F(x).jl: -------------------------------------------------------------------------------- 1 | function f(x) 2 | a=x*5 3 | b=a+3 4 | c=a-4 5 | d=b/c 6 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/f_inline.jl: -------------------------------------------------------------------------------- 1 | @inline function f_inline(x) 2 | a=x*5 3 | b=a+3 4 | c=a-4 5 | d=b/c 6 | end 7 | g_inline(x) = f_inline(2*x) -------------------------------------------------------------------------------- /Module 2/Chapter04/macro_horner.jl: -------------------------------------------------------------------------------- 1 | macro horner(x, p...) 2 | ex = esc(p[end]) 3 | for i = length(p)-1:-1:1 4 | ex = :(muladd(t, $ex, $(esc(p[i])))) 5 | end 6 | Expr(:block, :(t = $(esc(x))), ex) 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/muladd.jl: -------------------------------------------------------------------------------- 1 | muladd(x,muladd(x,muladd(x,muladd(x,5,4),3),2),1) -------------------------------------------------------------------------------- /Module 2/Chapter04/poly_horner.jl: -------------------------------------------------------------------------------- 1 | function poly_horner(x, a...) 2 | b=zero(x) 3 | for i = length(a):-1:1 4 | b = a[i] + b * x 5 | end 6 | return b 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/poly_naive.jl: -------------------------------------------------------------------------------- 1 | function poly_horner(x, a...) 2 | b=zero(x) 3 | for i = length(a):-1:1 4 | b = a[i] + b * x 5 | end 6 | return b 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/pow_Array.jl: -------------------------------------------------------------------------------- 1 | p = 2 2 | function pow_array(x::Vector{Float64}) 3 | s = 0.0 4 | for y in x 5 | s = s + y^p 6 | end 7 | return s 8 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/pow_Array2.jl: -------------------------------------------------------------------------------- 1 | const p2 = 2 2 | function pow_array2(x::Vector{Float64}) 3 | s = 0.0 4 | for y in x 5 | s = s + y^p2 6 | end 7 | return s 8 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/prod_tim.jl: -------------------------------------------------------------------------------- 1 | function prod_dim{T, N}(x::Array{T, N}) 2 | s = 1 3 | for i = 1:N 4 | s = s * size(x, i) 5 | end 6 | return s 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter04/sqrt_sin.jl: -------------------------------------------------------------------------------- 1 | trunc(x) = x < 0 ? zero(x) : x 2 | function sqrt_sin(x) 3 | y = trunc(x) 4 | return sin(sqrt(y)+1) 5 | end -------------------------------------------------------------------------------- /Module 2/Chapter05/Timestep.jl: -------------------------------------------------------------------------------- 1 | function col_iter(x) 2 | s=zero(eltype(x)) 3 | for i = 1:size(x, 2) 4 | for j = 1:size(x, 1) 5 | s = s + x[j, i] ^ 2 6 | x[j, i] = s 7 | end 8 | end 9 | end 10 | function row_iter(x) 11 | s=zero(eltype(x)) 12 | for i = 1:size(x, 1) 13 | for j = 1:size(x, 2) 14 | s = s + x[i, j] ^ 2 15 | x[i, j] = s 16 | end 17 | end 18 | end -------------------------------------------------------------------------------- /Module 2/Chapter05/fastmath_mac.jl: -------------------------------------------------------------------------------- 1 | function sum_diff(x) 2 | n = length(x); d = 1/(n-1) 3 | s = zero(eltype(x)) 4 | s = s + (x[2] - x[1]) / d 5 | for i = 2:length(x)-1 6 | s = s + (x[i+1] - x[i+1]) / (2*d) 7 | end 8 | s = s + (x[n] - x[n-1])/d 9 | end 10 | function sum_diff_fast(x) 11 | n=length(x); d = 1/(n-1) 12 | s = zero(eltype(x)) 13 | @fastmath s = s + (x[2] - x[1]) / d 14 | @fastmath for i = 2:n-1 15 | s = s + (x[i+1] - x[i+1]) / (2*d) 16 | end 17 | @fastmath s = s + (x[n] - x[n-1])/d 18 | end -------------------------------------------------------------------------------- /Module 2/Chapter05/myadd.jl: -------------------------------------------------------------------------------- 1 | myadd(x, y) = x + y -------------------------------------------------------------------------------- /Module 2/Chapter06/Prealloaction.jl: -------------------------------------------------------------------------------- 1 | function xpow!(result::Array{Int, 1}, x) 2 | @assert length(result) == 4 3 | result[1] = x 4 | result[2] = x^2 5 | result[3] = x^3 6 | result[4] = x^4 7 | end 8 | function xpow_loop_noalloc(n) 9 | r = [0, 0, 0, 0] 10 | s = 0 11 | for i = 1:n 12 | xpow!(r, i) 13 | s = s + r[2] 14 | end 15 | s 16 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/SIMD.jl: -------------------------------------------------------------------------------- 1 | function sum_vectors!(x, y, z) 2 | n = length(x) 3 | for i = 1:n 4 | x[i] = y[i] + z[i] 5 | end 6 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/allocations.jl: -------------------------------------------------------------------------------- 1 | function xpow(x) 2 | return [x x^2 x^3 x^4] 3 | end 4 | function xpow_loop(n) 5 | s = 0 6 | for i = 1:n 7 | s = s + xpow(i)[2] 8 | end 9 | return s 10 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/anynomous.jl: -------------------------------------------------------------------------------- 1 | sqr(x) = x ^ 2 -------------------------------------------------------------------------------- /Module 2/Chapter06/array_views.jl: -------------------------------------------------------------------------------- 1 | function sum_vector(x::Array{Float64, 1}) 2 | s = 0.0 3 | for i = 1:length(x) 4 | s = s + x[i] 5 | end 6 | return s 7 | end 8 | function sum_cols_matrix(x::Array{Float64, 2}) 9 | num_cols = size(x, 2) 10 | s = zeros(num_cols) 11 | for i = 1:num_cols 12 | s[i] = sum_vector(x[:, i]) 13 | end 14 | return s 15 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/array_views_ad.jl: -------------------------------------------------------------------------------- 1 | function sum_vector(x::AbstractArray) 2 | s = 0.0 3 | for i = 1:length(x) 4 | s = s + x[i] 5 | end 6 | return s 7 | end 8 | function sum_cols_matrix_views(x::Array{Float64, 2}) 9 | num_cols = size(x, 2); num_rows = size(x, 1) 10 | s = zeros(num_cols) 11 | for i = 1:num_cols 12 | s[i] = sum_vector(sub(x, 1:num_rows, i)) 13 | end 14 | return s 15 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/bound_check.jl: -------------------------------------------------------------------------------- 1 | function prefix_bounds(a, b) 2 | for i = 2:size(a, 1) 3 | a[i] = b[i-1] + b[i] 4 | end 5 | end 6 | function prefix_inbounds(a, b) 7 | @inbounds for i = 2:size(a, 1) 8 | a[i] = b[i-1] + b[i] 9 | end 10 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/col_iter.jl: -------------------------------------------------------------------------------- 1 | function col_iter(x) 2 | s=zero(eltype(x)) 3 | for i = 1:size(x, 2) 4 | for j = 1:size(x, 1) 5 | s = s + x[j, i] ^ 2 6 | x[j, i] = s 7 | end 8 | end 9 | end 10 | function row_iter(x) 11 | s=zero(eltype(x)) 12 | for i = 1:size(x, 1) 13 | for j = 1:size(x, 2) 14 | s = s + x[i, j] ^ 2 15 | x[i, j] = s 16 | end 17 | end 18 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/inbound_SIMD.jl: -------------------------------------------------------------------------------- 1 | function sum_vectors_simd!(x, y, z) 2 | n = length(x) 3 | @inbounds @simd for i = 1:n 4 | x[i] = y[i] + z[i] 5 | end 6 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/linear.jl: -------------------------------------------------------------------------------- 1 | function mysum_linear(a::AbstractArray) 2 | s=zero(eltype(a)) 3 | for i = 1:length(a) 4 | s=s+a[i] 5 | end 6 | return s 7 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/mysum_in.jl: -------------------------------------------------------------------------------- 1 | function mysum_in(a::AbstractArray) 2 | s = zero(eltype(a)) 3 | for i in a 4 | s = s + i 5 | end 6 | end -------------------------------------------------------------------------------- /Module 2/Chapter06/mysum_index.jl: -------------------------------------------------------------------------------- 1 | function mysum_eachindex(a::AbstractArray) 2 | s = zero(eltype(a)) 3 | for i in eachindex(a) 4 | s = s + a[i] 5 | end 6 | end -------------------------------------------------------------------------------- /Module 2/Chapter07/parallel_for.jl: -------------------------------------------------------------------------------- 1 | function serial_add() 2 | s=0.0 3 | for i = 1:1000000 4 | s=s+randn() 5 | end 6 | return s 7 | end 8 | function parallel_add() 9 | return @parallel (+) for i=1:1000000 10 | randn() 11 | end 12 | end -------------------------------------------------------------------------------- /Module 2/Chapter07/shared_array.jl: -------------------------------------------------------------------------------- 1 | S=SharedArray( Float64, (100, 100, 5), pids=[2,3,4,5]); -------------------------------------------------------------------------------- /Module 3/Chapter01/asian-asciiplot.jl: -------------------------------------------------------------------------------- 1 | # 2 | # asian-asciiplot.jl 3 | # 4 | using ASCIIPlots; 5 | 6 | S0 = 100; # Spot price 7 | K = 102; # Strike price 8 | r = 0.05; # Risk free rate 9 | q = 0.0; # Dividend yield 10 | v = 0.2; # Volatility 11 | tma = 0.25; # Time to maturity 12 | T = 100; # Number of time steps 13 | dt = tma/T; # Time increment 14 | S = zeros(Float64,T); 15 | S[1] = S0; 16 | dW = randn(T)*sqrt(dt) 17 | [ S[t] = S[t-1] * (1 + (r - q - 0.5*v*v)*dt + v*dW[t] + 0.5*v*v*dW[t]*dW[t]) for t=2:T ] 18 | x = linspace(1,T); 19 | scatterplot(x,S,sym='*') 20 | 21 | -------------------------------------------------------------------------------- /Module 3/Chapter01/asian-option.jl: -------------------------------------------------------------------------------- 1 | # 2 | # asian-option.jl 3 | # 4 | function run-asian(N = 100000, PutCall = 'C';) 5 | # European Asian option. 6 | # Uses geometric or arithmetic average. 7 | # Euler and Milstein discretization for Black-Scholes. 8 | # Option features. 9 | println("Setting option parameters"); 10 | S0 = 100; # Spot price 11 | K = 100; # Strike price 12 | r = 0.05; # Risk free rate 13 | q = 0.0; # Dividend yield 14 | v = 0.2; # Volatility 15 | tma = 0.25; # Time to maturity 16 | 17 | Averaging = 'A'; # 'A'rithmetic or 'G'eometric 18 | OptType = (PutCall == 'C' ? "CALL" : "PUT"); 19 | println("Option type is $OptType"); 20 | # Simulation settings. 21 | println("Setting simulation parameters"); 22 | T = 100; # Number of time steps 23 | dt = tma/T; # Time increment 24 | 25 | # Initialize the terminal stock price matrices 26 | # for the Euler and Milstein discretization schemes. 27 | S = zeros(Float64,N,T); 28 | for n=1:N 29 | S[n,1] = S0; 30 | end 31 | 32 | # Simulate the stock price under the Euler and Milstein schemes. 33 | # Take average of terminal stock price. 34 | println("Looping $N times."); 35 | A = zeros(Float64,N); 36 | for n=1:N 37 | for t=2:T 38 | dW = (randn(1)[1])*sqrt(dt); 39 | z0 = (r - q - 0.5*v*v)*S[n,t-1]*dt; 40 | z1 = v*S[n,t-1]*dW; 41 | z2 = 0.5*v*v*S[n,t-1]*dW*dW; 42 | S[n,t] = S[n,t-1] + z0 + z1 + z2; 43 | end 44 | if cmp(Averaging,'A') == 0 45 | A[n] = mean(S[n,:]); 46 | elseif cmp(Averaging,'G') == 0 47 | A[n] = exp(mean(log(S[n,:]))); 48 | end 49 | end 50 | 51 | # Define the payoff 52 | P = zeros(Float64,N); 53 | if cmp(PutCall,'C') == 0 54 | for n = 1:N 55 | P[n] = max(A[n] - K, 0); 56 | end 57 | elseif cmp(PutCall,'P') == 0 58 | for n = 1:N 59 | P[n] = max(K - A[n], 0); 60 | end 61 | end 62 | # Calculate the price of the Asian option 63 | AsianPrice = exp(-r*tma)*mean(P); 64 | @printf "Price: %10.4f\n" AsianPrice; 65 | end 66 | 67 | run-asian() 68 | 69 | -------------------------------------------------------------------------------- /Module 3/Chapter01/asian-winstonplot.jl: -------------------------------------------------------------------------------- 1 | # 2 | # asian-winstonplot.jl 3 | # 4 | # Note: 5 | # 6 | # With OSX I have had some problems using the Pango as part of the Winston package 7 | # to display titles and text etc. 8 | # 9 | # This seems to be a problem with Homebrew and the following worked for me 10 | # It only needs to be run once, 11 | # 12 | # using Homebrew 13 | # Homebrew.update() 14 | # Homebrew.rm("pango") 15 | # Homebrew.add("pango") 16 | # 17 | 18 | import Winston; 19 | wn = Winston; 20 | 21 | S0 = 100; # Spot price 22 | K = 102; # Strike price 23 | r = 0.05; # Risk free rate 24 | q = 0.0; # Dividend yield 25 | v = 0.2; # Volatility 26 | tma = 0.25; # Time to maturity 27 | T = 100; # Number of time steps 28 | dt = tma/T; # Time increment 29 | S = zeros(Float64,T) 30 | S[1] = S0; 31 | 32 | dW = randn(T)*sqrt(dt); 33 | [ S[t] = S[t-1] * (1 + (r - q - 0.5*v*v)*dt + v*dW[t] + 0.5*v*v*dW[t]*dW[t]) for t=2:T ] 34 | x = linspace(1, T, T); 35 | p = wn.FramedPlot(title = "Random Walk, drift 5%, volatility 20%") 36 | wn.add(p, wn.Curve(x,S,color="red")) 37 | wn.display(p) 38 | 39 | -------------------------------------------------------------------------------- /Module 3/Chapter01/estimate-pi.jl: -------------------------------------------------------------------------------- 1 | # 2 | # Estimate-pi.jl 3 | # 4 | sumsq(x,y) = x*x + y*y; 5 | 6 | N=1000000; 7 | x = 0; 8 | for i = 1:N 9 | if sumsq(rand(), rand()) < 1.0 10 | x += 1 11 | end 12 | end 13 | @printf "Estimate of PI for %d trials is %8.5f\n" N 4.0*(x / N); 14 | 15 | -------------------------------------------------------------------------------- /Module 3/Chapter02/bacs.jl: -------------------------------------------------------------------------------- 1 | function bacs () 2 | bulls = cows = turns = 0 3 | a = {} 4 | srand(int(time())) 5 | while length(unique(a)) < 4 6 | push!(a,rand('0':'9')) 7 | end 8 | my_guess = unique(a) 9 | println("Bulls and Cows") 10 | while (bulls != 4) 11 | print("Guess? ") 12 | if eof(STDIN) 13 | s = "q" 14 | else 15 | s = chomp(readline(STDIN)) 16 | end 17 | if (s == "q") 18 | print("My guess was "); [print(my_guess[i]) for i=1:4] 19 | return 20 | end 21 | guess = collect(s) 22 | if !(length(unique(guess)) == length(guess) == 4 && all(isdigit,guess)) 23 | print("\nEnter four distinct digits or q to quit: ") 24 | continue 25 | end 26 | bulls = sum(map(==, guess, my_guess)) 27 | cows = length(intersect(guess,my_guess)) - bulls 28 | println("$bulls bulls and $cows cows!") 29 | turns += 1 30 | end 31 | println("You guessed my number in $turns turns.") 32 | end 33 | -------------------------------------------------------------------------------- /Module 3/Chapter02/jmain.jl: -------------------------------------------------------------------------------- 1 | include("jset.jl") 2 | include("pgmfile.jl") 3 | 4 | h = 400; w = 800; m = Array(Int64, h, w); 5 | c0 = -0.8+0.16im; 6 | pgm_name = "julia.pgm"; 7 | 8 | t0 = time(); 9 | for y=1:h, x=1:w 10 | c = complex((x-w/2)/(w/2), (y-h/2)/(w/2)) 11 | m[y,x] = juliaset(c, c0, 256) 12 | end 13 | t1 = time(); 14 | 15 | create_pgmfile(m, pgm_name); 16 | print("Written $pgm_name\nFinished in $(t1-t0) seconds.\n"); 17 | -------------------------------------------------------------------------------- /Module 3/Chapter02/jset.jl: -------------------------------------------------------------------------------- 1 | function juliaset(z, z0, nmax::Int64) 2 | for n = 1:nmax 3 | if abs(z) > 2 (return n-1) end 4 | z = z^2 + z0 5 | end 6 | return nmax 7 | end -------------------------------------------------------------------------------- /Module 3/Chapter02/julia.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter02/julia.pgm -------------------------------------------------------------------------------- /Module 3/Chapter02/m3.txt: -------------------------------------------------------------------------------- 1 | 0.0,0.0,0.5,0.0 2 | 0.0,0.0,1.0,0.0 3 | 0.25,0.25,0.0,0.25 4 | 0.0,0.0,0.5,0.0 5 | -------------------------------------------------------------------------------- /Module 3/Chapter02/mouse.jl: -------------------------------------------------------------------------------- 1 | #http://en.wikipedia.org/wiki/Stochastic_matrix 2 | 3 | I = zeros(4,4); 4 | [I[i,i] = 1 for i in 1:4]; 5 | 6 | f = open("m3.txt","r") 7 | T = readdlm(f,','); 8 | close(f); 9 | 10 | Ep = [0 1 0 0]*inv(I - T)*[1,1,1,1]; 11 | 12 | println("Expected lifetime for the mouse is $Ep") 13 | -------------------------------------------------------------------------------- /Module 3/Chapter02/pgmfile.jl: -------------------------------------------------------------------------------- 1 | function create_pgmfile(img, outf::String) 2 | s = open(outf, "w") 3 | write(s, "P5\n") 4 | n, m = size(img) 5 | write(s, "$m $n 255\n") 6 | for i=1:n, j=1:m 7 | p = img[i,j] 8 | write(s, uint8(p)) 9 | end 10 | close(s) 11 | end -------------------------------------------------------------------------------- /Module 3/Chapter03/Vectors3D.jl: -------------------------------------------------------------------------------- 1 | module Vectors3D 2 | import Base.show, Base.convert, Base.abs, Base.dot 3 | export Vector3D, getindex, phi 4 | immutable Vector3D{T <: Real} 5 | x::T 6 | y::T 7 | z::T 8 | end 9 | +(u::Vector3D, v::Vector3D) = Vector3D(u.x + v.x, u.x + v.y, u.z + v.z) 10 | -(u::Vector3D, v::Vector3D) = Vector3D(u.x - v.x, u.x - v.y, u.z - v.z) 11 | *(a::Number, u::Vector3D) = Vector3D(a*u.x, a*u.y, a*u.z) 12 | *(u::Vector3D, a::Number) = Vector3D(a*u.x, a*u.y, a*u.z) 13 | /(a::Number, u::Vector3D) = Vector3D(u.x/a, u.y/a, u.z/a) 14 | /(u::Vector3D, a::Number) = Vector3D(u.x/a, u.y/a, u.z/a) 15 | show{T}(io::IO, u::Vector3D{T}) = print(io, "[$(u.x), $(u.y), $(u.z)]") 16 | 17 | abs{T}(u::Vector3D{T}) = (u.x*u.x + u.y*u.y + u.z*u.z)^0.5 18 | function phi(u::Vector3D, v::Vector3D) 19 | w0 = u.x*v.x + u.y*v.y + u.z*v.z 20 | w1 = abs(u) * abs(v) 21 | try 22 | return atan(w0 / w1) 23 | catch 24 | error("Division by zero") 25 | end 26 | end 27 | dot(u::Vector3D, v::Vector3D) = u.x*v.x + u.y*v.y + u.z+v.z 28 | getindex(u::Vector3D, i) = (i == 1 ? u.x : (i==2 ? u.y : u.z)) 29 | convert(::Type{Vector3D}, u::Array{Float64,1}) = 30 | Vector3D(u[1],u[2],u[3]) 31 | end 32 | -------------------------------------------------------------------------------- /Module 3/Chapter03/hailstone.jl: -------------------------------------------------------------------------------- 1 | function hailstone(n) 2 | k = 1 3 | a = [n] 4 | while n > 1 5 | n = (n % 2 == 0) ? n >> 1 : 3n + 1 6 | push!(a,n) 7 | k += 1 8 | end 9 | a 10 | end 11 | -------------------------------------------------------------------------------- /Module 3/Chapter03/queens.jl: -------------------------------------------------------------------------------- 1 | qadd(board::Array{Vector{Int}}, 2 | qrow::Vector{Int}) = push!(copy(board), qrow) 3 | qhits(a::Array{Int}, b::Array{Int}) = 4 | any(a .== b) || abs(a-b)[1] == abs(a-b)[2] 5 | qhit(qrow::Vector{Int}, board::Array{Vector{Int}}) = 6 | any(map(x->qhits(qrow, x), board)) 7 | 8 | function qsolve(m, n=m, board=Array(Vector{Int}, 0)) 9 | if n == 0 10 | return board 11 | end 12 | for px = 1:m 13 | for py = 1:m 14 | if !qhit([px, py], board) 15 | s = qsolve(m, n-1, qadd (board, [px, py])) 16 | s != nothing && return s 17 | end 18 | end 19 | end 20 | return nothing 21 | end 22 | -------------------------------------------------------------------------------- /Module 3/Chapter03/vehicles-ex.jl: -------------------------------------------------------------------------------- 1 | using Vehicles; 2 | 3 | malcolm = Contact("Malcolm","malcolm@abc.net","07777555999"); 4 | myCar = Ford(malcolm, "Model T", 1000, 50.0); 5 | myBike = Scooter(malcolm, "Vespa", 125, 35.0); 6 | 7 | james = Contact("James","james@abc.net","07777666888"); 8 | jmCar = BMW(james,"Series 500", 3200, 125.0); 9 | jmBoat = Yacht(james,"Oceanis 44",14.6); 10 | jmBike = MotorBike(james, "Harley", 850, 120.0); 11 | 12 | david = Contact("David","dave@abc.net","07777222444"); 13 | dvCar = VW(david,"Golf", "diesel", "red", 1800, 85.0); 14 | dvBoat = Speedboat(david,"Sealine","petrol", 600, 45.0, 8.2); 15 | 16 | 17 | ----------------------- 18 | 19 | dsBoat.owner 20 | 21 | msCar 22 | msCar.owner = david; 23 | msCar 24 | 25 | s = [myCar, jmCar, dvCar] 26 | 3-element Array{Car,1}: 27 | Ford(Contact("Malcolm","malcolm@abc.net","07777555999"),"Model T","Petrol","Black",1000,50.0) 28 | BMW(Contact("James","james@abc.net","07777666888"),"Series 500","Petrol","Blue",3200,125.0) 29 | VW(Contact("David","dave@abc.net","07777222444"),"Golf","diesel","red",1800,85.0) 30 | 31 | for c in s 32 | who = c.owner.name 33 | model = c.make 34 | println("$who has a $model car") 35 | end 36 | 37 | s =[jmCar, jmBike, jmBoat] 38 | for c in s 39 | who = c.owner.name 40 | model = c.make 41 | println("$who has a $model vehicle") 42 | end 43 | 44 | print "James owns these vehicles: " 45 | for c in s 46 | print("$(s.make) ") 47 | end 48 | println() 49 | 50 | Series 500 51 | Oceanis 44 -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/README.1st: -------------------------------------------------------------------------------- 1 | This is a directory which contains poems by Charles Dodgson (aka Lewis Carroll). 2 | 3 | These are mainly from the Alice books but als contaions the Mad Gardener's Song fron Sylvie and Bruno and the poem The Hunting of the Snark which was published separately. 4 | 5 | -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/father-william.txt: -------------------------------------------------------------------------------- 1 | 'You are old, father William,' the young man said, 2 | 'And your hair has become very white; 3 | And yet you incessantly stand on your head - 4 | Do you think, at your age, it is right?' 5 | 6 | 'In my youth,' father William replied to his son, 7 | 'I feared it would injure the brain; 8 | But now that I'm perfectly sure I have none, 9 | Why, I do it again and again.' 10 | 11 | 'You are old,' said the youth, 'as I mentioned before, 12 | And have grown most uncommonly fat; 13 | Yet you turned a back-somersault in at the door - 14 | Pray, what is the reason of that?' 15 | 16 | 'In my youth,' said the sage, as he shook his grey locks, 17 | 'I kept all my limbs very supple 18 | By the use of this ointment - one shilling the box - 19 | Allow me to sell you a couple.' 20 | 21 | 'You are old,' said the youth, 'and your jaws are too weak 22 | For anything tougher than suet; 23 | Yet you finished the goose, with the bones and the beak - 24 | Pray, how did you manage to do it?' 25 | 26 | 'In my youth,' said his father, 'I took to the law, 27 | And argued each case with my wife; 28 | And the muscular strength, which it gave to my jaw, 29 | Has lasted the rest of my life.' 30 | 31 | 'You are old,' said the youth; one would hardly suppose 32 | That your eye was as steady as ever; 33 | Yet you balanced an eel on the end of your nose - 34 | What made you so awfully clever?' 35 | 36 | 'I have answered three questions, and that is enough,' 37 | Said his father; 'don't give yourself airs! 38 | Do you think I can listen all day to such stuff? 39 | Be off, or I'll kick you down stairs!' -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/jabber4.txt: -------------------------------------------------------------------------------- 1 | 'Twas brillig, and the slithy toves 2 | Did gyre and gimble in the wabe: 3 | All mimsy were the borogoves, 4 | And the mome raths outgrabe. 5 | -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/jabberwocky.rev: -------------------------------------------------------------------------------- 1 | And the mome raths outgrabe 2 | All mimsy were the borogoves, 3 | Did gyre and gimble in the wabe: 4 | 'Twas brillig, and the slithy toves 5 | 6 | He chortled in his joy. 7 | Oh frabjous day! Callooh! Callay!' 8 | Come to my arms, my beamish boy! 9 | 'And hast thou slain the Jabberwock? 10 | 11 | He went galumphing back. 12 | He left it dead, and with its head 13 | The vorpal blade went snicker-snack! 14 | One two! One two! And through and through 15 | 16 | And burbled as it came! 17 | Came whiffling through the tulgey wood, 18 | The Jabberwock, with eyes of flame, 19 | And, as in uffish thought he stood, 20 | 21 | And stood a while in thought. 22 | So rested he by the Tumtum tree, 23 | Long time the manxome foe he sought -- 24 | He took his vorpal sword in hand: 25 | 26 | The frumious Bandersnatch!' 27 | Beware the Jubjub bird, and shun 28 | The jaws that bite, the claws that catch! 29 | 'Beware the Jabberwock, my son! 30 | 31 | And the mome raths outgrabe. 32 | All mimsy were the borogoves, 33 | Did gyre and gimble in the wabe: 34 | 'Twas brillig, and the slithy toves 35 | -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/jabberwocky.txt: -------------------------------------------------------------------------------- 1 | 'Twas brillig, and the slithy toves 2 | Did gyre and gimble in the wabe: 3 | All mimsy were the borogoves, 4 | And the mome raths outgrabe. 5 | 6 | 'Beware the Jabberwock, my son! 7 | The jaws that bite, the claws that catch! 8 | Beware the Jubjub bird, and shun 9 | The frumious Bandersnatch!' 10 | 11 | He took his vorpal sword in hand: 12 | Long time the manxome foe he sought -- 13 | So rested he by the Tumtum tree, 14 | And stood a while in thought. 15 | 16 | And, as in uffish thought he stood, 17 | The Jabberwock, with eyes of flame, 18 | Came whiffling through the tulgey wood, 19 | And burbled as it came! 20 | 21 | One two! One two! And through and through 22 | The vorpal blade went snicker-snack! 23 | He left it dead, and with its head 24 | He went galumphing back. 25 | 26 | 'And hast thou slain the Jabberwock? 27 | Come to my arms, my beamish boy! 28 | Oh frabjous day! Callooh! Callay!' 29 | He chortled in his joy. 30 | 31 | 'Twas brillig, and the slithy toves 32 | Did gyre and gimble in the wabe: 33 | All mimsy were the borogoves, 34 | And the mome raths outgrabe 35 | -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/lobster-quadrille.txt: -------------------------------------------------------------------------------- 1 | 'Will you walk a little faster?' said a whiting to a snail, 2 | 'There's a porpoise close behind us, and he's treading on my tail. 3 | See how eagerly the lobsters and the turtles all advance! 4 | They are waiting on the shingle -- will you come and join the dance? 5 | Will you, won't you, will you, won't you, will you join the dance? 6 | Will you, won't you, will you, won't you, won't you join the dance? 7 | 8 | 'You can really have no notion how delightful it will be 9 | When they take us up and throw us, with the lobsters, out to sea!' 10 | But the snail replied 'Too far, too far!' and gave a look askance 11 | Said he thanked the whiting kindly, but he would not join the dance. 12 | Would not, could not, would not, could not, would not join the dance. 13 | Would not, could not, would not, could not, could not join the dance. 14 | 15 | 'What matters it how far we go?' his scaly friend replied. 16 | 'There is another shore, you know, upon the other side. 17 | The further off from England the nearer is to France -- 18 | Then turn not pale, beloved snail, but come and join the dance. 19 | Will you, won't you, will you, won't you, will you join the dance? 20 | Will you, won't you, will you, won't you, won't you joint the dance? -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/mad-gardeners-song.txt: -------------------------------------------------------------------------------- 1 | poet Lewis Carroll#59 on top 500 poetsPoet's PagePoemsCommentsStatsE-BooksBiographyShare on FacebookShare on Twitter 2 | Poems by Lewis Carroll : 74 / 74 « The Mad Gardener's Song 3 | The Mad Gardener's Song 4 | 5 | 6 | 7 | 8 | He thought he saw an Elephant, 9 | That practised on a fife: 10 | He looked again, and found it was 11 | A letter from his wife. 12 | 'At length I realise,' he said, 13 | The bitterness of Life!' 14 | 15 | He thought he saw a Buffalo 16 | Upon the chimney-piece: 17 | He looked again, and found it was 18 | His Sister's Husband's Niece. 19 | 'Unless you leave this house,' he said, 20 | 'I'll send for the Police!' 21 | 22 | He thought he saw a Rattlesnake 23 | That questioned him in Greek: 24 | He looked again, and found it was 25 | The Middle of Next Week. 26 | 'The one thing I regret,' he said, 27 | 'Is that it cannot speak!' 28 | 29 | He thought he saw a Banker's Clerk 30 | Descending from the bus: 31 | He looked again, and found it was 32 | A Hippopotamus. 33 | 'If this should stay to dine,' he said, 34 | 'There won't be much for us!' 35 | 36 | He thought he saw a Kangaroo 37 | That worked a coffee-mill: 38 | He looked again, and found it was 39 | A Vegetable-Pill. 40 | 'Were I to swallow this,' he said, 41 | 'I should be very ill!' 42 | 43 | He thought he saw a Coach-and-Four 44 | That stood beside his bed: 45 | He looked again, and found it was 46 | A Bear without a Head. 47 | 'Poor thing,' he said, 'poor silly thing! 48 | It's waiting to be fed!' 49 | 50 | He thought he saw an Albatross 51 | That fluttered round the lamp: 52 | He looked again, and found it was 53 | A Penny-Postage Stamp. 54 | 'You'd best be getting home,' he said: 55 | 'The nights are very damp!' 56 | 57 | He thought he saw a Garden-Door 58 | That opened with a key: 59 | He looked again, and found it was 60 | A Double Rule of Three: 61 | 'And all its mystery,' he said, 62 | 'Is clear as day to me!' 63 | 64 | He thought he saw a Argument 65 | That proved he was the Pope: 66 | He looked again, and found it was 67 | A Bar of Mottled Soap. 68 | 'A fact so dread,' he faintly said, 69 | 'Extinguishes all hope!' -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/voice-of-the-lobster.txt: -------------------------------------------------------------------------------- 1 | ''Tis the voice of the Lobster: I heard him declare 2 | 'You have baked me too brown, I must sugar my hair.' 3 | As a duck with its eyelids, so he with his nose 4 | Trims his belt and his buttons, and turns out his toes. 5 | When the sands are all dry, he is gay as a lark, 6 | And will talk in contemptuous tones of the Shark: 7 | But, when the tide rises and sharks are around, 8 | His voice has a timid and tremulous sound.' 9 | 10 | 'I passed by his garden, and marked, with one eye, 11 | How the Owl and the Panter were sharing a pie: 12 | The Panther took pie-crust, and gravy, and meat, 13 | While the Owl had the dish as its share of the treat. 14 | When the pie was all finished, the Owl, as a boon, 15 | Was kindly permitted to pocket the spoon: 16 | While the Panther received knife and fork with a growl, 17 | And concluded the banquet by eating the Owl. -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/walrus-amd-carpenter.out: -------------------------------------------------------------------------------- 1 | 124 626 3291 walrus-and-carpenter.txt 2 | -------------------------------------------------------------------------------- /Module 3/Chapter04/Alice/walrus-and-carpenter.out: -------------------------------------------------------------------------------- 1 | 124 626 3291 walrus-and-carpenter.txt 2 | -------------------------------------------------------------------------------- /Module 3/Chapter04/call_curl.jl: -------------------------------------------------------------------------------- 1 | const CURLOPT_URL = 10002 2 | const CURLOPT_FOLLOWLOCATION = 52; 3 | const CURLE_OK = 0 4 | jlo = "http://julialang.org"; 5 | curl = ccall( (:curl_easy_init, "libcurl"), Ptr{Uint8}, ()) 6 | ccall((:curl_easy_setopt, "libcurl"), Ptr{Uint8}, 7 | (Ptr{Uint8}, Int, Ptr{Uint8}), curl, CURLOPT_URL, jlo.data) 8 | ccall((:curl_easy_perform,"libcurl"), 9 | Ptr{Uint8}, (Ptr{Uint8},), curl) 10 | ccall((:curl_easy_cleanup,"libcurl"), 11 | Ptr{Uint8},(Ptr{Uint8},), curl); 12 | -------------------------------------------------------------------------------- /Module 3/Chapter04/compute_dot.jl: -------------------------------------------------------------------------------- 1 | function compute_dot(DX::Vector{Float64},DY::Vector{Float64}) 2 | assert(length(DX) == length(DY)) 3 | n = length(DX) 4 | incx = incy = 1 5 | product = ccall((:ddot, "libLAPACK"), 6 | Float64, 7 | (Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, 8 | Ptr{Float64}, Ptr{Int32}), 9 | &n, DX, &incx, DY, &incy) 10 | return product 11 | end 12 | -------------------------------------------------------------------------------- /Module 3/Chapter04/enum.jl: -------------------------------------------------------------------------------- 1 | @enum STATUS INFO WARNING ERROR FATAL 2 | ::Type{enum STATUS (INFO, WARNING, ERROR, FATAL)} 3 | 4 | INFO; # => INFO 5 | STATUS(0); # => INFO 6 | STATUS(1); # => WARNING 7 | typeof(INFO); # => enum STATUS (INFO, WARNING, ERROR, FATAL) 8 | 9 | The typeof(INFO) looks a bit strange so to see how this occurs let us look at the definition of the enum macro. 10 | 11 | macro enum(T,syms...) 12 | blk = quote 13 | immutable $(esc(T)) 14 | n::Int32 15 | $(esc(T))(n::Integer) = new(n) 16 | end 17 | Base.show(io::IO, x::$(esc(T))) = print(io, $syms[x.n+1]) 18 | Base.show(io::IO, x::Type{$(esc(T))}) 19 | = print(io, 20 | $(string("enum ", T, ' ', '(', join(syms, ", "), ')'))) 21 | end 22 | for (i,sym) in enumerate(syms) 23 | push!(blk.args, :(const $(esc(sym)) = $(esc(T))($(i-1)))) 24 | end 25 | push!(blk.args, :nothing) 26 | blk.head = :toplevel 27 | return blk 28 | end 29 | -------------------------------------------------------------------------------- /Module 3/Chapter04/simple-mr.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter04/simple-mr.jl -------------------------------------------------------------------------------- /Module 3/Chapter05/aapl-stats.jl: -------------------------------------------------------------------------------- 1 | 2 | using Dataframes, StatsBase 3 | aapl = readtable("AAPL-Short,csv"); 4 | 5 | naapl = size(aapl)[1] 6 | m1 = int(mean((aapl[:Volume]))); # => 6306547 7 | 8 | using Match 9 | wts = zeros(naapl); 10 | for i in 1:naapl 11 | dt = aapl[:Date][i] 12 | wts[i] = @match dt begin 13 | r"^2000" => 1.0 14 | r"^2001" => 2.0 15 | r"^2002" => 4.0 16 | _ => 0.0 17 | end 18 | end; 19 | 20 | wv = WeightVec(wts); 21 | m2 = int(mean(aapl[:Volume], wv)) 22 | mean(aapl[:Close]) 23 | mean(aapl[:Close], wv) 24 | trimmean(aapl[:Close], 0.1) 25 | 26 | std(aapl[:Close]) 27 | skewness(aapl[:Close]) 28 | kurtosis(aapl[:Close]) 29 | -------------------------------------------------------------------------------- /Module 3/Chapter05/data/Gcsemv.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter05/data/Gcsemv.rda -------------------------------------------------------------------------------- /Module 3/Chapter05/data/guImmun.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter05/data/guImmun.rda -------------------------------------------------------------------------------- /Module 3/Chapter05/data/juliaset.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter05/data/juliaset.pgm -------------------------------------------------------------------------------- /Module 3/Chapter05/data/negative.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter05/data/negative.pgm -------------------------------------------------------------------------------- /Module 3/Chapter05/jsetcolor.ppm: -------------------------------------------------------------------------------- 1 | P6 2 | 800 400 255 3 | -------------------------------------------------------------------------------- /Module 3/Chapter05/kdensity.jl: -------------------------------------------------------------------------------- 1 | using RDatasets, KernelDensity 2 | mlmf = dataset("mlmRev", "Gcsemv"); 3 | 4 | df = mlmf[complete_cases(mlmf[[:Written, :Course]]), :]; 5 | 6 | dc = array(df[:Course]); 7 | dcc = zeros(0); 8 | for i in 1:length(dc) 9 | if !isnan(dc[i]) 10 | push!(dcc,dc[i]) 11 | end 12 | end 13 | kdc = kde(dcc); 14 | 15 | dw = array(df[:Written]); 16 | dww = zeros(0); 17 | for i in 1:length(dw) 18 | if !isnan(dw[i]) 19 | push!(dww,dw[i]) 20 | end 21 | end 22 | kdw = kde(dww); 23 | 24 | using Winston 25 | kdc = kde(dcc); kdw = kde(dww); 26 | plot(kdc.x, kdc.density, "r--", kdw.x, kdw.density, "b;") 27 | 28 | -------------------------------------------------------------------------------- /Module 3/Chapter05/light-xml.jl: -------------------------------------------------------------------------------- 1 | using LightXML 2 | xdoc = parse_file("data/books.xml"); 3 | xtop = root(xdoc); 4 | println(name(xtop)); 5 | 6 | for c in child_nodes(xtop) 7 | if is_elementnode(c) 8 | e = XMLElement(c) 9 | t = find_element(e, "title") 10 | title = content(t) 11 | genre = attribute(t, "genre") 12 | @printf "%20s :%s\n" title genre 13 | end 14 | end 15 | 16 | for c in child_nodes(xtop) 17 | if is_elementnode(c) 18 | e = XMLElement(c) 19 | t = find_element(e, "title") 20 | genre = attribute(t, "genre") 21 | if genre == "Computing" 22 | a = find_element(e,"author") 23 | p = find_element(e,"price") 24 | curr = attribute(p, "currency") 25 | ds = find_element(e,"publish_date") 26 | desc = find_element(e,"description") 27 | println("Title: ", content(t)) 28 | println("Author: " ,content(a)) 29 | println("Date: " ,ds) 30 | println("Price: " ,p ," (", curr, ")") 31 | println(content(desc),"\n"); 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /Module 3/Chapter05/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | data = readcsv("data/gasoline.csv") 4 | 5 | # Get the columns that correspond with our X values 6 | # and create a new matrix to hold them 7 | # syntax: data[row, column] 8 | # to get a whole row do data[row, :] 9 | # to get a whole column do data[:, column] 10 | # to get a range of columns do data[:, column_a:column_b] 11 | 12 | x = data[:, 2:4] 13 | y = data[:, 6] 14 | 15 | # Call linreg 16 | coefs = linreg(x, y) 17 | -------------------------------------------------------------------------------- /Module 3/Chapter05/mainols.jl: -------------------------------------------------------------------------------- 1 | include("./ols.jl") 2 | 3 | data = readcsv("data/gasoline.csv") 4 | 5 | # Get the columns that correspond with our X values 6 | # and create a new matrix to hold them 7 | # syntax: data[row, column] 8 | # to get a whole column do data[:, column] 9 | # to get a whole row do data[row, :] 10 | x = [data[:,2] data[:,3] data[:,4]] 11 | y = data[:,6] 12 | 13 | # Create a new OLS object 14 | reg = ols.tols(y, x, "Octane Rating", ["Error", "Component 1", "Component 2", "Component 3"]) 15 | 16 | -------------------------------------------------------------------------------- /Module 3/Chapter05/netpbm.jl: -------------------------------------------------------------------------------- 1 | 2 | function pseudocolor(pix::Uint8) 3 | if pix < 64 4 | pr = uint8(0) 5 | pg = uint8(0) 6 | pb = uint8(4*pix) 7 | elseif pix < 128 8 | pr = uint8(0) 9 | pg = uint8(4*(pix-64)) 10 | pb = uint8(255) 11 | elseif pix < 192 12 | pr = uint8(0) 13 | pg = uint8(255) 14 | pb = uint8(4*(192 - pix)) 15 | else 16 | pr = uint8(4*(pix - 192)) 17 | pg = uint8(4*(256 - pix)) 18 | pb = uint8(0) 19 | end 20 | return (pr, pg, pb) 21 | end 22 | 23 | img = open("data/juliaset.pgm"); 24 | magic = chomp(readline(img)); # => "P5" 25 | if magic == "P5" 26 | out = open("jsetcolor.ppm", "w"); 27 | println(out, "P6"); 28 | params = chomp(readline(img)); # => "800 400 255" 29 | println(out, params); 30 | (wd, ht, pmax) = int(split(params)); 31 | for i = 1:ht 32 | buf = readbytes(img, wd); 33 | for j = 1:wd 34 | (r,g,b) = pseudocolor(buf[j]); 35 | write(out,r); write(out,g); write(out,b); 36 | end 37 | end 38 | close(out); 39 | else 40 | error("Not a NetPBM grayscale file") 41 | end 42 | close(img); 43 | 44 | -------------------------------------------------------------------------------- /Module 3/Chapter05/quotes.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter05/quotes.db -------------------------------------------------------------------------------- /Module 3/Chapter06/bank-teller.jl: -------------------------------------------------------------------------------- 1 | using SimJulia 2 | using Distributions 3 | 4 | systime() = ccall((:time, "libc"), Int32, ()); 5 | randomize() = srand(systime()); 6 | 7 | function visit(customer::Process, 8 | time_in_bank::Float64, 9 | counter::Resource, 10 | max_in_queue::Int) 11 | arrive = now(customer); 12 | @printf("%8.4f %s: Here I am\n", arrive, customer); 13 | if length(counter.wait_queue) < max_in_queue 14 | request(customer, counter); 15 | wait = now(customer) - arrive; 16 | @printf("%8.4f %s: Waited %6.3f\n", 17 | now(customer), customer, wait); 18 | hold(customer, time_in_bank) 19 | release(customer, counter); 20 | @printf("%8.4f %s: Finished\n", now(customer), customer) 21 | else 22 | @printf("%8.4f %s: Waiting\n", now(customer), customer) 23 | end 24 | end 25 | 26 | function generate(source::Process, number::Int, 27 | mean_time_between_arrivals::Float64, 28 | mean_time_in_bank::Float64, 29 | counter::Resource, 30 | max_in_queue::Int) 31 | d_tba = Exponential(mean_time_of_arrivals); 32 | d_tib = Exponential(mean_time_in_bank); 33 | for i = 1:number 34 | c = Process(simulation(source), 35 | @sprintf("Customer%02d", i)); 36 | tib = rand(d_tib); 37 | activate(c, now(source), visit, tib, 38 | counter, max_in_queue); 39 | tba = rand(d_tba); 40 | hold(source, tba); 41 | end 42 | end 43 | 44 | function number_in_system(counter::Resource) 45 | length(counter.active_set) + length(counter.wait_queue); 46 | end 47 | 48 | # Set simulation data 49 | 50 | max_number = 8; 51 | max_time = 4000.0; 52 | max_in_queue = 1; 53 | mean_time_of_arrivals = 10.0; 54 | mean_time_in_bank = 12.0; 55 | number_of_counters = 1; 56 | randomize(); 57 | # a value to make run reproducible 58 | 59 | # Model/Experiment 60 | sim = Simulation(uint(16)); 61 | k = Resource(sim, "Counter", uint(1), false); 62 | s = Process(sim, "Source"); 63 | activate(s, 0.0, generate, max_number, mean_time_of_arrivals, 64 | mean_time_in_bank, k, max_in_queue); 65 | run(sim, max_time); 66 | -------------------------------------------------------------------------------- /Module 3/Chapter06/banky.jl: -------------------------------------------------------------------------------- 1 | using SimJulia 2 | using Distributions 3 | 4 | function visit(customer::Process, 5 | time_in_bank::Float64, 6 | counter::Resource, 7 | max_in_queue::Int) 8 | arrive = now(customer); 9 | @printf("%8.4f %s: Here I am\n", arrive, customer); 10 | if length(counter.wait_queue) < max_in_queue 11 | request(customer, counter); 12 | wait = now(customer) – arrive; 13 | @printf("%8.4f %s: Waited %6.3f\n", 14 | now(customer), customer, wait); 15 | hold(customer, time_in_bank) 16 | release(customer, counter); 17 | @printf("%8.4f %s: Finished\n", now(customer), customer) 18 | else 19 | @printf("%8.4f %s: Waiting\n", now(customer), customer) 20 | end 21 | end 22 | 23 | 24 | function generate(source::Process, number::Int, 25 | mean_time_between_arrivals::Float64, 26 | mean_time_in_bank::Float64, 27 | counter::Resource, 28 | max_in_queue::Int) 29 | d_tba = Exponential(mean_time_of_arrivals); 30 | d_tib = Exponential(mean_time_in_bank); 31 | for i = 1:number 32 | c = Process(simulation(source), 33 | @sprintf("Customer%02d", i)); 34 | tib = rand(d_tib); 35 | activate(c, now(source), visit, tib, 36 | counter, max_in_queue); 37 | tba = rand(d_tba); 38 | hold(source, tba); 39 | end 40 | end 41 | 42 | function number_in_system(counter::Resource) 43 | length(counter.active_set) + length(counter.wait_queue); 44 | end 45 | 46 | # Set simulation data 47 | max_number = 8; 48 | max_time = 3900.0; 49 | max_queue = 1; 50 | mean_arrival_time = 10.0; 51 | mean_service_time = 12.0; 52 | number_of_tellers = 1; 53 | seed = randomize(); # Use function defined early or pick 54 | # a value to make run reproducible 55 | 56 | # Model/Experiment 57 | srand(seed); 58 | sim = Simulation(uint(16)); 59 | k = Resource(sim, "Counter", uint(1), false); 60 | s = Process(sim, "Source"); 61 | activate(s, 0.0, generate, 62 | max_number, mean_arrival_time, 63 | mean_service_time, k, max_queue); 64 | run(sim, max_time); 65 | -------------------------------------------------------------------------------- /Module 3/Chapter06/dogs.wsv: -------------------------------------------------------------------------------- 1 | 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 | 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 3 | 0 0 0 0 0 1 1 0 1 1 0 0 1 1 0 1 0 1 1 1 1 1 1 1 1 4 | 0 1 1 0 0 1 1 1 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 5 | 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 6 | 0 0 0 0 0 0 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 7 | 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 8 | 0 0 0 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9 | 0 0 0 0 0 1 0 1 0 1 1 0 1 0 0 0 1 1 1 1 1 0 1 1 0 10 | 0 0 0 0 1 0 0 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 11 | 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 | 0 0 0 0 0 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 13 | 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 14 | 0 0 0 0 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 15 | 0 0 0 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 16 | 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 17 | 0 1 0 1 0 0 0 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 18 | 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 19 | 0 1 0 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 20 | 0 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 21 | 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 22 | 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 23 | 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 24 | 0 0 0 0 0 0 0 0 1 1 1 0 1 0 0 0 1 1 0 1 1 1 1 1 1 25 | 0 0 0 0 0 0 1 1 0 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 26 | 0 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 27 | 0 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 28 | 0 0 0 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 29 | 0 0 0 0 1 1 0 0 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 30 | 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 31 | -------------------------------------------------------------------------------- /Module 3/Chapter06/exotherm1.jl: -------------------------------------------------------------------------------- 1 | using Sundials 2 | function exotherm(t, x, dx; n=1, a=1, b=1) 3 | p = x[2]^n * exp(x[1]) 4 | dx[1] = p - a*x[1] 5 | dx[2] = -b*p 6 | return(dx) 7 | end; 8 | 9 | t = linspace(0.0,5.0,1001); 10 | fexo(t,x,dx) = exotherm(t, x, dx, a=0.6, b=0.1); 11 | 12 | x1 = Sundials.cvode(fexo, [0.9, 1.0], t); 13 | using Winston 14 | plot(t,x1[:,1])) 15 | -------------------------------------------------------------------------------- /Module 3/Chapter06/knapsack.jl: -------------------------------------------------------------------------------- 1 | using JuMP 2 | N = 6; 3 | m = Model(); # Use default solver 4 | @defVar(m, x[1:N], Bin); # Define array variable to hold results 5 | profit = [ 5, 3, 2, 7, 4, 4 ]; # Profit vector of size N 6 | weight = [ 2, 8, 4, 2, 5, 6 ]; # Weights vector of size 7 | 8 | maxcap = 12; 9 | @setObjective(m, Max, dot(profit, x)); 10 | @addConstraint(m, dot(weight, x) <= maxcap); 11 | 12 | status = solve(m); # Solve problem using MIP solver 13 | @printf "Value of the objective is %.1f" getObjectiveValue(m); 14 | 15 | println("Solution is:") 16 | for i = 1:N 17 | print("x[$i] = ", getValue(x[i])); 18 | println(", p[$i]/w[$i] = ", profit[i]/weight[i]); 19 | end 20 | 21 | -------------------------------------------------------------------------------- /Module 3/Chapter06/lena.jl: -------------------------------------------------------------------------------- 1 | img = open("lena.pgm"); 2 | magic = chomp(readline(img)); 3 | params = chomp(readline(img)); 4 | 5 | pm = split(params); 6 | wd = int(pm[1]); 7 | ht = int(pm[2]); 8 | 9 | data = uint8(readbytes(img,wd*ht)); 10 | data = reshape(data,wd,ht); 11 | close(img); 12 | 13 | dout = copy(data); 14 | for i = 2:wd-1 15 | for j = 2:ht-1 16 | temp = data[i-1:i+1, j-1:j+1]; 17 | x = sum(Gx.*temp) 18 | y = sum(Gy.*temp) 19 | p = int(sqrt(x*x + y*y)) 20 | dout[i,j] = (p < 256) ? uint8(p) : 0xff 21 | end 22 | end 23 | out = open("lenaX.pgm","w"); 24 | println(out,magic); 25 | println(out,params); 26 | write(out,dout); 27 | close(out); 28 | 29 | 30 | -------------------------------------------------------------------------------- /Module 3/Chapter06/lena.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter06/lena.pgm -------------------------------------------------------------------------------- /Module 3/Chapter06/lenaX.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter06/lenaX.pgm -------------------------------------------------------------------------------- /Module 3/Chapter06/lotka-volterra.jl: -------------------------------------------------------------------------------- 1 | using ODE 2 | 3 | function F(t,x,p) 4 | d1 = p[1]*x[1] - p[2]*x[1]*x[2] 5 | d2 = -p[3]*x[2] + p[4]*x[1]*x[2] - p[5]*x[2]*x[3] 6 | d3 = -p[6]*x[3] + p[7]*x[2]*x[3] 7 | [d1, d2, d3] 8 | end 9 | 10 | pp = ones(7); # Choose all parameters as 1.0 11 | x0 = [0.5, 1.0, 2.0]; # Setup the initial conditions 12 | tspan = [0.0:0.1:10.0]; # and the time range 13 | 14 | (t,x) = ODE.ode23((t,x) -> F(t,x,pp), x0, tspan); 15 | 16 | n = length(t); 17 | y1 = zeros(n); [y1[i] = x[i][1] for i = 1:n]; 18 | y2 = zeros(n); [y2[i] = x[i][2] for i = 1:n]; 19 | y3 = zeros(n); [y3[i] = x[i][3] for i = 1:n]; 20 | 21 | using Winston 22 | plot(t,y1,"b.",t,y2,"g-.",t,y3,"r--") 23 | 24 | -------------------------------------------------------------------------------- /Module 3/Chapter06/main-dsp.jl: -------------------------------------------------------------------------------- 1 | using DSP, Distributions 2 | 3 | t = linspace(0,5pi,512); 4 | x1 = sin(t); 5 | x2 = 0.4*cos(4t); 6 | x3 = 0.2*cos(8t); 7 | x = x1 + x2 + x3; 8 | 9 | responsetype = Lowpass(0.2) 10 | prototype = Elliptic(4, 0.5, 30) 11 | tf = convert(TFFilter, digitalfilter(responsetype, prototype)) 12 | numerator_coefs = coefb(tf) 13 | denominator_coefs = coefa(tf) 14 | 15 | responsetype = Bandpass(10, 40; fs=1000) 16 | prototype = Butterworth(4) 17 | xb = filt(digitalfilter(responsetype, prototype), x); 18 | 19 | using Winston 20 | plot(xb) 21 | -------------------------------------------------------------------------------- /Module 3/Chapter06/main-nlopt.jl: -------------------------------------------------------------------------------- 1 | using NLopt 2 | count = 0; 3 | function myfunc(x::Vector, grad::Vector) 4 | if length(grad) > 0 5 | grad[1] = 0 6 | grad[2] = 0.5/sqrt(x[2]) 7 | end 8 | global count; 9 | count::Int += 1; 10 | sqrt(x[2]); 11 | end 12 | 13 | function mycons(x::Vector, grad::Vector, a, b) 14 | if length(grad) > 0 15 | grad[1] = 3*a * (a*x[1] + b)^2 16 | grad[2] = -1 17 | end 18 | (a*x[1] + b)^3 - x[2] 19 | end 20 | 21 | opt = Opt(:LD_MMA, 2); 22 | lower_bounds!(opt, [-Inf, 0.]); 23 | xtol_rel!(opt,1e-4); 24 | min_objective!(opt, myfunc); 25 | 26 | inequality_constraint!(opt, (x,g) -> mycons(x,g,2,0), 1e-8); 27 | inequality_constraint!(opt, (x,g) -> mycons(x,g,-1,1), 1e-8); 28 | 29 | (minf,minx,ret) = optimize(opt, [1.2, 5.6]); 30 | @printf "Ans => %6.3f at (%6.3f,%6.3f)" minf minx[1] minx[2]; 31 | 32 | -------------------------------------------------------------------------------- /Module 3/Chapter06/mcmc-dogs.jl: -------------------------------------------------------------------------------- 1 | using Mamba, Distributions 2 | 3 | dogs = (Symbol => Any)[:Y => int(readdlm("dogs.wsv")) ]; 4 | dogs[:Dogs] = size(dogs[:Y], 1); 5 | dogs[:Trials] = size(dogs[:Y], 2); 6 | dogs[:xa] = mapslices(cumsum, dogs[:Y], 2); 7 | dogs[:xs] = mapslices(x -> [1:25] - x, dogs[:xa], 2); 8 | dogs[:y] = 1 - dogs[:Y][:, 2:25]; 9 | 10 | model = Model( 11 | y = Stochastic(2, 12 | @modelexpr(Dogs, Trials, alpha, xa, beta, xs, 13 | Distribution[ 14 | begin 15 | p = exp(alpha * xa[i,j] + beta * xs[i,j]) 16 | Bernoulli(p) 17 | end 18 | for i in 1:Dogs, j in 1:Trials-1]), 19 | false), 20 | alpha = Stochastic(:(Truncated(Flat(), -Inf, -1e-5))), 21 | A = Logical(@modelexpr(alpha,exp(alpha))), 22 | beta = Stochastic(:(Truncated(Flat(), -Inf, -1e-5))), 23 | B = Logical(@modelexpr(beta,exp(beta))) ); 24 | 25 | inits = [ 26 | [:y => dogs[:y], :alpha => -1, :beta => -1], 27 | [:y => dogs[:y], :alpha => -2, :beta => -2] 28 | ]; 29 | 30 | scheme = [Slice([:alpha, :beta], [1.0, 1.0])]; 31 | setsamplers!(model, scheme); 32 | sim = 33 | mcmc(model,dogs,inits,10000,burnin=2500,thin=2, chains=2); 34 | 35 | -------------------------------------------------------------------------------- /Module 3/Chapter06/sinusoids.jl: -------------------------------------------------------------------------------- 1 | using Winston 2 | fq = 500.0; 3 | N = 512; 4 | T = 6 / fq; 5 | td = linspace(0, T, N); 6 | x1 = sin(2pi * fq * td); 7 | x2 = cos(8pi * fq * td); 8 | x3 = cos(16pi * fq * td); 9 | x = x1 + 0.4*x2 + 0.2*x3 10 | plot(td, x) 11 | -------------------------------------------------------------------------------- /Module 3/Chapter07/cairo-stroke.jl: -------------------------------------------------------------------------------- 1 | using Cairo 2 | c = CairoRGBSurface(512, 128); 3 | cr = CairoContext(c); 4 | save(cr); 5 | set_source_rgb(cr, 0.8, 0.8, 0.8); # light gray 6 | rectangle(cr, 0.0, 0.0, 512.0, 128.0); # background 7 | fill(cr); 8 | restore(cr); 9 | save(cr); 10 | 11 | x0=51.2; y0=64.0; 12 | x1=204.8; y1=115.4; 13 | x2=307.2; y2=12.8; 14 | x3=460.8; y3=64.0; 15 | 16 | move_to (cr, x0, y0); 17 | curve_to (cr, x1, y1, x2, y2, x3, y3); 18 | set_line_width (cr, 10.0); 19 | stroke (cr); 20 | restore(cr); 21 | 22 | move_to(cr, 12.0, 12.0); 23 | set_source_rgb (cr, 0, 0, 0); 24 | show_text(cr,"Stroke"); 25 | write_to_png(c,"stroke.png"); 26 | -------------------------------------------------------------------------------- /Module 3/Chapter07/gaston-ex1.jl: -------------------------------------------------------------------------------- 1 | using Gaston 2 | g = Gaston; 3 | set_terminal("x11"); 4 | 5 | c = g.CurveConf(); 6 | c.legend = "Random"; 7 | c.plotstyle = "errorbars"; 8 | 9 | y = exp(-(1:.1:4.9)); 10 | ylow = y - 0.05*rand(40); 11 | yhigh = y + 0.05*rand(40); 12 | g.addcoords(1:40,y,c); 13 | g.adderror(0.1*rand(40)); 14 | 15 | a = g.AxesConf(); 16 | a.title = "Error bars (ydelta)"; 17 | g.addconf(a); 18 | g.llplot(); 19 | 20 | -------------------------------------------------------------------------------- /Module 3/Chapter07/gaston-ex2.jl: -------------------------------------------------------------------------------- 1 | using Gaston 2 | g = Gaston; 3 | 4 | set_terminal("x11"); 5 | 6 | c = g.CurveConf(); 7 | c.plotstyle = "pm3d"; 8 | 9 | x = -15:0.33:15; 10 | y = -15:0.33:15; 11 | Z = g.meshgrid(x, y, (x,y) -> sin(sqrt(x .* x+y .* y)) 12 | / sqrt(x .* x+y .* y)); 13 | g.addcoords(x,y,Z,c); 14 | 15 | a = g.AxesConf(); 16 | a.title = "3D: Sombrero"; 17 | g.addconf(a); 18 | g.llplot() 19 | 20 | -------------------------------------------------------------------------------- /Module 3/Chapter07/plotly-ex1.jl: -------------------------------------------------------------------------------- 1 | using Plotly 2 | 3 | # Signin with your userid and password 4 | Plotly.signin("myuserid", "abc32def7g") 5 | 6 | trace1 = [ 7 | "x" => [0, 1, 2, 3, 4, 5, 6, 7, 8], 8 | "y" => [8, 7, 6, 5, 4, 3, 2, 1, 0], 9 | "type" => "scatter" 10 | ]; 11 | trace2 = [ 12 | "x" => [0, 1, 2, 3, 4, 5, 6, 7, 8], 13 | "y" => [0, 1, 2, 3, 4, 5, 6, 7, 8], 14 | "type" => "scatter" 15 | ]; 16 | data = [trace1, trace2]; 17 | 18 | layout = [ 19 | "xaxis" => ["type" => "log", "autorange" => true], 20 | "yaxis" => ["type" => "log", "autorange" => true] 21 | ]; 22 | 23 | response = Plotly.plot(data, 24 | ["layout" => layout, 25 | "filename" => "plotly-log-axes", 26 | "fileopt" => "overwrite"]); 27 | 28 | plot_url = response["url"] 29 | -------------------------------------------------------------------------------- /Module 3/Chapter07/plotly-ex2.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter07/plotly-ex2.jl -------------------------------------------------------------------------------- /Module 3/Chapter07/sierp1.svg: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Module 3/Chapter07/sierp3.svg: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Module 3/Chapter07/sierpinski.jl: -------------------------------------------------------------------------------- 1 | using Compose 2 | function sierpinski(n) 3 | if n == 0 4 | compose(context(), polygon([(1,1), (0,1), (1/2, 0)])); 5 | else 6 | t = sierpinski(n - 1); 7 | compose( context(), (context( 1/4, 0, 1/2, 1/2), t), 8 | (context( 0, 1/2, 1/2, 1/2), t), 9 | (context( 1/2, 1/2, 1/2, 1/2), t)); 10 | end 11 | end 12 | 13 | cx1 = compose(sierpinski(1), linewidth(0.2mm), 14 | fill(nothing), stroke("black")); 15 | img = SVG("sierp1.svg", 10cm, 8.66cm); draw(img,cx1) 16 | 17 | cx3 = compose(sierpinski(3), linewidth(0.2mm), 18 | fill(nothing), stroke("black")); 19 | img = SVG("sierp3.svg", 10cm, 8.66cm); draw(img,cx3) 20 | 21 | cx5 = compose(sierpinski(5), linewidth(0.2mm), 22 | fill(nothing), stroke("black")); 23 | img = SVG("sierp5.svg", 10cm, 8.66cm); draw(img,cx5) 24 | 25 | 26 | -------------------------------------------------------------------------------- /Module 3/Chapter07/stroke.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter07/stroke.png -------------------------------------------------------------------------------- /Module 3/Chapter07/winston-graph.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter07/winston-graph.jl -------------------------------------------------------------------------------- /Module 3/Chapter07/xkcd-graph.jl: -------------------------------------------------------------------------------- 1 | using PyPlot 2 | 3 | xkcd() 4 | fig = figure(figsize=(10,5)) 5 | ax = axes() 6 | 7 | x = linspace(1,10,101) 8 | y = sin(3x + cos(5x)) 9 | p = plot(x,y) 10 | 11 | ax[:set_xlim]([0.0,6]) 12 | annotate("A little\nsketchy",xy=[0.98,.001], 13 | arrowprops=["arrowstyle"=>"->"],xytext=[1.3,-0.3]) 14 | 15 | xticks([]) 16 | yticks([]) 17 | xlabel("TIME") 18 | ylabel("PRODUCTIVITY") 19 | title("An xkcd-style plot in Julia") 20 | 21 | ax[:spines]["top"][:set_color]("none") 22 | ax[:spines]["right"][:set_color]("none") 23 | 24 | 25 | -------------------------------------------------------------------------------- /Module 3/Chapter08/Quotes/build.sql: -------------------------------------------------------------------------------- 1 | create table categories ( 2 | id integer not null, 3 | catname varchar(40) not null, 4 | primary key(id) 5 | ); 6 | 7 | create table quotes ( 8 | id integer not null, 9 | cid integer not null, 10 | author varchar(100), 11 | quoname varchar(250) not null, 12 | primary key(id) 13 | ); 14 | 15 | -------------------------------------------------------------------------------- /Module 3/Chapter08/Quotes/etl.jl: -------------------------------------------------------------------------------- 1 | #! /Users/malcolm/bin/julia 2 | # 3 | # Check on the number of arguments, print usage unless 1 or 2. 4 | nargs = length(ARGS); 5 | if nargs == 0 || nargs > 2 6 | println("usage: etl.jl infile [outfile]"); 7 | exit(); 8 | end 9 | 10 | # Assign first argument to input file 11 | # If second argument this is the output file otherwise STDOUT 12 | infile = ARGS[1]; 13 | if nargs == 2 14 | outfile = ARGS[2]; 15 | try 16 | outf = open(outfile,"w"); 17 | catch 18 | error("Can't create output file: ", outfile); 19 | end 20 | else 21 | outf = STDOUT; 22 | end 23 | 24 | # One liner to double up single quotes 25 | escticks(s) = replace(s,"'","''"); 26 | 27 | # Read all file into a matrix, first dimensions is number of lines 28 | qq = readdlm("quotes.tsv",'\t'); 29 | n = size(qq)[1]; 30 | 31 | # Going to store all categories in a dictionary 32 | j = 0; 33 | cats = Dict(); 34 | 35 | # Main loop to load up the quotes table 36 | for i = 1:n 37 | cat = qq[i,1]; 38 | if haskey(cats,cat) 39 | jd = cats[cat]; 40 | else 41 | j = j + 1; jd = j; 42 | cats[cat] = jd; 43 | end 44 | sql = "insert into quotes values($i,$jd,"; 45 | if (length(qq[i,2]) > 0) 46 | sql *= string("'", escticks(qq[i,2]), "',"); 47 | else 48 | sql *= string("null,"); 49 | end 50 | sql *= string("'", escticks(qq[i,3]), "');"); 51 | write(outf,"$sql\n"); 52 | end 53 | 54 | # Now dump the categories 55 | for cat = keys(cats) 56 | jd = cats[cat]; 57 | write(outf,"insert into categories values($jd,'$cat');\n"); 58 | end 59 | 60 | close(outf); # Will have no effect if outf = STDOUT 61 | 62 | -------------------------------------------------------------------------------- /Module 3/Chapter08/Quotes/q.sql: -------------------------------------------------------------------------------- 1 | insert into categories values(5,'Books & Plays'); 2 | insert into categories values(6,'Classics'); 3 | insert into categories values(2,'Science'); 4 | insert into categories values(4,'Politics'); 5 | insert into categories values(1,'Words of Wisdom'); 6 | -------------------------------------------------------------------------------- /Module 3/Chapter08/Quotes/quotes.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter08/Quotes/quotes.db -------------------------------------------------------------------------------- /Module 3/Chapter08/Quotes/quotes.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter08/Quotes/quotes.xlsx -------------------------------------------------------------------------------- /Module 3/Chapter08/build.sql: -------------------------------------------------------------------------------- 1 | create table categories ( 2 | id integer not null, 3 | catname varchar(40) not null, 4 | primary key(id) 5 | ); 6 | 7 | create table quotes ( 8 | id integer not null, 9 | cid integer not null, 10 | author varchar(100), 11 | quoname varchar(250) not null, 12 | primary key(id) 13 | ); 14 | 15 | -------------------------------------------------------------------------------- /Module 3/Chapter08/chinook-odbc.jl: -------------------------------------------------------------------------------- 1 | using ODBC 2 | 3 | conn = ODBC.connect("Chinook",usr="malcolm",pwd="mypasswd") 4 | res = ODBC.query("select count(*) from Customers", conn) 5 | println("Number of customers: $(res[:K][1])") 6 | 7 | sql = "select a.LastName, a.FirstName,"; 8 | sql *= " count(b.InvoiceId) as Invs, sum(b.Total) as Amt"; 9 | sql *= " from Customer a"; 10 | sql *= " join Invoice b on a.CustomerId = b.CustomerId"; 11 | sql *= " group by a.LastName having Amt >= 45.00"; 12 | sql *= " order by Amt desc;"; 13 | 14 | res = ODBC.query(sql); 15 | 16 | for i in 1:size(res)[1] 17 | LastName = res[:LastName][i] 18 | FirstName = res[:FirstName][i] 19 | Invs = res[:Invs][i] 20 | Amt = res[:Amt][i] 21 | @printf "%10s %10s %4d %10.2f\n" LastName FirstName Invs Amt 22 | end 23 | 24 | sql = "select a.LastName, a.FirstName, d.Name as TrackName"; 25 | sql *= " from Customer a"; 26 | sql *= " join Invoice b on a.CustomerId = b.CustomerId"; 27 | sql *= " join InvoiceLine c on b.InvoiceId = c.InvoiceId"; 28 | sql *= " join Track d on c.TrackId = d.TrackId"; 29 | sql *= " where a.LastName = 'Cunningham' limit 5;"; 30 | 31 | res = ODBC.query(sql); 32 | 33 | for i in 1:size(res)[1] 34 | LastName = res[:LastName][i] 35 | FirstName = res[:FirstName][i] 36 | TrackName = res[:TrackName][i] 37 | @printf "%15s %15s %15s\n" LastName FirstName TrackName 38 | end 39 | 40 | 41 | -------------------------------------------------------------------------------- /Module 3/Chapter08/couchdb-books.jl: -------------------------------------------------------------------------------- 1 | using HTTPClient.HTTPC, JSON 2 | cdb = "http://localhost:5984"; 3 | dbs = bytestring(get("$cdb/_all_dbs).body.data); 4 | JSON.parse(dbs); # => ["_replicator", "_users", "_quotes"] 5 | 6 | qc = cdb * "/quotes"; 7 | ropts = RequestOptions(content_type="application/json"); 8 | 9 | json = "{category:\"Computing\",author:\"Scott's Law\", 10 | \"quote\":\"Adding manpower to a late software project makes it later\"})"; 11 | HTTPC.post(qc, json, ropts); 12 | 13 | json = JSON.parse(docs.body.data)); 14 | 15 | json["total_rows"]; # => 35 16 | json["rows"][24]; # Pick out an specific record 17 | Dict{String,Any} with 3 entries: 18 | "key" => "d075d58c26d256c49b965a02cc00b77a" 19 | "id" => "d075d58c26d256c49b965a02cc00b77a" 20 | "value" => ["rev"=>"1-524b4b2c577e2eaff31f4b665cd48055"] 21 | key = json["rows"][24]["key"]; 22 | rev = json["rows"][24]["value"]["rev"]; 23 | 24 | JSON.parse(bytestring(get("$qc/$key").body.data)) 25 | Dict{String,Any} with 5 entries: 26 | "quote" => 27 | "To love oneself is the beginning of a lifelong romance" 28 | "_rev" => "1-524b4b2c577e2eaff31f4b665cd48055" 29 | "author" => "Oscar Wilde" 30 | "_id" => "d075d58c26d256c49b965a02cc00b77a" 31 | "category" => "Books & Plays" 32 | 33 | json = "{category:\"Books & Plays\",author:\"Oscar Wilde\", 34 | \"quote\":\"I can resist everything but temptation\"})"; 35 | HTTPC.post("$qc/$key", json, ropts); 36 | 37 | -------------------------------------------------------------------------------- /Module 3/Chapter08/etl.jl: -------------------------------------------------------------------------------- 1 | #! /Users/malcolm/bin/julia 2 | # 3 | # Check on the number of arguments, print usage unless 1 or 2. 4 | nargs = length(ARGS); 5 | if nargs == 0 || nargs > 2 6 | println("usage: etl.jl infile [outfile]"); 7 | exit(); 8 | end 9 | 10 | # Assign first argument to input file 11 | # If second argument this is the output file otherwise STDOUT 12 | infile = ARGS[1]; 13 | if nargs == 2 14 | outfile = ARGS[2]; 15 | try 16 | outf = open(outfile,"w"); 17 | catch 18 | error("Can't create output file: ", outfile); 19 | end 20 | else 21 | outf = STDOUT; 22 | end 23 | 24 | # One liner to double up single quotes 25 | escticks(s) = replace(s,"'","''"); 26 | 27 | # Read all file into a matrix, first dimensions is number of lines 28 | qq = readdlm("quotes.tsv",'\t'); 29 | n = size(qq)[1]; 30 | 31 | # Going to store all categories in a dictionary 32 | j = 0; 33 | cats = Dict(String,Int64); 34 | 35 | # Main loop to load up the quotes table 36 | for i = 1:n 37 | cat = qq[i,1]; 38 | if haskey(cats,cat) 39 | jd = cats[cat]; 40 | else 41 | j = j + 1; jd = j; 42 | cats[cat] = jd; 43 | end 44 | sql = "insert into quotes values($i,$jd,"; 45 | if (length(qq[i,2]) > 0) 46 | sql *= string("'", escticks(qq[i,2]), "',"); 47 | else 48 | sql *= string("null,"); 49 | end 50 | sql *= string("'", escticks(qq[i,3]), "');"); 51 | wrlte(outf,"$sql\n"); 52 | end 53 | 54 | # Now dump the categories 55 | for cat = keys(cats) 56 | jd = cats[cat]; 57 | write(outf,"insert into categories($jd,'$cat');\n"); 58 | end 59 | 60 | close(outf); # Will have no effect if outf = STDOUT 61 | 62 | -------------------------------------------------------------------------------- /Module 3/Chapter08/mysql-dbi.jl: -------------------------------------------------------------------------------- 1 | # Skipping the argument processing 2 | # Assuming that the input file is quotes.tsv 3 | # and using the test database 4 | 5 | Using DBI 6 | Using MySQL 7 | 8 | escticks(s) = replace(s,"'","''"); 9 | qq = readdlm("quotes.tsv",'\t'); 10 | n = size(qq)[1]; 11 | conn = connect(MySQL5,"localhost","malcolm","mypasswd","test"); 12 | 13 | # We can create the categories table and quotes tables: 14 | sql = "create table categories "; 15 | sql *= "(id integer primary key, "; 16 | sql *= catname varchar(40) not null); 17 | execute(prepare(conn,sql); 18 | if (errcode(conn) > 0) 19 | error("Can't build categories table") 20 | end; 21 | 22 | # Note: Similar code for building the quotes table ... 23 | 24 | j = 0; 25 | cats = Dict(String,Int64); 26 | 27 | # Main loop to load up the quotes table 28 | for i = 1:n 29 | cat = qq[i,1]; 30 | if haskey(cats,cat) 31 | jd = cats[cat]; 32 | else 33 | j = j + 1; jd = j; 34 | cats[cat] = jd; 35 | end 36 | sql = "insert into quotes values($i,$jd,"; 37 | if (length(qq[i,2]) > 0) 38 | sql *= string("'", escticks(qq[i,2]), "',"); 39 | else 40 | sql *= string("null,"); 41 | end 42 | sql *= string("'", escticks(qq[i,3]), "');"); 43 | stmt = prepare(conn,sql); execute(stmt); 44 | if errcode(conn) > 0 error(errstring(conn); end; 45 | end 46 | 47 | # Now dump the categories 48 | for cat = keys(cats) 49 | jd = cats[cat]; 50 | sql = "insert into categories($jd,'$cat')"; 51 | stmt = prepare(conn,sql); execute(stmt); 52 | if errcode(conn) > 0 error(errstring(conn); end; 53 | end; 54 | disconnect(conn); 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /Module 3/Chapter08/postgres-dbi.jl: -------------------------------------------------------------------------------- 1 | using DBI, PostgreSQL 2 | 3 | connect(Postgres) do conn 4 | stmt = prepare(conn,"SELECT * FROM \"MediaType\""); 5 | res = execute(stmt); 6 | for row in res 7 | @printf "ID: %2d, Media: %s\n" row[1] row[2] 8 | end 9 | finish(stmt); 10 | end 11 | -------------------------------------------------------------------------------- /Module 3/Chapter08/redis-quandl.jl: -------------------------------------------------------------------------------- 1 | using Quandl, DataFrames, Redis, Winston 2 | 3 | qapi_key = "aaaaaaaaaaaaaaaaaaaa" # Your Quandl key 4 | set_auth_token(qapi_key) 5 | 6 | qdf1 = quandl("WIKI/AAPL", format="DataFrame", order="asc"); 7 | aapl = convert(Array, qdf1[:Close]); 8 | scf1 = 1.0/aapl[1]; aapl = scf1 .* aapl; 9 | 10 | qdf2 = quandl("WIKI/MSFT", format="DataFrame", order="asc"); 11 | msft = convert(Array, qdf2[:Close]); 12 | scf2 = 1.0/msft[1]; msft = scf2 .* msft; 13 | 14 | n = [1:length(aapl)]; 15 | conn = RedisConnection() 16 | for i = 1:n 17 | rpush(conn,'APPL~Close',aapl[i]) 18 | rpush(conn,'MSFT~Close',msft[i]) 19 | end 20 | 21 | t = [1:n]; # Just plot the data not the dates 22 | 23 | aapl-data = float32(lrange(conn,'AAPL~Close',0,-1); 24 | msft-data = float32(lrange(conn,'MSFT~Close',0,-1); 25 | plot(t, aapl-data,"b--", t, msft-data, "r."); 26 | -------------------------------------------------------------------------------- /Module 3/Chapter08/rest-books.jl: -------------------------------------------------------------------------------- 1 | using HTTPClient.HTTPC 2 | using JSON 3 | 4 | api = "https://www.googleapis.com/books/v1/volumes" 5 | url = api * "?q=isbn:1408855895" 6 | uu = HTTPC.get(url) 7 | json = JSON.parse(bytestring(uu.body.data)); 8 | 9 | volumeInfo = json["items"][1]["volumeInfo"] 10 | title = volumeInfo["title"] 11 | author = volumeInfo["authors"][1] 12 | publisher = volumeInfo["publishedBy"] 13 | pubdate = volumeInfo["publishedDate"] 14 | ppcoount = volumeInfo["pageCount"] 15 | 16 | @printf "%s by %s\nPublished by %s (%s), Pages: $d" title, author, publisher, pubdate, ppcount 17 | 18 | -------------------------------------------------------------------------------- /Module 3/Chapter09/apt.jl: -------------------------------------------------------------------------------- 1 | create table categories ( 2 | id integer not null, 3 | catname varchar(40) not null, 4 | primary key(id) 5 | ); 6 | 7 | create table quotes ( 8 | id integer not null, 9 | cid integer not null, 10 | author varchar(100), 11 | quoname varchar(250) not null, 12 | primary key(id) 13 | ); 14 | -------------------------------------------------------------------------------- /Module 3/Chapter09/echos.jl: -------------------------------------------------------------------------------- 1 | #! /Users/malcolm/bin/julia -q 2 | # 3 | using ArgParse 4 | 5 | const ECHO_PORT = 3000 6 | const ECHO_HOST = "localhost" 7 | 8 | function parse_commandline() 9 | s = ArgParseSettings() 10 | @add_arg_table s begin 11 | "--server", "-s" 12 | help = "hostname of the echo server" 13 | default = ECHO_HOST 14 | "--port", "-p" 15 | help = "port number running the service" 16 | arg_type = Int 17 | default = ECHO_PORT 18 | "--quiet", "-q" 19 | help = "run quietly, i.e. with no server output" 20 | action = :store_true 21 | end 22 | return parse_args(s) 23 | end 24 | 25 | pa = parse_commandline() 26 | 27 | ehost = pa["server"] 28 | eport = pa["port"] 29 | vflag = !pa["quiet"] 30 | 31 | pp = (ehost == "localhost" ? "" : "$ehost>") 32 | 33 | if vflag println("Listening on port $eport") end 34 | server = listen(eport) 35 | while true 36 | conn = accept(server) 37 | @async begin 38 | try 39 | while true 40 | s0 = readline(conn) 41 | s1 = chomp(s0) 42 | if length(chomp(s1)) > 0 43 | s2 = reverse(s1) 44 | if s2 == "." 45 | println("Done.") 46 | close(conn) 47 | exit(0) 48 | else 49 | write(conn,string(pp,s2,"\r\n")) 50 | end 51 | end 52 | end 53 | catch err 54 | println("Connection lost: $err") 55 | exit(1) 56 | end 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /Module 3/Chapter09/eliza.jl: -------------------------------------------------------------------------------- 1 | using HttpServer 2 | using WebSockets 3 | 4 | const SDEF = "Tell me more ..."; 5 | const SBYE = "Goodbye, please let's talk again soon"; 6 | 7 | d = Dict(); 8 | 9 | d["hello"] = "Hi, my name is Eliza"; 10 | d["no"] = "Tell me more about the detail."; 11 | d["yes"] = "Tell me more about the detail."; 12 | d["you"] = "Let's not talk about me."; 13 | d["think"] = "Why do you think that?"; 14 | d["hate"] = "So you hate something, tell me more."; 15 | d["what"] = "Why do you ask ?"; 16 | d["want"] = "I'm here help you with what you want"; 17 | d["need"] = "We all need many thing, is this is important?"; 18 | d["why"] = "Remember therapy is good for you."; 19 | d["know"] = "How do you know that?"; 20 | d["can't"] = "Don't be negative -- be positive!"; 21 | d["never"] = "Don't be negative -- be positive!"; 22 | d["unhappy"] = "Why are you unhappy?"; 23 | d["like"] = "Why do you like that?"; 24 | d["help"] = "I'm here to help you."; 25 | 26 | looping = true; 27 | 28 | wsh = WebSocketHandler() do req,clt 29 | while looping 30 | s0 = lowercase(read(client)) 31 | s1 = SDEF 32 | for k in keys(d) 33 | s = lowercase(k) 34 | if s == "bye" 35 | looping = false 36 | s1 = SBYE 37 | else if contains(s0, s) 38 | s1 = d[k] 39 | break 40 | end 41 | end 42 | write(clt, "ELIZA> $s1") 43 | end 44 | end 45 | 46 | -------------------------------------------------------------------------------- /Module 3/Chapter09/epipe.jl: -------------------------------------------------------------------------------- 1 | #! /Users/malcolm/bin/julia -q 2 | # 3 | # Do some command processing here 4 | # usage: ./echo.jl [ -q ] [ -p ] [-h ] 5 | 6 | epipe = "/tmp/epipe" 7 | 8 | server = listen(epipe) 9 | while true 10 | conn = accept(server) 11 | @async begin 12 | try 13 | while true 14 | s0 = readline(conn) 15 | s1 = chomp(s0) 16 | if length(chomp(s1)) > 0 17 | s2 = reverse(s1) 18 | if s2 == "." 19 | println("Done.") 20 | close(conn) 21 | exit(0) 22 | else 23 | write(conn,string(s2,"\r\n")) 24 | end 25 | end 26 | end 27 | catch err 28 | println("Connection lost: $err") 29 | exit(1) 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /Module 3/Chapter09/esendex.jl: -------------------------------------------------------------------------------- 1 | using URIParser, Requests 2 | 3 | eacct = "EX123456" 4 | uname = "malcolm@amisllp.com" 5 | pword = "passwd" 6 | 7 | dispatcher = "api.esendex.com/v1.0/messagedispatcher2 8 | uri = URI(string(https://,uname,'@',pword,'/',dispatcher) 9 | 10 | message = """?xml version'1.0' encoding='UTF-8' ?> 11 | 12 | EX123456 13 | 14 | 447777555666 15 | Every message matters 16 | 17 | """ 18 | 19 | post(uri; data = message) 20 | 21 | -------------------------------------------------------------------------------- /Module 3/Chapter09/para_jset.jl: -------------------------------------------------------------------------------- 1 | function para_jset(img) 2 | yrange = img[1] 3 | xrange = img[2] 4 | array_slice = (size(yrange, 1), size(xrange, 1)) 5 | jset = Array(Uint8, array_slice) 6 | x0 = xrange[1] 7 | y0 = yrange[1] 8 | 9 | for x = xrange, y = yrange 10 | pix = 256 11 | z = complex( (x-width/2)/(height/2), 12 | (y-height/2)/(height/2)) 13 | for n = 1:256 14 | if abs(z) > 2 15 | pix = n-1 16 | break 17 | end 18 | z = z^2 + C 19 | end 20 | jset[y - y0 + 1, x - x0 + 1] = uint8(pix) 21 | end 22 | return jset 23 | end 24 | -------------------------------------------------------------------------------- /Module 3/Chapter09/py-email.jl: -------------------------------------------------------------------------------- 1 | using PyCall; 2 | @pyimport smtplib; 3 | fromaddr = "malcolm.sherrington@gmail.com"; 4 | toaddrs = "malcolm@amisllp.com"; 5 | 6 | messy = """From: $fromaddr 7 | To: $toaddrs 8 | Subject: Test SMTP using PyCall 9 | 10 | Testing - 1,2,3 11 | """; 12 | 13 | # Note that the blank line is necessary to distinguish 14 | # the SMTP header from the message text. 15 | 16 | username = fromaddr; 17 | password = "ABCDEF7890"; # Not my real password 18 | 19 | server = pycall(smtplib.SMTP,PyAny,"smtp.gmail.com:587"); 20 | server[:ehlo](); 21 | server[:starttls](); 22 | server[:login](username,password); 23 | server[:sendmail](fromaddr,toaddrs,messy); 24 | server[:quit](); 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Module 3/Chapter09/qserver.jl: -------------------------------------------------------------------------------- 1 | function qserver(sock::Integer) 2 | fin = open("quotes.txt"); 3 | hdr = "Content-type: text/plain\n\n"; 4 | qa = readlines(fin); 5 | close(fin); 6 | qn = length(qa); 7 | @async begin 8 | server = listen(sock) 9 | while true 10 | qi = rand(1:qn) 11 | qs = chomp(qa[qi]) 12 | sock = accept(server) 13 | println(hdr*qs) 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /Module 3/Chapter09/quotes-srv.jl: -------------------------------------------------------------------------------- 1 | using Morsel; 2 | using SQLite; 3 | 4 | db = SQLiteDB("quotes.db"); 5 | try 6 | res = query(db,"select count(*) from quotes"); 7 | catch 8 | error("Can't find quotes table"); 9 | end 10 | nq = res[1][1]; 11 | 12 | @assert nq > 0; 13 | 14 | htmlH = """ 15 | 16 | 17 | Julia Quotes Server< 18 | 19 | """; 20 | 21 | htmlF= ""; 22 | 23 | app = Morsel.app(); 24 | route(app, POST | PUT, "/") do req, res 25 | htmlB = "

Posting data to the server is not allowed

"; 26 | string(htmlH,htmlB,htmlF); 27 | end 28 | 29 | get(app, "/") do req, res 30 | qid = rand(1:nq); 31 | sql = "select q.author,c.catname,q.quoname from quotes q "; 32 | sql *= "join categories c on q.cid = c.id and q.id = $qid"; 33 | res = query(db,sql); 34 | author = res[1][1]; 35 | catname = res[2][1]; 36 | quotext = res[3][1]; 37 | htmlB = "

$quotext
$author ($catname)

"; 38 | string(htmlH,htmlB,htmlF); 39 | end 40 | 41 | -------------------------------------------------------------------------------- /Module 3/Chapter09/quotes.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Julia-High-Performance-Programming/1b5ca38ebeaa51373403c8e342038562f89d904f/Module 3/Chapter09/quotes.db -------------------------------------------------------------------------------- /Module 3/Chapter10/MyMod.jl: -------------------------------------------------------------------------------- 1 | module MyMod 2 | 3 | export hi, inc, fac, fib; 4 | 5 | hi() = "Hello" 6 | hi(who::String) = "Hello, $who" 7 | 8 | inc(x::Number) = x + 1 9 | 10 | function fac(n::Integer) 11 | @assert n > 0 12 | (n == 1) ? 1 : n*fac(n-1); 13 | end 14 | 15 | function fib_helper(a ::Integer, b::Integer, n::Integer) 16 | (n > 0) ? fib_helper(b, a+b, n-1) : a 17 | end 18 | 19 | function fib(n::Integer) 20 | @assert n > 0 21 | fib_helper(0, 1, n) 22 | end 23 | 24 | end 25 | -------------------------------------------------------------------------------- /Module 3/Chapter10/asian-debug.jl: -------------------------------------------------------------------------------- 1 | using Debug 2 | 3 | @debug function asianOpt(N=10000,T=100; S0=100.0,K= 100.0,r=0.05,v=0.2,tma=0.25) 4 | dt = tma/T; 5 | S = zeros(Float64,T); 6 | A = zeros(Float64,N); 7 | for n = 1:N 8 | S[1] = S0 9 | dW = randn(T)*sqrt(dt); 10 | for t = 2:T 11 | z0 = (r - 0.5*v*v)*S[t-1]*dt; 12 | z1 = v*S[t-1]*dW[t]; 13 | z2 = 0.5*v*v*S[t-1]*dW[t]*dW[t]; 14 | S[t] = S[t-1] + z0 + z1 + z2; 15 | end 16 | A[n] = mean(S); 17 | @bp 18 | end 19 | P = zeros(Float64,N); 20 | [ P[n] = max(A[n] - K, 0) for n = 1:N ]; 21 | @bp 22 | price = exp(-r*tma)*mean(P); 23 | end 24 | -------------------------------------------------------------------------------- /Module 3/Chapter10/asian-lint.jl: -------------------------------------------------------------------------------- 1 | using Lint 2 | 3 | function asianOpt(N::Int=10000.0,T::Int=100; S0=100.0,K= 100.0,v=0.05,v=0.2,tma=0.25) 4 | dt = tma/T; 5 | S = zeros(Float64,T); 6 | A = zeros(Float64,N); 7 | for n = 1:N 8 | S[1] = S0 9 | dW = randn(T)*sqrt(dt); 10 | for t = 2:T 11 | z0 = (r - 0.5*v*v)*S[t-1]*dt; 12 | z1 = v*S[t-1]*dW[t]; 13 | z2 = 0.5*v*v*S[t-1]*dW[t]*dW[t]; 14 | S[t] = S[t-1] + z0 + z1 + z2 + z3; 15 | end 16 | A[n] = mean(S); 17 | end 18 | P = zeros(Float64,N); 19 | @lintpragma "Print type P" 20 | [ P[n] = max(A[n] - K, 0) for n = 1:N ]; 21 | price = exp(-r*tma)*mean(P); 22 | end 23 | @lintpragma "Info me I've deliberately hacked this" 24 | -------------------------------------------------------------------------------- /Module 3/Chapter10/asian-opt.jl: -------------------------------------------------------------------------------- 1 | function asianOpt(N=10000,T=100; S0=100.0,K= 100.0,r=0.05,v=0.2,tma=0.25) 2 | dt = tma/T; 3 | S = zeros(Float64,T); 4 | A = zeros(Float64,N); 5 | for n = 1:N 6 | S[1] = S0 7 | dW = randn(T)*sqrt(dt); 8 | for t = 2:T 9 | z0 = (r - 0.5*v*v)*S[t-1]*dt; 10 | z1 = v*S[t-1]*dW[t]; 11 | z2 = 0.5*v*v*S[t-1]*dW[t]*dW[t]; 12 | S[t] = S[t-1] + z0 + z1 + z2; 13 | end 14 | A[n] = mean(S); 15 | end 16 | P = zeros(Float64,N); 17 | [ P[n] = max(A[n] - K, 0) for n = 1:N ]; 18 | price = exp(-r*tma)*mean(P); 19 | end 20 | -------------------------------------------------------------------------------- /Module 3/Chapter10/cl-mmul.jl: -------------------------------------------------------------------------------- 1 | import OpenCL 2 | const cl = OpenCL 3 | 4 | const mult_kernel = """ 5 | __kernel void mult(__global const float *a, 6 | __global const float *b, 7 | __global float *c) 8 | { 9 | int gid = get_global_id(0); 10 | c[gid] = a[gid] * b[gid]; 11 | } 12 | """ 13 | 14 | const N = 100_000; 15 | a = rand(Float32, N); 16 | b = rand(Float32, N); 17 | 18 | device, ctx, queue = cl.create_compute_context(); 19 | 20 | a_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=a); 21 | b_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=b); 22 | c_buff = cl.Buffer(Float32, ctx, :w, length(a)); 23 | 24 | p = cl.Program(ctx, source=mult_kernel) |> cl.build!; 25 | k = cl.Kernel(p, "mult"); 26 | 27 | tm = @elapsed cl.call(queue, k, size(a), nothing, a_buff, b_buff, c_buff); 28 | @printf "Time taken: %f\a sec.\n" tm 29 | -------------------------------------------------------------------------------- /Module 3/Chapter10/cl-platforms.jl: -------------------------------------------------------------------------------- 1 | using OpenCL 2 | cl = OpenCL 3 | function cl_platforms() 4 | for pf in cl.platforms() 5 | @printf "\n%s\n\n" pf 6 | @printf "Platform name:\t\t%s\n" pf[:name] 7 | if pf[:name] == "Portable Computing Language" 8 | warn("PCL platform is not yet supported") 9 | continue 10 | else 11 | @printf "Platform profile\t\t:%s\n" pf[:profile] 12 | @printf "Platform vendor:\t\t%s\n" pf[:vendor] 13 | @printf "Platform version:\t\t%s\n\n" pf[:version] 14 | 15 | for dv in cl.available_devices(pf) 16 | @printf "Device name:\t\t%s\n" dv[:name] 17 | @printf "Device type:\t\t%s\n" dv[:device_type] 18 | gms = dv[:global_mem_size] / (1024*1024) 19 | @printf "Device memory:\t%i MB\n" gms 20 | mma = dv[:max_mem_alloc_size] / (1024*1024) 21 | @printf "Device max memory alloc:\t%i MB\n" mma 22 | mcu = device[:max_compute_units] 23 | @printf "Device max compute units:\t%i\n" mcu 24 | mwgs = device[:max_work_group_size] 25 | @printf "Device max work group size:\t%i\n"mwgs 26 | mwis = device[:max_work_item_size] 27 | @printf "Device max work item size:\t%s\n" mwis 28 | end 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /Module 3/Chapter10/main-fitsio.jl: -------------------------------------------------------------------------------- 1 | using FITSIO 2 | using FITSIO.Libcfitsio 3 | 4 | # The low-level API is now part of a submodule Libcfitsio 5 | 6 | f001 = fits_open_file("f001a066.fits") 7 | n = fits_get_hdrspace(f001)[1]; # => 128 8 | 9 | for i = 1:n 10 | println(fits_read_keyn(f001,i)) 11 | end 12 | 13 | -------------------------------------------------------------------------------- /Module 3/Chapter10/pisqd.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // LIBEXEC will vary with the operating system being used 6 | #define LIBEXEC "/usr/lib64/julia" 7 | 8 | int main() { 9 | jl_init(LIBEXEC); 10 | JL_SET_STACK_BASE; 11 | jl_function_t *func = jl_get_function(jl_base_module, "^"); 12 | jl_value_t *arg1 = jl_box_float64(M_PI); 13 | jl_value_t *arg2 = jl_box_float64(2.0); 14 | jl_value_t *ret = jl_call2(func, arg1, arg2); 15 | if (jl_is_float64(ret)) { 16 | double pi2 = jl_unbox_float64(ret); 17 | printf("PI (squared) is %f\n", pi2); 18 | } 19 | return 0; 20 | } 21 | --------------------------------------------------------------------------------