├── Chapter01 ├── args.jl ├── hello.jl ├── ijulia_example.jl ├── isinteractive.jl └── main.jl ├── Chapter02 ├── arrays.jl ├── constants.jl ├── dates.jl ├── formatting.jl ├── regexp.jl ├── scope.jl └── strings_arrays.jl ├── Chapter03 ├── anonymous.jl ├── arguments.jl ├── first_class.jl ├── functions101.jl ├── generic_functions.jl └── map_filters.jl ├── Chapter04 ├── conditional.jl ├── errors.jl ├── file1.txt ├── repetitions.jl ├── scope.jl └── tasks.jl ├── Chapter05 ├── dicts.jl ├── matrices.jl ├── results_words1.txt ├── results_words2.txt ├── sets.jl ├── tuples.jl ├── word_frequency.jl ├── words1.txt └── words2.txt ├── Chapter06 ├── conversions.jl ├── file1.jl ├── file2.jl ├── inner_constructors.jl ├── modules.jl ├── parametric.jl ├── temperature_converter.jl ├── type_hierarchy.jl ├── unions.jl ├── user_defined.jl └── using_module.jl ├── Chapter07 ├── built_in_macros.jl ├── eval.jl ├── expressions.jl ├── macros.jl └── reflection.jl ├── Chapter08 ├── 495B2210 ├── csv_files.jl ├── dataframes.jl ├── defs.jl ├── echoserver.jl ├── example.dat ├── example2.dat ├── functions.jl ├── instpubs.sql ├── io.jl ├── odbc.jl ├── parallel.jl ├── parallel_loops_maps.jl ├── partial.dat ├── savetuple.csv ├── tcpserver.jl ├── tuple_csv.jl └── winequality.csv ├── Chapter09 ├── array_product_benchmark.jl ├── callc.jl ├── callpy.jl ├── file1.txt ├── file2.txt ├── performance.jl ├── shell.jl ├── test.txt └── tosort.txt ├── Chapter10 ├── plots_iris.jl └── stlib.jl ├── Chapter11 ├── Chapter 11.ipynb ├── Manifest.toml └── Project.toml ├── Chapter12 ├── Chapter 12.ipynb ├── Manifest.toml ├── Project.toml └── WebCrawler │ ├── Manifest.toml │ ├── Project.toml │ └── webcrawler.jl ├── Chapter13 ├── Chapter 13.ipynb ├── Manifest.toml ├── Project.toml ├── modules │ ├── Letters.jl │ ├── Numbers.jl │ ├── module_name.jl │ └── testinclude.jl └── sixdegrees │ ├── Articles.jl │ ├── Database.jl │ ├── Gameplay.jl │ ├── Manifest.toml │ ├── Project.toml │ ├── Wikipedia.jl │ └── six_degrees.jl ├── Chapter14 ├── Chapter 14.ipynb ├── Manifest.toml ├── Project.toml ├── hello.jl └── sixdegrees │ ├── Articles.jl │ ├── Database.jl │ ├── GameSession.jl │ ├── Gameplay.jl │ ├── Manifest.toml │ ├── Project.toml │ ├── WebApp.jl │ ├── Wikipedia.jl │ └── six_degrees.jl ├── Chapter15 ├── Chapter 15.ipynb ├── Manifest.toml ├── Project.toml ├── item_based_recommendations.jl ├── top_10_movies.tsv ├── top_10_movies_user_rankings.csv ├── top_10_movies_user_rankings.tsv └── user_based_movie_recommendations.jl ├── Chapter16 ├── Chapter 16.ipynb ├── Manifest.toml ├── Project.toml └── data │ ├── BX-Book-Ratings.csv.zip │ ├── BX-Books.csv.zip │ ├── BX-Users.csv.zip │ ├── large │ ├── test_data.csv │ ├── top_ratings.csv.zip │ └── training_data.csv │ ├── test_data.csv │ ├── top_ratings.csv │ └── training_data.csv ├── Graphics Bundle.pdf ├── LICENSE ├── README.md └── Software Hardware List.pdf /Chapter01/args.jl: -------------------------------------------------------------------------------- 1 | for arg in ARGS 2 | println(arg) 3 | end -------------------------------------------------------------------------------- /Chapter01/hello.jl: -------------------------------------------------------------------------------- 1 | println("Hello, Julia World!") 2 | -------------------------------------------------------------------------------- /Chapter01/ijulia_example.jl: -------------------------------------------------------------------------------- 1 | a = 5 2 | b = 2a^2 + 30a + 9 3 | 4 | using PyPlot 5 | x = range(0,stop=5,length=101) 6 | y = cos.(2x .+ 5) 7 | plot(x, y, linewidth=2.0, linestyle="--") 8 | title("a nice cosinus") 9 | xlabel("x axis") 10 | ylabel("y axis") 11 | -------------------------------------------------------------------------------- /Chapter01/isinteractive.jl: -------------------------------------------------------------------------------- 1 | println("Is this interactive? $(isinteractive())") -------------------------------------------------------------------------------- /Chapter01/main.jl: -------------------------------------------------------------------------------- 1 | include("hello.jl") 2 | -------------------------------------------------------------------------------- /Chapter02/arrays.jl: -------------------------------------------------------------------------------- 1 | for i in 1:2:9 2 | println(i) 3 | end #> 1 3 5 7 9 4 | 5 | typeof(1:1000) #> UnitRange{Int64} 6 | 7 | a = split("A,B,C,D",",") 8 | typeof(a) #> Array{SubString{String},1} 9 | show(a) #> SubString{String}["A","B","C","D"] 10 | 11 | arr = [100, 25, 37] 12 | arra = Any[100, 25, "ABC"] #> element type Any 13 | arr[1] #> 100 14 | arr[end] #> 37 15 | # arr[6] 16 | #> ERROR: BoundsError: attempt to access 3-element Array{Int64,1} at index [6] 17 | println(eltype(arr)) #> Int64 18 | println(length(arr)) #> 3 19 | println(ndims(arr)) #> 1 20 | println(size(arr,1)) #> 3 21 | println(size(arr)) #> (3,) 22 | 23 | arr2 = Array{Int64}(undef, 5) 24 | show(arr2) #> [1, 2, 3, 4, 5] 25 | sizehint!(arr2, 10^5) 26 | 27 | arr3 = Float64[] #> 0-element Array{Float64,1} 28 | push!(arr3, 1.0) #> 1-element Array{Float64,1} 29 | 30 | arr4 = collect(1:7) #> 7-element Array{Int64,1} 31 | show(arr4) #> [1, 2, 3, 4, 5, 6, 7] 32 | 33 | # for in loop and changing the array: 34 | da = [1,2,3,4,5] 35 | for n in da 36 | n *= 2 37 | end 38 | da #> 5-element Array{Int64,1}: 1 2 3 4 5 39 | for i in 1:length(da) 40 | da[i] *= 2 41 | end 42 | da #> 5-element Array{Int64,1}: 2 4 6 8 10 43 | 44 | arr4 = [1,2,3,4,5,6,7] #> 7-element Array{Int64,1}: [1,2,3,4,5,6,7] 45 | join(arr4, ", ") #> "1, 2, 3, 4, 5, 6, 7" 46 | arr4[1:3] # => [1, 2, 3] 47 | arr4[4:end] # => [4, 5, 6, 7] 48 | 49 | arr = [1,2,3,4,5] 50 | arr[2:4] = [8,9,10] 51 | println(arr) #> 1 8 9 10 5 52 | 53 | zeros(5) 54 | ones(4) 55 | ones(3, 2) 56 | eqa = range(0, step=10, length=5) #> 0:10:40 57 | println() 58 | show(eqa) #> 0:10:40 59 | fill!(arr, 42) #> [42, 42, 42, 42, 42] 60 | println() 61 | println(Array{Any}(undef, 4)) #> Any[#undef,#undef,#undef,#undef] 62 | 63 | v1 = rand(Int32, 5) 64 | println(v1) #> Int32[1735276173,972339632,1303377282,1493859467,-788555652] 65 | 66 | b = collect(1:7) 67 | c = [100,200,300] 68 | append!(b,c) # Now b is [1, 2, 3, 4, 5, 6, 7, 100, 200, 300] 69 | pop!(b) #> 300, b is now [1, 2, 3, 4, 5, 6, 7, 100, 200] 70 | push!(b, 42) # b is now [1, 2, 3, 4, 5, 6, 7, 100, 200, 42] 71 | popfirst!(b) #> 1, b is now [2, 3, 4, 5, 6, 7, 100, 200, 42] 72 | pushfirst!(b, 42) # b is now [1, 2, 3, 4, 5, 6, 7, 100, 200, 42] 73 | splice!(b,8) #> 100, b is now [42, 2, 3, 4, 5, 6, 7, 200, 42] 74 | in(42, b) #> true 75 | in(43, b) #> false 76 | println() 77 | println("sorting:") 78 | sort(b) #> [2,3,4,5,6,7,42,42,200], b is not changed 79 | println(b) #> [42,2,3,4,5,6,7,200,42] 80 | sort!(b) #> b is now changed to [2,3,4,5,6,7,42,42,200] 81 | println(b) #> [2,3,4,5,6,7,42,42,200] 82 | println() 83 | arr = [1, 5, 3] 84 | # looping 85 | for e in arr 86 | print("$e ") 87 | end # prints 1 5 3 88 | 89 | arr = [1, 2, 3] 90 | arr .+ 2 #> [3, 7, 5] 91 | arr * 2 #> [2, 10, 6] 92 | a1 = [1, 2, 3] 93 | a2 = [4, 5, 6] 94 | a1 .* a2 #> [4, 10, 18] 95 | 96 | using LinearAlgebra 97 | LinearAlgebra.dot(a1, a2) #> 32 98 | sum(a1 .* a2) 99 | 100 | repeat([1, 2, 3], inner = [2]) #> [1,1,2,2,3,3] 101 | 102 | a = [1,2,4,6] 103 | a1 = a 104 | show(a1) 105 | a[4] = 0 106 | show(a) #> [1,2,4,0] 107 | show(a1) #> [1,2,4,0] 108 | b = copy(a) 109 | b = deepcopy(a) 110 | 111 | a = [1,2,3] 112 | function change_array(arr) 113 | arr[2] = 25 114 | end 115 | change_array(a) 116 | println(a) #>[ 1, 25, 3] 117 | 118 | # the splat operator: 119 | arr = ['a', 'b', 'c'] 120 | show(join(arr)) #> "abc" 121 | show(string(arr)) #> "['a', 'b', 'c']" 122 | show(string(arr...)) #> "abc" -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /Chapter02/dates.jl: -------------------------------------------------------------------------------- 1 | # constructing: 2 | start_time = time() 3 | # long computation 4 | time_elapsed = time() - start_time 5 | println("Time elapsed: $time_elapsed") #> 0.0009999275207519531 6 | 7 | using Dates 8 | d = Date(2018,9,1) #> 2018-09-01 9 | dt = DateTime(2018,9,1,12,30,59,1) #> 2018-09-01T12:30:59.001 10 | # accessors: 11 | year(d) 12 | month(d) 13 | week(d) 14 | day(d) 15 | # functions: 16 | isleapyear(d) 17 | dayofyear(d) 18 | monthname(d) 19 | daysinmonth(d) -------------------------------------------------------------------------------- /Chapter02/formatting.jl: -------------------------------------------------------------------------------- 1 | using Printf 2 | # d for integers: 3 | @printf("%d\n", 1e5) #> 100000 4 | x = 7.35679 5 | # f = float format, rounded if needed: 6 | @printf("x = %0.3f\n", x) #> 7.357 7 | aa = 1.5231071779744345 8 | bb = 33.976886930000695 9 | @printf("%.2f %.2f\n", aa, bb) #> 1.52 33.98 10 | # or to create another string: 11 | str = @sprintf("%0.3f", x) 12 | show(str) #> "7.357" 13 | println() 14 | # e = scientific format with e: 15 | @printf("%0.6e\n", x) #> 7.356790e+00 16 | # c = for characters: 17 | @printf("output: %c\n", 'α') #> output: α 18 | # s for strings: 19 | @printf("%s\n", "I like Julia") 20 | # right justify: 21 | @printf("%50s\n", "text right justified!") 22 | # p for pointers: 23 | @printf("a pointer: %p\n", 1e10) #> a pointer: 0x00000002540be400 -------------------------------------------------------------------------------- /Chapter02/regexp.jl: -------------------------------------------------------------------------------- 1 | email_pattern = r".+@.+" 2 | input = "john.doe@mit.edu" 3 | println(occursin(email_pattern, input)) #> true 4 | 5 | visa = r"^(?:4[0-9]{12}(?:[0-9]{3})?)$" 6 | input = "4457418557635128" 7 | 8 | occursin(visa, input) #> true 9 | if occursin(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 | r = collect((m.match for m = eachmatch(reg, str))) 32 | show(r) #> ["The","sky","blue"] 33 | # eachmatch returns an iterator over all the matches 34 | iter = eachmatch(reg, str) 35 | for i in iter 36 | println("\"$(i.match)\" ") 37 | end -------------------------------------------------------------------------------- /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 5 | # ERROR: syntax: type declarations on global variables are not yet supported 6 | 7 | function scopetest() 8 | println(x) 9 | y::Float64 = 1.0 # y must be Float64, this is not possible in global scope 10 | # y = 1 11 | end 12 | 13 | scopetest() 14 | #> 1 15 | #> 1.0 16 | # println(y) #> ERROR: UndefVarError: y not defined 17 | 18 | # compound expressions: 19 | x = begin 20 | a = 5 21 | 2 * a 22 | end # after: x is 10 23 | println(a) #> a is 5 24 | x = (a = 5; 2 * a) #> 10 -------------------------------------------------------------------------------- /Chapter02/strings_arrays.jl: -------------------------------------------------------------------------------- 1 | using Statistics 2 | # a newspaper headline: 3 | str = "The Gold and Blue Loses a Bit of Its Luster" 4 | println(str) 5 | nchars = length(str) 6 | println("The headline counts $nchars characters") # 43 7 | str2 = replace(str, "Blue" => "Red") 8 | 9 | # strings are immutable 10 | println(str) # The Gold and Blue Loses a Bit of Its Luster 11 | println(str2) 12 | println("Here are the characters at position 25 to 30:") 13 | subs = str[25:30] 14 | print("-$(lowercase(subs))-") # "-a bit -" 15 | println("Here are all the characters:") 16 | for c in str 17 | println(c) 18 | end 19 | arr = split(str,' ') 20 | show(arr) # ["The","Gold","and","Blue","Loses","a","Bit","of","Its","Luster"] 21 | nwords = length(arr) 22 | println("The headline counts $nwords words") # 10 23 | println("Here are all the words:") 24 | for word in arr 25 | println(word) 26 | end 27 | arr[4] = "Red" 28 | show(arr) # arrays are mutable 29 | println("Convert back to a sentence:") 30 | nstr = join(arr, ' ') 31 | println(nstr) # The Gold and Red Loses a Bit of Its Luster 32 | # working with arrays: 33 | using Statistics 34 | println("arrays: calculates the sum, mean and standard deviation ") 35 | arr = collect(1:100) 36 | typeof(arr) #> Array{Int64,1} 37 | println(sum(arr)) #> 5050 38 | println(mean(arr)) #> 50.5 -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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: MethodError: no method matching f() 7 | # f(1, 2, 3) 8 | #> ERROR: MethodError: 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 | #> pairs(::NamedTuple) with 3 entries: 32 | # :k1 => "name1" 33 | # :k2 => "name2" 34 | # :k3 => 7 -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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) #> arguments: 1 2 (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 -------------------------------------------------------------------------------- /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 | 20 | using InteractiveUtils 21 | InteractiveUtils.methodswith(String) 22 | 23 | # measuring execution: 24 | fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) 25 | @time fib(35) 26 | @elapsed fib(35) #> elapsed time: 0.115853481 seconds (45144 bytes allocated) 27 | 28 | # broadcasting: 29 | arr = [1.0, 2.0, 3.0] 30 | sin.(arr) 31 | #> 3-element Array{Float64,1}: 32 | # 0.8414709848078965 33 | # 0.9092974268256817 34 | # 0.1411200080598672 35 | 36 | f(x,y) = x + 7y 37 | f.(pi, arr) 38 | #> 3-element Array{Float64,1}: 39 | # 10.141592653589793 40 | # 17.141592653589793 41 | # 24.141592653589793 -------------------------------------------------------------------------------- /Chapter03/map_filters.jl: -------------------------------------------------------------------------------- 1 | # maps: 2 | map(x -> x * 10, [1, 2, 3]) #> [10, 20, 30] 3 | cubes = map(x-> Base.power_by_squaring(x, 3), collect(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 | collect(-3:3)) #> [1,2,1,0,1,2,1] 14 | 15 | map(collect(-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), collect(1:10) )#> [2, 4, 6, 8, 10] 24 | filter( n -> n % 2 == 0, collect(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 collect(1:5)] #> [1, 8, 27, 64, 125] 31 | mat1 = [x + y for x in 1:2, y in 1:3] #> creates a 2 x 3 Array{Int64,2}: 32 | # 2 3 4 33 | # 3 4 5 34 | table10 = [x*y for x=1:10, y=1:10] #> 35 | #= 36 | #1 2 3 4 5 6 7 8 9 10 37 | #2 4 6 8 10 12 14 16 18 20 38 | #3 6 9 12 15 18 21 24 27 30 39 | #4 8 12 16 20 24 28 32 36 40 40 | #5 10 15 20 25 30 35 40 45 50 41 | #6 12 18 24 30 36 42 48 54 60 42 | #7 14 21 28 35 42 49 56 63 70 43 | #8 16 24 32 40 48 56 64 72 80 44 | #9 18 27 36 45 54 63 72 81 90 45 | #10 20 30 40 50 60 70 80 90 100 46 | =# 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 -------------------------------------------------------------------------------- /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: LoadError: TypeError: non-boolean (Int64) used in boolean context 13 | a = 10 14 | b = 15 15 | z = if a > b a 16 | else b 17 | end 18 | println(z) #> 15 19 | z = a > b ? a : b # with ternary operator 20 | 21 | var = 7 22 | varout = "var has value $var" 23 | cond = var > 10 ? "and is bigger than 10." : var < 10 ? "and is smaller than 10" : "and is 10." 24 | println("$varout $cond") # var has value 7 and is smaller than 10 25 | 26 | function sqroot(n::Int) 27 | n >= 0 || error("n must be non-negative") 28 | n == 0 && return 0 29 | sqrt(n) 30 | end 31 | sqroot(4) #> 2.0 32 | sqroot(0) #> 0.0 33 | # sqroot(-6) #> ERROR: LoadError: n must be non-negative -------------------------------------------------------------------------------- /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 with -3.0: 4 | # sqrt will only return a complex result if called with a complex argument. 5 | sqrt(complex(-3)) #> 0.0 + 1.7320508075688772im 6 | 7 | mutable struct CustomException <: Exception 8 | end 9 | 10 | # throw: 11 | codes = ["AO", "ZD", "SG", "EZ"] 12 | # code = "AR" 13 | code = "AO" 14 | if code in codes # in(code, codes) 15 | println("This is an acceptable code") 16 | else 17 | throw(DomainError()) 18 | end 19 | 20 | # error: 21 | function sqroot(n::Int) 22 | n >= 0 || error("n must be non-negative") 23 | n == 0 && return 0 24 | sqrt(n) 25 | end 26 | sqroot(4) #> 2.0 27 | sqroot(0) #> 0.0 28 | # sqroot(-6) #> ERROR: n must be non-negative 29 | 30 | # try / catch 31 | a = [] 32 | try 33 | pop!(a) 34 | catch ex 35 | println(typeof(ex)) #> ArgumentError 36 | backtrace() 37 | showerror(stdout, ex) #> ArgumentError: array must be non-empty 38 | end 39 | 40 | try 41 | # try this code 42 | catch ex 43 | if isa(ex, DomainError) 44 | # do this 45 | elseif isa(ex, BoundsError) 46 | # do this 47 | end 48 | end 49 | 50 | ret = try 51 | global a = 4 * 2 52 | catch ex 53 | end 54 | println(ret) #> 8 55 | 56 | # finally 57 | try 58 | global f = open("file1.txt", "r") #> IOStream() 59 | # operate on file f, for example: 60 | # alternative: open("file1.txt", "r") do f 61 | k = 0 62 | while(!eof(f)) 63 | a=readline(f) 64 | println(a) 65 | k += 1 66 | end 67 | println("\nNumber of lines in file: $k") 68 | catch ex 69 | finally 70 | close(f) 71 | end 72 | 73 | 74 | -------------------------------------------------------------------------------- /Chapter04/file1.txt: -------------------------------------------------------------------------------- 1 | Twas brillig and the slithy toves 2 | Did gyre and gimble in the wabe 3 | All mimsy were the borogroves 4 | And the momeraths outgrabe 5 | -------------------------------------------------------------------------------- /Chapter04/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 | for n = 1:10 8 | println(n^3) 9 | end 10 | # prints: 11 | #1 12 | #8 13 | #27 14 | #64 15 | #125 16 | #216 17 | #343 18 | #512 19 | #729 20 | #1000 21 | 22 | # iterate over index: 23 | arr = [x^2 for x in 1:10] 24 | #10-element Array{Int64,1}: 25 | # 1 26 | # 4 27 | # 9 28 | # 16 29 | # 25 30 | # 36 31 | # 49 32 | # 64 33 | # 81 34 | # 100 35 | 36 | for i = 1:length(arr) 37 | println("the $i-th element is $(arr[i])") 38 | end 39 | # the 1-th element is 1 40 | # the 2-th element is 4 41 | # the 3-th element is 9 42 | # the 4-th element is 16 43 | # the 5-th element is 25 44 | # the 6-th element is 36 45 | # the 7-th element is 49 46 | # the 8-th element is 64 47 | # the 9-th element is 81 48 | # the 10-th element is 100 49 | 50 | for (ix, val) in enumerate(arr) 51 | println("the $ix-th element is $val") 52 | end 53 | # 1 1 54 | # 2 4 55 | # 3 9 56 | # 4 16 57 | # 5 25 58 | # 6 36 59 | # 7 49 60 | # 8 64 61 | # 9 81 62 | # 10 100 63 | 64 | for n = 1:5 65 | for m = 1:5 66 | println("$n * $m = $(n * m)") 67 | end 68 | end 69 | 70 | for n = 1:5, m = 1:5 71 | println("$n * $m = $(n * m)") 72 | end 73 | # 74 | #1 * 1 = 1 75 | #1 * 2 = 2 76 | #1 * 3 = 3 77 | #1 * 4 = 4 78 | #1 * 5 = 5 79 | #2 * 1 = 2 80 | #2 * 2 = 4 81 | #2 * 3 = 6 82 | #2 * 4 = 8 83 | #2 * 5 = 10 84 | #3 * 1 = 3 85 | #3 * 2 = 6 86 | #3 * 3 = 9 87 | #3 * 4 = 12 88 | #3 * 5 = 15 89 | #4 * 1 = 4 90 | #4 * 2 = 8 91 | #4 * 3 = 12 92 | #4 * 4 = 16 93 | #4 * 5 = 20 94 | #5 * 1 = 5 95 | #5 * 2 = 10 96 | #5 * 3 = 15 97 | #5 * 4 = 20 98 | #5 * 5 = 25 99 | 100 | # while loop: 101 | a = 10 102 | b = 15 103 | while a < b 104 | # process(a) 105 | println(a) 106 | global a += 1 107 | end 108 | # prints: 109 | #10 110 | #11 111 | #12 112 | #13 113 | #14 114 | 115 | # loop over array that is changing in the loop: 116 | arr = [1,2,3,4] 117 | while !isempty(arr) 118 | print(pop!(arr), ", ") 119 | end 120 | # => 4, 3, 2, 1, 121 | # julia> arr 122 | # 0-element Array{Int64,1} 123 | 124 | # break: 125 | a = 10 126 | b = 150 127 | while a < b 128 | # process(a) 129 | println(a) 130 | global a += 1 131 | if a >= 50 132 | break 133 | end 134 | end 135 | 136 | arr = rand(1:10, 10) 137 | println(arr) 138 | # get the index of search in an array arr: 139 | searched = 4 140 | for (ix, curr) in enumerate(arr) 141 | if curr == searched 142 | println("The searched element $searched occurs on index $ix") 143 | break 144 | end 145 | end 146 | #= 147 | [8,4,3,6,3,5,4,4,6,6] 148 | The searched element 4 occurs on index 2 149 | =# 150 | 151 | # continue: 152 | for n in 1:10 153 | if 3 <= n <= 6 154 | continue # skip one iteration 155 | end 156 | println(n) 157 | end -------------------------------------------------------------------------------- /Chapter04/scope.jl: -------------------------------------------------------------------------------- 1 | # variant 1: 2 | x = 9 3 | function funscope(n) 4 | x = 0 # x is in the local scope of the function 5 | for i = 1:n 6 | local x # x is local to the for loop 7 | x = i + 1 8 | if (x == 7) 9 | println("This is the local x in for: $x") #> 7 10 | end 11 | end 12 | println("This is the local x in funscope: $x") #> 0 13 | global x = 15 14 | end 15 | funscope(10) 16 | println("This is the global x: $x") #> 15 17 | #= 18 | This is the local x in for: 7 19 | This is the local x in funscope: 0 20 | This is the global x: 15 21 | =# 22 | 23 | # variant 2: 24 | x = 9 25 | function funscope(n) 26 | x = 0 27 | for i = 1:n 28 | x = i + 1 29 | if (x == 7) 30 | println("This is the local x in funscope: $x") #> 7 31 | end 32 | end 33 | println("This is the local x in funscope: $x") #> 11 34 | global x = 15 35 | end 36 | funscope(10) 37 | println("This is the global x: $x") #> 15 38 | #= 39 | This is the local x in funscope: 7 40 | This is the local x in funscope: 11 41 | This is the global x: 15 42 | =# 43 | 44 | # variant 3: 45 | x = 9 46 | function funscope(n) 47 | x = 0 48 | for i = 1:n 49 | x = i + 1 50 | if (x == 7) 51 | println("This is the local x in for: $x") #> 7 52 | end 53 | end 54 | println("This is the local x in funscope: $x") #> 11 55 | end 56 | funscope(10) 57 | println("This is the global x: $x") #> 9 58 | #= 59 | This is the local x in for: 7 60 | This is the local x in funscope: 11 61 | This is the global x: 9 62 | =# 63 | 64 | # without let: 65 | anon = Array{Any}(undef, 2) 66 | for i = 1:2 67 | anon[i] = ()-> println(i) 68 | i += 1 69 | end 70 | anon[1]() #> 2 71 | anon[2]() #> 3 72 | 73 | # with let: 74 | anon = Array{Any}(undef, 2) 75 | for i = 1:2 76 | let i = i 77 | anon[i] = ()-> println(i) 78 | end 79 | i += 1 80 | end 81 | anon[1]() #> 1 82 | anon[2]() #> 2 83 | 84 | # combined with begin: 85 | begin 86 | local x = 1 87 | let 88 | local x = 2 89 | println(x) #> 2 90 | end 91 | x 92 | println(x) #> 1 93 | end 94 | 95 | # for-loops and comprehensions: 96 | i = 0 97 | for i = 1:10 98 | end 99 | println(i) #> 10 100 | 101 | i = 0 102 | [i for i = 1:10 ] 103 | println(i) #> 0 -------------------------------------------------------------------------------- /Chapter04/tasks.jl: -------------------------------------------------------------------------------- 1 | function fib_producer(c::Channel) 2 | a, b = (0, 1) 3 | for i = 1:10 4 | put!(c, b) 5 | a, b = (b, a + b) 6 | end 7 | end 8 | 9 | chnl = Channel(fib_producer) #> Channel{Any}(sz_max:0,sz_curr:1) 10 | 11 | take!(chnl) #> 1 12 | take!(chnl) #> 1 13 | take!(chnl) #> 2 14 | take!(chnl) #> 3 15 | take!(chnl) #> 5 16 | take!(chnl) #> 8 17 | take!(chnl) #> 13 18 | take!(chnl) #> 21 19 | take!(chnl) #> 34 20 | take!(chnl) #> 55 21 | # take!(chnl) #> ERROR: InvalidStateException("Channel is closed.", :closed) 22 | 23 | for n in chnl 24 | println(n) 25 | end 26 | #> 1 1 1 2 3 5 8 13 21 34 55 27 | 28 | chnl = @task fib_producer(c::Channel) # Task (runnable) @0x0000000005696d80 29 | 30 | fac(i::Integer) = (i > 1) ? i*fac(i - 1) : 1 31 | c = Channel(0) 32 | task = @async foreach(i->put!(c,fac(i)), 1:5) 33 | bind(c,task) 34 | for i in c 35 | @show i 36 | end 37 | # i = 1 38 | # i = 2 39 | # i = 6 40 | # i = 24 41 | # i = 120 -------------------------------------------------------------------------------- /Chapter05/dicts.jl: -------------------------------------------------------------------------------- 1 | d1 = Dict(1 => 4.2, 2 => 5.3) 2 | # Dict{Int64,Float64} with 2 entries: 3 | # 2 => 5.3 4 | # 1 => 4.2 5 | d1 = Dict{Int64,Float64}(1 => 4.2, 2 => 5.3) 6 | d1 = [1 => 4.2, 2 => 5.3] 7 | # 2-element Array{Pair{Int64,Float64},1}: 8 | # 1 => 4.2 9 | # 2 => 5.3 10 | 11 | d2 = Dict{Any,Any}("a"=>1, (2,3)=>true) 12 | 13 | d3 = Dict(:A => 100, :B => 200) 14 | # Dict{Symbol,Int64} with 2 entries: 15 | # :A => 100 16 | # :B => 200 17 | d3 = Dict{Symbol,Int64}(:A => 100, :B => 200) 18 | d3[:B] #> 200 19 | # d3[:Z] #> ERROR: KeyError: key :Z not found 20 | get(d3, :Z, 999) #> 999 21 | 22 | d3[:A] = 150 #> d3 is now [:A => 150, :B => 200] 23 | d3[:C] = 300 #> d3 is now [:A => 150, :B => 200, :C => 300] 24 | length(d3) #> 3 25 | # d3["CVO"] = 500 #> ERROR: KeyError: key "CVO" not found 26 | # d3[:CVO] = "Julia" #> ERROR: KeyError: key "CVO" not found 27 | 28 | dmus = Dict{Symbol,String}(:first_name => "Louis", :surname => "Armstrong", :occupation => "musician", 29 | :date_of_birth => "4/8/1901") 30 | # Dict{Symbol,String} with 4 entries: 31 | # :date_of_birth => "4/8/1901" 32 | # :occupation => "musician" 33 | # :surname => "Armstrong" 34 | # :first_name => "Louis" 35 | 36 | haskey(d3, :Z) #> false 37 | haskey(d3, :B) #> true 38 | 39 | d4 = Dict() #> Dict{Any,Any} with 0 entries 40 | d4["lang"] = "Julia" 41 | 42 | d5 = Dict{Float64, Int64}() #> Dict{Float64,Int64} with 0 entries 43 | # d5["c"] = 6 #> ERROR: MethodError: `convert` has no method matching convert(::Type{Float64}, ::ASCIIString) 44 | 45 | d3 = Dict(:A => 100, :B => 200) 46 | delete!(d3, :B) #> Dict{Symbol,Int64} with 1 entry: :A => 100 47 | 48 | d3 = Dict(:A => 100, :B => 200) 49 | ki = keys(d3) #> KeyIterator 50 | for k in ki 51 | println(k) 52 | end #> A B 53 | :A in ki #> true 54 | :Z in ki #> false 55 | 56 | collect(keys(d3)) #> 2-element Array{Symbol,1}: 57 | # :A 58 | # :B 59 | vi = values(d3) #> ValueIterator 60 | for v in values(d3) 61 | println(v) 62 | end #> 100 200 63 | 64 | keys1 = ["J.S. Bach", "Woody Allen", "Barack Obama"] 65 | values1 = [ 1685, 1935, 1961] 66 | d5 = Dict(zip(keys1, values1)) 67 | #> 68 | # Dict{String,Int64} with 3 entries: 69 | # "J.S. Bach" => 1685 70 | # "Woody Allen" => 1935 71 | # "Barack Obama" => 1961 72 | 73 | for (k, v) in d5 74 | println("$k was born in $v") 75 | end 76 | for p in d5 77 | println("$(p[1]) was born in $(p[2])") 78 | end 79 | #J.S. Bach was born in 1685 80 | #Barack Obama was born in 1961 81 | #Woody Allen was born in 1935 82 | 83 | capitals = Dict{String, String}("France"=> "Paris", "China"=>"Beijing") 84 | # Dict{String,String} with 2 entries: 85 | # "China" => "Beijing" 86 | # "France" => "Paris" 87 | 88 | # neat tricks: 89 | dict = Dict("a" => 1, "b" => 2, "c" => 3) 90 | arrkey = [key for (key, value) in dict] #> 3-element Array{String,1}: "a" "b" "c" 91 | # same as collect(keys(dict)) 92 | arrval = [value for (key, value) in dict] #> 3-element Array{Int64,1}: 1 2 3 93 | # same as collect(values(dict)) 94 | -------------------------------------------------------------------------------- /Chapter05/matrices.jl: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | [1 2 3] 3 | [1; 2; 3] 4 | # 3-element Array{Int64,1}: 5 | # 1 6 | # 2 7 | # 3 8 | 9 | Array{Int64, 1} == Vector{Int64} #> true 10 | Array{Int64, 2} == Matrix{Int64} #> true 11 | 12 | [1 2] * [3 ; 4] #> 11 13 | [1 2] .* [3 ; 4] 14 | # 2 Array{Int64,2}: 15 | # 3 6 16 | # 4 8 17 | 18 | matrix1 = [1 2; 3 4] 19 | matrix1[2, 1] #> 3 20 | matrix2 = [5 6; 7 8] 21 | println(matrix1 * matrix2) 22 | #= 23 | [19 22 24 | 43 50] 25 | =# 26 | 27 | ma1 = rand(3, 5) 28 | ndims(ma1) #> 2 29 | size(ma1) #> (3, 5) 30 | nrows, ncols = size(ma1) 31 | size(ma1,1) #> 3 32 | size(ma1,2) #> 5 33 | length(ma1) #> 15 34 | 35 | using LinearAlgebra 36 | idm = Matrix(1.0*I, 3, 3) 37 | idm[1:end, 2] #> 2nd column 38 | idm[2, :] #> 2nd row 39 | idmc = idm[2:end, 2:end] 40 | #2x2 Array{Float64,2}: 41 | # 1.0 0.0 42 | # 0.0 1.0 43 | idm[2, :] .= 0 44 | # idm 45 | # 3x3 Array{Float64,2}: 46 | # 1.0 0.0 0.0 47 | # 0.0 0.0 0.0 48 | # 0.0 0.0 1.0 49 | idm[2:end, 2:end] = [ 5 7 ; 9 11] 50 | # idm 51 | # 3x3 Array{Float64,2}: 52 | # 1.0 0.0 0.0 53 | # 0.0 5.0 7.0 54 | # 0.0 9.0 11.0 55 | 56 | a = [1 2;3 4] 57 | # 2 Array{Int64,2}: 58 | # 1 2 59 | # 3 4 60 | 61 | a[:] 62 | # 4-element Array{Int64,1}: 63 | # 1 64 | # 3 65 | # 2 66 | # 4 67 | 68 | jarr = (Array{Int64, 1})[] 69 | push!(jarr, [1,2]) 70 | push!(jarr, [1,2,3,4]) 71 | push!(jarr, [1,2,3]) 72 | jarr #> 73 | #3-element Array{Array{Int64,1},1}: 74 | # [1,2] 75 | # [1,2,3,4] 76 | # [1,2,3] 77 | 78 | ma = [1 2; 3 4] 79 | ma[:] 80 | # 4-element Array{Int64,1}: 81 | # 1 82 | # 3 83 | # 2 84 | # 4 85 | ma' #> [1 3; 2 4] 86 | ma * ma' #> 87 | #5 11 88 | #11 25 89 | ma .* ma' #> 2x2 Array{Int64,2}: 90 | #1 6 91 | #6 16 92 | 93 | inv(ma) #> 2x2 Array{Float64,2}: 94 | # -2.0 1.0 95 | # 1.5 -0.5 96 | 97 | ma * inv(ma) #> 2x2 Array{Float64,2}: 98 | # 1.0 0.0 99 | # 8.88178e-16 1.0 100 | 101 | v = [1.,2.,3.] #> equivalent to v = [1.0,2.0,3.0] 102 | w = [2.,4.,6.] 103 | append!(v, w) 104 | #6-element Array{Float64,1}: 105 | # 1.0 106 | # 2.0 107 | # 3.0 108 | # 2.0 109 | # 4.0 110 | # 6.0 111 | v = [1.,2.,3.] 112 | hcat(v,w) 113 | # 3x2 Array{Float64,2}: 114 | # 1.0 2.0 115 | # 2.0 4.0 116 | # 3.0 6.0 117 | vcat(v,w) 118 | # 6-element Array{Float64,1}: 119 | # 1.0 120 | # 2.0 121 | # 3.0 122 | # 2.0 123 | # 4.0 124 | # 6.0 125 | 126 | a = [1 2; 3 4] 127 | # 2x2 Array{Int64,2}: 128 | # 1 2 129 | # 3 4 130 | 131 | b = [5 6; 7 8] 132 | # 2x2 Array{Int64,2}: 133 | # 5 6 134 | # 7 8 135 | 136 | c = [a b] 137 | # 2x4 Array{Int64,2}: 138 | # 1 2 5 6 139 | # 3 4 7 8 140 | 141 | c = [a; b] 142 | # 4x2 Array{Int64,2}: 143 | # 1 2 144 | # 3 4 145 | # 5 6 146 | # 7 8 147 | 148 | c = [a, b] 149 | # 4x2 Array{Int64,2}: 150 | # 1 2 151 | # 3 4 152 | # 5 6 153 | # 7 8 154 | 155 | reshape(1:12, 3, 4) 156 | # 3x4 Array{Int64,2}: 157 | # 1 4 7 10 158 | # 2 5 8 11 159 | # 3 6 9 12 160 | 161 | a = rand(3, 3) 162 | # 3x3 Array{Float64,2}: 163 | # 0.332401 0.499608 0. 164 | # 0.0933291 0.132798 0. 165 | # 0.722452 0.932347 0. 166 | 167 | reshape(a, (9,1)) 168 | # 9x1 Array{Float64,2}: 169 | # 0.332401 170 | # 0.0933291 171 | # 0.722452 172 | # 0.499608 173 | # 0.132798 174 | # 0.932347 175 | # 0.355623 176 | # 0.967591 177 | # 0.809577 178 | 179 | # reshape(a, (2,2)) 180 | # ERROR: DimensionMismatch("new dimensions (2,2) must be consistent with array size 9") 181 | 182 | # copy and deepcopy: 183 | x = Array{Any}(undef, 2) #> 2-element Array{Any,1}: #undef #undef 184 | x[1] = ones(2) #> 2-element Array{Float64} 1.0 1.0 185 | x[2] = trues(3) #> 3-element BitArray{1}: true true true 186 | x #> 2-element Array{Any,1}: [1.0,1.0] Bool[true,true,true] 187 | a = x #> 2-element Array{Any,1}: [1.0,1.0] Bool[true,true,true] 188 | b = copy(x) #> 2-element Array{Any,1}: [1.0,1.0] Bool[true,true,true] 189 | c = deepcopy(x) #> 2-element Array{Any,1}: [1.0,1.0] Bool[true,true,true] 190 | x[1] = "Julia" 191 | x[2][1] = false 192 | x #> 2-element Array{Any,1}: "Julia" Bool[false,true,true] 193 | a #> 2-element Array{Any,1}: "Julia" Bool[false,true,true] 194 | isequal(a, x) #> true, a is identical to x 195 | b #> 2-element Array{Any,1}: [1.0,1.0] Bool[false,true,true] 196 | isequal(b, x) #> false, b is a shallow copy of x 197 | c #> 2-element Array{Any,1}: [1.0,1.0] Bool[true,true,true] 198 | isequal(c, x) #> false -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /Chapter05/results_words2.txt: -------------------------------------------------------------------------------- 1 | Word : frequency 2 | 3 | A : 6 4 | Ages : 1 5 | All : 1 6 | Alphonsus : 1 7 | Although : 2 8 | An : 1 9 | Arraying : 2 10 | As : 3 11 | Astronomy : 1 12 | At : 1 13 | August : 1 14 | Australia : 3 15 | BINARY : 1 16 | BRIEF : 1 17 | BY : 1 18 | Baseline : 1 19 | Bay : 1 20 | Because : 4 21 | Beginning : 1 22 | Being : 1 23 | Bigger : 1 24 | Binary : 2 25 | Bit : 1 26 | Both : 1 27 | Brightness : 1 28 | But : 1 29 | By : 2 30 | Byte : 1 31 | California : 2 32 | Canberra : 2 33 | Central : 1 34 | Clouds : 2 35 | Color : 1 36 | Configured : 1 37 | Crater : 2 38 | DSN : 8 39 | Data : 4 40 | Deep : 1 41 | During : 1 42 | Earth : 19 43 | Europa : 1 44 | European : 1 45 | Even : 1 46 | FACTS : 1 47 | FROM : 2 48 | Filters : 1 49 | First : 1 50 | For : 7 51 | From : 1 52 | GET : 2 53 | Galileo : 2 54 | Ganymede : 1 55 | Goldstone : 1 56 | Great : 1 57 | HISTORY : 1 58 | HOW : 2 59 | Haynes : 1 60 | His : 1 61 | However : 1 62 | If : 2 63 | Images : 3 64 | In : 5 65 | Instead : 1 66 | Interferometry : 1 67 | Io : 4 68 | JPL : 2 69 | Jet : 3 70 | Jovian : 1 71 | July : 1 72 | Jupiter : 13 73 | Laboratory : 3 74 | Long : 1 75 | Lunar : 5 76 | MISSION : 26 77 | Madrid : 1 78 | Mariner : 3 79 | Mariners : 1 80 | Mars : 7 81 | Mercury : 3 82 | Middle : 1 83 | Moon : 14 84 | NAME : 26 85 | NASA : 3 86 | NF : 1 87 | Neptune : 4 88 | Network : 1 89 | New : 1 90 | November : 1 91 | OF : 1 92 | Observatory : 1 93 | Ocean : 1 94 | Of : 1 95 | On : 3 96 | Once : 1 97 | Only : 1 98 | Orbiter : 5 99 | PICTURES : 3 100 | Parkes : 1 101 | Pasadena : 1 102 | Pioneer : 7 103 | Pluto : 2 104 | Propulsion : 3 105 | Radio : 1 106 | Ranger : 3 107 | Raster : 1 108 | Red : 1 109 | Reflected : 1 110 | Rhea : 1 111 | SPACE : 2 112 | SPACECRAFT : 1 113 | Saturn : 13 114 | Saturnian : 1 115 | Sea : 4 116 | September : 1 117 | Sequence : 2 118 | Since : 1 119 | Slowing : 1 120 | Solar : 4 121 | Space : 1 122 | Spacecraft : 1 123 | Spain : 1 124 | Spot : 1 125 | Stations : 1 126 | Storms : 1 127 | Surveyor : 6 128 | System : 4 129 | TABLE : 1 130 | TV : 1 131 | That : 4 132 | The : 30 133 | These : 2 134 | This : 3 135 | Those : 1 136 | Thus : 4 137 | To : 5 138 | Tranquility : 2 139 | Triton : 1 140 | Tycho : 1 141 | UNMANNED : 1 142 | Uranus : 10 143 | VLBI : 2 144 | Value : 4 145 | Values : 2 146 | Venus : 7 147 | Very : 1 148 | Viking : 2 149 | Voyager : 19 150 | WE : 2 151 | We : 1 152 | Whatever : 1 153 | When : 3 154 | While : 2 155 | YEAR : 26 156 | _____________________________________________________________________ : 1 157 | ______________________________________________________________________ : 1 158 | a : 76 159 | able : 1 160 | about : 5 161 | above : 2 162 | accompanied : 1 163 | accomplish : 1 164 | accomplished : 1 165 | accomplishment : 1 166 | accuracy : 2 167 | accurate : 2 168 | accurately : 1 169 | achieved : 1 170 | acquisition : 1 171 | across : 2 172 | action : 1 173 | active : 2 174 | add : 1 175 | adding : 2 176 | adjusting : 1 177 | after : 2 178 | aided : 1 179 | aim : 1 180 | aiming : 1 181 | all : 4 182 | allow : 2 183 | alone : 1 184 | alpha : 2 185 | alphabet : 1 186 | already : 1 187 | also : 2 188 | amber : 1 189 | amount : 3 190 | an : 14 191 | analyzed : 1 192 | ancient : 1 193 | and : 82 194 | angle : 1 195 | another : 2 196 | answered : 1 197 | antenna : 4 198 | antennas : 11 199 | anticipated : 1 200 | any : 2 201 | apart : 3 202 | apparent : 1 203 | appear : 4 204 | appears : 1 205 | approach : 1 206 | approaches : 1 207 | appropriate : 1 208 | approximately : 1 209 | are : 27 210 | area : 1 211 | around : 2 212 | array : 2 213 | arraying : 2 214 | arrival : 1 215 | as : 21 216 | assign : 1 217 | assigned : 6 218 | astound : 1 219 | at : 25 220 | atmosphere : 9 221 | atmospheric : 2 222 | attempting : 1 223 | back : 9 224 | bands : 2 225 | based : 1 226 | be : 24 227 | beam : 2 228 | became : 1 229 | because : 2 230 | becoming : 1 231 | been : 6 232 | before : 1 233 | began : 1 234 | behind : 1 235 | being : 3 236 | beside : 1 237 | best : 1 238 | better : 1 239 | between : 4 240 | beyond : 1 241 | biggest : 1 242 | binary : 1 243 | bit : 13 244 | bits : 10 245 | black : 8 246 | blanket : 1 247 | blended : 1 248 | blending : 1 249 | blocked : 1 250 | blue : 3 251 | bluish : 1 252 | blurred : 1 253 | board : 4 254 | body : 2 255 | both : 4 256 | bottom : 1 257 | bound : 2 258 | bright : 1 259 | brighter : 1 260 | brightness : 8 261 | broken : 1 262 | brown : 1 263 | busy : 1 264 | but : 5 265 | by : 31 266 | byte : 8 267 | bytes : 2 268 | calculating : 1 269 | call : 1 270 | called : 7 271 | came : 1 272 | camera : 5 273 | cameras : 10 274 | can : 14 275 | cannot : 1 276 | canyons : 1 277 | caps : 1 278 | carbon : 1 279 | carried : 1 280 | carries : 3 281 | carry : 1 282 | cathode : 1 283 | caused : 1 284 | cave : 1 285 | caves : 1 286 | centers : 1 287 | century : 1 288 | changing : 1 289 | character : 1 290 | charcoal : 1 291 | charting : 1 292 | chemical : 1 293 | chosen : 1 294 | circling : 2 295 | circuit : 1 296 | circulation : 3 297 | clarity : 1 298 | cliffs : 1 299 | close : 3 300 | closely : 1 301 | closest : 1 302 | closet : 1 303 | closeup : 1 304 | cloud : 1 305 | cloudtops : 4 306 | coincides : 1 307 | color : 6 308 | colored : 1 309 | colors : 1 310 | combined : 3 311 | command : 1 312 | commanded : 1 313 | common : 2 314 | compensation : 1 315 | complement : 1 316 | complete : 1 317 | complex : 2 318 | composed : 2 319 | compressing : 1 320 | compression : 1 321 | computer : 4 322 | computers : 8 323 | concentric : 1 324 | considered : 1 325 | consists : 1 326 | contact : 2 327 | contain : 1 328 | containing : 1 329 | contains : 2 330 | continued : 1 331 | continuous : 1 332 | contrast : 3 333 | control : 2 334 | controls : 2 335 | convention : 2 336 | convert : 2 337 | converting : 1 338 | converts : 1 339 | correct : 1 340 | correspond : 1 341 | correspondingly : 1 342 | corresponds : 2 343 | could : 3 344 | count : 3 345 | counted : 1 346 | counting : 3 347 | course : 1 348 | cover : 1 349 | coverage : 1 350 | covered : 1 351 | crafted : 1 352 | cratered : 2 353 | craters : 1 354 | critical : 1 355 | cup : 1 356 | currently : 1 357 | dark : 1 358 | darker : 2 359 | data : 27 360 | decrease : 1 361 | decreases : 1 362 | deep : 2 363 | deflection : 1 364 | degrees : 1 365 | dense : 1 366 | depict : 1 367 | designed : 3 368 | detail : 1 369 | detailed : 1 370 | details : 4 371 | determines : 1 372 | developed : 1 373 | devised : 1 374 | diameter : 2 375 | did : 1 376 | difference : 2 377 | differences : 2 378 | different : 1 379 | dioxide : 1 380 | direction : 2 381 | directly : 1 382 | disadvantage : 1 383 | disc : 1 384 | discerned : 2 385 | discovered : 4 386 | discoveries : 2 387 | dish : 3 388 | displayed : 1 389 | distance : 3 390 | distant : 2 391 | distinctive : 1 392 | distorting : 1 393 | distributed : 1 394 | divided : 1 395 | do : 2 396 | document : 1 397 | doing : 1 398 | done : 2 399 | dots : 4 400 | down : 1 401 | drawn : 2 402 | draws : 1 403 | drew : 1 404 | dry : 1 405 | dual : 1 406 | due : 1 407 | during : 2 408 | dweller : 1 409 | each : 12 410 | early : 1 411 | easy : 1 412 | effects : 2 413 | eight : 4 414 | either : 2 415 | ejecta : 1 416 | electrical : 1 417 | electronically : 1 418 | elements : 2 419 | eliminate : 1 420 | elsewhere : 1 421 | en : 1 422 | encircled : 1 423 | encounter : 7 424 | encounters : 1 425 | end : 2 426 | enduring : 1 427 | engineers : 2 428 | enhanced : 1 429 | enhancement : 2 430 | entered : 1 431 | enters : 2 432 | entire : 1 433 | erupting : 1 434 | etching : 1 435 | even : 4 436 | evenly : 1 437 | events : 1 438 | exaggerating : 1 439 | examination : 1 440 | examine : 1 441 | example : 3 442 | explain : 1 443 | exploration : 1 444 | exposure : 1 445 | extremely : 1 446 | eye : 4 447 | facsimile : 3 448 | facts : 1 449 | faint : 1 450 | fairly : 2 451 | falls : 1 452 | familiar : 1 453 | far : 1 454 | farther : 2 455 | fast : 1 456 | faster : 1 457 | favor : 1 458 | feat : 1 459 | featureless : 1 460 | features : 2 461 | feet : 1 462 | field : 2 463 | fields : 1 464 | filling : 1 465 | filter : 2 466 | filters : 2 467 | final : 1 468 | findings : 1 469 | fine : 1 470 | first : 13 471 | five : 2 472 | flew : 1 473 | flyby : 9 474 | flybys : 1 475 | focusing : 1 476 | fog : 1 477 | for : 21 478 | form : 1 479 | forms : 1 480 | formulating : 1 481 | found : 2 482 | foundations : 1 483 | four : 1 484 | fourth : 1 485 | frame : 1 486 | frames : 7 487 | frequently : 1 488 | from : 28 489 | ft : 3 490 | full : 4 491 | fundamental : 1 492 | future : 1 493 | fuzzy : 1 494 | gathered : 1 495 | gatherer : 1 496 | gaze : 1 497 | generated : 1 498 | generation : 2 499 | get : 2 500 | giant : 1 501 | give : 1 502 | given : 1 503 | giving : 1 504 | glass : 1 505 | globe : 1 506 | going : 1 507 | government : 1 508 | graphed : 1 509 | gravity : 2 510 | gray : 7 511 | great : 1 512 | greatly : 1 513 | green : 2 514 | greetings : 1 515 | ground : 1 516 | gyroscopes : 1 517 | had : 1 518 | halftones : 1 519 | hand : 3 520 | handicap : 1 521 | handles : 1 522 | happens : 2 523 | hardly : 1 524 | has : 8 525 | have : 17 526 | having : 1 527 | haze : 1 528 | heavens : 2 529 | heliocentric : 1 530 | here : 1 531 | high : 4 532 | higher : 1 533 | highest : 1 534 | hits : 1 535 | holds : 1 536 | hour : 2 537 | how : 1 538 | however : 2 539 | huge : 1 540 | human : 1 541 | humans : 1 542 | ice : 1 543 | if : 2 544 | illuminates : 1 545 | image : 18 546 | images : 15 547 | imagination : 1 548 | immersed : 1 549 | impact : 1 550 | impacted : 8 551 | important : 1 552 | in : 45 553 | including : 3 554 | increase : 1 555 | increased : 1 556 | increases : 1 557 | indicates : 1 558 | individual : 2 559 | information : 5 560 | instructed : 1 561 | intellect : 1 562 | intensities : 1 563 | interfere : 1 564 | intergalactic : 1 565 | intermediate : 1 566 | interplanetary : 1 567 | interpreted : 1 568 | interruption : 1 569 | intervals : 1 570 | into : 10 571 | involves : 1 572 | iron : 1 573 | is : 31 574 | isolate : 1 575 | it : 16 576 | its : 9 577 | job : 1 578 | kilometers : 1 579 | km : 2 580 | know : 1 581 | knowledge : 1 582 | known : 3 583 | landed : 5 584 | landing : 4 585 | lapse : 2 586 | large : 2 587 | largest : 2 588 | later : 1 589 | launched : 1 590 | leaving : 1 591 | left : 1 592 | lens : 1 593 | lenses : 1 594 | levels : 2 595 | lift : 1 596 | light : 8 597 | lights : 1 598 | like : 8 599 | limitation : 1 600 | limitations : 2 601 | limited : 2 602 | line : 2 603 | lines : 1 604 | linked : 1 605 | live : 1 606 | located : 2 607 | locations : 2 608 | long : 2 609 | longer : 2 610 | look : 1 611 | looked : 1 612 | looking : 1 613 | lose : 1 614 | lowest : 1 615 | lunar : 2 616 | made : 3 617 | magnetic : 3 618 | magnifying : 1 619 | making : 1 620 | managed : 1 621 | manner : 1 622 | many : 4 623 | markings : 1 624 | maximum : 1 625 | may : 1 626 | means : 2 627 | meant : 2 628 | measured : 6 629 | measurements : 2 630 | measures : 1 631 | measuring : 3 632 | medium : 2 633 | men : 1 634 | meter : 4 635 | mi : 2 636 | micrometeoroid : 1 637 | miles : 2 638 | millimeters : 1 639 | minute : 1 640 | minutes : 1 641 | mission : 1 642 | missions : 1 643 | modulated : 1 644 | month : 1 645 | moon : 4 646 | moons : 6 647 | more : 15 648 | most : 6 649 | mostly : 1 650 | motion : 1 651 | mounted : 1 652 | moved : 1 653 | movie : 1 654 | movies : 1 655 | much : 6 656 | multi : 1 657 | multiple : 1 658 | multiprobe : 1 659 | must : 3 660 | mysteries : 1 661 | mysterious : 1 662 | narrow : 1 663 | nature : 1 664 | near : 3 665 | nearly : 2 666 | needed : 1 667 | network : 1 668 | new : 9 669 | newer : 2 670 | newspaper : 1 671 | newspapers : 1 672 | next : 2 673 | night : 2 674 | nitrogen : 1 675 | no : 1 676 | noise : 1 677 | nondescript : 1 678 | normal : 1 679 | not : 5 680 | number : 2 681 | numbers : 3 682 | numerical : 2 683 | object : 4 684 | objects : 3 685 | obscured : 1 686 | obscuring : 1 687 | observing : 1 688 | occur : 1 689 | of : 125 690 | off : 2 691 | on : 41 692 | once : 1 693 | one : 16 694 | ones : 2 695 | only : 7 696 | open : 1 697 | operating : 1 698 | optical : 1 699 | or : 15 700 | orange : 3 701 | orbit : 2 702 | orbited : 2 703 | orbiting : 1 704 | order : 1 705 | origin : 1 706 | original : 1 707 | originally : 1 708 | other : 5 709 | others : 2 710 | our : 6 711 | out : 1 712 | outer : 1 713 | over : 2 714 | overcome : 3 715 | oxidized : 1 716 | pale : 1 717 | parallel : 1 718 | particles : 1 719 | passed : 1 720 | passes : 2 721 | past : 2 722 | patch : 1 723 | paths : 2 724 | pattern : 1 725 | patterns : 3 726 | payoff : 1 727 | people : 1 728 | per : 1 729 | percent : 2 730 | perceptible : 1 731 | performed : 1 732 | phases : 1 733 | photo : 1 734 | photograph : 1 735 | photographers : 1 736 | photographs : 2 737 | picture : 10 738 | pictures : 27 739 | pixel : 5 740 | pixels : 7 741 | plane : 1 742 | planes : 1 743 | planet : 18 744 | planetary : 6 745 | planets : 3 746 | plaque : 1 747 | platform : 1 748 | point : 2 749 | polar : 2 750 | portion : 2 751 | position : 2 752 | possible : 5 753 | power : 4 754 | powerful : 1 755 | precise : 1 756 | precisely : 1 757 | present : 2 758 | presently : 1 759 | previously : 1 760 | probe : 1 761 | probes : 1 762 | probing : 1 763 | process : 1 764 | produce : 1 765 | produced : 1 766 | producing : 1 767 | production : 1 768 | provide : 1 769 | provided : 2 770 | provides : 1 771 | pulses : 3 772 | pure : 2 773 | quality : 2 774 | quantity : 1 775 | questions : 1 776 | radio : 5 777 | radioed : 1 778 | radiometric : 1 779 | range : 3 780 | rapidly : 2 781 | raster : 1 782 | rate : 3 783 | rather : 2 784 | ray : 1 785 | reached : 2 786 | reaching : 2 787 | read : 2 788 | reasons : 1 789 | reassemble : 2 790 | receive : 1 791 | received : 9 792 | receiver : 2 793 | receiving : 1 794 | reception : 1 795 | reconstructed : 1 796 | recovered : 1 797 | recreate : 3 798 | red : 2 799 | reduced : 1 800 | refers : 2 801 | reflected : 1 802 | region : 1 803 | regions : 1 804 | registering : 1 805 | related : 1 806 | relayed : 2 807 | relied : 1 808 | remain : 1 809 | remained : 1 810 | renamed : 1 811 | represent : 1 812 | represented : 1 813 | represents : 3 814 | reprogrammed : 1 815 | required : 1 816 | resolution : 3 817 | resolved : 3 818 | restored : 1 819 | resulting : 2 820 | return : 1 821 | returned : 2 822 | revealed : 2 823 | revealing : 1 824 | reveals : 1 825 | righmost : 1 826 | right : 1 827 | ring : 6 828 | rings : 6 829 | rotate : 1 830 | rotates : 1 831 | rotating : 1 832 | rotation : 1 833 | route : 1 834 | rows : 1 835 | s : 22 836 | same : 3 837 | sample : 1 838 | satellite : 5 839 | satellites : 9 840 | saw : 1 841 | say : 1 842 | scanned : 2 843 | scanning : 3 844 | scatter : 2 845 | scheduled : 1 846 | scheme : 2 847 | science : 1 848 | scientists : 3 849 | scoop : 1 850 | screen : 4 851 | search : 1 852 | searching : 1 853 | second : 4 854 | seconds : 1 855 | security : 1 856 | see : 1 857 | seem : 1 858 | seen : 4 859 | selenium : 1 860 | send : 1 861 | sends : 1 862 | sensitivity : 1 863 | sensors : 4 864 | sent : 8 865 | sequence : 3 866 | set : 3 867 | several : 2 868 | shaded : 2 869 | shades : 8 870 | shaped : 2 871 | share : 1 872 | sharpening : 1 873 | shepherding : 2 874 | ship : 1 875 | shook : 1 876 | short : 1 877 | showed : 2 878 | showing : 1 879 | shown : 1 880 | shows : 1 881 | shutter : 1 882 | shutters : 1 883 | sight : 1 884 | signal : 3 885 | signals : 6 886 | similar : 2 887 | site : 1 888 | sites : 2 889 | six : 3 890 | sky : 4 891 | slight : 1 892 | slow : 1 893 | slowed : 1 894 | slower : 1 895 | slowly : 1 896 | small : 2 897 | snap : 1 898 | so : 5 899 | society : 1 900 | soft : 5 901 | soil : 1 902 | some : 1 903 | sometimes : 1 904 | sought : 1 905 | space : 13 906 | spacecraft : 24 907 | spectroscopes : 1 908 | sped : 1 909 | speeds : 1 910 | spokes : 1 911 | spread : 1 912 | square : 2 913 | squares : 1 914 | stabilizing : 1 915 | stargazer : 1 916 | stargazers : 3 917 | stars : 1 918 | startling : 1 919 | station : 3 920 | steadily : 1 921 | still : 1 922 | stone : 1 923 | storage : 1 924 | store : 1 925 | stored : 4 926 | strategy : 1 927 | stream : 1 928 | striking : 1 929 | strong : 1 930 | structure : 1 931 | studied : 2 932 | studios : 1 933 | subtle : 2 934 | successfully : 2 935 | succession : 1 936 | successive : 1 937 | such : 8 938 | sulfur : 1 939 | suppose : 1 940 | surface : 19 941 | surfaces : 1 942 | swing : 1 943 | switch : 1 944 | symbol : 1 945 | system : 7 946 | systems : 2 947 | table : 1 948 | take : 2 949 | taken : 6 950 | taking : 1 951 | tape : 2 952 | target : 2 953 | targets : 1 954 | task : 1 955 | technique : 6 956 | technology : 2 957 | telemetered : 1 958 | telemetry : 2 959 | telephoto : 1 960 | telescope : 1 961 | telescopes : 3 962 | television : 11 963 | temporarily : 2 964 | th : 1 965 | than : 12 966 | that : 22 967 | the : 207 968 | their : 6 969 | them : 5 970 | then : 6 971 | theories : 1 972 | there : 1 973 | thereby : 1 974 | they : 8 975 | thin : 1 976 | this : 5 977 | those : 5 978 | thought : 1 979 | thousand : 1 980 | thousands : 1 981 | three : 9 982 | through : 9 983 | tilted : 2 984 | time : 4 985 | times : 3 986 | tiniest : 1 987 | tiny : 2 988 | to : 82 989 | today : 1 990 | together : 1 991 | tone : 1 992 | tones : 1 993 | too : 1 994 | took : 3 995 | tools : 2 996 | top : 1 997 | topography : 1 998 | total : 3 999 | track : 2 1000 | tracked : 1 1001 | tracking : 3 1002 | trajectory : 2 1003 | translation : 1 1004 | transmission : 3 1005 | transmit : 2 1006 | transmitted : 7 1007 | transmitting : 2 1008 | transparent : 1 1009 | travel : 1 1010 | traveled : 1 1011 | traveling : 1 1012 | true : 1 1013 | tube : 5 1014 | twenty : 1 1015 | twice : 1 1016 | two : 6 1017 | typically : 1 1018 | ultraviolet : 1 1019 | unaided : 3 1020 | unblurred : 1 1021 | under : 1 1022 | understand : 1 1023 | unexplored : 1 1024 | unfolded : 1 1025 | unit : 3 1026 | universe : 2 1027 | unknown : 2 1028 | unmanned : 1 1029 | unprecedented : 1 1030 | until : 4 1031 | up : 4 1032 | us : 1 1033 | use : 3 1034 | used : 5 1035 | useful : 1 1036 | using : 1 1037 | vacuum : 1 1038 | valleys : 1 1039 | value : 11 1040 | values : 10 1041 | various : 3 1042 | variously : 1 1043 | vary : 1 1044 | varying : 1 1045 | ventured : 1 1046 | verified : 1 1047 | very : 3 1048 | vicinity : 1 1049 | vidicon : 2 1050 | view : 3 1051 | visited : 1 1052 | visual : 2 1053 | volcanic : 1 1054 | volcano : 1 1055 | volcanoes : 2 1056 | wanderers : 1 1057 | was : 11 1058 | waves : 1 1059 | way : 3 1060 | ways : 1 1061 | we : 2 1062 | well : 2 1063 | were : 12 1064 | what : 3 1065 | when : 6 1066 | where : 2 1067 | whereas : 1 1068 | which : 5 1069 | while : 5 1070 | white : 8 1071 | whose : 1 1072 | wide : 1 1073 | will : 6 1074 | with : 18 1075 | within : 2 1076 | without : 1 1077 | women : 1 1078 | wonder : 1 1079 | work : 1 1080 | works : 1 1081 | world : 1 1082 | would : 4 1083 | wrong : 1 1084 | x : 1 1085 | yearning : 1 1086 | years : 1 1087 | you : 3 1088 | zero : 2 -------------------------------------------------------------------------------- /Chapter05/sets.jl: -------------------------------------------------------------------------------- 1 | s = Set([11, 14, 13, 7, 14, 11]) 2 | #> Set([7, 14, 13, 11]) 3 | 4 | # empty set: 5 | Set() #> Set(Any[]) 6 | 7 | s1 = Set([11, 25]) 8 | s2 = Set([25, 3.14]) 9 | union(s1, s2) #> Set([3.14, 25.0, 11.0]) 10 | intersect(s1, s2) #> Set([25]) 11 | setdiff(s1, s2) #> Set([11]) 12 | setdiff(s2, s1) #> Set([3.14]) 13 | issubset(s1, s2) #> false 14 | issubset(s1, Set([11, 25, 36])) #> true 15 | 16 | push!(s1, 32) #> Set([25,32,11]) 17 | in(32, s1) #> true 18 | in(100, s1) #> false 19 | 20 | s1 = Set([1,2,3]) #> Set([2,3,1]) 21 | typeof(s1) #> Set{Int64} 22 | Set([[1,2,3]]) #> Set(Array{Int64,1}[[1, 2, 3]]) 23 | 24 | x = Set(collect(1:100)) 25 | @time 2 in x 26 | #> 0.003186 seconds (33 allocations: 2.078 KiB) 27 | x2 = Set(collect(1:1000000)) 28 | @time 2 in x2 29 | # 0.000003 seconds (4 allocations: 160 bytes) 30 | -------------------------------------------------------------------------------- /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) #> Tuple{Int64,Float64,String,Char} 8 | t2 = (1, 2, 3) 9 | typeof(t2) #> Tuple{Int64,Int64,Int64} 10 | () #> empty tuple 11 | (1,) #> one element tuple 12 | ('z', 3.14)::Tuple{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", 62) 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 62 -------------------------------------------------------------------------------- /Chapter05/word_frequency.jl: -------------------------------------------------------------------------------- 1 | # 1- read in text file: 2 | str = read("words1.txt", String) 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 -------------------------------------------------------------------------------- /Chapter05/words1.txt: -------------------------------------------------------------------------------- 1 | to be, or not to be, that is the question! -------------------------------------------------------------------------------- /Chapter05/words2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter05/words2.txt -------------------------------------------------------------------------------- /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) #> ERROR: InexactError: Int64(Int64, 7.01) 6 | # convert(Int64, "CV") 7 | # ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64 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, 1.0) #> (1.0, 1.0) 13 | promote_type(Int8, UInt16) #> UInt16 -------------------------------------------------------------------------------- /Chapter06/file1.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter06/file1.jl -------------------------------------------------------------------------------- /Chapter06/file2.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter06/file2.jl -------------------------------------------------------------------------------- /Chapter06/inner_constructors.jl: -------------------------------------------------------------------------------- 1 | mutable struct 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) #> 1-element Array{Person,1}: 14 | #Person("Alan", "Bates", 'M', 45.5, ["Jeff", "Stephan"]) 15 | push!(people, Person("Julia", "Smith", 'F', 27, ["Viral"])) 16 | 17 | show(people) 18 | #> Person[Person("Alan", "Bates", 'M', 45.5, ["Jeff", "Stephan"]), 19 | # Person("Julia", "Smith", 'F', 27.0, ["Viral"])] 20 | 21 | fullname(p::Person) = "$(p.firstname) $(p.lastname)" 22 | fullname(p::Person) = string(p.firstname, " ", p.lastname) 23 | print(fullname(p1)) #> Alan Bates 24 | 25 | mutable struct Family 26 | name::String 27 | members::Array{String, 1} 28 | big::Bool 29 | Family(name::String) = new(name, String[], false) 30 | Family(name::String, members) = new(name, members, length(members) > 4) 31 | end 32 | 33 | fam = Family("Bates-Smith", ["Alan", "Julia", "Jeff", "Stephan", "Viral"]) 34 | #> Family("Bates-Smith",String["Alan","Julia","Jeff","Stephan","Viral"],true) -------------------------------------------------------------------------------- /Chapter06/modules.jl: -------------------------------------------------------------------------------- 1 | module Package1 2 | 3 | export Type1, perc 4 | 5 | include("file1.jl") 6 | include("file2.jl") 7 | 8 | # code 9 | mutable struct Type1 10 | total 11 | end 12 | 13 | perc(a::Type1) = a.total * 0.01 14 | 15 | end -------------------------------------------------------------------------------- /Chapter06/parametric.jl: -------------------------------------------------------------------------------- 1 | mutable struct 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 | Point{Int64} <: Point #> true 11 | Point{String} <: Point #> true 12 | 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 | mutable struct PointP{T <: Real} 19 | x::T 20 | y::T 21 | end 22 | 23 | # p = PointP("London", "Great-Britain") #> ERROR: MethodError: no method matching PointP(::String, ::String) 24 | 25 | add(x::T, y::T) where T = x + y 26 | add(2, 3) #> 5 27 | # add(2, 3.0) #> ERROR: MethodError: `add` has no method matching add(::Int64, ::Float64) 28 | add(x::T, y::T) where T <: Number = x + y 29 | 30 | function vecfloat(x::Vector{T}) where T <: AbstractFloat 31 | # code 32 | end -------------------------------------------------------------------------------- /Chapter06/temperature_converter.jl: -------------------------------------------------------------------------------- 1 | module TemperatureConverter 2 | 3 | function as_celsius(temperature, unit) 4 | if unit == :Celsius 5 | return temperature 6 | elseif unit == :Kelvin 7 | return kelvin_to_celsius(temperature) 8 | end 9 | end 10 | 11 | function kelvin_to_celsius(temperature) 12 | # 'private' function 13 | return temperature + 273 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /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 | supertype(Int64) #> Signed 8 | supertype(Signed) #> Integer 9 | supertype(Integer) #> Real 10 | supertype(Real) #> Number 11 | supertype(Number) #> Any 12 | supertype(Any) #> Any 13 | 14 | using InteractiveUtils 15 | subtypes(Integer) #> 3-element Array{Any,1}: 16 | # Bool 17 | # Signed 18 | # Unsigned 19 | subtypes(Signed) #> 6-element Array{Any,1}: 20 | # BigInt 21 | # Int128 22 | # Int16 23 | # Int32 24 | # Int64 25 | # Int8 26 | subtypes(Int64) #> 0-element Array{Any,1} 27 | typeof(Nothing) #> DataType 28 | 29 | Bool <: Integer #> true 30 | Bool <: Any #> true 31 | Bool <: Char #> false 32 | Bool <: Integer #> true 33 | Float64 <: Integer #> false 34 | 35 | typeof(5) #> Int64 36 | isa(5, Number) #> true -------------------------------------------------------------------------------- /Chapter06/unions.jl: -------------------------------------------------------------------------------- 1 | mutable struct Point 2 | x::Float64 3 | y::Float64 4 | end 5 | 6 | mutable struct 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) #> MethodError: ERROR: `+` has no method matching +(::Point, ::Vector2D) 16 | 17 | import Base.+ 18 | +(p::Point, q::Point) = Point(p.x + q.x, p.y + q.y) 19 | +(u::Vector2D, v::Vector2D) = Point(u.x + v.x, u.y + v.y) 20 | +(u::Vector2D, p::Point) = Point(u.x + p.x, u.y + p.y) 21 | # +(p, v) #> ERROR: MethodError: `+` has no method matching +(::Point, ::Vector2D) 22 | +(p::Point, v::Vector2D) = Point(p.x + v.x, p.y + v.y) 23 | +(p, v) #> Point(5.0,7.0) 24 | 25 | # Example with dot product: 26 | # *(p, v) #> ERROR: MethodError: `*` has no method matching *(::Point, ::Vector2D) 27 | 28 | import Base.* 29 | *(p::Point, q::Point) = p.x * q.x + p.y * q.y 30 | *(u::Vector2D, v::Vector2D) = u.x * v.x + u.y * v.y 31 | *(u::Vector2D, p::Point) = u.x * p.x + u.y * p.y 32 | # *(p, v) #> ERROR: MethodError: `*` has no method matching *(::Point, ::Vector2D) 33 | *(p::Point, v::Vector2D) = p.x * v.x + p.y * v.y 34 | *(p, v) #> 16.0 35 | 36 | VecOrPoint = Union{Vector2D, Point} 37 | 38 | isa(p, VecOrPoint) #> true 39 | isa(v, VecOrPoint) #> true 40 | 41 | +(u::VecOrPoint, v:: VecOrPoint) = VecOrPoint(u.x + v.x, u.y + v.y) 42 | +(p, v) #> Point(5.0,7.0) 43 | 44 | *(u::VecOrPoint, v:: VecOrPoint) = u.x * v.x + u.y * v.y 45 | *(p, v) #> 16.0 -------------------------------------------------------------------------------- /Chapter06/user_defined.jl: -------------------------------------------------------------------------------- 1 | using InteractiveUtils 2 | 3 | mutable struct Point 4 | x::Float64 5 | y::Float64 6 | z::Float64 7 | end 8 | 9 | typeof(Point) #> DataType 10 | 11 | fieldnames(Point) #> (:x, :y, :z) 12 | 13 | orig = Point(0, 0, 0) #> Point(0.0,0.0,0.0) 14 | p1 = Point(2, 4, 1.3) #> Point(2.0,4.0,1.3) 15 | fieldnames(typeof(p1)) #> (:x, :y, :z) 16 | 17 | methods(Point) 18 | # 3 methods for generic function "(::Type)": 19 | # [1] Point(x::Float64, y::Float64, z::Float64) in Main at REPL[12]:2 20 | # [2] Point(x, y, z) in Main at REPL[12]:2 21 | # [3] (::Type{T})(arg) where T in Base at deprecated.jl:461 22 | 23 | typeof(p1) #> Point (constructor with 1 method) 24 | subtypes(Point) #> 0-element Array{Type,1} 25 | 26 | p1.y #> 4.0 27 | p1.z = 3.14 #> 3.14 28 | p1 #> Point(2.0, 4.0, 3.14) 29 | # p1.z = "A" #> ERROR: MethodError: Cannot `convert` an object of type String 30 | # to an object of type Float64 31 | 32 | struct Vector3D 33 | x::Float64 34 | y::Float64 35 | z::Float64 36 | end 37 | typeof(Vector3D) #> DataType 38 | p = Vector3D(1, 2, 3) #> Vector3D(1.0,2.0,3.0) 39 | # p.y = 5 #> ERROR: type Vector3D is immutable 40 | 41 | Point3D = Point 42 | p31 = Point3D(1, 2, 3) #> Point(1.0,2.0,3.0) 43 | 44 | 5 == 5 #> true 45 | 5 == 5.0 #> true 46 | isequal(5, 5) #> true 47 | isequal(5, 5.0) #> true 48 | 5 === 5 #> true 49 | 5 === 5.0 #> false 50 | 51 | q = Vector3D(4.0, 3.14, 2.71) 52 | r = Vector3D(4.0, 3.14, 2.71) 53 | isequal(q, r) #> true 54 | q === r #> true 55 | 56 | mutable struct MVector3D 57 | x::Float64 58 | y::Float64 59 | z::Float64 60 | end 61 | 62 | q = MVector3D(4.0, 3.14, 2.71) 63 | r = MVector3D(4.0, 3.14, 2.71) 64 | isequal(q, r) #> false 65 | q === r #> false 66 | 67 | # constructors, subtyping and multiple dispatch 68 | abstract type Employee 69 | end 70 | 71 | # Employee() #> ERROR: MethodError: no constructors have been defined for Employee 72 | 73 | mutable struct Developer <: Employee 74 | name::String 75 | iq 76 | favorite_lang 77 | end 78 | 79 | # mutable struct MobileDeveloper <: Developer 80 | # platform 81 | # end 82 | # ERROR: invalid subtyping in definition of MobileDeveloper 83 | 84 | # outer constructor: 85 | Developer(name, iq) = Developer(name, iq, "Java") 86 | #> Developer (constructor with 3 methods) 87 | 88 | mutable struct Manager 89 | name::String 90 | iq 91 | department::String 92 | end 93 | 94 | devel1 = Developer("Bob", 110) #> Developer("Bob",110,"Java") 95 | devel2 = Developer("William", 145, "Julia") 96 | #> Developer("William",145,"Julia") 97 | man1 = Manager("Julia", 120, "ICT") #> Manager("Julia",120,"ICT") 98 | 99 | cleverness(emp::Employee) = emp.iq 100 | cleverness(devel1) #> 110 101 | # cleverness(man1) #> ERROR: MethodError: `cleverness` has no method 102 | # matching cleverness(::Manager) 103 | 104 | function cleverer(m::Manager, e::Employee) 105 | println("The manager $(m.name) is cleverer!") 106 | end 107 | 108 | cleverer(man1, devel1) #> The manager Julia is cleverer! 109 | cleverer(man1, devel2) #> The manager Julia is cleverer! 110 | 111 | function cleverer(d::Developer, e::Employee) 112 | println("The developer $(d.name) is cleverer!") 113 | end 114 | 115 | cleverer(devel1, devel2) #> The developer Bob is cleverer! 116 | # cleverer(devel1, man1) #> ERROR: `cleverer` has no method matching cleverer(::Developer,::Manager) 117 | 118 | function cleverer(e::Employee, d::Developer) 119 | if e.iq <= d.iq 120 | println("The developer $(d.name) is cleverer!") 121 | else 122 | println("The employee $(e.name) is cleverer!") 123 | end 124 | end 125 | 126 | # cleverer(devel1, devel2) 127 | #> ERROR: MethodError: cleverer(::Developer, ::Developer) is ambiguous. Candidates: 128 | # cleverer(e::Employee, d::Developer) in Main at REPL[32]:2 129 | # cleverer(d::Developer, e::Employee) in Main at REPL[29]:2 130 | # Possible fix, define 131 | # cleverer(::Developer, ::Developer) 132 | 133 | function cleverer(d1::Developer, d2::Developer) 134 | if d1.iq <= d2.iq 135 | println("The developer $(d2.name) is cleverer!") 136 | else 137 | println("The developer $(d1.name) is cleverer!") 138 | end 139 | end 140 | 141 | cleverer(devel1, devel2) #> The developer William is cleverer! 142 | cleverer(devel2, devel1) #> The developer William is cleverer! -------------------------------------------------------------------------------- /Chapter06/using_module.jl: -------------------------------------------------------------------------------- 1 | include("temperature_converter.jl") 2 | 3 | println("$(TemperatureConverter.as_celsius(100, :Celsius))") #> 100 4 | println("$(TemperatureConverter.as_celsius(100, :Kelvin))") #> 373 5 | println("$(TemperatureConverter.kelvin_to_celsius(0))") #> 273 -------------------------------------------------------------------------------- /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 Test 6 | # @test 1==3 7 | #> 8 | # Test Failed at REPL[5]:1 9 | # Expression: 1 == 3 10 | # Evaluated: 1 == 3 11 | # ERROR: There was an error during testing. 12 | 13 | # @test 1 ≈ 1.1 14 | # Test Failed at REPL[58]:1 15 | # Expression: 1 ≈ 1.1 16 | # Evaluated: 1 ≈ 1.1 17 | # ERROR: There was an error during testing 18 | @test 1 ≈ 1.1 atol=0.2 #> Test Passed 19 | 20 | # Debugging: 21 | using InteractiveUtils # for @which 22 | arr = [1, 2] #> 2-element Array{Int64,1}: 1 2 23 | @which sort(arr) 24 | #> sort(v::AbstractArray{T,1} where T) in Base.Sort at sort.jl:683 25 | 456 * 789 + (@show 2 + 3) #> 2 + 3 => 5 359789 26 | 27 | # Benchmarking: 28 | @time [x^2 for x in 1:1000] #> elapsed time: 3.911e-6 seconds (8064 bytes allocated) # 1000-element Array{Int64,1}: … 29 | @timed [x^2 for x in 1:1000] 30 | #> ([1,4,9,16,25,36,49,64,81,100 … 982081,984064,986049,988036,990025,992016,9940 31 | # 09,996004,998001,1000000],3.911e-6,8064,0.0) 32 | @elapsed [x^2 for x in 1:1000] #> 3.422e-6 33 | @allocated [x^2 for x in 1:1000] #> 8064 34 | 35 | # starting a task: 36 | a = @async 1 + 2 37 | # Task (done) @0x000000002d70faf0 38 | -------------------------------------------------------------------------------- /Chapter07/eval.jl: -------------------------------------------------------------------------------- 1 | e1 = Expr(:call, *, 3, 4) #> :((*)(3,4)) 2 | eval(e1) #> 12 3 | 4 | # e1 = Expr(:call, *, 3, a) #> ERROR: UndefVarError: a not defined 5 | e2 = Expr(:call, *, 3, :a) #> :((*)(3,a)) 6 | # eval(e2) #> ERROR: UndefVarError: a not defined 7 | a = 4 #> 4 8 | eval(e2) #> 12 9 | 10 | # b #> ERROR: UndefVarError: 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 -------------------------------------------------------------------------------- /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 | e1.head #> :call 27 | e1.args #> 3-element Array{Any,1}: :+ 2 3 28 | 2 + 3 == +(2, 3) #> true 29 | 30 | e2 = :(2 + a * b - c) 31 | e2.args #> 3-element Array{Any,1}: :- :(2 + a * b) :c 32 | :(2 + a * b).args #> 3-element Array{Any,1}: :+ 2 :(a * b) 33 | :(a * b).args #> 3-element Array{Any,1}: :* :a :b 34 | 35 | x = 5 #> 5 36 | :x #> :x 37 | 38 | dump(:(2 + 2)) 39 | # Expr 40 | # head: Symbol call 41 | # args: Array(Any,(3,)) 42 | # 1: Symbol + 43 | # 2: Int64 2 44 | # 3: Int64 2 45 | 46 | dump(:(2 + a * b - c)) 47 | # Expr 48 | # head: Symbol call 49 | # args: Array(Any,(3,)) 50 | # 1: Symbol - 51 | # 2: Expr 52 | # head: Symbol call 53 | # args: Array(Any,(3,)) 54 | # 1: Symbol + 55 | # 2: Int64 2 56 | # 3: Expr 57 | # head: Symbol call 58 | # args: Array(Any,(3,)) 59 | # typ: Any 60 | # typ: Any 61 | # 3: Symbol c -------------------------------------------------------------------------------- /Chapter07/macros.jl: -------------------------------------------------------------------------------- 1 | # Example 1: 2 | macro macint(ex) 3 | quote 4 | println("start") 5 | $ex 6 | println("after") 7 | end 8 | end 9 | 10 | @macint println("Where am I?") 11 | #start 12 | #Where am I? 13 | #after 14 | 15 | # Example 2: 16 | macro duplicate(ex) 17 | quote 18 | $ex 19 | $ex 20 | end 21 | end 22 | 23 | @duplicate println(sin(42)) 24 | # -0.9165215479156338 25 | # -0.9165215479156338 26 | 27 | # Example 3: 28 | macro assert(ex) 29 | :($ex ? nothing : error("Assertion failed: ", $(string(ex)))) 30 | end 31 | 32 | @assert 1 == 1.0 33 | # @assert 1 == 42 #> ERROR: Assertion failed: 1 == 42 34 | 35 | # Example 4: 36 | macro unless(test_cond, branch) 37 | quote 38 | if !$test_cond 39 | $branch 40 | end 41 | end 42 | end 43 | 44 | arr = [3.14, 42, 'b'] 45 | @unless 41 in arr println("arr does not contain 41") 46 | #> array does not contain 41 47 | @unless 42 in arr println("arr does not contain 42") #> nothing 48 | @unless isempty(arr) println("array arr has elements") 49 | #> array arr has elements 50 | 51 | macroexpand(Main, :(@unless 41 in arr println("arr does not contain 41")) ) 52 | # quote 53 | # #= REPL[15]:3 =# 54 | # if !(41 in Main.arr) 55 | # #= REPL[15]:4 =# 56 | # (Main.println)("arr does not contain 41") 57 | # end 58 | # end 59 | 60 | # Example 5: 61 | @time factorial(10) 62 | #> 0.023171 seconds (15.36 k allocations: 797.196 KiB) 63 | # 3628800 64 | 65 | using Printf 66 | macro timeit(ex) 67 | quote 68 | local t0 = time() # local necessary to not conflict with outside 69 | local val = $(esc(ex)) # variables; esc makes sure ex is not 70 | local t1 = time() # expanded, but is used literally 71 | print("elapsed time in seconds: ") 72 | @printf "%.3f" t1 - t0 73 | val 74 | end 75 | end 76 | 77 | @timeit factorial(10) #> elapsed time in seconds: 0.0003628800 78 | @timeit factorial(15) #> elapsed time in seconds: 0.0001307674368000 79 | a = 42 80 | @timeit a^3 #> elapsed time in seconds: 0.00074088 81 | 82 | # Example 6: 83 | using Statistics 84 | macro bench(f) 85 | quote 86 | median([@elapsed sleep($f) for x=1:10]) 87 | end 88 | end 89 | 90 | @bench 0.1 #> 0.1010291465 91 | @bench 0.2 #> 0.20101891449999998 92 | @bench 0.5 #> 0.501034175 -------------------------------------------------------------------------------- /Chapter07/reflection.jl: -------------------------------------------------------------------------------- 1 | mutable struct Person 2 | name:: String 3 | height::Float64 4 | end 5 | 6 | fieldnames(Person) #> (:name, :height) 7 | Person.types #> svec(String, Float64) 8 | 9 | code_lowered(+, (Int, Int)) 10 | # 1-element Array{Core.CodeInfo,1}: 11 | # CodeInfo( 12 | # 53 1 ─ %1 = Base.add_int(%%x, %%y)::Any │ 13 | # └── return %1 │ 14 | # ) 15 | 16 | code_typed(+, (Int, Int)) 17 | # 1-element Array{Any,1}: 18 | # CodeInfo( 19 | # 53 1 ─ %1 = Base.add_int(%%x, %%y)::Int64 │ 20 | # └── return %1 │ 21 | # ) => Int64 -------------------------------------------------------------------------------- /Chapter08/csv_files.jl: -------------------------------------------------------------------------------- 1 | fname = "winequality.csv" 2 | 3 | using DelimitedFiles 4 | data = DelimitedFiles.readdlm(fname, ';') 5 | # 1600x12 Array{Any,2}: 6 | # "fixed acidity" "volatile acidity" … "alcohol" "quality" 7 | # 7.4 0.7 9.4 5.0 8 | # 7.8 0.88 9.8 5.0 9 | # 7.8 0.76 9.8 5.0 10 | # 11.2 0.28 9.8 6.0 11 | 12 | # variant: 13 | data3 = DelimitedFiles.readdlm(fname, ';', Float64, '\n', header=true) 14 | #> ([7.4 0.7 … 9.4 5.0; 7.8 0.88 … 9.8 5.0; … ; 5.9 0.645 … 10.2 5.0; 15 | # 6.0 0.31 … 11.0 6.0], 16 | # AbstractString["fixed acidity" "volatile acidity" … "alcohol" "quality"]) 17 | 18 | # extracting data: 19 | row3 = data[3, :] # measurements for wine xyz 20 | # 12-element Array{Any,1}: 7.8 0.88 0 2.6 0.098 25 67 0.9968 3.2 0.68 9.8 5 21 | col3 = data[ :, 3] # measurements of citric acid 22 | # 1600-element Array{Any,1}: 23 | # "citric acid" 24 | # 0.0 0.0 0.04 0.56 0.0 0.0 ⋮ 0.08 0.08 0.1 0.13 0.12 0.47 ... 25 | x = data[:, 2:4] 26 | # 1600×3 Array{Any,2}: 27 | # "volatile acidity" "citric acid" "residual sugar" 28 | # 0.7 0 1.9 29 | # 0.88 0 2.6 30 | # 0.76 0.04 2.3 31 | y = data[70:75, 2:4] 32 | # 6x3 Array{Any,2}: 33 | # 0.32 0.57 2.0 34 | # 0.705 0.05 1.9 35 | # 0.63 0.08 1.9 36 | # 0.67 0.23 2.1 37 | # 0.69 0.22 1.9 38 | # 0.675 0.26 2.1 39 | z = [data[:,3] data[:,6] data[:,11]] 40 | # 1600x3 Array{Any,2}: 41 | # "citric acid" "free sulfur dioxide" "alcohol" 42 | # 0.0 11.0 9.4 43 | # 0.0 25.0 9.8 44 | # 0.04 15.0 9.8 45 | # 0.56 17.0 9.8 46 | # ⋮ 47 | # 0.08 32.0 10.5 48 | # 0.1 39.0 11.2 49 | # 0.13 29.0 11.0 50 | # 0.12 32.0 10.2 51 | # 0.47 18.0 11.0 52 | 53 | # without headers: 54 | z = [data[2:end,3] data[2:end,6] data[2:end,11]] 55 | 56 | mutable struct Wine 57 | fixed_acidity::Array{Float64} 58 | volatile_acidity::Array{Float64} 59 | citric_acid::Array{Float64} 60 | #...define the other columns here 61 | quality::Array{Float64} 62 | end 63 | # wine1 = Wine(7.4, 0.7, 0, ..., 5) 64 | # wine1 = Wine(data[1, :]...) # ... = splat-operator 65 | 66 | data = z 67 | # writing to csv file: 68 | writedlm("partial.dat", data, ';') -------------------------------------------------------------------------------- /Chapter08/dataframes.jl: -------------------------------------------------------------------------------- 1 | using DataFrames, Missings, CSV 2 | 3 | # constructing a DataFrame: 4 | df = DataFrame() 5 | df[:Col1] = 1:4 6 | df[:Col2] = [exp(1), pi, sqrt(2), 42] 7 | df[:Col3] = [true, false, true, false] 8 | show(df) 9 | # 4x3 DataFrame 10 | # | Row | Col1 | Col2 | Col3 | 11 | # |-----|------|---------|-------| 12 | # | 1 | 1 | 2.71828 | true | 13 | # | 2 | 2 | 3.14159 | false | 14 | # | 3 | 3 | 1.41421 | true | 15 | # | 4 | 4 | 42.0 | false | 16 | 17 | df = DataFrame(Col1 = 1:4, Col2 = [exp(1), pi, sqrt(2), 42], Col3 = [true, false, true, false]) 18 | 19 | # columns: 20 | show(df[2]) 21 | #> [2.718281828459045,3.141592653589793,1.4142135623730951,42.0] 22 | show(df[:Col2]) #> same output 23 | 24 | # rows: 25 | show(df[1, :]) #> 1st row 26 | # 1x3 DataFrame 27 | # | Row | Col1 | Col2 | Col3 | 28 | # |-----|------|---------|------| 29 | # | 1 | 1 | 2.71828 | true | 30 | show(df[2:3, :]) #> 2nd and 3rd row: 31 | # 2x3 DataFrame 32 | # | Row | Col1 | Col2 | Col3 | 33 | # |-----|------|---------|-------| 34 | # | 1 | 2 | 3.14159 | false | 35 | # | 2 | 3 | 1.41421 | true | 36 | show(df[2:3, :Col2]) #> 2nd and 3rd row, only 2nd column: 37 | # [3.141592653589793,1.4142135623730951] 38 | df[2:3, [:Col2, :Col3]] #> 2nd and 3rd row, 2nd and 3rd column: 39 | # 2x2 DataFrame 40 | # | Row | Col2 | Col3 | 41 | # |-----|---------|-------| 42 | # | 1 | 3.14159 | false | 43 | # | 2 | 1.41421 | true | 44 | head(df) 45 | 46 | df0 = DataFrame(i = 1:10, x = rand(10), y = rand(["a", "b", "c"], 10)) 47 | head(df0) 48 | 49 | tail(df) 50 | 51 | names(df) 52 | # 3-element Array{Symbol,1}: 53 | # :Col1 54 | # :Col2 55 | # :Col3 56 | eltypes(df) 57 | # 3-element Array{Type{T<:Top},1}: 58 | # Int64 59 | # Float64 60 | # Bool 61 | 62 | describe(df) 63 | # 3×8 DataFrame 64 | # │ Row │ variable │ mean │ min │ median │ max │ nunique │ nmissing │ eltype │ 65 | # ├─────┼──────────┼─────────┼─────────┼─────────┼──────┼─────────┼──────────┼─────────┤ 66 | # │ 1 │ Col1 │ 2.5 │ 1 │ 2.5 │ 4 │ │ │ Int64 │ 67 | # │ 2 │ Col2 │ 12.3185 │ 1.41421 │ 2.92994 │ 42.0 │ │ │ Float64 │ 68 | # │ 3 │ Col3 │ 0.5 │ false │ 0.5 │ true │ │ │ Bool │ 69 | 70 | fname = "winequality.csv" 71 | data = CSV.read(fname, delim = ';') 72 | # 1599x12 DataFrame 73 | # | Row | fixed_acidity | volatile_acidity | citric_acid | residual_sugar | 74 | # |------|---------------|------------------|-------------|----------------| 75 | # | 1 | 7.4 | 0.7 | 0.0 | 1.9 | 76 | # | 2 | 7.8 | 0.88 | 0.0 | 2.6 | 77 | # | 3 | 7.8 | 0.76 | 0.04 | 2.3 | 78 | # ⋮ 79 | # | 1596 | 5.9 | 0.55 | 0.1 | 2.2 | 80 | # | 1597 | 6.3 | 0.51 | 0.13 | 2.3 | 81 | # | 1598 | 5.9 | 0.645 | 0.12 | 2.0 | 82 | # | 1599 | 6.0 | 0.31 | 0.47 | 3.6 | 83 | 84 | # | Row | chlorides | free_sulfur_dioxide | total_sulfur_dioxide | density | 85 | # |------|-----------|---------------------|----------------------|---------| 86 | # | 1 | 0.076 | 11.0 | 34.0 | 0.9978 | 87 | # | 2 | 0.098 | 25.0 | 67.0 | 0.9968 | 88 | # | 3 | 0.092 | 15.0 | 54.0 | 0.997 | 89 | # ⋮ 90 | # | 1596 | 0.062 | 39.0 | 51.0 | 0.99512 | 91 | # | 1597 | 0.076 | 29.0 | 40.0 | 0.99574 | 92 | # | 1598 | 0.075 | 32.0 | 44.0 | 0.99547 | 93 | # | 1599 | 0.067 | 18.0 | 42.0 | 0.99549 | 94 | 95 | # | Row | pH | sulphates | alcohol | quality | 96 | # |------|------|-----------|---------|---------| 97 | # | 1 | 3.51 | 0.56 | 9.4 | 5 | 98 | # | 2 | 3.2 | 0.68 | 9.8 | 5 | 99 | # | 3 | 3.26 | 0.65 | 9.8 | 5 | 100 | # ⋮ 101 | # | 1596 | 3.52 | 0.76 | 11.2 | 6 | 102 | # | 1597 | 3.42 | 0.75 | 11.0 | 6 | 103 | # | 1598 | 3.57 | 0.71 | 10.2 | 5 | 104 | # | 1599 | 3.39 | 0.66 | 11.0 | 6 | 105 | typeof(data) # DataFrame 106 | size(data) # (1599,12) 107 | data[:density] 108 | # 1599-element DataArray{Float64,1}: 109 | # 0.9978 110 | # 0.9968 111 | # 0.997 112 | # 0.998 113 | # ⋮ 114 | # 0.99512 115 | # 0.99574 116 | # 0.99547 117 | # 0.99549 118 | CSV.write("dataframe1.csv", df, delim = ';') 119 | 120 | # queries: 121 | # the quality for all wines: 122 | data[:quality] 123 | # give the wines with alcohol % = 9.5 124 | show(data[ data[:alcohol].== 9.5, :]) 125 | # count the number of wines grouped by quality 126 | show(by(data, :quality, data -> size(data, 1))) 127 | # 6x2 DataFrame 128 | # | Row | quality | x1 | 129 | # |-----|---------|-----| 130 | # | 1 | 3 | 10 | 131 | # | 2 | 4 | 53 | 132 | # | 3 | 5 | 681 | 133 | # | 4 | 6 | 638 | 134 | # | 5 | 7 | 199 | 135 | # | 6 | 8 | 18 | 136 | _, count = hist(data[:quality]) 137 | #> count 6-element Array{Int64,1}: 10 53 681 638 199 18 138 | class = sort(unique(data[:quality])) 139 | #> 6-element DataArray{Int64,1}: 3 4 5 6 7 8 140 | df_quality = DataFrame(qual=class, no=count) 141 | # 6x2 DataFrame 142 | # | Row | qual | no | 143 | # |-----|------|-----| 144 | # | 1 | 3 | 10 | 145 | # | 2 | 4 | 53 | 146 | # | 3 | 5 | 681 | 147 | # | 4 | 6 | 638 | 148 | # | 5 | 7 | 199 | 149 | # | 6 | 8 | 18 | 150 | -------------------------------------------------------------------------------- /Chapter08/defs.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter08/defs.jl -------------------------------------------------------------------------------- /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 | using Sockets 4 | server = Sockets.listen(8080) 5 | while true 6 | conn = accept(server) 7 | @async begin 8 | try 9 | while true 10 | line = readline(conn) 11 | println(line) 12 | write(conn,line) 13 | end 14 | catch ex 15 | print("connection ended with error $ex") 16 | end 17 | end # end coroutine block 18 | end -------------------------------------------------------------------------------- /Chapter08/example.dat: -------------------------------------------------------------------------------- 1 | this is line 1. 2 | 42; 3.14 3 | this is line 3. -------------------------------------------------------------------------------- /Chapter08/example2.dat: -------------------------------------------------------------------------------- 1 | I write myself to a file 2 | even with println! 3 | -------------------------------------------------------------------------------- /Chapter08/functions.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter08/functions.jl -------------------------------------------------------------------------------- /Chapter08/instpubs.sql: -------------------------------------------------------------------------------- 1 | /* */ 2 | /* InstPubs.SQL - Creates the Pubs database */ 3 | /* */ 4 | CREATE DATABASE pubs 5 | GO 6 | 7 | USE pubs 8 | GO 9 | 10 | CREATE TABLE titles 11 | ( 12 | title_id tid 13 | 14 | CONSTRAINT UPKCL_titleidind PRIMARY KEY CLUSTERED, 15 | 16 | title varchar(80) NOT NULL, 17 | type char(12) NOT NULL 18 | 19 | DEFAULT ('UNDECIDED'), 20 | 21 | pub_id char(4) NULL 22 | price money NULL, 23 | advance money NULL, 24 | royalty int NULL, 25 | ytd_sales int NULL, 26 | notes varchar(200) NULL, 27 | 28 | pubdate datetime NOT NULL 29 | 30 | DEFAULT (getdate()) 31 | ) 32 | GO 33 | 34 | 35 | insert titles values ('PC8888', 'Secrets of Silicon Valley', 'popular_comp', '1389', 36 | $20.00, $8000.00, 10, 4095, 37 | 'Muckraking reporting on the world''s largest computer hardware and software manufacturers.', 38 | '06/12/94') 39 | 40 | insert titles values ('BU1032', 'The Busy Executive''s Database Guide', 'business', 41 | '1389', $19.99, $5000.00, 10, 4095, 42 | 'An overview of available database systems with emphasis on common business applications. Illustrated.', 43 | '06/12/91') 44 | 45 | insert titles values ('PS7777', 'Emotional Security: A New Algorithm', 'psychology', 46 | '0736', $7.99, $4000.00, 10, 3336, 47 | 'Protecting yourself and your loved ones from undue emotional stress in the modern world. Use of computer and nutritional aids emphasized.', 48 | '06/12/91') 49 | 50 | insert titles values ('PS3333', 'Prolonged Data Deprivation: Four Case Studies', 51 | 'psychology', '0736', $19.99, $2000.00, 10, 4072, 52 | 'What happens when the data runs dry? Searching evaluations of information-shortage effects.', 53 | '06/12/91') 54 | 55 | insert titles values ('BU1111', 'Cooking with Computers: Surreptitious Balance Sheets', 56 | 'business', '1389', $11.95, $5000.00, 10, 3876, 57 | 'Helpful hints on how to use your electronic resources to the best advantage.', 58 | '06/09/91') 59 | 60 | insert titles values ('MC2222', 'Silicon Valley Gastronomic Treats', 'mod_cook', '0877', 61 | $19.99, $0.00, 12, 2032, 62 | 'Favorite recipes for quick, easy, and elegant meals.', 63 | '06/09/91') 64 | 65 | insert titles values ('TC7777', 'Sushi, Anyone?', 'trad_cook', '0877', $14.99, $8000.00, 66 | 10, 4095, 67 | 'Detailed instructions on how to make authentic Japanese sushi in your spare time.', 68 | '06/12/91') 69 | 70 | insert titles values ('TC4203', 'Fifty Years in Buckingham Palace Kitchens', 'trad_cook', 71 | '0877', $11.95, $4000.00, 14, 15096, 72 | 'More anecdotes from the Queen''s favorite cook describing life among English royalty. Recipes, techniques, tender vignettes.', 73 | '06/12/91') 74 | 75 | insert titles values ('PC1035', 'But Is It User Friendly?', 'popular_comp', '1389', 76 | $22.95, $7000.00, 16, 8780, 77 | 'A survey of software for the naive user, focusing on the ''friendliness'' of each.', 78 | '06/30/91') 79 | 80 | insert titles values('BU2075', 'You Can Combat Computer Stress!', 'business', '0736', 81 | $2.99, $10125.00, 24, 18722, 82 | 'The latest medical and psychological techniques for living with the electronic office. Easy-to-understand explanations.', 83 | '06/30/91') 84 | 85 | insert titles values('PS2091', 'Is Anger the Enemy?', 'psychology', '0736', $10.95, 86 | $2275.00, 12, 2045, 87 | 'Carefully researched study of the effects of strong emotions on the body. Metabolic charts included.', 88 | '06/15/91') 89 | 90 | insert titles values('PS2106', 'Life Without Fear', 'psychology', '0736', $7.00, $6000.00, 91 | 10, 111, 92 | 'New exercise, meditation, and nutritional techniques that can reduce the shock of daily interactions. Popular audience. Sample menus included, exercise video available separately.', 93 | '10/05/91') 94 | 95 | insert titles values('MC3021', 'The Gourmet Microwave', 'mod_cook', '0877', $2.99, 96 | $15000.00, 24, 22246, 97 | 'Traditional French gourmet recipes adapted for modern microwave cooking.', 98 | '06/18/91') 99 | 100 | insert titles values('TC3218', 'Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean', 101 | 'trad_cook', '0877', $20.95, $7000.00, 10, 375, 102 | 'Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend.', 103 | '10/21/91') 104 | 105 | insert titles (title_id, title, pub_id) values('MC3026', 106 | 'The Psychology of Computer Cooking', '0877') 107 | 108 | insert titles values ('BU7832', 'Straight Talk About Computers', 'business', '1389', 109 | $19.99, $5000.00, 10, 4095, 110 | 'Annotated analysis of what computers can do for you: a no-hype guide for the critical user.', 111 | '06/22/91') 112 | 113 | insert titles values('PS1372', 'Computer Phobic AND Non-Phobic Individuals: Behavior Variations', 114 | 'psychology', '0877', $21.59, $7000.00, 10, 375, 115 | 'A must for the specialist, this book examines the difference between those who hate and fear computers and those who don''t.', 116 | '10/21/91') 117 | 118 | insert titles (title_id, title, type, pub_id, notes) values('PC9999', 'Net Etiquette', 119 | 'popular_comp', '1389', 'A must-read for computer conferencing.') 120 | 121 | GO 122 | 123 | -------------------------------------------------------------------------------- /Chapter08/io.jl: -------------------------------------------------------------------------------- 1 | # this script does not run as a whole 2 | # (the code snippets are for demo-purposes only, 3 | # and should be used on their own, and/or in the REPL 4 | # on Julia prompt: 5 | # julia> stdin 6 | # Base.TTY(Base.Libc.WindowsRawSocket(0x000000000000027c) open, 0 bytes waiting) 7 | # julia> stdout 8 | # Base.TTY(Base.Libc.WindowsRawSocket(0x0000000000000280) open, 0 bytes waiting) 9 | 10 | # read(stdin, Char) 11 | write(stdout, "Julia") #> Julia5 12 | # read(stdin,3) 13 | # readline(stdin) 14 | # input: # Julia 15 | # output: # "Julia\r\n" (Windows) - "Julia\n" (Linux) 16 | 17 | # stream can be stdin or any other input stream: 18 | stream = stdin 19 | for line in eachline(stream) 20 | println("Found $line") 21 | end 22 | 23 | while !eof(stream) 24 | x = read(stream, Char) 25 | println("Found: $x") 26 | end 27 | 28 | 29 | function process(item) 30 | # do the processing 31 | end 32 | 33 | # files: 34 | fieldnames(IOStream) 35 | #> (:handle, :ios, :name, :mark) 36 | 37 | IOStream.types 38 | #> svec(Ptr{Nothing}, Array{UInt8,1}, AbstractString, Int64) 39 | 40 | # reading: 41 | fname = "example.dat" 42 | f1 = open(fname) 43 | # IOStream() 44 | 45 | data = readlines(f1) 46 | # 3-element Array{String,1}: 47 | # "this is line 1." 48 | # "42; 3.14" 49 | # "this is line 3." 50 | 51 | for line in data 52 | println(line) 53 | process(line) 54 | end 55 | close(f1) 56 | 57 | open(fname) do file 58 | process(file) 59 | end 60 | 61 | open(fname) do file 62 | for line in eachline(file) 63 | print(line) 64 | process(line) 65 | end 66 | end 67 | 68 | # writing: 69 | fname = "example2.dat" 70 | f2 = open(fname, "w") 71 | write(f2, "I write myself to a file\n") #> 24 72 | println(f2, "even with println!") 73 | close(f2) 74 | 75 | # looping over all files in a folder: 76 | for file in readdir() 77 | process(file) 78 | end 79 | 80 | # example: 81 | mydir = pwd(); 82 | cd("..") 83 | 84 | for fn in readdir() 85 | println(fn) 86 | end 87 | # possible output: 88 | # .DS_Store 89 | # .git 90 | # Chapter 1 91 | # Chapter 2 92 | # Chapter 3 93 | # Chapter 4 94 | # Chapter 5 95 | # Chapter 6 96 | # Chapter 7 97 | # Chapter 8 98 | # Chapter 9 99 | # LICENSE 100 | # README.md 101 | 102 | cd(mydir) 103 | -------------------------------------------------------------------------------- /Chapter08/odbc.jl: -------------------------------------------------------------------------------- 1 | using ODBC, Dates 2 | ODBC.DSN("pubsODBC", ,) 3 | # Connection Data Source: pubsODBC 4 | # pubsODBC Connection Number: 1 5 | # Contains resultset? No 6 | results = ODBC.query(dsn, "select * from titles") 7 | # elapsed time: 0.189238158 seconds 8 | # 18x10 DataFrame 9 | # | Row | title_id | 10 | # |-----|----------| 11 | # | 1 | "BU1032" | 12 | # | 2 | "BU1111" | 13 | # | 3 | "BU2075" | 14 | # | 4 | "BU7832" | 15 | # | 5 | "MC2222" | 16 | # | 6 | "MC3021" | 17 | # ⋮ 18 | # | 12 | "PS2091" | 19 | # | 13 | "PS2106" | 20 | # | 14 | "PS3333" | 21 | # | 15 | "PS7777" | 22 | # | 16 | "TC3218" | 23 | # | 17 | "TC4203" | 24 | # | 18 | "TC7777" | 25 | 26 | # | Row | title | 27 | # |-----|-------------------------------------------------------------------| 28 | # | 1 | "The Busy Executive's Database Guide" | 29 | # | 2 | "Cooking with Computers: Surreptitious Balance Sheets" | 30 | # | 3 | "You Can Combat Computer Stress!" | 31 | # | 4 | "Straight Talk About Computers" | 32 | # | 5 | "Silicon Valley Gastronomic Treats" | 33 | # | 6 | "The Gourmet Microwave" | 34 | # ⋮ 35 | # Row | _type | pub_id | price | advance | royalty | ytd_sales | 36 | # -----|----------------|--------|-------|---------|---------|-----------| 37 | # 1 | "business " | "1389" | 19.99 | 5000.0 | 10 | 4095 | 38 | # 2 | "business " | "1389" | 11.95 | 5000.0 | 10 | 3876 | 39 | # 3 | "business " | "0736" | 2.99 | 10125.0 | 24 | 18722 | 40 | # 4 | "business " | "1389" | 19.99 | 5000.0 | 10 | 4095 | 41 | # 5 | "mod_cook " | "0877" | 19.99 | 0.0 | 12 | 2032 | 42 | # 6 | "mod_cook " | "0877" | 2.99 | 15000.0 | 24 | 22246 | 43 | # fname = "books.dat" 44 | # ODBC.query(dsn, "select * from titles", file=fname, delim = '\t') 45 | 46 | # updates: 47 | updsql = "update titles set type = 'psychology' where title_id='BU1032'" 48 | stmt = ODBC.prepare(dsn, updsql) 49 | ODBC.execute!(stmt) 50 | 51 | ODBC.listdrivers() 52 | ODBC.listdsns() -------------------------------------------------------------------------------- /Chapter08/parallel.jl: -------------------------------------------------------------------------------- 1 | using Distributed 2 | # start the following on the command line: 3 | # julia -p n # starts n processes on the local machine 4 | # julia -p 8 # starts REPL with 8 workers 5 | workers() 6 | # 8-element Array{Int64,1}: 7 | # 2 8 | # 3 9 | # 4 10 | # 5 11 | # ⋮ 12 | # 8 13 | # 9 14 | 15 | # iterate over workers: 16 | for pid in workers() 17 | # do something with pid 18 | end 19 | myid() # 1 20 | addprocs(5) 21 | # 5-element Array{Any,1}: 22 | # 10 23 | # 11 24 | # 12 25 | # 13 26 | # 14 27 | nprocs() # 14 28 | rmprocs(3) #> Task (done) @0x0000000012f8f0f0 29 | # worker with id 3 is removed 30 | 31 | # cluster of computers: 32 | # julia --machinefile machines driver.jl 33 | # Run processes specified in driver.jl on hosts listed in machines 34 | 35 | # primitive operations with processes: 36 | r1 = remotecall(x -> x^2, 2, 1000) #> Future(2, 1, 15, nothing) 37 | fetch(r1) #> 1000000 38 | 39 | remotecall_fetch(sin, 5, 2pi) # -2.4492935982947064e-16 40 | 41 | r2 = @spawnat 4 sqrt(2) #> Future(4, 1, 18, nothing) 42 | # lets worker 4 calculate sqrt(2) 43 | fetch(r2) #> 1.4142135623730951 44 | r = [@spawnat w sqrt(5) for w in workers()] 45 | # or in a freshly started REPL: 46 | # r = [@spawnat i sqrt(5) for i=1:length(workers())] 47 | # 12-element Array{Future,1}: 48 | # Future(2, 1, 20, nothing) 49 | # Future(4, 1, 21, nothing) 50 | # Future(5, 1, 22, nothing) 51 | # Future(6, 1, 23, nothing) 52 | # Future(7, 1, 24, nothing) 53 | # Future(8, 1, 25, nothing) 54 | # Future(9, 1, 26, nothing) 55 | # Future(10, 1, 27, nothing) 56 | # Future(11, 1, 28, nothing) 57 | # Future(12, 1, 29, nothing) 58 | # Future(13, 1, 30, nothing) 59 | # Future(14, 1, 31, nothing) 60 | r3 = @spawn sqrt(5) #> Future(2, 1, 32, nothing) 61 | fetch(r3) #> 2.23606797749979 62 | 63 | # using @everywhere to make functions available to all workers: 64 | @everywhere w = 8 65 | @everywhere println(myid()) 66 | # 1 67 | # From worker 14: 14 68 | # From worker 8: 8 69 | # From worker 10: 10 70 | # From worker 7: 7 71 | # From worker 2: 2 72 | # From worker 4: 4 73 | # From worker 12: 12 74 | # From worker 9: 9 75 | # From worker 11: 11 76 | # From worker 6: 6 77 | # From worker 13: 13 78 | # From worker 5: 5 79 | 80 | x = 5 #> 5 81 | @everywhere println(x) #> 5 82 | # # exception on worker 2: ERROR: UndefVarError: x not defined ... 83 | # ...and 11 more exception(s) 84 | 85 | @everywhere include("defs.jl") 86 | @everywhere function fib(n) 87 | if (n < 2) 88 | return n 89 | else 90 | return fib(n-1) + fib(n-2) 91 | end 92 | end 93 | 94 | r2 = @spawnat 2 fib(10) 95 | # Future(2, 1, 70, nothing) 96 | fetch(r2) 97 | # 55 98 | 99 | include("functions.jl") 100 | 101 | # broadcast data to all workers: 102 | d = "Julia" 103 | for pid in workers() 104 | remotecall(x -> (global d; d = x; nothing), pid, d) 105 | end -------------------------------------------------------------------------------- /Chapter08/parallel_loops_maps.jl: -------------------------------------------------------------------------------- 1 | using Distributed 2 | # parallel loops: 3 | function buffon(n) 4 | hit = 0 5 | for i = 1:n 6 | mp = rand() 7 | phi = (rand() * pi) - pi / 2 # angle at which needle falls 8 | xright = mp + cos(phi)/2 # x-location of needle 9 | xleft = mp - cos(phi)/2 10 | # if xright >= 1 || xleft <= 0 11 | # hit += 1 12 | # end 13 | # Does needle cross either x == 0 or x == 1? 14 | p = (xright >= 1 || xleft <= 0) ? 1 : 0 15 | hit += p 16 | end 17 | miss = n - hit 18 | piapprox = n / hit * 2 19 | end 20 | 21 | @time buffon(100000) 22 | # 0.208500 seconds (504.79 k allocations: 25.730 MiB, 7.10% gc time) 23 | # 3.1441597233139444 24 | @time buffon(100000000) 25 | # 4.112683 seconds (5 allocations: 176 bytes) 26 | # 3.141258861373451 27 | 28 | function buffon_par(n) 29 | hit = @distributed (+) for i = 1:n 30 | mp = rand() 31 | phi = (rand() * pi) - pi / 2 32 | xright = mp + cos(phi)/2 33 | xleft = mp - cos(phi)/2 34 | (xright >= 1 || xleft <= 0) ? 1 : 0 35 | end 36 | miss = n - hit 37 | piapprox = n / hit * 2 38 | end 39 | @time buffon_par(100000) 40 | # 1.058487 seconds (951.35 k allocations: 48.192 MiB, 2.04% gc time) 41 | # 3.15059861373661 42 | 43 | @time buffon_par(100000000) 44 | # 0.735853 seconds (1.84 k allocations: 133.156 KiB) 45 | # 3.1418106012575633 46 | 47 | # arr is not correctly initialized: 48 | arr = zeros(100000) 49 | @distributed for i=1:100000 50 | arr[i] = i 51 | end #> Task (queued) @0x00000000147ad430 52 | #> arr only contains zeros! 53 | 54 | # parallel maps: 55 | using LinearAlgebra 56 | function rank_marray() 57 | marr = [rand(1000,1000) for i=1:10] 58 | for arr in marr 59 | println(rank(arr)) 60 | end 61 | end 62 | 63 | @time rank_marray() 64 | # 1000 65 | # 1000 66 | # 1000 67 | # 1000 68 | # 1000 69 | # 1000 70 | # 1000 71 | # 1000 72 | # 1000 73 | # 1000 74 | # 7.310404 seconds (91.33 k allocations: 162.878 MiB, 1.15% gc time) 75 | 76 | function prank_marray() 77 | marr = [rand(1000,1000) for i=1:10] 78 | println(pmap(rank, marr)) 79 | end 80 | @time prank_marray() 81 | # {1000,1000,1000,1000,1000,1000,1000,1000,1000,1000} 82 | # 5.966216 seconds (4.15 M allocations: 285.610 MiB, 2.15% gc time) -------------------------------------------------------------------------------- /Chapter08/savetuple.csv: -------------------------------------------------------------------------------- 1 | ColName A, ColName B, ColName C 2 | 0.5759616979698472,0.2597832683075949,0.6763647042230778 3 | 0.22641093419831848,0.25330112037052377,0.4254329735280291 4 | 0.24038682826261226,0.1489904275220344,0.34554192821813756 5 | 0.9047742467024442,0.4762523428683665,0.6555721751023464 6 | 0.7066097540260676,0.9228117851885098,0.6047681786507859 7 | 0.5698373969395576,0.19760388845977572,0.5378556937343291 8 | 0.5491000961739994,0.34557957137077056,0.38959869748190834 9 | 0.9265060082894219,0.6453628734073003,0.7124738625032145 10 | 0.6257468517955809,0.6167041462077394,0.7780396915716952 11 | 0.24328325235841408,0.3186172478161837,0.6129606280610105 12 | -------------------------------------------------------------------------------- /Chapter08/tcpserver.jl: -------------------------------------------------------------------------------- 1 | using Sockets 2 | server = Sockets.listen(8080) 3 | # Sockets.TCPServer(Base.Libc.WindowsRawSocket(0x00000000000002e4) active) 4 | 5 | conn = accept(server) 6 | # on the client: $ nc localhost 8080 7 | # TcpSocket(connected,0 bytes waiting) 8 | line = readline(conn) 9 | # hello Julia server! 10 | # "hello Julia server!\n" 11 | write(conn, "Hello back from server to client, what can I do for you?") 12 | 56 13 | close(conn) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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.enable(false) 15 | @time for i=1:50 result = sum(x .* y); end 16 | # with 1 processor: Array operations took 89.43973046 ms - avg: 90 ms 17 | # with 9 processors: 4.895387 seconds (336.22 k allocations: 3.742 GiB, 20.99% gc time) 18 | 19 | @time for i=1:50 result = inner(x, y) end 20 | # 0.967685 seconds (14.13 k allocations: 746.626 KiB) 21 | 22 | x = randn(1, 10000000) 23 | y = randn(10000000, 1) 24 | 25 | @time for i=1:50 result = x * y end 26 | # 2.815247 seconds (927.43 k allocations: 44.635 MiB, 0.83% gc time) 27 | -------------------------------------------------------------------------------- /Chapter09/callc.jl: -------------------------------------------------------------------------------- 1 | # calling a function in a shared library: 2 | lang = ccall( (:getenv, "libc"), Cstring, (Cstring,), "LANGUAGE") 3 | unsafe_string(lang) #> "en_US" 4 | 5 | # test existence of library: 6 | find_library(["libc"]) #> "libc" -------------------------------------------------------------------------------- /Chapter09/callpy.jl: -------------------------------------------------------------------------------- 1 | using PyCall 2 | py"10*10" #> 100 3 | @pyimport math 4 | math.sin(math.pi / 2) #> 1.0 5 | -------------------------------------------------------------------------------- /Chapter09/file1.txt: -------------------------------------------------------------------------------- 1 | This a a test for try / catch / finally -------------------------------------------------------------------------------- /Chapter09/file2.txt: -------------------------------------------------------------------------------- 1 | Julia RustJulia Rust -------------------------------------------------------------------------------- /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 | # 3 12 | function myFunc(a::T, c::Int) where T 13 | # code 14 | end 15 | 16 | # 9 17 | function with_keyword(x; name::String = "Smith") 18 | # ... 19 | end 20 | 21 | # 16 22 | mutable struct Person 23 | name::String 24 | height::Float64 25 | weight::Float64 26 | end 27 | # instead of: 28 | # type Person 29 | # name 30 | # height 31 | # weight 32 | # end 33 | 34 | # 18 35 | # Use 36 | file = open("file2.txt", "w") 37 | a = "Julia" 38 | b = "Rust" 39 | write(file, a, " ", b) 40 | # instead of: 41 | write(file, "$a $b") 42 | 43 | # TOOLS: 44 | # @time 45 | 46 | # linter: 47 | # add Lint 48 | # using Lint 49 | # lintfile("performance.jl") -------------------------------------------------------------------------------- /Chapter09/shell.jl: -------------------------------------------------------------------------------- 1 | pwd() 2 | # cd("d:\\test\\week1") 3 | # shell mode: 4 | # ; ls (on Linux and mac OS X) 5 | # ; mkdir folder 6 | # ; cd folder 7 | 8 | # on Linux and mac OS X: 9 | cmd = `echo Julia is smart` 10 | typeof(cmd) #> Cmd (constructor with 1 method) 11 | run(cmd) #> Julia is smart 12 | run(`date`) #> Sun Oct 12 09:44:50 GMT 2014 13 | cmd = `cat file1.txt` 14 | run(cmd) #> text from file1.txt: This a a test for try / catch / finally 15 | success(cmd) #> true 16 | 17 | # interpolation: 18 | file = "file1.txt" 19 | cmd = `cat $file` 20 | run(cmd) #> text from file1.txt: This a a test for try / catch / finally 21 | # cmd = `ls *.*` # works only on Windows 22 | # run(cmd) #> returns: file1.txt shell.jl test.txt 23 | # pipelining: 24 | run(pipeline(`cat $file`,"test.txt")) #> text from file1.txt is written into test.txt 25 | run(pipeline("test.txt",`cat`)) 26 | run(pipeline(`echo $("\nhi\nJulia")`,`cat`,`grep -n J`)) #> 3:Julia 27 | run(pipeline(`cat "tosort.txt"`,`sort`)) # returns A B C 28 | 29 | println() 30 | println("Output grep command:") 31 | # output: 32 | # run(`grep is $(readdir())`) # returns where "is" is found in text files in current dir 33 | #= 34 | array_product_benchmark.jl:# gc_disable() 35 | callc.jl:# test existence of library: 36 | file1.txt:This a a test for try / catch / finally 37 | performance.jl:foo1(x::Int) = isprime(x) ? x: false 38 | shell.jl:cmd = `echo Julia is smart` 39 | shell.jl:run(cmd) #> Julia is smart 40 | shell.jl:run(cmd) #> text from file1.txt: This a a test for try / catch / finally 41 | 42 | shell.jl:run(cmd) #> text from file1.txt: This a a test for try / catch / finally 43 | 44 | shell.jl:run(`cat $file` |> "test.txt") #> text from file1.txt is written into te 45 | st.txt 46 | shell.jl:run(`grep is $(readdir())`) # returns where "is" is found in text files 47 | in current dir 48 | shell.jl:# CThis a a test for try / catch / finally 49 | test.txt:This a a test for try / catch / finally 50 | =# 51 | println() 52 | 53 | # reading the output of the command: 54 | a = readall(pipeline(`cat "tosort.txt"`,`sort`)) 55 | #> a has value "A\r\nB\r\nC\n" 56 | 57 | run(`cat "file1.txt"` & `cat "tosort.txt"`) 58 | # B 59 | # A 60 | # CThis a a test for try / catch / finally 61 | 62 | # platform variations: 63 | Sys.KERNEL #> :NT 64 | fun1 = () 65 | fun2 = () 66 | Sys.iswindows() ? fun1 : fun2 67 | if Sys.iswindows() 68 | fun1 69 | else 70 | fun2 71 | end -------------------------------------------------------------------------------- /Chapter09/test.txt: -------------------------------------------------------------------------------- 1 | This a a test for try / catch / finally -------------------------------------------------------------------------------- /Chapter09/tosort.txt: -------------------------------------------------------------------------------- 1 | B 2 | A 3 | C -------------------------------------------------------------------------------- /Chapter10/plots_iris.jl: -------------------------------------------------------------------------------- 1 | using StatPlots, RDatasets 2 | iris = dataset("datasets", "iris") 3 | @df iris scatter(:SepalLength, :SepalWidth, group=:Species, 4 | m=(0.5, [:+ :h :star7], 4), bg=RGB(1.0,1.0,1.0)) -------------------------------------------------------------------------------- /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 | # clipboard: 13 | using InteractiveUtils 14 | a = 42 #> 42 15 | clipboard(a) 16 | # quit and restart REPL: 17 | # a #> ERROR: a not defined 18 | a = clipboard() #> "42" -------------------------------------------------------------------------------- /Chapter11/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" 3 | DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" 4 | Feather = "becb17da-46f6-5d3c-ad1b-1c5fe96bc73c" 5 | Gadfly = "c91e804a-d5a3-530f-b6f0-dfbca275c004" 6 | IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 7 | JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 8 | Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 9 | RDatasets = "ce6b1742-4840-55fa-b093-852dadbb1d8b" 10 | Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 11 | -------------------------------------------------------------------------------- /Chapter12/Manifest.toml: -------------------------------------------------------------------------------- 1 | [[AbstractTrees]] 2 | deps = ["Markdown", "Test"] 3 | git-tree-sha1 = "6621d9645702c1c4e6970cc6a3eae440c768000b" 4 | uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" 5 | version = "0.2.1" 6 | 7 | [[Base64]] 8 | uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 9 | 10 | [[BinaryProvider]] 11 | deps = ["Libdl", "Pkg", "SHA", "Test"] 12 | git-tree-sha1 = "055eb2690182ebc31087859c3dd8598371d3ef9e" 13 | uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" 14 | version = "0.5.3" 15 | 16 | [[Compat]] 17 | deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] 18 | git-tree-sha1 = "ec61a16eed883ad0cfa002d7489b3ce6d039bb9a" 19 | uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" 20 | version = "1.4.0" 21 | 22 | [[Conda]] 23 | deps = ["Compat", "JSON", "VersionParsing"] 24 | git-tree-sha1 = "fb86fe40cb5b35990e368709bfdc1b46dbb99dac" 25 | uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" 26 | version = "1.1.1" 27 | 28 | [[Dates]] 29 | deps = ["Printf"] 30 | uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" 31 | 32 | [[DelimitedFiles]] 33 | deps = ["Mmap"] 34 | uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" 35 | 36 | [[Distributed]] 37 | deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] 38 | uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" 39 | 40 | [[FileWatching]] 41 | uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" 42 | 43 | [[Gumbo]] 44 | deps = ["AbstractTrees", "BinaryProvider", "Libdl", "Test"] 45 | git-tree-sha1 = "b16b6c5127e8c6be3084e6658c5fb5dd1f97d7fd" 46 | uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 47 | version = "0.5.1" 48 | 49 | [[HTTP]] 50 | deps = ["Base64", "Dates", "Distributed", "IniFile", "MbedTLS", "Sockets", "Test"] 51 | git-tree-sha1 = "b881f69331e85642be315c63d05ed65d6fc8a05b" 52 | uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" 53 | version = "0.7.1" 54 | 55 | [[IJulia]] 56 | deps = ["Base64", "Compat", "Conda", "Dates", "InteractiveUtils", "JSON", "Markdown", "MbedTLS", "Pkg", "Printf", "REPL", "Random", "SoftGlobalScope", "Test", "UUIDs", "ZMQ"] 57 | git-tree-sha1 = "38d1ce0fbbefcb67f5ab46f1093cbce0335092e0" 58 | uuid = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 59 | version = "1.14.1" 60 | 61 | [[IniFile]] 62 | deps = ["Test"] 63 | git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8" 64 | uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" 65 | version = "0.5.0" 66 | 67 | [[InteractiveUtils]] 68 | deps = ["LinearAlgebra", "Markdown"] 69 | uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" 70 | 71 | [[JSON]] 72 | deps = ["Dates", "Distributed", "Mmap", "Sockets", "Test", "Unicode"] 73 | git-tree-sha1 = "1f7a25b53ec67f5e9422f1f551ee216503f4a0fa" 74 | uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 75 | version = "0.20.0" 76 | 77 | [[LibGit2]] 78 | uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" 79 | 80 | [[Libdl]] 81 | uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" 82 | 83 | [[LinearAlgebra]] 84 | deps = ["Libdl"] 85 | uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" 86 | 87 | [[Logging]] 88 | uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" 89 | 90 | [[Markdown]] 91 | deps = ["Base64"] 92 | uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" 93 | 94 | [[MbedTLS]] 95 | deps = ["BinaryProvider", "Dates", "Libdl", "Random", "Sockets", "Test"] 96 | git-tree-sha1 = "c93a87da4081a3de781f34e0540175795a2ce83d" 97 | uuid = "739be429-bea8-5141-9913-cc70e7f3736d" 98 | version = "0.6.6" 99 | 100 | [[Mmap]] 101 | uuid = "a63ad114-7e13-5084-954f-fe012c677804" 102 | 103 | [[OrderedCollections]] 104 | deps = ["Random", "Serialization", "Test"] 105 | git-tree-sha1 = "85619a3f3e17bb4761fe1b1fd47f0e979f964d5b" 106 | uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" 107 | version = "1.0.2" 108 | 109 | [[Pkg]] 110 | deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"] 111 | uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 112 | 113 | [[Printf]] 114 | deps = ["Unicode"] 115 | uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" 116 | 117 | [[REPL]] 118 | deps = ["InteractiveUtils", "Markdown", "Sockets"] 119 | uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" 120 | 121 | [[Random]] 122 | deps = ["Serialization"] 123 | uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 124 | 125 | [[SHA]] 126 | uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" 127 | 128 | [[Serialization]] 129 | uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" 130 | 131 | [[SharedArrays]] 132 | deps = ["Distributed", "Mmap", "Random", "Serialization"] 133 | uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" 134 | 135 | [[Sockets]] 136 | uuid = "6462fe0b-24de-5631-8697-dd941f90decc" 137 | 138 | [[SoftGlobalScope]] 139 | deps = ["Test"] 140 | git-tree-sha1 = "97f6dfcf612b9a7260fde44170725d9ea34b1431" 141 | uuid = "b85f4697-e234-5449-a836-ec8e2f98b302" 142 | version = "1.0.7" 143 | 144 | [[SparseArrays]] 145 | deps = ["LinearAlgebra", "Random"] 146 | uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" 147 | 148 | [[Statistics]] 149 | deps = ["LinearAlgebra", "SparseArrays"] 150 | uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 151 | 152 | [[Test]] 153 | deps = ["Distributed", "InteractiveUtils", "Logging", "Random"] 154 | uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" 155 | 156 | [[UUIDs]] 157 | deps = ["Random"] 158 | uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" 159 | 160 | [[Unicode]] 161 | uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" 162 | 163 | [[VersionParsing]] 164 | deps = ["Compat"] 165 | git-tree-sha1 = "c9d5aa108588b978bd859554660c8a5c4f2f7669" 166 | uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" 167 | version = "1.1.3" 168 | 169 | [[ZMQ]] 170 | deps = ["BinaryProvider", "FileWatching", "Libdl", "Sockets", "Test"] 171 | git-tree-sha1 = "34e7ac2d1d59d19d0e86bde99f1f02262bfa1613" 172 | uuid = "c2297ded-f4af-51ae-bb23-16f91089e4e1" 173 | version = "1.0.0" 174 | -------------------------------------------------------------------------------- /Chapter12/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" 3 | Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 4 | HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" 5 | IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 6 | OrderedCollections = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" 7 | Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 8 | -------------------------------------------------------------------------------- /Chapter12/WebCrawler/Manifest.toml: -------------------------------------------------------------------------------- 1 | [[AbstractTrees]] 2 | deps = ["Markdown", "Test"] 3 | git-tree-sha1 = "feb8b2c99359901e295443c9d0c7e711604acf39" 4 | uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" 5 | version = "0.2.0" 6 | 7 | [[Base64]] 8 | uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 9 | 10 | [[BinaryProvider]] 11 | deps = ["Libdl", "Pkg", "SHA", "Test"] 12 | git-tree-sha1 = "b530fbeb6f41ab5a83fbe3db1fcbe879334bcd2d" 13 | uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" 14 | version = "0.4.2" 15 | 16 | [[Compat]] 17 | deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] 18 | git-tree-sha1 = "ae262fa91da6a74e8937add6b613f58cd56cdad4" 19 | uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" 20 | version = "1.1.0" 21 | 22 | [[Dates]] 23 | deps = ["Printf"] 24 | uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" 25 | 26 | [[DelimitedFiles]] 27 | deps = ["Mmap"] 28 | uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" 29 | 30 | [[Distributed]] 31 | deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] 32 | uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" 33 | 34 | [[Gumbo]] 35 | deps = ["AbstractTrees", "BinaryProvider", "Libdl", "Pkg", "Test"] 36 | git-tree-sha1 = "b16b6c5127e8c6be3084e6658c5fb5dd1f97d7fd" 37 | uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 38 | version = "0.5.1" 39 | 40 | [[HTTP]] 41 | deps = ["Base64", "Dates", "Distributed", "IniFile", "MbedTLS", "Sockets", "Test"] 42 | git-tree-sha1 = "8a0f75e8b09df01d9f1ba9ad3fbf8b4983595d20" 43 | uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" 44 | version = "0.6.14" 45 | 46 | [[IniFile]] 47 | deps = ["Test"] 48 | git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8" 49 | uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" 50 | version = "0.5.0" 51 | 52 | [[InteractiveUtils]] 53 | deps = ["LinearAlgebra", "Markdown"] 54 | uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" 55 | 56 | [[LibGit2]] 57 | uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" 58 | 59 | [[Libdl]] 60 | uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" 61 | 62 | [[LinearAlgebra]] 63 | deps = ["Libdl"] 64 | uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" 65 | 66 | [[Logging]] 67 | uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" 68 | 69 | [[Markdown]] 70 | deps = ["Base64"] 71 | uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" 72 | 73 | [[MbedTLS]] 74 | deps = ["BinaryProvider", "Compat", "Libdl", "Pkg", "Sockets"] 75 | git-tree-sha1 = "17d5a81dbb1e682d4ff707c01f0afe5948068fa6" 76 | uuid = "739be429-bea8-5141-9913-cc70e7f3736d" 77 | version = "0.6.0" 78 | 79 | [[Mmap]] 80 | uuid = "a63ad114-7e13-5084-954f-fe012c677804" 81 | 82 | [[Pkg]] 83 | deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"] 84 | uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 85 | 86 | [[Printf]] 87 | deps = ["Unicode"] 88 | uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" 89 | 90 | [[REPL]] 91 | deps = ["InteractiveUtils", "Markdown", "Sockets"] 92 | uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" 93 | 94 | [[Random]] 95 | deps = ["Serialization"] 96 | uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 97 | 98 | [[SHA]] 99 | uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" 100 | 101 | [[Serialization]] 102 | uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" 103 | 104 | [[SharedArrays]] 105 | deps = ["Distributed", "Mmap", "Random", "Serialization"] 106 | uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" 107 | 108 | [[Sockets]] 109 | uuid = "6462fe0b-24de-5631-8697-dd941f90decc" 110 | 111 | [[SparseArrays]] 112 | deps = ["LinearAlgebra", "Random"] 113 | uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" 114 | 115 | [[Statistics]] 116 | deps = ["LinearAlgebra", "SparseArrays"] 117 | uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 118 | 119 | [[Test]] 120 | deps = ["Distributed", "InteractiveUtils", "Logging", "Random"] 121 | uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" 122 | 123 | [[UUIDs]] 124 | deps = ["Random"] 125 | uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" 126 | 127 | [[Unicode]] 128 | uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" 129 | -------------------------------------------------------------------------------- /Chapter12/WebCrawler/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 3 | HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" 4 | -------------------------------------------------------------------------------- /Chapter12/WebCrawler/webcrawler.jl: -------------------------------------------------------------------------------- 1 | using HTTP, Gumbo 2 | 3 | const PAGE_URL = "https://en.wikipedia.org/wiki/Julia_(programming_language)" 4 | const LINKS = String[] 5 | 6 | function fetchpage(url) 7 | response = HTTP.get(url) 8 | if response.status == 200 && parse(Int, Dict(response.headers)["Content-Length"]) > 0 9 | String(response.body) 10 | else 11 | "" 12 | end 13 | end 14 | 15 | function extractlinks(elem) 16 | if isa(elem, HTMLElement) && 17 | tag(elem) == :a && 18 | in("href", collect(keys(attrs(elem)))) 19 | url = getattr(elem, "href") 20 | startswith(url, "/wiki/") && ! occursin(":", url) && push!(LINKS, url) 21 | end 22 | 23 | for child in children(elem) 24 | extractlinks(child) 25 | end 26 | end 27 | 28 | content = fetchpage(PAGE_URL) 29 | 30 | if ! isempty(content) 31 | dom = Gumbo.parsehtml(content) 32 | 33 | extractlinks(dom.root) 34 | end 35 | 36 | display(unique(LINKS)) 37 | -------------------------------------------------------------------------------- /Chapter13/Chapter 13.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "using Pkg\n", 10 | "pkg\"activate .\"" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "# Run this cell in order to download all the package dependencies with the exact versions used in the book\n", 20 | "# This is necessary if (some of) the packages have been updated and have introduced breaking changes\n", 21 | "pkg\"instantiate\"" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "rand" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "function rand()\n", 40 | " # \n", 41 | "end" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "module MyModule\n", 51 | "\n", 52 | "function rand()\n", 53 | " println(\"I'll get a random Wikipedia page\")\n", 54 | "end\n", 55 | "\n", 56 | "end" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "MyModule.rand()" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "; mkdir modules" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [ 83 | "; cd modules " 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "for f in [\"Letters.jl\", \"Numbers.jl\", \"module_name.jl\"]\n", 93 | " touch(f)\n", 94 | "end" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "readdir()" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "edit(\"Letters.jl\")" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "function testinclude()\n", 122 | " include(\"testinclude.jl\")\n", 123 | " println(somevar)\n", 124 | "end" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": {}, 131 | "outputs": [], 132 | "source": [ 133 | "testinclude()" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "somevar" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": null, 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "LOAD_PATH" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "push!(LOAD_PATH, \"/path/to/modules\") # replace \"/path/to/modules\" with the actual path to the \"modules/\" folder" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "push!(LOAD_PATH, \".\")" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "metadata": {}, 176 | "outputs": [], 177 | "source": [ 178 | "using Letters" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": null, 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "randstring()" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "metadata": {}, 194 | "outputs": [], 195 | "source": [ 196 | "myname()" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": null, 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [ 205 | "Letters.myname()" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [], 213 | "source": [ 214 | "Letters.rand()" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": null, 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "names(Letters)" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "names(Letters, all = true)" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": null, 238 | "metadata": {}, 239 | "outputs": [], 240 | "source": [ 241 | "using Letters: myname" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": null, 247 | "metadata": {}, 248 | "outputs": [], 249 | "source": [ 250 | "myname()" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": {}, 257 | "outputs": [], 258 | "source": [ 259 | "using Letters: myname, MY_NAME" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": null, 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "MY_NAME" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "import Numbers" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": null, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "names(Numbers)" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "halfrand()" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "import Numbers.halfrand, Numbers.MY_NAME" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": null, 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "halfrand()" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "import Numbers: halfrand, MY_NAME" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": null, 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "halfrand()" 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": null, 337 | "metadata": {}, 338 | "outputs": [], 339 | "source": [ 340 | "double(x) = x*2" 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": {}, 347 | "outputs": [], 348 | "source": [ 349 | "map(double, [1, 2, 3, 5, 8, 13])" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "metadata": {}, 356 | "outputs": [], 357 | "source": [ 358 | "map(x -> x*2, [1, 2, 3, 5, 8, 13])" 359 | ] 360 | }, 361 | { 362 | "cell_type": "code", 363 | "execution_count": null, 364 | "metadata": {}, 365 | "outputs": [], 366 | "source": [ 367 | "map(x ->\n", 368 | "\tif x % 2 == 0\n", 369 | "\t\tx * 2\n", 370 | "\telseif x % 3 == 0\n", 371 | "\t\tx * 3\n", 372 | "\telseif x % 5 == 0\n", 373 | "\t\tx * 5\n", 374 | "\telse\n", 375 | "\t\tx\n", 376 | "\tend, \n", 377 | "\t[1, 2, 3, 5, 8, 13])" 378 | ] 379 | }, 380 | { 381 | "cell_type": "code", 382 | "execution_count": null, 383 | "metadata": {}, 384 | "outputs": [], 385 | "source": [ 386 | "map([1, 2, 3, 5, 8, 13]) do x\n", 387 | " if x % 2 == 0\n", 388 | " x * 2\n", 389 | " elseif x % 3 == 0\n", 390 | " x * 3\n", 391 | " elseif x % 5 == 0\n", 392 | " x * 5\n", 393 | " else\n", 394 | " x\n", 395 | " end\n", 396 | " end" 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": null, 402 | "metadata": {}, 403 | "outputs": [], 404 | "source": [ 405 | "struct Article\n", 406 | "\tcontent::String\n", 407 | " links::Vector{String}\n", 408 | " title::String\n", 409 | " image::String\n", 410 | "end" 411 | ] 412 | }, 413 | { 414 | "cell_type": "code", 415 | "execution_count": null, 416 | "metadata": {}, 417 | "outputs": [], 418 | "source": [ 419 | "julia = Article(\n", 420 | " \"Julia is a high-level dynamic programming language\",\n", 421 | " [\"/wiki/Jeff_Bezanson\", \n", 422 | " \"/wiki/Stefan_Karpinski\", \n", 423 | " \"/wiki/Viral_B._Shah\", \n", 424 | " \"/wiki/Alan_Edelman\"],\n", 425 | " \"Julia (programming language)\",\n", 426 | " \"/220px-Julia_prog_language.svg.png\"\n", 427 | " )" 428 | ] 429 | }, 430 | { 431 | "cell_type": "code", 432 | "execution_count": null, 433 | "metadata": {}, 434 | "outputs": [], 435 | "source": [ 436 | "julia.title" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": {}, 443 | "outputs": [], 444 | "source": [ 445 | "julia.title = \"The best programming language, period\"" 446 | ] 447 | }, 448 | { 449 | "cell_type": "code", 450 | "execution_count": null, 451 | "metadata": {}, 452 | "outputs": [], 453 | "source": [ 454 | "push!(julia.links, \"/wiki/Multiple_dispatch\")" 455 | ] 456 | }, 457 | { 458 | "cell_type": "code", 459 | "execution_count": null, 460 | "metadata": {}, 461 | "outputs": [], 462 | "source": [ 463 | "julia.links = [1, 2, 3]" 464 | ] 465 | }, 466 | { 467 | "cell_type": "code", 468 | "execution_count": null, 469 | "metadata": {}, 470 | "outputs": [], 471 | "source": [ 472 | "typeof([1, 2, 3])" 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": null, 478 | "metadata": {}, 479 | "outputs": [], 480 | "source": [ 481 | "mutable struct Player\n", 482 | " username::String\n", 483 | " score::Int\n", 484 | "end" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "metadata": {}, 491 | "outputs": [], 492 | "source": [ 493 | "me = Player(\"adrian\", 0)" 494 | ] 495 | }, 496 | { 497 | "cell_type": "code", 498 | "execution_count": null, 499 | "metadata": {}, 500 | "outputs": [], 501 | "source": [ 502 | "me.score += 10" 503 | ] 504 | }, 505 | { 506 | "cell_type": "code", 507 | "execution_count": null, 508 | "metadata": {}, 509 | "outputs": [], 510 | "source": [ 511 | "me" 512 | ] 513 | }, 514 | { 515 | "cell_type": "code", 516 | "execution_count": null, 517 | "metadata": {}, 518 | "outputs": [], 519 | "source": [ 520 | "exit() # to reload the Kernel and refresh the workspace" 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": null, 526 | "metadata": {}, 527 | "outputs": [], 528 | "source": [ 529 | "abstract type Mammal end" 530 | ] 531 | }, 532 | { 533 | "cell_type": "code", 534 | "execution_count": null, 535 | "metadata": {}, 536 | "outputs": [], 537 | "source": [ 538 | "abstract type Person <: Mammal end" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": null, 544 | "metadata": {}, 545 | "outputs": [], 546 | "source": [ 547 | "mutable struct Player <: Person\n", 548 | " username::String\n", 549 | " score::Int\n", 550 | "end" 551 | ] 552 | }, 553 | { 554 | "cell_type": "code", 555 | "execution_count": null, 556 | "metadata": {}, 557 | "outputs": [], 558 | "source": [ 559 | "struct User <: Person\n", 560 | " username::String\n", 561 | " password::String\n", 562 | "end" 563 | ] 564 | }, 565 | { 566 | "cell_type": "code", 567 | "execution_count": null, 568 | "metadata": {}, 569 | "outputs": [], 570 | "source": [ 571 | "sam = User(\"sam\", \"password\")" 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": null, 577 | "metadata": {}, 578 | "outputs": [], 579 | "source": [ 580 | "function getusername(p::Person)\n", 581 | " p.username\n", 582 | "end" 583 | ] 584 | }, 585 | { 586 | "cell_type": "code", 587 | "execution_count": null, 588 | "metadata": {}, 589 | "outputs": [], 590 | "source": [ 591 | "me = Player(\"adrian\", 0)" 592 | ] 593 | }, 594 | { 595 | "cell_type": "code", 596 | "execution_count": null, 597 | "metadata": {}, 598 | "outputs": [], 599 | "source": [ 600 | "getusername(me)" 601 | ] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": null, 606 | "metadata": { 607 | "scrolled": true 608 | }, 609 | "outputs": [], 610 | "source": [ 611 | "getusername(sam)" 612 | ] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": null, 617 | "metadata": {}, 618 | "outputs": [], 619 | "source": [ 620 | "struct Article\n", 621 | "\tcontent::String\n", 622 | " links::Vector{String}\n", 623 | " title::String\n", 624 | " image::String\n", 625 | "end\n", 626 | "julia = Article(\n", 627 | " \"Julia is a high-level dynamic programming language\",\n", 628 | " [\"/wiki/Jeff_Bezanson\", \n", 629 | " \"/wiki/Stefan_Karpinski\", \n", 630 | " \"/wiki/Viral_B._Shah\", \n", 631 | " \"/wiki/Alan_Edelman\"],\n", 632 | " \"Julia (programming language)\",\n", 633 | " \"/220px-Julia_prog_language.svg.png\"\n", 634 | " )" 635 | ] 636 | }, 637 | { 638 | "cell_type": "code", 639 | "execution_count": null, 640 | "metadata": {}, 641 | "outputs": [], 642 | "source": [ 643 | "GameEntity = Union{Person,Article}" 644 | ] 645 | }, 646 | { 647 | "cell_type": "code", 648 | "execution_count": null, 649 | "metadata": {}, 650 | "outputs": [], 651 | "source": [ 652 | "function entityname(e::GameEntity)\n", 653 | "\tisa(e, Person) ? e.username : e.title\n", 654 | "end" 655 | ] 656 | }, 657 | { 658 | "cell_type": "code", 659 | "execution_count": null, 660 | "metadata": {}, 661 | "outputs": [], 662 | "source": [ 663 | "entityname(julia)" 664 | ] 665 | }, 666 | { 667 | "cell_type": "code", 668 | "execution_count": null, 669 | "metadata": {}, 670 | "outputs": [], 671 | "source": [ 672 | "entityname(me)" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "metadata": {}, 679 | "outputs": [], 680 | "source": [ 681 | "function getscore(p::Player)\n", 682 | " p.score\n", 683 | "end" 684 | ] 685 | }, 686 | { 687 | "cell_type": "code", 688 | "execution_count": null, 689 | "metadata": {}, 690 | "outputs": [], 691 | "source": [ 692 | "mutable struct Customer\n", 693 | " name::String\n", 694 | " total_purchase_value::Float64\n", 695 | " credit_score::Float64\n", 696 | "end" 697 | ] 698 | }, 699 | { 700 | "cell_type": "code", 701 | "execution_count": null, 702 | "metadata": {}, 703 | "outputs": [], 704 | "source": [ 705 | "function getscore(c::Customer)\n", 706 | " c.credit_score\n", 707 | "end" 708 | ] 709 | }, 710 | { 711 | "cell_type": "code", 712 | "execution_count": null, 713 | "metadata": {}, 714 | "outputs": [], 715 | "source": [ 716 | "function getscore(t::Union{Player,Customer})\n", 717 | " isa(t, Player) ? t.score : t.credit_score\n", 718 | "end" 719 | ] 720 | }, 721 | { 722 | "cell_type": "code", 723 | "execution_count": null, 724 | "metadata": {}, 725 | "outputs": [], 726 | "source": [ 727 | "function getscore(s)\n", 728 | " if in(:score, fieldnames(typeof(s)))\n", 729 | " s.score\n", 730 | " elseif in(:credit_score, fieldnames(typeof(s)))\n", 731 | " s.credit_score\n", 732 | " else\n", 733 | " error(\"$(typeof(s)) does not have a score property\")\n", 734 | " end\n", 735 | "end" 736 | ] 737 | }, 738 | { 739 | "cell_type": "code", 740 | "execution_count": null, 741 | "metadata": {}, 742 | "outputs": [], 743 | "source": [ 744 | "@which getscore(me)" 745 | ] 746 | }, 747 | { 748 | "cell_type": "code", 749 | "execution_count": null, 750 | "metadata": {}, 751 | "outputs": [], 752 | "source": [ 753 | "sam = Customer(\"Sam\", 72.95, 100)" 754 | ] 755 | }, 756 | { 757 | "cell_type": "code", 758 | "execution_count": null, 759 | "metadata": {}, 760 | "outputs": [], 761 | "source": [ 762 | "@which getscore(sam)" 763 | ] 764 | }, 765 | { 766 | "cell_type": "code", 767 | "execution_count": null, 768 | "metadata": {}, 769 | "outputs": [], 770 | "source": [ 771 | "@which getscore(julia)" 772 | ] 773 | }, 774 | { 775 | "cell_type": "code", 776 | "execution_count": null, 777 | "metadata": {}, 778 | "outputs": [], 779 | "source": [ 780 | "getscore(julia)" 781 | ] 782 | }, 783 | { 784 | "cell_type": "code", 785 | "execution_count": null, 786 | "metadata": {}, 787 | "outputs": [], 788 | "source": [ 789 | "methods(getscore)" 790 | ] 791 | }, 792 | { 793 | "cell_type": "code", 794 | "execution_count": null, 795 | "metadata": {}, 796 | "outputs": [], 797 | "source": [] 798 | } 799 | ], 800 | "metadata": { 801 | "kernelspec": { 802 | "display_name": "Julia 1.0.1", 803 | "language": "julia", 804 | "name": "julia-1.0" 805 | }, 806 | "language_info": { 807 | "file_extension": ".jl", 808 | "mimetype": "application/julia", 809 | "name": "julia", 810 | "version": "1.0.2" 811 | } 812 | }, 813 | "nbformat": 4, 814 | "nbformat_minor": 2 815 | } 816 | -------------------------------------------------------------------------------- /Chapter13/Manifest.toml: -------------------------------------------------------------------------------- 1 | [[AbstractTrees]] 2 | deps = ["Markdown", "Test"] 3 | git-tree-sha1 = "6621d9645702c1c4e6970cc6a3eae440c768000b" 4 | uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" 5 | version = "0.2.1" 6 | 7 | [[Base64]] 8 | uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 9 | 10 | [[BinDeps]] 11 | deps = ["Compat", "Libdl", "SHA", "URIParser"] 12 | git-tree-sha1 = "12093ca6cdd0ee547c39b1870e0c9c3f154d9ca9" 13 | uuid = "9e28174c-4ba2-5203-b857-d8d62c4213ee" 14 | version = "0.8.10" 15 | 16 | [[BinaryProvider]] 17 | deps = ["Libdl", "Pkg", "SHA", "Test"] 18 | git-tree-sha1 = "055eb2690182ebc31087859c3dd8598371d3ef9e" 19 | uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" 20 | version = "0.5.3" 21 | 22 | [[Cascadia]] 23 | deps = ["AbstractTrees", "Gumbo", "Test"] 24 | git-tree-sha1 = "d51428ab540880c7329c74f178a793096f4e36f0" 25 | uuid = "54eefc05-d75b-58de-a785-1a3403f0919f" 26 | version = "0.4.0" 27 | 28 | [[Compat]] 29 | deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] 30 | git-tree-sha1 = "ec61a16eed883ad0cfa002d7489b3ce6d039bb9a" 31 | uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" 32 | version = "1.4.0" 33 | 34 | [[Conda]] 35 | deps = ["Compat", "JSON", "VersionParsing"] 36 | git-tree-sha1 = "fb86fe40cb5b35990e368709bfdc1b46dbb99dac" 37 | uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" 38 | version = "1.1.1" 39 | 40 | [[Dates]] 41 | deps = ["Printf"] 42 | uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" 43 | 44 | [[DecFP]] 45 | deps = ["BinaryProvider", "Compat", "Libdl", "SpecialFunctions"] 46 | git-tree-sha1 = "bb3314cdb0145ebb5bac7969b7c9e5a2a8d9ab34" 47 | uuid = "55939f99-70c6-5e9b-8bb0-5071ed7d61fd" 48 | version = "0.4.7" 49 | 50 | [[DelimitedFiles]] 51 | deps = ["Mmap"] 52 | uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" 53 | 54 | [[Distributed]] 55 | deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] 56 | uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" 57 | 58 | [[FileWatching]] 59 | uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" 60 | 61 | [[Gumbo]] 62 | deps = ["AbstractTrees", "BinaryProvider", "Libdl", "Test"] 63 | git-tree-sha1 = "b16b6c5127e8c6be3084e6658c5fb5dd1f97d7fd" 64 | uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 65 | version = "0.5.1" 66 | 67 | [[HTTP]] 68 | deps = ["Base64", "Dates", "Distributed", "IniFile", "MbedTLS", "Sockets", "Test"] 69 | git-tree-sha1 = "b881f69331e85642be315c63d05ed65d6fc8a05b" 70 | uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" 71 | version = "0.7.1" 72 | 73 | [[IJulia]] 74 | deps = ["Base64", "Compat", "Conda", "Dates", "InteractiveUtils", "JSON", "Markdown", "MbedTLS", "Pkg", "Printf", "REPL", "Random", "SoftGlobalScope", "Test", "UUIDs", "ZMQ"] 75 | git-tree-sha1 = "38d1ce0fbbefcb67f5ab46f1093cbce0335092e0" 76 | uuid = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 77 | version = "1.14.1" 78 | 79 | [[IniFile]] 80 | deps = ["Test"] 81 | git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8" 82 | uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" 83 | version = "0.5.0" 84 | 85 | [[InteractiveUtils]] 86 | deps = ["LinearAlgebra", "Markdown"] 87 | uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" 88 | 89 | [[JSON]] 90 | deps = ["Dates", "Distributed", "Mmap", "Sockets", "Test", "Unicode"] 91 | git-tree-sha1 = "1f7a25b53ec67f5e9422f1f551ee216503f4a0fa" 92 | uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 93 | version = "0.20.0" 94 | 95 | [[LibGit2]] 96 | uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" 97 | 98 | [[Libdl]] 99 | uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" 100 | 101 | [[LinearAlgebra]] 102 | deps = ["Libdl"] 103 | uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" 104 | 105 | [[Logging]] 106 | uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" 107 | 108 | [[Markdown]] 109 | deps = ["Base64"] 110 | uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" 111 | 112 | [[MbedTLS]] 113 | deps = ["BinaryProvider", "Dates", "Libdl", "Random", "Sockets", "Test"] 114 | git-tree-sha1 = "c93a87da4081a3de781f34e0540175795a2ce83d" 115 | uuid = "739be429-bea8-5141-9913-cc70e7f3736d" 116 | version = "0.6.6" 117 | 118 | [[Mmap]] 119 | uuid = "a63ad114-7e13-5084-954f-fe012c677804" 120 | 121 | [[MySQL]] 122 | deps = ["BinaryProvider", "Dates", "DecFP", "Libdl", "Tables", "Test"] 123 | git-tree-sha1 = "4b9828e56c9c70a04740f5fc369bd5c65efdbd0a" 124 | uuid = "39abe10b-433b-5dbd-92d4-e302a9df00cd" 125 | version = "0.7.0" 126 | 127 | [[Pkg]] 128 | deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"] 129 | uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 130 | 131 | [[Printf]] 132 | deps = ["Unicode"] 133 | uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" 134 | 135 | [[REPL]] 136 | deps = ["InteractiveUtils", "Markdown", "Sockets"] 137 | uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" 138 | 139 | [[Random]] 140 | deps = ["Serialization"] 141 | uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 142 | 143 | [[Requires]] 144 | deps = ["Test"] 145 | git-tree-sha1 = "f6fbf4ba64d295e146e49e021207993b6b48c7d1" 146 | uuid = "ae029012-a4dd-5104-9daa-d747884805df" 147 | version = "0.5.2" 148 | 149 | [[SHA]] 150 | uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" 151 | 152 | [[Serialization]] 153 | uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" 154 | 155 | [[SharedArrays]] 156 | deps = ["Distributed", "Mmap", "Random", "Serialization"] 157 | uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" 158 | 159 | [[Sockets]] 160 | uuid = "6462fe0b-24de-5631-8697-dd941f90decc" 161 | 162 | [[SoftGlobalScope]] 163 | deps = ["Test"] 164 | git-tree-sha1 = "97f6dfcf612b9a7260fde44170725d9ea34b1431" 165 | uuid = "b85f4697-e234-5449-a836-ec8e2f98b302" 166 | version = "1.0.7" 167 | 168 | [[SparseArrays]] 169 | deps = ["LinearAlgebra", "Random"] 170 | uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" 171 | 172 | [[SpecialFunctions]] 173 | deps = ["BinDeps", "BinaryProvider", "Libdl", "Test"] 174 | git-tree-sha1 = "0b45dc2e45ed77f445617b99ff2adf0f5b0f23ea" 175 | uuid = "276daf66-3868-5448-9aa4-cd146d93841b" 176 | version = "0.7.2" 177 | 178 | [[Statistics]] 179 | deps = ["LinearAlgebra", "SparseArrays"] 180 | uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 181 | 182 | [[Tables]] 183 | deps = ["Requires", "Test"] 184 | git-tree-sha1 = "940944e6b68a35046282897a2218891c7cf14a32" 185 | uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" 186 | version = "0.1.12" 187 | 188 | [[Test]] 189 | deps = ["Distributed", "InteractiveUtils", "Logging", "Random"] 190 | uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" 191 | 192 | [[URIParser]] 193 | deps = ["Test", "Unicode"] 194 | git-tree-sha1 = "6ddf8244220dfda2f17539fa8c9de20d6c575b69" 195 | uuid = "30578b45-9adc-5946-b283-645ec420af67" 196 | version = "0.4.0" 197 | 198 | [[UUIDs]] 199 | deps = ["Random"] 200 | uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" 201 | 202 | [[Unicode]] 203 | uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" 204 | 205 | [[VersionParsing]] 206 | deps = ["Compat"] 207 | git-tree-sha1 = "c9d5aa108588b978bd859554660c8a5c4f2f7669" 208 | uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" 209 | version = "1.1.3" 210 | 211 | [[ZMQ]] 212 | deps = ["BinaryProvider", "FileWatching", "Libdl", "Sockets", "Test"] 213 | git-tree-sha1 = "34e7ac2d1d59d19d0e86bde99f1f02262bfa1613" 214 | uuid = "c2297ded-f4af-51ae-bb23-16f91089e4e1" 215 | version = "1.0.0" 216 | -------------------------------------------------------------------------------- /Chapter13/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | Cascadia = "54eefc05-d75b-58de-a785-1a3403f0919f" 3 | Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 4 | HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" 5 | IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 6 | JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 7 | MySQL = "39abe10b-433b-5dbd-92d4-e302a9df00cd" 8 | Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 9 | Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 10 | -------------------------------------------------------------------------------- /Chapter13/modules/Letters.jl: -------------------------------------------------------------------------------- 1 | module Letters 2 | 3 | using Random 4 | 5 | export randstring 6 | 7 | const MY_NAME = "Letters" 8 | 9 | function rand() 10 | Random.rand('A':'Z') 11 | end 12 | 13 | function randstring() 14 | [rand() for _ in 1:10] |> join 15 | end 16 | 17 | include("module_name.jl") 18 | 19 | # include("Numbers.jl") 20 | 21 | end 22 | -------------------------------------------------------------------------------- /Chapter13/modules/Numbers.jl: -------------------------------------------------------------------------------- 1 | module Numbers 2 | 3 | using Random 4 | 5 | export halfrand 6 | 7 | const MY_NAME = "Numbers" 8 | 9 | function rand() 10 | Random.rand(1:1_000) 11 | end 12 | 13 | function halfrand() 14 | floor(rand() / 2) 15 | end 16 | 17 | include("module_name.jl") 18 | 19 | end 20 | -------------------------------------------------------------------------------- /Chapter13/modules/module_name.jl: -------------------------------------------------------------------------------- 1 | function myname() 2 | MY_NAME 3 | end 4 | -------------------------------------------------------------------------------- /Chapter13/modules/testinclude.jl: -------------------------------------------------------------------------------- 1 | somevar = 10 2 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/Articles.jl: -------------------------------------------------------------------------------- 1 | module Articles 2 | 3 | export Article, save, find 4 | 5 | using ...Database, MySQL, JSON 6 | 7 | struct Article 8 | content::String 9 | links::Vector{String} 10 | title::String 11 | image::String 12 | url::String 13 | 14 | Article(; content = "", links = String[], title = "", image = "", url = "") = new(content, links, title, image, url) 15 | Article(content, links, title, image, url) = new(content, links, title, image, url) 16 | end 17 | 18 | function find(url) :: Vector{Article} 19 | articles = Article[] 20 | 21 | result = MySQL.query(CONN, "SELECT * FROM `articles` WHERE url = '$url'") 22 | 23 | isempty(result.url) && return articles 24 | 25 | for i in eachindex(result.url) 26 | push!(articles, Article(result.content[i], 27 | JSON.parse(result.links[i]), 28 | result.title[i], 29 | result.image[i], 30 | result.url[i])) 31 | end 32 | 33 | articles 34 | end 35 | 36 | function save(a::Article) 37 | sql = "INSERT IGNORE INTO articles 38 | (title, content, links, image, url) VALUES (?, ?, ?, ?, ?)" 39 | stmt = MySQL.Stmt(CONN, sql) 40 | result = MySQL.execute!(stmt, 41 | [ a.title, 42 | a.content, 43 | JSON.json(a.links), 44 | a.image, 45 | a.url] 46 | ) 47 | end 48 | 49 | function createtable() 50 | sql = """ 51 | CREATE TABLE `articles` ( 52 | `title` varchar(1000), 53 | `content` text, 54 | `links` text, 55 | `image` varchar(500), 56 | `url` varchar(500), 57 | UNIQUE KEY `url` (`url`) 58 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 59 | """ 60 | 61 | MySQL.execute!(CONN, sql) 62 | end 63 | 64 | end 65 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/Database.jl: -------------------------------------------------------------------------------- 1 | module Database 2 | 3 | using MySQL 4 | 5 | const HOST = "localhost" 6 | const USER = "root" 7 | const PASS = "root" 8 | const DB = "six_degrees" 9 | 10 | const CONN = MySQL.connect(HOST, USER, PASS, db = DB) 11 | 12 | export CONN 13 | 14 | disconnect() = MySQL.disconnect(CONN) 15 | 16 | atexit(disconnect) 17 | 18 | end 19 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/Gameplay.jl: -------------------------------------------------------------------------------- 1 | module Gameplay 2 | 3 | using ..Wikipedia, ..Wikipedia.Articles 4 | 5 | export newgame 6 | 7 | const DIFFICULTY_EASY = 2 8 | const DIFFICULTY_MEDIUM = 4 9 | const DIFFICULTY_HARD = 6 10 | 11 | function newgame(difficulty = DIFFICULTY_HARD) 12 | articles = Article[] 13 | 14 | for i in 1:difficulty+1 15 | article = if i == 1 16 | article = persistedarticle(fetchrandom()...) 17 | else 18 | url = rand(articles[i-1].links) 19 | existing_articles = Articles.find(url) 20 | 21 | article = isempty(existing_articles) ? persistedarticle(fetchpage(url)...) : existing_articles[1] 22 | end 23 | 24 | push!(articles, article) 25 | end 26 | 27 | articles 28 | end 29 | 30 | end 31 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/Manifest.toml: -------------------------------------------------------------------------------- 1 | [[AbstractTrees]] 2 | deps = ["Markdown", "Test"] 3 | git-tree-sha1 = "feb8b2c99359901e295443c9d0c7e711604acf39" 4 | uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" 5 | version = "0.2.0" 6 | 7 | [[Base64]] 8 | uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 9 | 10 | [[BinDeps]] 11 | deps = ["Compat", "Libdl", "SHA", "URIParser"] 12 | git-tree-sha1 = "12093ca6cdd0ee547c39b1870e0c9c3f154d9ca9" 13 | uuid = "9e28174c-4ba2-5203-b857-d8d62c4213ee" 14 | version = "0.8.10" 15 | 16 | [[BinaryProvider]] 17 | deps = ["Libdl", "Pkg", "SHA", "Test"] 18 | git-tree-sha1 = "48c147e63431adbcee69bc40b04c3f0fec0a4982" 19 | uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" 20 | version = "0.5.0" 21 | 22 | [[Cascadia]] 23 | deps = ["AbstractTrees", "Gumbo", "Test"] 24 | git-tree-sha1 = "d51428ab540880c7329c74f178a793096f4e36f0" 25 | uuid = "54eefc05-d75b-58de-a785-1a3403f0919f" 26 | version = "0.4.0" 27 | 28 | [[Compat]] 29 | deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] 30 | git-tree-sha1 = "ae262fa91da6a74e8937add6b613f58cd56cdad4" 31 | uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" 32 | version = "1.1.0" 33 | 34 | [[DataStreams]] 35 | deps = ["Dates", "Missings", "Pkg", "Test", "WeakRefStrings"] 36 | git-tree-sha1 = "69c72a1beb4fc79490c361635664e13c8e4a9548" 37 | uuid = "9a8bc11e-79be-5b39-94d7-1ccc349a1a85" 38 | version = "0.4.1" 39 | 40 | [[Dates]] 41 | deps = ["Printf"] 42 | uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" 43 | 44 | [[DecFP]] 45 | deps = ["BinaryProvider", "Compat", "Libdl", "SpecialFunctions"] 46 | git-tree-sha1 = "5c783376875e7f7757d574945a97c3afb56ae2c5" 47 | uuid = "55939f99-70c6-5e9b-8bb0-5071ed7d61fd" 48 | version = "0.4.6" 49 | 50 | [[DelimitedFiles]] 51 | deps = ["Mmap"] 52 | uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" 53 | 54 | [[Distributed]] 55 | deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] 56 | uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" 57 | 58 | [[Gumbo]] 59 | deps = ["AbstractTrees", "BinaryProvider", "Libdl", "Pkg", "Test"] 60 | git-tree-sha1 = "b16b6c5127e8c6be3084e6658c5fb5dd1f97d7fd" 61 | uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 62 | version = "0.5.1" 63 | 64 | [[HTTP]] 65 | deps = ["Base64", "Dates", "Distributed", "IniFile", "MbedTLS", "Sockets", "Test"] 66 | git-tree-sha1 = "16499da36240bf80df9a7e9b0f228710be1fe37c" 67 | uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" 68 | version = "0.7.0" 69 | 70 | [[IniFile]] 71 | deps = ["Test"] 72 | git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8" 73 | uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" 74 | version = "0.5.0" 75 | 76 | [[InteractiveUtils]] 77 | deps = ["LinearAlgebra", "Markdown"] 78 | uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" 79 | 80 | [[JSON]] 81 | deps = ["Dates", "Distributed", "Mmap", "Pkg", "Sockets", "Test", "Unicode"] 82 | git-tree-sha1 = "fec8e4d433072731466d37ed0061b3ba7f70eeb9" 83 | uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 84 | version = "0.19.0" 85 | 86 | [[LibGit2]] 87 | uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" 88 | 89 | [[Libdl]] 90 | uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" 91 | 92 | [[LinearAlgebra]] 93 | deps = ["Libdl"] 94 | uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" 95 | 96 | [[Logging]] 97 | uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" 98 | 99 | [[Markdown]] 100 | deps = ["Base64"] 101 | uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" 102 | 103 | [[MbedTLS]] 104 | deps = ["BinaryProvider", "Libdl", "Pkg", "Random", "Sockets", "Test"] 105 | git-tree-sha1 = "30016e3f9359f43b76cc2185efea5de5f6c9aa62" 106 | uuid = "739be429-bea8-5141-9913-cc70e7f3736d" 107 | version = "0.6.2" 108 | 109 | [[Missings]] 110 | deps = ["Dates", "InteractiveUtils", "SparseArrays", "Test"] 111 | git-tree-sha1 = "adc26d2ee85a49c413464110d922cf21efc9d233" 112 | uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" 113 | version = "0.3.1" 114 | 115 | [[Mmap]] 116 | uuid = "a63ad114-7e13-5084-954f-fe012c677804" 117 | 118 | [[MySQL]] 119 | deps = ["BinaryProvider", "DataStreams", "Dates", "DecFP", "Libdl", "Missings", "Pkg", "Test"] 120 | git-tree-sha1 = "2f14118e79226c5c8f827e13c83de1368b59fede" 121 | uuid = "39abe10b-433b-5dbd-92d4-e302a9df00cd" 122 | version = "0.6.0" 123 | 124 | [[Pkg]] 125 | deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"] 126 | uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 127 | 128 | [[Printf]] 129 | deps = ["Unicode"] 130 | uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" 131 | 132 | [[REPL]] 133 | deps = ["InteractiveUtils", "Markdown", "Sockets"] 134 | uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" 135 | 136 | [[Random]] 137 | deps = ["Serialization"] 138 | uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 139 | 140 | [[SHA]] 141 | uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" 142 | 143 | [[Serialization]] 144 | uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" 145 | 146 | [[SharedArrays]] 147 | deps = ["Distributed", "Mmap", "Random", "Serialization"] 148 | uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" 149 | 150 | [[Sockets]] 151 | uuid = "6462fe0b-24de-5631-8697-dd941f90decc" 152 | 153 | [[SparseArrays]] 154 | deps = ["LinearAlgebra", "Random"] 155 | uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" 156 | 157 | [[SpecialFunctions]] 158 | deps = ["BinDeps", "BinaryProvider", "Libdl", "Test"] 159 | git-tree-sha1 = "c35c9c76008babf4d658060fc64aeb369a41e7bd" 160 | uuid = "276daf66-3868-5448-9aa4-cd146d93841b" 161 | version = "0.7.1" 162 | 163 | [[Statistics]] 164 | deps = ["LinearAlgebra", "SparseArrays"] 165 | uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 166 | 167 | [[Test]] 168 | deps = ["Distributed", "InteractiveUtils", "Logging", "Random"] 169 | uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" 170 | 171 | [[URIParser]] 172 | deps = ["Test", "Unicode"] 173 | git-tree-sha1 = "6ddf8244220dfda2f17539fa8c9de20d6c575b69" 174 | uuid = "30578b45-9adc-5946-b283-645ec420af67" 175 | version = "0.4.0" 176 | 177 | [[UUIDs]] 178 | deps = ["Random"] 179 | uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" 180 | 181 | [[Unicode]] 182 | uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" 183 | 184 | [[WeakRefStrings]] 185 | deps = ["Missings", "Random", "Test"] 186 | git-tree-sha1 = "1087e8be380f2c8b96434b02bb1150fc1c511135" 187 | uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5" 188 | version = "0.5.3" 189 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | Cascadia = "54eefc05-d75b-58de-a785-1a3403f0919f" 3 | Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 4 | HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" 5 | JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 6 | MySQL = "39abe10b-433b-5dbd-92d4-e302a9df00cd" 7 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/Wikipedia.jl: -------------------------------------------------------------------------------- 1 | module Wikipedia 2 | 3 | using HTTP, Gumbo, Cascadia 4 | import Cascadia: matchFirst 5 | 6 | include("Articles.jl") 7 | using .Articles 8 | 9 | const PROTOCOL = "https://" 10 | const DOMAIN_NAME = "en.m.wikipedia.org" 11 | const RANDOM_PAGE_URL = PROTOCOL * DOMAIN_NAME * "/wiki/Special:Random" 12 | 13 | export fetchrandom, fetchpage, articleinfo, persistedarticle 14 | 15 | # function fetchpage(url) 16 | # url = startswith(url, "/") ? buildurl(url) : url 17 | # 18 | # response = HTTP.get(url) 19 | # 20 | # if response.status == 200 && length(response.body) > 0 21 | # String(response.body) 22 | # else 23 | # "" 24 | # end 25 | # end 26 | 27 | function fetchpage(url) 28 | url = startswith(url, "/") ? buildurl(url) : url 29 | response = HTTP.get(url) 30 | content = if response.status == 200 && length(response.body) > 0 31 | String(response.body) 32 | else 33 | "" 34 | end 35 | relative_url = collect(eachmatch(r"/wiki/(.*)$", (response.request.parent == nothing ? url : Dict(response.request.parent.headers)["Location"])))[1].match 36 | 37 | content, relative_url 38 | end 39 | 40 | 41 | function extractlinks(elem) 42 | map(eachmatch(Selector("a[href^='/wiki/']:not(a[href*=':'])"), elem)) do e 43 | e.attributes["href"] 44 | end |> unique 45 | end 46 | 47 | function extracttitle(elem) 48 | matchFirst(Selector("#section_0"), elem) |> nodeText 49 | end 50 | 51 | function extractimage(elem) 52 | e = matchFirst(Selector(".content a.image img"), elem) 53 | isa(e, Nothing) ? "" : e.attributes["src"] 54 | end 55 | 56 | function fetchrandom() 57 | fetchpage(RANDOM_PAGE_URL) 58 | end 59 | 60 | function articledom(content) 61 | if ! isempty(content) 62 | return Gumbo.parsehtml(content) 63 | end 64 | 65 | error("Article content can not be parsed into DOM") 66 | end 67 | 68 | # function articleinfo(content) 69 | # dom = articledom(content) 70 | # 71 | # Dict( :content => content, 72 | # :links => extractlinks(dom.root), 73 | # :title => extracttitle(dom.root), 74 | # :image => extractimage(dom.root) 75 | # ) 76 | # end 77 | 78 | # function articleinfo(content) 79 | # dom = articledom(content) 80 | # Article(content, 81 | # extractlinks(dom.root), 82 | # extracttitle(dom.root), 83 | # extractimage(dom.root)) 84 | # end 85 | 86 | function articleinfo(content) 87 | dom = articledom(content) 88 | (content, extractlinks(dom.root), extracttitle(dom.root), extractimage(dom.root)) 89 | end 90 | 91 | function persistedarticle(article_content, url) 92 | article = Article(articleinfo(article_content)..., url) 93 | save(article) 94 | 95 | article 96 | end 97 | 98 | function buildurl(article_url) 99 | PROTOCOL * DOMAIN_NAME * article_url 100 | end 101 | 102 | end 103 | -------------------------------------------------------------------------------- /Chapter13/sixdegrees/six_degrees.jl: -------------------------------------------------------------------------------- 1 | using Pkg 2 | pkg"activate ." 3 | 4 | include("Database.jl") 5 | include("Wikipedia.jl") 6 | include("Gameplay.jl") 7 | 8 | using .Wikipedia, .Gameplay 9 | 10 | articles = newgame(Gameplay.DIFFICULTY_EASY) 11 | 12 | for article in articles 13 | println(article.title) 14 | end 15 | -------------------------------------------------------------------------------- /Chapter14/Chapter 14.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "using Pkg\n", 10 | "pkg\"activate .\"" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "# Run this cell in order to download all the package dependencies with the exact versions used in the book\n", 20 | "# This is necessary if (some of) the packages have been updated and have introduced breaking changes\n", 21 | "pkg\"instantiate\"" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "using HTTP, Sockets\n", 31 | "\n", 32 | "const HOST = ip\"0.0.0.0\"\n", 33 | "const PORT = 9999\n", 34 | "\n", 35 | "router = HTTP.Router()\n", 36 | "server = HTTP.Server(router)\n", 37 | "\n", 38 | "HTTP.register!(router, \"/\", HTTP.HandlerFunction(req -> HTTP.Messages.Response(200, \"Hello World\")))\n", 39 | "HTTP.register!(router, \"/bye\", HTTP.HandlerFunction(req -> HTTP.Messages.Response(200, \"Bye\")))\n", 40 | "HTTP.register!(router, \"*\", HTTP.HandlerFunction(req -> HTTP.Messages.Response(404, \"Not found\")))\n", 41 | "\n", 42 | "HTTP.serve(server, HOST, PORT)" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [] 51 | } 52 | ], 53 | "metadata": { 54 | "kernelspec": { 55 | "display_name": "Julia 1.0.1", 56 | "language": "julia", 57 | "name": "julia-1.0" 58 | }, 59 | "language_info": { 60 | "file_extension": ".jl", 61 | "mimetype": "application/julia", 62 | "name": "julia", 63 | "version": "1.0.2" 64 | } 65 | }, 66 | "nbformat": 4, 67 | "nbformat_minor": 2 68 | } 69 | -------------------------------------------------------------------------------- /Chapter14/Manifest.toml: -------------------------------------------------------------------------------- 1 | [[AbstractTrees]] 2 | deps = ["Markdown", "Test"] 3 | git-tree-sha1 = "6621d9645702c1c4e6970cc6a3eae440c768000b" 4 | uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" 5 | version = "0.2.1" 6 | 7 | [[Base64]] 8 | uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 9 | 10 | [[BinaryProvider]] 11 | deps = ["Libdl", "Pkg", "SHA", "Test"] 12 | git-tree-sha1 = "055eb2690182ebc31087859c3dd8598371d3ef9e" 13 | uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" 14 | version = "0.5.3" 15 | 16 | [[Cascadia]] 17 | deps = ["AbstractTrees", "Gumbo", "Test"] 18 | git-tree-sha1 = "d51428ab540880c7329c74f178a793096f4e36f0" 19 | uuid = "54eefc05-d75b-58de-a785-1a3403f0919f" 20 | version = "0.4.0" 21 | 22 | [[Compat]] 23 | deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] 24 | git-tree-sha1 = "ec61a16eed883ad0cfa002d7489b3ce6d039bb9a" 25 | uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" 26 | version = "1.4.0" 27 | 28 | [[Conda]] 29 | deps = ["Compat", "JSON", "VersionParsing"] 30 | git-tree-sha1 = "fb86fe40cb5b35990e368709bfdc1b46dbb99dac" 31 | uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" 32 | version = "1.1.1" 33 | 34 | [[Dates]] 35 | deps = ["Printf"] 36 | uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" 37 | 38 | [[DelimitedFiles]] 39 | deps = ["Mmap"] 40 | uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" 41 | 42 | [[Distributed]] 43 | deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] 44 | uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" 45 | 46 | [[FileWatching]] 47 | uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" 48 | 49 | [[Gumbo]] 50 | deps = ["AbstractTrees", "BinaryProvider", "Libdl", "Test"] 51 | git-tree-sha1 = "b16b6c5127e8c6be3084e6658c5fb5dd1f97d7fd" 52 | uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 53 | version = "0.5.1" 54 | 55 | [[HTTP]] 56 | deps = ["Base64", "Dates", "Distributed", "IniFile", "MbedTLS", "Sockets", "Test"] 57 | git-tree-sha1 = "b881f69331e85642be315c63d05ed65d6fc8a05b" 58 | uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" 59 | version = "0.7.1" 60 | 61 | [[IJulia]] 62 | deps = ["Base64", "Compat", "Conda", "Dates", "InteractiveUtils", "JSON", "Markdown", "MbedTLS", "Pkg", "Printf", "REPL", "Random", "SoftGlobalScope", "Test", "UUIDs", "ZMQ"] 63 | git-tree-sha1 = "38d1ce0fbbefcb67f5ab46f1093cbce0335092e0" 64 | uuid = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 65 | version = "1.14.1" 66 | 67 | [[IniFile]] 68 | deps = ["Test"] 69 | git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8" 70 | uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" 71 | version = "0.5.0" 72 | 73 | [[InteractiveUtils]] 74 | deps = ["LinearAlgebra", "Markdown"] 75 | uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" 76 | 77 | [[JSON]] 78 | deps = ["Dates", "Distributed", "Mmap", "Sockets", "Test", "Unicode"] 79 | git-tree-sha1 = "1f7a25b53ec67f5e9422f1f551ee216503f4a0fa" 80 | uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 81 | version = "0.20.0" 82 | 83 | [[LibGit2]] 84 | uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" 85 | 86 | [[Libdl]] 87 | uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" 88 | 89 | [[LinearAlgebra]] 90 | deps = ["Libdl"] 91 | uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" 92 | 93 | [[Logging]] 94 | uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" 95 | 96 | [[Markdown]] 97 | deps = ["Base64"] 98 | uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" 99 | 100 | [[MbedTLS]] 101 | deps = ["BinaryProvider", "Dates", "Libdl", "Random", "Sockets", "Test"] 102 | git-tree-sha1 = "c93a87da4081a3de781f34e0540175795a2ce83d" 103 | uuid = "739be429-bea8-5141-9913-cc70e7f3736d" 104 | version = "0.6.6" 105 | 106 | [[Mmap]] 107 | uuid = "a63ad114-7e13-5084-954f-fe012c677804" 108 | 109 | [[Pkg]] 110 | deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"] 111 | uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 112 | 113 | [[Printf]] 114 | deps = ["Unicode"] 115 | uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" 116 | 117 | [[REPL]] 118 | deps = ["InteractiveUtils", "Markdown", "Sockets"] 119 | uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" 120 | 121 | [[Random]] 122 | deps = ["Serialization"] 123 | uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 124 | 125 | [[SHA]] 126 | uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" 127 | 128 | [[Serialization]] 129 | uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" 130 | 131 | [[SharedArrays]] 132 | deps = ["Distributed", "Mmap", "Random", "Serialization"] 133 | uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" 134 | 135 | [[Sockets]] 136 | uuid = "6462fe0b-24de-5631-8697-dd941f90decc" 137 | 138 | [[SoftGlobalScope]] 139 | deps = ["Test"] 140 | git-tree-sha1 = "97f6dfcf612b9a7260fde44170725d9ea34b1431" 141 | uuid = "b85f4697-e234-5449-a836-ec8e2f98b302" 142 | version = "1.0.7" 143 | 144 | [[SparseArrays]] 145 | deps = ["LinearAlgebra", "Random"] 146 | uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" 147 | 148 | [[Statistics]] 149 | deps = ["LinearAlgebra", "SparseArrays"] 150 | uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 151 | 152 | [[Test]] 153 | deps = ["Distributed", "InteractiveUtils", "Logging", "Random"] 154 | uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" 155 | 156 | [[UUIDs]] 157 | deps = ["Random"] 158 | uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" 159 | 160 | [[Unicode]] 161 | uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" 162 | 163 | [[VersionParsing]] 164 | deps = ["Compat"] 165 | git-tree-sha1 = "c9d5aa108588b978bd859554660c8a5c4f2f7669" 166 | uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" 167 | version = "1.1.3" 168 | 169 | [[ZMQ]] 170 | deps = ["BinaryProvider", "FileWatching", "Libdl", "Sockets", "Test"] 171 | git-tree-sha1 = "34e7ac2d1d59d19d0e86bde99f1f02262bfa1613" 172 | uuid = "c2297ded-f4af-51ae-bb23-16f91089e4e1" 173 | version = "1.0.0" 174 | -------------------------------------------------------------------------------- /Chapter14/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | Cascadia = "54eefc05-d75b-58de-a785-1a3403f0919f" 3 | Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 4 | HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" 5 | IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 6 | Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 7 | Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 8 | Sockets = "6462fe0b-24de-5631-8697-dd941f90decc" 9 | -------------------------------------------------------------------------------- /Chapter14/hello.jl: -------------------------------------------------------------------------------- 1 | using HTTP, Sockets 2 | 3 | const HOST = ip"0.0.0.0" 4 | const PORT = 9999 5 | 6 | router = HTTP.Router() 7 | server = HTTP.Server(router) 8 | 9 | HTTP.register!(router, "/", HTTP.HandlerFunction(req -> HTTP.Messages.Response(200, "Hello World"))) 10 | HTTP.register!(router, "/bye", HTTP.HandlerFunction(req -> HTTP.Messages.Response(200, "Bye"))) 11 | HTTP.register!(router, "*", HTTP.HandlerFunction(req -> HTTP.Messages.Response(404, "Not found"))) 12 | 13 | HTTP.serve(server, HOST, PORT) 14 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/Articles.jl: -------------------------------------------------------------------------------- 1 | module Articles 2 | 3 | export Article, save, find 4 | 5 | using ...Database, MySQL, JSON 6 | 7 | struct Article 8 | content::String 9 | links::Vector{String} 10 | title::String 11 | image::String 12 | url::String 13 | 14 | Article(; content = "", links = String[], title = "", image = "", url = "") = new(content, links, title, image, url) 15 | Article(content, links, title, image, url) = new(content, links, title, image, url) 16 | end 17 | 18 | function find(url) :: Vector{Article} 19 | articles = Article[] 20 | 21 | result = MySQL.query(CONN, "SELECT * FROM `articles` WHERE url = '$url'") 22 | 23 | isempty(result.url) && return articles 24 | 25 | for i in eachindex(result.url) 26 | push!(articles, Article(result.content[i], 27 | JSON.parse(result.links[i]), 28 | result.title[i], 29 | result.image[i], 30 | result.url[i])) 31 | end 32 | 33 | articles 34 | end 35 | 36 | function save(a::Article) 37 | sql = "INSERT IGNORE INTO articles 38 | (title, content, links, image, url) VALUES (?, ?, ?, ?, ?)" 39 | stmt = MySQL.Stmt(CONN, sql) 40 | result = MySQL.execute!(stmt, 41 | [ a.title, 42 | a.content, 43 | JSON.json(a.links), 44 | a.image, 45 | a.url] 46 | ) 47 | end 48 | 49 | function createtable() 50 | sql = """ 51 | CREATE TABLE `articles` ( 52 | `title` varchar(1000), 53 | `content` text, 54 | `links` text, 55 | `image` varchar(500), 56 | `url` varchar(500), 57 | UNIQUE KEY `url` (`url`) 58 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 59 | """ 60 | 61 | MySQL.execute!(CONN, sql) 62 | end 63 | 64 | end 65 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/Database.jl: -------------------------------------------------------------------------------- 1 | module Database 2 | 3 | using MySQL 4 | 5 | const HOST = "127.0.0.1" 6 | const USER = "root" 7 | const PASS = "root" 8 | const DB = "six_degrees" 9 | const PORT = 8889 10 | 11 | const CONN = MySQL.connect(HOST, USER, PASS, db = DB, port = PORT) 12 | 13 | export CONN 14 | 15 | disconnect() = MySQL.disconnect(CONN) 16 | 17 | atexit(disconnect) 18 | 19 | end 20 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/GameSession.jl: -------------------------------------------------------------------------------- 1 | module GameSession 2 | 3 | using ..Gameplay, ..Wikipedia, ..Wikipedia.Articles 4 | using Random 5 | 6 | mutable struct Game 7 | id::String 8 | articles::Vector{Article} 9 | history::Vector{Article} 10 | steps_taken::UInt8 11 | difficulty::UInt8 12 | 13 | Game(game_difficulty) = new(randstring(), newgame(game_difficulty), Article[], 0, game_difficulty) 14 | end 15 | 16 | const GAMES = Dict{String,Game}() 17 | 18 | export newgamesession, gamesession, destroygamesession 19 | 20 | function newgamesession(difficulty) 21 | game = Game(difficulty) 22 | GAMES[game.id] = game 23 | 24 | game 25 | end 26 | 27 | function gamesession(id) 28 | GAMES[id] 29 | end 30 | 31 | function destroygamesession(id) 32 | delete!(GAMES, id) 33 | end 34 | 35 | end 36 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/Gameplay.jl: -------------------------------------------------------------------------------- 1 | module Gameplay 2 | 3 | using ..Wikipedia, ..Wikipedia.Articles 4 | 5 | export newgame 6 | 7 | const DIFFICULTY_EASY = 2 8 | const DIFFICULTY_MEDIUM = 4 9 | const DIFFICULTY_HARD = 6 10 | 11 | const MAX_NUMBER_OF_STEPS = 10 12 | 13 | function newgame(difficulty = DIFFICULTY_HARD) 14 | articles = Article[] 15 | 16 | for i in 1:difficulty+1 17 | article = if i == 1 18 | article = persistedarticle(fetchrandom()...) 19 | else 20 | url = rand(articles[i-1].links) 21 | existing_articles = Articles.find(url) 22 | 23 | article = isempty(existing_articles) ? persistedarticle(fetchpage(url)...) : existing_articles[1] 24 | end 25 | 26 | push!(articles, article) 27 | end 28 | 29 | articles 30 | end 31 | 32 | end 33 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/Manifest.toml: -------------------------------------------------------------------------------- 1 | [[AbstractTrees]] 2 | deps = ["Markdown", "Test"] 3 | git-tree-sha1 = "feb8b2c99359901e295443c9d0c7e711604acf39" 4 | uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" 5 | version = "0.2.0" 6 | 7 | [[Base64]] 8 | uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 9 | 10 | [[BinDeps]] 11 | deps = ["Compat", "Libdl", "SHA", "URIParser"] 12 | git-tree-sha1 = "12093ca6cdd0ee547c39b1870e0c9c3f154d9ca9" 13 | uuid = "9e28174c-4ba2-5203-b857-d8d62c4213ee" 14 | version = "0.8.10" 15 | 16 | [[BinaryProvider]] 17 | deps = ["Libdl", "Pkg", "SHA", "Test"] 18 | git-tree-sha1 = "48c147e63431adbcee69bc40b04c3f0fec0a4982" 19 | uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" 20 | version = "0.5.0" 21 | 22 | [[Cascadia]] 23 | deps = ["AbstractTrees", "Gumbo", "Test"] 24 | git-tree-sha1 = "d51428ab540880c7329c74f178a793096f4e36f0" 25 | uuid = "54eefc05-d75b-58de-a785-1a3403f0919f" 26 | version = "0.4.0" 27 | 28 | [[Compat]] 29 | deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] 30 | git-tree-sha1 = "ff2595695fc4f14427358ce2593f867085c45dcb" 31 | uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" 32 | version = "1.2.0" 33 | 34 | [[Dates]] 35 | deps = ["Printf"] 36 | uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" 37 | 38 | [[DecFP]] 39 | deps = ["BinaryProvider", "Compat", "Libdl", "SpecialFunctions"] 40 | git-tree-sha1 = "5c783376875e7f7757d574945a97c3afb56ae2c5" 41 | uuid = "55939f99-70c6-5e9b-8bb0-5071ed7d61fd" 42 | version = "0.4.6" 43 | 44 | [[DelimitedFiles]] 45 | deps = ["Mmap"] 46 | uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" 47 | 48 | [[Distributed]] 49 | deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] 50 | uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" 51 | 52 | [[Gumbo]] 53 | deps = ["AbstractTrees", "BinaryProvider", "Libdl", "Pkg", "Test"] 54 | git-tree-sha1 = "b16b6c5127e8c6be3084e6658c5fb5dd1f97d7fd" 55 | uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 56 | version = "0.5.1" 57 | 58 | [[HTTP]] 59 | deps = ["Base64", "Dates", "Distributed", "IniFile", "MbedTLS", "Sockets", "Test"] 60 | git-tree-sha1 = "b881f69331e85642be315c63d05ed65d6fc8a05b" 61 | uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" 62 | version = "0.7.1" 63 | 64 | [[IniFile]] 65 | deps = ["Test"] 66 | git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8" 67 | uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" 68 | version = "0.5.0" 69 | 70 | [[InteractiveUtils]] 71 | deps = ["LinearAlgebra", "Markdown"] 72 | uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" 73 | 74 | [[JSON]] 75 | deps = ["Dates", "Distributed", "Mmap", "Pkg", "Sockets", "Test", "Unicode"] 76 | git-tree-sha1 = "fec8e4d433072731466d37ed0061b3ba7f70eeb9" 77 | uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 78 | version = "0.19.0" 79 | 80 | [[LibGit2]] 81 | uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" 82 | 83 | [[Libdl]] 84 | uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" 85 | 86 | [[LinearAlgebra]] 87 | deps = ["Libdl"] 88 | uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" 89 | 90 | [[Logging]] 91 | uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" 92 | 93 | [[Markdown]] 94 | deps = ["Base64"] 95 | uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" 96 | 97 | [[MbedTLS]] 98 | deps = ["BinaryProvider", "Libdl", "Pkg", "Random", "Sockets", "Test"] 99 | git-tree-sha1 = "3775d205b09b624aa06d39012a8920ba99cb3b8b" 100 | uuid = "739be429-bea8-5141-9913-cc70e7f3736d" 101 | version = "0.6.3" 102 | 103 | [[Mmap]] 104 | uuid = "a63ad114-7e13-5084-954f-fe012c677804" 105 | 106 | [[MySQL]] 107 | deps = ["BinaryProvider", "Dates", "DecFP", "Libdl", "Pkg", "Tables", "Test"] 108 | git-tree-sha1 = "4b9828e56c9c70a04740f5fc369bd5c65efdbd0a" 109 | uuid = "39abe10b-433b-5dbd-92d4-e302a9df00cd" 110 | version = "0.7.0" 111 | 112 | [[Pkg]] 113 | deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"] 114 | uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 115 | 116 | [[Printf]] 117 | deps = ["Unicode"] 118 | uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" 119 | 120 | [[REPL]] 121 | deps = ["InteractiveUtils", "Markdown", "Sockets"] 122 | uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" 123 | 124 | [[Random]] 125 | deps = ["Serialization"] 126 | uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" 127 | 128 | [[Requires]] 129 | deps = ["Test"] 130 | git-tree-sha1 = "f6fbf4ba64d295e146e49e021207993b6b48c7d1" 131 | uuid = "ae029012-a4dd-5104-9daa-d747884805df" 132 | version = "0.5.2" 133 | 134 | [[SHA]] 135 | uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" 136 | 137 | [[Serialization]] 138 | uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" 139 | 140 | [[SharedArrays]] 141 | deps = ["Distributed", "Mmap", "Random", "Serialization"] 142 | uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" 143 | 144 | [[Sockets]] 145 | uuid = "6462fe0b-24de-5631-8697-dd941f90decc" 146 | 147 | [[SparseArrays]] 148 | deps = ["LinearAlgebra", "Random"] 149 | uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" 150 | 151 | [[SpecialFunctions]] 152 | deps = ["BinDeps", "BinaryProvider", "Libdl", "Test"] 153 | git-tree-sha1 = "c35c9c76008babf4d658060fc64aeb369a41e7bd" 154 | uuid = "276daf66-3868-5448-9aa4-cd146d93841b" 155 | version = "0.7.1" 156 | 157 | [[Statistics]] 158 | deps = ["LinearAlgebra", "SparseArrays"] 159 | uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 160 | 161 | [[Tables]] 162 | deps = ["Pkg", "Requires", "Test"] 163 | git-tree-sha1 = "277464179bc7cfb1b4d5a4f3ccde0fc75792157f" 164 | uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" 165 | version = "0.1.8" 166 | 167 | [[Test]] 168 | deps = ["Distributed", "InteractiveUtils", "Logging", "Random"] 169 | uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" 170 | 171 | [[URIParser]] 172 | deps = ["Test", "Unicode"] 173 | git-tree-sha1 = "6ddf8244220dfda2f17539fa8c9de20d6c575b69" 174 | uuid = "30578b45-9adc-5946-b283-645ec420af67" 175 | version = "0.4.0" 176 | 177 | [[UUIDs]] 178 | deps = ["Random"] 179 | uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" 180 | 181 | [[Unicode]] 182 | uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" 183 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | Cascadia = "54eefc05-d75b-58de-a785-1a3403f0919f" 3 | Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a" 4 | HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" 5 | JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" 6 | MySQL = "39abe10b-433b-5dbd-92d4-e302a9df00cd" 7 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/WebApp.jl: -------------------------------------------------------------------------------- 1 | module WebApp 2 | 3 | using HTTP, Sockets 4 | using ..Gameplay, ..GameSession, ..Wikipedia, ..Wikipedia.Articles 5 | 6 | # Configuration 7 | const HOST = ip"0.0.0.0" 8 | const PORT = 8888 9 | const ROUTER = HTTP.Router() 10 | const SERVER = HTTP.Server(ROUTER) 11 | 12 | # Functions 13 | function wikiarticle(game, article) 14 | html = """ 15 | 16 | 17 | $(head()) 18 | 19 | 20 | $(objective(game)) 21 |
22 | $( 23 | if losinggame(game) 24 | "

You Lost :(

" 25 | else 26 | puzzlesolved(game, article) ? "

You Won!

" : "" 27 | end 28 | ) 29 | 30 |

$(article.title)

31 |
32 | $(replace(article.content, "/wiki/"=>"/$(game.id)/wiki/")) 33 |
34 | 35 | 36 | """ 37 | end 38 | 39 | function history(game) 40 | html = """
    """ 41 | iter = 0 42 | for a in game.history 43 | html *= """ 44 |
  1. 45 | $(a.title) 46 |
  2. 47 | """ 48 | iter += 1 49 | end 50 | 51 | html * "
" 52 | end 53 | 54 | function objective(game) 55 | """ 56 |
57 |

Go from 58 | $(game.articles[1].title) 59 | to 60 | $(game.articles[end].title) 61 |

62 |
63 |
64 | Progress: 65 | $(size(game.history, 1) - 1) 66 | out of maximum 67 | $(size(game.articles, 1) - 1) 68 | links in 69 | $(game.steps_taken) 70 | steps 71 |
72 | $(history(game)) 73 |
74 |
75 | Solution? | 76 | New game 77 |
78 |
79 | """ 80 | end 81 | 82 | function head() 83 | """ 84 | 85 | 86 | 87 | 6 Degrees of Wikipedia 88 | 89 | """ 90 | end 91 | 92 | function puzzlesolved(game, article) 93 | article.url == game.articles[end].url 94 | end 95 | 96 | function losinggame(game) 97 | game.steps_taken >= Gameplay.MAX_NUMBER_OF_STEPS 98 | end 99 | 100 | function parseuri(uri) 101 | map(x -> String(x), split(uri, "/", keepempty = false)) 102 | end 103 | 104 | 105 | # Routes handlers 106 | const landingpage = HTTP.HandlerFunction() do req 107 | html = """ 108 | 109 | 110 | $(head()) 111 | 112 | 113 |
114 |

Six degrees of Wikipedia

115 |

116 | The goal of the game is to find the shortest path between two random Wikipedia articles.
117 | Depending on the difficulty level you choose, the Wiki pages will be further apart and less related.
118 | If you can’t find the solution, you can always go back up the articles chain, but you need to find the solution within the maximum number of steps, otherwise you lose.
119 | If you get stuck, you can always check the solution, but you'll lose.
120 | Good luck and enjoy! 121 |

122 | 123 |
124 | 125 | 131 |
132 | 133 | 134 | """ 135 | 136 | HTTP.Messages.Response(200, html) 137 | end 138 | 139 | const newgamepage = HTTP.HandlerFunction() do req 140 | game = parse(UInt8, (replace(req.target, "/new/"=>""))) |> newgamesession 141 | article = game.articles[1] 142 | push!(game.history, article) 143 | 144 | HTTP.Messages.Response(200, wikiarticle(game, article)) 145 | end 146 | 147 | const articlepage = HTTP.HandlerFunction() do req 148 | uri_parts = parseuri(req.target) 149 | game = gamesession(uri_parts[1]) 150 | article_uri = "/wiki/$(uri_parts[end])" 151 | 152 | existing_articles = Articles.find(article_uri) 153 | article = isempty(existing_articles) ? persistedarticle(fetchpage(article_uri)...) : existing_articles[1] 154 | 155 | push!(game.history, article) 156 | game.steps_taken += 1 157 | 158 | puzzlesolved(game, article) && destroygamesession(game.id) 159 | 160 | HTTP.Messages.Response(200, wikiarticle(game, article)) 161 | end 162 | 163 | const backpage = HTTP.HandlerFunction() do req 164 | uri_parts = parseuri(req.target) 165 | game = gamesession(uri_parts[1]) 166 | history_index = parse(UInt8, uri_parts[end]) 167 | 168 | article = game.history[history_index] 169 | game.history = game.history[1:history_index] 170 | 171 | HTTP.Messages.Response(200, wikiarticle(game, article)) 172 | end 173 | 174 | const solutionpage = HTTP.HandlerFunction() do req 175 | uri_parts = parseuri(req.target) 176 | game = gamesession(uri_parts[1]) 177 | game.history = game.articles 178 | game.steps_taken = Gameplay.MAX_NUMBER_OF_STEPS 179 | article = game.articles[end] 180 | 181 | HTTP.Messages.Response(200, wikiarticle(game, article)) 182 | end 183 | 184 | const notfoundpage = HTTP.HandlerFunction() do req 185 | HTTP.Messages.Response(404, "Sorry, this can't be found") 186 | end 187 | 188 | # Routes definitions 189 | HTTP.register!(ROUTER, "/", landingpage) # root page 190 | HTTP.register!(ROUTER, "/new/*", newgamepage) # /new/$difficulty_level -- new game 191 | HTTP.register!(ROUTER, "/*/wiki/*", articlepage) # /$session_id/wiki/$wikipedia_article_url -- article page 192 | HTTP.register!(ROUTER, "/*/back/*", backpage) # /$session_id/back/$number_of_steps -- go back the navigation history 193 | HTTP.register!(ROUTER, "/*/solution", solutionpage) # /$session_id/solution -- display the solution 194 | HTTP.register!(ROUTER, "*", notfoundpage) # everything else -- not found 195 | 196 | # Start server 197 | HTTP.serve(SERVER, HOST, PORT) 198 | 199 | end 200 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/Wikipedia.jl: -------------------------------------------------------------------------------- 1 | module Wikipedia 2 | 3 | using HTTP, Gumbo, Cascadia 4 | import Cascadia: matchFirst 5 | 6 | include("Articles.jl") 7 | using .Articles 8 | 9 | const PROTOCOL = "https://" 10 | const DOMAIN_NAME = "en.m.wikipedia.org" 11 | const RANDOM_PAGE_URL = PROTOCOL * DOMAIN_NAME * "/wiki/Special:Random" 12 | 13 | export fetchrandom, fetchpage, articleinfo, persistedarticle 14 | 15 | # function fetchpage(url) 16 | # url = startswith(url, "/") ? buildurl(url) : url 17 | # 18 | # response = HTTP.get(url) 19 | # 20 | # if response.status == 200 && length(response.body) > 0 21 | # String(response.body) 22 | # else 23 | # "" 24 | # end 25 | # end 26 | 27 | function fetchpage(url) 28 | url = startswith(url, "/") ? buildurl(url) : url 29 | response = HTTP.get(url) 30 | content = if response.status == 200 && length(response.body) > 0 31 | String(response.body) 32 | else 33 | "" 34 | end 35 | relative_url = collect(eachmatch(r"/wiki/(.*)$", (response.request.parent == nothing ? url : Dict(response.request.parent.headers)["Location"])))[1].match 36 | 37 | content, relative_url 38 | end 39 | 40 | 41 | function extractlinks(elem) 42 | map(eachmatch(Selector("a[href^='/wiki/']:not(a[href*=':'])"), elem)) do e 43 | e.attributes["href"] 44 | end |> unique 45 | end 46 | 47 | function extracttitle(elem) 48 | matchFirst(Selector("#section_0"), elem) |> nodeText 49 | end 50 | 51 | function extractimage(elem) 52 | e = matchFirst(Selector(".content a.image img"), elem) 53 | isa(e, Nothing) ? "" : e.attributes["src"] 54 | end 55 | 56 | function extractcontent(elem) 57 | matchFirst(Selector("#bodyContent"), elem) |> string 58 | end 59 | 60 | function fetchrandom() 61 | fetchpage(RANDOM_PAGE_URL) 62 | end 63 | 64 | function articledom(content) 65 | if ! isempty(content) 66 | return Gumbo.parsehtml(content) 67 | end 68 | 69 | error("Article content can not be parsed into DOM") 70 | end 71 | 72 | # function articleinfo(content) 73 | # dom = articledom(content) 74 | # 75 | # Dict( :content => content, 76 | # :links => extractlinks(dom.root), 77 | # :title => extracttitle(dom.root), 78 | # :image => extractimage(dom.root) 79 | # ) 80 | # end 81 | 82 | # function articleinfo(content) 83 | # dom = articledom(content) 84 | # Article(content, 85 | # extractlinks(dom.root), 86 | # extracttitle(dom.root), 87 | # extractimage(dom.root)) 88 | # end 89 | 90 | # function articleinfo(content) 91 | # dom = articledom(content) 92 | # (content, extractlinks(dom.root), extracttitle(dom.root), extractimage(dom.root)) 93 | # end 94 | 95 | function articleinfo(content) 96 | dom = articledom(content) 97 | (extractcontent(dom.root), extractlinks(dom.root), extracttitle(dom.root), extractimage(dom.root)) 98 | end 99 | 100 | function persistedarticle(article_content, url) 101 | article = Article(articleinfo(article_content)..., url) 102 | save(article) 103 | 104 | article 105 | end 106 | 107 | function buildurl(article_url) 108 | PROTOCOL * DOMAIN_NAME * article_url 109 | end 110 | 111 | end 112 | -------------------------------------------------------------------------------- /Chapter14/sixdegrees/six_degrees.jl: -------------------------------------------------------------------------------- 1 | using Pkg 2 | pkg"activate ." 3 | 4 | include("Database.jl") 5 | include("Wikipedia.jl") 6 | include("Gameplay.jl") 7 | include("GameSession.jl") 8 | include("WebApp.jl") 9 | 10 | using .Wikipedia, .Gameplay, .GameSession, .WebApp 11 | -------------------------------------------------------------------------------- /Chapter15/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" 3 | DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" 4 | DelimitedFiles = "8bb1440f-4735-579b-a4ab-409b98df4dab" 5 | Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" 6 | IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 7 | Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" 8 | Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" 9 | StatPlots = "60ddc479-9b66-56df-82fc-76a74619b69c" 10 | Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 11 | -------------------------------------------------------------------------------- /Chapter15/item_based_recommendations.jl: -------------------------------------------------------------------------------- 1 | using CSV, DataFrames, DelimitedFiles, Statistics 2 | 3 | const minimum_similarity = 0.8 4 | 5 | function setup_data() 6 | movies = readdlm("top_10_movies_user_rankings.tsv", '\t') 7 | movies = permutedims(movies, (2,1)) 8 | movies = convert(DataFrame, movies) 9 | 10 | names = convert(Array, movies[1, :])[1,:] 11 | 12 | names!(movies, [Symbol(name) for name in names]) 13 | deleterows!(movies, 1) 14 | rename!(movies, [Symbol("Movie title") => :User]) 15 | end 16 | 17 | function movie_similarity(target_movie) 18 | similarity = Dict{Symbol,Float64}() 19 | 20 | for movie in names(movies[:, 2:end]) 21 | movie == target_movie && continue 22 | ratings = movies[:, [movie, target_movie]] 23 | 24 | common_users = ratings[(ratings[movie] .>= 0) .& (ratings[target_movie] .> 0), :] 25 | 26 | correlation = try 27 | cor(common_users[movie], common_users[target_movie]) 28 | catch 29 | 0.0 30 | end 31 | 32 | similarity[movie] = correlation 33 | end 34 | 35 | # println("The movie $target_movie is similar to $similarity") 36 | similarity 37 | end 38 | 39 | function recommendations(target_movie) 40 | recommended = Dict{String,Vector{Tuple{String,Float64}}}() 41 | 42 | # @show target_movie 43 | # @show movie_similarity(target_movie) 44 | 45 | for (movie, similarity) in movie_similarity(target_movie) 46 | movie == target_movie && continue 47 | similarity > minimum_similarity || continue 48 | 49 | # println("Checking to which users we can recommend $movie") 50 | 51 | recommended["$movie"] = Vector{Tuple{String,Float64}}() 52 | 53 | for user_row in eachrow(movies) 54 | if user_row[target_movie] >= 5 55 | # println("$(user_row[:User]) has watched $target_movie so we can recommend similar movies") 56 | 57 | if user_row[movie] == 0 58 | # println("$(user_row[:User]) has not watched $movie so we can recommend it") 59 | # println("Recommending $(user_row[:User]) the movie $movie") 60 | 61 | push!(recommended["$movie"], (user_row[:User], user_row[target_movie] * similarity)) 62 | end 63 | end 64 | end 65 | end 66 | 67 | recommended 68 | end 69 | 70 | const movies = setup_data() 71 | println("Recommendations for users that watched Finding Dory (2016): $(recommendations(Symbol("Finding Dory (2016)")))") -------------------------------------------------------------------------------- /Chapter15/top_10_movies.tsv: -------------------------------------------------------------------------------- 1 | Movie title Action Animation Comedy Drama Kids Mistery Musical SF 2 | Moonlight (2016) 0 0 0 1 0 0 0 0 3 | Zootopia (2016) 1 1 1 0 0 0 0 0 4 | Arrival (2016) 0 0 0 1 0 1 0 1 5 | Hell or High Water (2016) 0 0 0 1 0 1 0 0 6 | La La Land (2016) 0 0 1 1 0 0 1 0 7 | The Jungle Book (2016) 1 0 0 0 1 0 0 0 8 | Manchester by the Sea (2016) 0 0 0 1 0 0 0 0 9 | Finding Dory (2016) 0 1 0 0 0 0 0 0 10 | Captain America: Civil War (2016) 1 0 0 0 0 0 0 1 11 | Moana (2016) 1 1 0 0 0 0 0 0 -------------------------------------------------------------------------------- /Chapter15/top_10_movies_user_rankings.csv: -------------------------------------------------------------------------------- 1 | Movie title;Acton;Annie;Comey;Dean;Kit;Missie;Musk;Sam 2 | Moonlight (2016);;3;;10;;9;2; 3 | Zootopia (2016);9;10;7;;10;;5; 4 | Arrival (2016);5;;6;10;;9;;10 5 | Hell or High Water (2016);3;;3;10;;8;; 6 | La La Land (2016);6;;8;9;;;10; 7 | The Jungle Book (2016);8;7;;2;9;;6; 8 | Manchester by the Sea (2016);;;2;8;;;; 9 | Finding Dory (2016);7;8;5;4;10;;; 10 | Captain America: Civil War (2016);10;;5;6;;;;9 11 | Moana (2016);8;9;;;10;;7; -------------------------------------------------------------------------------- /Chapter15/top_10_movies_user_rankings.tsv: -------------------------------------------------------------------------------- 1 | Movie title Acton Annie Comey Dean Kit Missie Musk Sam 2 | Moonlight (2016) 0 3 0 10 0 9 2 0 3 | Zootopia (2016) 9 10 7 0 10 0 5 0 4 | Arrival (2016) 5 0 6 10 0 9 0 10 5 | Hell or High Water (2016) 3 0 3 10 0 8 0 0 6 | La La Land (2016) 6 0 8 9 0 0 10 0 7 | The Jungle Book (2016) 8 7 0 2 9 0 6 0 8 | Manchester by the Sea (2016) 0 0 2 8 0 0 0 0 9 | Finding Dory (2016) 7 8 5 4 10 0 0 0 10 | Captain America: Civil War (2016) 10 0 5 6 0 0 0 9 11 | Moana (2016) 8 9 0 0 10 0 7 0 12 | -------------------------------------------------------------------------------- /Chapter15/user_based_movie_recommendations.jl: -------------------------------------------------------------------------------- 1 | using CSV, DataFrames, Statistics 2 | 3 | const minimum_similarity = 0.8 4 | const movies = CSV.read("top_10_movies_user_rankings.tsv", delim = '\t') 5 | 6 | function user_similarity(target_user) 7 | similarity = Dict{Symbol,Float64}() 8 | 9 | for user in names(movies[:, 2:end]) 10 | user == target_user && continue 11 | 12 | ratings = movies[:, [user, target_user]] 13 | common_movies = ratings[(ratings[user] .> 0) .& (ratings[target_user] .> 0), :] 14 | # common_movies = ratings[(ratings[user] .> 7) .& (ratings[target_user] .> 0), :] 15 | 16 | correlation = try 17 | cor(common_movies[user], common_movies[target_user]) 18 | catch 19 | 0.0 20 | end 21 | 22 | similarity[user] = correlation 23 | end 24 | 25 | similarity 26 | end 27 | 28 | function recommendations(target_user) 29 | recommended = Dict{String,Float64}() 30 | 31 | for (user,similarity) in user_similarity(target_user) 32 | similarity > minimum_similarity || continue 33 | 34 | ratings = movies[:, [Symbol("Movie title"), user, target_user]] 35 | recommended_movies = ratings[(ratings[user] .>= 7) .& (ratings[target_user] .== 0), :] 36 | 37 | for movie in eachrow(recommended_movies) 38 | recommended[movie[Symbol("Movie title")]] = movie[user] * similarity 39 | end 40 | end 41 | 42 | recommended 43 | end 44 | 45 | for user in names(movies)[2:end] 46 | println("Recommendations for $user: $(recommendations(user))") 47 | end -------------------------------------------------------------------------------- /Chapter16/Chapter 16.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "using Pkg\n", 10 | "pkg\"activate .\"" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "# Run this cell in order to download all the package dependencies with the exact versions used in the book\n", 20 | "# This is necessary if (some of) the packages have been updated and have introduced breaking changes\n", 21 | "pkg\"instantiate\"" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "using CSV" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "users = CSV.read(\"data/BX-Users.csv\", header = 1, delim = ';', missingstring = \"NULL\", escapechar = '\\\\')" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "books = CSV.read(\"data/BX-Books.csv\", header = 1, delim = ';', missingstring = \"NULL\", escapechar = '\\\\')" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "books_ratings = CSV.read(\"data/BX-Book-Ratings.csv\", header = 1, delim = ';', missingstring = \"NULL\", escapechar = '\\\\')" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "using DataFrames" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "describe(users, stats = [:min, :max, :nmissing, :nunique, :eltype])" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "using Gadfly" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "plot(users, x = :Age, Geom.histogram(bincount = 15))" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "users = users[users[:Age] .< 100, :]" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "using Statistics" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "mean(skipmissing(users[:Age]))" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "users[:Age] = coalesce.(users[:Age], mean(skipmissing(users[:Age])))" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "users = users[users[:Age] .< 100, :]" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "head(users)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [ 156 | "describe(books, stats = [:nmissing, :nunique, :eltype])" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "maximum(skipmissing(books[Symbol(\"Year-Of-Publication\")]))" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": null, 171 | "metadata": {}, 172 | "outputs": [], 173 | "source": [ 174 | "minimum(skipmissing(books[Symbol(\"Year-Of-Publication\")]))" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": null, 180 | "metadata": {}, 181 | "outputs": [], 182 | "source": [ 183 | "plot(books, x = Symbol(\"Year-Of-Publication\"), Geom.histogram)" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": null, 189 | "metadata": {}, 190 | "outputs": [], 191 | "source": [ 192 | "unique(books[Symbol(\"Year-Of-Publication\")]) |> sort" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [ 201 | "books = books[books[Symbol(\"Year-Of-Publication\")] .>= 1970, :]" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "books = books[books[Symbol(\"Year-Of-Publication\")] .<= 2004, :]" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "plot(books, x = Symbol(\"Year-Of-Publication\"), Geom.histogram)" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "metadata": {}, 226 | "outputs": [], 227 | "source": [ 228 | "describe(books_ratings)" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": null, 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "plot(books_ratings, x = Symbol(\"Book-Rating\"), Geom.histogram)" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "metadata": {}, 244 | "outputs": [], 245 | "source": [ 246 | "books_ratings = books_ratings[books_ratings[Symbol(\"Book-Rating\")] .> 0, :]" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": null, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "plot(books_ratings, x = Symbol(\"Book-Rating\"), Geom.histogram)" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "metadata": {}, 262 | "outputs": [], 263 | "source": [ 264 | "books_ratings_books = join(books_ratings, books, on = :ISBN, kind = :inner)" 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": null, 270 | "metadata": {}, 271 | "outputs": [], 272 | "source": [ 273 | "books_ratings_books_users = join(books_ratings_books, users, on = Symbol(\"User-ID\"), kind = :inner)" 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "execution_count": null, 279 | "metadata": {}, 280 | "outputs": [], 281 | "source": [ 282 | "top_ratings = books_ratings_books_users[books_ratings_books_users[Symbol(\"Book-Rating\")] .>= 8, :]" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": null, 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "for n in names(top_ratings)\n", 292 | " rename!(top_ratings, n => Symbol(replace(string(n), \"-\"=>\"\")))\n", 293 | "end" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "names(top_ratings)" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "metadata": {}, 309 | "outputs": [], 310 | "source": [ 311 | "ratings_count = by(top_ratings, :UserID, df -> size(df[:UserID])[1])" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": null, 317 | "metadata": {}, 318 | "outputs": [], 319 | "source": [ 320 | "describe(ratings_count)" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": null, 326 | "metadata": {}, 327 | "outputs": [], 328 | "source": [ 329 | "ratings_count = ratings_count[ratings_count[:x1] .>= 5, :]" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "metadata": {}, 336 | "outputs": [], 337 | "source": [ 338 | "plot(ratings_count, x = :x1, Geom.histogram(maxbincount = 6))" 339 | ] 340 | }, 341 | { 342 | "cell_type": "code", 343 | "execution_count": null, 344 | "metadata": {}, 345 | "outputs": [], 346 | "source": [ 347 | "ratings_count[ratings_count[:x1] .> 1000, :]" 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": null, 353 | "metadata": {}, 354 | "outputs": [], 355 | "source": [ 356 | "ratings_count = ratings_count[ratings_count[:x1] .<= 1000, :]" 357 | ] 358 | }, 359 | { 360 | "cell_type": "code", 361 | "execution_count": null, 362 | "metadata": {}, 363 | "outputs": [], 364 | "source": [ 365 | "top_ratings = join(top_ratings, ratings_count, on = :UserID, kind = :inner)" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": null, 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "CSV.write(\"top_ratings.csv\", top_ratings)" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "metadata": {}, 381 | "outputs": [], 382 | "source": [] 383 | } 384 | ], 385 | "metadata": { 386 | "kernelspec": { 387 | "display_name": "Julia 1.0.1", 388 | "language": "julia", 389 | "name": "julia-1.0" 390 | }, 391 | "language_info": { 392 | "file_extension": ".jl", 393 | "mimetype": "application/julia", 394 | "name": "julia", 395 | "version": "1.0.2" 396 | } 397 | }, 398 | "nbformat": 4, 399 | "nbformat_minor": 2 400 | } 401 | -------------------------------------------------------------------------------- /Chapter16/Project.toml: -------------------------------------------------------------------------------- 1 | [deps] 2 | CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" 3 | DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" 4 | Gadfly = "c91e804a-d5a3-530f-b6f0-dfbca275c004" 5 | IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" 6 | Recommendation = "d27d45ae-66f1-5d53-80d2-11744f5c9556" 7 | Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" 8 | -------------------------------------------------------------------------------- /Chapter16/data/BX-Book-Ratings.csv.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter16/data/BX-Book-Ratings.csv.zip -------------------------------------------------------------------------------- /Chapter16/data/BX-Books.csv.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter16/data/BX-Books.csv.zip -------------------------------------------------------------------------------- /Chapter16/data/BX-Users.csv.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter16/data/BX-Users.csv.zip -------------------------------------------------------------------------------- /Chapter16/data/large/top_ratings.csv.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter16/data/large/top_ratings.csv.zip -------------------------------------------------------------------------------- /Chapter16/data/top_ratings.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Chapter16/data/top_ratings.csv -------------------------------------------------------------------------------- /Graphics Bundle.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Graphics Bundle.pdf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Training By 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![GitHub issues](https://img.shields.io/github/issues/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide.svg)](https://github.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/issues) 2 | [![GitHub forks](https://img.shields.io/github/forks/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide.svg)](https://github.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/network) 3 | [![GitHub stars](https://img.shields.io/github/stars/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide.svg)](https://github.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/stargazers) 4 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/pulls) 5 | 6 | 7 | 8 | # Julia 1.0 Programming Complete Reference Guide 9 | Julia offers the high productivity and ease of use of Python and R with the lightning-fast speed of C++. There’s never been a better time to learn this language, thanks to its large-scale adoption across a wide range of domains, including fintech, biotech and artificial intelligence (AI). 10 | 11 | You will begin by learning how to set up a running Julia platform, before exploring its various built-in types. This Learning Path walks you through two important collection types: arrays and matrices. You’ll be taken through how type conversions and promotions work, and in further chapters you'll study how Julia interacts with operating systems and other languages. You’ll also learn about the use of macros, what makes Julia suitable for numerical and scientific computing, and how to run external programs. 12 | 13 | Once you have grasped the basics, this Learning Path goes on how to analyze the Iris dataset using DataFrames. While building a web scraper and a web app, you’ll explore the use of functions, methods, and multiple dispatches. In the final chapters, you'll delve into machine learning, where you'll build a book recommender system. 14 | 15 | By the end of this Learning Path, you’ll be well versed with Julia and have the skills you need to leverage its high speed and efficiency for your applications. 16 | 17 | This Learning Path includes content from the following Packt products: 18 | * Julia 1.0 Programming - Second Edition by Ivo Balbaert 19 | * Julia Programming Projects by Adrian Salceanu 20 | 21 | 22 | ## What you will learn 23 | * Create your own types to extend the built-in type system 24 | * Visualize your data in Julia with plotting packages 25 | * Explore the use of built-in macros for testing and debugging 26 | * Integrate Julia with other languages such as C, Python, and MATLAB 27 | * Analyze and manipulate datasets using Julia and DataFrames 28 | * Develop and run a web app using Julia and the HTTP package 29 | * Build a recommendation system using supervised machine learning 30 | 31 | 32 | ### Hardware requirements 33 | For an optimal student experience, we recommend the following hardware configuration: 34 | * **Processor**: Intel Core i5 or equivalent 35 | * **Memory**: 8GB RAM 36 | * **Graphics**: NVIDIA GeForce 7800 GS or equivalent 37 | * **Hard Disk**: 40GB or more 38 | 39 | 40 | ### Software requirements 41 | You’ll also need the following software installed in advance: 42 | * **Supported Operating systems**: Windows (7 or higher), macOS (10.8 or higher), FreeBSD (11.0 or higher), Linux (2.6.18 or higher) 43 | -------------------------------------------------------------------------------- /Software Hardware List.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TrainingByPackt/Julia-1-Programming-Complete-Reference-Guide/bc7d9d4bc090daa9a6e0757aa62f73fe394f3905/Software Hardware List.pdf --------------------------------------------------------------------------------