How to make user defined function descriptions ("docstrings") available to julia REPL?

How can user defined functions (say f) have meaningful printouts when inspected via the REPL using ?for help(f) For example imagine I write the following funciton function f(x::Float64, y::Float64) return 2x - y^2 end If I load this into a julia session and try help(f) I get the following: julia> help(f) f (generic function with 1 method) What if instead I wanted to see something like julia> help(f) f Compute 2 times x minus y squared where the description "Compute 2 time

How do I resolve LoadError while trying to make a png on Windows using Julia Studio and Gadfly?

I'm currently working through this tutorial and I'm having trouble getting the png image to display. This is my program. using DataFrames using Gadfly train_df = readtable("winequality-red.csv", separator=';') _, count = hist(train_df["quality"]) class = sort(unique(train_df["quality"])) value_counts = DataFrame(count=count, class=class) #value_counts p = plot(value_counts, x="class", y="count",, Guide.title("Class distributions (\"quality\")")) draw(PNG(14cm, 10cm), p) the erro

Type-I Discrete Cosine Transform not defined/found in Julia 0.3.0?

I recently tried to compute the Type-I DCT of an array in Julia using the r2r standard-library function, and got errors. I tried to execute the following minimal example: dat = [5; 4; 3; 1]; r2r(dat, "FFTW.REDFT00") I encountered this error message: ERROR: r2r not defined I can't figure out what this means. The r2r function is supposedly built-in to Julia 0.3.0, so how is it possible that it is giving a syntax error here? For comparison, the dct (Type-II discrete cosine transform) wo

Julia: BigFloat Normal distribution

In Julia has anyone implemented the normal distributions pdf or cdf to support arbitrary precision BigFloats. For example this code returns 0.0, when in fact the values should be slightly different. x = parse(BigFloat, "2.1") x_small = float64(x) pdf(Normal(), x) - pdf(Normal(), x_small)

Julia How to display a type alias instead of a parametric type in error messages

I build a parametric type in julia: type MyType{T} x::T end and for simplicity, I build a type alias for Float64: typealias MT MyType{Float64} I now deliberately cause an error involving MT. For example: y1 = MyType(1.0) y2 = MyType(2.0) y1 + y2 will throw an error because + is not defined for MyType. The error message says: `+` has no method matching +(::MyType{Float64}, ::MyType{Float64}) I would like it to say: `+` has no method matching +(::MT, ::MT) Why? Because real-worl

Unable to install Julia package

I'm trying to instal the Escher web based UI package for Julia. Following the instructions on the Escher page, I've started the Julia REPL and entered: julia> Pkg.add("Escher") …but I get the following error: ERROR: unknown package Escher in wait at task.jl:51 in sync_end at /Applications/ in add at pkg/entry.jl:319 in add at pkg/entry.jl:71 in anonymous at pkg/dir.jl:28 in cd at /Applications/

Julia installation on Mac Pro fails

I am using Mac Pro with El Capitan. I tried installing Julia through homebrew but it fails with the following stack trace ==> make FC=/usr/local/bin/gfortran Last 15 lines from /Users/vishalsharma/Library/Logs/Homebrew/openblas-julia/01.make: printf("#define DLOCAL_BUFFER_SIZE\t%ld\n", (DGEMM_DEFAULT_Q * DGEMM_DEFAULT_UNROLL_N * 2 * 1 * sizeof(double))); ^ getarch_2nd.c:69:50: error: use of undeclared identifier 'CGEMM_DEFAULT_

Resolving Julia 0.4 deprecation of Uint64

I want to create a 2D array of Uint64s in Julia 0.4. This worked in 0.3: s = 128 a = zeros(Uint64, s, s)::Array{Uint64,2} It continues to compile but gives me the notice WARNING: Base.Uint64 is deprecated, use UInt64 instead. I don't know what this message means. I've tried googling the error message but haven't found anything helpful. What is an equivalent line of code that will not produce any warnings?

Efficient way to sum an array of integers in Julia

I have an 2D array which I want to modify so as to sum a given element in a row with all the elements before it, so for example, if I have an array: [1 2; 3 6; 4 7; 4 8] I want to be able to transform it to [1 2; 4 8; 8 15; 12 23] I can do so using the following snippet in julia: for i in 1:10, for k in 2:size(d,1), d([k,i] += d[k-1,i)]; end end But I assume there must be a more efficient way to do this?

