Ruby - no implicit conversion of Symbol into Integer - ruby-on-rails

I'm trying to create AWS Security Group but I'm getting the error no implicit conversion of Symbol into Integer during ec2.create_security_group(GroupName=sg_name, VpcId=vpc_id)
I'm following this documentation. Any idea how to resolve the error?
begin
ec2 = get_aws_client
prov = $evm.root['miq_provision_request'] || \
$evm.root['miq_provision'] || \
$evm.root['miq_provision_request_template']
vpc_id = prov.get_option(:dialog_cloud_network).to_s.strip
#prov.get_option(:dialog_vm_name).to_s.strip
sg_name = 'test_sg_manageiq'
#ec2.create_security_group({vpcid: vpc_id, groupname: sg_name})
ec2.create_security_group(GroupName=sg_name, VpcId=vpc_id)
rescue => err
log(:error, "[#{err}]\n#{err.backtrace.join("\n")}")
exit MIQ_ABORT
end
Error:
[----] I, [2022-02-15T16:17:26.360528 #326:2ad4a042a1e0] INFO -- automation: Q-task_id([r49_miq_provision_183]) <AEMethod sg_preprovision> Found provider: AWS via default method
[----] E, [2022-02-15T16:17:26.660450 #326:2ad4a042a1e0] ERROR -- automation: Q-task_id([r49_miq_provision_183]) <AEMethod sg_preprovision> [no implicit conversion of Symbol into Integer]
/ManageIQ_Custom/Cloud/VM/Provisioning/StateMachines/Methods/SG_Preprovision:143:in `<main>'
[----] I, [2022-02-15T16:17:26.707133 #326:2ad4959cb960] INFO -- automation: Q-task_id([r49_miq_provision_183]) <AEMethod [/ManageIQ_Custom/Cloud/VM/Provisioning/StateMachines/Methods/SG_Preprovision]> Ending
[----] E, [2022-02-15T16:17:26.707734 #326:2ad4959cb960] ERROR -- automation: Q-task_id([r49_miq_provision_183]) State=<PreProvision> running raised exception: <Method exited with rc=MIQ_ABORT>
[----] W, [2022-02-15T16:17:26.707927 #326:2ad4959cb960] WARN -- automation: Q-task_id([r49_miq_provision_183]) Error in State=[PreProvision]

An "no implicit conversion of Symbol into Integer" error almost always means that you have an array or string where you're expecting to have a hash. In your case, the suspicious code is:
#ec2.create_security_group({vpcid: vpc_id, groupname: sg_name})
ec2.create_security_group(GroupName=sg_name, VpcId=vpc_id)
The create_security_group call you're using looks more like Python than Ruby to me and is equivalent to:
GroupName = sg_name
VpcId = vpc_id
ec2.create_security_group(GroupName, VpcId)
so you're passing a string (sg_name) to a method that expects a hash of parameters:
#create_security_group(params = {}) ⇒ Types::CreateSecurityGroupResult
Creates a security group.
[...]
Then create_security_group tries to treat sg_name as the params hash it is expecting and that triggers the exception.
I think you want to use the code you commented out and fix the keys to include underscores as per the documentation:
ec2.create_security_group(vpc_id: vpc_id, group_name: sg_name)

Related

How to return a function value from pcall() in lua

My code (psuedo)
function foo(cmd)
return load(cmd) --Note that this could cause an error, should 'cmd' be an invalid command
end
function moo()
return "moo"
end
function yoo(something)
something.do()
end
cmd = io.read() --Note that a syntax error will call an error in load. Therefore, I use pcall()
local result, error = pcall(cmd)
print(result)
This code looks okay, and works, but my problem is if I type in moo() then result will only show whether or not the command was executed without an error (If the command calls an error, error will have its value).
On another note, if I want to call yoo(), I won't get a return value from it, so I want pcall()'s true / false (or any alternate means other than pcall())
Is there an alternate way to call moo(), get a return value, and also be able to catch any errors?
NOTE: I couldn't find any try catch equivalent other then pcall / xpcall.
A bit outdated but still without proper answer...
What you are looking for is a combination of both load() and pcall()
Use load()to compile the entered string cmd into something that can be executed (function).
Use pcall() to execute the function returned by load()
Both functions can return error messages. Get syntax error description from load() and runtime error description from pcall()
function moo()
return "moo"
end
function yoo(something)
something.do_something()
end
cmd = io.read()
-- we got some command in the form of a string
-- to be able to execute it, we have to compile (load) it first
local cmd_fn, err = load("return "..cmd);
if not cmd_fn then
-- there was a syntax error
print("Syntax error: "..err);
else
-- we have now compiled cmd in the form of function cmd_fn(), so we can try to execute it
local ok, result_or_error = pcall(cmd_fn)
if ok then
-- the code was executed successfully, print the returned value
print("Result: "..tostring(result_or_error));
else
-- runtime error, print error description
print("Run error: "..result_or_error)
end
end

Argument Error when trying to specify :env in Elixir Port.open

I'm trying to set an environment variable when running a shell command using Port.open. It raises an error, ArgumentError no matter what I pass in.
port = Port.open({ :spawn_executable, "/usr/local/bin/cool" },
[:stream, :in, :binary, :eof, :hide,
{:env, [{"COOL_ENV", "cool"}]},
{ :args, ["test.js"] }])
According to the Elixir docs for Port.open, it should accept any arguments that the Erlang function :erlang.open_port accepts. The Erlang documentation mentions:
{env, Env} Only valid for {spawn, Command}, and {spawn_executable,
FileName}. The environment of the started process is extended using
the environment specifications in Env.
Env is to be a list of tuples {Name, Val}, where Name is the name of
an environment variable, and Val is the value it is to have in the
spawned port process. Both Name and Val must be strings. The one
exception is Val being the atom false (in analogy with os:getenv/1,
which removes the environment variable.
(http://erlang.org/doc/man/erlang.html#open_port-2)
This error occurs even if I try to call the erlang function directly like so:
:erlang.open_port({:spawn_executable, "/usr/local/bin/cool"}, [:stream, :in, :binary, :eof, :hide, {:env, [{"COOL", "cool"}] },{:args, ["test.js"]}])
The error goes away if I remove the {:env, [{...}] argument.
The :env option requires both the name and the value to be Erlang strings, which is called a charlist in Elixir, and is constructed using single quotes instead of double.
Opt =
...
{env, Env :: [{Name :: string(), Val :: string() | false}]} |
...
Source
The following should fix the error:
port = Port.open({ :spawn_executable, "/usr/local/bin/cool" },
[:stream, :in, :binary, :eof, :hide,
{:env, [{'COOL_ENV', 'cool'}]},
{ :args, ["test.js"] }])
:args accepts both Erlang strings and Erlang binaries (Elixir Strings), so you don't need to change that.

Handling error from one stored procedure into another in Sybase ASE 15.0

I need to execute a password reset on a Sybase ASE dataserver based on certain conditions:
if validations_here
begin
exec sp_password 'sso_passw', 'new_passw', #userid
end
sp_password might raise some errors, e.g. 10316 - "New password supplied is the same as the previous password". Although I couldn't find any documentation, I think they shouldn't be fatal errors and it should be possible to emulate them with raiserror.
Since it would be easier for the caller to handle it that way, I would like to get the error code and return it as part of a resultset, so I thought about SELECTing ##error. My code is as follows (I transcribed only those parts I think are relevant to the problem):
create procedure sp_desbloc_blanqueo_usr
#userid sysname,
#sso_pass varchar(20),
#new_pass varchar(20)
as
begin
declare #ret_code int
declare #ret_msg varchar(100)
declare #myerror int
select #ret_code = 0, #ret_msg = 'OK'
exec sp_password #sso_pass, #new_pass, #userid
set #myerror = ##error
if #myerror <> 0
begin
select #ret_code = #myerror, #ret_msg = 'Error occurred changing password'
-- It would be nice to have the actual error message as well
goto fin
end
fin:
select #ret_code as ret_code, #ret_msg as ret_msg
end
However, whenever I execute the stored procedure, I get 0 as ret_code and OK as ret_msg (even if parameters to sp_password are wrong).
How can I "catch" the error code of sp_password from my stored procedure?
Many "sp_" stored procedures set a nonzero return code when something goes wrong. Usually it is better to handle this return code than trying to catch errors raised inside the stored procedure. IIRC, this catching would not be possible with Transact-SQL; a 3rd generation language such as C would be required.
To get the return code of myproc stored procedure into variable #myvar, the syntax is
exec #myvar = myproc [arguments]
A simple example with sp_password:
declare #spreturn int
exec #spreturn = sp_password 'notmyoldpw', 'notmynewpw'
print "Return from sp_password is %1!", #spreturn
go
Server Message: Number 10315, Severity 14
Server 'SDSTRHA01_SY01', Procedure 'sp_password', Line 148:
Invalid caller's password specified, password left unchanged.
Server Message: Number 17720, Severity 16
Server 'SDSTRHA01_SY01', Procedure 'sp_password', Line 158:
Error: Unable to set the Password.
(1 row affected)
Return from sp_password is 1
(return status = 1)
The int variable #spreturn defined in the first line got sp_password return code, whose value was one as shown by (return status = 1) in the last message line. The reason why it was not zero is clear: there were two errors inside sp_password, 10315 and 17720. The point is to focus in this nonzero return code and ignore 10315 and 17720. In your stored proc, #spreturn ought to be checked against zero. If zero it ran OK, else something failed.

Print the exmpp Packet to Raw XML string

How to print the Packet type to raw XML string ? In the example https://github.com/processone/exmpp/blob/master/examples/echo_client.erl the echo_packet(MySession, Packet) -> function takes the parameter Packet which is of xmlel record type. As mentioned in the post https://stackoverflow.com/a/31020654/579689 tried the function xml:element_to_binary/1 but it did not work.
When i tried to print using the following expression
io:format("Received Presence stanza:~n~p~n~n", [xml:element_to_binary({xmlel,<<"message">>,[{<<"xml:lang">>,<<"en">>},{<<"type">>,<<"chat">>},{<<"to">>,<<"x">>},{<<"id">>,<<"aaf6a">>}],[{xmlcdata,<<"\n">>},{xmlel,<<"body">>,[],[{xmlcdata,<<"wewe">>}]},{xmlcdata,<<"\n">>},{xmlel,<<"active">>,[{<<"xmlns">>,<<"http://jabber.org/protocol/chatstates">>}],[]},{xmlcdata,<<"\n">>},{xmlel,<<"time">>,[{<<"xmlns">>,<<"urn:server-time">>},{<<"stamp">>,"2015-06-23T22:48:24Z"}],[]}]})]).
received following error
=ERROR REPORT==== 12-Oct-2015::09:06:01 ===
Error in process <0.30.0> with exit value: {undef,[{xml,element_to_binary,[{xmlel,<<7 bytes>>,[{<<8 bytes>>,<<2 bytes>>},{<<4 bytes>>,<<4 bytes>>},{<<2 bytes>>,<<1 byte>>},{<<2 bytes>>,<<5 bytes>>}],[{xmlcdata,<<1 byte>>},{xmlel,<<4 bytes>>,[],[{xmlcdata,<<4 bytes>>}]},{xmlcdata,<<1 byte>>},{xmlel,<<6 bytes>>,[{<<5 bytes>>,<<37 bytes>>}],[]},{xmlcdata,<<1 byte>>},{xmlel,<<4 bytes>>,[{<<5 bytes>>,<<15 bytes>>},{<<5 bytes>>,"2015-06-23T22:48:24Z"}],[]}]}],[]},{echo_client,loop,1,[{file,"../examples/ech...
Error {undef,[{xml,element_to_binary,[list of N args]}]} tells you that function xml:element_to_binary/N is undefined.
Looking through xml module of the project you may try element_to_string instead of element_to_binary.
However from the point of efficiency exmpp_xml:document_to_iolist/1 will suit you better

Thrift/Erlang string

I'm trying to write a simple Thrift server in Erlang that takes a string and returns a string.
Everything seems to be working up to the point of calling my function:
handle_function(Function, Args) when is_atom(Function), is_tuple(Args) ->
case apply(?MODULE, Function, tuple_to_list(Args)) of
ok -> ok;
Reply -> {reply, Reply}
end.
test([X]) ->
"You sent: " ++ X.
I'm getting a function_clause. The stack trace shows the following:
{function_clause, [{server, test,
[<<"w00t">>]},
{server,handle_function, 2}, ...
My handle_function is copied from the tutorial file so I won't be surprised if I need to tweak it. Any ideas?
That last argument of apply should be a list of arguments to 'test', e.g., if tuple_to_list(Args) resulted in:
[1]
...then:
test(1)
If tuple_to_list(Args) resulted in:
[1,2]
...then:
test(1,2)
So, if {<<"woot">>} is being passed to tuple_to_list, that's going to be:
[<<"woot">>]
...so:
test(<<"woot">>)
...but test's signature asks for a list as the argument, so there's a mismatch.

Resources