Exemple #1
0
PyObject *PyCodec_IgnoreErrors(PyObject *exc)
{
    Py_ssize_t end;
    if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
        if (PyUnicodeEncodeError_GetEnd(exc, &end))
            return NULL;
    }
    else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
        if (PyUnicodeDecodeError_GetEnd(exc, &end))
            return NULL;
    }
    else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
        if (PyUnicodeTranslateError_GetEnd(exc, &end))
            return NULL;
    }
    else {
        wrong_exception_type(exc);
        return NULL;
    }
    return Py_BuildValue("(Nn)", PyUnicode_New(0, 0), end);
}
Exemple #2
0
static PyObject *IOManager_submit(IOManager *self, PyObject *args) {
   PyObject *req_s, *iter;
   IORequest *item;
   Py_ssize_t l;
   int rc;
   struct iocb **cb, **cb_l;
   if (!PyArg_ParseTuple(args, "O", &req_s)) return NULL;

   if ((l = PySequence_Size(req_s)) < 0) return NULL;
   if (l > (self->nr_events - self->pending_events)) {
      PyErr_SetString(PyExc_ValueError, "Queue length exceeded.");
      return NULL;
   }
   
   cb = self->cbs;
   cb_l = cb + (self->nr_events - self->pending_events);
   
   if (!(iter = PyObject_GetIter(req_s))) return NULL;
   for (; (item = (IORequest*) PyIter_Next(iter)); cb++) {
      if (!PyObject_IsInstance((PyObject*) item, (PyObject*) &IORequestType)) {
         Py_DECREF(item);
         PyErr_SetString(PyExc_TypeError, "Elements of argument 0 must be of type IORequest.");
         return IOM_iocb_cleanup(self, cb+1);
      }
      if (cb == cb_l) {
         Py_DECREF(item);
         PyErr_SetString(PyExc_ValueError, "Queue length exceeded (secondary check)");
         return IOM_iocb_cleanup(self, cb+1);
      }
      if (item->submitted) {
         Py_DECREF(item);
         PyErr_SetString(PyExc_ValueError, "Element of argument 0 had already been submitted earlier.");
         return IOM_iocb_cleanup(self, cb+1);
      }
      item->submitted = 1;
      item->iocb.u.c.resfd = self->fd;
      *cb = &item->iocb;
   }
   if (PyErr_Occurred()) return IOM_iocb_cleanup(self, cb);
   
   l = cb - self->cbs;
   rc = io_submit(self->ctx, l, self->cbs);
   if (rc < 0) {
      errno = -rc;
      PyErr_SetFromErrno(PyExc_OSError);
      return IOM_iocb_cleanup(self, cb);
   }
   /* Keep one reference to each element read from the iterable, to make sure
      they aren't deallocated while we wait for their IO requests to complete
   */
   self->pending_events += l;
   Py_RETURN_NONE;
}
static PyObject*
rich_compare(PyObject *a, PyObject *b, int op)
{
    if (op == Py_EQ || op == Py_NE)
    {
        if (! (PyObject_IsInstance(a, (PyObject*)&ChipNameType) &&
               PyObject_IsInstance(b, (PyObject*)&ChipNameType)))
        {
            Py_INCREF(Py_NotImplemented);
            return Py_NotImplemented;
        }

        sensors_chip_name *c1 = &((ChipName*)a)->chip_name;
        sensors_chip_name *c2 = &((ChipName*)b)->chip_name;

        int equal = (((c1->prefix == NULL && c2->prefix == NULL) ||
                      strcmp(c1->prefix, c2->prefix) == 0) &&
                     c1->bus.type == c2->bus.type &&
                     c1->bus.nr == c2->bus.nr &&
                     c1->addr == c2->addr &&
                     ((c1->path == NULL && c2->path == NULL) ||
                      strcmp(c1->path, c2->path) == 0));

        int ret = op == Py_EQ ? equal : !equal;

        if (ret)
        {
            Py_RETURN_TRUE;
        }

        Py_RETURN_FALSE;
    }
    else
    {
        PyErr_SetString(
            PyExc_TypeError,
            "ChipName only supports the == and != comparison operators");
        return NULL;
    }
}
Exemple #4
0
static PyObject *
psyco_conn_cursor(connectionObject *self, PyObject *args, PyObject *keywds)
{
    const char *name = NULL;
    PyObject *obj, *factory = NULL;

    static char *kwlist[] = {"name", "cursor_factory", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "|sO", kwlist,
                                     &name, &factory)) {
        return NULL;
    }

    EXC_IF_CONN_CLOSED(self);

    if (self->status != CONN_STATUS_READY &&
        self->status != CONN_STATUS_BEGIN) {
        PyErr_SetString(OperationalError,
                        "asynchronous connection attempt underway");
        return NULL;
    }

    if (name != NULL && self->async == 1) {
        PyErr_SetString(ProgrammingError,
                        "asynchronous connections "
                        "cannot produce named cursors");
        return NULL;
    }

    Dprintf("psyco_conn_cursor: new cursor for connection at %p", self);
    Dprintf("psyco_conn_cursor:     parameters: name = %s", name);

    if (factory == NULL) factory = (PyObject *)&cursorType;
    if (name)
        obj = PyObject_CallFunction(factory, "Os", self, name);
    else
        obj = PyObject_CallFunction(factory, "O", self);

    if (obj == NULL) return NULL;
    if (PyObject_IsInstance(obj, (PyObject *)&cursorType) == 0) {
        PyErr_SetString(PyExc_TypeError,
            "cursor factory must be subclass of psycopg2._psycopg.cursor");
        Py_DECREF(obj);
        return NULL;
    }

    Dprintf("psyco_conn_cursor: new cursor at %p: refcnt = "
        FORMAT_CODE_PY_SSIZE_T,
        obj, obj->ob_refcnt
      );
    return obj;
}
/**
 * This function raises exceptions from the MultiResult object, as required
 */
