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

C++ PyArg_ParseTuple函数代码示例

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

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



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

示例1: _psyco_conn_tpc_finish

/* Implement tpc_commit/tpc_rollback.
 *
 * This is a common framework performing the chechs and state manipulation
 * common to the two functions.
 *
 * Parameters are:
 * - self, args: passed by Python
 * - opc_f: the function to call in case of one-phase commit/rollback
 *          one of conn_commit/conn_rollback
 * - tpc_cmd: the command to execute for a two-phase commit/rollback
 *
 * The function can be called in three cases:
 * - If xid is specified, the status must be "ready";
 *   issue the commit/rollback prepared.
 * - if xid is not specified and status is "begin" with a xid,
 *   issue a normal commit/rollback.
 * - if xid is not specified and status is "prepared",
 *   issue the commit/rollback prepared.
 */
static PyObject *
_psyco_conn_tpc_finish(connectionObject *self, PyObject *args,
    _finish_f opc_f, char *tpc_cmd)
{
    PyObject *oxid = NULL;
    xidObject *xid = NULL;
    PyObject *rv = NULL;

    if (!PyArg_ParseTuple(args, "|O", &oxid)) { goto exit; }

    if (oxid) {
        if (!(xid = xid_ensure(oxid))) { goto exit; }
    }

    if (xid) {
        /* committing/aborting a recovered transaction. */
        if (self->status != CONN_STATUS_READY) {
            PyErr_SetString(ProgrammingError,
                "tpc_commit/tpc_rollback with a xid "
                "must be called outside a transaction");
            goto exit;
        }
        if (0 > conn_tpc_command(self, tpc_cmd, xid)) {
            goto exit;
        }
    } else {
        /* committing/aborting our own transaction. */
        if (!self->tpc_xid) {
            PyErr_SetString(ProgrammingError,
                "tpc_commit/tpc_rollback with no parameter "
                "must be called in a two-phase transaction");
            goto exit;
        }

        switch (self->status) {
          case CONN_STATUS_BEGIN:
            if (0 > opc_f(self)) { goto exit; }
            break;

          case CONN_STATUS_PREPARED:
            if (0 > conn_tpc_command(self, tpc_cmd, self->tpc_xid)) {
                goto exit;
            }
            break;

          default:
            PyErr_SetString(InterfaceError,
                "unexpected state in tpc_commit/tpc_rollback");
            goto exit;
        }

        Py_CLEAR(self->tpc_xid);

        /* connection goes ready */
        self->status = CONN_STATUS_READY;
    }

    Py_INCREF(Py_None);
    rv = Py_None;

exit:
    Py_XDECREF(xid);
    return rv;
}
开发者ID:psycopg,项目名称:psycopg2,代码行数:83,代码来源:connection_type.c


示例2: evalDistribution

/**
 *  evalDistribution function evaluate a model function with input vector
 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
 *
 */ 
static PyObject * evalDistribution(CPoly_GaussCoil *self, PyObject *args){
	PyObject *qx, *qy;
	PyArrayObject * pars;
	int npars ,mpars;
	
	// Get parameters
	
	    // Reader parameter dictionary
    self->model->poly_m = PyFloat_AsDouble( PyDict_GetItemString(self->params, "poly_m") );
    self->model->rg = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rg") );
    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
    // Read in dispersion parameters
    PyObject* disp_dict;
    DispersionVisitor* visitor = new DispersionVisitor();
    disp_dict = PyDict_GetItemString(self->dispersion, "rg");
    self->model->rg.dispersion->accept_as_destination(visitor, self->model->rg.dispersion, disp_dict);

	
	// Get input and determine whether we have to supply a 1D or 2D return value.
	if ( !PyArg_ParseTuple(args,"O",&pars) ) {
	    PyErr_SetString(CPoly_GaussCoilError, 
	    	"CPoly_GaussCoil.evalDistribution expects a q value.");
		return NULL;
	}
    // Check params
	
    if(PyArray_Check(pars)==1) {
		
	    // Length of list should 1 or 2
	    npars = pars->nd; 
	    if(npars==1) {
	        // input is a numpy array
	        if (PyArray_Check(pars)) {
		        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
		    }
		}else{
		    PyErr_SetString(CPoly_GaussCoilError, 
                   "CPoly_GaussCoil.evalDistribution expect numpy array of one dimension.");
	        return NULL;
		}
    }else if( PyList_Check(pars)==1) {
    	// Length of list should be 2 for I(qx,qy)
	    mpars = PyList_GET_SIZE(pars); 
	    if(mpars!=2) {
	    	PyErr_SetString(CPoly_GaussCoilError, 
	    		"CPoly_GaussCoil.evalDistribution expects a list of dimension 2.");
	    	return NULL;
	    }
	     qx = PyList_GET_ITEM(pars,0);
	     qy = PyList_GET_ITEM(pars,1);
	     if (PyArray_Check(qx) && PyArray_Check(qy)) {
	         return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
		           (PyArrayObject*)qy);
		 }else{
		    PyErr_SetString(CPoly_GaussCoilError, 
                   "CPoly_GaussCoil.evalDistribution expect 2 numpy arrays in list.");
	        return NULL;
	     }
	}
	PyErr_SetString(CPoly_GaussCoilError, 
                   "CPoly_GaussCoil.evalDistribution couln't be run.");
	return NULL;
	
}
开发者ID:ricleal,项目名称:SasModeling,代码行数:70,代码来源:CPoly_GaussCoil.cpp


示例3: PositionWeightMatrix_nullScoreDistribution

