Generating and consuming an array within a StringTemplate-4 template - stringtemplate-4

I'm new to StringTemplate4 and probably I am going to ask something overly simple, impossible or stupid but I couldn't find any other information on it.
So far, I have set this minimal set of templates:
define(name,arity) ::= "<name>(<vars(arity)>)."
vars(n) ::= "<n:var();separator=\", \">"
var(n) ::= "V<n>"
and I would like to get:
pred(V1, V2, V3).
by calling the following code:
STGroup group = new STGroupFile(...);
ST st = group.getInstanceOf("define");
st.add("name", "pred");
st.add("arity", 3);
String result = st.render();
Is it possible? Many thanks in advance.

StringTemplate doesn't have built-in operators for repeating. Instead, you'll need to iterate, like described in the following question.
Is there anything like Enumerable.Range(x,y) in Java?
Keep in mind that you'll need to pass an Iterator<T> and not an Iterable<T> due to a current limitation in StringTemplate (the interpreter supports Collection<T>, but not Iterable<T>). If you want to use the built-in iteration variable i or i0, you could also pass an appropriately sized new Object[n].

Related

(Scala) Am I using Options correctly?

I'm currently working on my functional programming - I am fairly new to it. Am i using Options correctly here? I feel pretty insecure on my skills currently. I want my code to be as safe as possible - Can any one point out what am I doing wrong here or is it not that bad? My code is pretty straight forward here:
def main(args: Array[String]): Unit =
{
val file = "myFile.txt"
val myGame = Game(file) //I have my game that returns an Option here
if(myGame.isDefined) //Check if I indeed past a .txt file
{
val solutions = myGame.get.getAllSolutions() //This returns options as well
if(solutions.isDefined) //Is it possible to solve the puzzle(crossword)
{
for(i <- solutions.get){ //print all solutions to the crossword
i.solvedCrossword foreach println
}
}
}
}
-Thanks!! ^^
When using Option, it is recommended to use match case instead of calling 'isDefined' and 'get'
Instead of the java style for loop, use higher-order function:
myGame match {
case Some(allSolutions) =>
val solutions = allSolutions.getAllSolutions
solutions.foreach(_.solvedCrossword.foreach(println))
case None =>
}
As a rule of thumb, you can think of Option as a replacement for Java's null pointer. That is, in cases where you might want to use null in Java, it often makes sense to use Option in Scala.
Your Game() function uses None to represent errors. So you're not really using it as a replacement for null (at least I'd consider it poor practice for an equivalent Java method to return null there instead of throwing an exception), but as a replacement for exceptions. That's not a good use of Option because it loses error information: you can no longer differentiate between the file not existing, the file being in the wrong format or other types of errors.
Instead you should use Either. Either consists of the cases Left and Right where Right is like Option's Some, but Left differs from None in that it also takes an argument. Here that argument can be used to store information about the error. So you can create a case class containing the possible types of errors and use that as an argument to Left. Or, if you never need to handle the errors differently, but just present them to the user, you can use a string with the error message as the argument to Left instead of case classes.
In getAllSolutions you're just using None as a replacement for the empty list. That's unnecessary because the empty list needs no replacement. It's perfectly fine to just return an empty list when there are no solutions.
When it comes to interacting with the Options, you're using isDefined + get, which is a bit of an anti pattern. get can be used as a shortcut if you know that the option you have is never None, but should generally be avoided. isDefined should generally only be used in situations where you need to know whether an option contains a value, but don't need to know the value.
In cases where you need to know both whether there is a value and what that value is, you should either use pattern matching or one of Option's higher-order functions, such as map, flatMap, getOrElse (which is kind of a higher-order function if you squint a bit and consider by-name arguments as kind-of like functions). For cases where you want to do something with the value if there is one and do nothing otherwise, you can use foreach (or equivalently a for loop), but note that you really shouldn't do nothing in the error case here. You should tell the user about the error instead.
If all you need here is to print it in case all is good, you can use for-comprehension which is considered quite idiomatic Scala way
for {
myGame <- Game("mFile.txt")
solutions <- myGame.getAllSolutions()
solution <- solutions
crossword <- solution.solvedCrossword
} println(crossword)

