How to get the result using neo4j-driver functions as same as the result from evaluate() function in py2neo? - neo4j

def get_nlg(graph_query):
driver = Graph("neo4j://localhost:7687", auth=("neo4j","password"))
graph_response = graph.evaluate(graph_query)
For the above code, I replaced with the driver code as below, but its not working, what is the function in neo4j driver equivalent to evaluate() function in py2neo?
def get_nlg(graph_query):
driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j","password"))
with driver.session() as session:
graph_response = session.run(graph_query)
return graph_response
When the result from graph_response of 2nd code is passed to the below code, I am getting an error
TypeError: <neo4j.work.result.Result object at 0x7f94cf7f31d0> is not JSON serializable
class GetBiggestComponent(Action):
def name(self):
return "action_get_biggest_component"
def run(self, dispatcher, tracker, domain):
query = None
intent = tracker.latest_message['intent']
child_comp = tracker.get_slot('component_type_child')
parent_comp = tracker.get_slot('component_type_parent')
error = None
graph_response = GenerateQuery.get_biggest_component(child_comp, parent_comp)
graph_response['intent_name'] = intent['name']
dispatcher.utter_message(json.dumps(graph_response))
return []
the error is coming when it is passed in the line
dispatcher.utter_message(json.dumps(graph_response))

The output of session.run is an object that lets you navigate the result, not the result itself. I strongly recommend reading the manual and API docs for the driver, as this is all described in there.
https://neo4j.com/docs/driver-manual/current/session-api/simple/#driver-simple-result-consume
https://neo4j.com/docs/api/python-driver/current/api.html#result
As per my answer to your other question, to simulate evaluate, you will simply need to navigate to the first record of the result and then return the first value of that record.

Related

Calling expand entity from SAP Gateway Client

I try to call a GET_EXPANDED_ENTITYSET method of SRA020_PO_TRACKING Project, po tracking project. The following is the method:
METHOD /iwbep/if_mgw_appl_srv_runtime~get_expanded_entityset.
DATA: lv_ponumber TYPE bapiekko-po_number,
lv_leading_msg TYPE boolean.
DATA: lo_api TYPE REF TO cl_sra020_po_tracking_api.
DATA: ls_po_details TYPE cl_sra020_po_tracking_api=>ts_podetails,
lt_return TYPE bapirettab,
lo_msgcontainer TYPE REF TO /iwbep/if_message_container.
DATA: lt_poitem_details TYPE cl_sra020_po_tracking_api=>tt_poitemdetail.
FIELD-SYMBOLS: <fs_return> TYPE bapiret2,
<fs_key_tab> TYPE /iwbep/s_mgw_name_value_pair.
lo_api = cl_sra020_po_tracking_api=>get_instance( ).
*========================================================================================
* Read Entities key values within oData service URL
*========================================================================================
IF it_key_tab IS NOT INITIAL.
LOOP AT it_key_tab ASSIGNING <fs_key_tab>.
CASE <fs_key_tab>-name.
WHEN if_sra020_po_tracking_constant=>cc_po_number.
lv_ponumber = <fs_key_tab>-value.
ENDCASE.
ENDLOOP.
ENDIF.
TRY.
CASE iv_entity_set_name.
WHEN if_sra020_po_tracking_constant=>cc_podetaileddatas.
CALL METHOD lo_api->get_po_details
EXPORTING
iv_item_additional_data = 'X' "#EC NOTEXT
iv_po_number = lv_ponumber
IMPORTING
es_po_details = ls_po_details
et_return = lt_return.
IF NOT lt_return IS INITIAL.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception.
ENDIF.
lt_poitem_details = ls_po_details-poitemdetaildatas.
no_cache( ).
* Return the expanded clauses
APPEND cl_sra020_po_tracking_mpc=>gc_poitemdocflow TO et_expanded_tech_clauses.
APPEND cl_sra020_po_tracking_mpc=>gc_accounting TO et_expanded_tech_clauses.
APPEND cl_sra020_po_tracking_mpc=>gc_pricingconditions TO et_expanded_tech_clauses.
APPEND cl_sra020_po_tracking_mpc=>gc_confirmation TO et_expanded_tech_clauses.
CALL METHOD copy_data_to_ref
EXPORTING
is_data = lt_poitem_details
CHANGING
cr_data = er_entityset.
ENDCASE.
CATCH /iwbep/cx_mgw_busi_exception.
lo_msgcontainer = me->mo_context->get_message_container( ).
LOOP AT lt_return ASSIGNING <fs_return> WHERE type EQ 'E' OR type EQ 'A'. "#EC NOTEXT
IF <fs_return>-id EQ 'SRA020'.
lv_leading_msg = abap_true.
ELSE.
lv_leading_msg = abap_false.
ENDIF.
lo_msgcontainer->add_message(
iv_msg_type = <fs_return>-type
iv_msg_id = <fs_return>-id
iv_msg_number = <fs_return>-number
iv_msg_text = <fs_return>-message
iv_msg_v1 = <fs_return>-message_v1
iv_msg_v2 = <fs_return>-message_v2
iv_msg_v3 = <fs_return>-message_v3
iv_msg_v4 = <fs_return>-message_v4
iv_is_leading_message = lv_leading_msg
).
ENDLOOP.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
EXPORTING
textid = /iwbep/cx_mgw_busi_exception=>business_error
message_container = lo_msgcontainer.
ENDTRY.
ENDMETHOD.
Where
if_sra020_po_tracking_constant=>cc_po_number = PONumber
if_sra020_po_tracking_constant=>cc_podetaileddatas = PODetailedDatas
and PODetailedData entity has navigation properties of POItemDetailDatas,POItems,and POList
I try to call the method from Gateway Service Client by executing
/sap/opu/odata/SAP/SRA020_PO_TRACKING_SRV/PODetailedDatas?$expand=POItemDetailDatas,POItems,POList
However I got status code 400 Bad Request instead. What did I miss?
regards
Edit:
The message in the Bad Request says: Error while reading Purchase Order
edit 2:
association screen shot:
navigation screen shot:
Turns out I have to provide PONumber, so that:
PODetailedDatas(PONumber='4500000039')?$expand=POItems
works fine

