Esempio n. 1
0
static int
LerpFunc_init( py_obj_LerpFunc *self, PyObject *args, PyObject *kwds ) {
    static char *kwlist[] = { "start", "end", "length", NULL };
    PyObject *start_obj, *end_obj;

    if( !PyArg_ParseTupleAndKeywords( args, kwds, "OOd", kwlist, &start_obj, &end_obj, &self->length ) )
        return -1;

    if( self->length <= 0.0f ) {
        PyErr_SetString( PyExc_Exception, "length must be greater than 1." );
        return -1;
    }

    start_obj = PySequence_Fast( start_obj, "Expected a tuple or list for start." );

    if( !start_obj )
        return -1;

    float *a = &self->start.min.x;

    for( Py_ssize_t i = 0; i < 4; i++ ) {
        if( i < PySequence_Fast_GET_SIZE( start_obj ) )
            a[i] = PyFloat_AsDouble( PySequence_Fast_GET_ITEM( start_obj, i ) );
        else
            a[i] = 0.0f;
    }

    Py_DECREF( start_obj );

    end_obj = PySequence_Fast( end_obj, "Expected a tuple or list for end." );

    if( !end_obj )
        return -1;

    a = &self->end.min.x;

    for( Py_ssize_t i = 0; i < 4; i++ ) {
        if( i < PySequence_Fast_GET_SIZE( end_obj ) )
            a[i] = PyFloat_AsDouble( PySequence_Fast_GET_ITEM( end_obj, i ) );
        else
            a[i] = 0.0f;
    }

    Py_DECREF( end_obj );

    return 0;
}
static PyObject* information(PyObject* self, PyObject* args)
{
  int i,len;
  double tmp=0, n1=0, n2=0;
  PyObject* obj1;
  PyObject* obj2;
  PyObject* seq1;
  PyObject* seq2;
  PyObject* item;

  if (!PyArg_ParseTuple(args, "OO", &obj1, &obj2))
    return NULL;

  seq1 = PySequence_Fast(obj1, "expected a sequence");
  seq2 = PySequence_Fast(obj2, "expected a sequence");
  len = PySequence_Size(obj1);

  double a1[len];
  double a2[len];

  for (i = 0; i < len; i++) {
    item = PyList_GET_ITEM(seq1, i);
    if (PyFloat_Check(item)){
      tmp = PyFloat_AsDouble(item);
    }
    else if (PyInt_Check(item)){
      tmp = (double) PyInt_AsLong(item);
    }
    a1[i]=tmp;
    n1+=tmp;

    item = PyList_GET_ITEM(seq2, i);
    if (PyFloat_Check(item)){
      tmp = PyFloat_AsDouble(item);
    }
    else if (PyInt_Check(item)){
      tmp = (double) PyInt_AsLong(item);
    }
    a2[i]=tmp;
    n2+=tmp;
  }

  Py_CLEAR(seq1);
  Py_CLEAR(seq2);

  return Py_BuildValue("d",  _information(a1,a2,n1,n2,len));
}
Esempio n. 3
0
/* on error, -1 is returned and no allocation is made */
int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
{
	int size;

#if 1 /* approx 6x speedup for mathutils types */

	if ((size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
	    (size = EulerObject_Check(value)      ? 3 : 0) ||
	    (size = QuaternionObject_Check(value) ? 4 : 0) ||
	    (size = ColorObject_Check(value)      ? 3 : 0))
	{
		if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
			return -1;
		}

		if (size < array_min) {
			PyErr_Format(PyExc_ValueError,
			             "%.200s: sequence size is %d, expected > %d",
			             error_prefix, size, array_min);
			return -1;
		}
		
		*array = PyMem_Malloc(size * sizeof(float));
		memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
		return size;
	}
	else
#endif
	{
		PyObject *value_fast = NULL;
		// *array = NULL;
		int ret;

		/* non list/tuple cases */
		if (!(value_fast = PySequence_Fast(value, error_prefix))) {
			/* PySequence_Fast sets the error */
			return -1;
		}

		size = PySequence_Fast_GET_SIZE(value_fast);

		if (size < array_min) {
			PyErr_Format(PyExc_ValueError,
			             "%.200s: sequence size is %d, expected > %d",
			             error_prefix, size, array_min);
			return -1;
		}

		*array = PyMem_Malloc(size * sizeof(float));

		ret = mathutils_array_parse_fast(*array, size, value_fast, error_prefix);

		if (ret == -1) {
			PyMem_Free(*array);
		}

		return ret;
	}
}
Esempio n. 4
0
static PyObject *
attr_dir_merge_seq2(PyObject *_self, PyObject *seq2)
{
	PyObject *iter, *elem;
	Py_ssize_t i;		/* index into seq2 of current element */
	PyObject *fast;		/* item as a 2-tuple or 2-list */

	iter = PyObject_GetIter(seq2);
	if (!iter)
		return NULL;

	i = 0;
	while ( (elem = PyIter_Next(iter)) ) {
		PyObject *key, *value;
		Py_ssize_t n;
		int status;

		/* Convert item to sequence, and verify length 2. */
		fast = PySequence_Fast(elem, "");
		if (!fast) {
			if (PyErr_ExceptionMatches(PyExc_TypeError))
				PyErr_Format(PyExc_TypeError,
					     "cannot convert attribute update"
					     " sequence element #%zd"
					     " to a sequence", i);
			goto err;
		}
		n = PySequence_Fast_GET_SIZE(fast);
		if (n != 2) {
			PyErr_Format(PyExc_ValueError,
				     "attribute update sequence element #%zd "
				     "has length %zd; 2 is required",
				     i, n);
			goto err;
		}

		/* Update/merge with this (key, value) pair. */
		key = PySequence_Fast_GET_ITEM(fast, 0);
		value = PySequence_Fast_GET_ITEM(fast, 1);
		status = attr_dir_ass_subscript(_self, key, value);
		if (status < 0)
			goto err;
		Py_DECREF(fast);
		Py_DECREF(elem);
		++i;
	}
	Py_DECREF(iter);

	return PyErr_Occurred()
		? NULL
		: Py_None;

 err:
	Py_XDECREF(fast);
	Py_DECREF(elem);
	Py_DECREF(iter);
	return NULL;
}
Esempio n. 5
0
File: common.c Progetto: imclab/pyuv
static INLINE int
pyseq2uvbuf(PyObject *seq, Py_buffer **rviews, uv_buf_t **rbufs, int *rbuf_count)
{
    int i, j, buf_count;
    uv_buf_t *uv_bufs = NULL;
    Py_buffer *views = NULL;
    PyObject *data_fast = NULL;

    i = 0;
    *rviews = NULL;
    *rbufs = NULL;
    *rbuf_count = 0;

    if ((data_fast = PySequence_Fast(seq, "argument 1 must be an iterable")) == NULL) {
        goto error;
    }

    buf_count = PySequence_Fast_GET_SIZE(data_fast);
    if (buf_count > INT_MAX) {
        PyErr_SetString(PyExc_ValueError, "argument 1 is too long");
        goto error;
    }

    if (buf_count == 0) {
        PyErr_SetString(PyExc_ValueError, "argument 1 is empty");
        goto error;
    }

    uv_bufs = PyMem_Malloc(sizeof *uv_bufs * buf_count);
    views = PyMem_Malloc(sizeof *views * buf_count);
    if (!uv_bufs || !views) {
        PyErr_NoMemory();
        goto error;
    }

    for (i = 0; i < buf_count; i++) {
        if (!PyArg_Parse(PySequence_Fast_GET_ITEM(data_fast, i), PYUV_BYTES"*;argument 1 must be an iterable of buffer-compatible objects", &views[i])) {
            goto error;
        }
        uv_bufs[i].base = views[i].buf;
        uv_bufs[i].len = views[i].len;
    }

    *rviews = views;
    *rbufs = uv_bufs;
    *rbuf_count = buf_count;
    Py_XDECREF(data_fast);
    return 0;

error:
    for (j = 0; j < i; j++) {
        PyBuffer_Release(&views[j]);
    }
    PyMem_Free(views);
    PyMem_Free(uv_bufs);
    Py_XDECREF(data_fast);
    return -1;
}
Esempio n. 6
0
/* read a Python sequence of (i,x,y) sequences
 * return cairo_glyph_t *
 *        num_glyphs
 *        must call PyMem_Free(glyphs) when finished using the glyphs
 */
