Scala: Why is this pattern match code throwing an IndexOutOfBoundsException? - exception

I was checking out a tutorial, found at
http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4
This tutorial is from jan. 2008, I see, but I'm using Scala 2.8.0 if that makes a difference.
class Color(val red:Int, val green:Int, val blue:Int)
case class Red(r:Int) extends Color(r, 0, 0)
case class Green(g:Int) extends Color(0, g, 0)
case class Blue(b:Int) extends Color(0, 0, b)
def printColor(c:Color) = c match {
case Red(v) => println("Red: " + v)
case Green(v) => println("Green: " + v)
case Blue(v) => println("Blue: " + v)
case col:Color => {
print("R: " + col.red + ", ")
print("G: " + col.green + ", ")
println("B: " + col.blue)
}
case null => println("Invalid color")
}
When entering this into the interpreter, it produces
Exception in thread "main" java.lang.IndexOutOfBoundsException
at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:53)
at scala.collection.immutable.List.apply(List.scala:45)
plus another 185 lines of tracing, and the interpreter exits.
What does this error message mean, and can anyone tell me what is wrong with the code above?

A message like that is always a bug. Specifically https://lampsvn.epfl.ch/trac/scala/ticket/4025 .

Related

sending Strategy data using Webhooks for Pinescript 4.0

I am using Tradingview Pinescript 4.0.
This message was made with reference to :
https://stackoverflow.com/questions/66926863/combining-data-from-different-tradingview-4-0-indicators-for-the-purpose-of-crea
Basically, what I would like to do is use Tradingview 4.0 Pinescript Strategies with the Tradingview Webhook Alert system.
The closest I have seen that provides a hint a to how one can do this is found in this particular video (for a different product):
https://support.mudrex.com/hc/en-us/articles/360050211072-Automating-an-alert-from-a-Strategy-on-TradingView
It would use something like the "comment" below:
// strategy.entry(id=tostring(randomNumber), long=false,
comment="{"id" : " + tostring(randomNumber) + ", "action" :
"reverse_short_to_long"}")
I need to send JSON from the Strategy as part of the Web alert. According to the video, one would use something like:
{{ strategy.comment }}
Are there any solid examples as to how this could be done?
Tradingview sends the alert as JSON if the string is formatted as JSON. I suggest using the alert() function instead of alertcondition. It's then easy to construct a string in a JSON format however you want. Here's a nasty function I use to generate alerts.
customalert(_name, _symbol, _type, _asset_type, _action, _risk_value, _risk_percent, _sl, _tp1,_tp1_percent, _tp2, _tp2_percent, _message) =>
alert_array = array.new_string()
if _name != ''
array.push(alert_array, '"Name": "' + _name + '"')
if _symbol != ''
array.push(alert_array, '"Symbol": "' + _symbol + '"')
if _type != ''
array.push(alert_array, '"Type": "' + _type + '"')
if _asset_type != ''
array.push(alert_array, '"Asset Type": "' + _asset_type + '"')
if _action != ''
array.push(alert_array, '"Action": "' + _action + '"')
if _risk_value != 0
array.push(alert_array, '"Risk Value": "' + tostring(_risk_value) + '"')
if _risk_percent != 0
array.push(alert_array, '"Risk Percentage": "' + tostring(_risk_percent) + '"')
if _tp1 != 0
array.push(alert_array, '"Take Profit 1 Level": "' + tostring(_tp1) + '"')
if _tp1_percent != 0
array.push(alert_array, '"Take Profit 1 Percent": "' + tostring(_tp1_percent) + '"')
if _tp2 != 0
array.push(alert_array, '"Take Profit 2 Level": "' + tostring(_tp2) + '"')
if _tp2_percent != 0
array.push(alert_array, '"Take Profit 2 Percent": "' + tostring(_tp2_percent) + '"')
if _sl != 0
array.push(alert_array, '"Stop Loss Level": "' + tostring(_sl) + '"')
if _message != ''
array.push(alert_array, '"Message": "' + _message + '"')
alertstring = '{' + array.join(alert_array,', ') + '}'
alert(alertstring, alert.freq_once_per_bar_close)
You don't need to do anything complex though, the most important line is the alertstring = '{' + array.join(alert_array,', ') + '}'
You just need to make sure the string starts and ends with curly braces and is properly formatted JSON.
Could just as easily:
alert('{"Symbol": "' + syminfo.ticker + '", "Action": "Entry"}', alert.freq_once_per_bar_close)
You just need to be careful with your double and single quotes.
Also, this is explained if you go to set up an alert and click the option to learn more about alerts, at least the fact that formatting as JSON is what determines whether the alert is sent as text or JSON. As for the {{}}s, those are used to send a limited set of values for use with the alertcondition() function, and I don't really see an advantage to using them vs tostring() with alert().
Another thing to keep in mind is that this necessitates sending your data as strings, so you will need to make sure to convert back to ints and floats as necessary on the server side.

How to the display the number of instances of a string in vim statusline