Is there any way to build package dependency tree in julia-lang?

Using npm list will show a tree of installed packages, versions and relations: Although Julia package management is differ (e.g normally no duplicate copy of a package exists), But is there any way to: Know why one package have been installed? or build a package dependency tree.

Julia - Array of UTF8 behavior

I encountered a problem which I've solved, but why the solution works doesnt make sense to me I had a function similar to this one function testB(a::Array{AbstractString}) println(a) end running it like so gave me testB(convert(Array{UTF8String},["a","b"])) ERROR: MethodError: `testB` has no method matching testB(::Array{UTF8String,1}) Note that Im not manually converting to UTF8 in reality, its for demonstration, in reality I have an AbstractString array, but when I fetch element

Is it possible to call an overloaded function from overwriting function in Julia?

The problem is the following: I have an abstract type MyAbstract and derived composite types MyType1 and MyType2: abstract MyAbstract type MyType1 <: MyAbstract somestuff end type MyType2 <: MyAbstract someotherstuff end I want to specify some general behaviour for objects of type MyAbstract, so I have a function function dosth(x::MyAbstract) println(1) # instead of something useful end This general behaviour suffices for MyType1 but when dosth is called with an argume

Round Julia's Millisecond type to nearest Second or Minute

I would like to calculate the difference between a pair of DateTimes that is rounded to the nearest second or minute. initial = now() println(typeof(initial)) sleep(12) final = now() difference = final - initial println(typeof(difference)) gives DateTime Base.Dates.Millisecond The latter type is pretty difficult to use since almost all convenience types are for DateTimes. What is the recommend way to convert difference to seconds or fractional minutes? Is this possible without dropping dow

Julia How to define a parametric type over parametric type?

Suppose I have types immutable X{T} a::T end immutable Y{T} a::T end I would like to do something like type A{T, U} x::U{T} y::T end So that the instances could be A(X(a), a) or A(Y(a), a) It doesn't work as LoadError: TypeError: Type{...} expression: expected Type{T}, got TypeVar What's the correct way for it?

Running an external program with sequential inputs from Julia 0.5.1

I want to run an external program, lets call it program, sequentially piping inputs to its standard input. Lets call the inputs input_1, input_2 etc. I then want the standard output of the program to be piped back into memory, for example a Julia data structure, or if this is not possible, written to a text file. I can run the external program with: run(`program input_1 input_2`) which results in the standard output of the program being displayed to the shell. I however need to feed the in

Julia Cox Proportional Hazard in JuMP.jl

I am trying JuMP.jl in Julia for the first time and can't seem to get around an error. Here is my set up. using DataFrames, DataFramesMeta, JuMP, Ipopt #time to event times = [143,164,188,189,190,192,206,209,213,216,220,227,230,234,246,265,304,216,244, 142,156,163,198,205,232,232,233,233,233,233,239,240,261,280,280,296,296,232,204,344]; #make censored data is_censored = zeros(Int32, 40); is_censored[18]=1 is_censored[19]=1 is_censored[39]=1 is_censored[40]=1 #treatment vs control x1=ones(Int

Julia A function or a macro for retrieving attributes of annotated strings

I have strings with annotated attributes. You can think of them as XML-document strings, but with custom syntax of annotation. Attributes in a string are encoded as follows: #<atr_name>=<num_of_chars>:<atr_value>\n where <atr_name> is a name of the attribute <atr_value> is a value of the attribute <num_of_chars> is a character length of the <atr_value> That is attribute name is prefixed with # and postfixed with =, then followed by number that ind

Julia How to animate changing histogram in Plots.jl?

I'm working from the following example and failing miserably # initialize the attractor n = 1500 dt = 0.02 σ, ρ, β = 10., 28., 8/3 x, y, z = 1., 1., 1. # initialize a 3D plot with 1 empty series plt = path3d(1, xlim=(-25,25), ylim=(-25,25), zlim=(0,50), xlab = "x", ylab = "y", zlab = "z", title = "Lorenz Attractor", marker = 1) # build an animated gif, saving every 10th frame @gif for i=1:n dx = σ*(y - x) ; x += dt * dx dy = x*(ρ - z) - y ; y += dt

Julia Plotly Plots

