当前位置: 首页>>代码示例>>C++>>正文


C++ PySequence_Check函数代码示例

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


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

示例1: test_neighborhood_iterator

static PyObject*
test_neighborhood_iterator(PyObject* NPY_UNUSED(self), PyObject* args)
{
    PyObject *x, *fill, *out, *b;
    PyArrayObject *ax, *afill;
    PyArrayIterObject *itx;
    int i, typenum, mode, st;
    npy_intp bounds[NPY_MAXDIMS*2];
    PyArrayNeighborhoodIterObject *niterx;

    if (!PyArg_ParseTuple(args, "OOOi", &x, &b, &fill, &mode)) {
        return NULL;
    }

    if (!PySequence_Check(b)) {
        return NULL;
    }

    typenum = PyArray_ObjectType(x, 0);
    typenum = PyArray_ObjectType(fill, typenum);

    ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10);
    if (ax == NULL) {
        return NULL;
    }
    if (PySequence_Size(b) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence size not compatible with x input");
        goto clean_ax;
    }

    out = PyList_New(0);
    if (out == NULL) {
        goto clean_ax;
    }

    itx = (PyArrayIterObject*)PyArray_IterNew(x);
    if (itx == NULL) {
        goto clean_out;
    }

    /* Compute boundaries for the neighborhood iterator */
    for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) {
        PyObject* bound;
        bound = PySequence_GetItem(b, i);
        if (bounds == NULL) {
            goto clean_itx;
        }
        if (!PyInt_Check(bound)) {
            PyErr_SetString(PyExc_ValueError,
                    "bound not long");
            Py_DECREF(bound);
            goto clean_itx;
        }
        bounds[i] = PyInt_AsLong(bound);
        Py_DECREF(bound);
    }

    /* Create the neighborhood iterator */
    afill = NULL;
    if (mode == NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING) {
            afill = (PyArrayObject *)PyArray_FromObject(fill, typenum, 0, 0);
            if (afill == NULL) {
            goto clean_itx;
        }
    }

    niterx = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)itx, bounds, mode, afill);
    if (niterx == NULL) {
        goto clean_afill;
    }

    switch (typenum) {
        case NPY_OBJECT:
            st = copy_object(itx, niterx, bounds, &out);
            break;
        case NPY_INT:
            st = copy_int(itx, niterx, bounds, &out);
            break;
        case NPY_DOUBLE:
            st = copy_double(itx, niterx, bounds, &out);
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                    "Type not supported");
            goto clean_niterx;
    }

    if (st) {
        goto clean_niterx;
    }

    Py_DECREF(niterx);
    Py_XDECREF(afill);
    Py_DECREF(itx);

    Py_DECREF(ax);

    return out;
//.........这里部分代码省略.........
开发者ID:adevabhaktuni,项目名称:LADS,代码行数:101,代码来源:multiarray_tests.c

示例2: MGLContext_meth_framebuffer

/* MGLContext.framebuffer(...)
 */