Using LuaJ with Scala

I am attempting to use LuaJ with Scala. Most things work (actually all things work if you do them correctly!) but the simple task of setting object values has become incredibly complicated thanks to Scala's setter implementation.
Scala:
class TestObject {
var x: Int = 0
}
Lua:
function myTestFunction(testObject)
testObject.x = 3
end
If I execute the script or line containing this Lua function and pass a coerced instance of TestObject to myTestFunction this causes an error in LuaJ. LuaJ is trying to direct-write the value, and Scala requires you to go through the implicitly-defined setter (with the horrible name x_=, which is not valid Lua so even attempting to call that as a function makes your Lua not parse).
As I said, there are workarounds for this, such as defining your own setter or using the #BeanProperty markup. They just make code that should be easy to write much more complicated:
Lua:
function myTestFunction(testObject)
testObject.setX(testObject, 3)
end
Does anybody know of a way to get luaj to implicitly call the setter for such assignments? Or where I might look in the luaj source code to perhaps implement such a thing?
Thanks!
I must admit that I'm not too familiar with LuaJ, but the first thing that comes to my mind regarding your issue is to wrap the objects within proxy tables to ease interaction with the API. Depending upon what sort of needs you have, this solution may or may not be the best, but it could be a good temporary fix.
local mt = {}
function mt:__index(k)
return self.o[k] -- Define how your getters work here.
end
function mt:__newindex(k, v)
return self.o[k .. '_='](v) -- "object.k_=(v)"
end
local function proxy(o)
return setmetatable({o = o}, mt)
end
-- ...
function myTestFunction(testObject)
testObject = proxy(testObject)
testObject.x = 3
end
I believe this may be the least invasive way to solve your problem. As for modifying LuaJ's source code to better suit your needs, I had a quick look through the documentation and source code and found this, this, and this. My best guess says that line 71 of JavaInstance.java is where you'll find what you need to change, if Scala requires a different way of setting values.
f.set(m_instance, CoerceLuaToJava.coerce(value, f.getType()));
Perhaps you should use the method syntax:
testObject:setX(3)
Note the colon ':' instead of the dot '.' which can be hard to distinguish in some editors.
This has the same effect as the function call:
testObject.setX(testObject, 3)
but is more readable.
It can also be used to call static methods on classes:
luajava.bindClass("java.net.InetAddress"):getLocalHost():getHostName()
The part to the left of the ':' is evaluated once, so a statement such as
x = abc[d+e+f]:foo()
will be evaluated as if it were
local tmp = abc[d+e+f]
x = tmp.foo(tmp)

Logging syntax for Play Framework 2 in Scala