int
pycbc_multiresult_maybe_raise(pycbc_MultiResult *self)
{
    PyObject *type = NULL, *value = NULL, *traceback = NULL;

    if (self->errop == NULL && self->exceptions == NULL) {
        return 0;
    }

    if (self->exceptions) {
        PyObject *tuple = PyList_GetItem(self->exceptions, 0);

        assert(tuple);
        assert(PyTuple_Size(tuple) == 3);

        type = PyTuple_GetItem(tuple, 0);
        value = PyTuple_GetItem(tuple, 1);
        traceback = PyTuple_GetItem(tuple, 2);
        PyErr_NormalizeException(&type, &value, &traceback);
        Py_XINCREF(type);
        Py_XINCREF(value);
        Py_XINCREF(traceback);

        assert(PyObject_IsInstance(value, pycbc_helpers.default_exception));

    } else {
        pycbc_Result *res = (pycbc_Result*)self->errop;

        /** Craft an exception based on the operation */
        PYCBC_EXC_WRAP_KEY(PYCBC_EXC_LCBERR, res->rc, "Operational Error", res->key);

        /** Now we have an exception. Let's fetch it back */
        PyErr_Fetch(&type, &value, &traceback);
        PyObject_SetAttrString(value, "result", (PyObject*)res);
    }

    PyObject_SetAttrString(value, "all_results", (PyObject*)self);
    PyErr_Restore(type, value, traceback);

    /**
     * This is needed since the exception object will later contain
     * a reference to ourselves. If we don't free the original exception,
     * then we'll be stuck with a circular reference
     */
    Py_XDECREF(self->exceptions);
    Py_XDECREF(self->errop);
    self->exceptions = NULL;
    self->errop = NULL;


    return 1;
}
Exemple #6
0
/* initSetIteration
 *
 * Start the set iteration protocol.  See the comments at struct SetIteration.
 *
 * Arguments
 *      i           The address of a SetIteration control struct.
 *      s           The address of the set, bucket, BTree, ..., to be iterated.
 *      useValues   Boolean; if true, and s has values (is a mapping), copy
 *                  them into i->value each time i->next() is called; else
 *                  ignore s's values even if s is a mapping.
 *
 * Return
 *      0 on success; -1 and an exception set if error.
 *      i.usesValue is set to 1 (true) if s has values and useValues was
 *          true; else usesValue is set to 0 (false).
 *      i.set gets a new reference to s, or to some other object used to
 *          iterate over s.
 *      i.position is set to 0.
 *      i.next is set to an appropriate iteration function.
 *      i.key and i.value are left alone.
 *
 * Internal
 *      i.position < 0 means iteration terminated.
 *      i.position = 0 means iteration hasn't yet begun (next() hasn't
 *          been called yet).
 *      In all other cases, i.key, and possibly i.value, own references.
 *          These must be cleaned up, either by next() routines, or by
 *          finiSetIteration.
 *      next() routines must ensure the above.  They should return without
 *          doing anything when i.position < 0.
 *      It's the responsibility of {init, fini}setIteration to clean up
 *          the reference in i.set, and to ensure that no stale references
 *          live in i.key or i.value if iteration terminates abnormally.
 *          A SetIteration struct has been cleaned up iff i.set is NULL.
 */