Saxonica - .NET API - XQuery - XPDY0002: The context item for axis step root/descendant::xxx is absent

I'm getting same error as this question, but with XQuery:
SaxonApiException: The context item for axis step ./CLIENT is absent
When running from the command line, all is good. So I don't think there is a syntax problem with the XQuery itself. I won't post the input file unless needed.
The XQuery is displayed with a Console.WriteLine before the error appears:
----- Start: XQUERY:
(: FLWOR = For Let Where Order-by Return :)
<MyFlightLegs>
{
for $flightLeg in //FlightLeg
where $flightLeg/DepartureAirport = 'OKC' or $flightLeg/ArrivalAirport = 'OKC'
order by $flightLeg/ArrivalDate[1] descending
return $flightLeg
}
</MyFlightLegs>
----- End : XQUERY:
Error evaluating (<MyFlightLegs {for $flightLeg in root/descendant::FlightLeg[DepartureAirport = "OKC" or ArrivalAirport = "OKC"] ... return $flightLeg}/>) on line 4 column 20
XPDY0002: The context item for axis step root/descendant::FlightLeg is absent
I think that like the other question, maybe my input XML file is not properly specified.
I took the samples/cs/ExamplesHE.cs run method of the XQuerytoStream class.
Code there for easy reference is:
public class XQueryToStream : Example
{
public override string testName
{
get { return "XQueryToStream"; }
}
public override void run(Uri samplesDir)
{
Processor processor = new Processor();
XQueryCompiler compiler = processor.NewXQueryCompiler();
compiler.BaseUri = samplesDir.ToString();
compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
XQueryEvaluator eval = exp.Load();
Serializer qout = processor.NewSerializer();
qout.SetOutputProperty(Serializer.METHOD, "xml");
qout.SetOutputProperty(Serializer.INDENT, "yes");
qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
Console.WriteLine("Output written to testoutput.xml");
eval.Run(qout);
}
}
I changed to pass the Xquery file name, the xml file name, and the output file name, and tried to make a static method out of it. (Had success doing the same with the XSLT processor.)
static void DemoXQuery(string xmlInputFilename, string xqueryInputFilename, string outFilename)
{
// Create a Processor instance.
Processor processor = new Processor();
// Load the source document
DocumentBuilder loader = processor.NewDocumentBuilder();
loader.BaseUri = new Uri(xmlInputFilename);
XdmNode indoc = loader.Build(loader.BaseUri);
XQueryCompiler compiler = processor.NewXQueryCompiler();
//BaseUri is inconsistent with Transform= Processor?
//compiler.BaseUri = new Uri(xqueryInputFilename);
//compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
string xqueryFileContents = File.ReadAllText(xqueryInputFilename);
Console.WriteLine("----- Start: XQUERY:");
Console.WriteLine(xqueryFileContents);
Console.WriteLine("----- End : XQUERY:");
XQueryExecutable exp = compiler.Compile(xqueryFileContents);
XQueryEvaluator eval = exp.Load();
Serializer qout = processor.NewSerializer();
qout.SetOutputProperty(Serializer.METHOD, "xml");
qout.SetOutputProperty(Serializer.INDENT, "yes");
qout.SetOutputStream(new FileStream(outFilename,
FileMode.Create, FileAccess.Write));
eval.Run(qout);
}
Also two questions regarding "BaseURI".
1. Should it be a directory name, or can it be same as the Xquery file name?
2. I get this compile error: "Cannot implicity convert to "System.Uri" to "String".
compiler.BaseUri = new Uri(xqueryInputFilename);
It's exactly the same thing I did for XSLT which worked. But it looks like BaseUri is a string for XQuery, but a real Uri object for XSLT? Any reason for the difference?
You seem to be asking a whole series of separate questions, which are hard to disentangle.
Your C# code appears to be compiling the query
<saxon:example>{static-base-uri()}</saxon:example>
which bears no relationship to the XQuery code you supplied that involves MyFlightLegs.
The MyFlightLegs query uses //FlightLeg and is clearly designed to run against a source document containing a FlightLeg element, but your C# code makes no attempt to supply such a document. You need to add an eval.ContextItem = value statement.
Your second C# fragment creates an input document in the line
XdmNode indoc = loader.Build(loader.BaseUri);
but it doesn't supply it to the query evaluator.
A base URI can be either a directory or a file; resolving relative.xml against file:///my/dir/ gives exactly the same result as resolving it against file:///my/dir/query.xq. By convention, though, the static base URI of the query is the URI of the resource (eg file) containing the source query text.
Yes, there's a lot of inconsistency in the use of strings versus URI objects in the API design. (There's also inconsistency about the spelling of BaseURI versus BaseUri.) Sorry about that; you're just going to have to live with it.
Bottom line solution based on Michael Kay's response; I added this line of code after doing the exp.Load():
eval.ContextItem = indoc;
The indoc object created earlier is what relates to the XML input file to be processed by the XQuery.

