I am trying to handle a simple case where i could be getting an object, or a dictionary. So i am either going to get a object like:
obj.fields.nick
or its going to be a dictionary like
obj['nick']
I was wondering if there was a simpler way to do the following:
value = (eval("obj.fields." + field[1]) if obj?.fields ) ? eval("obj['#{field[1]}']")
I was hoping to do something like:
value = (obj?.fields?."#{field[1]}" ) ? eval("obj['#{field[1]}']")
But if that worked I wouldn't be writing this post...
I am basically looking for a way to execute a string as part of the if
value = obj.fields?[field] ? obj[field]
# or
value = (obj.fields ? obj)[field]
This is the same as
if obj.fields?
obj.fields[field]
else
obj[field]
There is absolutely no need for eval.
The string interpolation construct ("Equals four: #{2+2}") is something that is handled by the coffeescript compiler, and will therefore not work inside an eval. But assuming the naming of the stuff inside the string does not change, you could easily rewrite it, so that eval("obj['#{field[1]}']") becomes eval("obj['"+field[1]+"']"). Assuming I got your question right of course.
Related
I have an algorithm whose intermediate step is to replace a substring with another substring. To be precise I have a string HBIN_NEW and I have another string P. I want to replace every 6th,7th,8th element of the string HREP with the 1st,2nd,3rd element of PBIN_NEW. For this i have written the code
For example If PBIN_NEW='1111111101010101' and HBIN_NEW='1111100010101010'
then the new string HREP
should be HREP='1111111110101101'
for k=1:8:262144*8
HREP=strrep(HBIN_NEW,HBIN_NEW(k+5:k+7),PBIN_NEW(k:k+2));
end
Is this code correct to implement the above idea. And if yes, it is taking a long time do this replacement scheme, can somebody suggest some optimized way of doing this.
The wording on the question is still a bit awkward, and I'm not exactly sure how to get the example HREP given the wording, but most likely strrep is overkill for what it sounds like you are trying to do. A simple loop with assignments would be fine:
HREP = HBIN_NEW;
for k=1:8:length(HBIN_NEW)
HREP(k+5:k+7) = PBIN_NEW(k:k+2);
end
Often times though it can be better to just enumerate the position assignments and avoid the loop. So instead you have something like this:
HREP = HBIN_NEW;
HREP(6:8:end) = PBIN_NEW(1:8:end);
HREP(7:8:end) = PBIN_NEW(2:8:end);
HREP(8:8:end) = PBIN_NEW(3:8:end);
I think that does what you want, or should get you close enough ...
Finally, a bit of unsolicited style advice. Although Matlab doesn't have a very strict code style guide, most likely the use of all caps with underscores is not the best way of naming your variables. I personally prefer lowercase with underscores, e.g. pbin_new and only use capitalized words for constants ...
My codes looks like this:
_user.role >= level if _user?
I tried the codes below, but found it didn't work
_user?.role >= level
Does anyone have ideas about write shorter codes for this?
What do you want in case _user is null? If you want nothing (undefined), then use the first code. If you want false, then use second one. Or want another value from the expression?
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)
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.
So, in Perl, I have an array within an object (so, a reference to an array), and I want to find the first value of that array.
I find myself using code like the following quite often:
my $server_ref = $self->{source_env}->{server};
my #servers = #$server_ref;
my $main_server = $servers[0];
That works, but I'm sure I could do this without all the intermediate lines and variables.
Can someone help me with the syntax?
Try:
my $main_server = $self->{source_env}->{server}->[0];
Try $server_ref->[0], it should work.