How can I check if DatabaseLink`OpenSQLConnection was successful? My code is as follows
conn = OpenSQLConnection[JDBC["hsqldb", "file"], "Name"-> "test"];
Can I use something like Head[conn]?
The return value for successful connection will have head SQLConnection (in the DatabaseLink context)
More generally:
OpenSQLConnection returns $Failed when the connection failed for whatever reason:
In[25]:= OpenSQLConnection[JDBC["mysql", "localhost:3306/foo"],
"Username" -> "foo", "Password" -> "bar"]
During evaluation of In[25]:= JDBC::error: Access denied for user 'foo'#'localhost' (using password: YES) >>
Out[25]= $Failed
... and unevaluated when its arguments were not of the proper form:
In[28]:= OpenSQLConnection[Sin[x]]
Out[28]= OpenSQLConnection[Sin[x]]
Therefore, you can look for a return value of $Failed and optionally also use Check[...] to trap and handle messages that were generated. As you guessed, you can use Head[returnvalue] to make sure the head of the return value does not equal OpenSQLConnection.
This is not exactly an answer to your question, but this is what I do to connect reliably to my database:
Needs["DatabaseLink`"];
CloseSQLConnection[conn];
TimeConstrained[
conn=OpenSQLConnection[ JDBC["mysql","localhost:3306/mydb"],
"Username"->"myuser",
"Password"->"mypw"],
5,
CloseSQLConnection[conn];
conn=OpenSQLConnection[ JDBC["mysql","localhost:3306/mydb"],
"Username"->"myuser",
"Password"->"mypw"]
];
Related
I want to get the current restart policy of an AppServer (RUNNING, STOPPED or PREVIOUS) using Jython.
servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
for server in servers:
print server
print AdminConfig.showAttribute(server, "monitoringPolicy")
break
This gave me an exception that the attribute is invalid:
An exception occurred when executing the file "test.py". Information
about the exception: com.ibm.ws.scripting.ScriptingException:
WASX7080E: Invalid attributes for type "Server" -- "monitoringPolicy".
But I could get the attribute using print AdminConfig.showall(server):
...
[monitoringPolicy [[autoRestart true]
[maximumStartupAttempts 3]
[nodeRestartState STOPPED]
[pingInterval 60]
[pingTimeout 300]]]
...
For me it looks like monitoringPolicy is the key of an array, so that it should be possible to get the restart state with
policy = AdminConfig.showAttribute(server, "monitoringPolicy")
restartState = policy["restartState"] # Should be "STOPPED"
Where is the problem?
Edit
After taking a deeper look in the list output, I saw that I missed a top level property processDefinitions, which is the parent of monitoringPolicy.
pd = AdminConfig.showAttribute(server, "processDefinitions")
print pd
This prints:
[(cells/CnxCell/nodes/CnxNode01/servers/UtilCluster_server1|server.xml#JavaProcessDef_1578492353152)]
But I'm not able to get any of the child propertys from this object:
# TypeError: sequence subscript must be integer or slice
print pd["monitoringPolicy"]
# AttributeError: 'string' object has no attribute 'monitoringPolicy'
print pd.monitoringPolicy
MonitoringPolicy has his own type. This prints the server and the state, so 'RUNNING', 'STOPPED'
servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
for server in servers:
print(server)
mpol = AdminConfig.list("MonitoringPolicy", server)
print(AdminConfig.showAttribute(mpol, 'nodeRestartState'))
I have some Erlang code and Emacs is telling me that I have "Unbalanced parenthesis", but I can't figure what is wrong... Here is the code:
receive
{connect, Client} ->
NewPid = spawn_link(fun() -> game_loop(0,0)),
Client ! NewPid,
handle_connect()
end.
The error is at the row starting with NewPid...
You forgot the end after game_loop(0,0) in order to correctly completely define an anonymous function. The snippet should therefore look as follows:
receive
{connect, Client} ->
NewPid = spawn_link(fun() -> game_loop(0,0) end),
Client ! NewPid,
handle_connect()
end.
I'm debugging a problem where occasional writes to a mongo collection seem to be failing. As I was going over my error checking code, I found that the update method in the Collection class, seems to be returning a Fixnum instead of a hash.
Here is a code fragment (with debug statements)
begin
puts "collection type: #{#db_collection.class}"
status = #db_collection.update(selector, document)
puts "[Warn] Database update returned NULL status" unless status
puts "[Error] Mongo update returned an error: #{status.class}" unless (status == true)
puts "[Error] Mongo update returned an error: #{status}" unless (status == true)
rescue => e
puts "[Warn] Unable to update mongoDB (#{e})"
end
When I run this code, I get the following output:
collection type: Mongo::Collection
[Error] Mongo update returned an error: Fixnum
[Error] Mongo update returned an error: 236
I was expecting the update function to return a true for successful operations and a Hash for fails as per the documentation:
Returns:
(Hash, true) — Returns a Hash containing the last error object if acknowledging writes. > Otherwise, returns true.
I'm using version 1.8.0 of the ruby driver.
I'm not sure how to properly check that the writes have occurred correctly. I know that the driver should throw an exception if the write fails but I'm not seeing that happen. I don't know how to properly check the status variable since it's not returning a type I expect.
Thanks in advance for any help here.
I'm confused about how IO#select works in Ruby. I'm told here that it should only return the given IO objects if they are ready to be read. However, I'm getting IO objects returned even when eof? is true.
Am I missing something?
Here's some code that exhibits my confusion:
require 'open3'
stdin, stdout, stderr, thread = Open3.popen3('true')
eval_print = lambda {|code| puts "#{code} -> #{eval(code).inspect}" }
eval_print.call('stdout')
eval_print.call('stderr')
eval_print.call('select([stdout, stderr], nil, nil, 1)')
eval_print.call('stdout.eof?')
eval_print.call('stderr.eof?')
eval_print.call('stdout.gets')
eval_print.call('stderr.gets')
eval_print.call('select([stdout, stderr], nil, nil, 1)')
The output of this code (on Ruby version 1.9.2p136) is:
stdout -> #<IO:fd 5>
stderr -> #<IO:fd 7>
select([stdout, stderr], nil, nil, 1) -> [[#<IO:fd 5>, #<IO:fd 7>], [], []]
stdout.eof? -> true
stderr.eof? -> true
stdout.gets -> nil
stderr.gets -> nil
select([stdout, stderr], nil, nil, 1) -> [[#<IO:fd 5>, #<IO:fd 7>], [], []]
Shouldn't select return nil in both of those cases?
I don't blame you for being a little confused, the official docs are, shall we say, a little thin on what select is supposed to do.
IO.select is probably just a thin wrapper around the select system call so we'll have a look at that (which is quite well documented). From the Linux man pages:
Those listed in readfds will be watched to see if characters become available
for reading (more precisely, to see if a read will not block; in particular, a
file descriptor is also ready on end-of-file)
Emphasis mine. So, select is more about "will it block" than it is about "are there bytes waiting for me" and an EOF is a non-blocking state so select considers a file descriptor that is in an end-of-file condition to be ready for reading.
I am trying to figure out the logic of Message behavior.
Consider evaluation of the following:
On[]
Sin[1,1]
After evaluating the above you will get about 830 (!) Messages (in Mathematica 7).
All these Messages have arisen during producing the one:
Sin::argx: Sin called with 2 arguments; 1 argument is expected. >>
(this is one but last Message).
The last Message
Message::trace: Message[Sin::argx,Sin,2] --> Null. >>
corresponds to finishing of the work of internal Mathematica's Message function. Most of the other Messages go from evaluation of $NewMessage and $MessagePrePrint.
My questions are:
1) Why there are no infinite loop of Message generation? If calling Message[Sin::argx,Sin,2] produces more than 830 other Messages why each of them does not produce similar number of Messages? How such behavior can be simulated (by writing an analog of Message)?
2) Is it possible to force Message do not produce any additional Messages when it is called in the tracing mode (I mean the mode after evaluating On[])?
I am not understanding why it is necessary to turn on all the messages with On. Can you not only activate the subset you need. The reference page of On in "More Information" section lists various categories which you might find useful. In case you choose to proceed as stated, you can suppress trace messages by explicitly turning them off right after On[]:
On[]; Off[General::trace];
Sin[1, 1]
This outputs only two messages. Hence 830 of the messages you see are ::trace messages and originate from execution of some top-level code which is not necessarily message related, might be typesetting...
It seems that I have found one way to achieve with built-in function Message what I want:
Unprotect[Message];
Message[_, HoldForm[Block[List[$MyMagicalTag$, ___], _]], _] := Null;
Message[args___] /;
Block[{$MyMagicalTag$, Message}, Not#TrueQ[inMsg]] :=
Block[{$MyMagicalTag$, inMsg = True, lastargs = HoldComplete[args]},
Message[args]];
Message[args___] /;
Block[{$MyMagicalTag$,
Message}, (inMsg && (HoldComplete[args] =!= lastargs))] := Null;
Protect[Message];
Now things work as expected:
In[6]:= On[]
In[7]:= Sin[1,1]//AbsoluteTiming
During evaluation of In[7]:= Message::trace: Message[Sin::argx,Sin,2] --> Block[{$MyMagicalTag$,inMsg=True,lastargs=HoldComplete[Sin::argx,Sin,2]},Message[Sin::argx,Sin,2]]. >>
During evaluation of In[7]:= Sin::argx: Sin called with 2 arguments; 1 argument is expected. >>
During evaluation of In[7]:= AbsoluteTiming::trace: AbsoluteTiming[Sin[1,1]] --> {0.1502160,Sin[1,1]}. >>
Out[7]= {0.1502160,Sin[1,1]}
The only problem with the above is that CPU load is still high as you can see from the timings.
Other tested cases also work correctly:
In[8]:= 1+1//AbsoluteTiming
During evaluation of In[8]:= Plus::trace: 1+1 --> 2. >>
During evaluation of In[8]:= AbsoluteTiming::trace: AbsoluteTiming[1+1] --> {0.0400576,2}. >>
Out[8]= {0.0400576,2}
Thanks to Mr.Wizard for his help.