本文整理汇总了C++中PyList_SetItem函数的典型用法代码示例。如果您正苦于以下问题:C++ PyList_SetItem函数的具体用法?C++ PyList_SetItem怎么用?C++ PyList_SetItem使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyList_SetItem函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: switch
/*static*/
PyObject * PythonScript::VariantToPython(const QVariant & v)
{
int i;
QVariantList::const_iterator iList;
QVariantList list;
#if QT_VERSION >= 0x040500
QVariantHash::const_iterator iHash;
QVariantHash hash;
#endif
QVariantMap::const_iterator iMap;
QVariantMap map;
PyObject * pyList, * pyDict;
if (v.isNull()) Py_RETURN_NONE;
switch ((QMetaType::Type)v.type()) {
case QVariant::Double:
return Py_BuildValue("d", v.toDouble());
case QVariant::Bool:
if (v.toBool()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
case QVariant::Int:
return Py_BuildValue("i", v.toInt());
case QVariant::LongLong:
return Py_BuildValue("L", v.toLongLong());
case QVariant::UInt:
return Py_BuildValue("I", v.toUInt());
case QVariant::ULongLong:
return Py_BuildValue("K", v.toULongLong());
case QVariant::Char:
case QVariant::String:
#ifdef Py_UNICODE_WIDE
{
QVector<uint> tmp = v.toString().toUcs4();
return Py_BuildValue("u#", tmp.constData(), tmp.count());
}
#else
return Py_BuildValue("u", v.toString().constData());
#endif
case QVariant::List:
case QVariant::StringList:
list = v.toList();
pyList = PyList_New(list.size());
for (i = 0, iList = list.begin(); iList != list.end(); ++iList, ++i) {
PyList_SetItem(pyList, i, PythonScript::VariantToPython(*iList));
}
return pyList;
#if QT_VERSION >= 0x040500
case QVariant::Hash:
hash = v.toHash();
pyDict = PyDict_New();
for (iHash = hash.begin(); iHash != hash.end(); ++iHash) {
PyDict_SetItemString(pyDict, qPrintable(iHash.key()), PythonScript::VariantToPython(iHash.value()));
}
return pyDict;
#endif
case QVariant::Map:
map = v.toMap();
pyDict = PyDict_New();
for (iMap = map.begin(); iMap != map.end(); ++iMap) {
PyDict_SetItemString(pyDict, qPrintable(iMap.key()), PythonScript::VariantToPython(iMap.value()));
}
return pyDict;
case QMetaType::QObjectStar:
return PythonScript::QObjectToPython(v.value<QObject*>());
#if QT_VERSION < 0x050000
case QMetaType::QWidgetStar:
return PythonScript::QObjectToPython(qobject_cast<QObject*>(v.value<QWidget*>()));
#endif
default:
PyErr_Format(PyExc_TypeError, qPrintable(tr("the type %s is currently not supported")), v.typeName());
return NULL;
}
Py_RETURN_NONE;
}
示例2: batch_get_cb
/**
*******************************************************************************************************
* This callback will be called with the results with aerospike_batch_get().
*
* @param results An array of n as_batch_read entries
* @param n The number of results from the batch request
* @param udata The return value to be filled with result of
* get_many()
*
* Returns boolean value(true or false).
*******************************************************************************************************
*/
static bool batch_get_cb(const as_batch_read* results, uint32_t n, void* udata)
{
// Typecast udata back to PyObject
LocalData *data = (LocalData *) udata;
PyObject * py_recs = data->py_recs;
// Initialize error object
as_error err;
as_error_init(&err);
// Lock Python State
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
/*// Typecast udata back to PyObject
PyObject * py_recs = (PyObject *) udata;
// Initialize error object
as_error err;
as_error_init(&err);*/
// Loop over results array
for (uint32_t i = 0; i < n; i++) {
PyObject * rec = NULL;
PyObject * py_rec = NULL;
PyObject * p_key = NULL;
p_key = PyTuple_New(4);
py_rec = PyTuple_New(3);
if (results[i].key->ns && strlen(results[i].key->ns) > 0) {
PyTuple_SetItem(p_key, 0, PyString_FromString(results[i].key->ns));
}
if (results[i].key->set && strlen(results[i].key->set) > 0) {
PyTuple_SetItem(p_key, 1, PyString_FromString(results[i].key->set));
}
if (results[i].key->valuep) {
switch (((as_val*) (results[i].key->valuep))->type) {
case AS_INTEGER:
PyTuple_SetItem(p_key, 2,
PyInt_FromLong(
(long) results[i].key->value.integer.value));
break;
case AS_STRING:
PyTuple_SetItem(p_key, 2,
PyString_FromString(
(const char *) results[i].key->value.string.value));
break;
default:
break;
}
} else {
Py_INCREF(Py_None);
PyTuple_SetItem(p_key, 2, Py_None);
}
if (results[i].key->digest.init) {
PyTuple_SetItem(p_key, 3, PyByteArray_FromStringAndSize((char *) results[i].key->digest.value, AS_DIGEST_VALUE_SIZE));
}
PyTuple_SetItem(py_rec, 0, p_key);
// Check record status
if (results[i].result == AEROSPIKE_OK) {
record_to_pyobject(data->client, &err, &results[i].record,
results[i].key, &rec);
PyObject *py_obj = PyTuple_GetItem(rec, 1);
Py_INCREF(py_obj);
PyTuple_SetItem(py_rec, 1, py_obj);
py_obj = PyTuple_GetItem(rec, 2);
Py_INCREF(py_obj);
PyTuple_SetItem(py_rec, 2, py_obj);
// Set return value in return Dict
if (PyList_SetItem(py_recs, i, py_rec)) {
// Release Python State
PyGILState_Release(gstate);
return false;
}
Py_DECREF(rec);
} else if (results[i].result == AEROSPIKE_ERR_RECORD_NOT_FOUND) {
Py_INCREF(Py_None);
PyTuple_SetItem(py_rec, 1, Py_None);
Py_INCREF(Py_None);
PyTuple_SetItem(py_rec, 2, Py_None);
//.........这里部分代码省略.........
示例3: MagFieldLineSegArray
static PyObject* MagFieldLineSegArray(PyObject *self,PyObject *args)
{
// As an argument I am expecting first a list of LineSegs of the form
// [[[xs,ys,zs],[xe,ye,ze]],...] which describe the coil
// I am then expecting a list of Vectors of the form [[x,y,z],...]
// which describe the fieldpoints
// The returned value will be a list of field vectors of the form [[x,y,z,mag2],...]
//double x,y,z;
Vector A;
Vector B;
int i;//,tmpint;
PyObject *SegList;
PyObject *tmpSeg;
PyObject *start,*end;
// PyObject *p_Seg;
LineSeg tempseg;
int numsegs;
LineSeg* segs;
PyObject *FieldPoints;
PyObject *p_point;
int numpoints;
Vector *points;
Vector *Bfield;
PyObject *result; // the magnetic field in [[x,y,z,mag2],...] format
PyObject *elem; // [x,y,z,mag2]
// Find the SegList and FieldPoints lists in Python Format
if (!PyArg_ParseTuple(args, "OO", &SegList,&FieldPoints))
return NULL;
// Convert SegList from python format to segs in C format
numsegs=PySequence_Size(SegList);
segs=malloc(numsegs*sizeof(LineSeg));
//printf("numsegs %d\n",numsegs);
for(i=0;i<numsegs;i++)
{
tmpSeg=PySequence_GetItem(SegList,i);
if(PySequence_Size(tmpSeg) != 2)
{printf("Invalid Seg Format \n"); return NULL;}
start=PySequence_GetItem(tmpSeg,0);
A.coords[0]=PyFloat_AsDouble(PySequence_GetItem(start,0));
A.coords[1]=PyFloat_AsDouble(PySequence_GetItem(start,1));
A.coords[2]=PyFloat_AsDouble(PySequence_GetItem(start,2));
end=PySequence_GetItem(tmpSeg,1);
B.coords[0]=PyFloat_AsDouble(PySequence_GetItem(end,0));
B.coords[1]=PyFloat_AsDouble(PySequence_GetItem(end,1));
B.coords[2]=PyFloat_AsDouble(PySequence_GetItem(end,2));
tempseg = linesegGenerate(A,B);
segs[i]=tempseg;
}
// Convert FieldPoints from python format to points in C format
numpoints=PySequence_Size(FieldPoints);
points=malloc(numpoints*sizeof(Vector));
//printf("numpoints %d\n",numpoints);
for(i=0;i<numpoints;i++)
{
p_point=PySequence_GetItem(FieldPoints,i);
if(PySequence_Size(p_point) != 3)
{printf("Invalid fieldpoint format\n"); return NULL;}
A.coords[0]=PyFloat_AsDouble(PySequence_GetItem(p_point,0));
A.coords[1]=PyFloat_AsDouble(PySequence_GetItem(p_point,1));
A.coords[2]=PyFloat_AsDouble(PySequence_GetItem(p_point,2));
points[i]=A;
}
//printf("I parsed the arguments\n");
// do the work
//printf("About to Start the Magnetic Field Kernel\n");
Bfield=MagFieldLineSegArray_BACKEND(segs,numsegs,
points,numpoints);
//printf("Finished computing the Field, returning result to Python\n");
// Convert the Bfield from C format to Python format and add the mag2
result=PyList_New(numpoints);
for(i=0;i<numpoints;i++)
{
B=Bfield[i];
//printf("Bfield[i].x %g\n",B.x);
elem=PyList_New(4);
PyList_SetItem(elem,0,PyFloat_FromDouble(B.coords[0]));
PyList_SetItem(elem,1,PyFloat_FromDouble(B.coords[1]));
PyList_SetItem(elem,2,PyFloat_FromDouble(B.coords[2]));
PyList_SetItem(elem,3,PyFloat_FromDouble(B.coords[0]*B.coords[0]+B.coords[1]*B.coords[1]+B.coords[2]*B.coords[2]));
PyList_SetItem(result,i,elem);
}
// Return
return result;
}
示例4: strwicmp
static PyObject *py_lp_ctx_get_helper(struct loadparm_context *lp_ctx, const char *service_name, const char *param_name)
{
struct parm_struct *parm = NULL;
void *parm_ptr = NULL;
int i;
if (service_name != NULL && strwicmp(service_name, GLOBAL_NAME) &&
strwicmp(service_name, GLOBAL_NAME2)) {
struct loadparm_service *service;
/* its a share parameter */
service = lpcfg_service(lp_ctx, service_name);
if (service == NULL) {
return NULL;
}
if (strchr(param_name, ':')) {
/* its a parametric option on a share */
const char *type = talloc_strndup(lp_ctx, param_name,
strcspn(param_name, ":"));
const char *option = strchr(param_name, ':') + 1;
const char *value;
if (type == NULL || option == NULL) {
return NULL;
}
value = lpcfg_get_parametric(lp_ctx, service, type, option);
if (value == NULL) {
return NULL;
}
return PyString_FromString(value);
}
parm = lpcfg_parm_struct(lp_ctx, param_name);
if (parm == NULL || parm->p_class == P_GLOBAL) {
return NULL;
}
parm_ptr = lpcfg_parm_ptr(lp_ctx, service, parm);
} else if (strchr(param_name, ':')) {
/* its a global parametric option */
const char *type = talloc_strndup(lp_ctx,
param_name, strcspn(param_name, ":"));
const char *option = strchr(param_name, ':') + 1;
const char *value;
if (type == NULL || option == NULL) {
return NULL;
}
value = lpcfg_get_parametric(lp_ctx, NULL, type, option);
if (value == NULL)
return NULL;
return PyString_FromString(value);
} else {
/* its a global parameter */
parm = lpcfg_parm_struct(lp_ctx, param_name);
if (parm == NULL) {
return NULL;
}
parm_ptr = lpcfg_parm_ptr(lp_ctx, NULL, parm);
}
if (parm == NULL || parm_ptr == NULL) {
return NULL;
}
/* construct and return the right type of python object */
switch (parm->type) {
case P_CHAR:
return PyString_FromFormat("%c", *(char *)parm_ptr);
case P_STRING:
case P_USTRING:
return PyString_FromString(*(char **)parm_ptr);
case P_BOOL:
return PyBool_FromLong(*(bool *)parm_ptr);
case P_BOOLREV:
return PyBool_FromLong(!(*(bool *)parm_ptr));
case P_INTEGER:
case P_OCTAL:
case P_BYTES:
return PyLong_FromLong(*(int *)parm_ptr);
case P_ENUM:
for (i=0; parm->enum_list[i].name; i++) {
if (*(int *)parm_ptr == parm->enum_list[i].value) {
return PyString_FromString(parm->enum_list[i].name);
}
}
return NULL;
case P_CMDLIST:
case P_LIST:
{
int j;
const char **strlist = *(const char ***)parm_ptr;
PyObject *pylist;
if(strlist == NULL) {
return PyList_New(0);
}
pylist = PyList_New(str_list_length(strlist));
for (j = 0; strlist[j]; j++)
PyList_SetItem(pylist, j,
PyString_FromString(strlist[j]));
return pylist;
}
//.........这里部分代码省略.........
示例5: talloc_new
/*
return the list of interface IPs we have configured
takes an loadparm context, returns a list of IPs in string form
Does not return addresses on 127.0.0.0/8
*/
static PyObject *py_interface_ips(PyObject *self, PyObject *args)
{
PyObject *pylist;
int count;
TALLOC_CTX *tmp_ctx;
PyObject *py_lp_ctx;
struct loadparm_context *lp_ctx;
struct interface *ifaces;
int i, ifcount;
int all_interfaces = 1;
if (!PyArg_ParseTuple(args, "O|i", &py_lp_ctx, &all_interfaces))
return NULL;
tmp_ctx = talloc_new(NULL);
if (tmp_ctx == NULL) {
PyErr_NoMemory();
return NULL;
}
lp_ctx = lpcfg_from_py_object(tmp_ctx, py_lp_ctx);
if (lp_ctx == NULL) {
talloc_free(tmp_ctx);
return NULL;
}
load_interface_list(tmp_ctx, lp_ctx, &ifaces);
count = iface_list_count(ifaces);
/* first count how many are not loopback addresses */
for (ifcount = i = 0; i<count; i++) {
const char *ip = iface_list_n_ip(ifaces, i);
if (all_interfaces) {
ifcount++;
continue;
}
if (iface_list_same_net(ip, "127.0.0.1", "255.0.0.0")) {
continue;
}
if (iface_list_same_net(ip, "169.254.0.0", "255.255.0.0")) {
continue;
}
if (iface_list_same_net(ip, "::1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")) {
continue;
}
if (iface_list_same_net(ip, "fe80::", "ffff:ffff:ffff:ffff::")) {
continue;
}
ifcount++;
}
pylist = PyList_New(ifcount);
for (ifcount = i = 0; i<count; i++) {
const char *ip = iface_list_n_ip(ifaces, i);
if (all_interfaces) {
PyList_SetItem(pylist, ifcount, PyString_FromString(ip));
ifcount++;
continue;
}
if (iface_list_same_net(ip, "127.0.0.1", "255.0.0.0")) {
continue;
}
if (iface_list_same_net(ip, "169.254.0.0", "255.255.0.0")) {
continue;
}
if (iface_list_same_net(ip, "::1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")) {
continue;
}
if (iface_list_same_net(ip, "fe80::", "ffff:ffff:ffff:ffff::")) {
continue;
}
PyList_SetItem(pylist, ifcount, PyString_FromString(ip));
ifcount++;
}
talloc_free(tmp_ctx);
return pylist;
}
示例6: AerospikePredicates_GeoContains_Point
static PyObject * AerospikePredicates_GeoContains_Point(PyObject * self, PyObject * args)
{
PyObject * py_bin = NULL;
PyObject * py_lat = NULL;
PyObject * py_long = NULL;
PyObject * py_geo_object = NULL;
PyObject * py_shape = NULL;
PyObject * py_indexType = NULL;
as_error err;
as_error_init(&err);
py_geo_object = PyDict_New();
if (PyArg_ParseTuple(args, "OOO|O:geo_contains_point",
&py_bin, &py_lat, &py_long, &py_indexType) == false) {
goto CLEANUP;
}
if (py_indexType == NULL) {
py_indexType = Py_BuildValue("i", AS_INDEX_TYPE_DEFAULT);
}
PyObject *py_point = PyString_FromString("Point");
PyDict_SetItemString(py_geo_object, "type", py_point);
Py_DECREF(py_point);
if (PyString_Check(py_bin) && (PyFloat_Check(py_lat) || PyInt_Check(py_lat)) && (PyFloat_Check(py_long) || PyInt_Check(py_long))) {
PyObject * py_list = PyList_New(2);
PyList_SetItem(py_list, 0, py_lat);
PyList_SetItem(py_list, 1, py_long);
PyDict_SetItemString(py_geo_object, "coordinates", py_list);
py_shape = AerospikeGeospatial_DoDumps(py_geo_object, &err);
if (!py_shape) {
as_error_update(&err, AEROSPIKE_ERR_CLIENT, "Unable to call dumps function");
goto CLEANUP;
}
} else {
as_error_update(&err, AEROSPIKE_ERR_PARAM, "Latitude and longitude should be integer or double type, bin of string type");
goto CLEANUP;
}
return Py_BuildValue("iiOOO", AS_PREDICATE_RANGE, AS_INDEX_GEO2DSPHERE, py_bin, py_shape, Py_None, py_indexType);
CLEANUP:
// If an error occurred, tell Python.
if (err.code != AEROSPIKE_OK) {
PyObject * py_err = NULL;
error_to_pyobject(&err, &py_err);
PyObject *exception_type = raise_exception(&err);
PyErr_SetObject(exception_type, py_err);
Py_DECREF(py_err);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
示例7: CLazyLinker_call
PyObject *
CLazyLinker_call(PyObject *_self, PyObject *args, PyObject *kwds)
{
CLazyLinker * self = (CLazyLinker*)_self;
static char *kwlist[] = {
(char*)"time_thunks",
(char *)"n_calls",
NULL};
int n_calls=1;
if (! PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwlist,
&self->do_timing,
&n_calls))
return NULL;
int err = 0;
self->position_of_error = -1;
// create constants used to fill the var_compute_cells
PyObject * one = PyInt_FromLong(1);
PyObject * zero = PyInt_FromLong(0);
// pre-allocate our return value
Py_INCREF(Py_None);
PyObject * rval = Py_None;
//clear storage of pre_call_clear elements
for (int call_i = 0; call_i < n_calls && (!err); ++call_i)
{
Py_ssize_t n_pre_call_clear = PyList_Size(self->pre_call_clear);
assert(PyList_Check(self->pre_call_clear));
for (int i = 0; i < n_pre_call_clear; ++i)
{
PyObject * el_i = PyList_GetItem(self->pre_call_clear, i);
Py_INCREF(Py_None);
PyList_SetItem(el_i, 0, Py_None);
}
//clear the computed flag out of all non-input vars
for (int i = 0; i < self->n_vars; ++i)
{
self->var_computed[i] = !self->var_has_owner[i];
if (self->var_computed[i])
{
Py_INCREF(one);
PyList_SetItem(self->var_computed_cells[i], 0, one);
}
else
{
Py_INCREF(zero);
PyList_SetItem(self->var_computed_cells[i], 0, zero);
}
}
for (int i = 0; i < self->n_output_vars && (!err); ++i)
{
err = lazy_rec_eval(self, self->output_vars[i], one, zero);
}
if (!err)
{
// save references to outputs prior to updating storage containers
assert (self->n_output_vars >= self->n_updates);
Py_DECREF(rval);
rval = PyList_New(self->n_output_vars);
for (int i = 0; i < (self->n_output_vars); ++i)
{
Py_ssize_t src = self->output_vars[i];
PyObject * item = PyList_GetItem(self->var_value_cells[src], 0);
if (self->var_computed[src] != 1)
{
err = 1;
PyErr_Format(PyExc_AssertionError,
"The compute map of output %d should contain "
"1 at the end of execution, not %d.",
i, self->var_computed[src]);
break;
}
Py_INCREF(item);
PyList_SetItem(rval, i, item);
}
}
if (!err)
{
// Update the inputs that have an update rule
for (int i = 0; i < self->n_updates; ++i)
{
PyObject* tmp = PyList_GetItem(rval, self->n_output_vars - self->n_updates + i);
Py_INCREF(tmp);
Py_ssize_t dst = self->update_storage[i];
PyList_SetItem(self->var_value_cells[dst], 0, tmp);
}
}
}
/*
Clear everything that is left and not an output. This is needed
for lazy evaluation since the current GC algo is too conservative
with lazy graphs.
*/
if (self->allow_gc && !err)
{
for (Py_ssize_t i = 0; i < self->n_vars; ++i)
{
//.........这里部分代码省略.........
示例8: obj_read
static PyObject *
obj_read(PyObject *self, PyObject *args)
{
/* The :compress tells PyArg_ParseTuple what function to use
* in its error message
*/
char *pstr;
if (!PyArg_ParseTuple(args, "s:read", &pstr)) {
return NULL;
}
PyFileObject* f;
f = PyFile_FromString((char*) pstr, "r");
int bufsize = -1;
PyObject* faces = PyList_New(0);
PyObject* points = PyList_New(0);
PyObject* normals = PyList_New(0);
PyObject* faces_normals = PyList_New(0);
if (f != NULL) {
PyFile_SetBufSize(f, bufsize);
for (;;) {
/* From PyFile_GetLine doc
*
* If n is 0, exactly one line is read,
* regardless of the length of the line. If n is
* greater than 0, no more than n bytes will be read
* from the file; a partial line can be returned. In
* both cases, an empty string is returned if the end
* of the file is reached immediately.
*/
PyObject* line = PyFile_GetLine(f, 0);
/* Invalid line ? */
if (! line || ! PyString_Check(line)) break;
/* Empty line ? */
int num = PyString_Size(line);
if (num == 0) break;
/*
* sscanf params
* http://www.cs.utah.edu/~zachary/isp/tutorials/io/io.html
*/
char* cline = PyString_AsString(line);
if (cline[0] == 'f') {
char p1[255];
int has_normals = 0;
int f1, f2, f3, f4;
int n1, n2, n3, n4;
int tmp;
int cnt = sscanf(cline+2, "%s %s %s %s", p1, p1, p1, p1);
// printf("%d\n", cnt);
if (strchr(p1, '/') == NULL) {
if (cnt == 3)
sscanf(cline+2, "%d %d %d", &f1, &f2, &f3);
else
sscanf(cline+2, "%d %d %d", &f1, &f2, &f3);
} else {
has_normals = 1;
if (strstr(p1, "//")) {
if (cnt == 3)
sscanf(cline+2, "%d//%d %d//%d %d//%d",
&f1, &n1, &f2, &n2, &f3, &n3);
else
sscanf(cline+2, "%d//%d %d//%d %d//%d %d//%d",
&f1, &n1, &f2, &n2, &f3, &n3, &f4, &n4);
} else {
if (cnt == 3)
sscanf(cline+2, "%d/%d/%d %d/%d/%d %d/%d/%d",
&f1, &tmp, &n1, &f2, &tmp, &n2, &f3, &tmp, &n3);
else {
sscanf(cline+2, "%d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d",
&f1, &tmp, &n1, &f2, &tmp, &n2, &f3, &tmp, &n3, &f4, &tmp, &n4);
}
}
}
PyObject* face = PyList_New(3);
PyList_SetItem(face, 0, PyInt_FromLong(f1-1));
PyList_SetItem(face, 1, PyInt_FromLong(f2-1));
PyList_SetItem(face, 2, PyInt_FromLong(f3-1));
PyList_Append(faces, face);
if (cnt == 4) {
PyObject* face2 = PyList_New(3);
PyList_SetItem(face2, 0, PyInt_FromLong(f3-1));
PyList_SetItem(face2, 1, PyInt_FromLong(f4-1));
PyList_SetItem(face2, 2, PyInt_FromLong(f1-1));
PyList_Append(faces, face2);
}
if (has_normals) {
PyObject* n = PyList_New(3);
PyList_SetItem(n, 0, PyInt_FromLong(n1-1));
PyList_SetItem(n, 1, PyInt_FromLong(n2-1));
PyList_SetItem(n, 2, PyInt_FromLong(n3-1));
//.........这里部分代码省略.........
示例9: if
//============================================================================
// METHOD: SPELLpyValue::get
//============================================================================
PyObject* SPELLpyValue::get() const
{
if (m_type == BOOLEAN )
{
if (m_boolValue)
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
else if (m_type == STRING )
{
return SSTRPY(m_stringValue);
}
else if (m_type == LONG )
{
return PyLong_FromLong(m_intValue);
}
else if (m_type == DOUBLE)
{
return PyFloat_FromDouble(m_floatValue);
}
else if (m_type == RELTIME )
{
PyObject* time = SPELLpythonHelper::instance().pythonTime(m_timeValue);
return time;
}
else if (m_type == ABSTIME )
{
PyObject* time = SPELLpythonHelper::instance().pythonTime(m_timeValue);
return time;
}
else if (m_type == LIST )
{
PyObject* list = PyList_New(m_listValue.size());
ValueList::const_iterator it = m_listValue.begin();
unsigned int idx = 0;
for( it = m_listValue.begin(); it != m_listValue.end(); it++ )
{
const SPELLpyValue& value = *it;
PyObject* item = value.get();
Py_INCREF(item);
PyList_SetItem(list,idx,item);
idx++;
}
return list;
}
else if (m_type == DICT )
{
PyObject* dict = PyDict_New();
ValueMap::const_iterator it = m_dictValue.begin();
for( it = m_dictValue.begin(); it != m_dictValue.end(); it++ )
{
std::string key = it->first;
const SPELLpyValue& value = it->second;
PyObject* item = value.get();
Py_INCREF(item);
PyDict_SetItemString(dict,key.c_str(),item);
}
return dict;
}
Py_RETURN_NONE;
}
示例10: parse_multi_line_message
static int parse_multi_line_message(Request* request, const char* data, const size_t data_len){
char *newline = NULL;
int pos = 0, ok;
long long ll;
int partialdone = 0;
if (request->parse_phase == RDS_PHASE_CONNECT){
if (request->multibulklen == 0) {
newline = strchr(data,'\r');
if (newline == NULL) {
// if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) {
// addReplyError(c,"Protocol error: too big mbulk count string");
// setProtocolError(c,0);
// }
// we will come back here,
return -1;
}
ok = string2ll(data+1, newline-(data+1), &ll);
if (!ok || ll > 1024*1024) {
puts("couldnt find data length... ");
return -2;
}
pos = (newline - data)+2;
if (ll <= 0) {
// TODO: handle *-1\r\n ?
// c->querybuf = sdsrange(c->querybuf,pos,-1);
return true;
}
request->cmd_list = PyList_New(ll);
request->multibulklen = ll;
request->arg_cnt = 0;
request->parse_phase = RDS_PHASE_START;
// now send the remainder to start line...
request->lastpos = pos;
}
}
while (request->multibulklen){
// since we found the start line, here we parse it...
if (request->parse_phase == RDS_PHASE_START){
if (data[request->lastpos] == '$'){
//
newline = strchr(data+request->lastpos,'\r');
if (!newline){
return -1;
}
ok = string2ll(data+request->lastpos+1, newline - (data+ request->lastpos+1),&ll);
if (!ok || ll < 0 || ll > 512*1024*1024) {
return -2;
}
// now parse data line...
pos = (newline - data)+2;
if (ll < 0) {
// handle $-1\r\n ?
// protocol error !!!
// c->querybuf = sdsrange(c->querybuf,pos,-1);
return -2;
}
// now send the remainder to start line...
request->lastpos = pos;
request->parse_phase = RDS_PHASE_DATA;
request->bulklen = ll;
} else {
puts("ERR: protocol error");
return -2;
}
}
//
if (request->parse_phase == RDS_PHASE_DATA){
if ((int)(data_len - request->lastpos) < 0){
return -1;
}
// do we have enough data ???
if ( (int)(data_len - request->lastpos) < (int)(request->bulklen+2)) {
/* Not enough data (+2 == trailing \r\n) */
return -1;
break;
} else {
char *str2 = malloc(request->bulklen + 1);
memcpy(str2, data + request->lastpos, request->bulklen);
str2[request->bulklen] = '\0';
PyObject* str = PyString_FromStringAndSize(str2, request->bulklen);
PyList_SetItem(request->cmd_list, request->arg_cnt++, str);
// NOTE: as far as i understand, PyList_SetItem doesnt incref
// http://stackoverflow.com/questions/3512414/does-this-pylist-appendlist-py-buildvalue-leak
// Py_DECREF(str); <- TODO: why ? if i do this weird things happen
free(str2);
//.........这里部分代码省略.........
示例11: sizeof
static PyObject *Py_FindObjects(PyObject *obj, PyObject *args)
{
PyArrayObject *input = NULL;
PyObject *result = NULL, *tuple = NULL, *start = NULL, *end = NULL;
PyObject *slc = NULL;
int jj;
#if PY_VERSION_HEX < 0x02050000
long max_label;
#define FMT "l"
#else
npy_intp max_label;
#define FMT "n"
#endif
npy_intp ii, *regions = NULL;
if (!PyArg_ParseTuple(args, "O&" FMT,
NI_ObjectToInputArray, &input, &max_label))
goto exit;
#undef FMT
if (max_label < 0)
max_label = 0;
if (max_label > 0) {
if (input->nd > 0) {
regions = (npy_intp*)malloc(2 * max_label * input->nd *
sizeof(npy_intp));
} else {
regions = (npy_intp*)malloc(max_label * sizeof(npy_intp));
}
if (!regions) {
PyErr_NoMemory();
goto exit;
}
}
if (!NI_FindObjects(input, max_label, regions))
goto exit;
result = PyList_New(max_label);
if (!result) {
PyErr_NoMemory();
goto exit;
}
for(ii = 0; ii < max_label; ii++) {
npy_intp idx = input->nd > 0 ? 2 * input->nd * ii : ii;
if (regions[idx] >= 0) {
PyObject *tuple = PyTuple_New(input->nd);
if (!tuple) {
PyErr_NoMemory();
goto exit;
}
for(jj = 0; jj < input->nd; jj++) {
#if PY_VERSION_HEX < 0x02060000
start = PyLong_FromLong(regions[idx + jj]);
end = PyLong_FromLong(regions[idx + jj + input->nd]);
#else
start = PyLong_FromSsize_t(regions[idx + jj]);
end = PyLong_FromSsize_t(regions[idx + jj + input->nd]);
#endif
if (!start || !end) {
PyErr_NoMemory();
goto exit;
}
slc = PySlice_New(start, end, NULL);
if (!slc) {
PyErr_NoMemory();
goto exit;
}
Py_XDECREF(start);
Py_XDECREF(end);
start = end = NULL;
PyTuple_SetItem(tuple, jj, slc);
slc = NULL;
}
PyList_SetItem(result, ii, tuple);
tuple = NULL;
} else {
Py_INCREF(Py_None);
PyList_SetItem(result, ii, Py_None);
}
}
Py_INCREF(result);
exit:
Py_XDECREF(input);
Py_XDECREF(result);
Py_XDECREF(tuple);
Py_XDECREF(start);
Py_XDECREF(end);
Py_XDECREF(slc);
if (regions)
free(regions);
if (PyErr_Occurred()) {
Py_XDECREF(result);
return NULL;
} else {
return result;
}
//.........这里部分代码省略.........
示例12: to_Pyobj_vector
//.........这里部分代码省略.........
// if(my_callback){
// argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In STRSXP"));
// PyObject_CallObject(my_callback, argslist);
// }
if(STRING_ELT(robj, i)==R_NaString)
it = PyString_FromString(CHAR(NA_STRING));
else
{
strings = CHAR(STRING_ELT(robj, i));
if (!(it = PyString_FromString(strings)))
{
// tmp = Py_BuildValue("s", "failed in PyString_FromString!!!"); // we are at least getting an robj
// *obj = tmp;
// return 1;
return -1;
}
}
break;
case LISTSXP:
// if(my_callback){
// argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In LISTSXP"));
// PyObject_CallObject(my_callback, argslist);
// }
if (!(it = to_Pyobj_with_mode(elt(robj, i), mode)))
{
// tmp = Py_BuildValue("s", "failed in to_Pyobj_with_mode LISTSXP!!!"); // we are at least getting an robj
// *obj = tmp;
// return 1;
return -1;
}
break;
case VECSXP:
// if(my_callback){
// argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In VECSXP"));
// PyObject_CallObject(my_callback, argslist);
// }
if (!(it = to_Pyobj_with_mode(VECTOR_ELT(robj, i), mode)))
{
return -1;
}
break;
default:
Py_DECREF(tmp);
return 0; /* failed */
}
if (PyList_SetItem(tmp, i, it) < 0) // there was a failure in setting the item
{
// tmp = Py_BuildValue("s", "failed in PyList_SetItem!!!"); // we are at least getting an robj
// *obj = tmp;
// return 1;
return -1;
}
}
dim = GET_DIM(robj);
if (dim != R_NilValue) {
// #ifdef WITH_NUMERIC
// if(use_numeric)
// {
// array = to_PyNumericArray(tmp, dim);
// if (array) { /* If the conversion to Numeric succeed.. */
// *obj = array; /* we are done */
// Py_DECREF(tmp);
// return 1;
// }
// PyErr_Clear();
// }
// #endif
len = GET_LENGTH(dim);
*obj = to_PyArray(tmp, INTEGER(dim), len);
Py_DECREF(tmp);
return 1;
}
// if(my_callback){
// argslist = Py_BuildValue("(O)", Py_BuildValue("(O)", tmp));
// PyObject_CallObject(my_callback, argslist);
// }
names = GET_NAMES(robj);
if (names == R_NilValue)
{
*obj = tmp;
// if(my_callback){
// argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "returning as list (of lists)"));
// PyObject_CallObject(my_callback, argslist);
// }
}
else {
*obj = to_PyDict(tmp, names);
// if(my_callback){
// argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "returning as dict"));
// PyObject_CallObject(my_callback, argslist);
// }
Py_DECREF(tmp);
}
return 1;
}
示例13: python_apply
// python_apply implements the function call:
// (python-apply ("module.submodule" 'obj 'func)
// (arg1 arg2 arg3)
// (('keyword1 . val4) ('keyword2 . val5))
// sargtemplate
// skwtemplate)
// which is the basic way to invoke a Python function.
//
// sfunc specifies the function to be invoked. The possibilities
// are:
// String - denotes a top level function ("func" means __main__.func).
// pysmob - assumed to be a callable object.
// ("module.submodule" ...) - a List of strings/symbols/keywords
// in which the first item must be a string denotes:
// Module "module.submodule" (which should have already been imported
// using python-import)
// followed by name of object in that module, followed by attribute,...,
// until the final callable attribute.
// (pysmob ...) - a List starting with pysmob followed by
// strings/symbols/keywords - processed similarly, except that the
// pysmob stands for the module.
// sarg is a list of arguments (in Python it's *arg)
// skw is an alist (in Python it's **kw).
// sargtemplate - specifies how to convert sarg - optional argument.
// skwtemplate - specifies how to convert skw - optional argument.
// srestemplate - specifies how to convert the result back into
// SCM - optional argument.
SCM
python_apply(SCM sfunc, SCM sarg, SCM skw,
SCM sargtemplate, SCM skwtemplate, SCM srestemplate)
{
PyObject *pfunc = NULL;
PyObject *parg = NULL;
PyObject *pkw = NULL;
PyObject *pfuncobj = NULL;
PyObject *pres = NULL;
SCM sres = SCM_UNDEFINED;
if (SCM_UNBNDP(sargtemplate)) { //(sargtemplate == SCM_UNDEFINED) // SCM_UNSPECIFIED
sargtemplate = sargtemplate_default;
}
if (SCM_UNBNDP(skwtemplate)) {
skwtemplate = skwtemplate_default;
}
if (SCM_UNBNDP(srestemplate)) {
srestemplate = srestemplate_default;
}
// Retrieve the function object.
pfunc = guile2python(sfunc,SCM_UNSPECIFIED);
if (pyguile_verbosity_test(PYGUILE_VERBOSE_PYTHON_APPLY)) {
char *preprfunc = PyString_AsString(PyObject_Repr(pfunc));
scm_simple_format(scm_current_output_port(),scm_makfrom0str("# python_apply: decoded pfunc ~S\n"),scm_list_1(scm_makfrom0str(preprfunc)));
}
if (NULL == pfunc) {
scm_misc_error("python-apply","conversion failure (~S)",
scm_list_1(SCM_CDR(sfunc)));
}
// If it is a string, prepend it with "__main__".
if (PyString_CheckExact(pfunc)) {
// Convert it into a List of two items, to unify
// subsequent treatment.
PyObject *plist = PyList_New(2);
if (NULL == plist) {
Py_DECREF(pfunc); // NOT COVERED BY TESTS
scm_memory_error("python-apply"); // NOT COVERED BY TESTS
}
if (-1 == PyList_SetItem(plist,0,PyString_FromString("__main__"))) {
Py_DECREF(pfunc); // NOT COVERED BY TESTS
Py_DECREF(plist); // NOT COVERED BY TESTS
scm_misc_error("python-apply","PyList_SetItem 0 failure (~S)", // NOT COVERED BY TESTS
scm_list_1(SCM_CAR(sfunc)));
}
if (-1 == PyList_SetItem(plist,1,pfunc)) {
Py_DECREF(pfunc); // NOT COVERED BY TESTS
Py_DECREF(plist); // NOT COVERED BY TESTS
scm_misc_error("python-apply","PyList_SetItem 1 failure (~S)", // NOT COVERED BY TESTS
scm_list_1(SCM_CAR(sfunc)));
}
pfunc = plist; // plist stole previous pfunc's value's reference.
}
else if (IS_PYSMOBP(sfunc)) {
// We check the SCM object because guile2python() destroys
// the indication whether the SCM was originally a pysmob, when it
// converts it into PyObject.
PyObject *plist1 = PyList_New(1);
if (NULL == plist1) {
Py_DECREF(pfunc); // NOT COVERED BY TESTS
scm_memory_error("python-apply"); // NOT COVERED BY TESTS
}
if (-1 == PyList_SetItem(plist1,0,pfunc)) {
Py_DECREF(pfunc); // NOT COVERED BY TESTS
Py_DECREF(plist1); // NOT COVERED BY TESTS
scm_misc_error("python-apply","PyList_SetItem 0 failure (~S)", // NOT COVERED BY TESTS
scm_list_1(SCM_CAR(sfunc)));
}
pfunc = plist1; // plist1 stole previous pfunc's value's reference.
// Now pfunc is an 1-member list, and this member is
//.........这里部分代码省略.........
示例14: on_message
// get spectrum messages and delay them
static gboolean on_message(GstBus *bus, GstMessage *message, gpointer data)
{
base *base_object = data;
GstElement *spectrum = GST_ELEMENT(base_object->spectrum_element->obj);
gst_object_ref(spectrum);
GstElement *message_element = GST_ELEMENT(GST_MESSAGE_SRC(message));
gst_object_ref(message_element);
if (message_element == spectrum)
{
GstClockTime waittime = GST_CLOCK_TIME_NONE;
const GstStructure *message_structure = gst_message_get_structure(message);
// determine waittime
GstClockTime timestamp, duration;
if (
gst_structure_get_clock_time(message_structure, "running-time", ×tamp)
&& gst_structure_get_clock_time(message_structure, "duration", &duration)
)
{
/* wait for middle of buffer */
waittime = timestamp + duration/2;
}
else if (gst_structure_get_clock_time(message_structure, "endtime", ×tamp))
{
waittime = timestamp;
}
// delay message
if (GST_CLOCK_TIME_IS_VALID(waittime))
{
GstClockTime basetime = gst_element_get_base_time(spectrum);
GstClockID clock_id = gst_clock_new_single_shot_id(base_object->sync_clock, basetime+waittime);
spectrum_message *mess = g_malloc(sizeof(spectrum_message));
// set bands and threshold
g_object_get(message_element, "bands", &(mess->bands), "threshold", &(mess->threshold), NULL);
// set start and duration
GstClockTime streamtime, duration;
gst_structure_get_clock_time(message_structure, "stream-time", &streamtime);
gst_structure_get_clock_time(message_structure, "duration", &duration);
mess->start = (gfloat)streamtime / GST_SECOND;
mess->duration = (gfloat)duration / GST_SECOND;
// set rate
GstPad *sink = gst_element_get_static_pad(GST_ELEMENT(base_object->spectrum_element->obj), "sink");
GstCaps *caps = gst_pad_get_negotiated_caps(sink);
gst_object_unref(sink);
GstStructure *caps_structure = gst_caps_get_structure(caps, 0);
gst_structure_get_int(caps_structure, "rate", &(mess->rate));
gst_caps_unref(caps);
// set magnitudes
const GValue *list = gst_structure_get_value(message_structure, "magnitude");
PyGILState_STATE gstate = PyGILState_Ensure();
int i;
mess->magnitudes = PyList_New(mess->bands);
for (i=0; i < (mess->bands); i++)
{
const GValue *value = gst_value_list_get_value(list, i);
gfloat f = g_value_get_float(value);
PyList_SetItem(mess->magnitudes, i, Py_BuildValue("f", f));
}
PyGILState_Release(gstate);
// set gobj
GObject *gobj = (base_object->gobj).obj;
g_assert(gobj != NULL);
g_object_ref(gobj);
mess->gobj = gobj;
// delay message
gst_clock_id_wait_async(clock_id, delayed_spectrum_update, mess);
gst_clock_id_unref(clock_id);
}
}
gst_object_unref(spectrum);
gst_object_unref(message_element);
return TRUE;
}
示例15: PyList_New
PyObject* VRPyBase::toPyTuple( const vector<string>& v ) {
PyObject* res = PyList_New(v.size());
for (uint i=0; i<v.size(); i++) PyList_SetItem(res, i, PyString_FromString(v[i].c_str()));
return res;
}