I'm trying to do some really basic scatterplots. I'm following instructions from here: using Plotly trace1 = [ "x" => [1, 2, 3], "y" => [4, 5, 6], "type" => "scatter" ] trace2 = [ "x" => [20, 30, 40], "y" => [50, 60, 70], "xaxis" => "x2", "yaxis" => "y2", "type" => "scatter" ] data = [trace1, trace2] layout = [ "xaxis" => ["domain" => [0, 0.45]], "yaxis2" => ["anchor" => "x2"], "xaxis2" => ["domain" =

'Big' fractions in Julia

I've run across a little problem when trying to solve a Project Euler problem in Julia. I've basically written a recursive function which produces fractions with increasingly large numerators and denominators. I don't want to post the code for obvious reasons, but the last few fractions are as follows: 1180872205318713601//835002744095575440 2850877693509864481//2015874949414289041 6882627592338442563//4866752642924153522 At that point I get an OverflowError(), presumably because the numerato

Julia Broadcast version of in() function or in operator?

Consider an array, say 0 to 4. I want to test if each element is in a list and return an array of booleans. A call to in returns a single boolean, because this left-hand side array is not an element of the right-hand side array: > a = 0:4; > a in [1, 2] false Does Julia have a broadcast version of the in() function or the in operator that returns an array like this call to map and a lambda function? > map(x -> x in [1,2], a) 5-element Array{Bool,1}: false true true false f

Julia Using/Distributing pre-compiled files

I already asked this in the Julia community discourse but asking it here as expect to find different audience. I created a simple function as below: #MyFunction.jl __precompile__() function MyFunction(x) y = x * 5 y * 5 end And found the pre-compiled files saved as: /Users/hasan/.julia/compiled/v1.0/MyFunction.jl Can I use/distribute this pre-compiled file with my main function without using the original file source code itself?

Julia How do you pass all keyword-arguments to an inner function?

kwargs... allows you to accept arbitrary keyword arguments, but you can access them in the form of a Dictionary. How do you pass all the provided keyword arguments to an inner function? For example: function bar(;kwargs...) print(kwargs) end function foo(;kwargs...) bar(<MODIFY ME>) end How do I modify the call to bar such that it receives all the keyword arguments passed into foo?

Getting started with Julia Multiple Dispatch

Here's what looks to me the simplest imaginable example of multiple dispatch in Julia - it's the entire (8 line) contents of a file called adhoc.jl. f = function(x::String) println("Called first version of f") end f = function(x::Float64) println("Called second version of f") end f("x") f(1.0) and yet when I run that (via include("Adhoc.jl")) julia complains: ERROR: LoadError: MethodError: no method matching (::getfield(Main, Symbol("##17#18")))(::String) With screenshot here If

Julia Unpack dict entries inside a function

I want to unpack parameters that are stored in a dictionary. They should be available inside the local scope of a function afterwards. The name should be the same as the key which is a symbol. macro unpack_dict() code = :() for (k,v) in dict ex = :($k = $v) code = quote $code $ex end end return esc(code) end function assign_parameters(dict::Dict{Symbol, T}) where T<:Any @unpack_dict return a + b - c end dict = Dict(:a

Julia How can I write higher-order function to add methods to a given function?

Let's suppose I want to write a function that accepts any associative operator ⊕ and adds methods to it such that I can replace any value with a function. The semantics of these additional methods are as follows: If the operator is then applied to any two functions f and g, the result should be a function that first applies f and g (independently) to its arguments and then applies ⊕ to the results. If one argument is a function f but the other is any non-function value x, the result is a func

Issue with using pyimport in Julia 1.1.0

I made a module with an if condition on the number of cores. module mymodule import Pkg import PyCall using Distributed if nworkers() > 1 @everywhere using Pkg @everywhere Pkg.activate(".") @everywhere Pkg.instantiate() @everywhere using PyCall @everywhere @pyimport scipy.signal as ss function parallel() .... end else using Pkg Pkg.activate(".") Pkg.instantiate() using PyCall @pyimport scipy.signal as ss function serial()

Julia Updating a particular column of an array

The following code does what I need it to do, but since I am bound to have the same task in future codes, I would like to know what the best way to achieve the outcome is: p_last = fill(NaN, (n,periods-1)) p_first = ones(n) * 0.5 p = hcat(p_first,p_last)

How should we define mutli-dimensional structs inside julia?

I'm trying to define matrix-like structures. How should I define them? For example defining a matrix like this: struct Mat r11::Float64 r12::Float64 r21::Float64 r22::Float64 end But when the matrix is big, it can't be written like that. How should I define multi-dimensional matrices to be memory efficient and fast when added, subtracted, etc.

Saving an OrderedDict to Julia Data Format

I wish to use the JLD package to write an OrderedDict to file in such a way that I can subsequently read it back unchanged. Here was my first effort: using JLD, HDF5, DataStructures function testjld() res = OrderedDict("A" => 1, "B" => 2) filename = "c:/temp/test.jld" save(File(format"JLD", filename), "res", res) res2 = load(filename)["res"] #Check if round-tripping works res == res2 end But the "round-tripping" doesn't work - the function returns false. It a

Julia Given that Zygote does not support mutation, how does Recur gets away with it?

From Flux.jl's source code here: mutable struct Recur{T} cell::T init state end Recur(m, h = hidden(m)) = Recur(m, h, h) function (m::Recur)(xs...) h, y = m.cell(m.state, xs...) m.state = h return y end it looks like Recur struct, which is used for every recurrent layer, does mutation of its state field in the forward pass. But Zygote.jl does not support mutation, so why is this not throwing something like ERROR: Mutation is not supported! as it usually does in such cases? For

Julia using LsqFit for Lorentzian curve fitting

The following code in Julia plots a Lorenztian curve and then uses the curve_fit function to determine the parameters. using LsqFit model(x,p)=p[1] ./(p[1]^2 .+(x .-p[2]).^2) #Test values p0=[10,50] tdata=range(-150,stop=150,length=300) ydata = model(tdata, p0) fit=curve_fit(model,tdata,ydata,p0) In this case the result should be exact as I use the model to calculate the y-values and then pass these exact y-values to the curve_fit function. However, Julia returns the error: InexactError:

Plotting credible intervals in Julia from Turing model

Ok so I figured out how to plot the credible intervals for a univariate linear model in Turing.jl using the following code (I'm replicating Statistical rethinking by McElreath) This particular exercise is in chapter 4. If anyone has already plotted these types of models with Turing and can give me a guide, it would be great!!! Univariate model code: using Turing using StatsPlots using Plots height = df2.height weight = df2.weight @model heightmodel(y, x) = begin

Julia: how do I configure IJulia kernel to use specific environment?

I downloaded someone else's project and the structure is as follows: project/ notebooks/ notebook_a.ipynb notebook_b.ipynb library/ Manifest.toml Project.toml src/ test/ In the notebooks I would like to import library, and install its dependencies within its own evironment. Following the sugestions here, I can do using Pkg Pkg.activate("../library/") but I wonder if I could install a kernel that has the project directory specifi

Julia LoadError: JuliaTeam.toml": No such file or directory

I just installed JuliaPro and have no previous installations of Julia on the machine. I'm new to Julia so any advice would be appreciated. I'm running MacOS 10.15.6 and am using JuliaPro_v1.5.1-1. Here is the problem: julia> using Pkg julia>"HDF5") Building CMake → `~/.julia/packages/CMake/ULbyn/deps/build.log` Building Blosc → `~/.julia/packages/Blosc/lzFr0/deps/build.log` ┌ Error: Error building `Blosc`: │ ┌ Warning: platform_key() is deprecated, use platform

Julia Passing labels to Plots.jl histogram

I am new to Julia and was wondering how to pass labels to the Histogram function in Plots.jl package. using Plots gr() histogram( data[:sentiment_labels], title = "Hstogram of sentiment labels", xlabel = "Sentiment", ylabel = "count", label = ["Negative" "Positive" "Neutral"], fillcolor = [:coral,:dodgerblue,:slategray] ) Only the first labels "Negative" appears in the plot.

How to define tuple of types in julia type declaration's

How do I declare a tuple of specific types for a julia function? This works: function f(x, y)::Int8 x+y end julia> f(2, 3) 5 This works too: function g(x, y)::Tuple x+y, x*y end julia> g(2, 3) (5, 6) But I can't figure out how to define the types in the tuple. For example, this throws an error: function h(x, y)::Tuple(::Int8, ::Int8) x+y, x*y end ERROR: syntax: invalid "::" syntax around REPL[48]:2 An this too: function k(x, y)::Tuple(Int8, Int8) x+y, x

Julia Assertion failed, process aborted

I have implemented a recursive function for array usage in julia and it worked fine. But when I am using it for a bigger array this error appears. Has it sth. to do with disk usage? I am using ubuntu 14.04 LTS. julia: alloc.c:788: jl_unbox_int64: Assertion `jl_is_bitstype((((jl_value_t*)(v))->type))' failed. signal (6): Aborted gsignal at /lib/x86_64-linux-gnu/ (unknown line) abort at /lib/x86_64-linux-gnu/ (unknown line) unknown function (ip: -1627718778) unknown f

Julia error in assigning global variables to a tuple in global m,n = size(x);

I would expect the global variables m and n get the first and second dimension size. However it seeems incorrect: julia> x=rand(3,3) 3×3 Array{Float64,2}: 0.680079 0.929336 0.267358 0.874437 0.625239 0.804478 0.92407 0.737254 0.443433 julia> m,n = size(x); julia> m,n (3,3) julia> global m,n = size(x); julia> m,n (3,(3,3)) Why is this behaviour of assigning 2 variables to a tuple different when we add the global key word?

Julia Monte-Carlo Simulation for the sum of die

I am very new to programming so I apologise in advance for my lack of knowledge. I want to find the probability of obtaining the sum k when throwing m die. I am not looking for a direct answer, I just want to ask if I am on the right track and what I can improve. I begin with a function that calculates the sum of an array of m die: function dicesum(m) j = rand((1:6), m) sum(j) end Now I am trying specific values to see if I can find a pattern (but without much luck). I have tried m = 2 (tw

In Julia is big"123" a macro, function, or something else?

As a newcomer to Julia this month, Sept. 2018, I am just getting used to the initially unfamiliar "@" symbol for macros and "!" symbol for functions with mutable inputs. Am I right to assume that these are merely stylistic symbols for humans to read, and that they do not really provide any information to the compiler? I bring this up in the context of the following code that does not seem to match the style of a macro, a function, or anything else in Julia I am aware of. I am specifically ask

Julia Substitute of "occursin" function to find a string in an Array{String,1}

What I am trying to do is i = occursin("ENTITIES\n", lines) i != 0 || error("ENTITIES section not found") The error information is ERROR: LoadError: LoadError: MethodError: no method matching occursin(::String, ::Array{String,1}) Closest candidates are: occursin(::Union{AbstractChar, AbstractString}, ::AbstractString) at strings/search.jl:452 This is a piece of julia v0.6 code. I am using v1.1 now. I am new to julia and don't know what's the proper subsititute function for this. Please h

Duplicating Excel's representation of Dates in Julia

In Julia I need to convert numbers to DateTime in the same manner as Microsoft Excel. In Excel, today's date of 23-Sep-2019 is represented by 43731 and 6pm this afternoon by 43731.75. I can ignore the fact that Excel incorrectly assumes that 1900 is a leap year since all my data is safely beyond that point. Millisecond accuracy is sufficient. The code below seems to work, but is there a better way? function exceldatetodate(exceldate::Integer) Dates.Date(1899, 12, 30) + Dates.Day(exceldate

Use GR Arrow Styles in Julia.Plots

I'd like to annotate a point in a plot I draw using julia Plots with the GR backend. I get the arrows drawn with plot([(pos1), (pos2)], line=:arrow) As expected, this draws a :simple arrow. However, I can not figure out how to get :filled or :closed arrows. I have tried several permutations: plt1 = plot([(pos1), (pos2)], line=:arrow, arrow=arrow(:closed)) plt2 = plot([(pos1), (pos2)], line=:arrow, arrow=:closed) And also directly calling the GR function plt3 = plot([(pos1), (pos2)], line

Difficulties of implementing function in Julia involving if, else and matrices

I am trying to implement this function in Julia and I am not getting it. I think it's because of broadcasting, it doesn't seem to work with arrays. When I write the relational operators with dot (like .> instead of >), the number of errors decreases, but it accuses "TypeError: non-boolean (BitVector) used in boolean context". How can I fix this? function Rulkov(N, X, Y, α) global σ, μ for n=1:1:N if (X[n, 1]<=0) X[n, 2] = α[n] / (1 - X[n, 1]) + Y[n, 1]

  1    2   3   4   5   6  ... 下一页 最后一页 共 15 页