A while ago I got to find a function to use in .vimrc to show if there ocurrances of " TODO " in the current buffer and show TD in the statusline. This is the function:
...
hi If_TODO_COLOR ctermbg=0 ctermfg=175 cterm=bold
set statusline+=%#If_TODO_COLOR#%{If_TODO()}
...
function! If_TODO()
let todos = join(getline(1, '$'), "\n")
if todos =~? " TODO "
return " TD "
else
return ""
endif
endfunction
My question is how can I modify the function to also return how many times the string has appeared in the buffer - somthing like TD (6).
You could :help filter() the lines to get a list of lines containing TODO:
let lines = getline(1, '$')
let todos = filter(lines, 'v:val =~? " TODO "')
return len(todos) > 0 ? 'TD' : ''
The same thing, expressed in a slightly more "modern" way:
return getline(1, '$')
\ ->filter('v:val =~? " TODO "')
\ ->len() > 0 ? 'TD' : ''
See :help method.

Groovy withBatch is really slow

I'm trying to use Groovy withBatch function and it's really slow (15 sec). I've tried with different batch sizes (10, 400 ...) and it always take a lot of time doing each batch.
It's the second query that I write with it and there are both slow.
Here's my code. Is there a bug in it or am I using it the wrong way ?
static updateCSProducts(def conn, def webProductRows){
conn.withBatch(400, """
UPDATE cscart_products p
SET usergroup_ids=:usergroup_ids,
b2b_group_ids=:b2b_group_ids,
b2b_desc_hide=:b2b_desc_hide
WHERE product_code = :product_code
OR product_id = (SELECT product_id FROM cscart_product_options_inventory WHERE product_code = :product_code)
""") { ps ->
webProductRows.each({row ->
ProductType type = ProductType.fromCode(row.type)
String userGroupIds = type.getProductAvailabilityUserGroup().collect{it.getId()}.join(",")
String b2bGroupIds = type.getB2bUserGroup().collect{it.getId()}.join(",")
boolean b2bDescHide = !type.getB2bUserGroup().isEmpty()
println row.id + " " + userGroupIds + " " + b2bGroupIds + " " + b2bDescHide
ps.addBatch(product_code:row.id, usergroup_ids:userGroupIds, b2b_group_ids:b2bGroupIds, b2b_desc_hide:b2bDescHide)
})
}
}
I'm using MySql as Database. When I'm looking at SQL connections, I don't really see any connection running a query while I'm waiting for the next batch.
EDIT:
I've removed the queries and it still very slow.
Heres the updated version:
conn.withBatch(400, """
UPDATE cscart_products p
SET usergroup_ids=:usergroup_ids,
b2b_group_ids=:b2b_group_ids,
b2b_desc_hide=:b2b_desc_hide
WHERE p.product_code = :product_code
""") { ps ->
webProductRows.each({row ->
ProductType type = ProductType.fromCode(row.type)
String userGroupIds = type.getProductAvailabilityUserGroup().collect{it.getId()}.join(",")
String b2bGroupIds = type.getB2bUserGroup().collect{it.getId()}.join(",")
String b2bDescHide = !type.getB2bUserGroup().isEmpty() ? 'Y' : 'N'
println row.id + " " + userGroupIds + " " + b2bGroupIds + " " + b2bDescHide
ps.addBatch(product_code:row.id, usergroup_ids:userGroupIds, b2b_group_ids:b2bGroupIds, b2b_desc_hide:b2bDescHide)
})
}
You're running tons of queries on each and every update. You'd be better off retrieving a list of data and then looping over that. It's not withBatch that's the bottleneck, it's your implementation.

Invalid syntax for no reason

I cannot figure out why I keep receiving invalid syntax. Here is the function I can't figure out:
def coordType():
coordType = input("Automatic [a] or manual [m] message box coordinates?"
if coordType.lower not in ("a", "m"):
print("It must be 'a' or 'm'")
coordType()
elif coordType.lower() == "a":
print("Please put your mouse over the message box")
time.sleep(5)
xc, yc = m.position()
print("Done - " + str(xc) + ", " + str(yc))
elif coordType.lower() == "m":
xcoord()
ycoord()
try to indent everything.
the body of "coordType" is in the same allignment with the title, so it's invalid in python.

quadratic equation

Question: I have a program that solves a quadratic equation. The program gives real solutions only. How do I perform the quality testing of the program? Do you need to ask me for some extra input parameters?
Create test cases, and check the result of your program against the expected result (which is calculated externally) in the test case.
The test cases can cover several ordinary cases, together with special cases, such as when the coefficient is 0, or the discriminant is < 0, = 0, near 0. When you compare the result, make sure you handle the comparison properly (since the result is floating point numbers).
# "quadratic-rb.rb" Code by RRB, dated April 2014. email ab_z#yahoo.com
class Quadratic
def input
print "Enter the value of a: "
$a = gets.to_f
print "Enter the value of b: "
$b = gets.to_f
print "Enter the value of c: "
$c = gets.to_f
end
def announcement #Method to display Equation
puts "The formula is " + $a.to_s + "x^2 + " + $b.to_s + "x + " + $c.to_s + "=0"
end
def result #Method to solve the equation and display answer
if ($b**2-4*$a*$c)>0
x1=(((Math.sqrt($b**2-4*$a*$c))-($b))/(2*$a))
x2=(-(((Math.sqrt($b**2-4*$a*$c))-($b))/(2*$a)))
puts "The values of x1 and x2 are " +x1.to_s + " and " + x2.to_s
else
puts "x1 and x2 are imaginary numbers"
end
end
Quadratic_solver = Quadratic.new
Quadratic_solver.input
Quadratic_solver.announcement
Quadratic_solver.result
end