static PyObject* PositionWeightMatrix_nullScoreDistribution( PositionWeightMatrix* self, PyObject* args )
{
	PyObject* seq;
	int reps;
		
	if( !PyArg_ParseTuple( args, "Oi", &seq, &reps ) )
		return NULL;
	
	seq = PySequence_Fast( seq, "argument must be iterable" );
	if( !seq ) return NULL;
	
	PyObject** elems = PySequence_Fast_ITEMS( seq );
	size_t len = PySequence_Fast_GET_SIZE( seq );
	
	//allocate array to put elems in
	long* array = malloc( len * sizeof(long) );
	size_t i;
	for( i = 0 ; i < len ; ++i )
	{
		array[i] = PyInt_AsLong( elems[i] );
	}
	//check for error
	if( PyErr_Occurred() )
	{
		free( array );
		return NULL;
	}

	double** matrix = self->matrix;
	int n = self->n;
	int m = self->m;
	
	//allocate scores array
	size_t nmers = ( len - n + 1 );
	size_t lenScores = nmers*reps;
	double* scores = malloc( lenScores * sizeof( double ) ); 
	
	//for each replicate, shuffle and score the sequence
	int rep = 0;
	while( rep < reps )
	{
		shuffle( array, len, sizeof( long ) );
		scoreAllLong( matrix, n, m, array, len, scores, nmers * rep );
		++rep;
	}

	//sort the scores
	quicksort( scores, lenScores, sizeof( double ), &compareDoubleDescending );
	
	//free the long array
	free( array );
	
	//build a python list to return
	PyObject* list = PyList_New( lenScores );
	for( i = 0 ; i < lenScores ; ++i )
	{
		PyList_SetItem( list, i, PyFloat_FromDouble( scores[i] ) );
	}
	
	//free the scores array
	free( scores );
	
	return list;

}
开发者ID:tbepler,项目名称:MESS,代码行数:65,代码来源:PositionWeightMatrix.c


示例4:

static PyObject *softmax_vec_(PyObject *self, PyObject *args)
{
  PyArrayObject *input, *output;
  int i;

  if (!PyArg_ParseTuple(args, "O!O!", 
                        &PyArray_Type, &input, 
                        &PyArray_Type, &output)) return NULL;

  if ( (NULL == input) || (NULL == output) ) return NULL;
  
  if ( (input->descr->type_num != NPY_DOUBLE) || 
       (output->descr->type_num != NPY_DOUBLE) ||
       !PyArray_CHKFLAGS(input,NPY_C_CONTIGUOUS|NPY_ALIGNED) ||
       !PyArray_CHKFLAGS(output,NPY_C_CONTIGUOUS|NPY_ALIGNED|NPY_WRITEABLE) ) {
    PyErr_SetString(PyExc_ValueError,
                    "In softmax_vec_: all arguments must be of type double, C contiguous and aligned, and output should be writeable");
    return NULL;
  }
      
  if ( (input->nd != output->nd) )
  {
    PyErr_SetString(PyExc_ValueError,
                    "In softmax_vec_: both arguments should have the same dimensionality");
    return NULL;
  }

  int tot_dim = 1;
  for (i=0; i<input->nd; i++)
  {
    if ( (input->dimensions[i] != output->dimensions[i]) )
    {
      PyErr_SetString(PyExc_ValueError,
		      "In softmax_vec_: all dimensions of both arguments should be equal");
      return NULL;
    }
    tot_dim *= input->dimensions[i];
  }
  
  double * input_data_iter = (double *) input->data;
  double * output_data_iter = (double *) output->data;
  double max = *input_data_iter;
  for (i=0; i<tot_dim; i++)
  {
    if (max < *input_data_iter){ max = *input_data_iter; }
    input_data_iter++;
  }

  input_data_iter = (double *) input->data;
  output_data_iter = (double *) output->data;
  double sum = 0;
  for (i=0; i<tot_dim; i++)
  {
    *output_data_iter = exp(*input_data_iter++ - max);
    sum += *output_data_iter++;
  }

  output_data_iter = (double *) output->data;
  for (i=0; i<tot_dim; i++)
  {
    *output_data_iter++ /= sum;
  }


  Py_RETURN_NONE;
}
开发者ID:goelhardik,项目名称:projects,代码行数:66,代码来源:nonlinear_.c


示例5: getEffect

PyObject* Effect::wrapSetImage(PyObject *self, PyObject *args)
{
	// get the effect
	Effect * effect = getEffect();

	// check if we have aborted already
	if (effect->_abortRequested)
	{
		return Py_BuildValue("");
	}

	// determine the timeout
	int timeout = effect->_timeout;
	if (timeout > 0)
	{
		timeout = effect->_endTime - QDateTime::currentMSecsSinceEpoch();

		// we are done if the time has passed
		if (timeout <= 0)
		{
			return Py_BuildValue("");
		}
	}

	// bytearray of values
	int width, height;
	PyObject * bytearray = nullptr;
	if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray))
	{
		if (PyByteArray_Check(bytearray))
		{
			int length = PyByteArray_Size(bytearray);
			if (length == 3 * width * height)
			{
				Image<ColorRgb> image(width, height);
				char * data = PyByteArray_AS_STRING(bytearray);
				memcpy(image.memptr(), data, length);

				effect->_imageProcessor->process(image, effect->_colors);
				effect->setColors(effect->_priority, effect->_colors, timeout, false);
				return Py_BuildValue("");
			}
			else
			{
				PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should be 3*width*height");
				return nullptr;
			}
		}
		else
		{
			PyErr_SetString(PyExc_RuntimeError, "Argument 3 is not a bytearray");
			return nullptr;
		}
	}
	else
	{
		return nullptr;
	}

	// error
	PyErr_SetString(PyExc_RuntimeError, "Unknown error");
	return nullptr;
}
开发者ID:7h30n3,项目名称:hyperion,代码行数:63,代码来源:Effect.cpp


示例6: PyZlib_flush

static PyObject *
PyZlib_flush(compobject *self, PyObject *args)
{
    int err, length = DEFAULTALLOC;
    PyObject *RetVal;
    int flushmode = Z_FINISH;
    unsigned long start_total_out;

    if (!PyArg_ParseTuple(args, "|i:flush", &flushmode))
        return NULL;

    /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
       doing any work at all; just return an empty string. */
    if (flushmode == Z_NO_FLUSH) {
        return PyString_FromStringAndSize(NULL, 0);
    }

    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
        return NULL;

    ENTER_ZLIB

    start_total_out = self->zst.total_out;
    self->zst.avail_in = 0;
    self->zst.avail_out = length;
    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);

    Py_BEGIN_ALLOW_THREADS
    err = deflate(&(self->zst), flushmode);
    Py_END_ALLOW_THREADS

    /* while Z_OK and the output buffer is full, there might be more output,
       so extend the output buffer and try again */
    while (err == Z_OK && self->zst.avail_out == 0) {
        if (_PyString_Resize(&RetVal, length << 1) < 0)
            goto error;
        self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
            + length;
        self->zst.avail_out = length;
        length = length << 1;

        Py_BEGIN_ALLOW_THREADS
        err = deflate(&(self->zst), flushmode);
        Py_END_ALLOW_THREADS
    }

    /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
       various data structures. Note we should only get Z_STREAM_END when
       flushmode is Z_FINISH, but checking both for safety*/
    if (err == Z_STREAM_END && flushmode == Z_FINISH) {
        err = deflateEnd(&(self->zst));
        if (err != Z_OK) {
            zlib_error(self->zst, err, "from deflateEnd()");
            Py_DECREF(RetVal);
            RetVal = NULL;
            goto error;
        }
        else
            self->is_initialised = 0;

        /* We will only get Z_BUF_ERROR if the output buffer was full
           but there wasn't more output when we tried again, so it is
           not an error condition.
        */
    } else if (err!=Z_OK && err!=Z_BUF_ERROR) {
        zlib_error(self->zst, err, "while flushing");
        Py_DECREF(RetVal);
        RetVal = NULL;
        goto error;
    }

    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);

 error:
    LEAVE_ZLIB

    return RetVal;
}
开发者ID:CSC-IT-Center-for-Science,项目名称:scalable-python,代码行数:78,代码来源:zlibmodule.c


示例7: py_decodelzw

static PyObject *
py_decodelzw(PyObject *obj, PyObject *args)
{
    PyThreadState *_save = NULL;
    PyObject *byteobj = NULL;
    PyObject *result = NULL;
    int i, j;
    unsigned int encoded_len = 0;
    unsigned int decoded_len = 0;
    unsigned int result_len = 0;
    unsigned int table_len = 0;
    unsigned int len;
    unsigned int code, c, oldcode, mask, bitw, shr, bitcount;
    char *encoded = NULL;
    char *result_ptr = NULL;
    char *table2 = NULL;
    char *cptr;
    struct BYTE_STRING *decoded = NULL;
    struct BYTE_STRING *table[4096];
    struct BYTE_STRING *decoded_ptr, *newentry, *newresult, *t;
    int little_endian = 0;

    if (!PyArg_ParseTuple(args, "O", &byteobj))
        return NULL;

    if (!PyBytes_Check(byteobj)) {
        PyErr_Format(PyExc_TypeError, "expected byte string as input");
        goto _fail;
    }

    Py_INCREF(byteobj);
    encoded = PyBytes_AS_STRING(byteobj);
    encoded_len = (unsigned int)PyBytes_GET_SIZE(byteobj);

    /* release GIL: byte/string objects are immutable */
    _save = PyEval_SaveThread();

    if ((*encoded != -128) || ((*(encoded+1) & 128))) {
        PyEval_RestoreThread(_save);
        PyErr_Format(PyExc_ValueError,
            "strip must begin with CLEAR code");
        goto _fail;
    }
    little_endian = (*(unsigned short *)encoded) & 128;

    /* allocate buffer for codes and pointers */
    decoded_len = 0;
    len = (encoded_len + encoded_len/9) * sizeof(decoded);
    decoded = PyMem_Malloc(len * sizeof(void *));
    if (decoded == NULL) {
        PyEval_RestoreThread(_save);
        PyErr_Format(PyExc_MemoryError, "failed to allocate decoded");
        goto _fail;
    }
    memset((void *)decoded, 0, len * sizeof(void *));
    decoded_ptr = decoded;

    /* cache strings of length 2 */
    cptr = table2 = PyMem_Malloc(256*256*2 * sizeof(char));
    if (table2 == NULL) {
        PyEval_RestoreThread(_save);
        PyErr_Format(PyExc_MemoryError, "failed to allocate table2");
        goto _fail;
    }
    for (i = 0; i < 256; i++) {
        for (j = 0; j < 256; j++) {
            *cptr++ = (char)i;
            *cptr++ = (char)j;
        }
    }

    memset(table, 0, sizeof(table));
    table_len = 258;
    bitw = 9;
    shr = 23;
    mask = 4286578688;
    bitcount = 0;
    result_len = 0;
    code = 0;
    oldcode = 0;

    while ((unsigned int)((bitcount + bitw) >> 3) <= encoded_len) {
        /* read next code */
        code = *((unsigned int *)((void *)(encoded + (bitcount / 8))));
        if (little_endian)
            code = SWAP4BYTES(code);
        code <<= bitcount % 8;
        code &= mask;
        code >>= shr;
        bitcount += bitw;

        if (code == 257) /* end of information */
            break;

        if (code == 256) {  /* clearcode */
            /* initialize table and switch to 9 bit */
            while (table_len > 258) {
                t = table[--table_len];
                t->ref--;
                if (t->ref == 0) {
//.........这里部分代码省略.........
开发者ID:malaterre,项目名称:PublicRep,代码行数:101,代码来源:tifffile.c


示例8: pr_subscript

static PyObject *
pr_subscript(PyGimpPixelRgn *self, PyObject *key)
{
    GimpPixelRgn *pr = &(self->pr);
    PyObject *x, *y;
    Py_ssize_t x1, y1, x2, y2, xs, ys;
    PyObject *ret;

    if (!PyTuple_Check(key) || PyTuple_Size(key) != 2) {
        PyErr_SetString(PyExc_TypeError, "subscript must be a 2-tuple");
        return NULL;
    }

    if (!PyArg_ParseTuple(key, "OO", &x, &y))
        return NULL;

    if (PyInt_Check(x)) {
        x1 = PyInt_AsSsize_t(x);

        if (x1 < pr->x || x1 >= pr->x + pr->w) {
            PyErr_SetString(PyExc_IndexError, "x subscript out of range");
            return NULL;
        }

        if (PyInt_Check(y)) {
            y1 = PyInt_AsSsize_t(y);

            if (y1 < pr->y || y1 >= pr->y + pr->h) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return NULL;
            }

            ret = PyString_FromStringAndSize(NULL, pr->bpp);
            gimp_pixel_rgn_get_pixel(pr, (guchar*)PyString_AS_STRING(ret),
                                     x1, y1);

        } else if (PySlice_Check(y)) {
            if (PySlice_GetIndices((PySliceObject*)y, pr->y + pr->h,
                                   &y1, &y2, &ys) ||
                y1 >= y2 || ys != 1) {
                PyErr_SetString(PyExc_IndexError, "invalid y slice");
                return NULL;
            }

            if(y1 == 0)
                y1 = pr->y;

            if(y1 < pr->y || y2 < pr->y) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return NULL;
            }

            ret = PyString_FromStringAndSize(NULL, pr->bpp * (y2 - y1));
            gimp_pixel_rgn_get_col(pr, (guchar*)PyString_AS_STRING(ret),
                                   x1, y1, y2-y1);
	    }
        else {
            PyErr_SetString(PyExc_TypeError, "invalid y subscript");
            return NULL;
        }
    } else if (PySlice_Check(x)) {
        if (PySlice_GetIndices((PySliceObject *)x, pr->x + pr->w,
                               &x1, &x2, &xs) ||
            x1 >= x2 || xs != 1) {
            PyErr_SetString(PyExc_IndexError, "invalid x slice");
            return NULL;
        }
        if (x1 == 0)
            x1 = pr->x;
        if(x1 < pr->x || x2 < pr->x) {
            PyErr_SetString(PyExc_IndexError, "x subscript out of range");
            return NULL;
        }

        if (PyInt_Check(y)) {
            y1 = PyInt_AsSsize_t(y);
            if (y1 < pr->y || y1 >= pr->y + pr->h) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return NULL;
            }
            ret = PyString_FromStringAndSize(NULL, pr->bpp * (x2 - x1));
            gimp_pixel_rgn_get_row(pr, (guchar*)PyString_AS_STRING(ret),
                                   x1, y1, x2 - x1);

        } else if (PySlice_Check(y)) {
            if (PySlice_GetIndices((PySliceObject*)y, pr->y + pr->h,
                                   &y1, &y2, &ys) ||
                y1 >= y2 || ys != 1) {
                PyErr_SetString(PyExc_IndexError, "invalid y slice");
                return NULL;
            }

            if(y1 == 0)
                y1 = pr->y;
            if(y1 < pr->y || y2 < pr->y) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return NULL;
            }

            ret = PyString_FromStringAndSize(NULL,
//.........这里部分代码省略.........
开发者ID:AdamGrzonkowski,项目名称:gimp-1,代码行数:101,代码来源:pygimp-tile.c


示例9: pr_ass_sub

static int
pr_ass_sub(PyGimpPixelRgn *self, PyObject *v, PyObject *w)
{
    GimpPixelRgn *pr = &(self->pr);
    PyObject *x, *y;
    const guchar *buf;
    Py_ssize_t len, x1, x2, xs, y1, y2, ys;

    if (w == NULL) {
        PyErr_SetString(PyExc_TypeError, "can't delete subscripts");
        return -1;
    }

    if (!PyString_Check(w)) {
        PyErr_SetString(PyExc_TypeError, "must assign string to subscript");
        return -1;
    }

    if (!PyTuple_Check(v) || PyTuple_Size(v) != 2) {
        PyErr_SetString(PyExc_TypeError, "subscript must be a 2-tuple");
        return -1;
    }

    if (!PyArg_ParseTuple(v, "OO", &x, &y))
        return -1;

    buf = (const guchar *)PyString_AsString(w);
    len = PyString_Size(w);
    if (!buf || len > INT_MAX) {
        return -1;
    }

    if (PyInt_Check(x)) {
        x1 = PyInt_AsSsize_t(x);
        if (x1 < pr->x || x1 >= pr->x + pr->w) {
            PyErr_SetString(PyExc_IndexError, "x subscript out of range");
            return -1;
        }

        if (PyInt_Check(y)) {
            y1 = PyInt_AsSsize_t(y);

            if (y1 < pr->y || y1 >= pr->y + pr->h) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return -1;
            }

            if (len != pr->bpp) {
                PyErr_SetString(PyExc_TypeError, "string is wrong length");
                return -1;
            }
            gimp_pixel_rgn_set_pixel(pr, buf, x1, y1);

        } else if (PySlice_Check(y)) {
            if (PySlice_GetIndices((PySliceObject *)y, pr->y + pr->h,
                                   &y1, &y2, &ys) ||
                y1 >= y2 || ys != 1) {
                PyErr_SetString(PyExc_IndexError, "invalid y slice");
                return -1;
            }
            if (y1 == 0)
                y1 = pr->y;

            if(y1 < pr->y || y2 < pr->y) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return -1;
            }
            if (len != pr->bpp * (y2 - y1)) {
                PyErr_SetString(PyExc_TypeError, "string is wrong length");
                return -1;
            }
            gimp_pixel_rgn_set_col(pr, buf, x1, y1, y2 - y1);

        } else {
            PyErr_SetString(PyExc_IndexError,"invalid y subscript");
            return -1;
        }
    } else if (PySlice_Check(x)) {
        if (PySlice_GetIndices((PySliceObject *)x, pr->x + pr->w,
                               &x1, &x2, &xs) ||
	        x1 >= x2 || xs != 1) {
            PyErr_SetString(PyExc_IndexError, "invalid x slice");
	        return -1;
        }
        if(x1 == 0)
            x1 = pr->x;

        if(x1 < pr->x || x2 < pr->x) {
            PyErr_SetString(PyExc_IndexError, "x subscript out of range");
            return -1;
        }

        if (PyInt_Check(y)) {
            y1 = PyInt_AsSsize_t(y);

            if (y1 < pr->y || y1 >= pr->y + pr->h) {
                PyErr_SetString(PyExc_IndexError, "y subscript out of range");
                return -1;
            }

//.........这里部分代码省略.........
开发者ID:AdamGrzonkowski,项目名称:gimp-1,代码行数:101,代码来源:pygimp-tile.c


示例10: chunk_render

/* TODO triple check this to make sure reference counting is correct */
PyObject*
chunk_render(PyObject *self, PyObject *args) {
    RenderState state;

    int xoff, yoff;
    
    PyObject *imgsize, *imgsize0_py, *imgsize1_py;
    int imgsize0, imgsize1;
    
    PyObject *blocks_py;
    PyObject *left_blocks_py;
    PyObject *right_blocks_py;
    PyObject *up_left_blocks_py;
    PyObject *up_right_blocks_py;

    RenderModeInterface *rendermode;

    void *rm_data;
                
    PyObject *t = NULL;
    
    if (!PyArg_ParseTuple(args, "OOiiO",  &state.self, &state.img, &xoff, &yoff, &state.blockdata_expanded))
        return NULL;
    
    /* fill in important modules */
    state.textures = textures;
    state.chunk = chunk_mod;
    
    /* set up the render mode */
    rendermode = get_render_mode(&state);
    rm_data = calloc(1, rendermode->data_size);
    if (rendermode->start(rm_data, &state)) {
        free(rm_data);
        return Py_BuildValue("i", "-1");
    }

    /* get the image size */
    imgsize = PyObject_GetAttrString(state.img, "size");

    imgsize0_py = PySequence_GetItem(imgsize, 0);
    imgsize1_py = PySequence_GetItem(imgsize, 1);
    Py_DECREF(imgsize);

    imgsize0 = PyInt_AsLong(imgsize0_py);
    imgsize1 = PyInt_AsLong(imgsize1_py);
    Py_DECREF(imgsize0_py);
    Py_DECREF(imgsize1_py);


    /* get the block data directly from numpy: */
    blocks_py = PyObject_GetAttrString(state.self, "blocks");
    state.blocks = blocks_py;

    left_blocks_py = PyObject_GetAttrString(state.self, "left_blocks");
    state.left_blocks = left_blocks_py;

    right_blocks_py = PyObject_GetAttrString(state.self, "right_blocks");
    state.right_blocks = right_blocks_py;

    up_left_blocks_py = PyObject_GetAttrString(state.self, "up_left_blocks");
    state.up_left_blocks = up_left_blocks_py;

    up_right_blocks_py = PyObject_GetAttrString(state.self, "up_right_blocks");
    state.up_right_blocks = up_right_blocks_py;
    
    /* set up the random number generator again for each chunk
       so tallgrass is in the same place, no matter what mode is used */
    srand(1);
    
    for (state.x = 15; state.x > -1; state.x--) {
        for (state.y = 0; state.y < 16; state.y++) {
            PyObject *blockid = NULL;
            
            /* set up the render coordinates */
            state.imgx = xoff + state.x*12 + state.y*12;
            /* 128*12 -- offset for z direction, 15*6 -- offset for x */
            state.imgy = yoff - state.x*6 + state.y*6 + 128*12 + 15*6;
            
            for (state.z = 0; state.z < 128; state.z++) {
                state.imgy -= 12;
		
                /* get blockid */
                state.block = getArrayByte3D(blocks_py, state.x, state.y, state.z);
                if (state.block == 0) {
                    continue;
                }
                
                /* make sure we're rendering inside the image boundaries */
                if ((state.imgx >= imgsize0 + 24) || (state.imgx <= -24)) {
                    continue;
                }
                if ((state.imgy >= imgsize1 + 24) || (state.imgy <= -24)) {
                    continue;
                }

                
                /* decref'd on replacement *and* at the end of the z for block */
                if (blockid) {
                    Py_DECREF(blockid);
//.........这里部分代码省略.........
开发者ID:rmrector,项目名称:Minecraft-Overviewer,代码行数:101,代码来源:iterate.c


示例11: tile_ass_sub

static int
tile_ass_sub(PyGimpTile *self, PyObject *v, PyObject *w)
{
    GimpTile *tile = self->tile;
    int bpp = tile->bpp, i;
    long x, y;
    guchar *pix, *data;

    if (w == NULL) {
	PyErr_SetString(PyExc_TypeError,
			"can not delete pixels in tile");
	return -1;
    }

    if (!PyString_Check(w) && PyString_Size(w) == bpp) {
	PyErr_SetString(PyExc_TypeError, "invalid subscript");
	return -1;
    }

    pix = (guchar *)PyString_AsString(w);

    if (PyInt_Check(v)) {
	x = PyInt_AsLong(v);

	if (x < 0 || x >= tile->ewidth * tile->eheight) {
	    PyErr_SetString(PyExc_IndexError, "index out of range");
	    return -1;
	}

	data = tile->data + x * bpp;

	for (i = 0; i < bpp; i++)
	    data[i] = pix[i];

	tile->dirty = TRUE;

	return 0;
    }

    if (PyTuple_Check(v)) {
	if (!PyArg_ParseTuple(v, "ll", &x, &y))
	    return -1;

	if (x < 0 || y < 0 || x >= tile->ewidth || y>=tile->eheight) {
	    PyErr_SetString(PyExc_IndexError, "index out of range");
	    return -1;
	}

	data = tile->data + bpp * (x + y * tile->ewidth);

	for (i = 0; i < bpp; i++)
	    data[i] = pix[i];

	tile->dirty = TRUE;

	return 0;
    }

    PyErr_SetString(PyExc_TypeError, "tile subscript not int or 2-tuple");
    return -1;
}
开发者ID:AdamGrzonkowski,项目名称:gimp-1,代码行数:61,代码来源:pygimp-tile.c


示例12: curve_accurate_rect

static PyObject *
curve_accurate_rect(SKCurveObject * self, PyObject * args)
{
    SKRectObject * rect = NULL;
    CurveSegment * segment;
    PyObject * trafo = NULL;
    int i;

    if (!PyArg_ParseTuple(args, "|O!", &SKTrafoType, &trafo))
	return NULL;

    if (self->len == 0)
    {
	Py_INCREF(SKRect_EmptyRect);
	return (PyObject*)SKRect_EmptyRect;;
    }

    segment = self->segments;
    if (!trafo)
    {
	rect = (SKRectObject*)SKRect_FromDouble(segment->x, segment->y,
						segment->x, segment->y);
	if (!rect)
	    return NULL;

	segment += 1;
	for (i = 1; i < self->len; i++, segment++)
	{
	    SKRect_AddXY(rect, segment->x, segment->y);
	    if (segment->type == CurveBezier)
	    {
		add_bezier_rect(rect, segment[-1].x, segment[-1].y,
				segment->x1, segment->y1,
				segment->x2, segment->y2,
				segment->x, segment->y);
	    }
	}
    }
    else
    {
	SKCoord x, y;

	SKTrafo_TransformXY(trafo, segment->x, segment->y, &x, &y);
	rect = (SKRectObject*)SKRect_FromDouble(x, y, x, y);
	if (!rect)
	    return NULL;

	segment += 1;
	for (i = 1; i < self->len; i++, segment++)
	{
	    SKTrafo_TransformXY(trafo, segment->x, segment->y, &x, &y);
	    SKRect_AddXY(rect, x, y);
	    if (segment->type == CurveBezier)
	    {
		SKCoord p1x, p1y, p2x, p2y, p3x, p3y;
		SKTrafo_TransformXY(trafo, segment[-1].x, segment[-1].y,
				    &p1x, &p1y);
		SKTrafo_TransformXY(trafo, segment->x1, segment->y1,
				    &p2x, &p2y);
		SKTrafo_TransformXY(trafo, segment->x2, segment->y2,
				    &p3x, &p3y);
		add_bezier_rect(rect, p1x, p1y, p2x, p2y, p3x, p3y, x, y);
	    }
	}
    }
    return (PyObject*)rect;
}
开发者ID:kindlychung,项目名称:sk1,代码行数:67,代码来源:curveobject.c


示例13: curve_set_segment

static PyObject *
curve_set_segment(SKCurveObject * self, PyObject * args)
{
    double x, y, x1, y1, x2, y2;
    int cont = ContAngle;
    int idx, type;
    PyObject * p, *p1, *p2, *tuple;

    if (!PyArg_ParseTuple(args, "iOO|i", &idx, &type, &tuple, &p, &cont))
	return NULL;

    if (!skpoint_extract_xy(p, &x, &y))
    {
	PyErr_SetString(PyExc_TypeError,
			"third argument must be a point spec");
	return NULL;
    }


    idx = check_index(self, idx, "SetSegment");
    if (idx < 0)
	return NULL;

    self->segments[idx].type = CurveLine;
    self->segments[idx].cont = cont;
    self->segments[idx].x = x;
    self->segments[idx].y = y;

    if (type == CurveBezier)
    {
	if (!PyArg_ParseTuple(tuple, "OO", &p1, &p2))
	    return NULL;
	if (!skpoint_extract_xy(p1, &x1, &y1)
	    || !skpoint_extract_xy(p2, &x2, &y2))
	{
	    PyErr_SetString(PyExc_TypeError,
			    "for bezier segments, second argument "
			    "must be a sequence of two point specs ");
	    return NULL;
	}

	self->segments[idx].x1 = x1;	self->segments[idx].y1 = y1;
	self->segments[idx].x2 = x2;	self->segments[idx].y2 = y2;
    }

    if (self->closed)
    {
	if (idx == 0)
	{
	    self->segments[self->len - 1].x = x;
	    self->segments[self->len - 1].y = y;
	    self->segments[self->len - 1].cont = cont;
	}
	else if (idx == self->len - 1)
	{
	    self->segments[0].x = x;
	    self->segments[0].y = y;
	    self->segments[0].cont = cont;
	}
    }

    Py_INCREF(Py_None);
    return Py_None;
}
开发者ID:kindlychung,项目名称:sk1,代码行数:64,代码来源:curveobject.c


示例14: curve_set_curve

/* append a bezier segment to self. */
static PyObject *
curve_set_curve(SKCurveObject * self, PyObject * args)
{
    int idx, cont = ContAngle;
    double x, y, x1, y1, x2, y2;

    if (PyTuple_Size(args) > 5)
    {
	if (!PyArg_ParseTuple(args, "idddddd|i", &idx,
			      &x1, &y1, &x2, &y2, &x, &y, &cont))
	    return NULL;
    }
    else
    {
	PyObject *p1, *p2, *p3;
	int result;

	if (!PyArg_ParseTuple(args, "iOOO|i", &idx, &p1, &p2, &p3,
			      &cont))
	    return NULL;

	result = skpoint_extract_xy(p1, &x1, &y1);
	result = result && skpoint_extract_xy(p2, &x2, &y2);
	result = result && skpoint_extract_xy(p3, &x, &y);
	if (!result)
	{
	    PyErr_SetString(PyExc_TypeError, "three points expected");
	    return NULL;
	}
    }

    idx = check_index(self, idx, "SetBezier");
    if (idx < 0)
	return NULL;


    self->segments[idx].type = CurveBezier;
    self->segments[idx].cont = cont;
    self->segments[idx].x = x;	 self->segments[idx].y = y;
    self->segments[idx].x1 = x1; self->segments[idx].y1 = y1;
    self->segments[idx].x2 = x2; self->segments[idx].y2 = y2;

    if (self->closed)
    {
	if (idx == 0)
	{
	    self->segments[self->len - 1].x = x;
	    self->segments[self->len - 1].y = y;
	    self->segments[self->len - 1].cont = cont;
	}
	else if (idx == self->len - 1)
	{
	    self->segments[0].x = x;
	    self->segments[0].y = y;
	    self->segments[0].cont = cont;
	}
    }

    Py_INCREF(Py_None);
    return Py_None;
}
开发者ID:kindlychung,项目名称:sk1,代码行数:62,代码来源:curveobject.c


示例15: PyZlib_decompress

static PyObject *
PyZlib_decompress(PyObject *self, PyObject *args)
{
    PyObject *result_str;
    Byte *input;
    int length, err;
    int wsize=DEF_WBITS;
    Py_ssize_t r_strlen=DEFAULTALLOC;
    z_stream zst;

    if (!PyArg_ParseTuple(args, "s#|in:decompress",
                          &input, &length, &wsize, &r_strlen))
        return NULL;

    if (r_strlen <= 0)
        r_strlen = 1;

    zst.avail_in = length;
    zst.avail_out = r_strlen;

    if (!(result_str = PyString_FromStringAndSize(NULL, r_strlen)))
        return NULL;

    zst.zalloc = (alloc_func)NULL;
    zst.zfree = (free_func)Z_NULL;
    zst.next_out = (Byte *)PyString_AS_STRING(result_str);
    zst.next_in = (Byte *)input;
    err = inflateInit2(&zst, wsize);

    switch(err) {
    case(Z_OK):
        break;
    case(Z_MEM_ERROR):
        PyErr_SetString(PyExc_MemoryError,
                        "Out of memory while decompressing data");
        goto error;
    default:
        inflateEnd(&zst);
        zlib_error(zst, err, "while preparing to decompress data");
        goto error;
    }

    do {
        Py_BEGIN_ALLOW_THREADS
        err=inflate(&zst, Z_FINISH);
        Py_END_ALLOW_THREADS

        switch(err) {
        case(Z_STREAM_END):
            break;
        case(Z_BUF_ERROR):
            /*
             * If there is at least 1 byte of room according to zst.avail_out
             * and we get this error, assume that it means zlib cannot
             * process the inflate call() due to an error in the data.
             */
            if (zst.avail_out > 0) {
                zlib_error(zst, err, "while decompressing data");
                inflateEnd(&zst);
                goto error;
            }
            /* fall through */
        case(Z_OK):
            /* need more memory */
            if (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
                inflateEnd(&zst);
                goto error;
            }
            zst.next_out = (unsigned char *)PyString_AS_STRING(result_str) \
                + r_strlen;
            zst.avail_out = r_strlen;
            r_strlen = r_strlen << 1;
            break;
        default:
            inflateEnd(&zst);
            zlib_error(zst, err, "while decompressing data");
            goto error;
        }
    } while (err != Z_STREAM_END);

    err = inflateEnd(&zst);
    if (err != Z_OK) {
        zlib_error(zst, err, "while finishing data decompression");
        goto error;
    }

    _PyString_Resize(&result_str, zst.total_out);
    return result_str;

 error:
    Py_XDECREF(result_str);
    return NULL;
}
开发者ID:CSC-IT-Center-for-Science,项目名称:scalable-python,代码行数:93,代码来源:zlibmodule.c


示例16: strop_joinfields

static PyObject *
strop_joinfields(PyObject *self, PyObject *args)
{
	PyObject *seq;
	char *sep = NULL;
	Py_ssize_t seqlen, seplen = 0;
	Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
	PyObject *res = NULL;
	char* p = NULL;
	ssizeargfunc getitemfunc;

	WARN;
	if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
		return NULL;
	if (sep == NULL) {
		sep = " ";
		seplen = 1;
	}

	seqlen = PySequence_Size(seq);
	if (seqlen < 0 && PyErr_Occurred())
		return NULL;

	if (seqlen == 1) {
		/* Optimization if there's only one item */
		PyObject *item = PySequence_GetItem(seq, 0);
		if (item && !PyString_Check(item)) {
			PyErr_SetString(PyExc_TypeError,
				 "first argument must be sequence of strings");
			Py_DECREF(item);
			return NULL;
		}
		return item;
	}

	if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
		return NULL;
	p = PyString_AsString(res);

	/* optimize for lists, since it's the most common case.  all others
	 * (tuples and arbitrary sequences) just use the sequence abstract
	 * interface.
	 */
	if (PyList_Check(seq)) {
		for (i = 0; i < seqlen; i++) {
			PyObject *item = PyList_GET_ITEM(seq, i);
			if (!PyString_Check(item)) {
				PyErr_SetString(PyExc_TypeError,
				"first argument must be sequence of strings");
				Py_DECREF(res);
				return NULL;
			}
			slen = PyString_GET_SIZE(item);
			if (slen > PY_SSIZE_T_MAX - reslen ||
			    seplen > PY_SSIZE_T_MAX - reslen - seplen) {
				PyErr_SetString(PyExc_OverflowError,
						"input too long");
				Py_DECREF(res);
				return NULL;
			}
			while (reslen + slen + seplen >= sz) {
				if (_PyString_Resize(&res, sz * 2) < 0)
					return NULL;
				sz *= 2;
				p = PyString_AsString(res) + reslen;
			}
			if (i > 0) {
				memcpy(p, sep, seplen);
				p += seplen;
				reslen += seplen;
			}
			memcpy(p, PyString_AS_STRING(item), slen);
			p += slen;
			reslen += slen;
		}
		_PyString_Resize(&res, reslen);
		return res;
	}

	if (seq->ob_type->tp_as_sequence == NULL ||
		 (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
	{
		PyErr_SetString(PyExc_TypeError,
				"first argument must be a sequence");
		return NULL;
	}
	/* This is now type safe */
	for (i = 0; i < seqlen; i++) {
		PyObject *item = getitemfunc(seq, i);
		if (!item || !PyString_Check(item)) {
			PyErr_SetString(PyExc_TypeError,
				 "first argument must be sequence of strings");
			Py_DECREF(res);
			Py_XDECREF(item);
			return NULL;
		}
		slen = PyString_GET_SIZE(item);
		if (slen > PY_SSIZE_T_MAX - reslen ||
		    seplen > PY_SSIZE_T_MAX - reslen - seplen) {
			PyErr_SetString(PyExc_OverflowError,
//.........这里部分代码省略.........
开发者ID:lrq3000,项目名称:wpython2.wpython11,代码行数:101,代码来源:stropmodule.c


示例17: PyZlib_objdecompress

static PyObject *
PyZlib_objdecompress(compobject *self, PyObject *args)
{
    int err, inplen, max_length = 0;
    Py_ssize_t old_length, length = DEFAULTALLOC;
    PyObject *RetVal;
    Byte *input;
    unsigned long start_total_out;

    if (!PyArg_ParseTuple(args, "s#|i:decompress", &input,
                          &inplen, &max_length))
        return NULL;
    if (max_length < 0) {
        PyErr_SetString(PyExc_ValueError,
                        "max_length must be greater than zero");
        return NULL;
    }

    /* limit amount of data allocated to max_length */
    if (max_length && length > max_length)
        length = max_length;
    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
        return NULL;

    ENTER_ZLIB

    start_total_out = self->zst.total_out;
    self->zst.avail_in = inplen;
    self->zst.next_in = input;
    self->zst.avail_out = length;
    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);

    Py_BEGIN_ALLOW_THREADS
    err = inflate(&(self->zst), Z_SYNC_FLUSH);
    Py_END_ALLOW_THREADS

    /* While Z_OK and the output buffer is full, there might be more output.
       So extend the output buffer and try again.
    */
    while (err == Z_OK && self->zst.avail_out == 0) {
        /* If max_length set, don't continue decompressing if we've already
           reached the limit.
        */
        if (max_length && length >= max_length)
            break;

        /* otherwise, ... */
        old_length = length;
        length = length << 1;
        if (max_length && length > max_length)
            length = max_length;

        if (_PyString_Resize(&RetVal, length) < 0)
            goto error;
        self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
            + old_length;
        self->zst.avail_out = length - old_length;

        Py_BEGIN_ALLOW_THREADS
        err = inflate(&(self->zst), Z_SYNC_FLUSH);
        Py_END_ALLOW_THR 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ PyArg_UnpackTuple函数代码示例发布时间:2022-05-30
下一篇:
C++ PxVec3函数代码示例发布时间: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