PyObject * MGLContext_meth_framebuffer(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {
    if (nargs != 2) {
        PyErr_Format(moderngl_error, "num args");
        return 0;
    }

    PyObject * color_attachments = args[0];
    PyObject * depth_attachment = args[1];

    if (!PySequence_Check(color_attachments)) {
        PyObject * tuple = PyTuple_New(1);
        PyTuple_SET_ITEM(tuple, 0, color_attachments);
        color_attachments = tuple;
    } else {
        color_attachments = PySequence_Fast(color_attachments, "not iterable");
    }

    MGLFramebuffer * framebuffer = MGLContext_new_object(self, Framebuffer);

    const GLMethods & gl = self->gl;
    gl.GenFramebuffers(1, (GLuint *)&framebuffer->framebuffer_obj);

    if (!framebuffer->framebuffer_obj) {
        return 0;
    }

    self->bind_framebuffer(framebuffer->framebuffer_obj);

    int color_attachments_len = (int)PySequence_Fast_GET_SIZE(color_attachments);

    int width, height, samples;

    for (int i = 0; i < color_attachments_len; ++i) {
        PyObject * attachment = PySequence_Fast_GET_ITEM(color_attachments, i);
        if (attachment->ob_type == Renderbuffer_class) {
            MGLRenderbuffer * renderbuffer = SLOT(attachment, MGLRenderbuffer, Renderbuffer_class_mglo);
            framebuffer->attachment_type[i] = renderbuffer->data_type->shape;
            width = renderbuffer->width;
            height = renderbuffer->height;
            samples = renderbuffer->samples;
            gl.FramebufferRenderbuffer(
                GL_FRAMEBUFFER,
                GL_COLOR_ATTACHMENT0 + i,
                GL_RENDERBUFFER,
                renderbuffer->renderbuffer_obj
            );
        } else if (attachment->ob_type == Texture_class) {
            int level = PyLong_AsLong(SLOT(attachment, PyObject, Texture_class_level));
            MGLTexture * texture = SLOT(attachment, MGLTexture, Texture_class_mglo);
            framebuffer->attachment_type[i] = texture->data_type->shape;
            width = texture->width;
            height = texture->height;
            samples = texture->samples;
            if (texture->texture_target == GL_TEXTURE_CUBE_MAP) {
                gl.FramebufferTexture(
                    GL_FRAMEBUFFER,
                    GL_COLOR_ATTACHMENT0 + i,
                    texture->texture_obj,
                    level
                );
            } else {
                gl.FramebufferTexture2D(
                    GL_FRAMEBUFFER,
                    GL_COLOR_ATTACHMENT0 + i,
                    texture->texture_target,
                    texture->texture_obj,
                    level
                );
            }
        } else {
            return 0;
        }
    }

    // TODO:
    framebuffer->width = width;
    framebuffer->height = height;
    framebuffer->samples = samples;

    Py_DECREF(color_attachments);

    if (depth_attachment != Py_None) {
        if (depth_attachment->ob_type == Renderbuffer_class) {
            MGLRenderbuffer * renderbuffer = SLOT(depth_attachment, MGLRenderbuffer, Renderbuffer_class_mglo);
            gl.FramebufferRenderbuffer(
                GL_FRAMEBUFFER,
                GL_DEPTH_ATTACHMENT,
                GL_RENDERBUFFER,
                renderbuffer->renderbuffer_obj
            );
        } else if (depth_attachment->ob_type == Texture_class) {
            int level = PyLong_AsLong(SLOT(depth_attachment, PyObject, Texture_class_level));
            MGLTexture * texture = SLOT(depth_attachment, MGLTexture, Texture_class_mglo);
            if (texture->texture_target == GL_TEXTURE_CUBE_MAP) {
                gl.FramebufferTexture(
                    GL_FRAMEBUFFER,
                    GL_DEPTH_ATTACHMENT,
                    texture->texture_obj,
//.........这里部分代码省略.........
开发者ID:cprogrammer1994,项目名称:ModernGL,代码行数:101,代码来源:framebuffer.cpp

示例3: PyErr_SetString

/* note, this is called as a python getset */
int PyObjectPlus::py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef)
{
	PyObjectPlus *ref= (BGE_PROXY_REF(self_py));
	char* ptr = (attrdef->m_usePtr) ? (char*)BGE_PROXY_PTR(self_py) : (char*)ref;
	if (ref==NULL || !ref->py_is_valid() || ptr==NULL) {
		PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
		return PY_SET_ATTR_FAIL;
	}

	void *undoBuffer = NULL;
	void *sourceBuffer = NULL;
	size_t bufferSize = 0;
	PyObject *item = NULL;	// to store object that must be dereferenced in case of error
	PyObject *list = NULL;	// to store object that must be dereferenced in case of error
	
	ptr += attrdef->m_offset;
	if (attrdef->m_length > 1)
	{
		if (!PySequence_Check(value)) 
		{
			PyErr_Format(PyExc_TypeError, "expected a sequence for attribute \"%s\"", attrdef->m_name);
			return PY_SET_ATTR_FAIL;
		}
		if (PySequence_Size(value) != attrdef->m_length)
		{
			PyErr_Format(PyExc_TypeError, "incorrect number of elements in sequence for attribute \"%s\"", attrdef->m_name);
			return PY_SET_ATTR_FAIL;
		}
		switch (attrdef->m_type) 
		{
		case KX_PYATTRIBUTE_TYPE_FUNCTION:
			if (attrdef->m_setFunction == NULL) 
			{
				PyErr_Format(PyExc_AttributeError, "function attribute without function for attribute \"%s\", report to blender.org", attrdef->m_name);
				return PY_SET_ATTR_FAIL;
			}
			return (*attrdef->m_setFunction)(ref, attrdef, value);
		case KX_PYATTRIBUTE_TYPE_BOOL:
			bufferSize = sizeof(bool);
			break;
		case KX_PYATTRIBUTE_TYPE_SHORT:
			bufferSize = sizeof(short int);
			break;
		case KX_PYATTRIBUTE_TYPE_ENUM:
		case KX_PYATTRIBUTE_TYPE_INT:
			bufferSize = sizeof(int);
			break;
		case KX_PYATTRIBUTE_TYPE_FLOAT:
			bufferSize = sizeof(float);
			break;
		default:
			// should not happen
			PyErr_Format(PyExc_AttributeError, "Unsupported attribute type for attribute \"%s\", report to blender.org", attrdef->m_name);
			return PY_SET_ATTR_FAIL;
		}
		// let's implement a smart undo method
		bufferSize *= attrdef->m_length;
		undoBuffer = malloc(bufferSize);
		sourceBuffer = ptr;
		if (undoBuffer)
		{
			memcpy(undoBuffer, sourceBuffer, bufferSize);
		}
		for (int i=0; i<attrdef->m_length; i++)
		{
			item = PySequence_GetItem(value, i); /* new ref */
			switch (attrdef->m_type) 
			{
			case KX_PYATTRIBUTE_TYPE_BOOL:
				{
					bool *var = reinterpret_cast<bool*>(ptr);
					ptr += sizeof(bool);
					if (PyLong_Check(item)) 
					{
						*var = (PyLong_AsLong(item) != 0);
					} 
					else if (PyBool_Check(item))
					{
						*var = (item == Py_True);
					}
					else
					{
						PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
						goto UNDO_AND_ERROR;
					}
					break;
				}
			case KX_PYATTRIBUTE_TYPE_SHORT:
				{
					short int *var = reinterpret_cast<short int*>(ptr);
					ptr += sizeof(short int);
					if (PyLong_Check(item)) 
					{
						int val = PyLong_AsLong(item);
						if (attrdef->m_clamp)
						{
							if (val < attrdef->m_imin)
								val = attrdef->m_imin;
							else if (val > attrdef->m_imax)
//.........这里部分代码省略.........
开发者ID:akonneker,项目名称:blensor,代码行数:101,代码来源:PyObjectPlus.cpp

示例4: igraphmodule_EdgeSeq_set_attribute_values_mapping

/** \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 */
//.........这里部分代码省略.........
开发者ID:bravery,项目名称:python-igraph,代码行数:101,代码来源:edgeseqobject.c

示例5: JPy_array

PyObject* JPy_array(PyObject* self, PyObject* args)
{
    JNIEnv* jenv;
    JPy_JType* componentType;
    jarray arrayRef;
    PyObject* objType;
    PyObject* objInit;

    JPy_GET_JNI_ENV_OR_RETURN(jenv, NULL)

    if (!PyArg_ParseTuple(args, "OO:array", &objType, &objInit)) {
        return NULL;
    }

    if (JPy_IS_STR(objType)) {
        const char* typeName;
        typeName = JPy_AS_UTF8(objType);
        componentType = JType_GetTypeForName(jenv, typeName, JNI_FALSE);
        if (componentType == NULL) {
            return NULL;
        }
    } else if (JType_Check(objType)) {
        componentType = (JPy_JType*) objType;
    } else {
        PyErr_SetString(PyExc_ValueError, "array: argument 1 (type) must be a type name or Java type object");
        return NULL;
    }

    if (componentType == JPy_JVoid) {
        PyErr_SetString(PyExc_ValueError, "array: argument 1 (type) must not be 'void'");
        return NULL;
    }

    if (JPy_IS_CLONG(objInit)) {
        jint length = JPy_AS_CLONG(objInit);
        if (length < 0) {
            PyErr_SetString(PyExc_ValueError, "array: argument 2 (init) must be either an integer array length or any sequence");
            return NULL;
        }
        if (componentType == JPy_JBoolean) {
            arrayRef = (*jenv)->NewBooleanArray(jenv, length);
        } else if (componentType == JPy_JChar) {
            arrayRef = (*jenv)->NewCharArray(jenv, length);
        } else if (componentType == JPy_JByte) {
            arrayRef = (*jenv)->NewByteArray(jenv, length);
        } else if (componentType == JPy_JShort) {
            arrayRef = (*jenv)->NewShortArray(jenv, length);
        } else if (componentType == JPy_JInt) {
            arrayRef = (*jenv)->NewIntArray(jenv, length);
        } else if (componentType == JPy_JLong) {
            arrayRef = (*jenv)->NewLongArray(jenv, length);
        } else if (componentType == JPy_JFloat) {
            arrayRef = (*jenv)->NewFloatArray(jenv, length);
        } else if (componentType == JPy_JDouble) {
            arrayRef = (*jenv)->NewDoubleArray(jenv, length);
        } else {
            arrayRef = (*jenv)->NewObjectArray(jenv, length, componentType->classRef, NULL);
        }
        if (arrayRef == NULL) {
            return PyErr_NoMemory();
        }
        return (PyObject*) JObj_New(jenv, arrayRef);
    } else if (PySequence_Check(objInit)) {
        if (JType_CreateJavaArray(jenv, componentType, objInit, &arrayRef) < 0) {
            return NULL;
        }
        return (PyObject*) JObj_New(jenv, arrayRef);
    } else {
        PyErr_SetString(PyExc_ValueError, "array: argument 2 (init) must be either an integer array length or any sequence");
        return NULL;
    }
}
开发者ID:francbartoli,项目名称:jpy,代码行数:72,代码来源:jpy_module.c

示例6: PyDict_New

// Parse a Python object as a sequence of either QVector[234]D instances or a
// sequence of sequence of floats and return an array that can be passed to
// QGLShaderProgram::setAttributeArray().  The array is destroyed only when the
// shader is garbage collected or when replaced by another array.
const GLfloat *qpyopengl_attribute_array(PyObject *values, PyObject *shader,
        PyObject *key, int *tsize, sipErrorState *estate)
{
    // Check the key was created correctly.
    if (!key)
    {
        *estate = sipErrorFail;
        return 0;
    }

    // Get the dict that holds the converted arrays.
    PyObject *dict = ((sipSimpleWrapper *)shader)->user;

    if (!dict)
    {
        dict = PyDict_New();

        if (!dict)
        {
            Py_DECREF(key);

            *estate = sipErrorFail;
            return 0;
        }

        ((sipSimpleWrapper *)shader)->user = dict;
    }

    // Check that values is a non-empty sequence.
    values = PySequence_Fast(values, "an attribute array must be a sequence");

    if (!values)
    {
        Py_DECREF(key);

        *estate = sipErrorContinue;
        return 0;
    }

    SIP_SSIZE_T nr_items = PySequence_Fast_GET_SIZE(values);

    if (nr_items < 1)
    {
        PyErr_SetString(PyExc_TypeError,
                "an attribute array must have at least one element");

        Py_DECREF(key);
        Py_DECREF(values);

        *estate = sipErrorFail;
        return 0;
    }

    // The first element determines the type expected.
    PyObject *itm = PySequence_Fast_GET_ITEM(values, 0);

    const sipTypeDef *td;
    SIP_SSIZE_T nr_dim;

    if (sipCanConvertToType(itm, sipType_QVector2D, SIP_NOT_NONE))
    {
        td = sipType_QVector2D;
        nr_dim = 2;
    }
    else if (sipCanConvertToType(itm, sipType_QVector3D, SIP_NOT_NONE))
    {
        td = sipType_QVector3D;
        nr_dim = 3;
    }
    else if (sipCanConvertToType(itm, sipType_QVector4D, SIP_NOT_NONE))
    {
        td = sipType_QVector4D;
        nr_dim = 4;
    }
    else if (PySequence_Check(itm) && (nr_dim = PySequence_Size(itm)) >= 1)
    {
        td = 0;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError,
                "an attribute array must be a sequence of QVector2D, "
                "QVector3D, QVector4D, or a sequence of sequences of floats");

        Py_DECREF(key);
        Py_DECREF(values);

        *estate = sipErrorFail;
        return 0;
    }

    // Create the array that will be returned.
    GLfloat *array = new GLfloat[nr_items * nr_dim];

    // Convert the values.
    GLfloat *ap = array;
//.........这里部分代码省略.........
开发者ID:thaisdb,项目名称:TCC,代码行数:101,代码来源:qpyopengl_attribute_array.cpp

示例7: parse_params

static s_param *
parse_params(PyObject *pyarray, int *plen)
{
    struct s_param *params;

    // check and parse fractal params
    if(!PySequence_Check(pyarray))
    {
	PyErr_SetString(PyExc_TypeError,
			"parameters argument should be an array");
	return NULL;
    }


    int len = PySequence_Size(pyarray);
    if(len == 0)
    {
	params = (struct s_param *)malloc(sizeof(struct s_param));
	params[0].t = FLOAT;
	params[0].doubleval = 0.0;
    }
    else if(len > PF_MAXPARAMS)
    {
	PyErr_SetString(PyExc_ValueError,"Too many parameters");
	return NULL;
    }
    else
    {
	int i = 0;
	params = (struct s_param *)malloc(len * sizeof(struct s_param));
	if(!params) return NULL;
	for(i = 0; i < len; ++i)
	{
	    PyObject *pyitem = PySequence_GetItem(pyarray,i);
	    if(NULL == pyitem)
	    {
		return NULL;
	    }
	    if(PyFloat_Check(pyitem))
	    {
		params[i].t = FLOAT;
		params[i].doubleval = PyFloat_AsDouble(pyitem);
		//printf("%d = float(%g)\n",i,params[i].doubleval);
	    }
	    else if(PyInt_Check(pyitem))
	    {
		params[i].t = INT;
		params[i].intval = PyInt_AS_LONG(pyitem);
		//printf("%d = int(%d)\n",i,params[i].intval);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"cobject") &&
		PyObject_HasAttrString(pyitem,"segments"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"cobject");
		if(pycob == Py_None)
		{
		    Py_DECREF(pycob);
		    PyObject *pysegs = PyObject_GetAttrString(
			pyitem,"segments");

		    ColorMap *cmap = cmap_from_pyobject(pysegs);
		    Py_DECREF(pysegs);

		    if(NULL == cmap)
		    {
			return NULL;
		    }

		    pycob = PyCObject_FromVoidPtr(
			cmap, (void (*)(void *))cmap_delete);

		    if(NULL != pycob)
		    {
			PyObject_SetAttrString(pyitem,"cobject",pycob);
			// not quite correct, we are leaking some
			// cmap objects 
			Py_XINCREF(pycob);
		    }
		}
		params[i].t = GRADIENT;
		params[i].gradient = PyCObject_AsVoidPtr(pycob);
		//printf("%d = gradient(%p)\n",i,params[i].gradient);
		Py_DECREF(pycob);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"_img"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"_img");
		params[i].t = PARAM_IMAGE;
		params[i].image = PyCObject_AsVoidPtr(pycob);
		Py_DECREF(pycob);
	    }
	    else
	    {
		Py_XDECREF(pyitem);
		PyErr_SetString(
		    PyExc_ValueError,
		    "All params must be floats, ints, or gradients");
		free(params);
//.........这里部分代码省略.........
开发者ID:Bookaa,项目名称:gnofract4d.simplify,代码行数:101,代码来源:fract4dmodule_gmp.cpp

示例8: PyErr_Format

/* Open EWF file(s)
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_handle_open(
           pyewf_handle_t *pyewf_handle,
           PyObject *arguments,
           PyObject *keywords )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	liberror_error_t *error     = NULL;
	char **filenames            = NULL;
	static char *keyword_list[] = { "filenames", "access_flags", NULL };
	PyObject *sequence_object   = NULL;
	PyObject *string_object     = NULL;
	static char *function       = "pyewf_handle_open";
	size_t filename_length      = 0;
	int access_flags            = 0;
	int filename_index          = 0;
	int number_of_filenames     = 0;

	if( pyewf_handle == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf handle.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	      keywords,
	      "O|i",
	      keyword_list,
	      &sequence_object,
	      &access_flags ) == 0 )
	{
		return( NULL );
	}
	if( PySequence_Check(
	     sequence_object ) == 0 )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: argument: files must be a list or tuple.",
		 function );

		return( NULL );
	}
	number_of_filenames = PySequence_Size(
	                       sequence_object );

	if( ( number_of_filenames <= 0 )
	 || ( number_of_filenames > (int) UINT16_MAX ) )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid number of files.",
		 function );

		return( NULL );
	}
	filenames = (char **) memory_allocate(
	                       sizeof( char * ) * number_of_filenames );

	if( filenames == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to create filenames.",
		 function );

		return( NULL );
	}
	if( memory_set(
	     filenames,
	     0,
	     sizeof( char * ) * number_of_filenames ) == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to clear filenames.",
		 function );

		memory_free(
		 filenames );

		return( NULL );
	}
	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		string_object = PySequence_GetItem(
		                 sequence_object,
		                 filename_index );

		filename_length = PyString_Size(
		                   string_object );
//.........这里部分代码省略.........
开发者ID:eaas-framework,项目名称:xmount,代码行数:101,代码来源:pyewf_handle.c

示例9: AUTO_SCOPED_PROFILE

//-------------------------------------------------------------------------------------
bool Loginapp::_createAccount(Network::Channel* pChannel, std::string& accountName, 
								 std::string& password, std::string& datas, ACCOUNT_TYPE type)
{
	AUTO_SCOPED_PROFILE("createAccount");

	ACCOUNT_TYPE oldType = type;

	if(!g_kbeSrvConfig.getDBMgr().account_registration_enable)
	{
		WARNING_MSG(fmt::format("Loginapp::_createAccount({}): not available!\n", accountName));

		std::string retdatas = "";
		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_ACCOUNT_REGISTER_NOT_AVAILABLE;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}

	accountName = KBEngine::strutil::kbe_trim(accountName);
	password = KBEngine::strutil::kbe_trim(password);

	if(accountName.size() > ACCOUNT_NAME_MAX_LENGTH)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName too big, size={}, limit={}.\n",
			accountName.size(), ACCOUNT_NAME_MAX_LENGTH));

		return false;
	}

	if(password.size() > ACCOUNT_PASSWD_MAX_LENGTH)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: password too big, size={}, limit={}.\n",
			password.size(), ACCOUNT_PASSWD_MAX_LENGTH));

		return false;
	}

	if(datas.size() > ACCOUNT_DATA_MAX_LENGTH)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: bindatas too big, size={}, limit={}.\n",
			datas.size(), ACCOUNT_DATA_MAX_LENGTH));

		return false;
	}
	
	std::string retdatas = "";
	if(shuttingdown_ != SHUTDOWN_STATE_STOP)
	{
		WARNING_MSG(fmt::format("Loginapp::_createAccount: shutting down, create {} failed!\n", accountName));

		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_IN_SHUTTINGDOWN;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}

	PendingLoginMgr::PLInfos* ptinfos = pendingCreateMgr_.find(const_cast<std::string&>(accountName));
	if(ptinfos != NULL)
	{
		WARNING_MSG(fmt::format("Loginapp::_createAccount: pendingCreateMgr has {}, request create failed!\n", 
			accountName));

		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_BUSY;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}
	
	{
		// 把请求交由脚本处理
		SERVER_ERROR_CODE retcode = SERVER_SUCCESS;
		SCOPED_PROFILE(SCRIPTCALL_PROFILE);

		PyObject* pyResult = PyObject_CallMethod(getEntryScript().get(), 
											const_cast<char*>("onRequestCreateAccount"), 
											const_cast<char*>("ssy#"), 
											accountName.c_str(),
											password.c_str(),
											datas.c_str(), datas.length());

		if(pyResult != NULL)
		{
			if(PySequence_Check(pyResult) && PySequence_Size(pyResult) == 4)
			{
				char* sname;
				char* spassword;
			    char *extraDatas;
			    Py_ssize_t extraDatas_size = 0;
				
				if(PyArg_ParseTuple(pyResult, "H|s|s|y#",  &retcode, &sname, &spassword, &extraDatas, &extraDatas_size) == -1)
//.........这里部分代码省略.........
开发者ID:1564143452,项目名称:kbengine,代码行数:101,代码来源:loginapp.cpp

示例10: wsql_server_init

static PyObject* wsql_server_init(PyObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"args", "groups", NULL};
    char **cmd_args_c=NULL, **groups_c=NULL, *s;
    Py_ssize_t cmd_argc=0, i, groupc;
    PyObject *cmd_args=NULL, *groups=NULL, *item;

    if (wsql_server_init_done)
    {
        PyErr_SetString(wsql_programming_error, "already initialized");
        return NULL;
    }

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OO", kwlist, &cmd_args, &groups))
        return NULL;

#if MYSQL_VERSION_ID >= 40000
    if (cmd_args)
    {
        if (!PySequence_Check(cmd_args))
        {
            PyErr_SetString(PyExc_TypeError, "args must be a sequence");
            goto finish;
        }
        cmd_argc = PySequence_Size(cmd_args);
        if (cmd_argc == -1)
        {
            PyErr_SetString(PyExc_TypeError, "args could not be sized");
            goto finish;
        }
        cmd_args_c = (char **) PyMem_Malloc(cmd_argc * sizeof(char *));
        for (i=0; i< cmd_argc; ++i)
        {
            item = PySequence_GetItem(cmd_args, i);
            s = PyString_AsString(item);
            Py_DECREF(item);
            if (!s)
            {
                PyErr_SetString(PyExc_TypeError, "args must contain strings");
                goto finish;
            }
            cmd_args_c[i] = s;
        }
    }
    if (groups)
    {
        if (!PySequence_Check(groups))
        {
            PyErr_SetString(PyExc_TypeError, "groups must be a sequence");
            goto finish;
        }
        groupc = PySequence_Size(groups);
        if (groupc == -1)
        {
            PyErr_SetString(PyExc_TypeError, "groups could not be sized");
            goto finish;
        }
        groups_c = (char **) PyMem_Malloc((1+groupc)*sizeof(char *));
        for (i = 0; i < groupc; ++i)
        {
            item = PySequence_GetItem(groups, i);
            s = PyString_AsString(item);
            Py_DECREF(item);
            if (!s)
            {
                PyErr_SetString(PyExc_TypeError, "groups must contain strings");
                goto finish;
            }
            groups_c[i] = s;
        }
        groups_c[groupc] = (char *)NULL;
    }
    /* even though this may block, don't give up the interpreter lock
       so that the server can't be initialized multiple times. */
    if (mysql_server_init(cmd_argc, cmd_args_c, groups_c))
    {
        wsql_raise_error(NULL);
        goto finish;
    }
#endif
    wsql_server_init_done = 1;
    Py_RETURN_NONE;
  finish:
    PyMem_Free(groups_c);
    PyMem_Free(cmd_args_c);
    return NULL;
}
开发者ID:WebSQL,项目名称:wsql,代码行数:87,代码来源:module.c

示例11: do_set_servers

//----------------------------------------------------------------------------------------
//
static int
do_set_servers(CmemcacheObject* self, PyObject* servers)
{
    debug(("do_set_servers\n"));
    
    if (!PySequence_Check(servers))
    {
        PyErr_BadArgument();
        return -1;
    }

    int error = 0;
    
    /* there seems to be no way to remove servers, so get rid of memcache all together */
    if (self->mc)
    {
        mcm_free(self->mc_ctxt, self->mc);
        self->mc = NULL;
    }
    assert(self->mc == NULL);

    /* create new instance */
    self->mc = mcm_new(self->mc_ctxt);
    debug(("new mc %p\n", self->mc));
    if (self->mc == NULL)
    {
        PyErr_NoMemory();
        return -1;
    }

    /* add servers, allow any sequence of strings */
    const int size = PySequence_Size(servers);
    int i;
    for (i = 0; i < size && error == 0; ++i)
    {
        PyObject* item = PySequence_GetItem(servers, i);
        if (item)
        {
            PyObject* name = NULL;
            int weight = 1;
            
            if (PyString_Check(item))
            {
                name = item;
            }
            else if (PyTuple_Check(item))
            {
                error = ! PyArg_ParseTuple(item, "Oi", &name, &weight);
            }
            if (name)    
            {
                const char* cserver = PyString_AsString(name);
                assert(cserver);
                debug(("cserver %s weight %d\n", cserver, weight));
            
                /* mc_server_add4 is not happy without ':' (it segfaults!) so check */
                if (strstr(cserver, ":") == NULL)
                {
                    PyErr_Format(PyExc_TypeError,
                                 "expected \"server:port\" but \"%s\" found", cserver);
                    error = 1;
                }
                else
                {
                    int i;
                    if (weight>15)
                    {
                        weight = 15;
                    }
                    Py_BEGIN_ALLOW_THREADS;
                    for (i = 0; i < weight; ++i)
                    {
                        debug_def(int retval =)
                            mcm_server_add4(self->mc_ctxt, self->mc, cserver);
                        debug(("retval %d\n", retval));
                    }
                    Py_END_ALLOW_THREADS;
                }
            }
            else
            {
                PyErr_BadArgument();
                error = 1;
            }
            Py_DECREF(item);
        }
    }
开发者ID:Jai-Prakash-Singh,项目名称:like_v9,代码行数:89,代码来源:_cmemcache.c

示例12: MediaControl_new

/* The MediaControl constructor takes either an existing vlc.Instance or a
   list of strings */
static PyObject *
MediaControl_new( PyTypeObject *type, PyObject *args, PyObject *kwds )
{
    MediaControl *self;
    mediacontrol_Exception *exception = NULL;
    PyObject* py_param = NULL;
    char** ppsz_args = NULL;
    libvlc_instance_t* p_instance = NULL;
    Py_ssize_t i_size = 0;

    self = PyObject_New( MediaControl, &MediaControl_Type );

    fprintf (stderr, "Instantiating mediacontrol\n");
    if( PyArg_ParseTuple( args, "O", &py_param ) )
    {
        if( PyObject_TypeCheck( py_param, &vlcInstance_Type ) == 1 )
        {
            p_instance = ((vlcInstance*)py_param)->p_instance;
        }
        else
        {
            Py_ssize_t i_index;

            Py_INCREF( py_param );
            if( ! PySequence_Check( py_param ) )
            {
                PyErr_SetString( PyExc_TypeError, "Parameter must be a vlc.Instance or a sequence of strings." );
                Py_DECREF( py_param );
                return NULL;
            }
            i_size = PySequence_Size( py_param );
            ppsz_args = malloc( ( i_size + 1 ) * sizeof( char * ) );
            if( ! ppsz_args )
            {
                PyErr_SetString( PyExc_MemoryError, "Out of memory" );
                Py_DECREF( py_param );
                return NULL;
            }

            for ( i_index = 0; i_index < i_size; i_index++ )
            {
                ppsz_args[i_index] =
                    strdup( PyString_AsString( PyObject_Str(
                                                   PySequence_GetItem( py_param,
                                                                       i_index ) ) ) );
            }
            ppsz_args[i_size] = NULL;
            Py_DECREF( py_param );
        }
    }
    else
    {
        /* No arguments were given. Clear the exception raised
           by PyArg_ParseTuple. */
        PyErr_Clear( );
    }

    Py_BEGIN_ALLOW_THREADS
    MC_TRY;
    if( p_instance )
    {
        self->mc = mediacontrol_new_from_instance( p_instance, exception );
        Py_INCREF( py_param );
        self->vlc_instance = ( vlcInstance* ) py_param;
    }
    else
    {
        self->mc = mediacontrol_new( i_size, ppsz_args, exception );
        self->vlc_instance = PyObject_New( vlcInstance, &vlcInstance_Type );
        self->vlc_instance->p_instance = mediacontrol_get_libvlc_instance( LIBVLC_MC(self) );
    }
    MC_EXCEPT;
    Py_END_ALLOW_THREADS

    Py_INCREF( self );
    return ( PyObject * )self;
}
开发者ID:KaMaDrEl,项目名称:vlc,代码行数:79,代码来源:vlc_mediacontrol.c

示例13: test_neighborhood_iterator_oob

static PyObject*
test_neighborhood_iterator_oob(PyObject* NPY_UNUSED(self), PyObject* args)
{
    PyObject *x, *out, *b1, *b2;
    PyArrayObject *ax;
    PyArrayIterObject *itx;
    int i, typenum, mode1, mode2, st;
    npy_intp bounds[NPY_MAXDIMS*2];
    PyArrayNeighborhoodIterObject *niterx1, *niterx2;

    if (!PyArg_ParseTuple(args, "OOiOi", &x, &b1, &mode1, &b2, &mode2)) {
        return NULL;
    }

    if (!PySequence_Check(b1) || !PySequence_Check(b2)) {
        return NULL;
    }

    typenum = PyArray_ObjectType(x, 0);

    ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10);
    if (ax == NULL) {
        return NULL;
    }
    if (PySequence_Size(b1) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence 1 size not compatible with x input");
        goto clean_ax;
    }
    if (PySequence_Size(b2) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence 2 size not compatible with x input");
        goto clean_ax;
    }

    out = PyList_New(0);
    if (out == NULL) {
        goto clean_ax;
    }

    itx = (PyArrayIterObject*)PyArray_IterNew(x);
    if (itx == NULL) {
        goto clean_out;
    }

    /* Compute boundaries for the neighborhood iterator */
    for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) {
        PyObject* bound;
        bound = PySequence_GetItem(b1, i);
        if (bounds == NULL) {
            goto clean_itx;
        }
        if (!PyInt_Check(bound)) {
            PyErr_SetString(PyExc_ValueError,
                    "bound not long");
            Py_DECREF(bound);
            goto clean_itx;
        }
        bounds[i] = PyInt_AsLong(bound);
        Py_DECREF(bound);
    }

    /* Create the neighborhood iterator */
    niterx1 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)itx, bounds,
                    mode1, NULL);
    if (niterx1 == NULL) {
        goto clean_out;
    }

    for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) {
        PyObject* bound;
        bound = PySequence_GetItem(b2, i);
        if (bounds == NULL) {
            goto clean_itx;
        }
        if (!PyInt_Check(bound)) {
            PyErr_SetString(PyExc_ValueError,
                    "bound not long");
            Py_DECREF(bound);
            goto clean_itx;
        }
        bounds[i] = PyInt_AsLong(bound);
        Py_DECREF(bound);
    }

    niterx2 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)niterx1, bounds,
                    mode2, NULL);
    if (niterx1 == NULL) {
        goto clean_niterx1;
    }

    switch (typenum) {
        case NPY_DOUBLE:
            st = copy_double_double(niterx1, niterx2, bounds, &out);
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                    "Type not supported");
//.........这里部分代码省略.........
开发者ID:adevabhaktuni,项目名称:LADS,代码行数:101,代码来源:multiarray_tests.c

示例14: PythonSequenceIterator

 PythonSequenceIterator(PyObject* sequence, Py_ssize_t position):
   m_sequence(sequence), m_position(position) {
   assert(PySequence_Check(m_sequence));
   assert(m_position >= 0);
   assert(m_position <= PySequence_Size(m_sequence));
 }
开发者ID:zvyn,项目名称:CModuleForPython,代码行数:6,代码来源:PythonSequenceIterator.cpp

示例15: JPy_create_jvm

PyObject* JPy_create_jvm(PyObject* self, PyObject* args, PyObject* kwds)
{
    static char* keywords[] = {"options", NULL};
    PyObject*   options;
    Py_ssize_t  optionCount;
    PyObject*   option;
    JavaVMOption* jvmOptions;
    JavaVMInitArgs jvmInitArgs;
    jint        jvmErrorCode;
    JNIEnv*     jenv;
    Py_ssize_t  i;

    //printf("JPy_create_jvm: JPy_JVM=%p\n", JPy_JVM);

    options = NULL;
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:create_jvm", keywords, &options)) {
        return NULL;
    }

    if (JPy_JVM != NULL) {
        JPy_DIAG_PRINT(JPy_DIAG_F_JVM + JPy_DIAG_F_ERR, "JPy_create_jvm: WARNING: Java VM is already running.\n");
        Py_DECREF(options);
        return Py_BuildValue("");
    }

    if (!PySequence_Check(options)) {
        PyErr_SetString(PyExc_ValueError, "create_jvm: argument 1 (options) must be a sequence of Java VM option strings");
        return NULL;
    }

    optionCount = PySequence_Length(options);
    if (optionCount == -1) {
        PyErr_SetString(PyExc_ValueError, "create_jvm: failed to determine sequence length of argument 1 (options)");
        return NULL;
    }

    jvmOptions = PyMem_New(JavaVMOption, optionCount);
    if (jvmOptions == NULL) {
        return PyErr_NoMemory();
    }

    for (i = 0; i < optionCount; i++) {
        option = PySequence_GetItem(options, i);
        if (option == NULL) {
            PyMem_Del(jvmOptions);
            return NULL;
        }
        jvmOptions[i].optionString = (char*) JPy_AS_UTF8(option);
        jvmOptions[i].extraInfo = NULL;
        JPy_DIAG_PRINT(JPy_DIAG_F_JVM, "JPy_create_jvm: jvmOptions[%d].optionString = '%s'\n", i, jvmOptions[i].optionString);
        if (jvmOptions[i].optionString == NULL) {
            PyMem_Del(jvmOptions);
            return NULL;
        }
        Py_DECREF(option);
    }

    jvmInitArgs.version = JPY_JNI_VERSION;
    jvmInitArgs.options = jvmOptions;
    jvmInitArgs.nOptions = (size_t) optionCount;
    jvmInitArgs.ignoreUnrecognized = 0;
    jvmErrorCode = JNI_CreateJavaVM(&JPy_JVM, (void**) &jenv, &jvmInitArgs);
    JPy_MustDestroyJVM = JNI_TRUE;

    JPy_DIAG_PRINT(JPy_DIAG_F_JVM, "JPy_create_jvm: res=%d, JPy_JVM=%p, jenv=%p, JPy_MustDestroyJVM=%d\n", jvmErrorCode, JPy_JVM, jenv, JPy_MustDestroyJVM);

    PyMem_Del(jvmOptions);

    if (jvmErrorCode != JNI_OK) {
        JPy_DIAG_PRINT(JPy_DIAG_F_JVM + JPy_DIAG_F_ERR,
                       "JPy_create_jvm: INTERNAL ERROR: Failed to create Java VM (JNI error code %d). Possible reasons are:\n"
                       "* The Java heap space setting is too high (option -Xmx). Try '256M' first, then increment.\n"
                       "* The JVM shared library (Unix: libjvm.so, Windows: jvm.dll) cannot be found or cannot be loaded.\n"
                       "  Make sure the shared library can be found via the 'PATH' environment variable.\n"
                       "  Also make sure that the JVM is compiled for the same architecture as Python.\n",
                       jvmErrorCode);
        PyErr_SetString(PyExc_RuntimeError, "jpy: failed to create Java VM");
        return NULL;
    }

    if (JPy_InitGlobalVars(jenv) < 0) {
        return NULL;
    }

    return Py_BuildValue("");
}
开发者ID:francbartoli,项目名称:jpy,代码行数:86,代码来源:jpy_module.c


注:本文中的PySequence_Check函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。