static int
initSetIteration(SetIteration *i, PyObject *s, int useValues)
{
  i->set = NULL;
  i->position = -1;     /* set to 0 only on normal return */
  i->usesValue = 0;     /* assume it's a set or that values aren't iterated */

  if (PyObject_IsInstance(s, (PyObject *)&BucketType))
    {
      i->set = s;
      Py_INCREF(s);

      if (useValues)
        {
          i->usesValue = 1;
          i->next = nextBucket;
        }
      else
        i->next = nextSet;
    }
  else if (PyObject_IsInstance(s, (PyObject *)&SetType))
    {
      i->set = s;
      Py_INCREF(s);
      i->next = nextSet;
    }
  else if (PyObject_IsInstance(s, (PyObject *)&BTreeType))
    {
      i->set = BTree_rangeSearch(BTREE(s), NULL, NULL, 'i');
      UNLESS(i->set) return -1;

      if (useValues)
        {
          i->usesValue = 1;
          i->next = nextBTreeItems;
        }
      else
        i->next = nextTreeSetItems;
    }
Exemple #7
0
PyObject *PyCodec_IgnoreErrors(PyObject *exc)
{
    Py_ssize_t end;
    if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
        if (PyUnicodeEncodeError_GetEnd(exc, &end))
            return NULL;
    }
    else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
        if (PyUnicodeDecodeError_GetEnd(exc, &end))
            return NULL;
    }
    else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
        if (PyUnicodeTranslateError_GetEnd(exc, &end))
            return NULL;
    }
    else {
        wrong_exception_type(exc);
        return NULL;
    }
    /* ouch: passing NULL, 0, pos gives None instead of u'' */
    return Py_BuildValue("(u#n)", &end, 0, end);
}
static PyObject*
ChecksumV1_update(accuraterip_ChecksumV1* self, PyObject *args)
{
    PyObject *framelist_obj;
    pcm_FrameList *framelist;
    unsigned i;

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

    /*ensure framelist_obj is a FrameList object*/
    if (PyObject_IsInstance(framelist_obj, self->framelist_class)) {
        framelist = (pcm_FrameList*)framelist_obj;
    } else {
        PyErr_SetString(PyExc_TypeError, "objects must be of type FrameList");
        return NULL;
    }

    /*ensure FrameList is CD-formatted*/
    if (framelist->channels != 2) {
        PyErr_SetString(PyExc_ValueError,
                        "FrameList must be 2 channels");
        return NULL;
    }
    if (framelist->bits_per_sample != 16) {
        PyErr_SetString(PyExc_ValueError,
                        "FrameList must be 16 bits per sample");
        return NULL;
    }

    /*update CRC with values from FrameList*/
    for (i = 0; i < framelist->frames; i++) {
        if ((self->track_index >= self->start_offset) &&
            (self->track_index <= self->end_offset)) {
            const int left_s = framelist->samples[i * 2];
            const int right_s = framelist->samples[i * 2 + 1];
            const unsigned left_u =
                left_s >= 0 ? left_s : (1 << 16) - (-left_s);
            const unsigned right_u =
                right_s >= 0 ? right_s : (1 << 16) - (-right_s);
            const unsigned value = (right_u << 16) | left_u;

            self->checksum += (value * self->track_index);
        }

        self->track_index++;
    }

    Py_INCREF(Py_None);
    return Py_None;
}
/*
    Write a series of tokens to the current stack at once.
*/
int Tokenizer_emit_all(Tokenizer* self, PyObject* tokenlist)
{
    int pushed = 0;
    PyObject *stack, *token, *left, *right, *text;
    Textbuffer* buffer;
    Py_ssize_t size;

    if (PyList_GET_SIZE(tokenlist) > 0) {
        token = PyList_GET_ITEM(tokenlist, 0);
        switch (PyObject_IsInstance(token, Text)) {
            case 0:
                break;
            case 1: {
                pushed = 1;
                buffer = self->topstack->textbuffer;
                if (buffer->length == 0)
                    break;
                left = Textbuffer_render(buffer);
                if (!left)
                    return -1;
                right = PyObject_GetAttrString(token, "text");
                if (!right)
                    return -1;
                text = PyUnicode_Concat(left, right);
                Py_DECREF(left);
                Py_DECREF(right);
                if (!text)
                    return -1;
                if (PyObject_SetAttrString(token, "text", text)) {
                    Py_DECREF(text);
                    return -1;
                }
                Py_DECREF(text);
                if (Textbuffer_reset(buffer))
                    return -1;
                break;
            }
            case -1:
                return -1;
        }
    }
    if (!pushed) {
        if (Tokenizer_push_textbuffer(self))
            return -1;
    }
    stack = self->topstack->stack;
    size = PyList_GET_SIZE(stack);
    if (PyList_SetSlice(stack, size, size, tokenlist))
        return -1;
    return 0;
}
Exemple #10
0
/*	Initialize the LDAPConnection. */
static int
LDAPConnection_init(LDAPConnection *self, PyObject *args, PyObject *kwds) {
	PyObject *async_obj = NULL;
	PyObject *client = NULL;
	PyObject *ldapclient_type = NULL;
	PyObject *tmp = NULL;
	PyObject *page_size = NULL, *sort_list = NULL;
    static char *kwlist[] = {"client", "async", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O!", kwlist, &client,
    		&PyBool_Type, &async_obj)) {
    	return -1;
    }

    if (async_obj != NULL) self->async = PyObject_IsTrue(async_obj);

    ldapclient_type = load_python_object("pyldap.ldapclient", "LDAPClient");
    if (ldapclient_type == NULL ||
    		!PyObject_IsInstance(client, ldapclient_type)) {
    	return -1;
    }
	Py_DECREF(ldapclient_type);

    if (client) {
    	tmp = self->client;
    	Py_INCREF(client);
    	self->client = client;
    	Py_XDECREF(tmp);

    	/* Get page size from the client. */
    	page_size = PyObject_GetAttrString(self->client, "_LDAPClient__page_size");
    	if (page_size == NULL) return -1;
    	self->page_size = (int)PyLong_AsLong(page_size);
    	Py_DECREF(page_size);
    	if (PyErr_Occurred()) return -1;

    	/* Get sort list from the client. */
    	sort_list = PyObject_GetAttrString(self->client, "_LDAPClient__sort_attrs");
    	if (PyList_Size(sort_list) > 0) {
    		self->sort_list = PyList2LDAPSortKeyList(sort_list);
    		if (self->sort_list == NULL) {
    			PyErr_BadInternalCall();
    			return -1;
    		}
    	}

        return connecting(self);
    }
    return -1;
}
Exemple #11
0
    static void set_errors(Tango::EventData &event_data, boost::python::object &error)
    {
        PyObject* error_ptr = error.ptr();
        if (PyObject_IsInstance(error_ptr, PyTango_DevFailed.ptr()))
        {
            Tango::DevFailed df;
	    boost::python::object error_list = error.attr("args");
	    sequencePyDevError_2_DevErrorList(error_list.ptr(), event_data.errors);
        }
        else
        {
            sequencePyDevError_2_DevErrorList(error_ptr, event_data.errors);
        }
    }