static cairo_glyph_t *
_PyGlyphs_AsGlyphs (PyObject *py_object, int *num_glyphs)
{
  int length, i;
  cairo_glyph_t *glyphs = NULL, *glyph;
  PyObject *py_glyphs, *py_seq = NULL;

  py_glyphs = PySequence_Fast (py_object, "glyphs must be a sequence");
  if (py_glyphs == NULL)
    return NULL;

  length = PySequence_Fast_GET_SIZE(py_glyphs);
  if (*num_glyphs < 0 || *num_glyphs > length)
    *num_glyphs = length;

  glyphs = PyMem_Malloc (*num_glyphs * sizeof(cairo_glyph_t));
  if (glyphs == NULL) {
    PyErr_NoMemory();
    goto error;
  }
  for (i = 0, glyph = glyphs; i < *num_glyphs; i++, glyph++) {
    PyObject *py_item = PySequence_Fast_GET_ITEM(py_glyphs, i);
    py_seq = PySequence_Fast (py_item, "glyph items must be a sequence");
    if (py_seq == NULL)
      goto error;
    if (PySequence_Fast_GET_SIZE(py_seq) != 3) {
      PyErr_SetString(PyExc_ValueError,
		      "each glyph item must be an (i,x,y) sequence");
      goto error;
    }
    glyph->index = PyLong_AsLong(PySequence_Fast_GET_ITEM(py_seq, 0));
    glyph->x = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(py_seq, 1));
    glyph->y = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(py_seq, 2));
    if (PyErr_Occurred())
      goto error;
    Py_DECREF(py_seq);
  }
  Py_DECREF(py_glyphs);
  return glyphs;
 error:
  Py_DECREF(py_glyphs);
  Py_XDECREF(py_seq);
  PyMem_Free(glyphs);
  return NULL;
}
Esempio n. 7
0
void modena_substitute_model_calculate_maps
(
    modena_substitute_model_t *sm,
    modena_model_t *parent
)
{
    PyObject *pMaps = PyObject_CallMethod
    (
        parent->pModel, "calculate_maps", "(O)", sm->model->pModel
    );
    if(!pMaps){ Modena_PyErr_Print(); }

    PyObject *pMapOutputs = PyTuple_GET_ITEM(pMaps, 0); // Borrowed ref
    if(!pMapOutputs){ Modena_PyErr_Print(); }
    PyObject *pSeq = PySequence_Fast(pMapOutputs, "expected a sequence");
    sm->map_outputs_size = PySequence_Size(pMapOutputs);
    sm->map_outputs = malloc(sm->map_outputs_size*sizeof(double));
    size_t i;
    for(i = 0; i < sm->map_outputs_size; i++)
    {
        sm->map_outputs[i] = PyInt_AsSsize_t(PyList_GET_ITEM(pSeq, i));
        parent->argPos_used[sm->map_outputs[i]] = true;
    }
    sm->map_outputs_size /= 2;
    Py_DECREF(pSeq);
    Py_DECREF(pMapOutputs);
    if(PyErr_Occurred()){ Modena_PyErr_Print(); }

    PyObject *pMapInputs = PyTuple_GET_ITEM(pMaps, 1); // Borrowed ref
    if(!pMapInputs){ Modena_PyErr_Print(); }
    pSeq = PySequence_Fast(pMapInputs, "expected a sequence");
    sm->map_inputs_size = PySequence_Size(pMapInputs);
    sm->map_inputs = malloc(sm->map_inputs_size*sizeof(double));
    for(i = 0; i < sm->map_inputs_size; i++)
    {
        sm->map_inputs[i] = PyInt_AsSsize_t(PyList_GET_ITEM(pSeq, i));
    }
    sm->map_inputs_size /= 2;
    Py_DECREF(pSeq);
    Py_DECREF(pMapInputs);
    if(PyErr_Occurred()){ Modena_PyErr_Print(); }

    Py_DECREF(pMaps);
}
Esempio n. 8
0
static PyObject *
BaseRowProxy_processvalues(PyObject *values, PyObject *processors, int astuple)
{
    Py_ssize_t num_values, num_processors;
    PyObject **valueptr, **funcptr, **resultptr;
    PyObject *func, *result, *processed_value, *values_fastseq;

    num_values = PySequence_Length(values);
    num_processors = PyList_Size(processors);
    if (num_values != num_processors) {
        PyErr_Format(PyExc_RuntimeError,
            "number of values in row (%d) differ from number of column "
            "processors (%d)",
            (int)num_values, (int)num_processors);
        return NULL;
    }

    if (astuple) {
        result = PyTuple_New(num_values);
    } else {
        result = PyList_New(num_values);
    }
    if (result == NULL)
        return NULL;

    values_fastseq = PySequence_Fast(values, "row must be a sequence");
    if (values_fastseq == NULL)
        return NULL;

    valueptr = PySequence_Fast_ITEMS(values_fastseq);
    funcptr = PySequence_Fast_ITEMS(processors);
    resultptr = PySequence_Fast_ITEMS(result);
    while (--num_values >= 0) {
        func = *funcptr;
        if (func != Py_None) {
            processed_value = PyObject_CallFunctionObjArgs(func, *valueptr,
                                                           NULL);
            if (processed_value == NULL) {
                Py_DECREF(values_fastseq);
                Py_DECREF(result);
                return NULL;
            }
            *resultptr = processed_value;
        } else {
            Py_INCREF(*valueptr);
            *resultptr = *valueptr;
        }
        valueptr++;
        funcptr++;
        resultptr++;
    }
    Py_DECREF(values_fastseq);
    return result;
}
Esempio n. 9
0
/*	Update LDAPEntry form sequence. Based on the PyDict_MergeFromSeq2 function. */
int
LDAPEntry_UpdateFromSeq2(LDAPEntry *self, PyObject *seq2) {
    PyObject *iter;     /* iter(seq) */
    Py_ssize_t i = 0;   /* index into seq2 of current element */
    PyObject *item;     /* seq[i] */
    PyObject *fast;     /* item as a 2-tuple or 2-list */

    iter = PyObject_GetIter(seq2);
    if (iter == NULL) return -1;

    for (item = PyIter_Next(iter); item != NULL; item = PyIter_Next(iter)) {
        PyObject *key, *value;
        Py_ssize_t n;

        fast = NULL;
        if (PyErr_Occurred()) goto Fail;

        /* Convert item to sequence, and verify length 2. */
        fast = PySequence_Fast(item, "");
        if (fast == NULL) {
            if (PyErr_ExceptionMatches(PyExc_TypeError))
                PyErr_Format(PyExc_TypeError,
                    "cannot convert LDAPEntry update "
                    "sequence element #%zd to a sequence",
                    i);
            goto Fail;
        }
        n = PySequence_Fast_GET_SIZE(fast);
        if (n != 2) {
            PyErr_Format(PyExc_ValueError,
                         "LDAPEntry update sequence element #%zd "
                         "has length %zd; 2 is required",
                         i, n);
            goto Fail;
        }

        /* Update/merge with this (key, value) pair. */
        key = PySequence_Fast_GET_ITEM(fast, 0);
        value = PySequence_Fast_GET_ITEM(fast, 1);
		int status = LDAPEntry_SetItem(self, key, value);
		if (status < 0) goto Fail;
        Py_DECREF(fast);
        Py_DECREF(item);
    }
    i = 0;
    goto Return;
Fail:
    Py_XDECREF(item);
    Py_XDECREF(fast);
    i = -1;
Return:
    Py_DECREF(iter);
    return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
}
Esempio n. 10
0
int
set_pvcards(
    /*@propname@*/ const char* propname,
    PyObject* value,
    struct pvcard** pv,
    int *npv,
    int *npvmax) {

  PyObject* fastseq = NULL;
  struct pvcard* newmem = NULL;
  Py_ssize_t size;
  int ret = -1;
  int i;

  fastseq = PySequence_Fast(value, "Expected sequence type");
  if (!fastseq)
    goto done;

  size = PySequence_Fast_GET_SIZE(value);
  newmem = malloc(sizeof(struct pvcard) * size);

  /* Raise exception if size is nonzero but newmem
   * could not be allocated. */
  if (size && !newmem) {
    PyErr_SetString(PyExc_MemoryError, "Could not allocate memory.");
    return -1;
  }

  for (i = 0; i < size; ++i)
  {
    if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(value, i), "iid",
        &newmem[i].i, &newmem[i].m, &newmem[i].value))
    {
      goto done;
    }
  }

  if (size <= (Py_ssize_t)*npvmax) {
    memcpy(*pv, newmem, sizeof(struct pvcard) * size);
  } else { /* (size > (Py_ssize_t)*npvmax) */
    free(*pv);
    *npv = (int)size;
    *pv = newmem;
    newmem = NULL;
  }
  *npv = (int)size;

  ret = 0;