How to pass a table key in a function for use in a for loop?

For some reason it doesn't appear to work to pass in a table key as a function argument, what is the trick to do this?
I'm trying to wrap the for loop iteration technique in vanilla Lua into a function that has three arguments: (1) the table to iterate, (2) the table_key to check each time, and (3) the value to find. If a match is found, return it, otherwise return nil.
function table_find_match(table, table_key, match_value)
for i=1, #table do
local this = table[i]
if this[table_key] == match_value then
return this[table_key]
end
end
return nil
end
local table_example = {
{
key_example = "string_value_1"
},
{
key_example = "string_value_2"
}
}
local result = table_find_match(table_example, key_example, "string_value_1")
print(result)
Found a solution, if I pass in the table key as a string it works, such as
table_find_match(table_example, "key_example", "string_value_1")
but I really dislike having to convert it into a string, if anyone knows any other workaround to this please share
If you pass it like table_find_match(table_example, key_example, "string_value_1")
the key_example is now considered as a (nil) variable if not defined before executing, so it has to be like
local key_example = "key_example"
local result = table_find_match(table_example, key_example, "string_value_1")
print(result)

is there aliasing in lua similar to ruby

Can you alias a function (not in a class) in LUA in a similar way to Ruby? In ruby you would do something like this:
alias new_name_for_method method()
def method()
new_name_for_method() # Call original method then do custom code
i = 12 # New code
end
I'm asking because I'm developing for a program that uses LUA scripting and I need to override a function that is declared in a default file.
In Lua, functions are values, treated like any other value (number, string, table, etc.) You can refer to a function value via as many variables as you like.
In your case:
local oldmethod = method
function method(...)
oldmethod(...)
i = 12 -- new code
end
keep in mind that
function method() end
is shorthand for:
method = function() end
function() end just creates a function value, which we assign to the variable method. We could turn around and store that same value in a dozen other variables, or assign a string or number to the method variable. In Lua, variables do not have type, only values do.
More illustration:
print("Hello, World")
donut = print
donut("Hello, World")
t = { foo = { bar = donut } }
t.foo.bar("Hello, World")
assert(t.foo.bar == print) -- same value
FYI, when wrapping a function, if you want its old behavior to be unaffected for now and forever, even if its signature changes, you need to be forward all arguments and return values.
For a pre-hook (new code invoked before the old), this is trivial:
local oldmethod = method
function method(...)
i = 12 -- new code
return oldmethod(...)
end
A post-hook (new code invoked after the old) is a bit more expensive; Lua supports multiple return values and we have to store them all, which requires creating a table:
local oldmethod = method
function method(...)
local return_values = { oldmethod(...) }
i = 12 -- new code
return unpack(return_values)
end
In lua, you can simply override a variable by creating a new function or variable with the same name.
function name_to_override()
print('hi')
end
If you still want to be able to call the old function:
local old_function = name_to_override
function name_to_override()
old_function()
print('hi')
end

Why JAX-WS generates wrapper for all method arguments?

I am trying to generate web service interface using jax-ws, but i am getting a methods with wrapper class for all arguments instead of arguments list. For example:
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
#WebResult(name = "ResendControlsToDmiResponse", targetNamespace = "http://tempuri.org/", partName = "parameters")
#WebMethod(operationName = "ResendControlsToDmi", action = "http://tempuri.org/ResendControlsToDmi")
#Generated(value = "org.apache.cxf.tools.wsdlto.WSDLToJava", date = "2014-01-30T16:01:26.266+02:00")
public ResendControlsToDmiResponse resendControlsToDmi(
#WebParam(partName = "parameters", name = "ResendControlsToDmiData", targetNamespace = "http://tempuri.org/")
ResendControlsToDmiData parameters
);
Can't understand why it's happening and how to generate method with corredct signature.
There rules about the naming of the part elements as they related to the operation name. In your case, it looks like the operation is named resendControlsToDmi, but the incoming data part/element is named ResendControlsToDmiData. Remove the Data off the end of that and it may change. The response element is properly ResendControlsToDmiResponse.

Resources