Exemple #12
0
bool IsInstanceForThread(PyObject* param, const char* szModule, const char* szClass, PyObject** pcls)
{
    // Like PyObject_IsInstance but compares against a class specific to the current thread's
    // interpreter, for proper subinterpreter support.  Uses GetClassForThread.
    //
    // If `param` is an instance of the given class, true is returned and a new reference to
    // the class, specific to the current thread, is returned via pcls.  The caller is
    // responsible for decrementing the class.
    //
    // If `param` is not an instance, true is still returned (!) but *pcls will be zero.
    //
    // False is only returned when an exception has been raised.  (That is, the return value is
    // not used to indicate whether the instance check matched or not.)

    if (param == 0)
    {
        *pcls = 0;
        return true;
    }

    PyObject* cls = GetClassForThread(szModule, szClass);
    if (!cls)
    {
        *pcls = 0;
        return false;
    }

    int n = PyObject_IsInstance(param, cls);
    // (The checks below can be compressed into just a few lines, but I was concerned it
    //  wouldn't be clear.)

    if (n == 1)
    {
        // We have a match.
        *pcls = cls;
        return true;
    }

    Py_DECREF(cls);
    *pcls = 0;

    if (n == 0)
    {
        // No exception, but not a match.
        return true;
    }

    // n == -1; an exception occurred
    return false;
}
static int
_cairo_pattern_to_gvalue(GValue *value, PyObject *obj)
{
    if (obj == Py_None) {
        g_value_set_boxed(value, NULL);
        return 0;
    }

    if (!(PyObject_IsInstance(obj, (PyObject *) &PycairoPattern_Type)))
        return -1;

    g_value_set_boxed(value, ((PycairoPattern*)(obj))->pattern);
    return 0;
}
Exemple #14
0
static PyObject *
thunk_ipower(PyObject *a, PyObject *b, PyObject *c)
{
    PyObject *val;

    if (PyObject_IsInstance(a, (PyObject*) &thunk_type)) {
        val = _strict_eval_borrowed(a);
        return PyNumber_InPlacePower(val, b, c);
    }
    else {
        val = _strict_eval_borrowed(b);
        return PyNumber_InPlacePower(a, val, c);
    }
}
EpetraExt::ModelEvaluator::DerivativeMultiVector
getDerivativeMultiVectorObjectAttr(PyObject * object, CONST char * name)
{
    static
    PyObject * classDerivativeMultiVector = NULL;
    if (!classDerivativeMultiVector)
    {
        classDerivativeMultiVector = getClassFromModule(PyTrilinosEpetraExt,
                                     "DerivativeMultiVector");
        if (!classDerivativeMultiVector) throw PythonException();
    }
    PyObject * value = PyObject_GetAttrString(object, name);
    if (!value) throw PythonException();
    if (!PyObject_IsInstance(value, classDerivativeMultiVector))
    {
        PyErr_Format(PyExc_TypeError, "Attribute '%s' is not of type DerivativeMultiVector", name);
        Py_DECREF(value);
        throw PythonException();
    }
    // multiVector attribute
    Teuchos::RCP<Epetra_MultiVector> multiVector =
        getEpetraMultiVectorObjectAttr(value, "multiVector");
    // orientation attribute
    EpetraExt::ModelEvaluator::EDerivativeMultiVectorOrientation orientation;
    CONST char * linearity = getStringObjectAttr(value, "linearity");
    if (strncmp(linearity, "mv_by_col", 9) == 0)
        orientation = EpetraExt::ModelEvaluator::DERIV_MV_BY_COL;
    if (strncmp(linearity, "trans_mv_by_row", 15) == 0)
        orientation = EpetraExt::ModelEvaluator::DERIV_TRANS_MV_BY_ROW;
    // paramIndexes attribute
    PyObject * seq = PyObject_GetAttrString(value, "paramIndexes");
    if (!seq) throw PythonException();
    Py_ssize_t len = PySequence_Length(seq);
    if (len < 0) throw PythonException();
    Teuchos::Array<int> paramIndexes(len);
    for (Py_ssize_t i = 0; i < len; ++i)
    {
        PyObject * item = PySequence_GetItem(seq, i);
        if (!item) throw PythonException();
        paramIndexes[i] = (int) PyInt_AsLong(item);
        Py_DECREF(item);
        if (PyErr_Occurred()) throw PythonException();
    }
    Py_DECREF(seq);
    Py_DECREF(value);

    // Result
    return EpetraExt::ModelEvaluator::DerivativeMultiVector(multiVector, orientation,
            paramIndexes);
}
Exemple #16
0
static PyObject *
psyco_conn_lobject(connectionObject *self, PyObject *args, PyObject *keywds)
{
    Oid oid = InvalidOid, new_oid = InvalidOid;
    const char *new_file = NULL;
    const char *smode = "";
    PyObject *factory = (PyObject *)&lobjectType;
    PyObject *obj;

    static char *kwlist[] = {"oid", "mode", "new_oid", "new_file",
                             "lobject_factory", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "|IzIzO", kwlist,
                                     &oid, &smode, &new_oid, &new_file,
                                     &factory)) {
        return NULL;
    }

    EXC_IF_CONN_CLOSED(self);
    EXC_IF_CONN_ASYNC(self, lobject);
    EXC_IF_GREEN(lobject);
    EXC_IF_TPC_PREPARED(self, lobject);

    Dprintf("psyco_conn_lobject: new lobject for connection at %p", self);
    Dprintf("psyco_conn_lobject:     parameters: oid = %u, mode = %s",
            oid, smode);
    Dprintf("psyco_conn_lobject:     parameters: new_oid = %d, new_file = %s",
            new_oid, new_file);

    if (new_file)
        obj = PyObject_CallFunction(factory, "OIsIs",
            self, oid, smode, new_oid, new_file);
    else
        obj = PyObject_CallFunction(factory, "OIsI",
            self, oid, smode, new_oid);

    if (obj == NULL) return NULL;
    if (PyObject_IsInstance(obj, (PyObject *)&lobjectType) == 0) {
        PyErr_SetString(PyExc_TypeError,
            "lobject factory must be subclass of psycopg2.extensions.lobject");
        Py_DECREF(obj);
        return NULL;
    }

    Dprintf("psyco_conn_lobject: new lobject at %p: refcnt = "
            FORMAT_CODE_PY_SSIZE_T,
            obj, Py_REFCNT(obj));
    return obj;
}
static PyObject* PyDrawableComponent_new(PyTypeObject* type, PyObject* args, PyObject*)
{
  PyObject* owner;
  if(!PyArg_ParseTuple(args, "O", &owner))
    return NULL;

  if(!PyObject_IsInstance(owner, (PyObject*)&PyEntity_Type)) {
    PyErr_SetString(PyExc_TypeError, "Must pass an Entity object as the owner");
    return NULL;
  }
  
  PyDrawableComponent* c = (PyDrawableComponent*)type->tp_alloc(type, 0);
  c->coord = new DrawableComponent(((PyEntity*)owner)->ent);
  return (PyObject*)c;
}
Exemple #18
0
PyObject *
call_if_persistent(PyObject *x, PyObject *args)
{
	PyObject *f;     
	PyObject *arg; 
	if (!PyArg_UnpackTuple(args, "", 2, 2, &f, &arg)) {
		return NULL;
	}
	if (PyObject_IsInstance(arg, (PyObject *)&PersistentBase_Type)) {
		return PyObject_CallFunction(f, "O", arg);
 	} else {
		Py_INCREF(Py_None);
		return Py_None;
	}
}
Exemple #19
0
BOOST_PYTHON_DECL PyObject*
pytype_check(PyTypeObject* type_, PyObject* source)
{
    if (!PyObject_IsInstance(source, python::upcast<PyObject>(type_)))
    {
        ::PyErr_Format(
            PyExc_TypeError
            , "Expecting an object of type %s; got an object of type %s instead"
            , type_->tp_name
            , source->ob_type->tp_name
            );
        throw_error_already_set();
    }
    return source;
}
Exemple #20
0
bool PyPyCSA_Check (PyObject* obj)
{
  if (pCSAClasses == 0)
    {
      if (!CSAimported ())
	return false;

      // load CSA library
      bool status = loadCSA ();
      if (!status)
	return false;
    }

  return PyObject_IsInstance (obj, pCSAClasses);
}
Exemple #21
0
static PyObject *
snakeoil_iflatten_instance_new(PyTypeObject *type,
							   PyObject *args, PyObject *kwargs)
{
	snakeoil_iflatten_instance *self;
	PyObject *l=NULL, *skip_flattening=(PyObject*)&PyBaseString_Type;
	int res;

	if (kwargs && PyDict_Size(kwargs)) {
		PyErr_SetString(PyExc_TypeError,
						"iflatten_instance takes no keyword arguments");
		return NULL;
	}
	if (!PyArg_UnpackTuple(args, "iflatten_instance", 1, 2,
						   &l, &skip_flattening)) {
		return NULL;
	}

	/* Check if we got a single argument that should be skipped. */
	res = PyObject_IsInstance(l, skip_flattening);
	if (res == -1) {
		return NULL;
	} else if (res) {
		PyObject *tuple = PyTuple_Pack(1, l);
		if (!tuple) {
			return NULL;
		}
		PyObject *iter = PyObject_GetIter(tuple);
		Py_DECREF(tuple);
		return iter;
	}

	self = (snakeoil_iflatten_instance *)type->tp_alloc(type, 0);
	if (!self)
		return NULL;

	self->in_iternext = 0;

	if (!(self->iterables = build_initial_iterables(l))) {
		Py_DECREF(self);
		return NULL;
	}

	Py_INCREF(skip_flattening);
	self->skip_flattening = skip_flattening;

	return (PyObject *)self;
}
Exemple #22
0
/*	Setter for client attribute. */
static int
LDAPEntry_setClient(LDAPEntry *self, PyObject *value, void *closure) {
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the client attribute.");
        return -1;
    }

    if (!PyObject_IsInstance(value, (PyObject *)&LDAPClientType)) {
        PyErr_SetString(PyExc_TypeError, "The client attribute value must be a LDAPClient.");
        return -1;
    }

    if (LDAPEntry_SetClient(self, (LDAPClient *)value) != 0) return -1;

    return 0;
}
PyObject *py_unreal_engine_remove_ticker(PyObject * self, PyObject * args) {

	PyObject *py_obj;
	if (!PyArg_ParseTuple(args, "O:remove_ticker", &py_obj)) {
		return NULL;
	}

	if (!PyObject_IsInstance(py_obj, (PyObject *)&ue_PyFDelegateHandleType))
		return PyErr_Format(PyExc_Exception, "object is not a PyFDelegateHandle");

	ue_PyFDelegateHandle *py_handle = (ue_PyFDelegateHandle *)py_obj;
	FTicker::GetCoreTicker().RemoveTicker(py_handle->dhandle);

	Py_INCREF(Py_None);
	return Py_None;
}
Exemple #24
0
static gboolean
_pygi_marshal_from_py_interface_flags (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
{
    PyObject *py_long;
    unsigned long c_ulong;
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
    GIBaseInfo *interface;

    is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);

    py_long = PYGLIB_PyNumber_Long (py_arg);
    if (py_long == NULL) {
        PyErr_Clear ();
        goto err;
    }

    c_ulong = PYGLIB_PyLong_AsUnsignedLong (py_long);
    Py_DECREF (py_long);

    /* only 0 or argument of type Flag is allowed */
    if (!is_instance && c_ulong != 0)
        goto err;

    /* Write c_long into arg */
    interface = g_type_info_get_interface (arg_cache->type_info);
    g_assert (g_base_info_get_type (interface) == GI_INFO_TYPE_FLAGS);
    if (!gi_argument_from_c_long(arg, c_ulong,
                                 g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
        g_base_info_unref (interface);
        return FALSE;
    }

    g_base_info_unref (interface);
    return TRUE;

err:
    PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
                  iface_cache->type_name, Py_TYPE (py_arg)->tp_name);
    return FALSE;

}
Exemple #25
0
/**
 * pygi_error_marshal_from_py:
 * @pyerr: A Python exception instance.
 * @error: a standard GLib GError ** output parameter
 *
 * Converts from a Python implemented GError into a GError.
 *
 * Returns: TRUE if the conversion was successful, otherwise a Python exception
 *          is set and FALSE is returned.
 */