done:
  Py_XDECREF(fastseq);
  free(newmem);
  return ret;
}
Esempio n. 11
0
/*
 This symbol filters its children through a python function...  where anything is possible.

 functions are generated differently than other symbols:
 - each arg is generated into the output, but the start/end of each arg is recorded for later
 - after references (@symbols) are resolved, then all the functions can be called
 - function output replaces the args in the output (may be bigger or smaller than arg length)
 - function args may contain other function calls, so when function return replaces it's args,
   need to check if this falls within the range of another function arg, and if so repair the range
 */
static int
_generate_function(PyObject *s, void *g)
{
    PyObject *res, *l;
    int status, i, func_cookie, has_ref, defer_depth;
    int *args, nargs;

    // generate arg values
    l = PySequence_Fast(SYMOBJ(s)->data.func.args, "Error enumerating function args");
    if (!l)
        return -1;
    nargs = PySequence_Fast_GET_SIZE(l);
    args = (int *)malloc(sizeof(int) * (nargs + 1));
    if (!args) {
        Py_DECREF(l);
        PyErr_NoMemory();
        return -1;
    }
    args[0] = gen_state_tell(g);
    func_cookie = gen_state_enter_function(g);
    defer_depth = ((gen_state_t *)g)->nfuncs;
    for (i = 0; i < PySequence_Fast_GET_SIZE(l); i++) {
        status = _generate(SYMOBJ(PySequence_Fast_GET_ITEM(l, i)), g);
        if (status) {
            Py_DECREF(l);
            free(args);
            return -1;
        }
        args[i+1] = gen_state_tell(g); // mark end of this arg
    }
    Py_DECREF(l);
    has_ref = gen_state_leave_function(g, func_cookie);
    if (has_ref) {
        // function call must be deferred until after references are generated
        return gen_state_defer_function(g, s, nargs, args, defer_depth);
    } else {
        // call function now
        const char *strres;
        res = call_func_now(s, g, nargs, args);
        gen_state_backtrack(g, args[0]);
        free(args);
        if (!res)
            return -1;
        strres = PyBytes_AsString(res);
        if (!strres) {
            Py_DECREF(res);
            return -1;
        }
        status = gen_state_write((gen_state_t *)g, strres, PyBytes_GET_SIZE(res));
        Py_DECREF(res);
        return status;
    }
}
Esempio n. 12
0
PyObjectHandle LuaToPythonConverter::convertToFastSequence(lua_State* L,
                                                           int index) {
  fixIndex(L, index);

  if (auto ref = getOpaqueRef(L, index)) {
    // Must convert to a Python list or tuple
    PyObjectHandle seq(PySequence_Fast(ref->obj.get(), ""));
    checkPythonError(seq, L, "cannot convert to fast sequence");
    return seq;
  }

  return convertTupleFromTable(L, index, false);
}
Esempio n. 13
0
PyObject *
psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
    // Set process CPU affinity.
    // Reference:
    // http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
    long pid;
    int i;
    int seq_len;
    int ret;
    cpuset_t cpu_set;
    PyObject *py_cpu_set;
    PyObject *py_cpu_seq = NULL;

    if (!PyArg_ParseTuple(args, "lO", &pid, &py_cpu_set))
        return NULL;

    py_cpu_seq = PySequence_Fast(py_cpu_set, "expected a sequence or integer");
    if (!py_cpu_seq)
        return NULL;
    seq_len = PySequence_Fast_GET_SIZE(py_cpu_seq);

    // calculate the mask
    CPU_ZERO(&cpu_set);
    for (i = 0; i < seq_len; i++) {
        PyObject *item = PySequence_Fast_GET_ITEM(py_cpu_seq, i);
#if PY_MAJOR_VERSION >= 3
        long value = PyLong_AsLong(item);
#else
        long value = PyInt_AsLong(item);
#endif
        if (value == -1 && PyErr_Occurred())
            goto error;
        CPU_SET(value, &cpu_set);
    }

    // set affinity
    ret = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
                             sizeof(cpu_set), &cpu_set);
    if (ret != 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    Py_DECREF(py_cpu_seq);
    Py_RETURN_NONE;

error:
    if (py_cpu_seq != NULL)
        Py_DECREF(py_cpu_seq);
    return NULL;
}
Esempio n. 14
0
static int mathutils_array_parse_fast(float *array,
                                      int array_min, int array_max,
                                      PyObject *value, const char *error_prefix)
{
	PyObject *value_fast= NULL;
	PyObject *item;

	int i, size;

	/* non list/tuple cases */
	if (!(value_fast=PySequence_Fast(value, error_prefix))) {
		/* PySequence_Fast sets the error */
		return -1;
	}

	size= PySequence_Fast_GET_SIZE(value_fast);

	if (size > array_max || size < array_min) {
		if (array_max == array_min)	{
			PyErr_Format(PyExc_ValueError,
			             "%.200s: sequence size is %d, expected %d",
			             error_prefix, size, array_max);
		}
		else {
			PyErr_Format(PyExc_ValueError,
			             "%.200s: sequence size is %d, expected [%d - %d]",
			             error_prefix, size, array_min, array_max);
		}
		Py_DECREF(value_fast);
		return -1;
	}

	i= size;
	do {
		i--;
		if ( ((array[i]= PyFloat_AsDouble((item= PySequence_Fast_GET_ITEM(value_fast, i)))) == -1.0f) &&
		     PyErr_Occurred())
		{
			PyErr_Format(PyExc_TypeError,
			             "%.200s: sequence index %d expected a number, "
			             "found '%.200s' type, ",
			             error_prefix, i, Py_TYPE(item)->tp_name);
			Py_DECREF(value_fast);
			return -1;
		}
	} while (i);

	Py_XDECREF(value_fast);
	return size;
}
Esempio n. 15
0
    static bool is_convertible(PyObject *ob, bool raise_exception) {
        if (PySequence_Check(ob)) {
            pyref seq = PySequence_Fast(ob, "expected a sequence");
            // Sizes must match! Could we relax this condition to '<'?
            if (PySequence_Fast_GET_SIZE((PyObject *)seq) != std::tuple_size<tuple_t>::value) goto _false;
            if (!is_convertible_impl<0,Types...>((PyObject *)seq, raise_exception)) goto _false;
            return true;
        }
_false:
        if (raise_exception) {
            PyErr_SetString(PyExc_TypeError, "Cannot convert to std::tuple");
        }
        return false;
    }
