Inner function in Python - python-2.7

def getMessage1(self, id, queueName):
uuid = id
def onMessage(ch, method, properties, body):
if uuid in body:
requeued_messages = self.channel.stop_consuming()
return body
self.channel.basic_consume(consumer_callback = onMessage, queue = queueName, no_ack = True)
self.channel.start_consuming()
return onMessage(ch, method, properties, body)
#global name 'ch' is not defined
I am trying to define two function as shown in the code. I am try to return body to the inner function and I also want to the same body to return to my outer function i.e getMessage1.
But this above code returns me with
"function onMessage at 0x0000000006642128" not the "body"
and also I want my inner function to get the come out of the loop only when the uuid is present in the body.
Returned body is a string
here is the basic_consume function that I am using
def basic_consume(self, consumer_callback,
queue='',
no_ack=False,
exclusive=False,
consumer_tag=None,
arguments=None):
"""Sends the AMQP command Basic.Consume to the broker and binds messages
for the consumer_tag to the consumer callback. If you do not pass in
a consumer_tag, one will be automatically generated for you. Returns
the consumer tag.
For more information on basic_consume, see:
http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume
:param method consumer_callback: The method to callback when consuming
with the signature consumer_callback(channel, method, properties,
body), where
channel: pika.Channel
method: pika.spec.Basic.Deliver
properties: pika.spec.BasicProperties
body: str, unicode, or bytes

In order for getMessage1 to return the body from onMessage, you need to return the call of onMessage. As it stands now, you're returning a function.
Consider these two examples:
def foo():
def bar():
return "This is from Bar"
return bar()
print foo()
Result:
This is from Bar
vs
def foo():
def bar():
return "This is from Bar"
return bar
print foo()
Result:
<function bar at 0x0270E070>

You get the message function onMessage at 0x0000000006642128 because your return statement return onMessage returns the function onMessage without evaluating the results. If you want to evaluate the function you need something like return onMessage(channel, method, properties, body) with the values/variables you want evaluated inside the parentheses. Below is a working example of an inner and outer function:
def sumOfSquares(a,b):
def square(c):
return (c*c)
return square(a)+square(b)
print(sumOfSquares(2,3))
I don't see a loop in either function. Please provide more information on the second part of your question.

Related

readLine(prompt =) use in shiny

Can readLines(prompt = ...) be used in any way in shiny?
Suppose the following: in the server, inside a renderPrint component I will use shinijs::display("takeInput). This GUI component takes input from the user, so I will pass the input to a function by means of the function call. Afterwards, the function calls another function and sends the input to that function. The input will be received and tested by the second function. The result of the test will be returned to the first function which will return it to the server. Please see below:
Is there another way to do this? A simpler way? I do not see the way of doing it by just using readLine(promp = ..) in the second function. I do not see how this can be compatible with shiny.
ui{
selectInput("xxxxx")
verbatimTextOutput(
}
source(program containing functionName)
source(program containing another function name)
functionName <- function(parameters, takeInput){
functionName2 <- anotherFunctionName(parameters, takeInput)
functionName2 <- valueOfFunctionName2
if(functionName2 == xx){
dosomthing
return the value to the server
list(functionName2 = functionName2)
}
anotherFunctionName<- function(parameters, takeInput){
if(takeInput == something){
return the value of anotherFunctionName to functionName which will return it to the server
valueOfFunctionName2
}
}

Modifying an object inside a class leads to an error

I am a beginner in Python and I am trying to understand trees better. Why can't I add nodes inside the function f below? I would expect that the final print returns the value 2 instead of an error that f(test) in None.
class Testcls(object):
def __init__(self,data):
self.data= data
self.children = []
def add_child(self,obj):
self.children.append(obj)
def f(test):
data1 = test.data+1
test.add_child(Testcls(data1))
test = Testcls(1)
print f(test).data
Final print in your case should actually return an error. Function f doesn't return anything (hence the None if you type print f(test). To add children using f you can add a return statement:
def f(test):
data1 = test.data+1
test.add_child(Testcls(data1))
return test
Which now returns the object test which you can further access and process,
f(test)
print test.children[0].data
Since it actually returns the test object you can also call it and use it directly:
print (f(test).children)[0].data
You don't have to have a return statement either - f will still change the object you're sending to it. In case you don't want to return the object, you just need to call the function separately and only then use test like shown in the second code snippet.

Groovy MockFor demands not acting as expected for stream

I wanted to create a unit test verifying that a stream was closed. My class decorates the stream it receives with DataputStream, which seems to break the mocking demands feature.
void testBadMock() {
def mockInputClass = new MockFor(InputStream)
mockInputClass.demand.with {
close() {}
}
def mockInput1 = mockInputClass.proxyInstance()
mockInput1.close()
mockInputClass.verify mockInput1 // passes
def mockInput2 = mockInputClass.proxyInstance()
new DataInputStream(mockInput2).close()
mockInputClass.verify mockInput2 // fails
}
The specific error message:
junit.framework.AssertionFailedError: verify[0]: expected 1..1 call(s) to 'close' but was called 0 time(s).
I checked the source code for DataInputStream, and as expected, the stream passed into the constructor is the object which it delegates the close() method call to.
def fakeInput = [close: {println 'I was called'}] as InputStream
new DataInputStream(fakeInput).close() // prints 'I was called'
I see no reason why my mock object is not seeing the close() method call.
A potential workaround:
def mockInput2 = mockInputClass.proxyInstance()
new DataInputStream([close: { mockInput2.close() }] as InputStream).close()
mockInputClass.verify mockInput2

No such property in Groovy test case

I have a Groovy test class MsgDispatcherTest extends GroovyTestCase.
Within this class there is the following test case:
#Test
void test_register()
{
def d = MsgDispatcher.instance // MsgDispatcher is a singelton
def cb1Called = 0
def cb1 = { cb1Called++; void }
d.registerCallback("msg1", cb1) // closure cb1 should be registered
}
And the interface of MsgDispatcher.registerCallback looks like this:
void registerCallback(String message, Closure callback)
{
assert callback && message
// ...
}
Now when I run this test case I get the following error message on the call to d.registerCallback("msg1", cb1):
groovy.lang.MissingPropertyException: No such property: msg1 for class: ecs.MsgDispatcherTest
Any ideas what I am missing here?
Ok, I found the problem. There was a bug in my registerCallback() method. The issue was that I have tried to access the callback parameter as map (callback[message]), which of course does not work.
That's ok, I understand why this is a problem. However, why is the Groovy compiler error message so cryptic? It was referring not to that problematic line within registerCallback(), but instead to the line where I call that function.

Django calling a function that returns a value doesn't work

I'm having a problem in calling a function that returns a result, from another function
To make it clear, my functions are:
def calculate_questions_vote(request):
useranswer = Answer.objects.filter (answer_by = request.user)
positive_votes = VoteUpAnswer.objects.filter(answer = useranswer)
negative_votes = VoteDownAnswer.objects.filter(answer = useranswer)
question_vote_rank = sum(positive_votes) - sum(negative_votes.count)
return question_vote_rank
def calculate_replies(request):
the_new = News.objects.filter(created_by = request.user)
reply = Reply.objects.filter(reply_to = the_new)
reply_rank = sum(reply)
return reply_rank
and I want to call them in another function, so that it could return a value.
I'm calling the function form another function like this:
rank = calculate_questions_vote
Let's say I just want for now to display the value returned by the function calculate_questions_vote.
Of course, I'm putting the rank variable in the context of the function.
My problem is that my output is:
<function calculate_questions_vote at 0x9420144>
How can I actually make it display the value returned by the function, instead of that string?
This is basic Python. What you are doing is simply referring to the function - assigning the function itself to another variable. To actually call a function, you need to use parenthesis after its name:
calculate_questions_vote()
In your case, you've defined that function as needing the request object, so you need to use that in the call as well:
calculate_questions_vote(request)
you need to pass a request object to calculate_questions_vote like:
rank = calculate_questions_vote(request)