This is a really silly question, but how can you do convenient formatting of log strings in Play Framework 2 (and in Scala?).
I've googled but its very difficult to find an example, essentially most links are talking about configuring Logback in the first place which I've done fine.
I'm basically trying to find the best stylistic way to do something like:
if(Logger.isDebugEnabled)
Logger.debug("Modified: Id = '" + real_session_id + "', Modified = " + modified.toString)
Coming from a C# background (and log4net) I'd assume you could do something like:
if(Logger.isDebugEnabled)
Logger.debug("Modified: Id = '{0}', Modified = {1}", real_session_id, modified.toString)
But I can't see how this would work with the trait the way it is defined. I've also seen vague references to how you might be able to avoid checking Logger.isDebugEnabled by using a lazy evaluative syntax like:
Logger.debug("Modified: Id = ${real_session_id}, Modified = ${modified.toString}")
That uses Scala macros - but again, that doesn't work and I can find very little information about it.
Am I missing something really blatant here?
The framework used for logging is logback. When you type : Logger.debug, the isDebugEnabled is already implicitly checked.
For the syntax of logging, use the Scala string interpolation.
Logger.debug(s"Modified: Id = '$real_session_id', Modified = $modified.toString")
Why not just use the standard String interpolation capabilities of the language/stdlib? http://docs.scala-lang.org/overviews/core/string-interpolation.html
I apologise if I've missed something crucial about your question.
As to avoiding the if (Logger.isDebugEnabled) check, if the logging framework is not providing some sort of lazy evaluation scheme for arguments passed into it, I would just first consider defining my own wrappers:
object MyLazyLogger {
def debug(msg: => Any) =
if (Logger.isDebugEnabled) Logger.debug(msg)
}
Also, I don't think the way in which you interpolate stuff into the string has anything to do with not evaluating the arguments to debug() if logging is disabled—if debug() declares that it eager-evaluates any arguments passed into it, there's no way that I can see you can change to lazy evaluation at the call site by just using a "special form" of string interpolation. (I'd be happy if anyone proved me wrong here and taught me something new :))
Disclosure: I'm not familiar with Play (yet), so I'm just taking a shot at a general approach here.

Simplify boolean expression i.t.o variable occurrence

How to simplify a given boolean expression with many variables (>10) so that the number of occurrences of each variable is minimized?
In my scenario, the value of a variable has to be considered ephemeral, that is, has to recomputed for each access (while still being static of course). I therefor need to minimize the number of times a variable has to be evaluated before trying to solve the function.
Consider the function
f(A,B,C,D,E,F) = (ABC)+(ABCD)+(ABEF)
Recursively using the distributive and absorption law one comes up with
f'(A,B,C,E,F) = AB(C+(EF))
I'm now wondering if there is an algorithm or method to solve this task in minimal runtime.
Using only Quine-McCluskey in the example above gives
f'(A,B,C,E,F) = (ABEF) + (ABC)
which is not optimal for my case. Is it save to assume that simplifying with QM first and then use algebra like above to reduce further is optimal?
I usually use Wolfram Alpha for this sort of thing.
Try Logic Friday 1
It features multi-level design of boolean circuits.
For your example, input and output look as follows:
You can use an online boolean expression calculator like https://www.dcode.fr/boolean-expressions-calculator
You can refer to Any good boolean expression simplifiers out there? it will definitely help.

Python: outside function applying changes to a class object's unique namespace

My question is how to program in Python (2.6) a function that uses a namespace of an object, while the function is defined outside the object/class. In addition, that function should only change the variables in the object's namespace; it should not take over the namespace (because with multiple objects they will all use the same namespace).
My reason for pursuing this, is because I wish to write a very small class, where during construction all necessary functions for future use are already given and subsequent function calls (self.__call__) on the object itself can be directly applied.
I realize that this idea is not very pythonic (as they say), and I have thought of various other solutions (such as putting the functions in another class and connecting them), but I can't help but feel that each of these solutions is a lot more work than I would think makes sense.
One simple way that accomplishes what I want is the following:
class A:
def __init__(self, some_dict, func_a):
self.memory = some_dict
self.__call__ = func_a
def test_func(obj, some_input):
if some_input in obj.memory :
return obj.memory[some_input]
else :
obj.memory[some_input] = 0. # some default value
return 0.
first_object = A({}, test_func)
print first_object(first_object, '3')
This will work fine, but what aches me is that when I make function calls to the object, I will also have to give the object itself (see the last line). I hope to be able make calls as such:
print first_object('3')
So far, my ideas were unsuccesful to avoid this (e.g. copying the function method and link its namespace by self.__call__.memory = self.memory). I wish to find something to change the def __init__ part to 'adopt' a function and link their namespaces.
I have rigorously searched for an answer on the internet, but a definite solution has not yet been found. The following http://www.velocityreviews.com/forums/t738476-inserting-class-namespace-into-method-scope.html seeks the same, but is also not succesfull.
Anyone have a solution to tackle this?