Esempio n. 16
0
static PlanarBBoxObject *
BBox_new_from_shapes(PyTypeObject *type, PyObject *shapes) 
{
    PlanarBBoxObject *result, *bbox = NULL;
    Py_ssize_t size;
    PyObject **item;

    assert(PyType_IsSubtype(type, &PlanarBBoxType));
    result = (PlanarBBoxObject *)type->tp_alloc(type, 0);
    shapes = PySequence_Fast(shapes, "expected iterable of bounded shapes");
    if (result == NULL || shapes == NULL) {
        goto error;
    }
    size = PySequence_Fast_GET_SIZE(shapes);
    if (size < 1) {
        PyErr_SetString(PyExc_ValueError,
            "Cannot construct a BoundingBox without at least one shape");
        goto error;
    }
    result->min.x = result->min.y = DBL_MAX;
    result->max.x = result->max.y = -DBL_MAX;
    item = PySequence_Fast_ITEMS(shapes);
    while (size--) {
        bbox = get_bounding_box(*(item++));
        if (bbox == NULL) {
            goto error;
        }
        if (bbox->min.x < result->min.x) {
            result->min.x = bbox->min.x;
        }
        if (bbox->min.y < result->min.y) {
            result->min.y = bbox->min.y;
        }
        if (bbox->max.x > result->max.x) {
            result->max.x = bbox->max.x;
        }
        if (bbox->max.y > result->max.y) {
            result->max.y = bbox->max.y;
        }
        Py_CLEAR(bbox);
    }
    Py_DECREF(shapes);
    return result;
    
error:
    Py_XDECREF(bbox);
    Py_XDECREF(result);
    Py_XDECREF(shapes);
    return NULL;
}
Esempio n. 17
0
void modena_model_read_substituteModels(modena_model_t *m)
{
    PyObject *pSubstituteModels = PyObject_GetAttrString
    (
        m->pModel, "substituteModels"
    );
    if(!pSubstituteModels){ Modena_PyErr_Print(); }

    PyObject *pSeq = PySequence_Fast
    (
        pSubstituteModels, "expected a sequence"
    );
    m->substituteModels_size = PySequence_Size(pSubstituteModels);
    m->substituteModels =
        malloc(m->substituteModels_size*sizeof(modena_substitute_model_t));
    size_t i;
    for(i = 0; i < m->substituteModels_size; i++)
    {
        PyObject *args = PyTuple_New(0);
        PyObject *kw = Py_BuildValue
        (
            "{s:O}", "model", PyList_GET_ITEM(pSeq, i)
        );

        m->substituteModels[i].model = (modena_model_t *) PyObject_Call
        (
            (PyObject *) &modena_model_tType, args, kw
        );
        Py_DECREF(args);
        Py_DECREF(kw);
        if(!m->substituteModels[i].model){ Modena_PyErr_Print(); }

        m->substituteModels[i].inputs = modena_inputs_new
        (
            m->substituteModels[i].model
        );

        m->substituteModels[i].outputs = modena_outputs_new
        (
            m->substituteModels[i].model
        );

        modena_substitute_model_calculate_maps(&m->substituteModels[i], m);
    }

    Py_DECREF(pSeq);
    Py_DECREF(pSubstituteModels);
    if(PyErr_Occurred()){ Modena_PyErr_Print(); }
}
Esempio n. 18
0
static PyObject *trivium_rounds(PyObject *self, PyObject *args) {
	u8 iv[10], key[10];
	u16 num_rounds;
	PyObject *iv_seq, *key_seq;

	if (!PyArg_ParseTuple(args, "OOH", &iv_seq, &key_seq, &num_rounds))
		return NULL;

	iv_seq = PySequence_Fast(iv_seq, "IV must be iterable.");
	if (!iv_seq)
		return NULL;
 	if (80 != PySequence_Fast_GET_SIZE(iv_seq)) {
		Py_DECREF(iv_seq);
		return NULL;
	}
	if (seq2array(iv_seq, iv)) {
		Py_DECREF(iv_seq);
		return NULL;
	}
	Py_DECREF(iv_seq);

	key_seq = PySequence_Fast(key_seq, "KEY must be iterable.");
	if (!key_seq)
		return NULL;
	if (80 != PySequence_Fast_GET_SIZE(key_seq)) {
		Py_DECREF(key_seq);
		return NULL;
	}
	if (seq2array(key_seq, key)) {
		Py_DECREF(key_seq);
		return NULL;
	}
	Py_DECREF(key_seq);

	return Py_BuildValue("i", rounds(iv, key, num_rounds));
}
Esempio n. 19
0
static PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw)
{
	StructRNA *srna;

	BPY_PROPDEF_HEAD(EnumProperty)
	
	if(srna) {
		static const char *kwlist[] = {"attr", "items", "name", "description", "default", "options", NULL};
		const char *id=NULL, *name="", *description="";
		PyObject *def= NULL;
		int id_len;
		int defvalue=0;
		PyObject *items, *items_fast;
		EnumPropertyItem *eitems;
		PropertyRNA *prop;
		PyObject *pyopts= NULL;
		int opts=0;

		if (!PyArg_ParseTupleAndKeywords(args, kw, "s#O|ssOO!:EnumProperty", (char **)kwlist, &id, &id_len, &items, &name, &description, &def, &PySet_Type, &pyopts))
			return NULL;

		BPY_PROPDEF_CHECK(EnumProperty, property_flag_enum_items)

		if(!(items_fast= PySequence_Fast(items, "EnumProperty(...): expected a sequence of tuples for the enum items"))) {
			return NULL;
		}

		eitems= enum_items_from_py(items_fast, def, &defvalue, (opts & PROP_ENUM_FLAG)!=0);

		Py_DECREF(items_fast);

		if(!eitems)
			return NULL;

		if(opts & PROP_ENUM_FLAG)	prop= RNA_def_enum_flag(srna, id, eitems, defvalue, name, description);
		else						prop= RNA_def_enum(srna, id, eitems, defvalue, name, description);

		if(pyopts) {
			if(opts & PROP_HIDDEN) RNA_def_property_flag(prop, PROP_HIDDEN);
			if((opts & PROP_ANIMATABLE)==0) RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
		}
		RNA_def_property_duplicate_pointers(srna, prop);
		MEM_freeN(eitems);
	}
	Py_RETURN_NONE;
}
Esempio n. 20
0
//note that the returned double should be freed
double* PyObj2DoublePtr(PyObject *dSeq, int seqlen)
{
    //PyObject* dSeq;
    double *dC;
    //int seqlen;
    int i;
    
    dSeq = PySequence_Fast(dSeq, "argument must be iterable");
    if(!dSeq)
        return NULL;
 
    // prepare data as an array of doubles 
    //*seqlen = PySequence_Fast_GET_SIZE(seq);
    dC = (double*)malloc(seqlen*sizeof(double));
    if(!dC) 
    {
        Py_DECREF(dSeq);
        //return PyErr_NoMemory( );
        return NULL;
    }

    for(i=0; i < seqlen; i++) 
    {
        PyObject *fitem;
        PyObject *item = PySequence_Fast_GET_ITEM(dSeq, i);
        if(!item) 
        {
            Py_DECREF(dSeq);
            free(dC);
            return NULL;
        }
        fitem = PyNumber_Float(item);
        if(!fitem) 
        {
            Py_DECREF(dSeq);
            free(dC);
            PyErr_SetString(PyExc_TypeError, "all items must be numbers");
            return NULL;
        }
        dC[i] = PyFloat_AS_DOUBLE(fitem);
        Py_DECREF(fitem);
    }

    Py_DECREF(dSeq);
    return dC;
}
SAMPLE      read_struct_examples(char *file, STRUCT_LEARN_PARM *sparm)
{
  /* Reads struct examples and returns them in sample. The number of
     examples must be written into sample.n */
  SAMPLE   sample;  /* sample */
  EXAMPLE  *examples;
  PyObject *pFunc,*pValue,*pSeq;
  int i;

  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_READ_EXAMPLES);
  pValue = PyObject_CallFunction(pFunc, "sN", file, Sparm_FromSparm(sparm));

  PY_RUNCHECK;
  
  // Convert this into a sequence.
  pSeq = PySequence_Fast(pValue, "examples not a sequence");
  Py_DECREF(pValue);
  if (pSeq == NULL) {
    PyErr_Print();
    Py_Exit(1);
  }

  // Read the examples from the sequence.
  sample.n = PySequence_Size(pSeq);
  examples=(EXAMPLE *)my_malloc(sizeof(EXAMPLE)*sample.n);
  for (i=0; i<sample.n; ++i) {
    PyObject *pExample = PySequence_Fast_GET_ITEM(pSeq, i);
    if (!pExample || !PySequence_Check(pExample) ||
        PySequence_Size(pExample)<2){
      fprintf(stderr, "%s's item %d is not a sequence element of "
              "at least two items!\n", PYTHON_READ_EXAMPLES, i);
      free(examples);
      Py_DECREF(pSeq);
      Py_Exit(1);
    }
    examples[i].x.py_x = PySequence_GetItem(pExample, 0);
    examples[i].y.py_y = PySequence_GetItem(pExample, 1);
    Py_DECREF(pExample);
  }
  Py_DECREF(pSeq);

  /* fill in your code here */
  sample.examples=examples;
  return(sample);
}
Esempio n. 22
0
bool sequenceToArgcArgv(PyObject* argList, int* argc, char*** argv, const char* defaultAppName)
{
    if (!PySequence_Check(argList))
        return false;

    if (!defaultAppName)
        defaultAppName = "PySideApplication";

    // Check all items
    Shiboken::AutoDecRef args(PySequence_Fast(argList, 0));
    int numArgs = PySequence_Fast_GET_SIZE(argList);
    for (int i = 0; i < numArgs; ++i) {
        PyObject* item = PySequence_Fast_GET_ITEM(args.object(), i);
        if (!PyString_Check(item) && !PyUnicode_Check(item))
            return false;
    }

    bool hasEmptyArgList = numArgs == 0;
    if (hasEmptyArgList)
        numArgs = 1;

    *argc = numArgs;
    *argv = new char*[*argc];

    if (hasEmptyArgList) {
        // Try to get the script name
        PyObject* globals = PyEval_GetGlobals();
        PyObject* appName = PyDict_GetItemString(globals, "__file__");
        (*argv)[0] = strdup(appName ? PyString_AS_STRING(appName) : defaultAppName);
    } else {
        for (int i = 0; i < numArgs; ++i) {
            PyObject* item = PySequence_Fast_GET_ITEM(args.object(), i);
            char* string;
            if (PyUnicode_Check(item)) {
                Shiboken::AutoDecRef utf8(PyUnicode_AsUTF8String(item));
                string = strdup(PyString_AS_STRING(utf8.object()));
            } else {
                string = strdup(PyString_AS_STRING(item));
            }
            (*argv)[i] = string;
        }
    }

    return true;
}
Esempio n. 23
0
static polypaths_planar_overridePolygonObject *
Poly_create_new_from_points(PyTypeObject *type, PyObject *points)
{
	polypaths_planar_overridePolygonObject *poly;
    Py_ssize_t size;
    Py_ssize_t i;

	if (polypaths_planar_overridePolygon_CheckExact(points)) {
		poly = (polypaths_planar_overridePolygonObject *)Poly_copy(
			(polypaths_planar_overridePolygonObject *)points, NULL);
	} else if (polypaths_planar_overrideSeq2_Check(points)) {
		/* Copy existing Seq2 (optimized) */
		poly = Poly_new(type, Py_SIZE(points));
		if (poly == NULL) {
			return NULL;
		}
		memcpy(poly->vert, ((polypaths_planar_overrideSeq2Object *)points)->vec, 
			sizeof(polypaths_planar_override_vec2_t) * Py_SIZE(points));
    } else {
		/* Generic iterable of points */
		points = PySequence_Fast(points, "expected iterable of Vec2 objects");
		if (points == NULL) {
			return NULL;
		}
		size = PySequence_Fast_GET_SIZE(points);
		poly = Poly_new(type, size);
		if (poly == NULL) {
			Py_DECREF(points);
			return NULL;
		}
		for (i = 0; i < size; ++i) {
			if (!polypaths_planar_overrideVec2_Parse(PySequence_Fast_GET_ITEM(points, i), 
				&poly->vert[i].x, &poly->vert[i].y)) {
				PyErr_SetString(PyExc_TypeError,
					"expected iterable of Vec2 objects");
				Py_DECREF(poly);
				Py_DECREF(points);
				return NULL;
			}
		}
		Py_DECREF(points);
    }
    return poly;
}
Esempio n. 24
0
static int
Matcher_init(Matcher *self, PyObject *args, PyObject *kwds)
{
    PyObject *items = NULL, *p = NULL, *py_items = NULL, *level1 = NULL, *level2 = NULL, *level3 = NULL, *collator = NULL;
    int32_t i = 0;
    UErrorCode status = U_ZERO_ERROR;
    UCollator *col = NULL;

    if (!PyArg_ParseTuple(args, "OOOOO", &items, &collator, &level1, &level2, &level3)) return -1;
    
    // Clone the passed in collator (cloning is needed as collators are not thread safe)
    if (!PyCapsule_CheckExact(collator)) { PyErr_SetString(PyExc_TypeError, "Collator must be a capsule"); return -1; }
    col = (UCollator*)PyCapsule_GetPointer(collator, NULL);
    if (col == NULL) return -1;
    self->collator = ucol_safeClone(col, NULL, NULL, &status);
    col = NULL;
    if (U_FAILURE(status)) { self->collator = NULL; PyErr_SetString(PyExc_ValueError, u_errorName(status)); return -1; }

    py_items = PySequence_Fast(items,  "Must pass in two sequence objects");
    if (py_items == NULL) goto end;
    self->item_count = (uint32_t)PySequence_Size(items);

    self->items = (UChar**)calloc(self->item_count, sizeof(UChar*));
    self->item_lengths = (int32_t*)calloc(self->item_count, sizeof(uint32_t));
    self->level1 = python_to_icu(level1, NULL);
    self->level2 = python_to_icu(level2, NULL);
    self->level3 = python_to_icu(level3, NULL);

    if (self->items == NULL || self->item_lengths == NULL ) { PyErr_NoMemory(); goto end; }
    if (self->level1 == NULL || self->level2 == NULL || self->level3 == NULL) goto end;

    for (i = 0; i < (int32_t)self->item_count; i++) {
        p = PySequence_Fast_GET_ITEM(py_items, i);
        self->items[i] = python_to_icu(p, self->item_lengths + i);
        if (self->items[i] == NULL) { PyErr_NoMemory(); goto end; }
    }

end:
    Py_XDECREF(py_items);
    if (PyErr_Occurred()) { free_matcher(self); }
    return (PyErr_Occurred()) ? -1 : 0;
}
Esempio n. 25
0
static PyObject *normalize(Normalizer *self, PyObject *args)
{
    int j;
    PyObject * data=NULL ;

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

    if (PyList_Check(data)) {
        PyObject *list;

        list = PyList_New(0);

        data = PySequence_Fast(data, "object must be sequence"); 

        for (j=0; j<PyList_Size(data); j++) {
            PyObject *word=NULL,*item=NULL;

            item = PySequence_Fast_GET_ITEM(data,j);
            word = NormalizeWord(self, item);
            PyList_Append(list, word);
        }

        return list;

    } else if (PyUnicode_Check(data) || PyString_Check(data) ) {

        PyObject *word=NULL;

        if (! (word = NormalizeWord(self,data)))
            return NULL;

        return (PyObject *) word;

    } else {
        PyErr_SetString(PyExc_TypeError,"argument must be unicode or string");
        return NULL;
    }

    return data;
}
Esempio n. 26
0
/* Iterate over the names in the type's _anonymous_ attribute, if present,
 */
