What method am I not using right? - arrays

I'm new to Julia and currently trying to run the following code:
Using DelimitedFiles
M=readdlm(data)
ts,A=M[:,1],M[:,2:end]
(nsweeps,N)=size(A)
dx=0.01;
x=[minimum(collect(A)):dx:maximum(collect(A))];
bx=[x-dx/2,x[end]+dx/2];
But, when I try to run the last line of code, it gives me the following error:
MethodError: no method
matching(::Array{StepRangeLen{Float64,Base.TwicePrecision
{Float64},Base.TwicePrecision{Float64}},1}, ::Float64)
Closest candidates are:
-(!Matched::BigFloat, ::Union{Float16, Float32, Float64}) at
mpfr.jl:437
-(!Matched::Complex{Bool}, ::Real) at complex.jl:307
-(!Matched::Missing, ::Number) at missing.jl:115
Can you please help me? Also, the data I'm using it's
30×6 Array{Float64,2}
UPDATE here's the whole function I'm trying to run is the following:
function mymain(filename,nsamples)
start_time=time()
M=readdlm(filename)
ts,A=M[:,1],M[:,2:end]
(nsweeps,N)=size(A)
dx=0.01;
x=[minimum(collect(A)):dx:maximum(collect(A))];
bx=[x-dx/2,x[end]+dx/2];
(bx,hA)=hist(A[:],bx);
f1=figure()
subplot(2,1,1); plot(ts,A,"-o"); xlabel("Time [ms]"); ylabel("Amps
[mV]");
subplot(2,1,2); plot(x,hA,"-"); xlabel("Amps [mV]");
ylabel("Density");draw()
nparams=8
Sx=Array(ASCIIString,1,nparams)
Rx=zeros(2,nparams)
nx=zeros(Int,1,nparams)
Sx[1,1]="p"; Rx[1:2,1]=[0.02,0.98]; nx[1]=49
Sx[1,2]="n"; Rx[1:2,2]=[1,20]; nx[2]=20
Sx[1,3]="tD"; Rx[1:2,3]=[50,200]; nx[3]=46
Sx[1,4]="a"; Rx[1:2,4]=[0.05,0.5]; nx[4]=46
Sx[1,5]="siga"; Rx[1:2,5]=[0.01,0.2]; nx[5]=39
Sx[1,6]="sigb"; Rx[1:2,6]=[0.01,0.1]; nx[6]=19
Sx[1,7]="tauf"; Rx[1:2,7]=[50,200]; nx[7]=46
Sx[1,8]="u1"; Rx[1:2,8]=Rx[1:2,1]; nx[8]=nx[1]
x=zeros(maximum(nx),nparams)
p=zeros(maximum(nx),nparams)
dx=zeros(1,nparams)
for j=1:nparams
x[1:nx[j],j]=linspace(Rx[1,j],Rx[2,j],nx[j])'
dx[j]=x[2,j]-x[1,j]
end
S=zeros(Int,nsamples,nparams)
sold=zeros(Int,1,nparams)
for j=1:nparams
sold[j]=rand(1:nx[j])
end
while x[sold[4],4]<=x[sold[5],5]
sold[4]=rand(1:nx[4])
sold[5]=rand(1:nx[5])
end
while x[sold[8],8]<=x[sold[1],1]
sold[1]=rand(1:nx[1])
sold[8]=rand(1:nx[8])
end
xold=zeros(1,nparams)
xnew=zeros(1,nparams)
for j=1:nparams
xold[j]=x[sold[j],j]
end
llold=myloglikelihood(xold,ts,A)
for k=1:nsamples
snew=sold+rand(-1:1,1,nparams)
if all(ones(1,nparams).<=snew.<=nx)
allowed2=x[snew[4],4]>x[snew[5],5]
allowed3=x[snew[8],8]>x[snew[1],1]
if allowed2&allowed3
for j=1:nparams
xnew[j]=x[snew[j],j]
end
llnew=myloglikelihood(xnew,ts,A)
if rand()<exp(llnew-llold)
sold,llold=snew,llnew
end
end
end
S[k,:]=sold
end
for k=1:nsamples
for j=1:nparams
p[S[k,j],j]+=1/(nsamples*dx[j])
end
end
f2=figure()
for j=1:nparams
subplot(2,4,j)
plot(x[1:nx[j],j],p[1:nx[j],j]);
xlabel(Sx[j])
end
diff_time=time()-start_time;
println("Total runtime
",round(diff_time,3),"s=",round(diff_time/60,1),"mins." );
return S
end
This goes in line with some other functions, but as you can see, this is the main function, so I really can't move forward without first runnning this one.

It isn't clear what outcome you are hoping for here. So I'll just give some pointers that hopefully help.
First, in this line:
x=[minimum(collect(A)):dx:maximum(collect(A))];
the calls to collect are redundant. Also, I suspect you are trying to construct a StepRangeLen, but by putting it in [] you actually are getting a Vector{StepRangeLen}. I think what you want in this line is actually this:
x=minimum(A):dx:maximum(A);
Second, in this line:
bx=[x-dx/2,x[end]+dx/2];
note that dx/2 is a Float64 while x is a StepRangeLen. This is important because the latter is a collection so if you want to perform this operation element-wise across the collection you need to broadcast, that is, x .- dx/2. Note, I suspect you may not be on the latest version of Julia, because when I run this the error message actually tells me explicitly I need to broadcast. Anyway, in contrast, x[end]+dx/2 is fine and does not need to be broadcast because x[end] is Float64. So I think you want:
bx=[x .- dx/2, x[end] + dx/2];
Having said that, it isn't clear to me why you want this bx, which is why I said at the start I'm not sure what outcome you were hoping for.

Related

LUA - Hammerspoon - Loop - eventtap keeps triggering

I'm trying to write a fairly simple script for Hammerspoon where I am looping through a table of app windows. The problem is for some reason when I call hs.eventtap inside the loop it keeps firing.
Any help much appreciated 🙏
function toggleMute()
local teams = hs.application.find("com.microsoft.teams"):allWindows()
if not (teams == null) then
for i, v in pairs(teams) do
hs.eventtap.keyStroke({"cmd", "shift"}, "m", 0, v)
end
end
hs.alert.show('Mute Toggled')
end

how do I filter my values using an array?

I am trying to sift through some free text answers on geographical locations. As one of the steps, I want to check if the answer is any of the 290 municipalities in my country. As 290 entries would make my code cumbersome/hard to read I try saving them in an array, like below:
Data resorTEST;
keep R_res_ort_namn R_res_ort_txt R_kom_lan R_kommun;
set resor1TEST resor2TEST resor3TEST;
R_res_ort_namn=strip(lowcase(R_res_ort_namn));
R_res_ort_txt=strip(lowcase(R_res_ort_txt));
R_kom_lan=strip(lowcase(R_kom_lan));
array kommuner{290} $ ("upplands väsby" "vallentuna" "österåker" "värmdö"
"järfälla" "ekerö" "huddinge" "botkyrka" "salem"
"haninge" "tyresö" "upplands-bro" "nykvarn" "täby"
"danderyd" "sollentuna" "stockholm" "södertälje" "nacka" "sundbyberg"
"solna" "lidingö" "vaxholm" "norrtälje" "sigtuna" "nynäshamn"
"håbo" "älvkarleby" "knivsta" "heby" "tierp" "uppsala"
"enköping" "östhammar" "vingåker" "gnesta" "nyköping" "oxelösund" "flen"
"katrineholm" "eskilstuna" "strängnäs" "trosa" "ödeshög" "ydre"
"kinda" "boxholm" "åtvidaberg" "finspång" "valdemarsvik" "linköping"
"norrköping" "söderköping" "motala" "vadstena" "mjölby" "aneby"
"gnosjö" "mullsjö" "habo" "gislaved" "vaggeryd" "jönköping"
"nässjö" "värnamo" "sävsjö" "vetlanda" "eksjö" "tranås"
"uppvidinge" "lessebo" "tingsryd" "alvesta" "älmhult" "markaryd"
"växjö" "ljungby" "högsby" "torsås" "mörbylånga" "hultsfred"
"mönsterås" "emmaboda" "kalmar" "nybro" "oskarshamn" "västervik"
"vimmerby" "borgholm" "gotland" "olofström" "karlskrona" "ronneby"
"karlshamn" "sölvesborg" "svalöv" "staffanstorp" "burlöv" "vellinge"
"östra göinge" "örkelljunga" "bjuv" "kävlinge" "lomma" "svedala"
"skurup" "sjöbo" "hörby" "höör" "tomelilla" "bromölla"
"osby" "perstorp" "klippan" "åstorp" "båstad" "malmö"
"lund" "landskrona" "helsingborg" "höganäs" "eslöv" "ystad"
"trelleborg" "kristianstad" "simrishamn" "ängelholm" "hässleholm" "hylte"
"halmstad" "laholm" "falkenberg" "varberg" "kungsbacka" "härryda"
"partille" "öckerö" "stenungsund" "tjörn" "orust" "sotenäs"
"munkedal" "tanum" "dals-ed" "färgelanda" "ale" "lerum"
"vårgårda" "bollebygd" "grästorp" "essunga" "karlsborg" "gullspång"
"tranemo" "bengtsfors" "mellerud" "lilla edet" "mark" "svenljunga"
"herrljunga" "vara" "götene" "tibro" "töreboda" "göteborg"
"mölndal" "kungälv" "lysekil" "uddevalla" "strömstad" "vänersborg"
"trollhättan" "alingsås" "borås" "ulricehamn" "åmål" "mariestad"
"lidköping" "skara" "skövde" "hjo" "tidaholm" "falköping"
"kil" "eda" "torsby" "storfors" "hammarö" "munkfors"
"forshaga" "grums" "årjäng" "sunne" "karlstad" "kristinehamn"
"filipstad" "hagfors" "arvika" "säffle" "lekeberg" "laxå"
"hallsberg" "degerfors" "hällefors" "ljusnarsberg" "örebro" "kumla"
"askersund" "karlskoga" "nora" "lindesberg" "skinnskatteberg" "surahammar"
"kungsör" "hallstahammar" "norberg" "västerås" "sala" "fagersta"
"köping" "arboga" "vansbro" "malung-sälen" "gagnef" "leksand"
"rättvik" "orsa" "älvdalen" "smedjebacken" "mora" "falun"
"borlänge" "säter" "hedemora" "avesta" "ludvika" "ockelbo"
"hofors" "ovanåker" "nordanstig" "ljusdal" "gävle" "sandviken"
"söderhamn" "bollnäs" "hudiksvall" "ånge" "timrå" "härnösand"
"sundsvall" "kramfors" "sollefteå" "örnsköldsvik" "ragunda" "bräcke"
"krokom" "strömsund" "åre" "berg" "härjedalen" "östersund"
"nordmaling" "bjurholm" "vindeln" "robertsfors" "norsjö" "malå"
"storuman" "sorsele" "dorotea" "vännäs" "vilhelmina" "åsele"
"umeå" "lycksele" "skellefteå" "arvidsjaur" "arjeplog" "jokkmokk"
"överkalix" "kalix" "övertorneå" "pajala" "gällivare" "älvsbyn"
"luleå" "piteå" "boden" "haparanda" "kiruna");
/*if not missing(R_res_ort_namn) then R_kommun=prxchange("s/^.*-(.* kommun)/$1/",1,R_res_ort_namn);
else if prxmatch("/^.*([a-zA-Z]*? kommun).*$/",R_res_ort_txt) then R_kommun=prxchange("s/^.*?([a-zA-Z]*? kommun).*$/$1/",-1,R_res_ort_txt);
else if prxmatch("/^.*([a-zA-Z]*? kommun).*$/",R_kom_lan) then R_kommun=prxchange("s/^.*?([a-zA-Z]*? kommun).*$/$1/",-1,R_kom_lan);
else */if R_res_ort_txt in kommuner then R_kommun=R_res_ort_txt;
run;
However, for some reason this does not seem to work for all of the municipalities. The municipality of "uppsala" works for instance, but not the municipality of "ängelholm".
I have tried stripping the variables of whitespace and converting everything to lowercase. What am I doing wrong?
Additional info:
For some reason it does work flawlessly if I skip the array and just copy-paste the exact same list of municipality names into a parenthesis following the in-operator. I would however need to repeat this step 5-6 times and this solution would make my code quite cumbersome.
You are defining the ARRAY
Array kommuner{290} $
with character length 8. See what happens when you fix that.

Adding an array to an existing csv file

I know this question was already asked, but after trying most of the accepted answer none of them seems to work with my simple task...
I have a csv file as follow:
Date,Median
2000-01-31,9
2000-02-28,8
2000-03-31,7
2000-04-30,6
2000-05-31,5
2000-06-30,4
2000-07-31,3
2000-08-31,2
2000-09-30,1
2000-10-31,0
2000-11-30,11
2000-12-31,12
and then an array:
[0.1829 0.171349 0.162461 0.152306 0.14122 0.137749 0.138802 0.150315
0.156784 0.168297 0.180634 0.187241]
I wish to append this array as a third column to the csv file to get the following output:
Date,Median,Median2
2000-01-31,9,0.1829
2000-02-28,8,0.171349
2000-03-31,7,0.162461
2000-04-30,6,0.152306
2000-05-31,5,0.14122
2000-06-30,4,0.137749
2000-07-31,3,0.138802
2000-08-31,2,0.150315
2000-09-30,1,0.156784
2000-10-31,0,0.168297
2000-11-30,11,0.180634
2000-12-31,12,0.187241
I tried most of the answer related to this kind of question but I did not succeed to make them work..here is the last code I tried, using pandas that looks easier but it does not work:
data=pd.read_csv("data_1.csv",sep=',')
array_transpose = array.reshape((-1, 1)) #in order to transpose the array
data['Median2'] = data[array_transpose]
data.to_csv('output.csv')
which produce the following error:
KeyError: '[0.1829 0.171349 0.162461 0.152306 0.14122 0.137749 0.138802 0.150315\n 0.156784 0.168297 0.180634 0.187241] not in index'
How to append this array to my csv file?
You may not need reshape
data=pd.read_csv("data_1.csv",sep=',')
data['Median2'] = array
data.to_csv('output.csv')

Error: Can't Assign Function Call / Don't want to

It's friday and I'm tired and my brain obvs doesn't want to find this answer. Please help.
I want to assign the value to an array. It works in subsequent lines but not in one particular line, even though syntax seems the same to me? It seems to think I'm calling a function??
for entry in PROJECT:
i = i + 1
#A
if entry.startswith("A") :
ProjectA(i) = entry
#B
elif entry.startswith("B"):
ProjectB(i)= entry
#C
elif entry.startswith("C") :
ProjectC(i) = entry
# and Programme
elif entry.startswith("D") :
ProjectD(i) = entry
I'm told the problem is the last line: "ProjectD(i) = entry". Which to me seems like a replica of "ProjectC(i) = entry"
ProjectA(i) looks like you are calling a function; ProjectA[i] looks like an array element.

how to fetch value from an array and check its range in rails

I have included given code and its working fine
def check_ip
start = IPAddr.new(10.10.0.10).to_i
last = IPAddr.new(20.10.10.16).to_i
begin
ip_pool = IpPool.pluck(:start_ip, :end_ip)
# [["10.10.10.12", "10.10.10.15"], ["192.168.1.13", "192.168.1.13"]]
low = IPAddr.new("10.10.10.12").to_i
high = IPAddr.new("10.10.10.15").to_i
# it will check so on with ["192.168.1.13", "192.168.1.13"] values too
raise ArgumentError, I18n.t('errors.start') if ((low..high)===start or (low..high)===last
end
rescue ArgumentError => msg
self.errors.add(:start, msg)
return false
end
return true
end
Please guide me on how to implement this code without giving static value IPAddr.new("10.10.10.12").to_i I want to add values dynamically which I am fetching in ip_pool array so in low and high I am giving static values which are present in an array how could I give this values dynamically.
Since you have an array of low/high, you probably want to check all items in it:
begin
IpPool.pluck(:start_ip, :end_ip).each do |(low,high)|
raise ArgumentError, I18n.t('errors.start') \
if (low..high) === start || (low..high) === last
end
true
rescue ArgumentError => msg
self.errors.add(:start, msg)
false
end
Please note that I have the code a bit cleaned up:
removed superfluous returns;
corrected begin-rescue clause (there was a superfluous end right before rescue, that actually addressed rescue to the whole function body.

Resources