_NonPyObjectUniqueSorterIncer(PyObject * fast_seq) 
 {           
     if (fast_seq == Py_None)
         return;
 
     vals.reserve(PySequence_Fast_GET_SIZE(fast_seq));            
     for (size_t i = 0; i < static_cast<size_t>(PySequence_Fast_GET_SIZE(fast_seq)); ++i) {    
         PyObject * const val = PySequence_Fast_GET_ITEM(fast_seq, i);    
         DBG_ASSERT(PyTuple_Check(val));
         DBG_ASSERT(PyTuple_Size(val) == 2);
         PyObject * const key = PyTuple_GET_ITEM(val, 0);
         BANYAN_PYOBJECT_INCREF(key);
         vals.push_back(std::make_pair(
             std::make_pair(                    
                 _KeyFactory<Key_Type>::convert(key), 
                 key),
             PyTuple_GET_ITEM(val, 1)));
     }            
         
     _FirstLT<_FirstLT<std::less<Key_Type> > > lt;            
     std::sort(vals.begin(), vals.end(), lt);
     vals.erase(unique(vals.begin(), vals.end(), not2(lt)), vals.end());
     
     for (size_t i = 0; i < vals.size(); ++i)
         BANYAN_PYOBJECT_INCREF(vals[i].second);            
 }
Example #2
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;
    }
}
Example #3
0
static PyObject *
pycairo_set_dash (PycairoContext *o, PyObject *args) {
  double *dashes, offset = 0;
  int num_dashes, i;
  PyObject *py_dashes;

  if (!PyArg_ParseTuple (args, "O|d:Context.set_dash", &py_dashes, &offset))
    return NULL;

  py_dashes = PySequence_Fast (py_dashes,
			       "first argument must be a sequence");
  if (py_dashes == NULL)
    return NULL;

  num_dashes = PySequence_Fast_GET_SIZE(py_dashes);
  dashes = PyMem_Malloc (num_dashes * sizeof(double));
  if (dashes == NULL) {
    Py_DECREF(py_dashes);
    return PyErr_NoMemory();
  }

  for (i = 0; i < num_dashes; i++) {
    dashes[i] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(py_dashes, i));
    if (PyErr_Occurred()) {
      PyMem_Free (dashes);
      Py_DECREF(py_dashes);
      return NULL;
    }
  }
  cairo_set_dash (o->ctx, dashes, num_dashes, offset);
  PyMem_Free (dashes);
  Py_DECREF(py_dashes);
  RETURN_NULL_IF_CAIRO_CONTEXT_ERROR(o->ctx);
  Py_RETURN_NONE;
}
Example #4
0
static PyObject* PositionWeightMatrix_scoreAll( PositionWeightMatrix* self, PyObject* args )
{
	PyObject* seq = parseTupleToFastSequence( args );
	if( !seq ) return NULL;
	
	double** matrix = self -> matrix;
	int n = self -> n;
	int m = self -> m;
	int len = PySequence_Fast_GET_SIZE( seq );
	//check that length is correct
	if( n > len )
	{
		//TODO raise error
		return NULL;
	}
	
	PyObject** elems = PySequence_Fast_ITEMS( seq );
	
	//create new python list and fill it with the scores at each position
	int end = len - n + 1;
	PyObject* list = PyList_New( end );
	int i;
	for( i = 0 ; i < end ; ++i )
	{
		PyList_SetItem( list, i, PyFloat_FromDouble( scoreFromIndex( matrix, n, m, elems, i ) ) );
	}
	return list;
	
}
Example #5
0
/*
 * Callback function which is exposed as a part of the additional methods which allow
 * a Python plugin to issue a Register Event to register additional events it wants
 * to receive.
 */