static int
MakeAnonFields(PyObject *type)
{
	PyObject *anon;
	PyObject *anon_names;
	Py_ssize_t i;

	anon = PyObject_GetAttrString(type, "_anonymous_");
	if (anon == NULL) {
		PyErr_Clear();
		return 0;
	}
	anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
	Py_DECREF(anon);
	if (anon_names == NULL)
		return -1;

	for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
		PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
		CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
		if (descr == NULL) {
			Py_DECREF(anon_names);
			return -1;
		}
		assert(Py_TYPE(descr) == &CField_Type);
		descr->anonymous = 1;

		/* descr is in the field descriptor. */
		if (-1 == MakeFields(type, (CFieldObject *)descr,
				     ((CFieldObject *)descr)->index,
				     ((CFieldObject *)descr)->offset)) {
			Py_DECREF(descr);
			Py_DECREF(anon_names);
			return -1;
		}
		Py_DECREF(descr);
	}

	Py_DECREF(anon_names);
	return 0;
}
Esempio n. 27
0
PyObject *SibPair_Cons(PyObject *members, int recursive) {

  // checked

  PyObject *seq = PySequence_Fast(members,
				  "cons members object must be a sequence");
  if(! seq) {
    return NULL;
  }

  int count = PySequence_Fast_GET_SIZE(seq);
  if (! count) {
    Py_DECREF(seq);
    Py_INCREF(SibNil);
    return SibNil;
  }

  PyObject *result = SibPair_New(PySequence_Fast_GET_ITEM(seq, 0), SibNil);

  if (count == 1) {
    if (recursive) {
      SibPair_SETCDR(result, result);
    }

  } else {
    PyObject *work = recursive? result: PySequence_Fast_GET_ITEM(seq, --count);
    Py_INCREF(work);

    while (--count) {
      PyObject *tmp = SibPair_New(PySequence_Fast_GET_ITEM(seq, count), work);
      Py_DECREF(work);
      work = tmp;
    }

    SibPair_SETCDR(result, work);
    Py_DECREF(work);
  }

  Py_DECREF(seq);
  return result;
}
Esempio n. 28
0
	CString GetPyExceptionStr() {
			PyObject* ptype;
			PyObject* pvalue;
			PyObject* ptraceback;
			PyErr_Fetch(&ptype, &pvalue, &ptraceback);
			CString result;
			if (!pvalue) {
				Py_INCREF(Py_None);
				pvalue = Py_None;
			}
			if (!ptraceback) {
				Py_INCREF(Py_None);
				ptraceback = Py_None;
			}
			PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
			PyObject* strlist = PyObject_CallFunctionObjArgs(m_PyFormatException, ptype, pvalue, ptraceback, NULL);
			Py_CLEAR(ptype);
			Py_CLEAR(pvalue);
			Py_CLEAR(ptraceback);
			if (!strlist) {
				return "Couldn't get exact error message";
			}

			if (PySequence_Check(strlist)) {
				PyObject* strlist_fast = PySequence_Fast(strlist, "Shouldn't happen (1)");
				PyObject** items = PySequence_Fast_ITEMS(strlist_fast);
				Py_ssize_t L = PySequence_Fast_GET_SIZE(strlist_fast);
				for (Py_ssize_t i = 0; i < L; ++i) {
					PyObject* utf8 = PyUnicode_AsUTF8String(items[i]);
					result += PyBytes_AsString(utf8);
					Py_CLEAR(utf8);
				}
				Py_CLEAR(strlist_fast);
			} else {
				result = "Can't get exact error message";
			}

			Py_CLEAR(strlist);

			return result;
	}