gboolean
pygi_error_marshal_from_py (PyObject *pyerr, GError **error)
{
    gboolean res = FALSE;
    PyObject *py_message = NULL,
             *py_domain = NULL,
             *py_code = NULL;

    if (PyObject_IsInstance (pyerr, PyGError) != 1) {
        PyErr_Format (PyExc_TypeError, "Must be GLib.Error, not %s",
                      pyerr->ob_type->tp_name);
        return FALSE;
    }

    py_message = PyObject_GetAttrString (pyerr, "message");
    if (!py_message || !PYGLIB_PyUnicode_Check (py_message)) {
        PyErr_SetString (PyExc_ValueError,
                         "GLib.Error instances must have a 'message' string attribute");
        goto cleanup;
    }

    py_domain = PyObject_GetAttrString (pyerr, "domain");
    if (!py_domain || !PYGLIB_PyUnicode_Check (py_domain)) {
        PyErr_SetString (PyExc_ValueError,
                         "GLib.Error instances must have a 'domain' string attribute");
        goto cleanup;
    }

    py_code = PyObject_GetAttrString (pyerr, "code");
    if (!py_code || !PYGLIB_PyLong_Check (py_code)) {
        PyErr_SetString (PyExc_ValueError,
                         "GLib.Error instances must have a 'code' int attribute");
        goto cleanup;
    }

    res = TRUE;
    g_set_error_literal (error,
                         g_quark_from_string (PYGLIB_PyUnicode_AsString (py_domain)),
                         PYGLIB_PyLong_AsLong (py_code),
                         PYGLIB_PyUnicode_AsString (py_message));

cleanup:
    Py_XDECREF (py_message);
    Py_XDECREF (py_code);
    Py_XDECREF (py_domain);
    return res;
}
Exemple #26
0
/* Create a thunk that wraps a single value. */
static PyObject *
thunk_fromvalue(PyTypeObject *cls, PyObject *value)
{
    if (PyObject_IsInstance(value, (PyObject*) &PyType_Type) &&
        PyObject_IsSubclass(value, (PyObject*) &strict_type)) {
        Py_INCREF(value);
        return value;
    }
    if (PyObject_IsSubclass((PyObject*) Py_TYPE(value),
                            (PyObject*) &thunk_type)) {
        /* thunk.fromvalue of a thunk is the identity */
        Py_INCREF(value);
        return value;
    }

    return  _thunk_new_normal(cls, value);
}
Exemple #27
0
static int
descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value,
	       int *pres)
{
	assert(obj != NULL);
	if (!PyObject_IsInstance(obj, (PyObject *)(descr->d_type))) {
		PyErr_Format(PyExc_TypeError,
			     "descriptor '%.200s' for '%.100s' objects "
			     "doesn't apply to '%.100s' object",
			     descr_name(descr),
			     descr->d_type->tp_name,
			     obj->ob_type->tp_name);
		*pres = -1;
		return 1;
	}
	return 0;
}
Exemple #28
0
/* Return 1 if `obj` is a `psycopg2.sql.Composable` instance, else 0
 * Set an exception and return -1 in case of error.
 */
