• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PyFloat_Check函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中PyFloat_Check函数的典型用法代码示例。如果您正苦于以下问题:C++ PyFloat_Check函数的具体用法?C++ PyFloat_Check怎么用?C++ PyFloat_Check使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了PyFloat_Check函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: igraphmodule_ARPACKOptions_setattr

/** \ingroup python_interface_arpack
 * \brief Sets one of the attributes of a given ARPACK parameters object
 */
int igraphmodule_ARPACKOptions_setattr(
  igraphmodule_ARPACKOptionsObject* self, char* attrname,
  PyObject* value) {
  if (value == 0) {
    PyErr_SetString(PyExc_TypeError, "attribute can not be deleted");
    return -1;
  }
  if (strcmp(attrname, "maxiter") == 0 ||
      strcmp(attrname, "mxiter") == 0) {
    if (PyInt_Check(value)) {
      long int n=PyInt_AsLong(value);
      if (n>0)
          self->params.mxiter=(igraph_integer_t)n;
      else {
        PyErr_SetString(PyExc_ValueError, "maxiter must be positive");
        return -1;
      }
    } else {
      PyErr_SetString(PyExc_ValueError, "integer expected");
      return -1;
    }
  } else if (strcmp(attrname, "tol") == 0) {
    if (PyInt_Check(value)) {
      self->params.tol = (igraph_real_t) PyInt_AsLong(value);
    } else if (PyFloat_Check(value)) {
      self->params.tol = (igraph_real_t) PyFloat_AsDouble(value);
    } else {
      PyErr_SetString(PyExc_ValueError, "integer or float expected");
      return -1;
    }
  } else {
    PyErr_SetString(PyExc_AttributeError, attrname);
    return -1;
  }

  return 0;
}
开发者ID:CansenJIANG,项目名称:igraph,代码行数:40,代码来源:arpackobject.c


示例2: get_wrapped_ulong

static int
get_wrapped_ulong(PyObject *v, unsigned long *p)
{
	long x = (long)PyLong_AsUnsignedLong(v);
	if (x == -1 && PyErr_Occurred()) {
		PyObject *wrapped;
		PyErr_Clear();
#ifdef PY_STRUCT_FLOAT_COERCE
		if (PyFloat_Check(v)) {
			PyObject *o;
			int res;
			PyErr_Clear();
			if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
				return -1;
			o = PyNumber_Int(v);
			if (o == NULL)
				return -1;
			res = get_wrapped_ulong(o, p);
			Py_DECREF(o);
			return res;
		}
#endif
		wrapped = PyNumber_And(v, pylong_ulong_mask);
		if (wrapped == NULL)
			return -1;
		if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0) {
			Py_DECREF(wrapped);
			return -1;
		}
		x = (long)PyLong_AsUnsignedLong(wrapped);
		Py_DECREF(wrapped);
		if (x == -1 && PyErr_Occurred())
			return -1;
	}
	*p = (unsigned long)x;
	return 0;
}
开发者ID:grobe0ba,项目名称:plan9front,代码行数:37,代码来源:_struct.c


示例3: PyObjectToDVariant

		DVariant PyObjectToDVariant(PyObject* obj) {
			// Do a conversion from python object to DVariant instance
			// Look for the type of the python object

			if (PyLong_Check(obj))
				return DVariant(static_cast<int>(PyLong_AsLong(obj)));
			else if (PyBool_Check(obj))
			{
				if(obj == Py_True)
					return DVariant((bool)true);
				else
					return DVariant((bool)false);
			}
			else if (PyFloat_Check(obj))
				return DVariant((float)PyFloat_AsDouble(obj));
#ifdef IS_PY3K
			else if (PyBytes_Check(obj))
				return DVariant(PyBytes_AsString(obj));
#else
			else if (PyString_Check(obj))
				return DVariant(PyString_AsString(obj));
#endif
			else if (PyModule_Check(obj))
			{
				float x, y, z, w;

				if (PyArg_Parse(obj, "[ffff]", &x, &y, &z, &w)) {
					return DVariant(x, y, z, w);
				} else if (PyArg_Parse(obj, "[fff]", &x, &y, &z)) {
					return DVariant(x, y, z);
				} else
					return DVariant(DVariant::DV_INVALID);

			}

			return DVariant(DVariant::DV_INVALID); //Py_None, or a non-handled type
		}
开发者ID:Painpillow,项目名称:openDarkEngine,代码行数:37,代码来源:bindings.cpp


示例4: Vector3D_setattro

static int Vector3D_setattro(PyVector3D *self, PyObject *oname, PyObject *v)
{
    char * name = PyString_AsString(oname);
    float val;
    if (PyInt_Check(v)) {
        val = PyInt_AsLong(v);
    } else if (PyFloat_Check(v)) {
        val = PyFloat_AsDouble(v);
    } else {
        PyErr_SetString(PyExc_TypeError, "Vector3D attributes must be numeric");
        return -1;
    }
    if (strcmp(name, "x") == 0) {
        self->coords.x() = val;
    } else if (strcmp(name, "y") == 0) {
        self->coords.y() = val;
    } else if (strcmp(name, "z") == 0) {
        self->coords.z() = val;
    } else {
        PyErr_SetString(PyExc_AttributeError, "Vector3D attribute does not exist");
        return -1;
    }
    return 0;
}
开发者ID:alriddoch,项目名称:cyphesis,代码行数:24,代码来源:Py_Vector3D.cpp