Esempio n. 29
0
/* parse an array of vectors */
int mathutils_array_parse_alloc_v(float **array,
                                  int array_dim,
                                  PyObject *value,
                                  const char *error_prefix)
{
  PyObject *value_fast;
  const int array_dim_flag = array_dim;
  int i, size;

  /* non list/tuple cases */
  if (!(value_fast = PySequence_Fast(value, error_prefix))) {
    /* PySequence_Fast sets the error */
    return -1;
  }

  size = PySequence_Fast_GET_SIZE(value_fast);

  if (size != 0) {
    PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
    float *fp;

    array_dim &= ~MU_ARRAY_FLAGS;

    fp = *array = PyMem_Malloc(size * array_dim * sizeof(float));

    for (i = 0; i < size; i++, fp += array_dim) {
      PyObject *item = value_fast_items[i];

      if (mathutils_array_parse(fp, array_dim, array_dim_flag, item, error_prefix) == -1) {
        PyMem_Free(*array);
        *array = NULL;
        size = -1;
        break;
      }
    }
  }

  Py_DECREF(value_fast);
  return size;
}
Esempio n. 30
0
inline PointVector* PointVector_from_python(PyObject* py) {
  PyObject* seq = PySequence_Fast(py, "Argument must be an iterable of Points");
  if (seq == NULL)
    return 0;
  int size = PySequence_Fast_GET_SIZE(seq);
  PointVector* cpp = new PointVector();
  try {
    cpp->reserve(size);
    for (int i = 0; i < size; ++i) {
      PyObject* point = PySequence_Fast_GET_ITEM(seq, i);
      Point p = coerce_Point(point);
      cpp->push_back(p);
    }
  } catch (std::exception e) {
    delete cpp;
    Py_DECREF(seq);
    PyErr_SetString(PyExc_RuntimeError, e.what());
    return 0;
  }
  Py_DECREF(seq);
  return cpp;
}