コード例 #1
0
ファイル: TWPythonPlugin.cpp プロジェクト: Berenco/texworks
/*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
0
/**
 *******************************************************************************************************
 * 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);
            if (PyList_SetItem(py_recs, i, py_rec)) {
                // Release Python State
                PyGILState_Release(gstate);
                return false;
            }
        }
    }
    // Release Python State
    PyGILState_Release(gstate);
    return true;
}
コード例 #3
0
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
0
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;
	}
    case P_SEP:
	return NULL; /* this stands for a separator, can be ignored */
    }
    return NULL;

}
コード例 #5
0
ファイル: pyglue.c プロジェクト: AIdrifter/samba
/*
  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
0
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
0
ファイル: lazylinker_c.c プロジェクト: Donghuan/Theano
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)
        {
          int do_cleanup = 1;
          if (!self->var_has_owner[i] || !self->var_computed[i])
            continue;
          for (int j = 0; j < self->n_output_vars; ++j)
            {
              if (i == self->output_vars[j])
                {
                  do_cleanup = 0;
                  break;
                }
            }
          if (!do_cleanup)
            continue;
          Py_INCREF(Py_None);
          PyList_SetItem(self->var_value_cells[i], 0, Py_None);
        }
    }
  Py_DECREF(one);
  Py_DECREF(zero);
  if (err)
    {
      Py_DECREF(rval);
      return NULL;
    }
  return rval;
}
コード例 #8
0
ファイル: cobj.c プロジェクト: bsergean/oglshow
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));
                    PyList_Append(faces_normals, n);

                    if (cnt == 4) {
                        PyObject* p = PyList_New(3);
                        PyList_SetItem(p, 0, PyInt_FromLong(n3-1));
                        PyList_SetItem(p, 1, PyInt_FromLong(n4-1));
                        PyList_SetItem(p, 2, PyInt_FromLong(n1-1));
                        PyList_Append(faces_normals, p);
                    }
                }
			}
			else if (cline[0] == 'v' && cline[1] == ' ') {
				double a, b, c;
				PyObject* vertex = PyList_New(3);
				sscanf(cline+2, "%lf %lf %lf", &a, &b, &c);

				// printf("%lf %lf %lf\n", a, b, c);

				PyList_SetItem(vertex, 0, PyFloat_FromDouble(a));
				PyList_SetItem(vertex, 1, PyFloat_FromDouble(b));
				PyList_SetItem(vertex, 2, PyFloat_FromDouble(c));

				PyList_Append(points, vertex);
			}
			else if (cline[0] == 'v' && cline[1] == 'n') {
				double a, b, c;
				PyObject* normal = PyList_New(3);
				sscanf(cline+3, "%lf %lf %lf", &a, &b, &c);

				// printf("%lf %lf %lf\n", a, b, c);

				PyList_SetItem(normal, 0, PyFloat_FromDouble(a));
				PyList_SetItem(normal, 1, PyFloat_FromDouble(b));
				PyList_SetItem(normal, 2, PyFloat_FromDouble(c));

				PyList_Append(normals, normal);
			}
		}
	}
	fclose(PyFile_AsFile(f));

	PyObject* tuple = PyList_New(4);
	PyList_SetItem(tuple, 0, points);
	PyList_SetItem(tuple, 1, faces);
	PyList_SetItem(tuple, 2, normals);
	PyList_SetItem(tuple, 3, faces_normals);

	return tuple;
}
コード例 #9
0
ファイル: SPELLpyValue.C プロジェクト: seciltabur/spell-sat
//============================================================================
// 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
0
ファイル: request.c プロジェクト: ybrs/the-giant
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);                  
                }                                

              
              request->lastpos = request->lastpos + request->bulklen + 2;
              request->parse_phase = RDS_PHASE_START;              
              request->multibulklen--;                              
          
          } // if RDS_PHASE_DATA
    } // while bulklen

    if (request->multibulklen == 0){      
        return 1;
    }
    
    return -1;
}
コード例 #11
0
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
0
/* NOTE: R vectors of length 1 will yield a python list of length 1*/
int
to_Pyobj_vector(SEXP robj, PyObject **obj, int mode)
{
  PyObject *it, *tmp;
  SEXP names, dim;
  int len, *integers, i, type;
  const char *strings, *thislevel;
  double *reals;
  Rcomplex *complexes;
#ifdef WITH_NUMERIC
  PyObject *array;
#endif

  if (!robj)
    {
    // return -1;                  /* error */
    // if(my_callback){
        // argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "robj does not exist"));
        // PyObject_CallObject(my_callback, argslist);
    // }
    return 1;
    }
  if (robj == R_NilValue) {
    Py_INCREF(Py_None);
    *obj = Py_None;
    return 1;                   /* succeed */
  }

  len = GET_LENGTH(robj);
  tmp = PyList_New(len);
  type = TYPEOF(robj);

    // if(my_callback){
        // argslist = Py_BuildValue("(O)", Py_BuildValue("(si)", "robj length is ", len));
        // PyObject_CallObject(my_callback, argslist);
    // }
    
  /// break for checking the R length and other aspects
  for (i=0; i<len; i++) {
    switch (type)
      {
      case LGLSXP:
            // if(my_callback){
                // argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In LGLSXP"));
                // PyObject_CallObject(my_callback, argslist);
            // }
         integers = INTEGER(robj);
         if(integers[i]==NA_INTEGER) /* watch out for NA's */
           {
             if (!(it = PyInt_FromLong(integers[i])))
             //return -1;
             tmp = Py_BuildValue("s", "failed in the PyInt_FromLong");  // we are at least getting an robj
             *obj = tmp;
             return 1;
             //it = Py_None;
           }
         else if (!(it = PyBool_FromLong(integers[i])))
            {
            tmp = Py_BuildValue("s", "failed in the PyBool_FromLong");  // we are at least getting an robj
             *obj = tmp;
             return 1;
           //return -1;
           }
         break;
      case INTSXP:
            // if(my_callback){
                // argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In INTSXP"));
                // PyObject_CallObject(my_callback, argslist);
            // }
        integers = INTEGER(robj);
        if(isFactor(robj)) {
          /* Watch for NA's! */
          if(integers[i]==NA_INTEGER)
            it = PyString_FromString(CHAR(NA_STRING));
          else
            {
              thislevel = CHAR(STRING_ELT(GET_LEVELS(robj), integers[i]-1));
              if (!(it = PyString_FromString(thislevel)))
                {
                tmp = Py_BuildValue("s", "failed in the PyString_FromString");  // we are at least getting an robj
                *obj = tmp;
                return 1;
                }
                //return -1;
            }
        }
        else {
          if (!(it = PyInt_FromLong(integers[i])))
            {
            tmp = Py_BuildValue("s", "failed in the PyInt_FromLong");  // we are at least getting an robj
                *obj = tmp;
                return 1;
            //return -1;
            }
        }
        break;
      case REALSXP:
            // if(my_callback){
                // argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In REALSXP"));
                // PyObject_CallObject(my_callback, argslist);
            // }
        reals = REAL(robj);
        if (!(it = PyFloat_FromDouble(reals[i])))
        {
        // tmp = Py_BuildValue("s", "failed in the PyFloat_FromDouble");  // we are at least getting an robj
                // *obj = tmp;
                // return 1;
         return -1;
        }
        break;
      case CPLXSXP:
            // if(my_callback){
                // argslist = Py_BuildValue("(O)", Py_BuildValue("(s)", "In CPLXSXP"));
                // PyObject_CallObject(my_callback, argslist);
            // }
        complexes = COMPLEX(robj);
        if (!(it = PyComplex_FromDoubles(complexes[i].r,
                                         complexes[i].i)))
          {
            
            // tmp = Py_BuildValue("s", "failed in PyComplex_FromDoubles!!!");  // we are at least getting an robj
            // *obj = tmp;
            // return 1;
            return -1;
            }
        break;
      case STRSXP:
            // 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
0
ファイル: pyguile.c プロジェクト: tddpirate/pyguile
// 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
    // expected to be callable.
  }
  else if (!PyList_CheckExact(pfunc)) {
    // Now, the qualified function name must be a proper list.
    scm_wrong_type_arg("python-apply",SCM_ARG1,sfunc);
  }

  if (1 > PyList_Size(pfunc)) {
    // The list must consist of at least one callable module name/object.
    scm_misc_error("python-apply",
		   "first argument must contain at least one callable object (~S)",
		   scm_list_1(SCM_CAR(sfunc)));
  }

  if (PyString_CheckExact(PyList_GetItem(pfunc,0))) {
    // If it is a string, we assume it to be the name of a module
    // which has already been imported.
    // Due to the existence of dots, 
    // we don't allow it to be symbol or keyword.

    pfuncobj = PyImport_AddModule(PyString_AsString(PyList_GetItem(pfunc,0)));
    if (NULL == pfuncobj) {
      Py_DECREF(pfunc);
      scm_misc_error("python-apply",
		     "module ~S could not be accessed - probably not imported",
		     scm_list_1(SCM_CAR(sfunc)));
    }
    Py_INCREF(pfuncobj);
  }
  else {
    // We assume that it is a callable or object with attributes.
    pfuncobj = PyList_GetItem(pfunc,0);
    if (NULL == pfuncobj) {
      Py_DECREF(pfunc);
      scm_misc_error("python-apply",
		     "could not access object starting ~S",
		     scm_list_1(sfunc));
    }
    Py_INCREF(pfuncobj);
  }

  // Here we dereference attributes (if any).
  int listsize = PyList_Size(pfunc);
  int ind;

  for (ind = 1; ind < listsize; ++ind) {
    PyObject *pnextobj = PyObject_GetAttr(pfuncobj,PyList_GetItem(pfunc,ind));
    if (NULL == pnextobj) {
      PyObject *pexception = PyErr_Occurred();
      Py_DECREF(pfunc);
      Py_DECREF(pfuncobj);
      if (pexception) {
	PyErr_Clear();
	// An AttributeError exception is expected here.
	if (!PyErr_GivenExceptionMatches(pexception,PyExc_AttributeError)) {
	  PyObject *prepr = PyObject_Repr(pexception);
	  if (NULL == prepr) {
	    scm_misc_error("python-apply",
			   "python exception - could not be identified",
			   SCM_UNSPECIFIED);
	  }
	  else {
	    int strlength = PyString_Size(prepr);
	    char *pstr = PyString_AsString(prepr);
	    SCM srepr = scm_list_1(scm_mem2string(pstr,strlength));
	    Py_DECREF(prepr);
	    scm_misc_error("python-apply",
			   "Python exception (~A) while dereferencing object attribute",
			   srepr);
	  }
	}
	// else we got the expected AttributeError exception.
      }
      // else we got NULL==pnextobj without Python exception.
      scm_misc_error("python-apply",
		     "could not dereference ~Ath level attribute in ~S",
		     scm_list_2(scm_long2num(ind),sfunc));
    }
    Py_INCREF(pnextobj);
    Py_DECREF(pfuncobj);
    pfuncobj = pnextobj;
  }
  Py_DECREF(pfunc);  // We do not need it anymore.  pfuncobj points at
                     // the function actually to be invoked.
  if (!PyCallable_Check(pfuncobj)) {
    Py_DECREF(pfuncobj);
    scm_misc_error("python-apply","function denoted by ~S is not callable",scm_list_1(sfunc));
  }

  if (pyguile_verbosity_test(PYGUILE_VERBOSE_PYTHON_APPLY)) {
    char *preprfuncobj = PyString_AsString(PyObject_Repr(pfuncobj));
    scm_simple_format(scm_current_output_port(),
		      scm_makfrom0str("# python_apply: decoded function actually to be invoked: ~S\n"),
		      scm_list_1(scm_makfrom0str(preprfuncobj)));
  }

  // Retrieve positional arguments

  parg = g2p_apply(sarg,sargtemplate);
  if (NULL == parg) {
    Py_DECREF(pfuncobj);
    scm_misc_error("python-apply","positional arguments conversion failure (~S)",
		   scm_list_1(sarg));
  }
  // Validate that it is indeed a tuple.
  if (!PyTuple_CheckExact(parg)) {
    Py_DECREF(pfuncobj);
    Py_DECREF(parg);
    scm_wrong_type_arg("python-apply",SCM_ARG2,sarg);
  }
  if (pyguile_verbosity_test(PYGUILE_VERBOSE_PYTHON_APPLY)) {
    char *pposarg = PyString_AsString(PyObject_Repr(parg));
    scm_simple_format(scm_current_output_port(),scm_makfrom0str("# python_apply: decoded positional arguments ~S\n"),scm_list_1(scm_makfrom0str(pposarg)));
  }

  // Retrieve keyword arguments.

  pkw = guileassoc2pythondict(skw,skwtemplate);
  if (NULL == pkw) {
    // Seems that PyDict_CheckExact() does not handle NULL argument gracefully.
     Py_DECREF(pfuncobj);
     Py_DECREF(parg);
     scm_misc_error("python-apply","keyword arguments conversion failure (~S)",
		    scm_list_1(skw));
  }
  if (!PyDict_CheckExact(pkw)) {
     Py_DECREF(pfuncobj);
     Py_DECREF(parg);
     Py_DECREF(pkw);
     scm_misc_error("python-apply",
		    "keyword arguments (~S) not properly converted into Python Dict",
		    scm_list_1(skw));
  }
  if (pyguile_verbosity_test(PYGUILE_VERBOSE_PYTHON_APPLY)) {
    char *pkwarg = PyString_AsString(PyObject_Repr(pkw));
    scm_simple_format(scm_current_output_port(),scm_makfrom0str("# python_apply: decoded keyword arguments ~S\n"),scm_list_1(scm_makfrom0str(pkwarg)));
  }

  // Ready to invoke the function.

  pres = PyEval_CallObjectWithKeywords(pfuncobj,parg,pkw);
  PyObject *pexception = PyErr_Occurred();
  if (pexception) {
    PyObject *prepr = PyObject_Repr(pexception);
    Py_DECREF(pfuncobj);
    Py_DECREF(parg);
    Py_DECREF(pkw);
    Py_XDECREF(pres);
    PyErr_Clear();
    if (NULL == prepr) {
      scm_misc_error("python-apply",
		     "python exception - could not be identified",
		     SCM_UNSPECIFIED);
    }
    else {
      int strlength = PyString_Size(prepr);
      char *pstr = PyString_AsString(prepr);
      SCM srepr = scm_list_1(scm_mem2string(pstr,strlength));
      Py_DECREF(prepr);
      scm_misc_error("python-apply","Python exception: ~A",
		     srepr);
    }
  }
  if (NULL != pres) {
    sres = p2g_apply(pres,srestemplate);
    if (pyguile_verbosity_test(PYGUILE_VERBOSE_PYTHON_APPLY)) {
      char *presstr = PyString_AsString(PyObject_Repr(pres));
      scm_simple_format(scm_current_output_port(),scm_makfrom0str("# python_apply: decoded results:\n#     Python: ~S\n#     Scheme: ~S\n"),scm_list_2(scm_makfrom0str(presstr),sres));
    }
  }
  else {
    // else sres remains SCM_UNDEFINED.
    if (pyguile_verbosity_test(PYGUILE_VERBOSE_PYTHON_APPLY)) {
      scm_simple_format(scm_current_output_port(),scm_makfrom0str("# python_apply: Python code returned <NULL>\n"),SCM_EOL);
    }
  }
  return(sres);
}
// 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", &timestamp)
			&& 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", &timestamp))
		{
			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
0
ファイル: VRPyBase.cpp プロジェクト: Victor-Haefner/polyvr
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;
}
コード例 #16
0
PyObject *
libxml_xmlXPathObjectPtrWrap(xmlXPathObjectPtr obj)
{
    PyObject *ret;

#ifdef DEBUG
    printf("libxml_xmlXPathObjectPtrWrap: ctxt = %p\n", obj);
#endif
    if (obj == NULL) {
        Py_INCREF(Py_None);
        return (Py_None);
    }
    switch (obj->type) {
        case XPATH_XSLT_TREE: {
            if ((obj->nodesetval == NULL) ||
		(obj->nodesetval->nodeNr == 0) ||
		(obj->nodesetval->nodeTab == NULL)) {
                ret = PyList_New(0);
	    } else {
		int i, len = 0;
		xmlNodePtr node;

		node = obj->nodesetval->nodeTab[0]->children;
		while (node != NULL) {
		    len++;
		    node = node->next;
		}
		ret = PyList_New(len);
		node = obj->nodesetval->nodeTab[0]->children;
		for (i = 0;i < len;i++) {
                    PyList_SetItem(ret, i, libxml_xmlNodePtrWrap(node));
		    node = node->next;
		}
	    }
	    /*
	     * Return now, do not free the object passed down
	     */
	    return (ret);
	}
        case XPATH_NODESET:
            if ((obj->nodesetval == NULL)
                || (obj->nodesetval->nodeNr == 0)) {
                ret = PyList_New(0);
	    } else {
                int i;
                xmlNodePtr node;

                ret = PyList_New(obj->nodesetval->nodeNr);
                for (i = 0; i < obj->nodesetval->nodeNr; i++) {
                    node = obj->nodesetval->nodeTab[i];
                    /* TODO: try to cast directly to the proper node type */
                    PyList_SetItem(ret, i, libxml_xmlNodePtrWrap(node));
                }
            }
            break;
        case XPATH_BOOLEAN:
            ret = PyInt_FromLong((long) obj->boolval);
            break;
        case XPATH_NUMBER:
            ret = PyFloat_FromDouble(obj->floatval);
            break;
        case XPATH_STRING:
            ret = PyString_FromString((char *) obj->stringval);
            break;
        case XPATH_POINT:
        case XPATH_RANGE:
        case XPATH_LOCATIONSET:
        default:
#ifdef DEBUG
            printf("Unable to convert XPath object type %d\n", obj->type);
#endif
            Py_INCREF(Py_None);
            ret = Py_None;
    }
    xmlXPathFreeObject(obj);
    return (ret);
}
コード例 #17
0
ファイル: VRPyBase.cpp プロジェクト: Victor-Haefner/polyvr
PyObject* VRPyBase::toPyTuple( const vector<PyObject*>& v ) {
    PyObject* res = PyList_New(v.size());
    for (uint i=0; i<v.size(); i++) PyList_SetItem(res, i, v[i]);
    return res;
}
コード例 #18
0
ファイル: pyjobject.c プロジェクト: codeApeFromChina/jep
static int pyjobject_init(JNIEnv *env, PyJObject *pyjob)
{
    jobjectArray      methodArray = NULL;
    jobjectArray      fieldArray  = NULL;
    int               i, len = 0;
    jobject           langClass   = NULL;

    jstring           className   = NULL;
    const char       *cClassName  = NULL;
    PyObject         *pyClassName = NULL;
    PyObject         *pyAttrName  = NULL;

    JepThread   *jepThread;
    PyObject    *cachedMethodList = NULL;

    (*env)->PushLocalFrame(env, 20);
    // ------------------------------ call Class.getMethods()

    // well, first call getClass()
    if (objectGetClass == 0) {
        objectGetClass = (*env)->GetMethodID(env,
                                             pyjob->clazz,
                                             "getClass",
                                             "()Ljava/lang/Class;");
        if (process_java_exception(env) || !objectGetClass) {
            goto EXIT_ERROR;
        }
    }

    langClass = (*env)->CallObjectMethod(env, pyjob->clazz, objectGetClass);
    if (process_java_exception(env) || !langClass) {
        goto EXIT_ERROR;
    }

    /*
     * attach attribute java_name to the pyjobject instance to assist with
     * understanding the type at runtime
     */
    if (classGetName == 0) {
        classGetName = (*env)->GetMethodID(env, langClass, "getName",
                                           "()Ljava/lang/String;");
    }
    className = (*env)->CallObjectMethod(env, pyjob->clazz, classGetName);
    cClassName = jstring2char(env, className);
    pyClassName = PyString_FromString(cClassName);
    release_utf_char(env, className, cClassName);
    pyAttrName = PyString_FromString("java_name");
    if (PyObject_SetAttr((PyObject *) pyjob, pyAttrName, pyClassName) == -1) {
        PyErr_Format(PyExc_RuntimeError,
                     "Couldn't add java_name as attribute.");
    } else {
        pyjobject_addfield(pyjob, pyAttrName);
    }
    pyjob->javaClassName = pyClassName;
    Py_DECREF(pyAttrName);
    (*env)->DeleteLocalRef(env, className);

    // then, get methodid for getMethods()
    if (classGetMethods == 0) {
        classGetMethods = (*env)->GetMethodID(env,
                                              langClass,
                                              "getMethods",
                                              "()[Ljava/lang/reflect/Method;");
        if (process_java_exception(env) || !classGetMethods) {
            goto EXIT_ERROR;
        }
    }

    /*
     * Performance improvement.  The code below is very similar to previous
     * versions except methods are now cached in memory.
     *
     * Previously every time you instantiate a pyjobject, JEP would get the
     * complete list of methods, turn them into pyjmethods, and add them as
     * attributes to the pyjobject.
     *
     * Now JEP retains a python dictionary in memory with a key of the fully
     * qualified Java classname to a list of pyjmethods. Since the
     * Java methods will never change at runtime for a particular Class, this
     * is safe and drastically speeds up pyjobject instantiation by reducing
     * reflection calls. We continue to set and reuse the pyjmethods as
     * attributes on the pyjobject instance, but if pyjobject_getattr sees a
     * pyjmethod, it will put it inside a pymethod and return that, enabling
     * the reuse of the pyjmethod for this particular object instance.
     *
     * We have the GIL at this point, so we can safely assume we're
     * synchronized and multiple threads will not alter the dictionary at the
     * same time.
     */
    jepThread = pyembed_get_jepthread();
    if (jepThread == NULL) {
        goto EXIT_ERROR;
    }
    if (jepThread->fqnToPyJmethods == NULL) {
        PyObject *methodCache = PyDict_New();
        jepThread->fqnToPyJmethods = methodCache;
    }

    cachedMethodList = PyDict_GetItem(jepThread->fqnToPyJmethods, pyClassName);
    if (cachedMethodList == NULL) {
        PyObject *pyjMethodList = NULL;
        pyjMethodList = PyList_New(0);

        // - GetMethodID fails when you pass the clazz object, it expects
        //   a java.lang.Class jobject.
        // - if you CallObjectMethod with the langClass jclass object,
        //   it'll return an array of methods, but they're methods of the
        //   java.lang.reflect.Method class -- not ->object.
        //
        // so what i did here was find the methodid using langClass,
        // but then i call the method using clazz. methodIds for java
        // classes are shared....

        methodArray = (jobjectArray) (*env)->CallObjectMethod(env, pyjob->clazz,
                      classGetMethods);
        if (process_java_exception(env) || !methodArray) {
            goto EXIT_ERROR;
        }

        // for each method, create a new pyjmethod object
        // and add to the internal methods list.
        len = (*env)->GetArrayLength(env, methodArray);
        for (i = 0; i < len; i++) {
            PyJMethodObject *pymethod = NULL;
            jobject rmethod = NULL;

            rmethod = (*env)->GetObjectArrayElement(env, methodArray, i);

            // make new PyJMethodObject, linked to pyjob
            if (pyjob->object) {
                pymethod = pyjmethod_new(env, rmethod, pyjob);
            } else {
                pymethod = pyjmethod_new_static(env, rmethod, pyjob);
            }

            if (!pymethod) {
                continue;
            }

            if (pymethod->pyMethodName && PyString_Check(pymethod->pyMethodName)) {
                int multi = 0;
                Py_ssize_t cacheLen = PyList_Size(pyjMethodList);
                int cacheIndex = 0;
                for (cacheIndex = 0; cacheIndex < cacheLen; cacheIndex += 1) {
                    PyObject* cached = PyList_GetItem(pyjMethodList, cacheIndex);
                    if (pyjmethod_check(cached)) {
                        PyJMethodObject* cachedMethod = (PyJMethodObject*) cached;
                        if (PyObject_RichCompareBool(pymethod->pyMethodName, cachedMethod->pyMethodName,
                                                     Py_EQ)) {
                            PyObject* multimethod = PyJmultiMethod_New((PyObject*) pymethod, cached);
                            PyList_SetItem(pyjMethodList, cacheIndex, multimethod);
                            multi = 1;
                            break;
                        }
                    } else if (PyJmultiMethod_Check(cached)) {
                        PyObject* methodName = PyJmultiMethod_GetName(cached);
                        if (PyObject_RichCompareBool(pymethod->pyMethodName, methodName, Py_EQ)) {
                            Py_DECREF(methodName);
                            PyJmultiMethod_Append(cached, (PyObject*) pymethod);
                            multi = 1;
                            break;
                        } else {
                            Py_DECREF(methodName);
                        }
                    }
                }
                if (!multi) {
                    if (PyList_Append(pyjMethodList, (PyObject*) pymethod) != 0) {
                        printf("WARNING: couldn't add method");
                    }
                }
            }

            Py_DECREF(pymethod);
            (*env)->DeleteLocalRef(env, rmethod);
        } // end of looping over available methods
        PyDict_SetItem(jepThread->fqnToPyJmethods, pyClassName, pyjMethodList);
        cachedMethodList = pyjMethodList;
        Py_DECREF(pyjMethodList); // fqnToPyJmethods will hold the reference
        (*env)->DeleteLocalRef(env, methodArray);
    } // end of setting up cache for this Java Class

    len = (int) PyList_Size(cachedMethodList);
    for (i = 0; i < len; i++) {
        PyObject* name   = NULL;
        PyObject* cached = PyList_GetItem(cachedMethodList, i);
        if (pyjmethod_check(cached)) {
            PyJMethodObject* cachedMethod = (PyJMethodObject*) cached;
            name = cachedMethod->pyMethodName;
            Py_INCREF(name);
        } else if (PyJmultiMethod_Check(cached)) {
            name = PyJmultiMethod_GetName(cached);
        }
        if (name) {
            if (PyObject_SetAttr((PyObject *) pyjob, name, cached) != 0) {
                PyErr_SetString(PyExc_RuntimeError,
                                "Couldn't add method as attribute.");
            } else {
                pyjobject_addmethod(pyjob, name);
            }
            Py_DECREF(name);
        }
    } // end of cached method optimizations


    // ------------------------------ process fields

    if (classGetFields == 0) {
        classGetFields = (*env)->GetMethodID(env,
                                             langClass,
                                             "getFields",
                                             "()[Ljava/lang/reflect/Field;");
        if (process_java_exception(env) || !classGetFields) {
            goto EXIT_ERROR;
        }
    }

    fieldArray = (jobjectArray) (*env)->CallObjectMethod(env,
                 pyjob->clazz,
                 classGetFields);
    if (process_java_exception(env) || !fieldArray) {
        goto EXIT_ERROR;
    }

    // for each field, create a pyjfield object and
    // add to the internal members list.
    len = (*env)->GetArrayLength(env, fieldArray);
    for (i = 0; i < len; i++) {
        jobject          rfield   = NULL;
        PyJFieldObject *pyjfield = NULL;

        rfield = (*env)->GetObjectArrayElement(env,
                                               fieldArray,
                                               i);

        pyjfield = pyjfield_new(env, rfield, pyjob);

        if (!pyjfield) {
            continue;
        }

        if (pyjfield->pyFieldName && PyString_Check(pyjfield->pyFieldName)) {
            if (PyObject_SetAttr((PyObject *) pyjob,
                                 pyjfield->pyFieldName,
                                 (PyObject *) pyjfield) != 0) {
                printf("WARNING: couldn't add field.\n");
            } else {
                pyjobject_addfield(pyjob, pyjfield->pyFieldName);
            }
        }

        Py_DECREF(pyjfield);
        (*env)->DeleteLocalRef(env, rfield);
    }
    (*env)->DeleteLocalRef(env, fieldArray);

    // we've finished the object.
    pyjob->finishAttr = 1;
    (*env)->PopLocalFrame(env, NULL);
    return 1;


EXIT_ERROR:
    (*env)->PopLocalFrame(env, NULL);

    if (PyErr_Occurred()) { // java exceptions translated by this time
        if (pyjob) {
            pyjobject_dealloc(pyjob);
        }
    }

    return 0;
}
コード例 #19
0
ファイル: lazylinker_c.c プロジェクト: Donghuan/Theano
static
int lazy_rec_eval(CLazyLinker * self, Py_ssize_t var_idx, PyObject*one, PyObject*zero)
{
  PyObject *rval = NULL;
  int verbose = 0;
  int err = 0;

  if (verbose) fprintf(stderr, "lazy_rec computing %i\n", (int)var_idx);

  if (self->var_computed[var_idx] || !self->var_has_owner[var_idx])
    return 0;

  Py_ssize_t owner_idx = self->var_owner[var_idx];

  // STEP 1: compute the pre-requirements of the node
  // Includes input nodes for non-lazy ops.
  for (int i = 0; i < self->node_n_prereqs[owner_idx]; ++i)
    {
      Py_ssize_t prereq_idx = self->node_prereqs[owner_idx][i];
      if (!self->var_computed[prereq_idx])
        {
          err = lazy_rec_eval(self, prereq_idx, one, zero);
          if (err) return err;
        }
      assert (self->var_computed[prereq_idx]);
    }

  // STEP 2: compute the node itself
  if (self->is_lazy[owner_idx])
    {
      // update the compute_map cells corresponding to the inputs of this thunk
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          int in_idx = self->node_inputs[owner_idx][i];
          if (self->var_computed[in_idx])
            {
              Py_INCREF(one);
              err = PyList_SetItem(self->var_computed_cells[in_idx], 0, one);
            }
          else
            {
              Py_INCREF(zero);
              err = PyList_SetItem(self->var_computed_cells[in_idx], 0, zero);
            }
          if (err) goto fail;
        }

      rval = pycall(self, owner_idx, verbose);
      // refcounting - rval is new ref
      //TODO: to prevent infinite loops
      // - consider check that a thunk does not ask for an input that is already computed
      if (rval == NULL)
        {
          assert (PyErr_Occurred());
          err = 1;
          goto fail;
        }

      //update the computed-ness of any output cells
      for (int i = 0; i < self->node_n_outputs[owner_idx]; ++i)
        {
          int out_idx = self->node_outputs[owner_idx][i];
          PyObject * el_i = PyList_GetItem(self->var_computed_cells[out_idx], 0);
          Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
          if (PyErr_Occurred())
            {
              err = -1;
              goto pyfail;
            }
          assert (N==0 || N==1);
          self->var_computed[out_idx] = N;
        }
      if (!self->var_computed[var_idx])
        {
          /*
           * If self is not computed after the call, this means that some
           * inputs are needed.  Compute the ones on the returned list
           * and try to compute the current node again (with recursive call).
           * This allows a node to request more nodes more than once before
           * finally yielding a result.
           */
          if (!PyList_Check(rval))
            {
              //TODO: More helpful error to help find *which node* made this
              // bad thunk
              PyErr_SetString(PyExc_TypeError,
                              "lazy thunk should return a list");
              err = 1;
              goto pyfail;
            }

          if (!PyList_Size(rval))
            {
              PyErr_SetString(PyExc_ValueError,
                              "lazy thunk returned empty list without computing output");
              err = 1;
              goto pyfail;
            }

          for (int i = 0; i < PyList_Size(rval); ++i)
            {
              PyObject * el_i = PyList_GetItem(rval, i);
              Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
              if (PyErr_Occurred())
                {
                  err = 1;
                  goto pyfail;
                }
              assert (N <= self->node_n_inputs[owner_idx]);
              Py_ssize_t input_idx = self->node_inputs[owner_idx][N];
              err = lazy_rec_eval(self, input_idx, one, zero);
              if (err) goto pyfail;
            }

          Py_DECREF(rval);
          /*
           * We intentionally skip all the end-of-function processing
           * (mark outputs, GC) as it will be performed by the call
           * that actually manages to compute the result.
           */
          return lazy_rec_eval(self, var_idx, one, zero);
        }

      Py_DECREF(rval);
    }
  else //owner is not a lazy op. Ensure all intputs are evaluated.
    {
      // loop over inputs to owner
      // call lazy_rec_eval on each one that is not computed.
      // if there's an error, pass it up the stack
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          Py_ssize_t input_idx = self->node_inputs[owner_idx][i];
          if (!self->var_computed[input_idx])
            {
              err = lazy_rec_eval(self, input_idx, one, zero);
              if (err) return err;
            }
          assert (self->var_computed[input_idx]);
        }

      // call the thunk for this owner.
      if (self->thunk_cptr_fn[owner_idx])
        {
          err = c_call(self, owner_idx, verbose);
          if (err) goto fail;
        }
      else
        {
          rval = pycall(self, owner_idx, verbose);
          //rval is new ref
          if (rval) //pycall returned normally (no exception)
            {
              if (rval == Py_None)
                {
                  Py_DECREF(rval); //ignore a return of None
                }
              else if (PyList_Check(rval))
                {
                  PyErr_SetString(PyExc_TypeError,
                                  "non-lazy thunk should return None, not list");
                  err = 1;
                  goto pyfail;
                }
              else // don't know what it returned, but it wasn't right.
                {
                  PyErr_SetObject(PyExc_TypeError, rval);
                  err = 1;
                  // We don't release rval since we put it in the error above
                  goto fail;
                }
            }
          else // pycall returned NULL (internal error)
            {
              err = 1;
              goto fail;
            }
        }
    }

  // loop over all outputs and mark them as computed
  for (int i = 0; i < self->node_n_outputs[owner_idx]; ++i)
    {
      self->var_computed[self->node_outputs[owner_idx][i]] = 1;
    }

  // Free vars that are not needed anymore
  if (self->allow_gc)
    {
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          int cleanup = 1;
          Py_ssize_t i_idx = self->node_inputs[owner_idx][i];
          if (!self->var_has_owner[i_idx])
            continue;

          for (int j = 0; j < self->n_output_vars; ++j)
            {
              if (i_idx == self->output_vars[j])
                {
                  cleanup = 0;
                  break;
                }
            }
          if (!cleanup) continue;

          for (int j = 0; j < self->n_dependencies[i_idx]; ++j)
            {
              if (!self->var_computed[self->dependencies[i_idx][j]])
                {
                  cleanup = 0;
                  break;
                }
            }
          if (!cleanup) continue;

          Py_INCREF(Py_None);
          err = PyList_SetItem(self->var_value_cells[i_idx], 0, Py_None);
//See the Stack gc implementation for why we change it to 2 and not 0.
          self->var_computed[i_idx] = 2;
          if (err) goto fail;
        }
    }

  return 0;
 pyfail:
  Py_DECREF(rval);
 fail:
  set_position_of_error(self, owner_idx);
  return err;
}
コード例 #20
0
ファイル: edgeseqobject.c プロジェクト: bravery/python-igraph
/** \ingroup python_interface_edgeseq
 * \brief Sets the list of values for a given attribute
 */
