static int __init__(PyObject *self, PyObject *args, PyObject *kwds) { ligolw_RowBuilder *rowbuilder = (ligolw_RowBuilder *) self; rowbuilder->interns = NULL; if(!PyArg_ParseTuple(args, "OO|O", &rowbuilder->rowtype, &rowbuilder->attributes, &rowbuilder->interns)) return -1; Py_INCREF(rowbuilder->rowtype); rowbuilder->attributes = llwtokenizer_build_attributes(rowbuilder->attributes); if(rowbuilder->interns) rowbuilder->interns = PySequence_Tuple(rowbuilder->interns); else rowbuilder->interns = PyTuple_New(0); if(!rowbuilder->attributes || !rowbuilder->interns) return -1; rowbuilder->row = Py_None; Py_INCREF(rowbuilder->row); rowbuilder->i = 0; rowbuilder->iter = NULL; return 0; }
static int PyBobSpIDCT1D_SetShape (PyBobSpIDCT1DObject* self, PyObject* o, void* /*closure*/) { if (!PySequence_Check(o)) { PyErr_Format(PyExc_TypeError, "`%s' shape can only be set using tuples (or sequences), not `%s'", Py_TYPE(self)->tp_name, Py_TYPE(o)->tp_name); return -1; } PyObject* shape = PySequence_Tuple(o); auto shape_ = make_safe(shape); if (PyTuple_GET_SIZE(shape) != 1) { PyErr_Format(PyExc_RuntimeError, "`%s' shape can only be set using 1-position tuples (or sequences), not an %" PY_FORMAT_SIZE_T "d-position sequence", Py_TYPE(self)->tp_name, PyTuple_GET_SIZE(shape)); return -1; } Py_ssize_t len = PyNumber_AsSsize_t(PyTuple_GET_ITEM(shape, 0), PyExc_OverflowError); if (PyErr_Occurred()) return -1; try { self->cxx->setLength(len); } catch (std::exception& ex) { PyErr_SetString(PyExc_RuntimeError, ex.what()); return -1; } catch (...) { PyErr_Format(PyExc_RuntimeError, "cannot reset `shape' of %s: unknown exception caught", Py_TYPE(self)->tp_name); return -1; } return 0; }
static PyObject * pygpgme_context_get_signers(PyGpgmeContext *self) { PyObject *list, *tuple; gpgme_key_t key; int i; list = PyList_New(0); for (i = 0, key = gpgme_signers_enum(self->ctx, 0); key != NULL; key = gpgme_signers_enum(self->ctx, ++i)) { PyObject *item; item = pygpgme_key_new(key); gpgme_key_unref(key); if (item == NULL) { Py_DECREF(list); return NULL; } PyList_Append(list, item); Py_DECREF(item); } tuple = PySequence_Tuple(list); Py_DECREF(list); return tuple; }
/** * Return a string representation of the Key instance. */ static PyObject * key_repr(Key *self) { PyObject *repr = NULL; PyObject *tup = PySequence_Tuple((PyObject *) self); if(tup) { repr = PyObject_Repr(tup); Py_DECREF(tup); } else { if(! (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ValueError))) { return NULL; } PyErr_Clear(); repr = PyString_FromString("(<corrupt>)"); } if(! repr) { return NULL; } const char *repr_s = PyString_AS_STRING(repr); PyObject *out = PyString_FromFormat("acid.Key%s", repr_s); Py_DECREF(repr); return out; }
static PyObject * Affine_subscript(polypaths_planar_overrideAffineObject *self, PyObject *item) { Py_ssize_t i; PyObject *t, *s; assert(polypaths_planar_overrideAffine_Check(self)); if (PyIndex_Check(item)) { i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) { return NULL; } if (i < 0) { i += Affine_len((PyObject *)self); } return Affine_getitem(self, i); } else if (PySlice_Check(item)) { /* We cheat a bit here by constructing a tuple from ourself and slicing that, which is convenient since slicing a transform results in a tuple. Not the most efficient, but I don't expect transform slicing to be a common, performance sensitive operation */ t = PySequence_Tuple((PyObject *)self); if (t == NULL) { return NULL; } s = PyObject_GetItem(t, item); Py_DECREF(t); return s; } PyErr_Format(PyExc_TypeError, "Affine indices must be integers, not %.200s", Py_TYPE(item)->tp_name); return NULL; }
/** * ResultTuple.__reduce__() implementation. * Always returns (tuple, tuple(self)) * Needed so that pickling doesn't depend on our tuple subclass and unpickling * works without it. As a result unpickle will give back in a normal tuple. */ static PyObject * resulttuple_reduce(PyObject *self) { PyObject *tuple = PySequence_Tuple (self); if (tuple == NULL) return NULL; return Py_BuildValue ("(O, (N))", &PyTuple_Type, tuple); }
BOOL PyObject_AsCOORD(PyObject *obcoord, COORD *coord) { PyObject *tpcoord=PySequence_Tuple(obcoord); if (tpcoord==NULL) return FALSE; BOOL bsuccess=PyArg_ParseTuple(tpcoord, "HH", &coord->X, &coord->Y); Py_DECREF(tpcoord); return bsuccess; }
PyObject* rtopArrayToTuple(VALUE rArray) { PyObject *pTuple,*pList; pList = rtopArrayToList(rArray); pTuple = PySequence_Tuple(pList); Py_XDECREF(pList); return pTuple; }
static int DCMultiSphereShapeInit(DCMultiSphereShape *self, PyObject *args, PyObject *kwds) { DKObject<DKMultiSphereShape> shape = NULL; if (self->shape == NULL) { DKASSERT_DEBUG(PyTuple_Check(args)); size_t numItems = PyTuple_GET_SIZE(args); DKArray<DKVector3> centers; DKArray<float> radii; centers.Reserve(numItems); radii.Reserve(numItems); for (size_t i = 0; i < numItems; ++i) { PyObject* obj = PyTuple_GET_ITEM(args, i); PyObject* sphere = PySequence_Tuple(obj); if (sphere == NULL) { PyErr_SetString(PyExc_TypeError, "argument must be sequence object."); return -1; } DKVector3 v; float r; if (!PyArg_ParseTuple(sphere, "O&f", &DCVector3Converter, &v, &r)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "each spere should have center:Vector3, radius:float"); } Py_DECREF(sphere); if (PyErr_Occurred()) return -1; centers.Add(v); radii.Add(r); } DKASSERT_DEBUG(centers.Count() == radii.Count()); if (centers.Count() > 0) { shape = DKOBJECT_NEW DKMultiSphereShape(centers, radii, centers.Count()); self->shape = shape; } else { PyErr_SetString(PyExc_TypeError, "argument must have one or more tuples to describe sphere."); return -1; } } self->base.shape = self->shape; return DCConvexShapeTypeObject()->tp_init((PyObject*)self, args, kwds); }
PyObjectHandle LuaToPythonConverter::convertToTuple(lua_State* L, int index) { fixIndex(L, index); if (auto ref = getOpaqueRef(L, index)) { // Must convert to a Python tuple. PyObjectHandle tup(PySequence_Tuple(ref->obj.get())); checkPythonError(tup, L, "cannot convert to tuple"); return tup; } return convertTupleFromTable(L, index, false); }
// Converts sequence into a tuple and verifies that length fits in length variable PyObject *PyWinSequence_Tuple(PyObject *obseq, DWORD *len) { PyObject *obtuple=PySequence_Tuple(obseq); if (obtuple==NULL) return NULL; Py_ssize_t py_len=PyTuple_GET_SIZE(obtuple); if (py_len > MAXDWORD){ Py_DECREF(obtuple); return PyErr_Format(PyExc_ValueError, "Sequence can contain at most %d items", MAXDWORD); } *len=(DWORD)py_len; return obtuple; }
extern "C" Box* tupleNew(Box* _cls, BoxedTuple* args, BoxedDict* kwargs) { if (!PyType_Check(_cls)) raiseExcHelper(TypeError, "tuple.__new__(X): X is not a type object (%s)", getTypeName(_cls)); BoxedClass* cls = static_cast<BoxedClass*>(_cls); if (!isSubclass(cls, tuple_cls)) raiseExcHelper(TypeError, "tuple.__new__(%s): %s is not a subtype of tuple", getNameOfClass(cls), getNameOfClass(cls)); int args_sz = args->size(); int kwargs_sz = kwargs ? kwargs->d.size() : 0; if (args_sz + kwargs_sz > 1) raiseExcHelper(TypeError, "tuple() takes at most 1 argument (%d given)", args_sz + kwargs_sz); if (args_sz || kwargs_sz) { Box* elements; // if initializing from iterable argument, check common case positional args first if (args_sz) { elements = args->elts[0]; } else { assert(kwargs_sz); auto const seq = *(kwargs->d.begin()); auto const kw = static_cast<BoxedString*>(seq.first.value); if (kw->s() == "sequence") elements = seq.second; else raiseExcHelper(TypeError, "'%s' is an invalid keyword argument for this function", kw->data()); } if (cls == tuple_cls) { // Call PySequence_Tuple since it has some perf special-cases // that can make it quite a bit faster than the generic pyElements iteration: Box* r = PySequence_Tuple(elements); if (!r) throwCAPIException(); return r; } std::vector<Box*, StlCompatAllocator<Box*>> elts; for (auto e : elements->pyElements()) elts.push_back(e); return BoxedTuple::create(elts.size(), &elts[0], cls); } else { if (cls == tuple_cls) return EmptyTuple; return BoxedTuple::create(0, cls); } }
static PyObject * Node_traverse(Node *self, PyObject *args, PyObject *kwargs) { PyObject *f, *nargs, *it, *rc; f = PyTuple_GetItem(args, 0); if (!f) { PyErr_SetString(PyExc_TypeError, "function takes at least 1 argument"); return NULL; } if (!PyCallable_Check(f)) { PyErr_SetString(PyExc_TypeError, "first parameter must be a callable object"); return NULL; } it = PyObject_GetIter(args); nargs = PySequence_Tuple(it); Py_DECREF(it); Py_INCREF(self); if (PyTuple_SetItem(nargs, 0, (PyObject *)self)) goto err; if (!(rc = PyObject_Call(f, nargs, kwargs))) goto err; Py_DECREF(rc); Py_DECREF(nargs); if (NOT_NONE(self->left)) { rc = Node_traverse(self->left, args, kwargs); if (rc) Py_DECREF(rc); else return NULL; } if (NOT_NONE(self->right)) { rc = Node_traverse(self->right, args, kwargs); if (rc) Py_DECREF(rc); else return NULL; } Py_INCREF(Py_None); return Py_None; err: Py_DECREF(nargs); return NULL; }
static PyObject *set_types(PyObject *self, PyObject *sequence) { ligolw_Tokenizer *tokenizer = (ligolw_Tokenizer *) self; Py_ssize_t length, i; /* * Simplify the sequence access. */ sequence = PySequence_Tuple(sequence); if(!sequence) return NULL; length = PyTuple_GET_SIZE(sequence); /* * Free the current internal type list. */ unref_types(tokenizer); /* * Allocate a new internal type list. */ tokenizer->types = malloc(length * sizeof(*tokenizer->types)); if(!tokenizer->types) { Py_DECREF(sequence); return PyErr_NoMemory(); } tokenizer->type = tokenizer->types; tokenizer->types_length = &tokenizer->types[length]; /* * Copy the input sequence's contents into the internal type list. */ for(i = 0; i < length; i++) { tokenizer->types[i] = PyTuple_GET_ITEM(sequence, i); Py_INCREF(tokenizer->types[i]); } /* * Done. */ Py_DECREF(sequence); Py_INCREF(Py_None); return Py_None; }
/* Intern selected string constants */ static int intern_string_constants(PyObject *tuple) { int modified = 0; Py_ssize_t i; for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { PyObject *v = PyTuple_GET_ITEM(tuple, i); if (PyUnicode_CheckExact(v)) { if (PyUnicode_READY(v) == -1) { PyErr_Clear(); continue; } if (all_name_chars(v)) { PyObject *w = v; PyUnicode_InternInPlace(&v); if (w != v) { PyTuple_SET_ITEM(tuple, i, v); modified = 1; } } } else if (PyTuple_CheckExact(v)) { intern_string_constants(v); } else if (PyFrozenSet_CheckExact(v)) { PyObject *w = v; PyObject *tmp = PySequence_Tuple(v); if (tmp == NULL) { PyErr_Clear(); continue; } if (intern_string_constants(tmp)) { v = PyFrozenSet_New(tmp); if (v == NULL) { PyErr_Clear(); } else { PyTuple_SET_ITEM(tuple, i, v); Py_DECREF(w); modified = 1; } } Py_DECREF(tmp); } } return modified; }
static PyObject * tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg = NULL; static char *kwlist[] = {"sequence", 0}; if (type != &PyTuple_Type) return tuple_subtype_new(type, args, kwds); if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) return NULL; if (arg == NULL) return PyTuple_New(0); else return PySequence_Tuple(arg); }
/** * Fetch a slice of the Key. */ static PyObject * key_subscript(Key *self, PyObject *key) { if(PySlice_Check(key)) { // TODO: make this more efficient PyObject *tup = PySequence_Tuple((PyObject *) self); PyObject *slice = NULL; PyObject *newkey = NULL; if(tup) { PyMappingMethods *funcs = tup->ob_type->tp_as_mapping; slice = funcs->mp_subscript((PyObject *) tup, key); Py_DECREF(tup); } if(slice) { newkey = key_new(&KeyType, slice, NULL); Py_DECREF(slice); } return newkey; } else { // Fetch the `i`th item from the Key. Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_OverflowError); if(i == -1 && PyErr_Occurred()) { return NULL; } struct reader rdr; rdr.p = Key_DATA(self); rdr.e = Key_SIZE(self) + rdr.p; int eof = rdr.p == rdr.e; if(i < 0) { // TODO: make this more efficient Py_ssize_t len = key_length(self); i += len; eof |= i < 0; } while(i-- && !eof) { if(acid_skip_element(&rdr, &eof)) { return NULL; } } if(eof) { PyErr_SetString(PyExc_IndexError, "Key index out of range"); return NULL; } return acid_read_element(&rdr); } }
PyObject * PySequence_Fast(PyObject *v, const char *m) { if (v == NULL) return null_error(); if (PyList_Check(v) || PyTuple_Check(v)) { Py_INCREF(v); return v; } v = PySequence_Tuple(v); if (v == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) return type_error(m); return v; }
static PyObject * partial_setstate(partialobject *pto, PyObject *state) { PyObject *fn, *fnargs, *kw, *dict; if (!PyTuple_Check(state) || !PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) || !PyCallable_Check(fn) || !PyTuple_Check(fnargs) || (kw != Py_None && !PyDict_Check(kw))) { PyErr_SetString(PyExc_TypeError, "invalid partial state"); return NULL; } if(!PyTuple_CheckExact(fnargs)) fnargs = PySequence_Tuple(fnargs); else Py_INCREF(fnargs); if (fnargs == NULL) return NULL; if (kw == Py_None) kw = PyDict_New(); else if(!PyDict_CheckExact(kw)) kw = PyDict_Copy(kw); else Py_INCREF(kw); if (kw == NULL) { Py_DECREF(fnargs); return NULL; } if (dict == Py_None) dict = NULL; else Py_INCREF(dict); Py_INCREF(fn); pto->use_fastcall = _PyObject_HasFastCall(fn); Py_SETREF(pto->fn, fn); Py_SETREF(pto->args, fnargs); Py_SETREF(pto->kw, kw); Py_XSETREF(pto->dict, dict); Py_RETURN_NONE; }
BOOL PyObject_AsColorTable(PyObject *obColorTable, COLORREF *ColorTable) { BOOL ret; PyObject *tpColorTable=PySequence_Tuple(obColorTable); if (tpColorTable==NULL) ret=FALSE; else if (PyTuple_GET_SIZE(tpColorTable)!=16){ PyErr_SetString(PyExc_TypeError,"ColorTable object must be a sequence of 16 ints"); ret=FALSE; } else ret=PyArg_ParseTuple(tpColorTable, "kkkkkkkkkkkkkkkk", &ColorTable[0], &ColorTable[1], &ColorTable[2], &ColorTable[3], &ColorTable[4], &ColorTable[5], &ColorTable[6], &ColorTable[7], &ColorTable[8], &ColorTable[9], &ColorTable[10], &ColorTable[11], &ColorTable[12], &ColorTable[13], &ColorTable[14], &ColorTable[15]); Py_DECREF(tpColorTable); return ret; }
/* Convert the set of state numbers into a sorted tuple for use as a * dictionary key. */ static PyObject *make_key(PyObject *state_set) { PyObject *states, *key; states = PyDict_Keys(state_set); if (states == NULL) { return NULL; } if (PyList_Sort(states) < 0) { Py_DECREF(states); return NULL; } key = PySequence_Tuple(states); Py_DECREF(states); if (key == NULL) { return NULL; } return key; }
/** * Converts from camera coordinates to world coordinates. * The arguments to the function are: * 1 - camera coordinates (3-tuple) (xc, yc, zc) * 2 - dictionary of camera parameters * It returns a 2-tuple containing (xw, yw, zw). */ static PyObject* tsai_cc2wc(PyObject *self, PyObject *args) { double xw, yw, zw, xc, yc, zc; PyObject *cc = NULL, *params = NULL, *cc2 = NULL; /* parse arguments */ if (!PyArg_ParseTuple(args, "OO", &cc, ¶ms)) return NULL; if (!PyTuple_Check(cc)) { cc2 = PySequence_Tuple(cc); if (cc2 == NULL) { PyErr_SetString(PyExc_TypeError, "First argument must be a 3-member sequence."); return NULL; } } else { cc2 = cc; Py_INCREF(cc2); } if (!PyArg_ParseTuple(cc2, "ddd", &xc, &yc, &zc)) { PyErr_SetString(PyExc_TypeError, "First argument must be a 3-member sequence."); return NULL; } Py_DECREF(cc2); /* fetch the camera parameter mapping */ if (parse_camera_mapping(params) == 0) return NULL; /* perform the C call */ camera_coord_to_world_coord(xc, yc, zc, &xw, &yw, &zw); /* return the value (xw, yw, zw) */ return Py_BuildValue("ddd", xw, yw, zw); }
/** * Converts from world coordinates to image coordinates. * The arguments to the function are: * 1 - world coordinates (3-tuple) * 2 - dictionary of camera parameters * It returns a 2-tuple containing (Xf, Yf). */ static PyObject* tsai_wc2ic(PyObject *self, PyObject *args) { double xw, yw, zw, Xf, Yf; PyObject *wc = NULL, *params = NULL, *wc2 = NULL; /* parse arguments */ if (!PyArg_ParseTuple(args, "OO", &wc, ¶ms)) return NULL; if (!PyTuple_Check(wc)) { wc2 = PySequence_Tuple(wc); if (wc2 == NULL) { PyErr_SetString(PyExc_TypeError, "First argument must be a 3-member sequence."); return NULL; } } else { wc2 = wc; Py_INCREF(wc2); } if (!PyArg_ParseTuple(wc2, "ddd", &xw, &yw, &zw)) { PyErr_SetString(PyExc_TypeError, "First argument must be a 3-member sequence."); return NULL; } Py_DECREF(wc2); /* fetch the camera parameter mapping */ if (parse_camera_mapping(params) == 0) return NULL; /* perform the C call */ world_coord_to_image_coord(xw, yw, zw, &Xf, &Yf); /* return the value (Xf, Yf) */ return Py_BuildValue("dd", Xf, Yf); }
static PyObject * SpiDev_xfer2(SpiDevObject *self, PyObject *args) { int status; uint16_t delay_usecs = 0; uint32_t speed_hz = 0; uint8_t bits_per_word = 0; uint16_t ii, len; PyObject *obj; PyObject *seq; struct spi_ioc_transfer xfer; Py_BEGIN_ALLOW_THREADS memset(&xfer, 0, sizeof(xfer)); Py_END_ALLOW_THREADS uint8_t *txbuf, *rxbuf; char wrmsg_text[4096]; if (!PyArg_ParseTuple(args, "O|IHB:xfer2", &obj, &speed_hz, &delay_usecs, &bits_per_word)) return NULL; seq = PySequence_Fast(obj, "expected a sequence"); len = PySequence_Fast_GET_SIZE(seq); if (!seq || len <= 0) { PyErr_SetString(PyExc_TypeError, wrmsg_list0); return NULL; } if (len > SPIDEV_MAXPATH) { snprintf(wrmsg_text, sizeof(wrmsg_text) - 1, wrmsg_listmax, SPIDEV_MAXPATH); PyErr_SetString(PyExc_OverflowError, wrmsg_text); return NULL; } Py_BEGIN_ALLOW_THREADS txbuf = malloc(sizeof(__u8) * len); rxbuf = malloc(sizeof(__u8) * len); Py_END_ALLOW_THREADS for (ii = 0; ii < len; ii++) { PyObject *val = PySequence_Fast_GET_ITEM(seq, ii); #if PY_MAJOR_VERSION < 3 if (PyInt_Check(val)) { txbuf[ii] = (__u8)PyInt_AS_LONG(val); } else #endif { if (PyLong_Check(val)) { txbuf[ii] = (__u8)PyLong_AS_LONG(val); } else { snprintf(wrmsg_text, sizeof (wrmsg_text) - 1, wrmsg_val, val); PyErr_SetString(PyExc_TypeError, wrmsg_text); free(txbuf); free(rxbuf); return NULL; } } } if (PyTuple_Check(obj)) { Py_DECREF(seq); seq = PySequence_List(obj); } Py_BEGIN_ALLOW_THREADS xfer.tx_buf = (unsigned long)txbuf; xfer.rx_buf = (unsigned long)rxbuf; xfer.len = len; xfer.delay_usecs = delay_usecs; xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz; xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word; status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer); Py_END_ALLOW_THREADS if (status < 0) { PyErr_SetFromErrno(PyExc_IOError); free(txbuf); free(rxbuf); return NULL; } for (ii = 0; ii < len; ii++) { PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]); PySequence_SetItem(seq, ii, val); } // WA: // in CS_HIGH mode CS isnt pulled to low after transfer // reading 0 bytes doesn't really matter but brings CS down // tomdean: // Stop generating an extra CS except in mode CS_HOGH if (self->mode & SPI_CS_HIGH) status = read(self->fd, &rxbuf[0], 0); Py_BEGIN_ALLOW_THREADS free(txbuf); free(rxbuf); Py_END_ALLOW_THREADS if (PyTuple_Check(obj)) { PyObject *old = seq; seq = PySequence_Tuple(seq); Py_DECREF(old); } return seq; }
:See: `EncoderInterface`"); static PyObject * TDI_SoupEncoderType_starttag(tdi_soup_encoder_t *self, PyObject *args) { PyObject *name, *attr, *closed, *newattr, *attiter, *tmp, *item, *result; tdi_attr_t *attritem; char *cresult; Py_ssize_t size, j, length; int res, is_closed; if (!(PyArg_ParseTuple(args, "SOO", &name, &attr, &closed))) return NULL; /* 1st pass - fixup parameters and count result bytes */ if (!PyString_CheckExact(name)) { if (!(name = PyObject_Str(name))) return NULL; } else Py_INCREF(name); size = PyString_GET_SIZE(name) + 2; /* <> */ if ((is_closed = PyObject_IsTrue(closed)) == -1) { Py_DECREF(name); return NULL; } else if (is_closed) { size += 2; } if (!(attiter = PyObject_GetIter(attr))) { Py_DECREF(name); return NULL; } newattr = PyList_New(0); while ((tmp = PyIter_Next(attiter))) { item = PySequence_Tuple(tmp); Py_DECREF(tmp); if (!item) break; if (PyTuple_GET_SIZE(item) != 2) { Py_DECREF(item); PyErr_SetString(PyExc_TypeError, "Expected Sequence of length 2"); break; } tmp = PyTuple_GET_ITEM(item, 0); if (PyString_CheckExact(tmp)) Py_INCREF(tmp); else if (PyString_Check(tmp)) { if (!(tmp = PyObject_Str(tmp))) { Py_DECREF(item); break; } } else { Py_DECREF(item); PyErr_SetString(PyExc_ValueError, "Attribute key is not a string"); break; } size += PyString_GET_SIZE(tmp) + 1; /* ' ' */ attritem = (tdi_attr_t *)tdi_attr_new(tmp, Py_None); Py_DECREF(tmp); if (!attritem) { Py_DECREF(item); break; } tmp = PyTuple_GET_ITEM(item, 1); if (tmp != Py_None) { if (PyString_CheckExact(tmp)) { Py_INCREF(tmp); Py_DECREF(Py_None); attritem->value = tmp; } else if (PyString_Check(tmp)) { if (!(attritem->value = PyObject_Str(tmp))) { attritem->value = Py_None; break; } Py_DECREF(Py_None); } else { Py_DECREF(item); PyErr_SetString(PyExc_ValueError, "Attribute value is neither a string nor None"); break; } size += PyString_GET_SIZE(attritem->value) + 1; /* '=' */ } Py_DECREF(item); res = PyList_Append(newattr, (PyObject *)attritem); Py_DECREF(attritem); if (res == -1) break; } Py_DECREF(attiter); if (PyErr_Occurred()) { Py_DECREF(newattr); Py_DECREF(name); return NULL; } /* 2nd pass: assemble result */ if (!(result = PyString_FromStringAndSize(NULL, size))) { Py_DECREF(newattr); Py_DECREF(name); return NULL; } cresult = PyString_AS_STRING(result); *cresult++ = '<'; size = PyString_GET_SIZE(name); (void)memcpy(cresult, PyString_AS_STRING(name), (size_t)size); cresult += size; Py_DECREF(name); length = PyList_GET_SIZE(newattr); for (j = 0; j < length; ++j) { attritem = (tdi_attr_t *)PyList_GET_ITEM(newattr, j); *cresult++ = ' '; size = PyString_GET_SIZE(attritem->key); (void)memcpy(cresult, PyString_AS_STRING(attritem->key), (size_t)size); cresult += size; if (attritem->value != Py_None) { *cresult++ = '='; size = PyString_GET_SIZE(attritem->value); (void)memcpy(cresult, PyString_AS_STRING(attritem->value), (size_t)size); cresult += size; } } Py_DECREF(newattr); if (is_closed) { *cresult++ = ' '; *cresult++ = '/'; } *cresult = '>'; return result; }
CString CGenethonDoc::runTest2(PyObject *pModule, CString& function) { CString output = CString(); CString format = CString(); PyObject *pDict, *pFunc; PyObject *pValue, *pArgTuple; PyObject *ptype, *pvalue, *ptraceback; int i; // Set the path to include the current directory in case the module is located there. Found from // http://stackoverflow.com/questions/7624529/python-c-api-doesnt-load-module // and http://stackoverflow.com/questions/7283964/embedding-python-into-c-importing-modules if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, function); //Get the function by its name // pFunc is a new reference if (pFunc && PyCallable_Check(pFunc)) { //Set up a tuple that will contain the function arguments. In this case, the //function requires two tuples, so we set up a tuple of size 2. pArgTuple = PyTuple_New(2); PyObject* s1 = PySequence_Tuple(PyUnicode_FromString("ASBSDBASJBB")); PyObject* s2 = PySequence_Tuple(PyUnicode_FromString("ASHADKBBJSS")); PyObject* s3 = PySequence_Tuple(PyUnicode_FromString("ABSFDHSGJAS")); PyObject* a = PyTuple_Pack(3, s1, s2, s3); PyTuple_SetItem(pArgTuple, 0, a); // color matrix PyObject *l = PyList_New(3); for (size_t i = 0; i<3; i++) { PyObject *li = PyList_New(11); for (size_t j = 0; j < 11; j++) { pValue = PyLong_FromLong(0); PyList_SetItem(li, j, pValue); } PyList_SetItem(l, i, li); } // PyObject *av = Py_BuildValue("(O)", l); PyTuple_SetItem(pArgTuple, 1, l); //Call the python function pValue = PyObject_CallObject(pFunc, pArgTuple); for (size_t i = 0; i<3; i++) { PyObject *li = PyList_GetItem(l, i); output.Append("["); for (size_t j = 0; j < 11; j++) { PyObject *pListV = PyList_GetItem(li, j); long lon = PyLong_AsLong(pListV); format.Format("%ld,", lon); output.Append(format.GetString()); // Py_DECREF(pListV); } output.Append("]\n"); // Py_DECREF(li); } // Py_DECREF(l); // Py_DECREF(s1); // Py_DECREF(s2); // Py_DECREF(s3); // Py_DECREF(a); if (pValue != NULL) { PyObject* v = PyObject_GetAttrString(pModule, "richTextOutput"); // output.Format("Result of call: %ld", PyLong_AsLong(pValue)); Py_DECREF(pValue); } //Some error catching else { Py_DECREF(pFunc); Py_DECREF(pModule); return handlePyError(); } } else { if (PyErr_Occurred()) { return handlePyError(); } } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { return handlePyError(); } return output; }
// Convert Python lists to CvMat * CvArr * PySequence_to_CvArr (PyObject * obj) { int dims [CV_MAX_DIM] = { 1, 1, 1}; PyObject * container[CV_MAX_DIM+1] = {NULL, NULL, NULL, NULL}; int ndim = 0; PyObject * item = Py_None; // TODO: implement type detection - currently we create CV_64F only // scan full array to // - figure out dimensions // - check consistency of dimensions // - find appropriate data-type and signedness // enum NEEDED_DATATYPE { NEEDS_CHAR, NEEDS_INTEGER, NEEDS_FLOAT, NEEDS_DOUBLE }; // NEEDED_DATATYPE needed_datatype = NEEDS_CHAR; // bool needs_sign = false; // scan first entries to find out dimensions for (item = obj, ndim = 0; PySequence_Check (item) && ndim <= CV_MAX_DIM; ndim++) { dims [ndim] = PySequence_Size (item); container [ndim] = PySequence_GetItem (item, 0); item = container[ndim]; } // in contrast to PyTuple_GetItem, PySequence_GetItame returns a NEW reference if (container[0]) { Py_DECREF (container[0]); } if (container[1]) { Py_DECREF (container[1]); } if (container[2]) { Py_DECREF (container[2]); } if (container[3]) { Py_DECREF (container[3]); } // it only makes sense to support 2 and 3 dimensional data at this time if (ndim < 2 || ndim > 3) { PyErr_SetString (PyExc_TypeError, "Nested sequences should have 2 or 3 dimensions"); return NULL; } // also, the number of channels should match what's typical for OpenCV if (ndim == 3 && (dims[2] < 1 || dims[2] > 4)) { PyErr_SetString (PyExc_TypeError, "Currently, the third dimension of CvMat only supports 1 to 4 channels"); return NULL; } // CvMat CvMat * matrix = cvCreateMat (dims[0], dims[1], CV_MAKETYPE (CV_64F, dims[2])); for (int y = 0; y < dims[0]; y++) { PyObject * rowobj = PySequence_GetItem (obj, y); // double check size if (PySequence_Check (rowobj) && PySequence_Size (rowobj) == dims[1]) { for (int x = 0; x < dims[1]; x++) { PyObject * colobj = PySequence_GetItem (rowobj, x); if (dims [2] > 1) { if (PySequence_Check (colobj) && PySequence_Size (colobj) == dims[2]) { PyObject * tuple = PySequence_Tuple (colobj); double a, b, c, d; if (PyArg_ParseTuple (colobj, "d|d|d|d", &a, &b, &c, &d)) { cvSet2D (matrix, y, x, cvScalar (a, b, c, d)); } else { PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float"); cvReleaseMat (& matrix); Py_DECREF (tuple); Py_DECREF (colobj); Py_DECREF (rowobj); return NULL; } Py_DECREF (tuple); } else { PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries"); cvReleaseMat (& matrix); Py_DECREF (colobj); Py_DECREF (rowobj); return NULL; } } else { if (PyFloat_Check (colobj) || PyInt_Check (colobj)) { cvmSet (matrix, y, x, PyFloat_AsDouble (colobj)); } else { PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float"); cvReleaseMat (& matrix); Py_DECREF (colobj); Py_DECREF (rowobj); return NULL; } } Py_DECREF (colobj); } } else { PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries"); cvReleaseMat (& matrix); Py_DECREF (rowobj); return NULL; } Py_DECREF (rowobj); } return matrix; }
Tuple List::asTuple() const { return Tuple(NewReference(PySequence_Tuple(mPtr))); }
/** * Parses calibration data. The calibration data should be in the form of a * sequence of sequences. eg: * [ * [ xs, ys, zs, xi, yi ], ... * ] * where (xs, ys, zs) are the coordinates of a point in 3D space, and (xi, yi) * are the coordinates of the corresponding point in an image. * * If the method fails, it returns NULL and raises an appropriate exception. * On success, a flat array of doubles will be PyMem_Malloc()'d and filled * with the calibration data: * { xs1, ys1, zs1, xi1, yi1, xs2, ys2, zs2, xi2, yi2, ... } * size will be populated with the number of calibration points. */ static double* parse_calibration_data(PyObject *pyobj, int *size) { PyObject *subseq = NULL, *sstuple = NULL; int i = 0, ncoords = 0, index = 0; double *array = NULL, xs, ys, zs, xi, yi; /* check that pyobj is a sequence, and find out its size */ if (PySequence_Check(pyobj) == 0) { PyErr_SetString(PyExc_TypeError, "First argument must be a sequence of coordinate " \ "sequences."); return NULL; } ncoords = PySequence_Size(pyobj); *size = ncoords; /* allocate memory */ array = PyMem_Malloc(sizeof(double) * ncoords * 5); if (array == NULL) return NULL; /* iterate over each sub-sequence within pyobj, performing appropriate * checks and fetching data. */ for (i = 0; i < ncoords; i++) { subseq = PySequence_GetItem(pyobj, i); if (PySequence_Check(subseq) == 0) { Py_DECREF(subseq); PyMem_Free(array); PyErr_SetString(PyExc_TypeError, "First argument must be a sequence of " \ "coordinate sequences."); return NULL; } sstuple = PySequence_Tuple(subseq); Py_DECREF(subseq); if (sstuple == NULL) { Py_DECREF(sstuple); PyMem_Free(array); PyErr_SetString(PyExc_TypeError, "First argument must be a sequence of " \ "coordinate sequences."); return NULL; } if (!PyArg_ParseTuple(sstuple, "ddddd", &xs, &ys, &zs, &xi, &yi)) { Py_DECREF(sstuple); PyMem_Free(array); PyErr_SetString(PyExc_TypeError, "First argument's coordinate sequences must " \ "contain 5 elements each: [x,y,z,xi,yi]"); return NULL; } array[index++] = xs; array[index++] = ys; array[index++] = zs; array[index++] = xi; array[index++] = yi; /* printf("xs = %f, ys = %f, zs = %f, xi = %f, yi = %f\n", xs, ys, zs, xi, yi); */ Py_DECREF(sstuple); } return array; }
static PyObject * resource_setrlimit(PyObject *self, PyObject *args) { struct rlimit rl; int resource; PyObject *limits, *curobj, *maxobj; if (!PyArg_ParseTuple(args, "iO:setrlimit", &resource, &limits)) return NULL; if (resource < 0 || resource >= RLIM_NLIMITS) { PyErr_SetString(PyExc_ValueError, "invalid resource specified"); return NULL; } limits = PySequence_Tuple(limits); if (!limits) /* Here limits is a borrowed reference */ return NULL; if (PyTuple_GET_SIZE(limits) != 2) { PyErr_SetString(PyExc_ValueError, "expected a tuple of 2 integers"); goto error; } curobj = PyTuple_GET_ITEM(limits, 0); maxobj = PyTuple_GET_ITEM(limits, 1); #if !defined(HAVE_LARGEFILE_SUPPORT) rl.rlim_cur = PyLong_AsLong(curobj); if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) goto error; rl.rlim_max = PyLong_AsLong(maxobj); if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) goto error; #else /* The limits are probably bigger than a long */ rl.rlim_cur = PyLong_AsLongLong(curobj); if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) goto error; rl.rlim_max = PyLong_AsLongLong(maxobj); if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) goto error; #endif rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; rl.rlim_max = rl.rlim_max & RLIM_INFINITY; if (setrlimit(resource, &rl) == -1) { if (errno == EINVAL) PyErr_SetString(PyExc_ValueError, "current limit exceeds maximum limit"); else if (errno == EPERM) PyErr_SetString(PyExc_ValueError, "not allowed to raise maximum limit"); else PyErr_SetFromErrno(ResourceError); goto error; } Py_DECREF(limits); Py_INCREF(Py_None); return Py_None; error: Py_DECREF(limits); return NULL; }