示例5: GetPyFloatListToArrayOfDoubles

static double* GetPyFloatListToArrayOfDoubles(const char*const argName,
					      const int requiredSize,
					      const double minVal,
					      const double maxVal,
					      PyObject* pyList) {
  int i, size;
  double* result;
  PyObject* item;

  assert(PyList_Check(pyList));
  size = PyList_GET_SIZE(pyList);
  if (requiredSize != size) {
    PyErr_Format(PyExc_TypeError,"%s:list size should be %i not %i",
		 argName,requiredSize,size);
    return NULL;
  }
  result = SafeCalloc(requiredSize,sizeof(double));
  for (i=0; i<requiredSize; i++) {
    item = PyList_GET_ITEM(pyList,i);
    if (PyInt_Check(item)) result[i] = PyInt_AsLong(item);
    else if (PyFloat_Check(item)) result[i]=PyFloat_AsDouble(item);
    else {
      PyErr_Format(PyExc_TypeError,"%s:element %i not an int or float",
		   argName,i);
      free(result);
      return NULL;
    }
    if (result[i] > maxVal || result[i] < minVal) {
      PyErr_Format(PyExc_TypeError,"%s:element %i not in required range",
		   argName,i);
      free(result);
      return NULL;
    }
  }
  return result;
}
开发者ID:PedersenThomas,项目名称:Fault-Tolerant-Systems,代码行数:36,代码来源:pySAT.c


示例6: pysqlite_statement_bind_parameter

int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter)
{
    int rc = SQLITE_OK;
    long longval;
#ifdef HAVE_LONG_LONG
    PY_LONG_LONG longlongval;
#endif
    const char* buffer;
    char* string;
    Py_ssize_t buflen;
    PyObject* stringval;

    if (parameter == Py_None) {
        rc = sqlite3_bind_null(self->st, pos);
    } else if (PyInt_Check(parameter)) {
        longval = PyInt_AsLong(parameter);
        rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval);
#ifdef HAVE_LONG_LONG
    } else if (PyLong_Check(parameter)) {
        longlongval = PyLong_AsLongLong(parameter);
        /* in the overflow error case, longlongval is -1, and an exception is set */
        rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval);