int igraphmodule_EdgeSeq_set_attribute_values_mapping(igraphmodule_EdgeSeqObject* self, PyObject* attrname, PyObject* values) {
  PyObject *dict, *list, *item;
  igraphmodule_GraphObject *gr;
  igraph_vector_t es;
  long i, j, n, no_of_edges;
  
  gr = self->gref;
  dict = ATTR_STRUCT_DICT(&gr->g)[ATTRHASH_IDX_EDGE];

  if (!igraphmodule_attribute_name_check(attrname))
    return -1;

  if (values == 0) {
    if (igraph_es_type(&self->es) == IGRAPH_ES_ALL)
      return PyDict_DelItem(dict, attrname);
    PyErr_SetString(PyExc_TypeError, "can't delete attribute from an edge sequence not representing the whole graph");
    return -1;
  }

 if (PyString_Check(values) || !PySequence_Check(values)) {
    /* If values is a string or not a sequence, we construct a list with a
     * single element (the value itself) and then call ourselves again */
    int result;
    PyObject *newList = PyList_New(1);
    if (newList == 0) return -1;
    Py_INCREF(values);
    PyList_SET_ITEM(newList, 0, values);    /* reference stolen here */
    result = igraphmodule_EdgeSeq_set_attribute_values_mapping(self, attrname, newList);
    Py_DECREF(newList);
    return result;
  }

  n=PySequence_Size(values);
  if (n<0) return -1;

  if (igraph_es_type(&self->es) == IGRAPH_ES_ALL) {
    no_of_edges = (long)igraph_ecount(&gr->g);
    if (n == 0 && no_of_edges > 0) {
      PyErr_SetString(PyExc_ValueError, "sequence must not be empty");
      return -1;
    }

    /* Check if we already have attributes with the given name */
    list = PyDict_GetItem(dict, attrname);
    if (list != 0) {
      /* Yes, we have. Modify its items to the items found in values */
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) return -1;
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        if (PyList_SetItem(list, i, item)) {
          Py_DECREF(item);
          return -1;
        } /* PyList_SetItem stole a reference to the item automatically */ 
      }
    } else if (values != 0) {
      /* We don't have attributes with the given name yet. Create an entry
       * in the dict, create a new list and copy everything */
      list = PyList_New(no_of_edges);
      if (list == 0) return -1;
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) { Py_DECREF(list); return -1; }
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        PyList_SET_ITEM(list, i, item);
        /* PyList_SET_ITEM stole a reference to the item automatically */
      }
      if (PyDict_SetItem(dict, attrname, list)) {
        Py_DECREF(list);
        return -1;
      }
      Py_DECREF(list);   /* compensating for PyDict_SetItem */
    }
  } else {
    /* We are working with a subset of the graph. Convert the sequence to a
     * vector and loop through it */
    if (igraph_vector_init(&es, 0)) {
      igraphmodule_handle_igraph_error();
      return -1;
    } 
    if (igraph_es_as_vector(&gr->g, self->es, &es)) {
      igraphmodule_handle_igraph_error();
      igraph_vector_destroy(&es);
      return -1;
    }
    no_of_edges = (long)igraph_vector_size(&es);
    if (n == 0 && no_of_edges > 0) {
      PyErr_SetString(PyExc_ValueError, "sequence must not be empty");
      igraph_vector_destroy(&es);
      return -1;
    }
    /* Check if we already have attributes with the given name */
    list = PyDict_GetItem(dict, attrname);
    if (list != 0) {
      /* Yes, we have. Modify its items to the items found in values */
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) { igraph_vector_destroy(&es); return -1; }
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        if (PyList_SetItem(list, (long)VECTOR(es)[i], item)) {
          Py_DECREF(item);
          igraph_vector_destroy(&es);
          return -1;
        } /* PyList_SetItem stole a reference to the item automatically */ 
      }
      igraph_vector_destroy(&es);
    } else if (values != 0) {
      /* We don't have attributes with the given name yet. Create an entry
       * in the dict, create a new list, fill with None for vertices not in the
       * sequence and copy the rest */
      long n2 = igraph_ecount(&gr->g);
      list = PyList_New(n2);
      if (list == 0) { igraph_vector_destroy(&es); return -1; }
      for (i=0; i<n2; i++) {
        Py_INCREF(Py_None);
        PyList_SET_ITEM(list, i, Py_None);
      }
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) {
          igraph_vector_destroy(&es);
          Py_DECREF(list); return -1;
        }
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        PyList_SET_ITEM(list, (long)VECTOR(es)[i], item);
        /* PyList_SET_ITEM stole a reference to the item automatically */
      }
      igraph_vector_destroy(&es);
      if (PyDict_SetItem(dict, attrname, list)) {
        Py_DECREF(list);
        return -1;
      }
      Py_DECREF(list);   /* compensating for PyDict_SetItem */
    }
  }
  return 0;
}
コード例 #21
0
ファイル: py_spoolss_drivers.c プロジェクト: hajuuk/R7000
PyObject *spoolss_enumprinterdrivers(PyObject *self, PyObject *args,
				     PyObject *kw)
{
	WERROR werror;
	PyObject *result = NULL, *creds = NULL;
	PRINTER_DRIVER_CTR ctr;
	int level = 1, i;
	uint32 needed, num_drivers;
	char *arch = "Windows NT x86", *server, *errstr;
	static char *kwlist[] = {"server", "level", "creds", "arch", NULL};
	struct cli_state *cli = NULL;
	TALLOC_CTX *mem_ctx = NULL;
	
	/* Parse parameters */

	if (!PyArg_ParseTupleAndKeywords(
		    args, kw, "s|iOs", kwlist, &server, &level, &creds,
		    &arch)) 
		return NULL;
	
	if (server[0] != '\\' || server[1] != '\\') {
		PyErr_SetString(PyExc_ValueError, "UNC name required");
		return NULL;
	}

	server += 2;

	if (creds && creds != Py_None && !PyDict_Check(creds)) {
		PyErr_SetString(PyExc_TypeError, 
				"credentials must be dictionary or None");
		return NULL;
	}

	/* Call rpc function */
	
	if (!(cli = open_pipe_creds(server, creds, PI_SPOOLSS, &errstr))) {
		PyErr_SetString(spoolss_error, errstr);
		free(errstr);
		goto done;
	}

	if (!(mem_ctx = talloc_init("spoolss_enumprinterdrivers"))) {
		PyErr_SetString(
			spoolss_error, "unable to init talloc context\n");
		goto done;
	}	

	werror = cli_spoolss_enumprinterdrivers(
		cli, mem_ctx, 0, &needed, level, arch,
		&num_drivers, &ctr);

	if (W_ERROR_V(werror) == ERRinsufficientbuffer)
		werror = cli_spoolss_enumprinterdrivers(
			cli, mem_ctx, needed, NULL, level, arch, 
			&num_drivers, &ctr);

	if (!W_ERROR_IS_OK(werror)) {
		PyErr_SetObject(spoolss_werror, py_werror_tuple(werror));
		goto done;
	}

	/* Return value */

	switch (level) {
	case 1:
		result = PyDict_New();
		
		for (i = 0; i < num_drivers; i++) {
			PyObject *value;
			fstring name;
			
			rpcstr_pull(name, ctr.info1[i].name.buffer,
				    sizeof(fstring), -1, STR_TERMINATE);

			py_from_DRIVER_INFO_1(&value, &ctr.info1[i]);

			PyDict_SetItemString(result, name, value);
		}
		
		break;
	case 2: 
		result = PyDict_New();

		for(i = 0; i < num_drivers; i++) {
			PyObject *value;
			fstring name;

			rpcstr_pull(name, ctr.info2[i].name.buffer,
				    sizeof(fstring), -1, STR_TERMINATE);

			py_from_DRIVER_INFO_2(&value, &ctr.info2[i]);

			PyDict_SetItemString(result, name, value);
		}

		break;
	case 3: 
		result = PyDict_New();

		for(i = 0; i < num_drivers; i++) {
			PyObject *value;
			fstring name;

			rpcstr_pull(name, ctr.info3[i].name.buffer,
				    sizeof(fstring), -1, STR_TERMINATE);

			py_from_DRIVER_INFO_3(&value, &ctr.info3[i]);

			PyDict_SetItemString(result, name, value);
		}

		break;
	case 6: 
		result = PyDict_New();

		for(i = 0; i < num_drivers; i++) {
			PyObject *value;
			fstring name;

			rpcstr_pull(name, ctr.info6[i].name.buffer,
				    sizeof(fstring), -1, STR_TERMINATE);

			py_from_DRIVER_INFO_6(&value, &ctr.info6[i]);

			PyList_SetItem(result, i, value);
		}

		break;
	default:
		PyErr_SetString(spoolss_error, "unknown info level");
		goto done;
	}
	
 done:
	if (cli)
		cli_shutdown(cli);

	if (mem_ctx)
		talloc_destroy(mem_ctx);

	return result;
}
コード例 #22
0
ファイル: pyewf.c プロジェクト: eaas-framework/xmount
/* Globs filenames according to the EWF segment file naming schema
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_glob(
           PyObject *self,
           PyObject *arguments,
           PyObject *keywords )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	char **filenames            = NULL;
	liberror_error_t *error     = NULL;
	PyObject *list_object       = NULL;
	PyObject *string_object     = NULL;
	static char *function       = "pyewf_glob";
	static char *keyword_list[] = { "filename", NULL };
	const char *errors          = NULL;
	const char *filename        = NULL;
	size_t filename_length      = 0;
	int filename_index          = 0;
	int number_of_filenames     = 0;

	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "|s",
	     keyword_list,
	     &filename ) == 0 )
	{
		return( NULL );
	}
	filename_length = libcstring_narrow_string_length(
	                   filename );

	if( libewf_glob(
	     filename,
	     filename_length,
	     LIBEWF_FORMAT_UNKNOWN,
	     &filenames,
	     &number_of_filenames,
	     &error ) != 1 )
	{
		if( liberror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to glob filenames.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to glob filenames.\n%s",
			 function,
			 error_string );
		}
		liberror_error_free(
		 &error );

		return( NULL );
	}
	list_object = PyList_New(
	               (Py_ssize_t) number_of_filenames );

	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		filename_length = libcstring_narrow_string_length(
		                   filenames[ filename_index ] );

		string_object = PyUnicode_DecodeUTF8(
		                 filenames[ filename_index ],
		                 filename_length,
		                 errors );

		if( string_object == NULL )
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to convert UTF-8 filename: %d into Unicode.",
			 function,
			 filename_index );

			libewf_glob_free(
			 filenames,
			 number_of_filenames,
			 NULL );

			Py_DecRef(
			 list_object );

			return( NULL );
		}
		if( PyList_SetItem(
		     list_object,
		     (Py_ssize_t) filename_index,
		     string_object ) != 0 )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to set filename: %d in list.",
			 function,
			 filename_index );

			libewf_glob_free(
			 filenames,
			 number_of_filenames,
			 NULL );

			Py_DecRef(
			 string_object );
			Py_DecRef(
			 list_object );

			return( NULL );
		}
	}
	if( libewf_glob_free(
	     filenames,
	     number_of_filenames,
	     &error ) != 1 )
	{
		if( liberror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to free globbed filenames.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to free globbed filenames.\n%s",
			 function,
			 error_string );
		}
		liberror_error_free(
		 &error );

		Py_DecRef(
		 list_object );

		return( NULL );
	}
	return( list_object );
}
コード例 #23
0
static int Printer_init(Printer *self, PyObject * /*args*/, PyObject * /*kwds*/)
{
// pool system for installed printers
// most code is stolen and little adopted from druck.cpp
	PyObject *allPrinters = PyList_New(0);
	if (allPrinters){
		Py_DECREF(self->allPrinters);
		self->allPrinters = allPrinters;
	}
	QStringList printers = PrinterUtil::getPrinterNames();
	for (int i = 0; i < printers.count(); ++i)
	{
		QString prn = printers[i];
		if (prn.isEmpty())
			continue;
		PyObject *tmppr = PyString_FromString(prn.toLocal8Bit().constData());
		if (tmppr){
			PyList_Append(self->allPrinters, tmppr);
			Py_DECREF(tmppr);
		}
	}
	PyObject *tmp2 = PyString_FromString("File");
	PyList_Append(self->allPrinters, tmp2);
	Py_DECREF(tmp2);
// as defaut set to print into file
	PyObject *printer = NULL;
	printer = PyString_FromString("File");
	if (printer){
		Py_DECREF(self->printer);
		self->printer = printer;
	}
// set defaul name of file to print into
	QString tf(ScCore->primaryMainWindow()->doc->pdfOptions().fileName);
	if (tf.isEmpty()) {
		QFileInfo fi = QFileInfo(ScCore->primaryMainWindow()->doc->DocName);
		tf = fi.path()+"/"+fi.baseName()+".pdf";
	}
	PyObject *file = NULL;
	file = PyString_FromString(tf.toLatin1());
	if (file){
		Py_DECREF(self->file);
		self->file = file;
	} else {
		PyErr_SetString(PyExc_SystemError, "Can not initialize 'file' attribute");
		return -1;
	}
// alternative printer commands default to ""
	PyObject *cmd = NULL;
	cmd = PyString_FromString("");
	if (cmd){
		Py_DECREF(self->cmd);
		self->cmd = cmd;
	}
// if document exist when created Printer instance
// set to print all pages
	PyObject *pages = NULL;
	int num = 0;
	if (ScCore->primaryMainWindow()->HaveDoc)
		// which one should I use ???
		// new = ScCore->primaryMainWindow()->view->Pages.count()
		num = ScCore->primaryMainWindow()->doc->Pages->count();
	pages = PyList_New(num);
	if (pages){
		Py_DECREF(self->pages);
		self->pages = pages;
	}
	for (int i = 0; i<num; i++) {
		PyObject *tmp=NULL;
		tmp = PyInt_FromLong((long)i+1L); // instead of 1 put here first page number
		if (tmp)
			PyList_SetItem(self->pages, i, tmp);
	}
// do not print separation
	PyObject *separation = NULL;
	separation = PyString_FromString("No");
	if (separation){
		Py_DECREF(self->separation);
		self->separation = separation;
	}
// print in color
	self->color = 1;
// do not use ICC Profile
	self->useICC = 0;
// use PostScrip level 3
	self->pslevel = 3;
// do not mirror pages
	self->mph = 0;
// do not mirror pages
	self->mpv = 0;
// apply Under Color Removal as default
	self->ucr = 1;
// number of copies
	self->copies = 1;
	return 0;
}
コード例 #24
0
ファイル: pycorba-marshal.c プロジェクト: GNOME/pyorbit
static PyObject *
demarshal_value(CORBA_TypeCode tc, gconstpointer *val)
{
    PyObject *ret = NULL;

    while (tc->kind == CORBA_tk_alias)
	tc = tc->subtypes[0];

    switch (tc->kind) {
    case CORBA_tk_null:
    case CORBA_tk_void:
	ret = Py_None;
	Py_INCREF(ret);
	break;
    case CORBA_tk_short:
	alignval(val, ORBIT_ALIGNOF_CORBA_SHORT);
	ret = PyInt_FromLong(getval(val, CORBA_short));
	advanceptr(val, sizeof(CORBA_short));
	break;
    case CORBA_tk_long:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG);
	ret = PyInt_FromLong(getval(val, CORBA_long));
	advanceptr(val, sizeof(CORBA_long));
	break;
    case CORBA_tk_ushort:
	alignval(val, ORBIT_ALIGNOF_CORBA_SHORT);
	ret = PyInt_FromLong(getval(val, CORBA_unsigned_short));
	advanceptr(val, sizeof(CORBA_unsigned_short));
	break;
    case CORBA_tk_ulong:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG);
	ret = PyLong_FromUnsignedLong(getval(val, CORBA_unsigned_long));
	advanceptr(val, sizeof(CORBA_unsigned_long));
	break;
    case CORBA_tk_float:
	alignval(val, ORBIT_ALIGNOF_CORBA_FLOAT);
	ret = PyFloat_FromDouble(getval(val, CORBA_float));
	advanceptr(val, sizeof(CORBA_float));
	break;
    case CORBA_tk_double:
	alignval(val, ORBIT_ALIGNOF_CORBA_DOUBLE);
	ret = PyFloat_FromDouble(getval(val, CORBA_double));
	advanceptr(val, sizeof(CORBA_double));
	break;
    case CORBA_tk_boolean:
	ret = getval(val, CORBA_boolean) ? Py_True : Py_False;
	Py_INCREF(ret);
	advanceptr(val, sizeof(CORBA_boolean));
	break;
    case CORBA_tk_char: {
	char charbuf[2];

	charbuf[0] = getval(val, CORBA_char);
	charbuf[1] = '\0';
	ret = PyString_FromString(charbuf);
	advanceptr(val, sizeof(CORBA_char));
	break;
    }
    case CORBA_tk_octet:
	ret = PyInt_FromLong(getval(val, CORBA_octet));
	advanceptr(val, sizeof(CORBA_octet));
	break;
    case CORBA_tk_any:
	alignval(val, ORBIT_ALIGNOF_CORBA_ANY);
	ret = pycorba_any_new(&getval(val, CORBA_any));
	advanceptr(val, sizeof(CORBA_any));
	break;
    case CORBA_tk_TypeCode:
	alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	ret = pycorba_typecode_new(getval(val, CORBA_TypeCode));
	advanceptr(val, sizeof(CORBA_TypeCode));
	break;
    case CORBA_tk_Principal:
	g_warning("can't demarshal Principal's");
	break;
    case CORBA_tk_objref:
	alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	ret = pycorba_object_new_with_type(getval(val, CORBA_Object), tc);
	advanceptr(val, sizeof(CORBA_Object));
	break;
    case CORBA_tk_struct:
    case CORBA_tk_except: {
	PyObject *stub;
	PyObject *instance;
	gint i;

	alignval(val, tc->c_align);
	stub = pyorbit_get_stub(tc);
	if (!stub) {
	    if (tc->kind == CORBA_tk_struct)
		stub = (PyObject *)&PyBaseObject_Type;
	    else
		stub = pyorbit_exception;
	}
	instance = PyObject_CallFunction(stub, "()");
	if (!instance)
	    break;
	if (stub == pyorbit_exception) {
	    PyObject *pytc = pycorba_typecode_new(tc);

	    PyObject_SetAttrString(instance, "__typecode__", pytc);
	    Py_DECREF(pytc);
	}
	for (i = 0; i < tc->sub_parts; i++) {
	    PyObject *item;
	    gchar *pyname;

	    item = demarshal_value(tc->subtypes[i], val);
	    if (!item) {
		Py_DECREF(instance);
		break;
	    }
	    pyname = _pyorbit_escape_name(tc->subnames[i]);
	    PyObject_SetAttrString(instance, pyname, item);
	    g_free(pyname);
	    Py_DECREF(item);
	}
	if (i == tc->sub_parts) ret = instance;
	break;
    }
    case CORBA_tk_union: {
	PyObject *stub, *instance, *discrim, *subval;
	CORBA_TypeCode subtc;
	gint i, sz = 0;
	gconstpointer body;

	alignval(val, MAX(tc->c_align, tc->discriminator->c_align));
	stub = pyorbit_get_stub(tc);
	if (!stub) {
	    if (tc->kind == CORBA_tk_struct)
		stub = (PyObject *)&PyBaseObject_Type;
	    else
		stub = PyExc_Exception;
	}
	instance = PyObject_CallFunction(stub, "()");
	if (!instance)
	    break;

	discrim = demarshal_value(tc->discriminator, val);
	if (!discrim) {
	    Py_DECREF(instance);
	    break;
	}
	subtc = get_union_tc(tc, discrim);
	if (!subtc) {
	    Py_DECREF(instance);
	    Py_DECREF(discrim);
	    break;
	}
	PyObject_SetAttrString(instance, "_d", discrim);
	Py_DECREF(discrim);

	for (i = 0; i < tc->sub_parts; i++)
	    sz = MAX(sz, ORBit_gather_alloc_info(tc->subtypes[i]));
	alignval(val, tc->c_align);
	body = *val;

	subval = demarshal_value(subtc, &body);
	if (!subval) {
	    Py_DECREF(instance);
	    break;
	}
	PyObject_SetAttrString(instance, "_v", subval);
	Py_DECREF(subval);

	ret = instance;
	advanceptr(val, sz);
	break;
    }
    case CORBA_tk_enum:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG);
	ret = pycorba_enum_from_long(tc, getval(val, CORBA_unsigned_long));
	advanceptr(val, sizeof(CORBA_unsigned_long));
	break;
    case CORBA_tk_string: {
	CORBA_string str;

	alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	str = getval(val, CORBA_string);
	advanceptr(val, sizeof(CORBA_string));
	if (str) {
	    ret = PyString_FromString(str);
	} else {
	    Py_INCREF(Py_None);
	    ret = Py_None;
	}
	break;
    }
    case CORBA_tk_sequence: {
	const CORBA_sequence_CORBA_octet *sval;
	gconstpointer seqval;

	alignval(val, ORBIT_ALIGNOF_CORBA_SEQ);
	sval = (CORBA_sequence_CORBA_octet *)*val;
	advanceptr(val, sizeof(CORBA_sequence_CORBA_octet));
	switch (tc->subtypes[0]->kind) {
	case CORBA_tk_char:
	case CORBA_tk_octet:
	    ret = PyString_FromStringAndSize((char *) sval->_buffer, sval->_length);
	    break;
	default: {
	    PyObject *list;
	    Py_ssize_t i;
            int align;

	    list = PyList_New(sval->_length);
	    align = tc->subtypes[0]->c_align;
	    seqval = sval->_buffer;
	    for (i = 0; i < sval->_length; i++) {
		PyObject *item;

		alignval(&seqval, align);
		item = demarshal_value(tc->subtypes[0], &seqval);
		if (!item) {
		    Py_DECREF(list);
		    break;
		}
		PyList_SetItem(list, i, item);
	    }
	    if (i == sval->_length) ret = list;
	}
	}
	break;
    }
    case CORBA_tk_array:
	switch (tc->subtypes[0]->kind) {
	case CORBA_tk_char:
	case CORBA_tk_octet:
	    ret = PyString_FromStringAndSize(*val, tc->length);
	    advanceptr(val, tc->length);
	    break;
	default: {
	    PyObject *list;
	    gint i, align;

	    list = PyList_New(tc->length);
	    align = tc->subtypes[0]->c_align;
	    for (i = 0; i < tc->length; i++) {
		PyObject *item;

		alignval(val, align);
		item = demarshal_value(tc->subtypes[0], val);
		if (!item) {
		    Py_DECREF(list);
		    break;
		}
		PyList_SetItem(list, i, item);
	    }
	    if (i == tc->length) ret = list;
	}
	}
	break;
    case CORBA_tk_longlong:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG_LONG);
	ret = PyLong_FromLongLong(getval(val, CORBA_long_long));
	advanceptr(val, sizeof(CORBA_long_long));
	break;
    case CORBA_tk_ulonglong:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG_LONG);
	ret = PyLong_FromUnsignedLongLong(getval(val, CORBA_unsigned_long_long));
	advanceptr(val, sizeof(CORBA_unsigned_long_long));
	break;
    case CORBA_tk_longdouble:
	g_warning("can't demarshal long doubles");
	break;
    case CORBA_tk_wchar: {
	Py_UNICODE uchar;

	alignval(val, ORBIT_ALIGNOF_CORBA_SHORT);
	uchar = getval(val, CORBA_wchar);
	ret = PyUnicode_FromUnicode(&uchar, 1);
	advanceptr(val, sizeof(CORBA_wchar));
	break;
    }
    case CORBA_tk_wstring: {
	CORBA_wstring wstr;

	alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	wstr = getval(val, CORBA_wstring);
	advanceptr(val, sizeof(CORBA_wstring));

	if (wstr) {
	    gint i, length = CORBA_wstring_len(wstr);
	    Py_UNICODE *ustr;

	    ustr = g_new(Py_UNICODE, length);
	    for (i = 0; i < length; i++) ustr[i] = wstr[i];
	    ret = PyUnicode_FromUnicode(ustr, length);
	    g_free(ustr);
	} else {
	    Py_INCREF(Py_None);
	    ret = Py_None;
	}
	break;
    }
    default:
	g_warning("unhandled typecode: %s, (kind==%d)", tc->repo_id, tc->kind);
	break;
    }
    return ret;
}
コード例 #25
0
/**
 *******************************************************************************************************
 * This function will be called with the results with aerospike_batch_read().
 *
 * @param records               A vector list of as_batch_read_record entries
 * @param py_recs               The pyobject to be filled with.
 *
 *******************************************************************************************************
 */