static PyObject *PyBareosRegisterEvents(PyObject *self, PyObject *args)
{
   int len, event;
   bpContext *ctx;
   PyObject *pyCtx, *pyEvents, *pySeq, *pyEvent;

   if (!PyArg_ParseTuple(args, "OO:BareosRegisterEvents", &pyCtx, &pyEvents)) {
      return NULL;
   }

   pySeq = PySequence_Fast(pyEvents, "Expected a sequence of events");
   if (!pySeq) {
      return NULL;
   }

   len = PySequence_Fast_GET_SIZE(pySeq);

   ctx = PyGetbpContext(pyCtx);
   for (int i = 0; i < len; i++) {
      pyEvent = PySequence_Fast_GET_ITEM(pySeq, i);
      event = PyInt_AsLong(pyEvent);

      if (event >= bDirEventJobStart && event <= bDirEventGetScratch) {
         Dmsg(ctx, dbglvl, "PyBareosRegisterEvents: registering event %d\n", event);
         bfuncs->registerBareosEvents(ctx, 1, event);
      }
   }

   Py_DECREF(pySeq);

   Py_INCREF(Py_None);
   return Py_None;
}
Example #6
0
static PyObject* pathlist_new(PyTypeObject* pytype, PyObject* args,
			      PyObject* kwds) {
  PyObject* py_arg = 0;
  if (PyArg_ParseTuple(args, "|O", &py_arg) <= 0)
    return 0;
  boost::shared_ptr<PathList> p(new PathList());
  if (py_arg != 0) {
    PyObject* seq = PySequence_Fast(py_arg, "Argument must be a sequence of Path objects.");
    if (seq == 0)
      return 0;
    int size = PySequence_Fast_GET_SIZE(seq);
    for (int i = 0; i < size; ++i) {
      PyObject* py_path = PySequence_Fast_GET_ITEM(seq, i);
      if (!is_PathObject(py_path)) {
	PyErr_SetString(PyExc_TypeError, "Argument must be a sequence of Path objects.");
	Py_DECREF(seq);
	return 0;
      }
      p->push_back(((PathObject*)py_path)->m_x);
    }
  }
  
  PathListObject* so;
  so = (PathListObject*)pytype->tp_alloc(pytype, 0);
  so->m_x = p;
  return (PyObject*)so;
}
Example #7
0
GdkAtom*
pygdk_atom_vector_from_sequence(PyObject *py_targets, gint *n_targets)
{
    gint i;
    GdkAtom *targets;

    if (!(py_targets = PySequence_Fast(py_targets,
                                       "targets must be a sequence")))
        return NULL;

    *n_targets = PySequence_Fast_GET_SIZE(py_targets);
    targets = g_new(GdkAtom, *n_targets);
    for (i = 0; i < *n_targets; i++) {
        PyObject *trgt = PySequence_Fast_GET_ITEM(py_targets, i);
        targets[i] = pygdk_atom_from_pyobject(trgt);
        if (PyErr_Occurred()) {
            PyErr_Clear();
            PyErr_SetString(PyExc_TypeError,
                            "each 'targets' item must be a GdkAtom or string");
            g_free(targets);
            Py_DECREF(py_targets);
            return NULL;
        }
    }
    Py_DECREF(py_targets);
    return targets;
}
Example #8
0
GtkTargetList *
pygtk_target_list_from_sequence(PyObject *py_targets)
{
    gint n_targets, i;
    GtkTargetEntry *targets;
    GtkTargetList *target_list;

    if (!(py_targets = PySequence_Fast(py_targets,
                                       "target list must be a sequence")))
	return NULL;
    n_targets = PySequence_Fast_GET_SIZE(py_targets);
    targets = g_new(GtkTargetEntry, n_targets);
    for (i = 0; i < n_targets; i++) {
        PyObject *item = PySequence_Fast_GET_ITEM(py_targets, i);
        if (!PyArg_ParseTuple(item, "sii", &targets[i].target,
                              &targets[i].flags, &targets[i].info)) {
            PyErr_Clear();
            PyErr_SetString(PyExc_TypeError,
                            "target list items should be of form (string,int,int)");
            g_free(targets);
	    Py_DECREF(py_targets);
            return NULL;
        }
    }
    target_list = gtk_target_list_new(targets, n_targets);
    g_free(targets);
    Py_DECREF(py_targets);
    return target_list;
}
Example #9
0
int py_array_from_obj(PyObject *obj, float *arr) {

   PyObject *seqdata = NULL;
   PyObject *elem;
   int i;

  if (!(seqdata = PySequence_Fast(obj, "Coordinate argument must be a sequence")))
    goto failure;

  if (PySequence_Fast_GET_SIZE(seqdata) != 3) {
    PyErr_SetString(PyExc_ValueError, "Coordinate must have length 3");
    goto failure;
  }

  for (i = 0; i < 3; i++) {
    elem = PySequence_Fast_GET_ITEM(seqdata, i);

    arr[i] = PyFloat_AsDouble(elem);
    if (PyErr_Occurred()) {
      PyErr_SetString(PyExc_ValueError, "Problem unpacking coordinate");
      goto failure;
    }
  }
  return 1;  // successful return

failure:
  Py_XDECREF(seqdata);
  return 0;
}
Example #10
0
/* returns NULL on success, error string on failure */
static int idp_sequence_type(PyObject *seq_fast)
{
    PyObject *item;
    int type = IDP_INT;

    Py_ssize_t i, len = PySequence_Fast_GET_SIZE(seq_fast);
    for (i = 0; i < len; i++) {
        item = PySequence_Fast_GET_ITEM(seq_fast, i);
        if (PyFloat_Check(item)) {
            if (type == IDP_IDPARRAY) { /* mixed dict/int */
                return -1;
            }
            type = IDP_DOUBLE;
        }
        else if (PyLong_Check(item)) {
            if (type == IDP_IDPARRAY) { /* mixed dict/int */
                return -1;
            }
        }
        else if (PyMapping_Check(item)) {
            if (i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
                return -1;
            }
            type = IDP_IDPARRAY;
        }
        else {
            return -1;
        }
    }

    return type;
}
static PyObject *
pycairo_set_dash (PycairoContext *o, PyObject *args)
{
    double *dashes, offset = 0;
    int ndash, i;
    PyObject *py_dashes;

    if (!PyArg_ParseTuple (args, "O|d:Context.set_dash", &py_dashes, &offset))
	return NULL;

    py_dashes = PySequence_Fast (py_dashes,
				 "first argument must be a sequence");
    if (!py_dashes)
	return NULL;

    ndash = PySequence_Fast_GET_SIZE(py_dashes);
    dashes = malloc (ndash * sizeof(double));
    for (i = 0; i < ndash; i++) {
	PyObject *item = PySequence_Fast_GET_ITEM(py_dashes, i);

	dashes[i] = PyFloat_AsDouble(item);
	if (PyErr_Occurred()) {
	    free (dashes);
	    Py_DECREF(py_dashes);
	    return NULL;
	}
    }
    Py_DECREF(py_dashes);

    cairo_set_dash (o->ctx, dashes, ndash, offset);
    free (dashes);
    if (Pycairo_Check_Status (cairo_status (o->ctx)))
	return NULL;
    Py_RETURN_NONE;
}
// set capture size
int ImageViewport_setCaptureSize(PyImage *self, PyObject *value, void *closure)
{
	// check validity of parameter
	if (value == NULL ||
	    !(PyTuple_Check(value) || PyList_Check(value)) ||
	    PySequence_Fast_GET_SIZE(value) != 2 ||
	    !PyLong_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
	    !PyLong_Check(PySequence_Fast_GET_ITEM(value, 1)))
	{
		PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
		return -1;
	}
	// set capture size
	short size[2] = {
	    short(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
	    short(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
	};
	try
	{
		// can throw in case of resize and buffer exports
		getImageViewport(self)->setCaptureSize(size);
	}
	catch (Exception & exp)
	{
		exp.report();
		return -1;
	}
	// success
	return 0;
}
Example #13
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 = NULL;
	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) {
		float *fp;

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

		for (i = 0; i < size; i++, fp += array_dim) {
			PyObject *item = PySequence_Fast_GET_ITEM(value, i);

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

	Py_DECREF(value_fast);
	return size;
}
Example #14
0
int* sequenceToIntArray(PyObject* obj, bool zeroTerminated)
{
    AutoDecRef seq(PySequence_Fast(obj, "Sequence of ints expected"));
    if (seq.isNull())
        return 0;

    Py_ssize_t size = PySequence_Fast_GET_SIZE(seq.object());
    int* array = new int[size + (zeroTerminated ? 1 : 0)];

    for (int i = 0; i < size; i++) {
        PyObject* item = PySequence_Fast_GET_ITEM(seq.object(), i);
        if (!PyInt_Check(item)) {
            PyErr_SetString(PyExc_TypeError, "Sequence of ints expected");
            delete[] array;
            return 0;
        } else {
            array[i] = PyInt_AsLong(item);
        }
    }

    if (zeroTerminated)
        array[size] = 0;

    return array;
}
Example #15
0
inline IntVector* IntVector_from_python(PyObject* py) {
  PyObject* seq = PySequence_Fast(py, "Argument must be a sequence of ints.");
  if (seq == NULL)
    return 0;
  int size = PySequence_Fast_GET_SIZE(seq);
  IntVector* cpp = new IntVector(size);
  try {
    for (int i = 0; i < size; ++i) {
      PyObject* number = PySequence_Fast_GET_ITEM(seq, i);
      if (!PyInt_Check(number)) {
        PyErr_SetString(PyExc_TypeError,
                        "Argument must be a sequence of ints.");
        delete cpp;
        Py_DECREF(seq);
        return 0;
      }
      (*cpp)[i] = (int)PyInt_AsLong(number);
    }
  } catch (std::exception e) {
    delete cpp;
    Py_DECREF(seq);
    PyErr_SetString(PyExc_RuntimeError, e.what());
    return 0;
  }
  Py_DECREF(seq);
  return cpp;
}
Example #16
0
static PyObject*
convert_seq(PyObject *ob, convert_func convert_string)
{
    PyObject *seq = PySequence_Fast(ob, "ob is not a sequence");
    if (seq == NULL) {
        return NULL;
    }

    Py_ssize_t i = 0;
    Py_ssize_t seq_len = PySequence_Fast_GET_SIZE(seq);
    PyObject **items = PySequence_Fast_ITEMS(seq);

    for (i=0; i < seq_len; ++i) {
        PyObject *old_item = items[i];
        PyObject *new_item = convert_nested(old_item, convert_string);
        if (new_item == NULL) {
            Py_DECREF(seq);
            return NULL;
        }
        items[i] = new_item;
        Py_DECREF(old_item);
    }

    return seq;
}
Example #17
0
inline ComplexVector* ComplexVector_from_python(PyObject* py) {
  PyObject* seq = PySequence_Fast(py, "Argument must be a sequence of complex numbers.");
  if (seq == NULL)
    return 0;
  int size = PySequence_Fast_GET_SIZE(seq);
  ComplexVector* cpp = new ComplexVector(size);
  try {
    for (int i = 0; i < size; ++i) {
      PyObject* value = PySequence_Fast_GET_ITEM(seq, i);
      if (!PyComplex_Check(value)) {
        delete cpp;
        Py_DECREF(seq);
        PyErr_SetString(PyExc_TypeError, "Argument must be a sequence of complex numbers.");
        return 0;
      }
      Py_complex temp = PyComplex_AsCComplex(value);
      (*cpp)[i] = ComplexPixel(temp.real, temp.imag);
    }
  } catch (std::exception e) {
    delete cpp;
    Py_DECREF(seq);
    PyErr_SetString(PyExc_RuntimeError, e.what());
    return 0;
  }
  Py_DECREF(seq);
  return cpp;
}
static void process_domains(PyObject *domains, char ***rdomains, int *ndomains)
{
    Py_ssize_t i, n;
    PyObject *item, *data_fast;
    char **c_domains;
    char *arg_str, *tmp_str;

    c_domains = NULL;

    *rdomains = NULL;
    *ndomains = 0;

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

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

    if (n == 0) {
        return;
    }

    c_domains = (char **)PyMem_Malloc(sizeof(char *) * n+1);
    if (!c_domains) {
        PyErr_NoMemory();
        goto cleanup;
    }
    memset(c_domains, 0, n+1);
    i = 0;
    while (i < n) {
        item = PySequence_Fast_GET_ITEM(data_fast, i);
        if (!item || !PyArg_Parse(item, "s;args contains a non-string value", &arg_str)) {
            Py_XDECREF(item);
            goto cleanup;
        }
        Py_DECREF(item);
        tmp_str = (char *) PyMem_Malloc(strlen(arg_str) + 1);
        if (!tmp_str) {
            PyErr_NoMemory();
            goto cleanup;
        }
        strcpy(tmp_str, arg_str);
        c_domains[i] = tmp_str;
        i++;
    }
    c_domains[n] = NULL;

    *rdomains = c_domains;
    *ndomains = n;
    return;

cleanup:
    *rdomains = NULL;
    *ndomains = -1;
    free_domains(c_domains);
}
Example #19
0
static PyObject* PyBlitzArray_getitem(PyBlitzArrayObject* self,
    PyObject* item) {

  if (PyBob_NumberCheck(item)) {

    if (self->ndim != 1) {
      PyErr_Format(PyExc_TypeError, "expected tuple for accessing %" PY_FORMAT_SIZE_T "dD array", self->ndim);
      return 0;
    }

    // if you get to this point, the user has passed single number
    Py_ssize_t k = PyNumber_AsSsize_t(item, PyExc_IndexError);
    return PyBlitzArray_GetItem(self, &k);

  }

  if (PySequence_Check(item)) {

    if (self->ndim != PySequence_Fast_GET_SIZE(item)) {
      PyErr_Format(PyExc_TypeError, "expected tuple of size %" PY_FORMAT_SIZE_T "d for accessing %" PY_FORMAT_SIZE_T "dD array", self->ndim, self->ndim);
      return 0;
    }

    // if you get to this point, then the input tuple has the same size
    PyBlitzArrayObject shape;
    PyBlitzArrayObject* shape_p = &shape;
    if (!PyBlitzArray_IndexConverter(item, &shape_p)) return 0;
    return PyBlitzArray_GetItem(self, shape.shape);

  }

  PyErr_Format(PyExc_TypeError, "%s(@%" PY_FORMAT_SIZE_T "d,'%s') indexing requires a single integers (for 1D arrays) or sequences, for any rank size", Py_TYPE(self)->tp_name, self->ndim, PyBlitzArray_TypenumAsString(self->type_num));
  return 0;
}
Example #20
0
static int
pygpgme_context_set_signers(PyGpgmeContext *self, PyObject *value)
{
    PyObject *signers = NULL;
    int i, length, ret = 0;

    if (value == NULL) {
        PyErr_SetString(PyExc_AttributeError, "Can not delete attribute");
        return -1;
    }

    signers = PySequence_Fast(value, "signers must be a sequence of keys");
    if (!signers) {
        ret = -1;
        goto end;
    }

    gpgme_signers_clear(self->ctx);
    length = PySequence_Fast_GET_SIZE(signers);
    for (i = 0; i < length; i++) {
        PyObject *item = PySequence_Fast_GET_ITEM(signers, i);

        if (!PyObject_TypeCheck(item, &PyGpgmeKey_Type)) {
            PyErr_SetString(PyExc_TypeError,
                            "signers must be a sequence of keys");
            ret = -1;
            goto end;
        }
        gpgme_signers_add(self->ctx, ((PyGpgmeKey *)item)->key);
    }

 end:
    Py_XDECREF(signers);
    return ret;
}
Example #21
0
static PyObject * Node_from_list(PyTypeObject *type, PyObject *args)
{
    PyObject *o, *l;
    Py_ssize_t len, i;
    PyObject **arr;
    Node *tree;

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

    l = PySequence_Fast(o, "sequence is required");
    if (!l)
        return NULL;

    len = PySequence_Fast_GET_SIZE(l);
    arr = PySequence_Fast_ITEMS(l);

    if (len < 1) {
        Py_INCREF(Py_None);
        return Py_None;
    } else
        tree = Node__new(type, arr[0], (Node *)Py_None,
                (Node *)Py_None, (Node *)Py_None);

    for (i=1; i<len; i++)
        Node__insert(tree, arr[i]);

    return (PyObject *)tree;
}
Example #22
0
/*
 * Get possible out argument from kwds, and returns the number of outputs
 * contained within it: if a tuple, the number of elements in it, 1 otherwise.
 * The out argument itself is returned in out_kwd_obj, and the outputs
 * in the out_obj array (all as borrowed references).
 *
 * Returns -1 if kwds is not a dict, 0 if no outputs found.
 */
static int
get_out_objects(PyObject *kwds, PyObject **out_kwd_obj, PyObject ***out_objs)
{
    if (kwds == NULL) {
        return 0;
    }
    if (!PyDict_CheckExact(kwds)) {
        PyErr_SetString(PyExc_TypeError,
                        "Internal Numpy error: call to PyUFunc_WithOverride "
                        "with non-dict kwds");
        return -1;
    }
    /* borrowed reference */
    *out_kwd_obj = PyDict_GetItemString(kwds, "out");
    if (*out_kwd_obj == NULL) {
        return 0;
    }
    if (PyTuple_CheckExact(*out_kwd_obj)) {
        *out_objs = PySequence_Fast_ITEMS(*out_kwd_obj);
        return PySequence_Fast_GET_SIZE(*out_kwd_obj);
    }
    else {
        *out_objs = out_kwd_obj;
        return 1;
    }
}
Example #23
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;
}
Example #24
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;
	}
}
Example #25
0
File: common.c Project: 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;
}
Example #26
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;
}
Example #27
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;
}
Example #28
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);
}
Example #29
0
int
set_pvcards(
    /*@[email protected]*/ 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;
}
Example #30
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;
}