#endif
    } else if (PyFloat_Check(parameter)) {
        rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
    } else if (PyBuffer_Check(parameter)) {
        if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) {
            rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT);
        } else {
            PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
            rc = -1;
        }
    } else if PyString_Check(parameter) {
        string = PyString_AsString(parameter);
        rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
    } else if PyUnicode_Check(parameter) {
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:36,代码来源:statement.c


示例7: array_power_is_scalar

static int
array_power_is_scalar(PyObject *o2, double* out_exponent)
{
    PyObject *temp;
    const int optimize_fpexps = 1;

    if (PyInt_Check(o2)) {
        *out_exponent = (double)PyInt_AsLong(o2);
        return NPY_INTPOS_SCALAR;
    }
    if (optimize_fpexps && PyFloat_Check(o2)) {
        *out_exponent = PyFloat_AsDouble(o2);
        return NPY_FLOAT_SCALAR;
    }
    if ((PyArray_IsZeroDim(o2) &&
            ((PyArray_ISINTEGER((PyArrayObject *)o2) ||
              (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) ||
            PyArray_IsScalar(o2, Integer) ||
            (optimize_fpexps && PyArray_IsScalar(o2, Floating))) {
        temp = Py_TYPE(o2)->tp_as_number->nb_float(o2);
        if (temp != NULL) {
            *out_exponent = PyFloat_AsDouble(o2);
            Py_DECREF(temp);
            if (PyArray_IsZeroDim(o2)) {
                if (PyArray_ISINTEGER((PyArrayObject *)o2)) {
                    return NPY_INTPOS_SCALAR;
                }
                else { /* ISFLOAT */
                    return NPY_FLOAT_SCALAR;
                }
            }
            else if PyArray_IsScalar(o2, Integer) {
                return NPY_INTPOS_SCALAR;
            }
            else { /* IsScalar(o2, Floating) */
                return NPY_FLOAT_SCALAR;
开发者ID:kumarravi123,项目名称:satire,代码行数:36,代码来源:number.c


示例8: GMPy_MPC_From_Complex

static MPC_Object *
GMPy_MPC_From_Complex(PyObject* obj, mp_prec_t rprec, mp_prec_t iprec,
                           CTXT_Object *context)
{
    CHECK_CONTEXT(context);

    if (MPC_Check(obj))
        return GMPy_MPC_From_MPC((MPC_Object*)obj, rprec, iprec, context);

    if (MPFR_Check(obj))
        return GMPy_MPC_From_MPFR((MPFR_Object*)obj, rprec, iprec, context);

    if (PyFloat_Check(obj))
        return GMPy_MPC_From_PyFloat(obj, rprec, iprec, context);

    if (PyComplex_Check(obj))
        return GMPy_MPC_From_PyComplex(obj, rprec, iprec, context);

    if (MPQ_Check(obj))
        return GMPy_MPC_From_MPQ((MPQ_Object*)obj, rprec, iprec, context);

    if (MPZ_Check(obj) || XMPZ_Check(obj))
        return GMPy_MPC_From_MPZ((MPZ_Object*)obj, rprec, iprec, context);

    if (PyIntOrLong_Check(obj))
        return GMPy_MPC_From_PyIntOrLong(obj, rprec, iprec, context);

    if (IS_DECIMAL(obj))
        return GMPy_MPC_From_Decimal(obj, rprec, iprec, context);

    if (IS_FRACTION(obj))
        return GMPy_MPC_From_Fraction(obj, rprec, iprec, context);

    TYPE_ERROR("object could not be converted to 'mpc'");
    return NULL;
}
开发者ID:martingkelly,项目名称:gmpy,代码行数:36,代码来源:gmpy2_convert_mpc.c


示例9: cdistance_distance

static PyObject *
cdistance_distance(PyObject *self, PyObject *args)
{
    PyObject *resulto, *ratioo, *ret;
    PyObject *cutoffo = Py_None;
    const char *a, *b, *t;
    int cutoff = -1;
    int al, bl, tl;
    float ratio;
    if (!PyArg_ParseTuple(args, "s#s#|O", &a, &al, &b, &bl, &cutoffo))
        return NULL;
    if (al > bl) {
        t = a; tl = al;
        a = b; al = bl;
        b = t; bl = tl;
    }
    if (cutoffo != Py_None) {
        if (PyInt_Check(cutoffo)) {
            cutoff = (int)PyInt_AsLong(cutoffo);
        } else if (PyFloat_Check(cutoffo)) {
            cutoff = (int)(float)(bl-PyFloat_AsDouble(cutoffo)*bl);
        } else {
            PyErr_SetString(PyExc_TypeError, "cutoff must be int or float");
            return NULL;
        }
    }
    resulto = PyInt_FromLong(distance(a, al, b, bl, cutoff, &ratio));
    if (!resulto) return NULL;
    ratioo = PyFloat_FromDouble((double)ratio);
    if (!ratioo) return NULL;
    ret = PyTuple_New(2);
    if (!ret) return NULL;
    PyTuple_SET_ITEM(ret, 0, resulto);
    PyTuple_SET_ITEM(ret, 1, ratioo);
    return ret;
}
开发者ID:bluelightning,项目名称:smart,代码行数:36,代码来源:cdistance.c


示例10: signal

static PyObject *PyCMOR_set_variable_attribute(PyObject * self, PyObject * args)
{
    signal(signal_to_catch, signal_handler);
    char *name;
    char *value;
    char *type;
    long lValue;
    int nValue;
    float fValue;
    double dValue;
    PyObject *oValue;
    int ierr, var_id;
    value = NULL;
    if (!PyArg_ParseTuple(args, "issO", &var_id, &name, &type, &oValue))
        return NULL;

#if PY_MAJOR_VERSION >= 3
    if(PyBytes_Check(oValue)) {
        value = PyBytes_AsString(oValue);
#else
    if(PyString_Check(oValue)) {
        value = PyString_AsString(oValue);
#endif
    } else if(PyLong_Check(oValue)) {
        lValue = PyLong_AsLong(oValue);
    } else if (PyFloat_Check(oValue)) {
        dValue = PyFloat_AsDouble(oValue);
    }

    if (type[0] == 'f') {
        fValue = (float) dValue;
        value = (char *) &fValue;
    } else if (type[0] == 'd') {
        value = (char *) &dValue;
    } else if (type[0] == 'i') {
        nValue = (int) lValue;
        value = (char *) &nValue;
    } else if (type[0] == 'l') {
        value = (char *) &lValue;
    }

    ierr = cmor_set_variable_attribute(var_id, name, type[0], (void *)value);

    if (ierr != 0 || raise_exception) {
        raise_exception = 0;
        PyErr_Format(CMORError, exception_message, "set_variable_attribute");
        return NULL;
    }

    return (Py_BuildValue("i", ierr));
}

/************************************************************************/
/*                   PyCMOR_get_variable_attribute()                    */
/************************************************************************/
static PyObject *PyCMOR_get_variable_attribute(PyObject * self, PyObject * args)
{
    signal(signal_to_catch, signal_handler);
    char *name;
    char value[CMOR_MAX_STRING];
    int ierr, var_id;

    if (!PyArg_ParseTuple(args, "is", &var_id, &name))
        return NULL;

    ierr = cmor_get_variable_attribute(var_id, name, (void *)value);

    if (ierr != 0 || raise_exception) {
        raise_exception = 0;
        PyErr_Format(CMORError, exception_message, "get_variable_attribute");
        return NULL;
    }

    return (Py_BuildValue("s", value));
}
开发者ID:PCMDI,项目名称:cmor,代码行数:75,代码来源:_cmormodule.c


示例11: SaneDev_set_option

static PyObject *
SaneDev_set_option(SaneDevObject *self, PyObject *args)
{
  SANE_Status st;
  const SANE_Option_Descriptor *d;
  SANE_Int i;
  PyObject *value;
  int n;
  void *v;
  
  if (!PyArg_ParseTuple(args, "iO", &n, &value))
    return NULL;
  if (self->h==NULL)
    {
      PyErr_SetString(ErrorObject, "SaneDev object is closed");
      return NULL;
    }
  d=sane_get_option_descriptor(self->h, n);
  v=malloc(d->size+1);

  switch(d->type)
    {
    case(SANE_TYPE_BOOL):
      if (!PyInt_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_BOOL requires an integer");
	  free(v);
	  return NULL;
	}
	/* fall through */
    case(SANE_TYPE_INT):
      if (!PyInt_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_INT requires an integer");
	  free(v);
	  return NULL;
	}
      *( (SANE_Int*)v) = PyInt_AsLong(value);
      break;
    case(SANE_TYPE_FIXED):
      if (!PyFloat_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_FIXED requires a floating point number");
	  free(v);
	  return NULL;
	}
      *( (SANE_Fixed*)v) = SANE_FIX(PyFloat_AsDouble(value));
      break;
    case(SANE_TYPE_STRING):
      if (!PyString_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_STRING requires a string");
	  free(v);
	  return NULL;
	}
      strncpy(v, PyString_AsString(value), d->size-1);
      ((char*)v)[d->size-1] = 0;
      break;
    case(SANE_TYPE_BUTTON): 
    case(SANE_TYPE_GROUP):
      break;
    }
  
  st=sane_control_option(self->h, n, SANE_ACTION_SET_VALUE,
			 v, &i);
  if (st) {free(v); return PySane_Error(st);}
  
  free(v);
  return Py_BuildValue("i", i);
}
开发者ID:10printhello,项目名称:gitpil,代码行数:70,代码来源:_sane.c


示例12: Object_beginTypeContext

void Object_beginTypeContext (PyObject *obj, JSONTypeContext *tc)
{
	TypeContext *pc = (TypeContext *) tc->prv;
	PyObject *toDictFunc;

	tc->prv[0] = 0;
	tc->prv[1] = 0;
	tc->prv[2] = 0;
	tc->prv[3] = 0;
	tc->prv[4] = 0;
	tc->prv[5] = 0;
	tc->prv[6] = 0;
	tc->prv[7] = 0;
	tc->prv[8] = 0;
	tc->prv[9] = 0;
	tc->prv[10] = 0;
	tc->prv[11] = 0;
	tc->prv[12] = 0;
	tc->prv[13] = 0;
	tc->prv[14] = 0;
	
	if (PyIter_Check(obj))
	{
		goto ISITERABLE;
	}

	if (PyBool_Check(obj))
	{
		PRINTMARK();
		tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
		return;
	}
	else
	if (PyInt_Check(obj))
	{
		PRINTMARK();
#ifdef _LP64
		pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
		pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
		return;
	}
	else 
	if (PyLong_Check(obj))
	{
		PyObject *exc;

		PRINTMARK();
		pc->PyTypeToJSON = PyLongToINT64; 
		tc->type = JT_LONG;
		GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

		exc = PyErr_Occurred();

		if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
		{
			PRINTMARK();
			tc->type = JT_INVALID;
			return;
		}

		return;
	}
	else
	if (PyString_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
		return;
	}
	else
	if (PyUnicode_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
		return;
	}
	else
	if (PyFloat_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
		return;
	}
	else 
	if (PyDateTime_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
		return;
	}
	else 
	if (PyDate_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
		return;
	}
	else
//.........这里部分代码省略.........
开发者ID:paintcan,项目名称:ultrajson,代码行数:101,代码来源:objToJSON.c


示例13: GMPy_Real_Add

static PyObject *
GMPy_Real_Add(PyObject *x, PyObject *y, CTXT_Object *context)
{
    MPFR_Object *result;

    CHECK_CONTEXT(context);

    if (!(result = GMPy_MPFR_New(0, context)))
        return NULL;

    if (MPFR_Check(x) && MPFR_Check(y)) {
        mpfr_clear_flags();
        result->rc = mpfr_add(result->f, MPFR(x), MPFR(y), GET_MPFR_ROUND(context));
        goto done;
    }

    if (MPFR_Check(x)) {
        if (PyIntOrLong_Check(y)) {
            mpz_t tempz;
            long temp;
            int error;

            temp = GMPy_Integer_AsLongAndError(y, &error);
            
            if (error) {
                mpz_inoc(tempz);
                mpz_set_PyIntOrLong(tempz, y);
                mpfr_clear_flags();
                result->rc = mpfr_add_z(result->f, MPFR(x), tempz, GET_MPFR_ROUND(context));
                mpz_cloc(tempz);
                goto done;
            }
            else {
                mpfr_clear_flags();
                result->rc = mpfr_add_si(result->f, MPFR(x), temp, GET_MPFR_ROUND(context));
                goto done;
            }
        }

        if (CHECK_MPZANY(y)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_z(result->f, MPFR(x), MPZ(y), GET_MPFR_ROUND(context));
            goto done;
        }

        if (IS_RATIONAL(y)) {
            MPQ_Object *tempy;

            if (!(tempy = GMPy_MPQ_From_Number(y, context))) {
                Py_DECREF((PyObject*)result);
                return NULL;
            }
            mpfr_clear_flags();
            result->rc = mpfr_add_q(result->f, MPFR(x), tempy->q, GET_MPFR_ROUND(context));
            Py_DECREF((PyObject*)tempy);
            goto done;
        }

        if (PyFloat_Check(y)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_d(result->f, MPFR(x), PyFloat_AS_DOUBLE(y), GET_MPFR_ROUND(context));
            goto done;
        }
    }

    if (MPFR_Check(y)) {
        if (PyIntOrLong_Check(x)) {
            mpz_t tempz;
            long temp;
            int error;

            temp = GMPy_Integer_AsLongAndError(x, &error);
            if (error) {
                mpz_inoc(tempz);
                mpz_set_PyIntOrLong(tempz, x);
                mpfr_clear_flags();
                result->rc = mpfr_add_z(result->f, MPFR(y), tempz, GET_MPFR_ROUND(context));
                mpz_cloc(tempz);
                goto done;
            }
            else {
                mpfr_clear_flags();
                result->rc = mpfr_add_si(result->f, MPFR(y), temp, GET_MPFR_ROUND(context));
                goto done;
            }
        }

        if (CHECK_MPZANY(x)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_z(result->f, MPFR(y), MPZ(x), GET_MPFR_ROUND(context));
            goto done;
        }

        if (IS_RATIONAL(x)) {
            MPQ_Object *tempx;

            if (!(tempx = GMPy_MPQ_From_Number(x, context))) {
                Py_DECREF((PyObject*)result);
                return NULL;
            }
//.........这里部分代码省略.........
开发者ID:fuzzylogician,项目名称:gmpy,代码行数:101,代码来源:gmpy2_add.c


示例14: PyObject_GetAttrString

void DataSourceWrapper::GetRow(StringList& row, const String& table, int row_index, const StringList& columns)
{
	PyObject* callable = PyObject_GetAttrString(self, "GetRow");
	if (!callable)
	{
		Core::String error_message(128, "Function \"GetRow\" not found on python data source %s.", Utilities::GetPythonClassName(self).CString());
		Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
		PyErr_SetString(PyExc_RuntimeError, error_message.CString());
		python::throw_error_already_set();
		return;
	}

	python::tuple t = python::make_tuple(table.CString(), row_index, columns);
	PyObject* result = PyObject_CallObject(callable, t.ptr());
	Py_DECREF(callable);	

	// If it's a list, then just get the entries out of it
	if (result && PyList_Check(result))
	{
		int num_entries = PyList_Size(result);
		for (int i = 0; i < num_entries; i++)
		{
			Core::String entry;

			PyObject* entry_object = PyList_GetItem(result, i);
			if (PyString_Check(entry_object))
			{
				entry = PyString_AS_STRING(entry_object);
			}
			else if (PyInt_Check(entry_object))
			{
				int entry_int = (int)PyInt_AS_LONG(entry_object);
				Core::TypeConverter< int, Core::String >::Convert(entry_int, entry);
			}
			else if (PyFloat_Check(entry_object))
			{
				float entry_float = (float)PyFloat_AS_DOUBLE(entry_object);
				Core::TypeConverter< float, Core::String >::Convert(entry_float, entry);
			}
			else
			{
				Core::String error_message(128, "Failed to convert row %d entry %d on data source %s.", row_index, i, Utilities::GetPythonClassName(self).CString());
				Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
				PyErr_SetString(PyExc_RuntimeError, error_message.CString());
				python::throw_error_already_set();
			}

			row.push_back(entry);
		}
	}
	else
	{
		// Print the error and restore it to the caller
		PyObject *type, *value, *traceback;
		PyErr_Fetch(&type, &value, &traceback);
		Py_XINCREF(type);
		Py_XINCREF(value);
		Py_XINCREF(traceback);

		Core::String error_message(128, "Failed to get entries for table %s row %d from python data source %s.", table.CString(), row_index, Utilities::GetPythonClassName(self).CString());
		Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
		if (type == NULL)
			PyErr_SetString(PyExc_RuntimeError, error_message.CString());
		else
			PyErr_Restore(type, value, traceback);

		python::throw_error_already_set();
	}

	if (result)
		Py_DECREF(result);
}
开发者ID:LiberatorUSA,项目名称:GUCEF,代码行数:72,代码来源:DataSourceWrapper.cpp


示例15: GetJSONVectorFromPyObject

bool
GetJSONVectorFromPyObject(PyObject *obj, JSONNode &vec)
{
    bool retval = true;

    if(obj == 0)
    {
        retval = false;
    }
    else if(PyBool_Check(obj))
    {
        vec = obj == Py_True ? true : false;
    }
    else if(PyTuple_Check(obj))
    {
        // Extract arguments from the tuple.
        vec = JSONNode::JSONArray();

        for(int i = 0; i < PyTuple_Size(obj); ++i)
        {
            PyObject *item = PyTuple_GET_ITEM(obj, i);
            JSONNode node;
            if(!GetJSONVectorFromPyObject(item,node))
                return false;
            vec.Append(node);
        }
    }
    else if(PyList_Check(obj))
    {
        vec = JSONNode::JSONArray();

        // Extract arguments from the list.
        for(int i = 0; i < PyList_Size(obj); ++i)
        {
            PyObject *item = PyList_GET_ITEM(obj, i);
            JSONNode node;
            if(!GetJSONVectorFromPyObject(item,node))
                return false;
            vec.Append(node);
        }
    }
    else if(PyString_Check(obj))
    {
        vec = PyString_AS_STRING(obj);
    }
    else if(PyInt_Check(obj))
    {
        vec = PyInt_AsLong(obj);
    }
    else if(PyFloat_Check(obj))
    {
        vec = PyFloat_AsDouble(obj);
    }
    else if(PyDict_Check(obj))
    {
        vec = JSONNode::JSONObject();

        PyObject* keys = PyDict_Keys(obj);
        for(int i = 0; i < PyList_Size(keys); ++i)
        {
            PyObject *item = PyList_GET_ITEM(keys, i);
            if(!PyString_Check(item))
            {
                std::cerr << "unknown element type, skipping " << std::endl;
                continue;
            }

            JSONNode node;

            std::string key = PyString_AsString(item);

            PyObject *value = PyDict_GetItem(obj,item);
            if(!GetJSONVectorFromPyObject(value,node))
                return false;
            vec[key] = node;
        }
    }
    else
    {
        retval = false;
        VisItErrorFunc("The object could not be converted to a "
                       "vector of strings.");
    }

    return retval;
}
开发者ID:burlen,项目名称:visit_vtk_7_src,代码行数:86,代码来源:PyProgrammableOpAttributes.C


示例16: PyObject_AsQVariant

/* Convert a Python object to a QVariant */
QVariant PyObject_AsQVariant(PyObject *obj)
{
    // Dict -> QVariantHash
    if (PyDict_Check(obj))
    {
        QVariantHash result;
        Py_ssize_t pos = 0;
        PyObject *pykey, *pyval;
        while (PyDict_Next(obj, &pos, &pykey, &pyval))
        {
            QString key = PyString_AsQString(pykey);
            result[key] = PyObject_AsQVariant(pyval);
        }
        return result;
    }
    // List -> QVariantList
    else if (PyList_Check(obj))
    {
        QVariantList result;
        Py_ssize_t len = PyList_Size(obj);
        for (Py_ssize_t i = 0; i < len; i++)
        {
            PyObject *item = PyList_GetItem(obj, i);
            result << PyObject_AsQVariant(item);
        }
        return result;
    }
    // Tuple -> QVariantList
    else if (PyTuple_Check(obj))
    {
        QVariantList result;
        Py_ssize_t len = PyTuple_Size(obj);
        for (Py_ssize_t i = 0; i < len; i++)
        {
            PyObject *item = PyTuple_GetItem(obj, i);
            result << PyObject_AsQVariant(item);
        }
        return result;
    }
    // Long
    else if (PyLong_Check(obj))
        return PyLong_AsLongLong(obj);

    // Int
#if PY_MAJOR_VERSION == 2
    else if (PyInt_Check(obj))
        return (long long) PyInt_AsLong(obj);
#endif

    // Float
    else if (PyFloat_Check(obj))
        return PyFloat_AsDouble(obj);

    // String
#if PY_MAJOR_VERSION >= 3
    else if (PyUnicode_Check(obj) || PyByteArray_Check(obj))
#else
    else if (PyUnicode_Check(obj) || PyString_Check(obj))
#endif
        return PyString_AsQString(obj);

    // Unknown
    else
    {
        qDebug("Error: convert an PyObject of unknown type to QVariant.");
        return QVariant();
    }
}
开发者ID:coslyk,项目名称:moonplayer,代码行数:69,代码来源:python_wrapper.cpp


示例17: AerospikeClient_Operate_Invoke


//.........这里部分代码省略.........
				goto CLEANUP;
			}

			switch(operation) {
				case AS_OPERATOR_APPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
					} else {
						val = PyString_AsString(py_value);
					}
					as_operations_add_append_str(&ops, bin, val);
					break;
				case AS_OPERATOR_PREPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
					} else {
						val = PyString_AsString(py_value);
					}
					as_operations_add_prepend_str(&ops, bin, val);
					break;
				case AS_OPERATOR_INCR:
					if (PyInt_Check(py_value)) {
                        offset = PyInt_AsLong(py_value);
                        as_operations_add_incr(&ops, bin, offset);
                    } else if ( PyLong_Check(py_value) ) {
                        offset = PyLong_AsLong(py_value);
                        if(-1 == offset) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        as_operations_add_incr(&ops, bin, offset);
                    } else if (PyFloat_Check(py_value)) {
                        double_offset = PyFloat_AsDouble(py_value);
                        as_operations_add_incr_double(&ops, bin, double_offset);
                    }
                    break;
				case AS_OPERATOR_TOUCH:
					if (PyInt_Check(py_value)) {
                        ops.ttl = PyInt_AsLong(py_value);
                    } else if ( PyLong_Check(py_value) ) {
                        ttl = PyLong_AsLong(py_value);
                        if((uint32_t)-1 == ttl) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for ttl exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        ops.ttl = ttl;
                    }
					as_operations_add_touch(&ops);
					break;
				case AS_OPERATOR_READ:
					as_operations_add_read(&ops, bin);
					break;
				case AS_OPERATOR_WRITE:
					pyobject_to_astype_write(self, err, bin, py_value, &put_val, &ops,
							&static_pool, SERIALIZER_PYTHON);
					if (err->code != AEROSPIKE_OK) {
						goto CLEANUP;
					}
					as_operations_add_write(&ops, bin, (as_bin_value *) put_val);
					break;
				default:
					as_error_update(err, AEROSPIKE_ERR_PARAM, "Invalid operation given");
			}
		}
开发者ID:arthurprs,项目名称:aerospike-client-python,代码行数:67,代码来源:operate.c


示例18: PyPath_Flatten

int
PyPath_Flatten(PyObject* data, double **pxy)
{
    int i, j, n;
    double *xy;
    PyBufferProcs *buffer;
	Py_buffer view;

    if (PyPath_Check(data)) {
	/* This was another path object. */
	PyPathObject *path = (PyPathObject*) data;
        xy = alloc_array(path->count);
	if (!xy)
	    return -1;
	memcpy(xy, path->xy, 2 * path->count * sizeof(double));
	*pxy = xy;
	return path->count;
    }
	
    buffer = Py_TYPE(data)->tp_as_buffer;
    if (buffer && buffer->bf_getbuffer &&
			 (*buffer->bf_getbuffer)(data, &view, PyBUF_SIMPLE) == 1) {
        /* Assume the buffer contains floats */
        float* ptr;
        int n = view.len;
	    PyBuffer_Release(&view);
        n /= 2 * sizeof(float);
        xy = alloc_array(n);
        if (!xy)
            return -1;
        for (i = 0; i < n+n; i++)
            xy[i] = ptr[i];
        *pxy = xy;
        return n;
    }

    if (!PySequence_Check(data)) {
	PyErr_SetString(PyExc_TypeError, "argument must be sequence");
	return -1;
    }

    j = 0;
    n = PyObject_Length(data);
    /* Just in case __len__ breaks (or doesn't exist) */
    if (PyErr_Occurred())
        return -1;

    /* Allocate for worst case */
    xy = alloc_array(n);
    if (!xy)
	return -1;

    /* Copy table to path array */
    if (PyList_Check(data)) {
        for (i = 0; i < n; i++) {
            double x, y;
            PyObject *op = PyList_GET_ITEM(data, i);
            if (PyFloat_Check(op))
		xy[j++] = PyFloat_AS_DOUBLE(op);
            else if (PyLong_Check(op))
		xy[j++] = (float) PyLong_AS_LONG(op);
            else if (PyNumber_Check(op))
                xy[j++] = PyFloat_AsDouble(op);
            else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
                xy[j++] = x;
                xy[j++] = y;
            } else {
                free(xy);
                return -1;
            }
        }
    } else if (PyTuple_Check(data)) {
        for (i = 0; i < n; i++) {
            double x, y;
            PyObject *op = PyTuple_GET_ITEM(data, i);
            if (PyFloat_Check(op))
		xy[j++] = PyFloat_AS_DOUBLE(op);
            else if (PyLong_Check(op))
		xy[j++] = (float) PyLong_AS_LONG(op);
            else if (PyNumber_Check(op))
                xy[j++] = PyFloat_AsDouble(op);
            else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
                xy[j++] = x;
                xy[j++] = y;
            } else {
                free(xy);
                return -1;
            }
        }
    } else {
        for (i = 0; i < n; i++) {
            double x, y;
            PyObject *op = PySequence_GetItem(data, i);
            if (!op) {
                /* treat IndexError as end of sequence */
                if (PyErr_Occurred() &&
                    PyErr_ExceptionMatches(PyExc_IndexError)) {
                    PyErr_Clear();
                    break;
                } else {
//.........这里部分代码省略.........
开发者ID:agross91,项目名称:pil-py3k,代码行数:101,代码来源:path.c


示例19: complex_new


//.........这里部分代码省略.........
	/* XXX Hack to support classes with __complex__ method */
	if (complexstr == NULL) {
		complexstr = PyString_InternFromString("__complex__");
		if (complexstr == NULL)
			return NULL;
	}
	f = PyObject_GetAttr(r, complexstr);
	if (f == NULL)
		PyErr_Clear();
	else {
		PyObject *args = PyTuple_New(0);
		if (args == NULL)
			return NULL;
		r = PyEval_CallObject(f, args);
		Py_DECREF(args);
		Py_DECREF(f);
		if (r == NULL)
			return NULL;
		own_r = 1;
	}
	nbr = r->ob_type->tp_as_number;
	if (i != NULL)
		nbi = i->ob_type->tp_as_number;
	if (nbr == NULL || nbr->nb_float == NULL ||
	    ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
		PyErr_SetString(PyExc_TypeError,
			   "complex() argument must be a string or a number");
		if (own_r) {
			Py_DECREF(r);
		}
		return NULL;
	}

	/* If we get this far, then the "real" and "imag" parts should
	   both be treated as numbers, and the constructor should return a
	   complex number equal to (real + imag*1j).

 	   Note that we do NOT assume the input to already be in canonical
	   form; the "real" and "imag" parts might themselves be complex
	   numbers, which slightly complicates the code below. */
	if (PyComplex_Check(r)) {
		/* Note that if r is of a complex subtype, we're only
		   retaining its real & imag parts here, and the return
		   value is (properly) of the builtin complex type. */
		cr = ((PyComplexObject*)r)->cval;
		cr_is_complex = 1;
		if (own_r) {
			Py_DECREF(r);
		}
	}
	else {
		/* The "real" part really is entirely real, and contributes
		   nothing in the imaginary direction.  
		   Just treat it as a double. */
		tmp = PyNumber_Float(r);
		if (own_r) {
			/* r was a newly created complex number, rather
			   than the original "real" argument. */
			Py_DECREF(r);
		}
		if (tmp == NULL)
			return NULL;
		if (!PyFloat_Check(tmp)) {
			PyErr_SetString(PyExc_TypeError,
					"float(r) didn't return a float");
			Py_DECREF(tmp);
			return NULL;
		}
		cr.real = PyFloat_AsDouble(tmp);
		cr.imag = 0.0; /* Shut up compiler warning */
		Py_DECREF(tmp);
	}
	if (i == NULL) {
		ci.real = 0.0;
	}
	else if (PyComplex_Check(i)) {
		ci = ((PyComplexObject*)i)->cval;
		ci_is_complex = 1;
	} else {
		/* The "imag" part really is entirely imaginary, and
		   contributes nothing in the real direction.
		   Just treat it as a double. */
		tmp = (*nbi->nb_float)(i);
		if (tmp == NULL)
			return NULL;
		ci.real = PyFloat_AsDouble(tmp);
		Py_DECREF(tmp);
	}
	/*  If the input was in canonical form, then the "real" and "imag"
	    parts are real numbers, so that ci.imag and cr.imag are zero.
	    We need this correction in case they were not real numbers. */

	if (ci_is_complex) {
		cr.real -= ci.imag;
	}
	if (cr_is_complex) {
		ci.real += cr.imag;
	}
	return complex_subtype_from_doubles(type, cr.real, ci.real);
}
开发者ID:santagada,项目名称:wpython,代码行数:101,代码来源:complexobject.c


示例20: PySequence_to_CvArr


//.........这里部分代码省略.........
  {
    Py_DECREF (container[2]);
  }
  if (container[3])
  {
    Py_DECREF (container[3]);
  }
  
  // it only makes sense to support 2 and 3 dimensional data at this time
  if (ndim < 2 || ndim > 3)
  {
    PyErr_SetString (PyExc_TypeError, "Nested sequences should have 2 or 3 dimensions");
    return NULL;
  }
  
  // also, the number of channels should match what's typical for OpenCV
  if (ndim == 3  &&  (dims[2] < 1  ||  dims[2] > 4))
  {
    PyErr_SetString (PyExc_TypeError, "Currently, the third dimension of CvMat only supports 1 to 4 channels");
    return NULL;
  }
  
  // CvMat
  CvMat * matrix = cvCreateMat (dims[0], dims[1], CV_MAKETYPE (CV_64F, dims[2]));
  
  for (int y = 0; y < dims[0]; y++)
  {
    PyObject * rowobj = PySequence_GetItem (obj, y);
    
    // double check size
    if (PySequence_Check (rowobj)  &&  PySequence_Size (rowobj) == dims[1])
    {
      for (int x = 0; x < dims[1]; x++)
      {
        PyObject * colobj = PySequence_GetItem (rowobj, x);
        
        if (dims [2] > 1)
        {
          if (PySequence_Check (colobj)  &&  PySequence_Size (colobj) == dims[2])
          {
            PyObject * tuple = PySequence_Tuple (colobj);
            
            double  a, b, c, d;
            if (PyArg_ParseTuple (colobj, "d|d|d|d", &a, &b, &c, &d))
            {
              cvSet2D (matrix, y, x, cvScalar (a, b, c, d));
            }
            else 
            {
              PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float");
              cvReleaseMat (& matrix);
              Py_DECREF (tuple);
              Py_DECREF (colobj);
              Py_DECREF (rowobj);
              return NULL;
            }

            Py_DECREF (tuple);
          }
          else
          {
            PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
            cvReleaseMat (& matrix);
            Py_DECREF (colobj);
            Py_DECREF (rowobj); 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PyFloat_FromDouble函数代码示例发布时间:2022-05-30
下一篇:
C++ PyFloat_AsDouble函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap