Ejemplo n.º 1
0
/* 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;
}
Ejemplo n.º 2
0
/**
 *  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;
	
}
Ejemplo n.º 3
0
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;

}
Ejemplo n.º 4
0
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;
}
Ejemplo n.º 5
0
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;
}
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;
}
Ejemplo n.º 7
0
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) {
                    if (t->len > 2)
                        PyMem_Free(t->str);
                    PyMem_Free(t);
                }
            }
            bitw = 9;
            shr = 23;
            mask = 4286578688;

            /* 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;

            /* decoded.append(table[code]) */
            if (code < 256) {
                result_len++;
                *((int *)decoded_ptr++) = code;
            } else {
                newresult = table[code];
                newresult->ref++;
                result_len += newresult->len;
                 *(struct BYTE_STRING **)decoded_ptr++ = newresult;
            }
        } else {
            if (code < table_len) {
                /* code is in table */
                /* newresult = table[code]; */
                /* newentry = table[oldcode] + table[code][0] */
                /* decoded.append(newresult); table.append(newentry) */
                if (code < 256) {
                    c = code;
                    *((unsigned int *)decoded_ptr++) = code;
                    result_len++;
                } else {
                    newresult = table[code];
                    newresult->ref++;
                    c = (unsigned int) *newresult->str;
                    *(struct BYTE_STRING **)decoded_ptr++ = newresult;
                    result_len += newresult->len;
                }
                newentry = PyMem_Malloc(sizeof(struct BYTE_STRING));
                newentry->ref = 1;
                if (oldcode < 256) {
                    newentry->len = 2;
                    newentry->str = table2 + (oldcode << 9) +
                                    ((unsigned char)c << 1);
                } else {
                    len = table[oldcode]->len;
                    newentry->len = len + 1;
                    newentry->str = PyMem_Malloc(newentry->len);
                    if (newentry->str == NULL)
                        break;
                    memmove(newentry->str, table[oldcode]->str, len);
                    newentry->str[len] = c;
                }
                table[table_len++] = newentry;
            } else {
                /* code is not in table */
                /* newentry = newresult = table[oldcode] + table[oldcode][0] */
                /* decoded.append(newresult); table.append(newentry) */
                newresult = PyMem_Malloc(sizeof(struct BYTE_STRING));
                newentry = newresult;
                newentry->ref = 2;
                if (oldcode < 256) {
                    newentry->len = 2;
                    newentry->str = table2 + 514*oldcode;
                } else {
                    len = table[oldcode]->len;
                    newentry->len = len + 1;
                    newentry->str = PyMem_Malloc(newentry->len);
                    if (newentry->str == NULL)
                        break;
                    memmove(newentry->str, table[oldcode]->str, len);
                    newentry->str[len] = *table[oldcode]->str;
                }
                table[table_len++] = newentry;
                *(struct BYTE_STRING **)decoded_ptr++ = newresult;
                result_len += newresult->len;
            }
        }
        oldcode = code;
        /* increase bit-width if necessary */
        switch (table_len) {
            case 511:
                bitw = 10;
                shr = 22;
                mask = 4290772992;
                break;
            case 1023:
                bitw = 11;
                shr = 21;
                mask = 4292870144;
                break;
            case 2047:
                bitw = 12;
                shr = 20;
                mask = 4293918720;
        }
    }
Ejemplo n.º 8
0
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,
                                             pr->bpp * (x2 - x1) * (y2 - y1));
            gimp_pixel_rgn_get_rect(pr, (guchar*)PyString_AS_STRING(ret),
                                    x1, y1, x2 - x1, y2 - y1);
	    }
        else {
            PyErr_SetString(PyExc_TypeError, "invalid y subscript");
            return NULL;
        }

    } else {
        PyErr_SetString(PyExc_TypeError, "invalid x subscript");
        return NULL;
    }
    return ret;
}
Ejemplo n.º 9
0
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;
            }

            if (len != pr->bpp * (x2 - x1)) {
                PyErr_SetString(PyExc_TypeError, "string is wrong length");
                return -1;
            }
            gimp_pixel_rgn_set_row(pr, buf, 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 -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 * (x2 - x1) * (y2 - y1)) {
                PyErr_SetString(PyExc_TypeError, "string is wrong length");
                return -1;
            }
            gimp_pixel_rgn_set_rect(pr, buf, x1, y1, x2 - x1, y2 - y1);

        } else {
            PyErr_SetString(PyExc_IndexError,"invalid y subscript");
            return -1;
        }
    } else {
        PyErr_SetString(PyExc_TypeError, "invalid x subscript");
        return -1;
    }
    return 0;
}
Ejemplo n.º 10
0
/* 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);
                }
                blockid = PyInt_FromLong(state.block);

                // check for occlusion
                if (rendermode->occluded(rm_data, &state)) {
                    continue;
                }
                
                // everything stored here will be a borrowed ref

                /* get the texture and mask from block type / ancil. data */
                if (!PySequence_Contains(special_blocks, blockid)) {
                    /* t = textures.blockmap[blockid] */
                    t = PyList_GetItem(blockmap, state.block);
                } else {
                    PyObject *tmp;
                    
                    unsigned char ancilData = getArrayByte3D(state.blockdata_expanded, state.x, state.y, state.z);
                    state.block_data = ancilData;
                    /* block that need pseudo ancildata:
                     * grass, water, glass, chest, restone wire,
                     * ice, fence and portal. */
                    if ((state.block ==  2) || (state.block ==  9) || 
                        (state.block == 20) || (state.block == 54) || 
                        (state.block == 55) || (state.block == 79) ||
                        (state.block == 85) || (state.block == 90)) {
                        ancilData = generate_pseudo_data(&state, ancilData);
                        state.block_pdata = ancilData;
                    } else {
                        state.block_pdata = 0;
                    }
                    
                    tmp = PyTuple_New(2);

                    Py_INCREF(blockid); /* because SetItem steals */
                    PyTuple_SetItem(tmp, 0, blockid);
                    PyTuple_SetItem(tmp, 1, PyInt_FromLong(ancilData));
                    
                    /* this is a borrowed reference. no need to decref */
                    t = PyDict_GetItem(specialblockmap, tmp);
                    Py_DECREF(tmp);
                }
                
                /* if we found a proper texture, render it! */
                if (t != NULL && t != Py_None)
                {
                    PyObject *src, *mask, *mask_light;
                    int randx = 0, randy = 0;
                    src = PyTuple_GetItem(t, 0);
                    mask = PyTuple_GetItem(t, 1);
                    mask_light = PyTuple_GetItem(t, 2);

                    if (mask == Py_None)
                        mask = src;

                    if (state.block == 31) {
                        /* add a random offset to the postion of the tall grass to make it more wild */
                        randx = rand() % 6 + 1 - 3;
                        randy = rand() % 6 + 1 - 3;
                        state.imgx += randx;
                        state.imgy += randy;
                    }
                    
                    rendermode->draw(rm_data, &state, src, mask, mask_light);
                    
                    if (state.block == 31) {
                        /* undo the random offsets */
                        state.imgx -= randx;
                        state.imgy -= randy;
                    }
                }               
            }
            
            if (blockid) {
                Py_DECREF(blockid);
                blockid = NULL;
            }
        }
    }

    /* free up the rendermode info */
    rendermode->finish(rm_data, &state);
    free(rm_data);
    
    Py_DECREF(blocks_py);
    Py_XDECREF(left_blocks_py);
    Py_XDECREF(right_blocks_py);
    Py_XDECREF(up_left_blocks_py);
    Py_XDECREF(up_right_blocks_py);

    return Py_BuildValue("i",2);
}
Ejemplo n.º 11
0
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;
}
Ejemplo n.º 12
0
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;
}
Ejemplo n.º 13
0
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;
}
Ejemplo n.º 14
0
/* 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;
}
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;
}
Ejemplo n.º 16
0
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,
					"input too long");
			Py_DECREF(res);
			Py_XDECREF(item);
			return NULL;
		}
		while (reslen + slen + seplen >= sz) {
			if (_PyString_Resize(&res, sz * 2) < 0) {
				Py_DECREF(item);
				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;
		Py_DECREF(item);
	}
	_PyString_Resize(&res, reslen);
	return res;
}
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_THREADS
    }

    /* Not all of the compressed data could be accommodated in the output buffer
       of specified size. Return the unconsumed tail in an attribute.*/
    if(max_length) {
        Py_DECREF(self->unconsumed_tail);
        self->unconsumed_tail = PyString_FromStringAndSize((char *)self->zst.next_in,
                                                           self->zst.avail_in);
        if(!self->unconsumed_tail) {
            Py_DECREF(RetVal);
            RetVal = NULL;
            goto error;
        }
    }

    /* The end of the compressed data has been reached, so set the
       unused_data attribute to a string containing the remainder of the
       data in the string.  Note that this is also a logical place to call
       inflateEnd, but the old behaviour of only calling it on flush() is
       preserved.
    */
    if (err == Z_STREAM_END) {
        Py_XDECREF(self->unused_data);  /* Free original empty string */
        self->unused_data = PyString_FromStringAndSize(
            (char *)self->zst.next_in, self->zst.avail_in);
        if (self->unused_data == NULL) {
            Py_DECREF(RetVal);
            goto error;
        }
        /* 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 decompressing");
        Py_DECREF(RetVal);
        RetVal = NULL;
        goto error;
    }

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

 error:
    LEAVE_ZLIB

    return RetVal;
}
Ejemplo n.º 18
0
static PyObject *
strop_expandtabs(PyObject *self, PyObject *args)
{
	/* Original by Fredrik Lundh */
	char* e;
	char* p;
	char* q;
	Py_ssize_t i, j, old_j;
	PyObject* out;
	char* string;
	Py_ssize_t stringlen;
	int tabsize = 8;

	WARN;
	/* Get arguments */
	if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
		return NULL;
	if (tabsize < 1) {
		PyErr_SetString(PyExc_ValueError,
				"tabsize must be at least 1");
		return NULL;
	}

	/* First pass: determine size of output string */
	i = j = old_j = 0; /* j: current column; i: total of previous lines */
	e = string + stringlen;
	for (p = string; p < e; p++) {
		if (*p == '\t') {
			j += tabsize - (j%tabsize);
			if (old_j > j) {
				PyErr_SetString(PyExc_OverflowError,
						"new string is too long");
				return NULL;
			}
			old_j = j;
		} else {
			j++;
			if (*p == '\n') {
				i += j;
				j = 0;
			}
		}
	}

	if ((i + j) < 0) {
		PyErr_SetString(PyExc_OverflowError, "new string is too long");
		return NULL;
	}

	/* Second pass: create output string and fill it */
	out = PyString_FromStringAndSize(NULL, i+j);
	if (out == NULL)
		return NULL;

	i = 0;
	q = PyString_AS_STRING(out);

	for (p = string; p < e; p++) {
		if (*p == '\t') {
			j = tabsize - (i%tabsize);
			i += j;
			while (j-- > 0)
				*q++ = ' ';
		} else {
			*q++ = *p;
			i++;
			if (*p == '\n')
				i = 0;
		}
	}

	return out;
}
static PyObject *
PyZlib_unflush(compobject *self, PyObject *args)
{
    int err, length = DEFAULTALLOC;
    PyObject * retval = NULL;
    unsigned long start_total_out;

    if (!PyArg_ParseTuple(args, "|i:flush", &length))
        return NULL;
    if (length <= 0) {
        PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
        return NULL;
    }
    if (!(retval = PyString_FromStringAndSize(NULL, length)))
        return NULL;


    ENTER_ZLIB

    start_total_out = self->zst.total_out;
    self->zst.avail_out = length;
    self->zst.next_out = (Byte *)PyString_AS_STRING(retval);

    Py_BEGIN_ALLOW_THREADS
    err = inflate(&(self->zst), Z_FINISH);
    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 || err == Z_BUF_ERROR) && self->zst.avail_out == 0) {
        if (_PyString_Resize(&retval, length << 1) < 0)
            goto error;
        self->zst.next_out = (Byte *)PyString_AS_STRING(retval) + length;
        self->zst.avail_out = length;
        length = length << 1;

        Py_BEGIN_ALLOW_THREADS
        err = inflate(&(self->zst), Z_FINISH);
        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 */
    if (err == Z_STREAM_END) {
        err = inflateEnd(&(self->zst));
        self->is_initialised = 0;
        if (err != Z_OK) {
            zlib_error(self->zst, err, "from inflateEnd()");
            Py_DECREF(retval);
            retval = NULL;
            goto error;
        }
    }
    _PyString_Resize(&retval, self->zst.total_out - start_total_out);

error:

    LEAVE_ZLIB

    return retval;
}
Ejemplo n.º 20
0
static PyObject *
strop_translate(PyObject *self, PyObject *args)
{
	register char *input, *table, *output;
	Py_ssize_t i; 
	int c, changed = 0;
	PyObject *input_obj;
	char *table1, *output_start, *del_table=NULL;
	Py_ssize_t inlen, tablen, dellen = 0;
	PyObject *result;
	int trans_table[256];

	WARN;
	if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
			      &table1, &tablen, &del_table, &dellen))
		return NULL;
	if (tablen != 256) {
		PyErr_SetString(PyExc_ValueError,
			      "translation table must be 256 characters long");
		return NULL;
	}

	table = table1;
	inlen = PyString_GET_SIZE(input_obj);
	result = PyString_FromStringAndSize((char *)NULL, inlen);
	if (result == NULL)
		return NULL;
	output_start = output = PyString_AsString(result);
	input = PyString_AsString(input_obj);

	if (dellen == 0) {
		/* If no deletions are required, use faster code */
		for (i = inlen; --i >= 0; ) {
			c = Py_CHARMASK(*input++);
			if (Py_CHARMASK((*output++ = table[c])) != c)
				changed = 1;
		}
		if (changed)
			return result;
		Py_DECREF(result);
		Py_INCREF(input_obj);
		return input_obj;
	}

	for (i = 0; i < 256; i++)
		trans_table[i] = Py_CHARMASK(table[i]);

	for (i = 0; i < dellen; i++)
		trans_table[(int) Py_CHARMASK(del_table[i])] = -1;

	for (i = inlen; --i >= 0; ) {
		c = Py_CHARMASK(*input++);
		if (trans_table[c] != -1)
			if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
				continue;
		changed = 1;
	}
	if (!changed) {
		Py_DECREF(result);
		Py_INCREF(input_obj);
		return input_obj;
	}
	/* Fix the size of the resulting string */
	if (inlen > 0)
		_PyString_Resize(&result, output - output_start);
	return result;
}
Ejemplo n.º 21
0
static PyObject *
py_decodepackbits(PyObject *obj, PyObject *args)
{
    int n;
    char e;
    char *decoded = NULL;
    char *encoded = NULL;
    char *encoded_end = NULL;
    char *encoded_pos = NULL;
    unsigned int encoded_len;
    unsigned int decoded_len;
    PyObject *byteobj = NULL;
    PyObject *result = NULL;

    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 */
    Py_BEGIN_ALLOW_THREADS

    /* determine size of decoded string */
    encoded_pos = encoded;
    encoded_end = encoded + encoded_len;
    decoded_len = 0;
    while (encoded_pos < encoded_end) {
        n = (int)*encoded_pos++;
        if (n >= 0) {
            n++;
            if (encoded_pos+n > encoded_end)
                n = (int)(encoded_end - encoded_pos);
            encoded_pos += n;
            decoded_len += n;
        } else if (n > -128) {
            encoded_pos++;
            decoded_len += 1-n;
        }
    }
    Py_END_ALLOW_THREADS

    result = PyBytes_FromStringAndSize(0, decoded_len);
    if (result == NULL) {
        PyErr_Format(PyExc_MemoryError, "failed to allocate decoded string");
        goto _fail;
    }
    decoded = PyBytes_AS_STRING(result);

    Py_BEGIN_ALLOW_THREADS

    /* decode string */
    encoded_end = encoded + encoded_len;
    while (encoded < encoded_end) {
        n = (int)*encoded++;
        if (n >= 0) {
            n++;
            if (encoded+n > encoded_end)
                n = (int)(encoded_end - encoded);
            /* memmove(decoded, encoded, n); decoded += n; encoded += n; */
            while (n--)
                *decoded++ = *encoded++;
        } else if (n > -128) {
            n = 1 - n;
            e = *encoded++;
            /* memset(decoded, e, n); decoded += n; */
            while (n--)
                *decoded++ = e;
        }
    }
    Py_END_ALLOW_THREADS

    Py_DECREF(byteobj);
    return result;

  _fail:
    Py_XDECREF(byteobj);
    Py_XDECREF(result);
    return NULL;
}
Ejemplo n.º 22
0
/* Convert 9-item tuple to tm structure.  Return 1 on success, set
 * an exception and return 0 on error.
 */
static int
gettmarg(PyObject *args, struct tm *p)
{
    int y;

    memset((void *) p, '\0', sizeof(struct tm));

    if (!PyTuple_Check(args)) {
        PyErr_SetString(PyExc_TypeError,
                        "Tuple or struct_time argument required");
        return 0;
    }

    if (!PyArg_ParseTuple(args, "iiiiiiiii",
                          &y, &p->tm_mon, &p->tm_mday,
                          &p->tm_hour, &p->tm_min, &p->tm_sec,
                          &p->tm_wday, &p->tm_yday, &p->tm_isdst))
        return 0;

    /* If year is specified with less than 4 digits, its interpretation
     * depends on the accept2dyear value.
     *
     * If accept2dyear is true (default), a backward compatibility behavior is
     * invoked as follows:
     *
     *   - for 2-digit year, century is guessed according to POSIX rules for
     *      %y strptime format: 21st century for y < 69, 20th century
     *      otherwise.  A deprecation warning is issued when century
     *      information is guessed in this way.
     *
     *   - for 3-digit or negative year, a ValueError exception is raised.
     *
     * If accept2dyear is false (set by the program or as a result of a
     * non-empty value assigned to PYTHONY2K environment variable) all year
     * values are interpreted as given.
     */
    if (y < 1000) {
        PyObject *accept = PyDict_GetItemString(moddict,
                                                "accept2dyear");
        if (accept != NULL) {
            int acceptval =  PyObject_IsTrue(accept);
            if (acceptval == -1)
                return 0;
            if (acceptval) {
                if (0 <= y && y < 69)
                    y += 2000;
                else if (69 <= y && y < 100)
                    y += 1900;
                else {
                    PyErr_SetString(PyExc_ValueError,
                                    "year out of range");
                    return 0;
                }
                if (PyErr_WarnEx(PyExc_DeprecationWarning,
                           "Century info guessed for a 2-digit year.", 1) != 0)
                    return 0;
            }
        }
        else
            return 0;
    }
    p->tm_year = y - 1900;
    p->tm_mon--;
    p->tm_wday = (p->tm_wday + 1) % 7;
    p->tm_yday--;
    return 1;
}
Ejemplo n.º 23
0
PyObject* Effect::wrapSetColor(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("");
		}
	}

	// check the number of arguments
	int argCount = PyTuple_Size(args);
	if (argCount == 3)
	{
		// three seperate arguments for red, green, and blue
		ColorRgb color;
		if (PyArg_ParseTuple(args, "bbb", &color.red, &color.green, &color.blue))
		{
			std::fill(effect->_colors.begin(), effect->_colors.end(), color);
			effect->setColors(effect->_priority, effect->_colors, timeout, false);
			return Py_BuildValue("");
		}
		else
		{
			return nullptr;
		}
	}
	else if (argCount == 1)
	{
		// bytearray of values
		PyObject * bytearray = nullptr;
		if (PyArg_ParseTuple(args, "O", &bytearray))
		{
			if (PyByteArray_Check(bytearray))
			{
				size_t length = PyByteArray_Size(bytearray);
				if (length == 3 * effect->_imageProcessor->getLedCount())
				{
					char * data = PyByteArray_AS_STRING(bytearray);
					memcpy(effect->_colors.data(), data, length);
					effect->setColors(effect->_priority, effect->_colors, timeout, false);
					return Py_BuildValue("");
				}
				else
				{
					PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should be 3*ledCount");
					return nullptr;
				}
			}
			else
			{
				PyErr_SetString(PyExc_RuntimeError, "Argument is not a bytearray");
				return nullptr;
			}
		}
		else
		{
			return nullptr;
		}
	}
	else
	{
		PyErr_SetString(PyExc_RuntimeError, "Function expect 1 or 3 arguments");
		return nullptr;
	}

	// error
	PyErr_SetString(PyExc_RuntimeError, "Unknown error");
	return nullptr;
}
Ejemplo n.º 24
0
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
    PyObject *tup = NULL;
    struct tm buf;
    const time_char *fmt;
