i try make chord piano detection by using matlab language. i able to identify every single tone note and i want to display the result by using string comparison so i make code like this
function akor=readChord(notes) %notes is input String data type
a1={'A' 'C#/Db' 'E'};
b1={'B' 'D' 'F#/Gb'};
c1={'C' 'E' 'G'};
d1={'D' 'F#/Gb' 'A'};
e1={'E' 'G#/Ab' 'B'};
f1={'F' 'A' 'C'};
g1={'G' 'A#/Bb' 'D'};
%Chord Minor
a2={'A' 'C' 'E'};
b2={'B' 'D' 'F#/Gb'};
c2={'C' 'D#/Eb' 'G'};
d2={'D' 'F' 'A'};
e2={'E' 'G' 'B'};
f2={'F' 'G#/Ab' 'C'};
g2={'G' 'A#/Bb' 'D'};
a=notes(3,:)
if v=isempty(setxor(a,a1))==1;
display('Chord A mayor')
elseif v = isempty(setxor(a,b1))==1;
display('Chord B')
elseif v = isempty(setxor(a,c1))==1;
display('Chord C mayor')
elseif v = isempty(setxor(a,d1))==1;
display('Chord D mayor')
elseif v = isempty(setxor(a,e1))==1;
display('Chord E mayor')
elseif v = isempty(setxor(a,f1)==1;
display('Chord F mayor')
elseif v = v = isempty(setxor(a,g1)==1;
display('Chord G mayor')
elseif v = isempty(setxor(a,a2))==1;
display('Chord A minor')
elseif v = isempty(setxor(a,b2))==1;
display('Chord B')
elseif v = isempty(setxor(a,c2))==1;
display('Chord C minor')
elseif v = isempty(setxor(a,d2))==1;
display('Chord D minor')
elseif v = isempty(setxor(a,e2))==1;
display('Chord E minor')
elseif v = isempty(setxor(a,f2)==1;
display('Chord F minor')
elseif v = isempty(setxor(a,g2)==1;
display('Chord G minor')
else
display('not Detect')
end
but it look like i have error
Error: File: bacagambar.m Line: 18 Column: 9
The expression to the left of the equals sign is not a valid target for an assignment.
anyone know what i should did
Using a switch staement might be more appropriate in this case
switch note(3,:)
case {'A' 'C#/Db' 'E'}
akor = 'Chord A mayor';
case {'B' 'D' 'F#/Gb'}
akor = 'Chord B';
% put all other patters in similar case
otherwise
akor = '';
error('not detected');
end
fprintf( 1, '%s\n', akor );
Related
I'm trying to encode some strings in my lua script, and since that I have a lua script with over 200k characters, encrypting each string query in the script with a function such as this example below
local string = "stackoverflow"
local string = [[stackoverflow]]
local string = [==[stackoverflow]==]
local string = 'stackoverflow'
to
local string=decode("jkrtbfmviwcfn",519211)
Trying to provide all above results to thread through a gsub and have the gsub encode the string text with a random offset number.
So far, I was only capable of gsubbing full quotation marks through.
function encode(x,offset,a)
for char in string.gmatch(x, "%a") do
local encrypted = string.byte(char) + offset
while encrypted > 122 do
encrypted = encrypted - 26
end
while encrypted < 97 do
encrypted = encrypted + 26
end
a[#a+1] = string.char(encrypted)
end
return table.concat(a)
end
luacode=[==[thatstring.Value="Encryptme!" testvalue.Value=[[string with
a linebreak]] string.Text="STOP!"]==]
luacode=luacode:gsub([=["(.-)"]=],function(s)
print("Caught "..s)
local offset=math.random(1,4)
local encoded=encode(s,offset,{})
return [[decode("]]..encoded..[[",]]..offset..[[)]]
end)
print("\n"..luacode)
With its output being
Caught Encryptme!
Caught STOP!
thatstring.Value=decode("crgvctxqi",4) testvalue.Value=[[string with
a linebreak]] string.Text=decode("opkl",2)
Any better solutions?
local function strings_and_comments(lua_code, callback)
-- lua_code must be valid Lua code (an error may be raised on syntax error)
-- callback will be invoked as callback(object_type, value, start_pos, end_pos)
-- callback("comment", comment_text, start_pos, end_pos) -- for comments
-- callback("string", string_value, start_pos, end_pos) -- for string literals
local objects = {} -- possible comments and string literals in the code
-- search for all start positions of comments (with false positives)
for pos, br1, eq, br2 in lua_code:gmatch"()%-%-(%-*%[?)(=*)(%[?)" do
table.insert(objects, {start_pos = pos,
terminator = br1 == "[" and br2 == "[" and "]"..eq.."]" or "\n"})
end
-- search for all start positions of string literals (with false positives)
for pos, eq in lua_code:gmatch"()%[(=*)%[[%[=]*" do
table.insert(objects, {is_string = true, start_pos = pos,
terminator = "]"..eq.."]"})
end
for pos, quote in lua_code:gmatch"()(['\"])" do
table.insert(objects, {is_string = true, start_pos = pos, quote = quote})
end
table.sort(objects, function(a, b) return a.start_pos < b.start_pos end)
local end_pos = 0
for _, object in ipairs(objects) do
local start_pos, ok, symbol = object.start_pos
if start_pos > end_pos then
if object.terminator == "\n" then
end_pos = lua_code:find("\n", start_pos + 1, true) or #lua_code
-- exclude last spaces and newline
while lua_code:sub(end_pos, end_pos):match"%s" do
end_pos = end_pos - 1
end
elseif object.terminator then
ok, end_pos = lua_code:find(object.terminator, start_pos + 1, true)
assert(ok, "Not a valid Lua code")
else
end_pos = start_pos
repeat
ok, end_pos, symbol = lua_code:find("(\\?.)", end_pos + 1)
assert(ok, "Not a valid Lua code")
until symbol == object.quote
end
local value = lua_code:sub(start_pos, end_pos):gsub("^%-*%s*", "")
if object.terminator ~= "\n" then
value = assert((loadstring or load)("return "..value))()
end
callback(object.is_string and "string" or "comment", value, start_pos, end_pos)
end
end
end
local inv256
local function encode(str)
local seed = math.random(0x7FFFFFFF)
local result = '",'..seed..'))'
if not inv256 then
inv256 = {}
for M = 0, 127 do
local inv = -1
repeat inv = inv + 2
until inv * (2*M + 1) % 256 == 1
inv256[M] = inv
end
end
repeat
seed = seed * 3
until seed > 2^43
local K = 8186484168865098 + seed
result = '(decode("'..str:gsub('.',
function(m)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
m = m:byte()
local c = (m * inv256[M] - (H - M) / 128) % 256
K = L * 21271 + H + c + m
return ('%02x'):format(c)
end
)..result
return result
end
function hide_strings_in_lua_code(lua_code)
local text = { [[
local function decode(str, seed)
repeat
seed = seed * 3
until seed > 2^43
local K = 8186484168865098 + seed
return (str:gsub('%x%x',
function(c)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
c = tonumber(c, 16)
local m = (c + (H - M) / 128) * (2*M + 1) % 256
K = L * 21271 + H + c + m
return string.char(m)
end
))
end
]] }
local pos = 1
strings_and_comments(lua_code,
function (object_type, value, start_pos, end_pos)
if object_type == "string" then
table.insert(text, lua_code:sub(pos, start_pos - 1))
table.insert(text, encode(value))
pos = end_pos + 1
end
end)
table.insert(text, lua_code:sub(pos))
return table.concat(text)
end
Usage:
math.randomseed(os.time())
-- This is the program to be converted
local luacode = [===[
print"Hello world!"
print[[string with
a linebreak]]
local str1 = "stackoverflow"
local str2 = [[stackoverflow]]
local str3 = [==[stackoverflow]==]
local str4 = 'stackoverflow'
print(str1)
print(str2)
print(str3)
print(str4)
]===]
-- Conversion
print(hide_strings_in_lua_code(luacode))
Output (converted program)
local function decode(str, seed)
repeat
seed = seed * 3
until seed > 2^43
local K = 8186484168865098 + seed
return (str:gsub('%x%x',
function(c)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
c = tonumber(c, 16)
local m = (c + (H - M) / 128) * (2*M + 1) % 256
K = L * 21271 + H + c + m
return string.char(m)
end
))
end
print(decode("ef869b23b69b7fbc7f89bbe7",2686976))
print(decode("c2dc20f7061c452db49302f8a1d9317aad1009711e0984",1210253312))
local str1 = (decode("84854df4599affe9c894060431",415105024))
local str2 = (decode("a5d7db792f0b514417827f34e3",1736704000))
local str3 = (decode("6a61bcf9fd6f403ed1b4846e58",1256259584))
local str4 = (decode("cad56d9dea239514aca9c8b8e0",1030488064))
print(str1)
print(str2)
print(str3)
print(str4)
Output of output (output produced by the converted program)
Hello world!
string with
a linebreak
stackoverflow
stackoverflow
stackoverflow
stackoverflow
Let's say I receive the following string in Lua mÜ⌠⌠í∩and would like to apply it to my current processing code, which is the following
function inTable(tbl, item)
for key, value in pairs(tbl) do
if value == item then return true end
end
return false
end
function processstring(instr)
finmsg = ""
achar = {131,132,133,134,142,143,145,146,160,166,181,182,183,198,199,224}
echar = {130,137,138,144,228}
ichar = {139,140,141,161,173,179,244}
ochar = {147,148,149,153,162,167,229,233,234,248}
uchar = {129,150,151,154,163}
nchar = {164,165,227,252}
outmsg = string.upper(instr)
for c in outmsg:gmatch"." do
bc = string.byte(c)
if(bc <= 47 or (bc>=58 and bc<=64) or (bc>=91 and bc<=96) or bc >=123)then
elseif (bc == 52) then finmsg = finmsg.."A"
elseif (bc == 51) then finmsg = finmsg.."E"
elseif (bc == 49) then finmsg = finmsg.."I"
elseif (bc == 48) then finmsg = finmsg.."O"
elseif (inTable(achar, bc)==true) then finmsg = finmsg.."A"
elseif (inTable(echar, bc)==true) then finmsg = finmsg.."E"
elseif (inTable(ichar, bc)==true) then finmsg = finmsg.."I"
elseif (inTable(ochar, bc)==true) then finmsg = finmsg.."O"
elseif (inTable(uchar, bc)==true) then finmsg = finmsg.."U"
elseif (inTable(nchar, bc)==true) then finmsg = finmsg.."N"
else
finmsg = finmsg..c
end
end
return finmsg
end
function checkword (instr)
specword = [[]]
wordlist = {"FIN", "FFI", "PHIN", "PHEN", "FIN", "PHIN", "IFFUM", "MUF", "MEUFEEN", "FEN","FEEN"}
for i, v in ipairs (wordlist) do
if (string.match(processstring(instr), v) ~= nil)then
return 1
end
end
--if (string.match(instr,specword) ~= nil)then
-- return 1
--end
end
print (checkword("mÜ⌠⌠í∩"))
As of now, I have found no way to proof strings like that. Not even by using string.byte() to reduce it to ASCII have I been able to reliably work with exoctic characters like those. Even more weird is that if I do a print(bc) on processstring I get the folowing output
160 226 140 160 195 173 226 136 169
Now, that's 9 ASCII codes for a 6 letter word, how can this be? I built the code referencing http://www.asciitable.com/, is it wrong? How can I approach this processing?
local subst = {
U = "üûùÜú",
N = "ñÑπⁿ∩",
O = "ôöòÖóºσΘΩ°",
I = "ïîìí¡│",
F = "⌠",
A = "âäàåÄÅæÆáª╡╢╖╞╟α",
E = "éëèÉΣ",
}
local subst_utf8 = {}
for base_letter, list_of_letters in pairs(subst) do
for utf8letter in list_of_letters:gmatch'[%z\1-\x7F\xC0-\xFF][\x80-\xBF]*' do
subst_utf8[utf8letter] = base_letter
end
end
function processstring(instr)
return (instr:upper():gsub('[%z\1-\x7F\xC0-\xFF][\x80-\xBF]*', subst_utf8))
end
print(processstring("mÜ⌠⌠í∩")) --> MUFFIN
I would appreciate your point of view where I might did wrong using OpenMP.
I parallelized this code pretty strait forward - yet even with single thread (i.e., call omp_set_num_threads(1)) I get wrong results.
I have checked with Intel Inspector, and I do not have a race condition, yet the Inspector tool indicated as a warning that a thread might approach other thread stack (I have this warning in other code I have, and it runs well with OpenMP). I do not think this is the problem.
SUBROUTINE GR(NUMBER_D, RAD_D, RAD_CC, SPECT)
use TERM,only: DENSITY, TEMPERATURE, VISCOSITY, WATER_DENSITY, &
PRESSURE, D_HOR, D_VER, D_TEMP, QQQ, UMU
use SATUR,only: FF, A1, A2, AAA, BBB, SAT
use DELTA,only: DDM, DT
use CONST,only: PI, G
IMPLICIT NONE
INTEGER,INTENT(IN) :: NUMBER_D
DOUBLE PRECISION,INTENT(IN) :: RAD_CC(NUMBER_D), SPECT(NUMBER_D)
DOUBLE PRECISION,INTENT(INOUT) :: RAD_D(NUMBER_D)
DOUBLE PRECISION :: R3, DR3, C2, C0, P, Q, RAD_CR, SAT_CR, C4, A, &
C, D, CC, DD, CC2, DD2, RAD_ST, DRAA, DRA, DM, X1
INTEGER :: I
DDM = 0.0D0
!$OMP PARALLEL DO DEFAULT(SHARED) &
!$OMP PRIVATE(I,R3,DR3,C2,C0,P,Q,SAT,SAT_CR,C4,A) &
!$OMP PRIVATE (C,D,CC,DD,CC2,DD2,RAD_ST,DRAA,DRA,DM,RAD_CR,X1) &
!$OMP REDUCTION (+:DDM)
DO I=1,NUMBER_D
R3 = RAD_CC(I)**3
DR3 = RAD_D(I)**3-R3
IF(DR3.LT.1.0D-100) DR3 = 1.0D-100
C2 = -DSQRT(3.0D0*BBB*R3/AAA)
C0 = -R3
P = -0.3333333333D0*C2**2
Q = C0+0.074074074D0*C2**3
CALL CUBIC(P, Q, RAD_CR)
RAD_CR = RAD_CR - 0.3333333333D0*C2
SAT_CR = DEXP(AAA/RAD_CR-BBB*R3/(RAD_CR**3-R3))-1.0D0
DRA = DT*(SAT+1.0D0-DEXP(AAA/RAD_DROP(I)-BBB*R3/DR3))/ &
(FF*RAD_D(I))
IF(SAT.LT.SAT_CR) THEN
IF(DABS(SAT).LT.1.0D-10) THEN
P = -BBB*R3/AAA
Q = -R3
CALL CUBIC(P, Q, RAD_ST)
GO TO 22
END IF
C4 = DLOG(SAT+1.0D0)
A = -AAA/C4
C = (BBB-C4)*R3/C4
D = -A*R3
P = A*C-4.0D0*D
Q = -(A**2*D+C**2)
CALL CUBIC(P, Q, X1)
CC = DSQRT(A**2+4.D0*X1)
DD = DSQRT(X1**2-4.D0*D)
CC2 = 0.5D0*(A-CC)
IF(SAT.LT.0.0D0) THEN
DD2 = 0.5D0*(X1-DD)
RAD_ST = 0.5D0*(-CC2+DSQRT(CC2**2-4.0D0*DD2))
ELSE
DD2 = 0.5D0*(X1+DD)
RAD_ST = 0.5D0*(-CC2-DSQRT(CC2**2-4.0D0*DD2))
END IF
22 CONTINUE
DRAA = RAD_ST-RAD_D(I)
IF(ABS(DRAA).LT.ABS(DRA)) THEN
DRA = DRAA
DM = 1.3333333333333333D0*PI*WATER_DENSITY* &
(RAD_ST**3-RAD_D(I)**3)
ELSE
DM = 4.0D0*PI*WATER_DENSITY*RAD_D(I)**2*DRA
END IF
DDM = DDM+SPECT(I)*DM
RAD_D(I) = RAD_D(I) + DRA
ELSE
DM = 4.0D0*PI*WATER_DENSITY*RAD_D(I)**2*DRA
DDM = DDM+SPECT(I)*DM
RAD_D(I) = RAD_D(I) + DRA
END IF
END DO
!$OMP END PARALLEL DO
RETURN
END SUBROUTINE GR
SUBROUTINE CUBIC(P, Q, X)
IMPLICIT NONE
DOUBLE PRECISION,INTENT(IN) :: P, Q
DOUBLE PRECISION,INTENT(OUT) :: X
DOUBLE PRECISION :: DIS, PP, COSALFA,ALFA, QQ, U, V
DIS = (P/3.D0)**3+(0.5D0*Q)**2
IF(DIS.LT.0.0D0) THEN
PP = -P/3.0D0
COSALFA = -0.5D0*Q/DSQRT(PP**3)
ALFA = DACOS(COSALFA)
X = 2.0D0*DSQRT(PP)*DCOS(ALFA/3.0D0)
RETURN
ELSE
QQ = DSQRT(DIS)
U = -0.5D0*Q+QQ
V = -0.5D0*Q-QQ
IF(U.GE.0.0D0) THEN
U = U**0.333333333333333D0
ELSE
U = -(-U)**0.333333333333333D0
END IF
IF(V.GE.0.0D0) THEN
V = V**0.333333333333333D0
ELSE
V = -(-V)**0.333333333333333D0
END IF
X = U+V
END IF
RETURN
END SUBROUTINE CUBIC
Instead of writing for a vector V:
V[a>1 & b==2 & c<1]
I would like something like:
V[restriction]
with
restriction = "a>1 & b==2 & c<1"
Any ideas?
Thanks,
F.
Try this:
> V <- data.frame(a = 1:5, b = 1:5, c = 0)
> restriction = "a>1 & b==2 & c<1"
> subset(V, eval(parse(text = restriction)))
a b c
2 2 2 0
Hey guys so this is a strange little error I'm getting and I'm not understand why it's giving it to me.
It says Parse Error in input 'appendString' yet I see nothing wrong with it...
I call it from an if,then else statement as follows:
createShow currentIndex (Grid {delta = d, middle = (x,y), points = g}) dir counter =
if currentIndex ==0 || dir == 2
then (appendString d (x,y) g currentIndex) ++ (createShow currentIndex+1 (Grid {delta = d, middle = (x,y), points = g}) 2 (counter+1))
else if counter == (2*d+1)
then (appendString d (x,y) g currentIndex) ++ (appendX x)
else if dir == 1
then (appendString d (x,y) g currentIndex) ++ (createShow currentIndex-1 (Grid {delta = d, middle = (x,y), points = g}) 1 (counter+1))
where createShow returns a string and so does appendString
appendString gives the error in the constructor:
appendString d (x,y) g currentIndex =
(if currentIndex == y
then "y "
else
" " ) ++ (show currentIndex) ++(rowFunction g x d 0 (x+d) 1)++ "\n"
do you see where I could have gone wrong with it?
Edit: Added entire area
Haskell if's are not like other if's in say Java or python. The biggest difference is that they are expressions unlike java or python where they are statements.
They are much closer to the condition ? res1 : res2 from C.
The correct way to write nested if's is like this:
if condition
then foo
else if condition2
then bar
else ...
You'll notice that this is horribly ugly.
That's why haskell has guards:
foo args | condition = foo
| condition2= bar
| otherwise = meh
Here we declare a function foo and if condition is true then we execute foo otherwise we proceed to condition2 and otherwise is always true. For you
createShow currentIndex (Grid {delta = d, middle = (x,y), points = g}) dir counter
| currentIndex == 0 || dir == 2 = appendString d ....
| counter == (2 * d + 1) = appendString d ....
| dir == 1 = appendString d ....
which looks much more readable.
Here's a refactoring::
createShow currentIndex grid#(Grid {delta = d, middle = (x,y), points = g}) dir counter =
prefix ++ show currentIndex ++ row ++ "\n" ++ nextLine
where
prefix = if currentIndex == y then "y " else " "
row = rowFunction g x d 0 (x+d) 1
nextLine | currentIndex == 0 || dir == 2 = createShow (currentIndex+1) grid 2 (counter+1)
nextLine | counter == (2*d+1) = appendX x
nextLine | dir == 1 = createShow (currentIndex-1) grid 1 (counter+1)
appendX x = ...
Things to notice:
Using a where clause often lets you avoid repeating parameters
The common call to appendString has been factored out, and moved to the top, and then in-lined, since it is only called once.
Use of guards in nextLine to handle a cascaded if more clearly.
The guards and form of nextLine make it clear it isn't a total function. What happens when it falls off the end?
The use of grid# to name a pattern. This way you don't need to "reconstruct" the Grid value when making the recursive calls.
One can go further. Noticing that Grid {...} and dir never change throughout the function suggests factoring those out:
createShow currentIndex (Grid {delta = d, middle = (x,y), points = g}) dir counter =
line currentIndex counter
where
line currentIndex counter =
prefix ++ show currentIndex ++ row ++ "\n" ++ nextLine currentIndex counter
prefix = if currentIndex == y then "y " else " "
row = rowFunction g x d 0 (x+d) 1
nextLine currentIndex counter
| currentIndex == 0 || dir == 2 = line (currentIndex+1) (counter+1)
| counter == (2*d+1) = appendX x
| dir == 1 = line (currentIndex-1) (counter+1)
appendX x = ...
Here, line plays the part of "carrying" around the only values that differ as the function recurses. It would be a common idiom to place those arguments at the end of what createShow takes, and thus even factor them out:
createShow :: Grid -> Int -> Int -> Int -> String
createShow (Grid {delta = d, middle = (x,y), points = g}) dir = line
where
line currentIndex counter =
prefix ++ show currentIndex ++ row ++ "\n" ++ nextLine currentIndex counter
prefix = if currentIndex == y then "y " else " "
row = rowFunction g x d 0 (x+d) 1
nextLine currentIndex counter
| currentIndex == 0 || dir == 2 = line (currentIndex+1) (counter+1)
| counter == (2*d+1) = appendX x
| dir == 1 = line (currentIndex-1) (counter+1)
appendX x = ...