Convert an iterable object to tuple in python C api - python-3.x

I have an iterable PyObject that I need to pass as the list of arguments to a Python callable, ala
xs = [1,2,5,7]
some_function(*xs)
However, PyObject_CallObject only allows tuples to be passed as the arguments' container.
I'm not sure, though, what is the best way to create a new tuple containing the elements of an iterable. Here's a tentative code:
PyObject* unpack_call(PyObject* callable, PyObject* args) {
PyObject* tuple;
if (PyTuple_Check(args)) {
tuple = args;
} else {
PyObject* iter = PyObject_GetIter(args);
if (!iter) return NULL;
tuple = PyTuple_New(0);
for (Py_ssize_t pos=0; ; ++pos) {
PyObject* arg = PyIter_Next(iter);
if (!arg) break;
PyTuple_SetItem(tuple,pos,arg);
}
}
return PyObject_CallObject(callable,tuple);
}
I'm not sure if I need to grow the size of the tuple myself or not. What's confusing me is the sentence in the documentation saying:
The tuple will always grow or shrink at the end.
I'm also not sure if I need to increment or decrement reference counts for any of these objects.

You're much better using PySequence_Tuple which can create a tuple directly from an iterable. There's probably other similar options to do this too.
If you did want to do it your way then you do need to call PyTuple_Resize each time you add to it (or resize it in chunks possibly). What the sentence
The tuple will always grow or shrink at the end.
tells you is that extra space is at the end of the tuple.
PyTuple_SetItem steals a reference, so you don't need to touch the reference count of the items you're adding. You should be doing some error checking though - PyIter_Next can raise an exception. You also need to decref iter and the tuple when you're done with them.

Related

How can rust safely drop a cpp array through FFI?

I have a array T* which is created like the following
T* array = new T[len];
// Some initialization codes
We know we can delete the array like
delete [] array;
However, I am writing a Rust FFI program with C++. I have sent this array pointer to the Rust part of my code, and I want to delete the code now.
So I can implement a function ffi_delete_array_of_T on the C++ part, and the Rust part code will call the function through FFI, attached with the argument array.
void ffi_delete_array_of_T(void * arr) {
delete [] reinterpret_cast<T *>(arr);
}
However, I already have a function which can delete single element of T.
void ffi_delete_pointer_of_T(void * arr) {
delete reinterpret_cast<T *>(arr);
}
These two functions are so similar that I wonder if I can combined them into one, so I don't need to write two copy.
void ffi_delete_whatever_of_T(void * arr, bool is_array) {
if (is_array)
delete [] reinterpret_cast<T *>(arr);
else
delete reinterpret_cast<T *>(arr);
}
However, I still think the above codes redundant. I wonder if I only give ffi_delete_pointer_of_T, is it possible the Rust do some magic, and have ffi_delete_array_of_T for me?
To the best of my knowledge, it is not possible. C++ can delete [] a array without hint of length, because it has already stored the length of array somewhere when array is allocated. However, the Rust part don't know the actual length of this array.
However, I still wonder if there are some other ways to do that?

How to properly use Iterators w/in Python? Python Beginner