static void batch_get_recs(AerospikeClient *self, as_error *err, as_batch_read_records* records, PyObject **py_recs)
{
    as_vector* list = &records->list;
    for (uint32_t i = 0; i < list->size; i++) {
        as_batch_read_record* batch = as_vector_get(list, i);

        PyObject * rec = NULL;
        PyObject * py_rec = NULL;
        PyObject * p_key = NULL;
        py_rec = PyTuple_New(3);
        p_key = PyTuple_New(4);

        if ( batch->key.ns && strlen(batch->key.ns) > 0 ) {
            PyTuple_SetItem(p_key, 0, PyString_FromString(batch->key.ns));
        }

        if ( batch->key.set && strlen(batch->key.set) > 0 ) {
            PyTuple_SetItem(p_key, 1, PyString_FromString(batch->key.set));
        }

        if(batch->key.valuep) {
            switch(((as_val*)(batch->key.valuep))->type) {
            case AS_INTEGER:
                PyTuple_SetItem(p_key, 2, PyInt_FromLong((long)batch->key.value.integer.value));
                break;

            case AS_STRING:
                PyTuple_SetItem(p_key, 2, PyString_FromString((const char *)batch->key.value.string.value));
                break;
            default:
                break;
            }
        } else {
            Py_INCREF(Py_None);
            PyTuple_SetItem(p_key, 2, Py_None);
        }

        if (batch->key.digest.init) {
            PyTuple_SetItem(p_key, 3, PyByteArray_FromStringAndSize((char *) batch->key.digest.value, AS_DIGEST_VALUE_SIZE));
        }

        PyTuple_SetItem(py_rec, 0, p_key);

        if ( batch->result == AEROSPIKE_OK ) {
            record_to_pyobject(self, err, &batch->record, &batch->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);
            PyList_SetItem( *py_recs, i, py_rec);
            Py_DECREF(rec);
        } else if (batch->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);
            PyList_SetItem( *py_recs, i, py_rec);
        }
    }
}
コード例 #26
0
ファイル: VRPyBase.cpp プロジェクト: Victor-Haefner/polyvr
PyObject* VRPyBase::toPyTuple(const OSG::Vec3d& v) {
    PyObject* res = PyList_New(3);
    for (int i=0; i<3; i++) PyList_SetItem(res, i, PyFloat_FromDouble(v[i]));
    return res;
}
コード例 #27
0
ファイル: _spglib.c プロジェクト: akashneo/pymatgen
static PyObject * get_triplets_reciprocal_mesh(PyObject *self, PyObject *args)
{
  PyArrayObject* mesh;
  int is_time_reversal;
  PyArrayObject* rotations;
  if (!PyArg_ParseTuple(args, "OiO",
			&mesh,
			&is_time_reversal,
			&rotations)) {
    return NULL;
  }

  int i, j, k, num_grid;
  PyObject * triplets, * weights, *tp, *ret_array, *mesh_points;

  int mesh_int[3];
  const long* mesh_long = (long*)mesh->data;
  for (i = 0; i < 3; i++) {
    mesh_int[i] = (int) mesh_long[i];
  }  
  const long* rot_long = (long*)rotations->data;
  const int num_rot = rotations->dimensions[0];
  int rot[num_rot][3][3];
  for (i = 0; i < num_rot; i++) {
    for (j = 0; j < 3; j++) {
      for (k = 0; k < 3; k++) {
	rot[i][j][k] = (int) rot_long[ i*9 + j*3 + k ];
      }
    }
  }

  SpglibTriplets * spg_triplets =
    spg_get_triplets_reciprocal_mesh(mesh_int,
				     is_time_reversal,
				     num_rot,
				     rot);

  num_grid = mesh_int[0] * mesh_int[1] * mesh_int[2];
  ret_array = PyList_New(3);
  triplets = PyList_New(spg_triplets->size);
  weights = PyList_New(spg_triplets->size);
  mesh_points = PyList_New(num_grid);
  
  for (i = 0; i < spg_triplets->size; i++) {
    tp = PyList_New(3);
    for (j = 0; j < 3; j++) {
      PyList_SetItem(tp, j,
		     PyInt_FromLong((long) spg_triplets->triplets[i][j]));
    }
    PyList_SetItem(triplets, i, tp);
    PyList_SetItem(weights, i, PyInt_FromLong((long) spg_triplets->weights[i]));
  }

  for (i = 0; i < num_grid; i++) {
    tp = PyList_New(3);
    for (j = 0; j < 3; j++) {
      PyList_SetItem(tp, j,
		     PyInt_FromLong((long) spg_triplets->mesh_points[i][j]));
    }
    PyList_SetItem(mesh_points, i, tp);
  }

  PyList_SetItem(ret_array, 0, triplets);
  PyList_SetItem(ret_array, 1, weights);
  PyList_SetItem(ret_array, 2, mesh_points);

  spg_free_triplets(spg_triplets);

  return ret_array;
}
コード例 #28
0
ファイル: VRPyBase.cpp プロジェクト: Victor-Haefner/polyvr
PyObject* VRPyBase::toPyTuple(const OSG::Vec4i& v) {
    PyObject* res = PyList_New(4);
    for (int i=0; i<4; i++) PyList_SetItem(res, i, PyInt_FromLong(v[i]));
    return res;
}
コード例 #29
0
ファイル: _spglib.c プロジェクト: arbegla/phonopy
static PyObject * get_dataset(PyObject *self, PyObject *args)
{
  int i, j, k;
  double symprec, angle_tolerance;
  SpglibDataset *dataset;
  PyArrayObject* lattice;
  PyArrayObject* position;
  PyArrayObject* atom_type;
  PyObject* array, *vec, *mat, *rot, *trans, *wyckoffs, *equiv_atoms;
  
  if (!PyArg_ParseTuple(args, "OOOdd",
			&lattice,
			&position,
			&atom_type,
			&symprec,
			&angle_tolerance)) {
    return NULL;
  }

  SPGCONST double (*lat)[3] = (double(*)[3])lattice->data;
  SPGCONST double (*pos)[3] = (double(*)[3])position->data;
  const int num_atom = position->dimensions[0];
  const int* typat = (int*)atom_type->data;

  dataset = spgat_get_dataset(lat,
			      pos,
			      typat,
			      num_atom,
			      symprec,
			      angle_tolerance);

  array = PyList_New(9);

  /* Space group number, international symbol, hall symbol */
  PyList_SetItem(array, 0, PyInt_FromLong((long) dataset->spacegroup_number));
  PyList_SetItem(array, 1, PyString_FromString(dataset->international_symbol));
  PyList_SetItem(array, 2, PyString_FromString(dataset->hall_symbol));

  /* Transformation matrix */
  mat = PyList_New(3);
  for (i = 0; i < 3; i++) {
    vec = PyList_New(3);
    for (j = 0; j < 3; j++) {
      PyList_SetItem(vec, j, PyFloat_FromDouble(dataset->transformation_matrix[i][j]));
    }
    PyList_SetItem(mat, i, vec);
  }
  PyList_SetItem(array, 3, mat);

  /* Origin shift */
  vec = PyList_New(3);
  for (i = 0; i < 3; i++) {
    PyList_SetItem(vec, i, PyFloat_FromDouble(dataset->origin_shift[i]));
  }
  PyList_SetItem(array, 4, vec);

  /* Rotation matrices */
  rot = PyList_New(dataset->n_operations);
  for (i = 0; i < dataset->n_operations; i++) {
    mat = PyList_New(3);
    for (j = 0; j < 3; j++) {
      vec = PyList_New(3);
      for (k = 0; k < 3; k++) {
	PyList_SetItem(vec, k, PyInt_FromLong((long) dataset->rotations[i][j][k]));
      }
      PyList_SetItem(mat, j, vec);
    }
    PyList_SetItem(rot, i, mat);
  }
  PyList_SetItem(array, 5, rot);

  /* Translation vectors */
  trans = PyList_New(dataset->n_operations);
  for (i = 0; i < dataset->n_operations; i++) {
    vec = PyList_New(3);
    for (j = 0; j < 3; j++) {
      PyList_SetItem(vec, j, PyFloat_FromDouble(dataset->translations[i][j]));
    }
    PyList_SetItem(trans, i, vec);
  }
  PyList_SetItem(array, 6, trans);

  /* Wyckoff letters, Equivalent atoms */
  wyckoffs = PyList_New(dataset->n_atoms);
  equiv_atoms = PyList_New(dataset->n_atoms);
  for (i = 0; i < dataset->n_atoms; i++) {
    PyList_SetItem(wyckoffs, i, PyInt_FromLong((long) dataset->wyckoffs[i]));
    PyList_SetItem(equiv_atoms, i, PyInt_FromLong((long) dataset->equivalent_atoms[i]));
  }
  PyList_SetItem(array, 7, wyckoffs);
  PyList_SetItem(array, 8, equiv_atoms);
  spg_free_dataset(dataset);

  return array;
}
コード例 #30
0
ファイル: VRPyBase.cpp プロジェクト: TobiasHue/polyvr
PyObject* VRPyBase::toPyTuple(OSG::Vec2f v) {
    PyObject* res = PyList_New(2);
    for (int i=0; i<2; i++) PyList_SetItem(res, i, PyFloat_FromDouble(v[i]));
    return res;
}