#ifdef HAVE_WCSFTIME
    wchar_t *format;
#else
    PyObject *format;
#endif
    PyObject *format_arg;
    size_t fmtlen, buflen;
    time_char *outbuf = NULL;
    size_t i;
    PyObject *ret = NULL;

    memset((void *) &buf, '\0', sizeof(buf));

    /* Will always expect a unicode string to be passed as format.
       Given that there's no str type anymore in py3k this seems safe.
    */
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
        return NULL;

    if (tup == NULL) {
        time_t tt = time(NULL);
        buf = *localtime(&tt);
    }
    else if (!gettmarg(tup, &buf) || !checktm(&buf))
        return NULL;

#if defined(_MSC_VER) || defined(sun)
    if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
        PyErr_SetString(PyExc_ValueError,
                        "strftime() requires year in [1; 9999]");
        return NULL;
    }
#endif

    /* Normalize tm_isdst just in case someone foolishly implements %Z
       based on the assumption that tm_isdst falls within the range of
       [-1, 1] */
    if (buf.tm_isdst < -1)
        buf.tm_isdst = -1;
    else if (buf.tm_isdst > 1)
        buf.tm_isdst = 1;

#ifdef HAVE_WCSFTIME
    format = PyUnicode_AsWideCharString(format_arg, NULL);
    if (format == NULL)
        return NULL;
    fmt = format;