I'm trying to clarify some confusion on the use of __iter__() and __next__() methods. Here's an example provided from the reading:
Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
I'm trying to learn general patterns here, and am confused by myiter = iter(myclass). First the object myclass is created, and belongs to the class MyNumbers. This I understand.
Q: But what's going on with the way myiter is defined? It's a new object myiter set equal to an iter function I don't see defined, and including an entire class as a parameter? How does this work exactly? The reading further suggests these iteration methods to be analogous to __init__ but I don't see the relation. Hows the interpreter exactly go through this code?
Much thank for the time and help.
First of all, let's see the difference between iterable and iterator
In our day-to-day programming life, we use for-loop for often.
In below snippet you see that sampleList is iterable.
sampleList = [5,8,90,1,2]
for num in sampleList:
print num
How the above statement works: (steps involved in for-loop when it's executing)
for-loop gets/receives the iterator
if the iterator has the next item then sets the current index to next available item's index and execute code statement
if the iterator doesn't have the next item break the loop and come out of it
So now we understand that iterator can take action on the next item.
But how much information do we know about the iterator() and iterable() functions?
Iterator:
This contains a method iter() and next()
Here the iterator itself returns iter(). The primary key element to implement for num in sampleList
Iterable:
This contains a method iter(). Here this calls sampleList.iter() to get an iterator.
Now comes the next() definition. difference between the iterable and iterator object is next(). next() has the two action items on it whenever it called.
Update the iterator and point the index to the next item
return the current item.
First off, you're not "passing a classing as an argument". myclass is not a class, it's an instance of the class MyNumbers.
In this case, iter() calls the __iter__() method on thr object you pass, which you defined in the object's class. However, since your __iter__() implementation just returns the object itself, the call to iter() has no effect here.

Injecting key/value into HashMap

I'm trying to generate HashMap object that will have properties and values set from parsed text input. Working fine with simple assigned, but wanted to make it more clever and use inject.
def result = new HashMap();
def buildLog = """
BuildDir:
MSBuildProjectFile:test.csproj
TargetName: test
Compile:
Reference:
""".trim().readLines()*.trim()
buildLog.each {
def (k,v) = it.tokenize(':')
result."${k.trim()}"=v?.trim()
}
println "\nResult:\n${result.collect { k,v -> "\t$k='$v'\n" }.join()}"
generates expected output:
Result:
Reference='null'
MSBuildProjectFile='test.csproj'
BuildDir='null'
TargetName='test'
Compile='null'
after replacing the insides of .each { } closure with injection:
it.tokenize(':').inject({ key, value -> result."${key}" = value?.trim()})
the results generated are missing unset values
Result:
MSBuildProjectFile='test.csproj'
TargetName='test'
Am I doing something wrong, tried with inject ("", {...}) but it seems to push may keys into values.
inject is basically a reduce. The reducing function takes two arguments, the result of the previous iteration or the initial value (e.g. the accumulator) and the next value from the sequence. So it could be made to work, but since you only expect one sequence value, it just convolutes the code.
I do see a great use for collectEntries here, as it allows you to create a Map using either small key/values map, or lists of two elements. And the latter you have:
result = buildLog.collectEntries {
it.split(":",2)*.trim()
}
should work for your code instead of buildLog.each

List iterator not incrementable assertion

The DoCollision function is a callback function which is checking for collisions every frame by iterating over a collider list.
void Collision::DoCollisions(Game *game){
for (ColliderList::const_iterator colliderAIt = colliders_.begin();
colliderAIt != colliders_.end();
colliderAIt++)
{
ColliderList::const_iterator colliderBIt = colliderAIt;
for (++colliderBIt; colliderBIt != colliders_.end(); ++colliderBIt)
{
Collider *colliderA = *colliderAIt;
Collider *colliderB = *colliderBIt;
if (CollisionTest(colliderA, colliderB))
{
game->DoCollision(colliderA->entity, colliderB->entity);
}
}
}
if collision test passes for any two game entities, game entity(Base class for all game objects) class destructor invoke function DestroyCollider which removes the respective collider elements from the list.
void Collision::DestroyCollider(Collider *collider){
colliders_.remove_if(std::bind1st((std::equal_to<Collider *>()), collider));
delete collider }
You're removing the element of a list that the iterator points to. That invalidates the iterator, meaning you're not allowed to use it anymore.
A typical remove loop for a list or vector looks like this:
for (auto iterator = list.begin(); iterator != list.end(); ) {
if (should_remove(iterator)) {
iterator = list.erase(iterator);
} else {
++iterator;
}
}
Note how, if an element is to be removed, the iterator is not incremented, but instead replaced with the result of the erase call.
You will have to find a way to refactor your code to match this pattern. This is complicated because your condition is deep within the collision function, but you can do either that (which has the advantage of making your code more efficient by getting rid of the linear search, by the way), or you can, instead of immediately removing the elements, collect them in a separate list, and then remove them after you're done iterating over the main list.
Or you can turn colliders_ into an intrusive list (e.g. from Boost.Intrusive, or hand-written). Intrusive lists are very good for situations like yours.

EachWithIndex groovy statement

I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.
Are each and eachWithIndex actually methods? If so what are the arguments that they take?
In the groovy documentation there is this certain example:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number
Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?
I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.
These are plain methods but they follow quite a specific pattern - they take a Closure as their last argument. A Closure is a piece of functionality that you can pass around and call when applicable.
For example, method eachWithIndex might look like this (roughly):
void eachWithIndex(Closure operation) {
for (int i = 0; this.hasNext(); i++) {
operation(this.next(), i); // Here closure passed as parameter is being called
}
}
This approach allows one to build generic algorithms (like iteration over items) and change the concrete processing logic at runtime by passing different closures.
Regarding the parameters part, as you see in the example above we call the closure (operation) with two parameters - the current element and current index. This means that the eachWithIndex method expects to receive not just any closure but one which would accept these two parameters. From a syntax prospective one defines the parameters during closure definition like this:
{ elem, index ->
// logic
}
So -> is used to separate arguments part of closure definition from its logic. When a closure takes only one argument, its parameter definition can be omitted and then the parameter will be accessible within the closure's scope with the name it (implicit name for the first argument). For example:
[1,2,3].each {
println it
}
It could be rewritten like this:
[1,2,3].each({ elem ->
println elem
})
As you see the Groovy language adds some syntax sugar to make such constructions look prettier.
each and eachWithIndex are, amongst many others, taking so called Closure as an argument. The closure is just a piece of Groovy code wrapped in {} braces. In the code with array:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" }
there is only one argument (closure, or more precisely: function), please note that in Groovy () braces are sometime optional. num and idx are just an optional aliases for closure (function) arguments, when we need just one argument, this is equivalent (it is implicit name of the first closure argument, very convenient):
def numbers = [ 5, 7, 9, 12 ]
numbers.each {println "$it" }
References:
http://groovy.codehaus.org/Closures
http://en.wikipedia.org/wiki/First-class_function
Normally, if you are using a functional programing language such as Groovy, you would want to avoid using each and eachWithIndex since they encourage you to modify state within the closure or do things that have side effects.
If possible, you may want to do your operations using other groovy collection methods such as .collect or .inject or findResult etc.
However, to use these for your problem, i.e print the list elements with their index, you will need to use the withIndex method on the original collection which will transform the collection to a collection of pairs of [element, index]
For example,
println(['a', 'b', 'c'].withIndex())
EachWithIndex can be used as follows:
package json
import groovy.json.*
import com.eviware.soapui.support.XmlHolder
def project = testRunner.testCase.testSuite.project
def testCase = testRunner.testCase;
def strArray = new String[200]
//Response for a step you want the json from
def response = context.expand('${Offers#Response#$[\'Data\']}').toString()
def json = new JsonSlurper().parseText(response)
//Value you want to compare with in your array
def offername = project.getPropertyValue("Offername")
log.info(offername)
Boolean flagpresent = false
Boolean flagnotpresent = false
strArray = json.Name
def id = 0;
//To find the offername in the array of offers displayed
strArray.eachWithIndex
{
name, index ->
if("${name}" != offername)
{
flagnotpresent= false;
}
else
{
id = "${index}";
flagpresent = true;
log.info("${index}.${name}")
log.info(id)
}
}

Resources