RAISES_NEG static int
_curs_is_composible(PyObject *obj)
{
    int rv = -1;
    PyObject *m = NULL;
    PyObject *comp = NULL;

    if (!(m = PyImport_ImportModule("psycopg2.sql"))) { goto exit; }
    if (!(comp = PyObject_GetAttrString(m, "Composable"))) { goto exit; }
    rv = PyObject_IsInstance(obj, comp);

exit:
    Py_XDECREF(comp);
    Py_XDECREF(m);
    return rv;

}
Exemple #29
0
static PyObject *
wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds)
{
	STACKLESS_GETARG();
	Py_ssize_t argc;
	PyObject *self, *func, *result;

	/* Make sure that the first argument is acceptable as 'self' */
	assert(PyTuple_Check(args));
	argc = PyTuple_GET_SIZE(args);
	if (argc < 1) {
		PyErr_Format(PyExc_TypeError,
			     "descriptor '%.300s' of '%.100s' "
			     "object needs an argument",
			     descr_name((PyDescrObject *)descr),
			     descr->d_type->tp_name);
		return NULL;
	}
	self = PyTuple_GET_ITEM(args, 0);
	if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
		PyErr_Format(PyExc_TypeError,
			     "descriptor '%.200s' "
			     "requires a '%.100s' object "
			     "but received a '%.100s'",
			     descr_name((PyDescrObject *)descr),
			     descr->d_type->tp_name,
			     self->ob_type->tp_name);
		return NULL;
	}

	func = PyWrapper_New((PyObject *)descr, self);
	if (func == NULL)
		return NULL;
	args = PyTuple_GetSlice(args, 1, argc);
	if (args == NULL) {
		Py_DECREF(func);
		return NULL;
	}
	STACKLESS_PROMOTE_ALL();
	result = PyEval_CallObjectWithKeywords(func, args, kwds);
	STACKLESS_ASSERT();
	Py_DECREF(args);
	Py_DECREF(func);
	return result;
}
EpetraExt::ModelEvaluator::DerivativeProperties
getDerivativePropertiesItemObjectAttr(PyObject * object, CONST char * name, int i)
{
    // The DerivativeProperties python class object
    static
    PyObject * classDerivativeProperties = NULL;
    if (!classDerivativeProperties)
    {
        classDerivativeProperties = getClassFromModule(PyTrilinosEpetraExt, "DerivativeProperties");
        if (!classDerivativeProperties) throw PythonException();
    }
    // Get the item from the object attribute
    PyObject * tuple = getTupleObjectAttr(object, name);
    PyObject * item  = PyTuple_GetItem(tuple, i);
    Py_DECREF(tuple);
    if (!item) throw PythonException();
    if (!PyObject_IsInstance(item, classDerivativeProperties))
    {
        PyErr_Format(PyExc_TypeError, "Attribute '%s' is not tuple of DerivativeProperties", name);
        Py_DECREF(item);
        throw PythonException();
    }
    EpetraExt::ModelEvaluator::DerivativeProperties result;
    // linearity attribute
    CONST char * linearity = getStringObjectAttr(item, "linearity");
    if (strncmp(linearity, "unknown", 7) == 0)
        result.linearity = EpetraExt::ModelEvaluator::DERIV_LINEARITY_UNKNOWN;
    if (strncmp(linearity, "const", 5) == 0)
        result.linearity = EpetraExt::ModelEvaluator::DERIV_LINEARITY_CONST;
    if (strncmp(linearity, "nonconst", 8) == 0)
        result.linearity = EpetraExt::ModelEvaluator::DERIV_LINEARITY_NONCONST;
    // rank attribute
    CONST char * rank = getStringObjectAttr(item, "rank");
    if (strncmp(rank, "unknown", 7) == 0)
        result.rank = EpetraExt::ModelEvaluator::DERIV_RANK_UNKNOWN;
    if (strncmp(rank, "full", 4) == 0)
        result.rank = EpetraExt::ModelEvaluator::DERIV_RANK_FULL;
    if (strncmp(rank, "deficient", 9) == 0)
        result.rank = EpetraExt::ModelEvaluator::DERIV_RANK_DEFICIENT;
    // supportsAdjoint attribute
    result.supportsAdjoint = getBoolObjectAttr(item, "supportsAdjoint");
    Py_DECREF(item);

    return result;
}