#else
    /* Convert the unicode string to an ascii one */
    format = PyUnicode_EncodeFSDefault(format_arg);
    if (format == NULL)
        return NULL;
    fmt = PyBytes_AS_STRING(format);
#endif

#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
    /* check that the format string contains only valid directives */
    for(outbuf = strchr(fmt, '%');
        outbuf != NULL;
        outbuf = strchr(outbuf+2, '%'))
    {
        if (outbuf[1]=='#')
            ++outbuf; /* not documented by python, */
        if (outbuf[1]=='\0' ||
            !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
        {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            Py_DECREF(format);
            return NULL;
        }
    }
#endif

    fmtlen = time_strlen(fmt);

    /* I hate these functions that presume you know how big the output
     * will be ahead of time...
     */
    for (i = 1024; ; i += i) {
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        int err;
#endif
        outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
        if (outbuf == NULL) {
            PyErr_NoMemory();
            break;
        }
        buflen = format_time(outbuf, i, fmt, &buf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        err = errno;
#endif
        if (buflen > 0 || i >= 256 * fmtlen) {
            /* If the buffer is 256 times as long as the format,
               it's probably not failing for lack of room!
               More likely, the format yields an empty result,
               e.g. an empty format, or %Z when the timezone
               is unknown. */
#ifdef HAVE_WCSFTIME
            ret = PyUnicode_FromWideChar(outbuf, buflen);
#else
            ret = PyUnicode_DecodeFSDefaultAndSize(outbuf, buflen);
#endif
            PyMem_Free(outbuf);
            break;
        }
        PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        /* VisualStudio .NET 2005 does this properly */
        if (buflen == 0 && err == EINVAL) {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            break;
        }
#endif
    }
#ifdef HAVE_WCSFTIME
    PyMem_Free(format);
#else
    Py_DECREF(format);
#endif
    return ret;
}
Ejemplo n.º 25
0
/*******************************************************************************
 ** Calculate the bond order parameters and filter atoms (if required).
 **
 ** Inputs:
 **     - visibleAtoms: the list of atoms that are currently visible
 **     - pos: positions of all the atoms
 **     - maxBondDistance: the maximum bond distance to consider
 **     - scalarsQ4: array to store the Q4 parameter value
 **     - scalarsQ6: array to store the Q6 parameter value
 **     - cellDims: simulation cell dimensions
 **     - PBC: periodic boundaries conditions
 **     - NScalars: the number of previously calculated scalar values
 **     - fullScalars: the full list of previously calculated scalars
 **     - NVectors: the number of previously calculated vector values
 **     - fullVectors: the full list of previously calculated vectors
 **     - filterQ4: filter atoms by the Q4 parameter
 **     - minQ4: the minimum Q4 for an atom to be visible
 **     - maxQ4: the maximum Q4 for an atom to be visible
 **     - filterQ6: filter atoms by the Q6 parameter
 **     - minQ6: the minimum Q6 for an atom to be visible
 **     - maxQ6: the maximum Q6 for an atom to be visible
 *******************************************************************************/
static PyObject*
bondOrderFilter(PyObject *self, PyObject *args)
{
    int NVisibleIn, *visibleAtoms, *PBC, NScalars, filterQ4Enabled, filterQ6Enabled;
    int NVectors;
    double maxBondDistance, *scalarsQ4, *scalarsQ6, *cellDims;
    double *pos, *fullScalars, minQ4, maxQ4, minQ6, maxQ6;
    PyArrayObject *posIn=NULL;
    PyArrayObject *visibleAtomsIn=NULL;
    PyArrayObject *PBCIn=NULL;
    PyArrayObject *scalarsQ4In=NULL;
    PyArrayObject *scalarsQ6In=NULL;
    PyArrayObject *cellDimsIn=NULL;
    PyArrayObject *fullScalarsIn=NULL;
    PyArrayObject *fullVectors=NULL;

    int i, NVisible, boxstat;
    double *visiblePos, maxSep2;
    struct Boxes *boxes;
    struct NeighbourList *nebList;
    struct AtomStructureResults *results;

    /* parse and check arguments from Python */
    if (!PyArg_ParseTuple(args, "O!O!dO!O!O!O!iO!iddiddiO!", &PyArray_Type, &visibleAtomsIn, &PyArray_Type, &posIn, &maxBondDistance,
            &PyArray_Type, &scalarsQ4In, &PyArray_Type, &scalarsQ6In, &PyArray_Type, &cellDimsIn, &PyArray_Type, &PBCIn, &NScalars,
            &PyArray_Type, &fullScalarsIn, &filterQ4Enabled, &minQ4, &maxQ4, &filterQ6Enabled, &minQ6, &maxQ6, &NVectors,
            &PyArray_Type, &fullVectors))
        return NULL;

    if (not_intVector(visibleAtomsIn)) return NULL;
    visibleAtoms = pyvector_to_Cptr_int(visibleAtomsIn);
    NVisibleIn = (int) PyArray_DIM(visibleAtomsIn, 0);

    if (not_doubleVector(posIn)) return NULL;
    pos = pyvector_to_Cptr_double(posIn);

    if (not_doubleVector(scalarsQ4In)) return NULL;
    scalarsQ4 = pyvector_to_Cptr_double(scalarsQ4In);

    if (not_doubleVector(scalarsQ6In)) return NULL;
    scalarsQ6 = pyvector_to_Cptr_double(scalarsQ6In);

    if (not_doubleVector(cellDimsIn)) return NULL;
    cellDims = pyvector_to_Cptr_double(cellDimsIn);

    if (not_intVector(PBCIn)) return NULL;
    PBC = pyvector_to_Cptr_int(PBCIn);

    if (not_doubleVector(fullScalarsIn)) return NULL;
    fullScalars = pyvector_to_Cptr_double(fullScalarsIn);

    if (not_doubleVector(fullVectors)) return NULL;

    /* construct array of positions of visible atoms */
    visiblePos = malloc(3 * NVisibleIn * sizeof(double));
    if (visiblePos == NULL)
    {
        PyErr_SetString(PyExc_MemoryError, "Could not allocate visiblePos");
        return NULL;
    }
    for (i = 0; i < NVisibleIn; i++)
    {
        int index = visibleAtoms[i];
        int ind3 = 3 * index;
        int i3 = 3 * i;
        visiblePos[i3    ] = pos[ind3    ];
        visiblePos[i3 + 1] = pos[ind3 + 1];
        visiblePos[i3 + 2] = pos[ind3 + 2];
    }

    /* box visible atoms */
    boxes = setupBoxes(maxBondDistance, PBC, cellDims);
    if (boxes == NULL)
    {
        free(visiblePos);
        return NULL;
    }
    boxstat = putAtomsInBoxes(NVisibleIn, visiblePos, boxes);
    if (boxstat)
    {
        free(visiblePos);
        return NULL;
    }

    /* build neighbour list */
    maxSep2 = maxBondDistance * maxBondDistance;
    nebList = constructNeighbourList(NVisibleIn, visiblePos, boxes, cellDims, PBC, maxSep2);

    /* only required for building neb list */
    free(visiblePos);
    freeBoxes(boxes);

    /* return if failed to build the neighbour list */
    if (nebList == NULL) return NULL;

    /* allocate results structure */
    results = malloc(NVisibleIn * sizeof(struct AtomStructureResults));
    if (results == NULL)
    {
        PyErr_SetString(PyExc_MemoryError, "Could not allocate results");
        freeNeighbourList(nebList, NVisibleIn);
        return NULL;
    }

    /* first calc q_lm for each atom over all m values */
    complex_qlm(NVisibleIn, visibleAtoms, nebList, pos, cellDims, PBC, results);

    /* free neighbour list */
    freeNeighbourList(nebList, NVisibleIn);

    /* calculate Q4 and Q6 */
    calculate_Q(NVisibleIn, results);

    /* do filtering here, storing results along the way */
    NVisible = 0;
    for (i = 0; i < NVisibleIn; i++)
    {
        int j;
        double q4 = results[i].Q4;
        double q6 = results[i].Q6;

        /* skip if not within the valid range */
        if (filterQ4Enabled && (q4 < minQ4 || q4 > maxQ4))
            continue;
        if (filterQ6Enabled && (q6 < minQ6 || q6 > maxQ6))
            continue;

        /* store in visible atoms array */
        visibleAtoms[NVisible] = visibleAtoms[i];

        /* store calculated values */
        scalarsQ4[NVisible] = q4;
        scalarsQ6[NVisible] = q6;

        /* update full scalars/vectors arrays */
        for (j = 0; j < NScalars; j++)
        {
            int nj = j * NVisibleIn;
            fullScalars[nj + NVisible] = fullScalars[nj + i];
        }

        for (j = 0; j < NVectors; j++)
        {
            int nj = j * NVisibleIn;
            DIND2(fullVectors, nj + NVisible, 0) = DIND2(fullVectors, nj + i, 0);
            DIND2(fullVectors, nj + NVisible, 1) = DIND2(fullVectors, nj + i, 1);
            DIND2(fullVectors, nj + NVisible, 2) = DIND2(fullVectors, nj + i, 2);
        }

        NVisible++;
    }

    /* free results memory */
    free(results);

    return Py_BuildValue("i", NVisible);
}
Ejemplo n.º 26
0
static PyObject *extfunc_do_select(PyObject *self, PyObject *args, int mode) {
	wchar_t** command;
	const char *type, *name;
	int haderror;
	int i;
	
	// This accepts a variable number of arguments.
	
	if (PyTuple_Size(args) == 0) {
		PyErr_SetString(g_PrPyExc, "You must pass at least one Praat object name to the select method.");
		return NULL;
	}
	
	for (i = 0; i < PyTuple_Size(args); i++) {
		PyObject *item = PyTuple_GetItem(args, i);
		
		// If it is a string, it is an object type and name together.
		if (PyString_Check(item)) {
			type = NULL;
			name = PyString_AsString(item);
			
		// If it is a tuple of length two, it has (type, name)
		} else if (PyTuple_Check(item) && PyTuple_Size(item) == 2) {
			if (!PyArg_ParseTuple(item, "ss", &type, &name)) 
				return NULL;

		} else {
			PyErr_SetString(g_PrPyExc, "Arguments to select must be strings like 'LongSound mysound' or tuples like ('LongSound', 'mysound').");
			return NULL;
		}
		
		command = (wchar_t**)calloc(4, sizeof(wchar_t*));		
		

		if (i == 0 && mode == 0)
			command[0] = wcsdup(L"select");
		else if (mode == 0 || mode == 1)
			command[0] = wcsdup(L"plus");
		else if (mode == 2)
			command[0] = wcsdup(L"minus");

		if (type == NULL) {
			command[1] = (wchar_t*)calloc(strlen(name)+1, sizeof(wchar_t));
			command[2] = NULL;
			swprintf(command[1], (strlen(name)+1)*sizeof(wchar_t), L"%s", name);
		} else {
			command[1] = (wchar_t*)calloc(strlen(type)+1, sizeof(wchar_t));
			command[2] = (wchar_t*)calloc(strlen(name)+1, sizeof(wchar_t));
			command[3] = NULL;
			swprintf(command[1], (strlen(type)+1)*sizeof(wchar_t), L"%s", type);
			swprintf(command[2], (strlen(name)+1)*sizeof(wchar_t), L"%s", name);
		}

		wchar_t *ret = scripting_executePraatCommand(command, 0, &haderror);
		if (haderror) {
			char *cret = wc2c(ret, 1);
			PyErr_SetString(g_PrPyExc, cret);
			free(cret);
			return NULL;
		}
	}

	return Py_BuildValue("");
}
Ejemplo n.º 27
0
inline static PyObject* parseTupleToFastSequence( PyObject* args )
{
	PyObject* seq;
	if( !PyArg_ParseTuple( args, "O", &seq ) ) return NULL;
	return PySequence_Fast( seq, "argument must be iterable" );
}
static PyObject *
PyZlib_compress(PyObject *self, PyObject *args)
{
    PyObject *ReturnVal = NULL;
    Byte *input, *output;
    int length, level=Z_DEFAULT_COMPRESSION, err;
    z_stream zst;

    /* require Python string object, optional 'level' arg */
    if (!PyArg_ParseTuple(args, "s#|i:compress", &input, &length, &level))
        return NULL;

    zst.avail_out = length + length/1000 + 12 + 1;

    output = (Byte*)malloc(zst.avail_out);
    if (output == NULL) {
        PyErr_SetString(PyExc_MemoryError,
                        "Can't allocate memory to compress data");
        return NULL;
    }

    /* Past the point of no return.  From here on out, we need to make sure
       we clean up mallocs & INCREFs. */

    zst.zalloc = (alloc_func)NULL;
    zst.zfree = (free_func)Z_NULL;
    zst.next_out = (Byte *)output;
    zst.next_in = (Byte *)input;
    zst.avail_in = length;
    err = deflateInit(&zst, level);

    switch(err) {
    case(Z_OK):
        break;
    case(Z_MEM_ERROR):
        PyErr_SetString(PyExc_MemoryError,
                        "Out of memory while compressing data");
        goto error;
    case(Z_STREAM_ERROR):
        PyErr_SetString(ZlibError,
                        "Bad compression level");
        goto error;
    default:
        deflateEnd(&zst);
        zlib_error(zst, err, "while compressing data");
        goto error;
    }

    Py_BEGIN_ALLOW_THREADS;
    err = deflate(&zst, Z_FINISH);
    Py_END_ALLOW_THREADS;

    if (err != Z_STREAM_END) {
        zlib_error(zst, err, "while compressing data");
        deflateEnd(&zst);
        goto error;
    }

    err=deflateEnd(&zst);
    if (err == Z_OK)
        ReturnVal = PyString_FromStringAndSize((char *)output,
                                               zst.total_out);
    else
        zlib_error(zst, err, "while finishing compression");

 error:
    free(output);

    return ReturnVal;
}
Ejemplo n.º 29
0
static PyObject*
movie_set_display (PyObject* self, PyObject* args)
{
    SMPEG* movie = PyMovie_AsSMPEG (self);
    PyObject* surfobj, *posobj=NULL;
    GAME_Rect *rect, temp;
    int x=0, y=0;
    if (!PyArg_ParseTuple (args, "O|O", &surfobj, &posobj))
        return NULL;


	if (!SDL_WasInit (SDL_INIT_VIDEO))
        return RAISE (PyExc_SDLError,
                      "cannot convert without pygame.display initialized");


    Py_XDECREF (((PyMovieObject*) self)->surftarget);
    ((PyMovieObject*) self)->surftarget = NULL;

    if (PySurface_Check (surfobj))
    {
        SMPEG_Info info;
        SDL_Surface* surf;

        if (posobj == NULL)
        {
            Py_BEGIN_ALLOW_THREADS;
            SMPEG_getinfo (movie, &info);
            SMPEG_scaleXY (movie, info.width, info.height);
            Py_END_ALLOW_THREADS;
            x = y = 0;
        }
        else if (TwoIntsFromObj (posobj, &x, &y))
        {
            Py_BEGIN_ALLOW_THREADS;
            SMPEG_getinfo (movie, &info);
            SMPEG_scaleXY (movie, info.width, info.height);
            Py_END_ALLOW_THREADS;
        }
        else if ((rect = GameRect_FromObject (posobj, &temp)))
        {
            x = rect->x;
            y = rect->y;
            Py_BEGIN_ALLOW_THREADS;
            SMPEG_scaleXY (movie, rect->w, rect->h);
            Py_END_ALLOW_THREADS;
        }
        else
            return RAISE (PyExc_TypeError, "Invalid position argument");

        surf = PySurface_AsSurface (surfobj);

        Py_BEGIN_ALLOW_THREADS;
        SMPEG_getinfo (movie, &info);
        SMPEG_enablevideo (movie, 1);
        SMPEG_setdisplay (movie, surf, NULL, NULL);
        SMPEG_move (movie, x, y);
        Py_END_ALLOW_THREADS;
    }
    else
    {
        Py_BEGIN_ALLOW_THREADS;
        SMPEG_enablevideo (movie, 0);
        Py_END_ALLOW_THREADS;
        if (surfobj != Py_None)
            return RAISE (PyExc_TypeError, "destination must be a Surface");
    }

    Py_RETURN_NONE;
}
Ejemplo n.º 30
0
static PyObject *py_normalize_string_latin(PyObject *self, PyObject *args) 
{
    PyObject *arg1;
    uint64_t options;
    if (!PyArg_ParseTuple(args, "OK:normalize", &arg1, &options)) {
        return 0;
    }

    PyObject *unistr = PyUnicode_FromObject(arg1);
    if (unistr == NULL) {
        PyErr_SetString(PyExc_TypeError,
                        "Parameter could not be converted to unicode in scanner");
        return 0;
    }

    #ifdef IS_PY3K
        // Python 3 encoding, supported by Python 3.3+

        char *input = PyUnicode_AsUTF8(unistr);

    #else
        // Python 2 encoding

        PyObject *str = PyUnicode_AsEncodedString(unistr, "utf-8", "strict");
        if (str == NULL) {
            PyErr_SetString(PyExc_TypeError,
                            "Parameter could not be utf-8 encoded");
            goto error_decref_unistr;
        }

        char *input = PyBytes_AsString(str);

    #endif

    if (input == NULL) {
        goto error_decref_str;
    }

    char *normalized = normalize_string_latin(input, strlen(input), options);

    PyObject *result = PyUnicode_DecodeUTF8((const char *)normalized, strlen(normalized), "strict");
    free(normalized);
    if (result == NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "Result could not be utf-8 decoded");
        goto error_decref_str;
    }

    #ifndef IS_PY3K
    Py_XDECREF(str);
    #endif
    Py_XDECREF(unistr);

    return result;

error_decref_str:
#ifndef IS_PY3K
    Py_XDECREF(str);
#endif
error_decref_unistr:
    Py_XDECREF(unistr);
    return 0;
}