Example #1
0
PyObject *wsgi_convert_headers_to_bytes(PyObject *headers)
{
    PyObject *result = NULL;

    int i;
    long size;

    if (!PyList_Check(headers)) {
        PyErr_Format(PyExc_TypeError, "expected list object for headers, "
                     "value of type %.200s found", headers->ob_type->tp_name);
        return 0;
    }

    size = PyList_Size(headers);
    result = PyList_New(size);

    for (i = 0; i < size; i++) {
        PyObject *header = NULL;

        PyObject *header_name = NULL;
        PyObject *header_value = NULL;

        PyObject *header_name_as_bytes = NULL;
        PyObject *header_value_as_bytes = NULL;

        PyObject *result_tuple = NULL;

        header = PyList_GetItem(headers, i);

        if (!PyTuple_Check(header)) {
            PyErr_Format(PyExc_TypeError, "list of tuple values "
                         "expected for headers, value of type %.200s found",
                         header->ob_type->tp_name);
            Py_DECREF(result);
            return 0;
        }

        if (PyTuple_Size(header) != 2) {
            PyErr_Format(PyExc_ValueError, "tuple of length 2 "
                         "expected for header, length is %d",
                         (int)PyTuple_Size(header));
            Py_DECREF(result);
            return 0;
        }

        result_tuple = PyTuple_New(2);
        PyList_SET_ITEM(result, i, result_tuple);

        header_name = PyTuple_GetItem(header, 0);
        header_value = PyTuple_GetItem(header, 1);

        header_name_as_bytes = wsgi_convert_string_to_bytes(header_name);

        if (!header_name_as_bytes)
            goto failure;

        PyTuple_SET_ITEM(result_tuple, 0, header_name_as_bytes);

        if (!wsgi_validate_header_name(header_name_as_bytes))
            goto failure;

        header_value_as_bytes = wsgi_convert_string_to_bytes(header_value);

        if (!header_value_as_bytes)
            goto failure;

        PyTuple_SET_ITEM(result_tuple, 1, header_value_as_bytes);

        if (!wsgi_validate_header_value(header_value_as_bytes))
            goto failure;
    }

    return result;

failure:
    Py_DECREF(result);
    return NULL;
}
PyObject * dataconv_ReadFromInTuple(PyObject *self, PyObject *args)
{
	PyObject *obArgTypes;
	PyObject *obArgType;
	PyObject *obPtr;
	BYTE *pb;
	BYTE *pbArg;
	Py_ssize_t cArgs, i;
	PyObject *obArgs = NULL;
	PyObject *obArg;
	VARTYPE vtArgType;
	UINT cb;
	VARIANT var;
	BOOL bIsByRef;
	

	if (!PyArg_ParseTuple(args, "OO:ReadFromInTuple", &obArgTypes, &obPtr))
		return NULL;
	
	pbArg = (BYTE *)PyLong_AsVoidPtr(obPtr);
	assert(pbArg);
	if (!pbArg)
		return NULL;

	pb = pbArg;

	if (!PyTuple_Check(obArgTypes))
	{
		PyErr_SetString(PyExc_TypeError, "OLE type description - expecting a tuple");
		return NULL;
	}
	
	cArgs = PyTuple_Size(obArgTypes);
	obArgs = PyTuple_New(cArgs);
	if (!obArgs)
		return NULL;

	for(i = 0 ; i < cArgs; i++)
	{
		// (<type tuple>, argPtr offset, arg size)
		if (PyTuple_Size(PyTuple_GET_ITEM(obArgTypes, i)) != 3)
		{
			PyErr_SetString(PyExc_TypeError, "OLE type description - expecting an arg desc tuple of size 3");
			goto Error;
		}
		
		obArgType = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 0);

		// Position pb to point to the current argument.
		pb = pbArg + PyInt_AS_LONG(PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 1));
		vtArgType = (VARTYPE)PyInt_AS_LONG(obArgType);
#ifdef _M_IX86
		bIsByRef = vtArgType & VT_BYREF;
#elif _M_X64
		// params > 64bits always passed by address - and the only
		// arg we support > 64 bits is a VARIANT structure.
		bIsByRef = (vtArgType==VT_VARIANT) || (vtArgType & VT_BYREF);
#else
#error Unknown platform
#endif
		VARTYPE vtConversionType = vtArgType & VT_TYPEMASK;
		if (vtArgType & VT_ARRAY) {
			SAFEARRAY FAR *psa = *((SAFEARRAY **)pb);
			if (psa==NULL) { // A NULL array
				Py_INCREF(Py_None);
				obArg = Py_None;
			} else {
				if (vtArgType & VT_BYREF) // one more level of indirection
					psa = *((SAFEARRAY FAR **)psa);
				if (psa==NULL) { // A NULL array
					Py_INCREF(Py_None);
					obArg = Py_None;
				} else 
					obArg = PyCom_PyObjectFromSAFEARRAY(psa, (VARENUM)vtConversionType);
			}
		} else {
			switch (vtConversionType)
			{
			// If they can fit in a VARIANT, cheat and make that code do all of the work...
			case VT_I2:
			case VT_I4:
			case VT_R4:
			case VT_R8:
			case VT_CY:
			case VT_DATE:
			case VT_BSTR:
			case VT_ERROR:
			case VT_BOOL:
			case VT_I1:
			case VT_UI1:
			case VT_UI2:
			case VT_UI4:
			case VT_INT:
			case VT_UINT:
			case VT_UNKNOWN:
			case VT_DISPATCH:
			case VT_HRESULT:
				VariantInit(&var);
				if (vtConversionType == VT_HRESULT ||
					vtConversionType == VT_INT)
				{
					// Preserve VT_BYREF or VT_ARRAY
					vtArgType = VT_I4 | (vtArgType & VT_TYPEMASK);
				}
				if (vtArgType == VT_UINT) 
				{
					// Preserve VT_BYREF or VT_ARRAY
					vtArgType = VT_UI4 | (vtArgType & VT_TYPEMASK);
				}
				V_VT(&var) = vtArgType;
				// Copy the data into the variant...
				if (!SizeOfVT(V_VT(&var), (int *)&cb, NULL))
					goto Error;
				memcpy(&V_I4(&var), pb, cb);
				// Convert it into a PyObject:
				obArg = PyCom_PyObjectFromVariant(&var);
				break;
			case VT_VARIANT:
				// A _real_ variant.
				if (bIsByRef)
					obArg = PyCom_PyObjectFromVariant(*(VARIANT**)pb);
				else
					obArg = PyCom_PyObjectFromVariant((VARIANT*)pb);
				break;
			case VT_LPSTR:
				obArg = PyString_FromString(*(CHAR **)pb);
				break;
			case VT_LPWSTR:
				obArg = PyWinObject_FromOLECHAR(*(OLECHAR **)pb);
				break;
			// Special cases:
			case VT_UI8:
				if (bIsByRef)
				{
					obArg = PyWinObject_FromULARGE_INTEGER(*(ULARGE_INTEGER *)pb);
				}
				else
				{
					obArg = PyWinObject_FromULARGE_INTEGER(**(ULARGE_INTEGER **)pb);
				}
				break;
			case VT_I8:
				if (bIsByRef)
				{
					obArg = PyWinObject_FromLARGE_INTEGER(*(LARGE_INTEGER *)pb);
				}
				else
				{
					obArg = PyWinObject_FromLARGE_INTEGER(**(LARGE_INTEGER **)pb);
				}
				break;
			// Pointers to unhandled arguments:
			// neither of these will be VT_BYREF'd.
			case VT_RECORD:
			case VT_PTR:
				obArg = PyLong_FromVoidPtr((void *)pb);
				break;
			// None of these should ever happen:
			case VT_USERDEFINED:
			// Should have been coerced into VT_PTR.
			case VT_CARRAY:
			default:
				obArg = NULL;
				PyErr_SetString(PyExc_TypeError, "Unknown/bad type description type!");
				// barf here, we don't wtf they were thinking...
				break;
			} // switch
		} // if ARRAY

		if (obArg == NULL)
		{
			goto Error;
		}
		PyTuple_SET_ITEM(obArgs, i, obArg);
	}

	return obArgs;
	
Error:
	Py_XDECREF(obArgs);
	return NULL;
}
Example #3
0
// The type init slot.
static int pyqtSignal_init(PyObject *self, PyObject *args, PyObject *kwd_args)
{
    qpycore_pyqtSignal *ps = (qpycore_pyqtSignal *)self;

    // Get the keyword arguments.
    PyObject *name_obj = 0;
    const char *name = 0;
    int revision = 0;
    QList<QByteArray> *parameter_names = 0;

    if (kwd_args)
    {
        Py_ssize_t pos = 0;
        PyObject *key, *value;

        while (PyDict_Next(kwd_args, &pos, &key, &value))
        {
#if PY_MAJOR_VERSION >= 3
            if (PyUnicode_CompareWithASCIIString(key, "name") == 0)
#else
            Q_ASSERT(PyString_Check(key));

            if (qstrcmp(PyString_AsString(key), "name") == 0)
#endif
            {
                name_obj = value;
                name = sipString_AsASCIIString(&name_obj);

                if (!name)
                {
                    PyErr_Format(PyExc_TypeError,
                            "signal 'name' must be a str, not %s",
                            sipPyTypeName(Py_TYPE(value)));

                    return -1;
                }
            }
#if PY_MAJOR_VERSION >= 3
            else if (PyUnicode_CompareWithASCIIString(key, "revision") == 0)
#else
            else if (qstrcmp(PyString_AsString(key), "revision") == 0)
#endif
            {
                revision = sipLong_AsInt(value);

                if (PyErr_Occurred())
                {
                    if (PyErr_ExceptionMatches(PyExc_TypeError))
                        PyErr_Format(PyExc_TypeError,
                                "signal 'revision' must be an int, not %s",
                                sipPyTypeName(Py_TYPE(value)));

                    Py_XDECREF(name_obj);
                    return -1;
                }
            }
#if PY_MAJOR_VERSION >= 3
            else if (PyUnicode_CompareWithASCIIString(key, "arguments") == 0)
#else
            else if (qstrcmp(PyString_AsString(key), "arguments") == 0)
#endif
            {
                bool ok = true;

                if (PySequence_Check(value))
                {
                    Py_ssize_t len = PySequence_Size(value);

                    parameter_names = new QList<QByteArray>;

                    for (Py_ssize_t i = 0; i < len; ++i)
                    {
                        PyObject *py_attr = PySequence_GetItem(value, i);

                        if (!py_attr)
                        {
                            ok = false;
                            break;
                        }

                        PyObject *py_ascii_attr = py_attr;
                        const char *attr = sipString_AsASCIIString(
                                &py_ascii_attr);

                        Py_DECREF(py_attr);

                        if (!attr)
                        {
                            ok = false;
                            break;
                        }

                        parameter_names->append(QByteArray(attr));

                        Py_DECREF(py_ascii_attr);
                    }
                }
                else
                {
                    ok = false;
                }

                if (!ok)
                {
                    PyErr_Format(PyExc_TypeError,
                            "signal 'attribute_names' must be a sequence of str, not %s",
                            sipPyTypeName(Py_TYPE(value)));

                    if (parameter_names)
                        delete parameter_names;

                    Py_XDECREF(name_obj);
                    return -1;
                }
            }
            else
            {
#if PY_MAJOR_VERSION >= 3
                PyErr_Format(PyExc_TypeError,
                        "pyqtSignal() got an unexpected keyword argument '%U'",
                        key);
#else
                PyErr_Format(PyExc_TypeError,
                        "pyqtSignal() got an unexpected keyword argument '%s'",
                        PyString_AsString(key));
#endif

                Py_XDECREF(name_obj);
                return -1;
            }
        }
    }

    // If there is at least one argument and it is a sequence then assume all
    // arguments are sequences.  Unfortunately a string is also a sequence so
    // check for tuples and lists explicitly.
    if (PyTuple_Size(args) > 0 && (PyTuple_Check(PyTuple_GetItem(args, 0)) || PyList_Check(PyTuple_GetItem(args, 0))))
    {
        for (Py_ssize_t i = 0; i < PyTuple_Size(args); ++i)
        {
            PyObject *types = PySequence_Tuple(PyTuple_GetItem(args, i));

            if (!types)
            {
                PyErr_SetString(PyExc_TypeError,
                        "pyqtSignal() argument expected to be sequence of types");

                if (name)
                {
                    Py_DECREF(name_obj);
                }

                return -1;
            }

            int rc;

            if (i == 0)
            {
                // The first is the default.
                rc = init_signal_from_types(ps, name, parameter_names,
                        revision, types);
            }
            else
            {
                qpycore_pyqtSignal *overload = (qpycore_pyqtSignal *)PyType_GenericNew(qpycore_pyqtSignal_TypeObject, 0, 0);

                if (!overload)
                {
                    rc = -1;
                }
                else if ((rc = init_signal_from_types(overload, name, 0, revision, types)) < 0)
                {
                    Py_DECREF((PyObject *)overload);
                }
                else
                {
                    overload->default_signal = ps;
                    append_overload(overload);
                }
            }

            Py_DECREF(types);

            if (rc < 0)
            {
                if (name)
                {
                    Py_DECREF(name_obj);
                }

                return -1;
            }
        }
    }
    else if (init_signal_from_types(ps, name, parameter_names, revision, args) < 0)
    {
        if (name)
        {
            Py_DECREF(name_obj);
        }

        return -1;
    }

    if (name)
    {
        Py_DECREF(name_obj);
    }

    return 0;
}
Example #4
0
AerospikeScan * AerospikeScan_Select(AerospikeScan * self, PyObject * args, PyObject * kwds)
{
	TRACE();

	char * bin = NULL; 
	PyObject * py_ustr = NULL;
	as_error err;
	as_error_init(&err);

	if (!self || !self->client->as) {
		as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object");
		goto CLEANUP;
	}

	if (!self->client->is_conn_16) {
		as_error_update(&err, AEROSPIKE_ERR_CLUSTER, "No connection to aerospike cluster");
		goto CLEANUP;
	}

	int nbins = (int) PyTuple_Size(args);
	as_scan_select_init(&self->scan, nbins);

	for ( int i = 0; i < nbins; i++ ) {
		PyObject * py_bin = PyTuple_GetItem(args, i);
		if ( py_bin) {
			TRACE();
			if (PyUnicode_Check(py_bin)) {
				py_ustr = PyUnicode_AsUTF8String(py_bin);
				bin = PyString_AsString(py_ustr);
			} else if (PyString_Check(py_bin)) {
				bin = PyString_AsString(py_bin);
			} else {
				as_error_update(&err, AEROSPIKE_ERR_PARAM, "Bin name should be of type string");
				PyObject * py_err = NULL;
				error_to_pyobject(&err, &py_err);
				PyObject *exception_type = raise_exception(&err);
				PyErr_SetObject(exception_type, py_err);
				Py_DECREF(py_err);
				return NULL;

			}
		} else {
			TRACE();
		}
		as_scan_select(&self->scan, bin);
		if (py_ustr) {
			Py_DECREF(py_ustr);
			py_ustr = NULL;
		}
	}

CLEANUP:

	if ( err.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(&err, &py_err);
		PyObject *exception_type = raise_exception(&err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}

	Py_INCREF(self);
	return self;
}
// The type call slot.
static PyObject *pyqtMethodProxy_call(PyObject *self, PyObject *args,
        PyObject *kw_args)
{
    qpycore_pyqtMethodProxy *mp = (qpycore_pyqtMethodProxy *)self;

    const char *py_name = mp->py_name->constData();

    // Check for keyword arguments.
    if (kw_args)
    {
        PyErr_Format(PyExc_TypeError,
                "%s() does not support keyword arguments", py_name);
        return 0;
    }

    QMetaMethod method = mp->qobject->metaObject()->method(mp->method_index);
    QList<QByteArray> arg_types = method.parameterTypes();

    if (PyTuple_Size(args) != arg_types.size())
    {
        PyErr_Format(PyExc_TypeError,
#if PY_VERSION_HEX >= 0x02050000
                "%s() called with %zd arguments but %d expected",
#else
                "%s() called with %d arguments but %d expected",
#endif
                py_name, PyTuple_Size(args), arg_types.size());
        return 0;
    }

    // Parse the return type and the arguments.
    QGenericReturnArgument ret;
    QGenericArgument a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
    Chimera::Storage *return_storage, *storage[10];
    QByteArray return_type(method.typeName());
    bool failed = false;

    return_storage = 0;

    if (!return_type.isEmpty())
    {
        const Chimera *ct = Chimera::parse(return_type);

        if (!ct)
        {
            PyErr_Format(PyExc_TypeError,
                    "unable to convert return value of %s from '%s' to a Python object",
                    py_name, return_type.constData());
            return 0;
        }

        return_storage = ct->storageFactory();

        ret = QGenericReturnArgument(return_type.constData(),
                return_storage->address());
    }

    parse_arg(args, 0, arg_types, a0, storage, failed, py_name);
    parse_arg(args, 1, arg_types, a1, storage, failed, py_name);
    parse_arg(args, 2, arg_types, a2, storage, failed, py_name);
    parse_arg(args, 3, arg_types, a3, storage, failed, py_name);
    parse_arg(args, 4, arg_types, a4, storage, failed, py_name);
    parse_arg(args, 5, arg_types, a5, storage, failed, py_name);
    parse_arg(args, 6, arg_types, a6, storage, failed, py_name);
    parse_arg(args, 7, arg_types, a7, storage, failed, py_name);
    parse_arg(args, 8, arg_types, a8, storage, failed, py_name);
    parse_arg(args, 9, arg_types, a9, storage, failed, py_name);

    // Invoke the method.
    PyObject *result = 0;

    if (!failed)
    {
#if QT_VERSION >= 0x040500
        failed = !method.invoke(mp->qobject, ret, a0, a1, a2, a3, a4, a5, a6,
                a7, a8, a9);
#else
        // Get the method name.
        QByteArray mname(method.signature());
        mname.truncate(mname.indexOf('('));

        failed = !QMetaObject::invokeMethod(mp->qobject, mname.constData(),
                ret, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
#endif

        if (failed)
        {
            PyErr_Format(PyExc_TypeError, "invocation of %s() failed", py_name);
        }
        else if (return_storage)
        {
            result = return_storage->toPyObject();
        }
        else
        {
            result = Py_None;
            Py_INCREF(result);
        }
    }

    // Release any storage.
    if (return_storage)
    {
        delete return_storage->type();
        delete return_storage;
    }

    for (int i = 0; i < 10; ++i)
    {
        Chimera::Storage *st = storage[i];

        if (st)
        {
            delete st->type();
            delete st;
        }
    }

    return result;
}
Example #6
0
static PyObject *py_sorted_tree_items(PyObject *self, PyObject *entries)
{
	struct tree_item *qsort_entries;
	int num, i;
	PyObject *ret;
	Py_ssize_t pos = 0; 
	PyObject *key, *value;

	if (!PyDict_Check(entries)) {
		PyErr_SetString(PyExc_TypeError, "Argument not a dictionary");
		return NULL;
	}

	num = PyDict_Size(entries);
	qsort_entries = malloc(num * sizeof(struct tree_item));
	if (qsort_entries == NULL) {
		PyErr_NoMemory();
		return NULL;
	}

	i = 0;
	while (PyDict_Next(entries, &pos, &key, &value)) {
		PyObject *py_mode, *py_sha;
		
		if (PyTuple_Size(value) != 2) {
			PyErr_SetString(PyExc_ValueError, "Tuple has invalid size");
			free(qsort_entries);
			return NULL;
		}

		py_mode = PyTuple_GET_ITEM(value, 0);
		py_sha = PyTuple_GET_ITEM(value, 1);
		qsort_entries[i].tuple = Py_BuildValue("(OOO)", key, py_mode, py_sha);
		if (!PyString_CheckExact(key)) {
			PyErr_SetString(PyExc_TypeError, "Name is not a string");
			free(qsort_entries);
			return NULL;
		}
		qsort_entries[i].name = PyString_AS_STRING(key);
		if (!PyInt_CheckExact(py_mode)) {
			PyErr_SetString(PyExc_TypeError, "Mode is not an int");
			free(qsort_entries);
			return NULL;
		}
		qsort_entries[i].mode = PyInt_AS_LONG(py_mode);
		i++;
	}

	qsort(qsort_entries, num, sizeof(struct tree_item), cmp_tree_item);

	ret = PyList_New(num);
	if (ret == NULL) {
		free(qsort_entries);
		PyErr_NoMemory();
		return NULL;
	}

	for (i = 0; i < num; i++) {
		PyList_SET_ITEM(ret, i, qsort_entries[i].tuple);
	}

	free(qsort_entries);

	return ret;
}
Example #7
0
// find and call a method on this object that matches the python args.
// typically called by way of pyjmethod when python invokes __call__.
//
// steals reference to self, methodname and args.
PyObject* find_method(JNIEnv *env,
                      PyObject *methodName,
                      Py_ssize_t methodCount,
                      PyObject *attr,
                      PyObject *args) {
    // all possible method candidates
    PyJmethod_Object **cand = NULL;
    Py_ssize_t         pos, i, listSize, argsSize;
    
    pos = i = listSize = argsSize = 0;

    // not really likely if we were called from pyjmethod, but hey...
    if(methodCount < 1) {
        PyErr_Format(PyExc_RuntimeError, "I have no methods.");
        return NULL;
    }

    if(!attr || !PyList_CheckExact(attr)) {
        PyErr_Format(PyExc_RuntimeError, "Invalid attr list.");
        return NULL;
    }
    
    cand = (PyJmethod_Object **)
        PyMem_Malloc(sizeof(PyJmethod_Object*) * methodCount);
    
    // just for safety
    for(i = 0; i < methodCount; i++)
        cand[i] = NULL;
    
    listSize = PyList_GET_SIZE(attr);
    for(i = 0; i < listSize; i++) {
        PyObject *tuple = PyList_GetItem(attr, i);               /* borrowed */

        if(PyErr_Occurred())
            break;
        
        if(!tuple || tuple == Py_None || !PyTuple_CheckExact(tuple))
            continue;

        if(PyTuple_Size(tuple) == 2) {
            PyObject *key = PyTuple_GetItem(tuple, 0);           /* borrowed */
            
            if(PyErr_Occurred())
                break;
            
            if(!key || !PyString_Check(key))
                continue;
            
            if(PyObject_Compare(key, methodName) == 0) {
                PyObject *method = PyTuple_GetItem(tuple, 1);    /* borrowed */
                if(pyjmethod_check(method))
                    cand[pos++] = (PyJmethod_Object *) method;
            }
        }
    }
    
    if(PyErr_Occurred())
        goto EXIT_ERROR;
    
    // makes more sense to work with...
    pos--;
    
    if(pos < 0) {
        // didn't find a method by that name....
        // that shouldn't happen unless the search above is broken.
        PyErr_Format(PyExc_NameError, "No such method.");
        goto EXIT_ERROR;
    }
    if(pos == 0) {
        // we're done, call that one
        PyObject *ret = pyjmethod_call_internal(cand[0], args);
        PyMem_Free(cand);
        return ret;
    }

    // first, find out if there's only one method that
    // has the correct number of args
    argsSize = PyTuple_Size(args);
    {
        PyJmethod_Object *matching = NULL;
        int               count    = 0;
        
        for(i = 0; i <= pos && cand[i]; i++) {
            // make sure method is fully initialized
            if(!cand[i]->parameters) {
                if(!pyjmethod_init(env, cand[i])) {
                    // init failed, that's not good.
                    cand[i] = NULL;
                    PyErr_Warn(PyExc_Warning, "pyjmethod init failed.");
                    continue;
                }
            }

            if(cand[i]->lenParameters == argsSize) {
                matching = cand[i];
                count++;
            }
            else
                cand[i] = NULL; // eliminate non-matching
        }
        
        if(matching && count == 1) {
            PyMem_Free(cand);
            return pyjmethod_call_internal(matching, args);
        }
    } // local scope
    
    for(i = 0; i <= pos; i++) {
        int parmpos = 0;
        
        // already eliminated?
        if(!cand[i])
            continue;
        
        // check if argument types match
        (*env)->PushLocalFrame(env, 20);
        for(parmpos = 0; parmpos < cand[i]->lenParameters; parmpos++) {
            PyObject *param       = PyTuple_GetItem(args, parmpos);
            int       paramTypeId = -1;
            jclass    pclazz;
            jclass    paramType =
                (jclass) (*env)->GetObjectArrayElement(env,
                                                       cand[i]->parameters,
                                                       parmpos);

            if(process_java_exception(env) || !paramType)
                break;
            
            pclazz = (*env)->GetObjectClass(env, paramType);
            if(process_java_exception(env) || !pclazz)
                break;
            
            paramTypeId = get_jtype(env, paramType, pclazz);
            
            if(pyarg_matches_jtype(env, param, paramType, paramTypeId)) {
                if(PyErr_Occurred())
                    break;
                continue;
            }
            
            // args don't match
            break;
        }
        (*env)->PopLocalFrame(env, NULL);
        
        // this method matches?
        if(parmpos == cand[i]->lenParameters) {
            PyObject *ret = pyjmethod_call_internal(cand[i], args);
            PyMem_Free(cand);
            return ret;
        }
    }


EXIT_ERROR:
    PyMem_Free(cand);
    if(!PyErr_Occurred())
        PyErr_Format(PyExc_NameError,
                     "Matching overloaded method not found.");
    return NULL;
}
Example #8
0
static PyObject *
Text2DObject_SetTextColor(PyObject *self, PyObject *args)
{
    Text2DObjectObject *obj = (Text2DObjectObject *)self;

    int c[4];
    if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3]))
    {
        c[3] = 255;
        if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2]))
        {
            double dr, dg, db, da;
            if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = int(da);
            }
            else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = 255;
            }
            else
            {
                PyObject *tuple = NULL;
                if(!PyArg_ParseTuple(args, "O", &tuple))
                    return NULL;

                if(!PyTuple_Check(tuple))
                    return NULL;

                // Make sure that the tuple is the right size.
                if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4)
                    return NULL;

                // Make sure that all elements in the tuple are ints.
                for(int i = 0; i < PyTuple_Size(tuple); ++i)
                {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i);
                    if(PyInt_Check(item))
                        c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i)));
                    else if(PyFloat_Check(item))
                        c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i)));
                    else
                        return NULL;
                }
            }
        }
        PyErr_Clear();
    }

    // Set the textColor in the object.
    ColorAttribute ca(c[0], c[1], c[2], c[3]);
    obj->data->SetTextColor(ca);
/*CUSTOM*/
    UpdateAnnotationHelper(obj->data);

    Py_INCREF(Py_None);
    return Py_None;
}
Example #9
0
static PyObject *cboodle_init(PyObject *self, PyObject *args)
{
  char *devname = NULL;
  int ratewanted = 0;
  int verbose = 0;
  int ix, res;
  PyObject *extras = NULL;
  extraopt_t *opts = NULL;
  extraopt_t dummyopt = {NULL, NULL};

  if (!PyArg_ParseTuple(args, "|ziiO:init", &devname, &ratewanted, &verbose, &extras))
    return NULL;

  res = noteq_init();
  if (!res) {
    PyErr_SetString(PyExc_IOError, "unable to initialize note queue");
    return NULL;
  }

  if (extras && PyList_Check(extras)) {
    int count = PyList_Size(extras);

    opts = (extraopt_t *)malloc(sizeof(extraopt_t) * (count+1));
    if (!opts) {
      PyErr_SetString(PyExc_IOError, "unable to initialize extra options");
      return NULL;
    }

    for (ix=0; ix<count; ix++) {
      PyObject *tup = PyList_GetItem(extras, ix);
      PyObject *tkey, *tval;
      if (!tup)
	return NULL;
      if (!PyTuple_Check(tup) || PyTuple_Size(tup) != 2) {
	PyErr_SetString(PyExc_TypeError, "extraopts must be a list of 2-tuples");
	return NULL;
      }

      tkey = PyTuple_GetItem(tup, 0);
      if (!tkey)
	return NULL;
      tval = PyTuple_GetItem(tup, 1);
      if (!tval)
	return NULL;
      if (!PyString_Check(tkey) 
	|| !(tval == Py_None || PyString_Check(tval))) {
	PyErr_SetString(PyExc_TypeError, "extraopts must be (string, string) or (string, None)");
	return NULL;
      }

      opts[ix].key = PyString_AsString(tkey);
      if (tval == Py_None)
	opts[ix].val = NULL;
      else
	opts[ix].val = PyString_AsString(tval);
    }

    opts[count].key = NULL;
    opts[count].val = NULL;
  }

  res = audev_init_device(devname, ratewanted, (verbose!=0),
    (opts?opts:(&dummyopt)));
  if (!res) {
    PyErr_SetString(PyExc_IOError, "unable to initialize audio device");
    if (opts) {
      free(opts);
    }
    return NULL;
  }

  if (opts) {
    free(opts);
  }

  Py_INCREF(Py_None);
  return Py_None;
}
Example #10
0
int pygrpc_produce_op(PyObject *op, grpc_op *result) {
  static const int OP_TUPLE_SIZE = 6;
  static const int STATUS_TUPLE_SIZE = 2;
  static const int TYPE_INDEX = 0;
  static const int INITIAL_METADATA_INDEX = 1;
  static const int TRAILING_METADATA_INDEX = 2;
  static const int MESSAGE_INDEX = 3;
  static const int STATUS_INDEX = 4;
  static const int STATUS_CODE_INDEX = 0;
  static const int STATUS_DETAILS_INDEX = 1;
  static const int WRITE_FLAGS_INDEX = 5;
  int type;
  Py_ssize_t message_size;
  char *message;
  char *status_details;
  gpr_slice message_slice;
  grpc_op c_op;
  if (!PyTuple_Check(op)) {
    PyErr_SetString(PyExc_TypeError, "expected tuple op");
    return 0;
  }
  if (PyTuple_Size(op) != OP_TUPLE_SIZE) {
    char *buf;
    gpr_asprintf(&buf, "expected tuple op of length %d", OP_TUPLE_SIZE);
    PyErr_SetString(PyExc_ValueError, buf);
    gpr_free(buf);
    return 0;
  }
  type = PyInt_AsLong(PyTuple_GET_ITEM(op, TYPE_INDEX));
  if (PyErr_Occurred()) {
    return 0;
  }
  c_op.op = type;
  c_op.flags = PyInt_AsLong(PyTuple_GET_ITEM(op, WRITE_FLAGS_INDEX));
  if (PyErr_Occurred()) {
    return 0;
  }
  switch (type) {
  case GRPC_OP_SEND_INITIAL_METADATA:
    if (!pygrpc_cast_pyseq_to_send_metadata(
            PyTuple_GetItem(op, INITIAL_METADATA_INDEX),
            &c_op.data.send_initial_metadata.metadata,
            &c_op.data.send_initial_metadata.count)) {
      return 0;
    }
    break;
  case GRPC_OP_SEND_MESSAGE:
    PyString_AsStringAndSize(
        PyTuple_GET_ITEM(op, MESSAGE_INDEX), &message, &message_size);
    message_slice = gpr_slice_from_copied_buffer(message, message_size);
    c_op.data.send_message = grpc_raw_byte_buffer_create(&message_slice, 1);
    gpr_slice_unref(message_slice);
    break;
  case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
    /* Don't need to fill in any other fields. */
    break;
  case GRPC_OP_SEND_STATUS_FROM_SERVER:
    if (!pygrpc_cast_pyseq_to_send_metadata(
            PyTuple_GetItem(op, TRAILING_METADATA_INDEX),
            &c_op.data.send_status_from_server.trailing_metadata,
            &c_op.data.send_status_from_server.trailing_metadata_count)) {
      return 0;
    }
    if (!PyTuple_Check(PyTuple_GET_ITEM(op, STATUS_INDEX))) {
      char *buf;
      gpr_asprintf(&buf, "expected tuple status in op of length %d",
                   STATUS_TUPLE_SIZE);
      PyErr_SetString(PyExc_ValueError, buf);
      gpr_free(buf);
      return 0;
    }
    c_op.data.send_status_from_server.status = PyInt_AsLong(
        PyTuple_GET_ITEM(PyTuple_GET_ITEM(op, STATUS_INDEX), STATUS_CODE_INDEX));
    status_details = PyString_AsString(
        PyTuple_GET_ITEM(PyTuple_GET_ITEM(op, STATUS_INDEX), STATUS_DETAILS_INDEX));
    if (PyErr_Occurred()) {
      return 0;
    }
    c_op.data.send_status_from_server.status_details =
        gpr_malloc(strlen(status_details) + 1);
    strcpy((char *)c_op.data.send_status_from_server.status_details,
           status_details);
    break;
  case GRPC_OP_RECV_INITIAL_METADATA:
    c_op.data.recv_initial_metadata = gpr_malloc(sizeof(grpc_metadata_array));
    grpc_metadata_array_init(c_op.data.recv_initial_metadata);
    break;
  case GRPC_OP_RECV_MESSAGE:
    c_op.data.recv_message = gpr_malloc(sizeof(grpc_byte_buffer *));
    break;
  case GRPC_OP_RECV_STATUS_ON_CLIENT:
    c_op.data.recv_status_on_client.trailing_metadata =
        gpr_malloc(sizeof(grpc_metadata_array));
    grpc_metadata_array_init(c_op.data.recv_status_on_client.trailing_metadata);
    c_op.data.recv_status_on_client.status =
        gpr_malloc(sizeof(grpc_status_code *));
    c_op.data.recv_status_on_client.status_details =
        gpr_malloc(sizeof(char *));
    *c_op.data.recv_status_on_client.status_details = NULL;
    c_op.data.recv_status_on_client.status_details_capacity =
        gpr_malloc(sizeof(size_t));
    *c_op.data.recv_status_on_client.status_details_capacity = 0;
    break;
  case GRPC_OP_RECV_CLOSE_ON_SERVER:
    c_op.data.recv_close_on_server.cancelled = gpr_malloc(sizeof(int));
    break;
  default:
    return 0;
  }
  *result = c_op;
  return 1;
}
Example #11
0
/*
    Returns new reference that must be decref'd.
*/
static PyObject*
obexserver_notifynewrequest(OBEXServer *self, obex_object_t *obj, int obex_cmd, int *respcode)
{
    PyObject *resp;
    PyObject *respheaders;
    PyObject *tmpfileobj;

    PyObject *reqheaders;
    int nonhdrdata_len;
    PyObject *nonhdrdata_obj;
    uint8_t *nonhdrdata;

    DEBUG("%s() cmd=%d\n", __func__, obex_cmd);

    if (self->notifiednewrequest) {
        DEBUG("\tAlready called cb_newrequest");
        return NULL;
    }

    if (self->cb_newrequest == NULL) {  /* shouldn't happen */
        obexserver_errorstr(self, PyExc_IOError, "cb_newrequest is NULL");
        return NULL;
    }

    reqheaders = lightblueobex_readheaders(self->obex, obj);
    if (reqheaders == NULL) {
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading request headers");
        return NULL;
    }

    nonhdrdata_len = OBEX_ObjectGetNonHdrData(obj, &nonhdrdata);
    if (nonhdrdata_len < 0) {
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading non-header data");
        return NULL;
    }

    nonhdrdata_obj = PyBuffer_FromMemory(nonhdrdata,
                                         (Py_ssize_t)nonhdrdata_len);
    if (nonhdrdata_obj == NULL) {
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading non-header buffer");
        return NULL;
    }

    resp = PyObject_CallFunction(self->cb_newrequest, "iOOO",
                                 obex_cmd, reqheaders, nonhdrdata_obj,
                                 (self->hasbodydata ? Py_True : Py_False));
    Py_DECREF(nonhdrdata_obj);
    self->notifiednewrequest = 1;

    if (resp == NULL) {
        DEBUG("\terror calling cb_newrequest\n");
        obexserver_errorfetch(self);
        return NULL;
    }

    if ( !PyTuple_Check(resp) || PyTuple_Size(resp) < 3 ||
            !PyInt_Check(PyTuple_GetItem(resp, 0)) ||
            !PyDict_Check(PyTuple_GetItem(resp, 1)) ) {
        obexserver_errorstr(self, PyExc_TypeError,
                            "callback must return (int, dict, fileobj | None) tuple");
        return NULL;
    }

    tmpfileobj = PyTuple_GetItem(resp, 2);

    if (obex_cmd == OBEX_CMD_PUT && self->hasbodydata &&
            !PyObject_HasAttrString(tmpfileobj, "write")) {
        obexserver_errorstr(self, PyExc_ValueError,
                            "specified file object does not have 'write' method for Put request");
        return NULL;
    }

    if (obex_cmd == OBEX_CMD_GET &&
            !PyObject_HasAttrString(tmpfileobj, "read")) {
        obexserver_errorstr(self, PyExc_ValueError,
                            "specified file object does not have 'read' method for Get request");
        return NULL;
    }

    *respcode = PyInt_AsLong(PyTuple_GetItem(resp, 0));
    if (PyErr_Occurred()) {
        PyErr_Clear();
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading returned response code");
        return NULL;
    }

    Py_XDECREF(self->fileobj);
    Py_INCREF(tmpfileobj);
    self->fileobj = tmpfileobj;

    respheaders = PyTuple_GetItem(resp, 1);
    Py_INCREF(respheaders);
    return respheaders;
}
/**
 *********************************************************************
 * This function will invoke aerospike_batch_get_bins to get filtered
 * bins from all the records in a batches.
 *
 * @param self                    AerospikeClient object
 * @param py_keys                 List of keys passed on by user
 * @param py_bins                 List of filter bins passed on by user
 * @param py_policy               User specified Policy dictionary
 *
 *********************************************************************
 **/
static
PyObject * AerospikeClient_Select_Many_Invoke(
    AerospikeClient * self,
    PyObject * py_keys, PyObject * py_bins, PyObject * py_policy)
{
    // Python Return Value
    PyObject * py_recs = NULL;

    // Aerospike Client Arguments
    as_error err;
    as_policy_batch policy;
    as_policy_batch * batch_policy_p = NULL;
    Py_ssize_t bins_size = 0;
    char **filter_bins = NULL;
    bool has_batch_index = false;

    // Unicode object's pool
    UnicodePyObjects u_objs;
    u_objs.size = 0;
    int i = 0;

    // Initialize error
    as_error_init(&err);

    if (!self || !self->as) {
        as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object");
        goto CLEANUP;
    }

    if (!self->is_conn_16) {
        as_error_update(&err, AEROSPIKE_ERR_CLUSTER, "No connection to aerospike cluster");
        goto CLEANUP;
    }

    // Check the type of bins and get it's size
    // i.e. number of bins provided
    if (py_bins != NULL && PyList_Check(py_bins)) {
        bins_size    = PyList_Size(py_bins);
    }
    else if (py_bins != NULL && PyTuple_Check(py_bins)) {
        bins_size    = PyTuple_Size(py_bins);
    }
    else {
        as_error_update(&err, AEROSPIKE_ERR_PARAM, "Filter bins should be specified as a list or tuple.");
        goto CLEANUP;
    }

    filter_bins = (char **)malloc(sizeof(long int) * bins_size);

    for (i = 0; i < bins_size; i++) {
        PyObject *py_bin = NULL;
        if(PyList_Check(py_bins)) {
            py_bin = PyList_GetItem(py_bins, i);
        }
        if(PyTuple_Check(py_bins)) {
            py_bin = PyTuple_GetItem(py_bins, i);
        }
        if (PyUnicode_Check(py_bin)) {
            // Store the unicode object into a pool
            // It is DECREFed at later stages
            // So, no need of DECREF here.
            filter_bins[i] = PyStr_AsString(
                                 store_unicode_bins(&u_objs, PyUnicode_AsUTF8String(py_bin)));
        }
        else if (PyStr_Check(py_bin)) {
            filter_bins[i]    = PyStr_AsString(py_bin);
        }
        else {
            as_error_update(&err, AEROSPIKE_ERR_PARAM, "Bin name should be a string or unicode string.");
            goto CLEANUP;
        }
    }

    // Convert python policy object to as_policy_batch
    pyobject_to_policy_batch(&err, py_policy, &policy, &batch_policy_p,
                             &self->as->config.policies.batch);
    if ( err.code != AEROSPIKE_OK ) {
        goto CLEANUP;
    }

    has_batch_index = aerospike_has_batch_index(self->as);
    if (has_batch_index) {
        py_recs = batch_select_aerospike_batch_read(&err, self, py_keys, batch_policy_p, filter_bins, bins_size);
    } else {
        py_recs = batch_select_aerospike_batch_get(&err, self, py_keys, batch_policy_p, filter_bins, bins_size);
    }

CLEANUP:

    if (filter_bins != NULL) {
        free(filter_bins);
    }

    // DECREFed all the unicode objects stored in Pool
    for ( i = 0; i< u_objs.size; i++) {
        Py_DECREF(u_objs.ob[i]);
    }

    if ( err.code != AEROSPIKE_OK ) {
        PyObject * py_err = NULL;
        error_to_pyobject(&err, &py_err);
        PyObject *exception_type = raise_exception(&err);
        if(PyObject_HasAttrString(exception_type, "key")) {
            PyObject_SetAttrString(exception_type, "key", py_keys);
        }
        if(PyObject_HasAttrString(exception_type, "bin")) {
            PyObject_SetAttrString(exception_type, "bin", Py_None);
        }
        PyErr_SetObject(exception_type, py_err);
        Py_DECREF(py_err);
        return NULL;
    }
    return py_recs;
}
/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_select_aerospike_batch_get(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char **filter_bins, Py_ssize_t bins_size)
{
    PyObject * py_recs = NULL;

    as_batch batch;
    bool batch_initialised = false;

    // Convert python keys list to as_key ** and add it to as_batch.keys
    // keys can be specified in PyList or PyTuple
    if ( py_keys != NULL && PyList_Check(py_keys) ) {
        Py_ssize_t size = PyList_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_init(&batch, size);

        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {

            PyObject * py_key = PyList_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
        Py_ssize_t size = PyTuple_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_init(&batch, size);
        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {
            PyObject * py_key = PyTuple_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else {
        as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
        goto CLEANUP;
    }

    // Invoke C-client API
    aerospike_batch_get_bins(self->as, err, batch_policy_p,
                             &batch, (const char **) filter_bins, bins_size,
                             (aerospike_batch_read_callback) batch_select_cb,
                             py_recs);

CLEANUP:
    if (batch_initialised == true) {
        // We should destroy batch object as we are using 'as_batch_init' for initialisation
        // Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
        // is necessary.
        as_batch_destroy(&batch);
    }

    return py_recs;
}
/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_select_aerospike_batch_read(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char** filter_bins, Py_ssize_t bins_size)
{
    PyObject * py_recs = NULL;

    as_batch_read_records records;

    as_batch_read_record* record = NULL;
    bool batch_initialised = false;

    // Convert python keys list to as_key ** and add it to as_batch.keys
    // keys can be specified in PyList or PyTuple
    if ( py_keys != NULL && PyList_Check(py_keys) ) {
        Py_ssize_t size = PyList_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_read_inita(&records, size);

        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {

            PyObject * py_key = PyList_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            record = as_batch_read_reserve(&records);

            pyobject_to_key(err, py_key, &record->key);
            if (bins_size) {
                record->bin_names = filter_bins;
                record->n_bin_names = bins_size;
            } else {
                record->read_all_bins = true;
            }

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
        Py_ssize_t size = PyTuple_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_read_inita(&records, size);
        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {
            PyObject * py_key = PyTuple_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            record = as_batch_read_reserve(&records);

            pyobject_to_key(err, py_key, &record->key);
            if (bins_size) {
                record->bin_names = filter_bins;
                record->n_bin_names = bins_size;
            } else {
                record->read_all_bins = true;
            }

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else {
        as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
        goto CLEANUP;
    }

    // Invoke C-client API
    if (aerospike_batch_read(self->as, err, batch_policy_p, &records) != AEROSPIKE_OK)
    {
        goto CLEANUP;
    }
    batch_select_recs(err, &records, &py_recs);

CLEANUP:
    if (batch_initialised == true) {
        // We should destroy batch object as we are using 'as_batch_init' for initialisation
        // Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
        // is necessary.
        as_batch_read_destroy(&records);
    }

    return py_recs;
}
Example #15
0
/**
 * pyg_flags_get_value:
 * @flag_type: the GType of the flag.
 * @obj: a Python object representing the flag value
 * @val: a pointer to the location to store the integer representation of the flag.
 *
 * Converts a Python object to the integer equivalent.  The conversion
 * will depend on the type of the Python object.  If the object is an
 * integer, it is passed through directly.  If it is a string, it will
 * be treated as a full or short flag name as defined in the GType.
 * If it is a tuple, then the items are treated as strings and ORed
 * together.
 *
 * Returns: 0 on success or -1 on failure
 */
gint
pyg_flags_get_value(GType flag_type, PyObject *obj, gint *val)
{
    GFlagsClass *fclass = NULL;
    gint res = -1;

    g_return_val_if_fail(val != NULL, -1);
    if (!obj) {
	*val = 0;
	res = 0;
    } else if (PYGLIB_PyLong_Check(obj)) {
	*val = PYGLIB_PyLong_AsLong(obj);
	res = 0;
    } else if (PyLong_Check(obj)) {
        *val = PyLong_AsLongLong(obj);
        res = 0;
    } else if (PYGLIB_PyUnicode_Check(obj)) {
	GFlagsValue *info;
	char *str = PYGLIB_PyUnicode_AsString(obj);

	if (flag_type != G_TYPE_NONE)
	    fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type));
	else {
	    PyErr_SetString(PyExc_TypeError, "could not convert string to flag because there is no GType associated to look up the value");
	    res = -1;
	}
	info = g_flags_get_value_by_name(fclass, str);
	g_type_class_unref(fclass);

	if (!info)
	    info = g_flags_get_value_by_nick(fclass, str);
	if (info) {
	    *val = info->value;
	    res = 0;
	} else {
	    PyErr_SetString(PyExc_TypeError, "could not convert string");
	    res = -1;
	}
    } else if (PyTuple_Check(obj)) {
	int i, len;

	len = PyTuple_Size(obj);
	*val = 0;
	res = 0;

	if (flag_type != G_TYPE_NONE)
	    fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type));
	else {
	    PyErr_SetString(PyExc_TypeError, "could not convert string to flag because there is no GType associated to look up the value");
	    res = -1;
	}

	for (i = 0; i < len; i++) {
	    PyObject *item = PyTuple_GetItem(obj, i);
	    char *str = PYGLIB_PyUnicode_AsString(item);
	    GFlagsValue *info = g_flags_get_value_by_name(fclass, str);

	    if (!info)
		info = g_flags_get_value_by_nick(fclass, str);
	    if (info) {
		*val |= info->value;
	    } else {
		PyErr_SetString(PyExc_TypeError, "could not convert string");
		res = -1;
		break;
	    }
	}
	g_type_class_unref(fclass);
    } else {
	PyErr_SetString(PyExc_TypeError,
			"flag values must be strings, ints, longs, or tuples");
	res = -1;
    }
    return res;
}
Example #16
0
static int
_same_vals_helper(PyObject *v1, PyObject *v2)
{
    PyTypeObject *typ1, *typ2;
    if (v1 == v2) return 0;   // 0 -> items are equal
    typ1 = v1->ob_type;
    typ2 = v2->ob_type;
    if (typ1 != typ2) return 1;
    if (typ1 == &PyDict_Type) {
        PyObject *key;
        PyObject *value;
        XXX_Py_ssize_t pos = 0;

        if (PyDict_Size(v1) != PyDict_Size(v2)) {
            return 1;
        }
        while (PyDict_Next(v1, &pos, &key, &value)) {
            // note: when compiling the above line I get the following warning, hopefully harmless:
            // samevalshelp.c:49: warning: passing argument 2 of ‘PyDict_Next’ from incompatible pointer type
            // [bruce 090206, compiling on Mac OS 10.5.6, pyrexc version 0.9.6.4]
            PyObject *value2 = PyDict_GetItem(v2, key);
            if (value2 == NULL) {
                return 1;
            }
            if (_same_vals_helper(value, value2)) {
                return 1;
            }
        }
        return 0;
    } else if (typ1 == &PyList_Type) {
        int i, n;

        n = PyList_Size(v1);
        if (n != PyList_Size(v2)) {
            return 1;
        }
        for (i = 0; i < n; i++)
            if (_same_vals_helper(PyList_GetItem(v1, i),
                                 PyList_GetItem(v2, i)))
                return 1;
        return 0;
    } else if (typ1 == &PyTuple_Type) {
        int i, n;

        n = PyTuple_Size(v1);
        if (n != PyTuple_Size(v2)) {
            return 1;
        }
        for (i = 0; i < n; i++)
            if (_same_vals_helper(PyTuple_GetItem(v1, i),
                                 PyTuple_GetItem(v2, i)))
                return 1;
        return 0;
    } else if (arrayType != NULL && typ1 == arrayType) {
        PyArrayObject *x = (PyArrayObject *) v1;
        PyArrayObject *y = (PyArrayObject *) v2;
        int i;
        int elementSize;
        int *indices;
        int topDimension;
        char *xdata;
        char *ydata;
        int objectCompare = 0;

        // do all quick rejects first (no loops)
        if (x->nd != y->nd) {
            // number of dimensions doesn't match
            return 1;
            // note that a (1 x X) array can never equal a single
            // dimensional array of length X.
        }
        if (x->descr->type_num != y->descr->type_num) {
            // type of elements doesn't match
            return 1;
        }
        if (x->descr->type_num == PyArray_OBJECT) {
            objectCompare = 1;
        }
        elementSize = x->descr->elsize;
        if (elementSize != y->descr->elsize) {
            // size of elements doesn't match (shouldn't happen if
            // types match!)
            return 1;
        }
        for (i = x->nd - 1; i >= 0; i--) {
            if (x->dimensions[i] != y->dimensions[i])
                // shapes don't match
                return 1;
        }
        // we do a lot of these, so handle them early
        if (x->nd == 1 && !objectCompare && x->strides[0]==elementSize && y->strides[0]==elementSize) {
            // contiguous one dimensional array of non-objects
            return memcmp(x->data, y->data, elementSize * x->dimensions[0]) ? 1 : 0;
        }
        if (x->nd == 0) {
            // scalar, just compare one element
            if (objectCompare) {
                return _same_vals_helper(*(PyObject **)x->data, *(PyObject **)y->data);
            } else {
                return memcmp(x->data, y->data, elementSize) ? 1 : 0;
            }
        }
        // If we decide we can't do alloca() for some reason, we can
        // either have a fixed maximum dimensionality, or use alloc
        // and free.
        indices = (int *)alloca(sizeof(int) * x->nd);
        for (i = x->nd - 1; i >= 0; i--) {
            indices[i] = 0;
        }
        topDimension = x->dimensions[0];
        while (indices[0] < topDimension) {
            xdata = x->data;
            ydata = y->data;
            for (i = 0; i < x->nd; i++) {
                xdata += indices[i] * x->strides[i];
                ydata += indices[i] * y->strides[i];
            }
            if (objectCompare) {
                if (_same_vals_helper(*(PyObject **)xdata, *(PyObject **)ydata)) {
                    return 1;
                }
            } else if (memcmp(xdata, ydata, elementSize) != 0) {
                // element mismatch
                return 1;
            }
            // step to next element
            for (i = x->nd - 1; i>=0; i--) {
                indices[i]++;
                if (i == 0 || indices[i] < x->dimensions[i]) {
                    break;
                }
                indices[i] = 0;
            }
        }
        // all elements match
        return 0;
    }
#if 0
    XX({
        if (typ1 == &PyInstance_Type) {
            PyInstanceObject *x = (PyInstanceObject *) v1;
            PyObject_Print(x->in_class->cl_name, stdout, 0);
        } else {
            PyObject_Print((PyObject*)typ1, stdout, 0);
        }
        if (typ1->tp_compare == NULL)
            printf(" (rich comparison)");
        printf("\n");
    });
Example #17
0
std::shared_ptr<MI::MIValue> Py2MI(PyObject* pyValue, MI_Type valueType)
{
    if (pyValue == Py_None)
    {
        return std::make_shared<MI::MIValue>(valueType);
    }
    if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyBool_Type)))
    {
        return MI::MIValue::FromBoolean(PyObject_IsTrue(pyValue) ? MI_TRUE : MI_FALSE);
    }
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyLong_Type)))
    {
        switch (valueType)
        {
        case MI_BOOLEAN:
            return MI::MIValue::FromBoolean(PyLong_AsLong(pyValue) != 0);
        case MI_UINT8:
            return MI::MIValue::FromUint8((MI_Uint8)PyLong_AsUnsignedLong(pyValue));
        case MI_SINT8:
            return MI::MIValue::FromSint8((MI_Sint8)PyLong_AsLong(pyValue));
        case MI_UINT16:
            return MI::MIValue::FromUint16((MI_Uint16)PyLong_AsUnsignedLong(pyValue));
        case MI_SINT16:
            return MI::MIValue::FromSint16((MI_Sint16)PyLong_AsLong(pyValue));
        case MI_CHAR16:
            return MI::MIValue::FromChar16((MI_Char16)PyLong_AsLong(pyValue));
        case MI_UINT32:
            return MI::MIValue::FromUint32(PyLong_AsUnsignedLong(pyValue));
        case MI_SINT32:
            return MI::MIValue::FromSint32(PyLong_AsLong(pyValue));
        case MI_UINT64:
            return MI::MIValue::FromUint64(PyLong_AsUnsignedLongLong(pyValue));
        case MI_SINT64:
            return MI::MIValue::FromSint64(PyLong_AsLongLong(pyValue));
        case MI_REAL32:
            return MI::MIValue::FromReal32((MI_Real32)PyLong_AsDouble(pyValue));
        case MI_REAL64:
            return MI::MIValue::FromReal64(PyLong_AsDouble(pyValue));
        case MI_STRING:
            return Py2StrMIValue(pyValue);
        default:
            throw MI::TypeConversionException();
        }
    }
#ifndef IS_PY3K
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyInt_Type)))
    {
        switch (valueType)
        {
        case MI_BOOLEAN:
            return MI::MIValue::FromBoolean(PyInt_AsLong(pyValue) != 0);
        case MI_UINT8:
            return MI::MIValue::FromUint8((MI_Uint8)PyInt_AsLong(pyValue));
        case MI_SINT8:
            return MI::MIValue::FromSint8((MI_Sint8)PyInt_AsLong(pyValue));
        case MI_UINT16:
            return MI::MIValue::FromUint16((MI_Uint16)PyInt_AsLong(pyValue));
        case MI_SINT16:
            return MI::MIValue::FromSint16((MI_Sint16)PyInt_AsLong(pyValue));
        case MI_CHAR16:
            return MI::MIValue::FromChar16((MI_Char16)PyLong_AsLong(pyValue));
        case MI_UINT32:
            return MI::MIValue::FromUint32((MI_Uint32)PyInt_AsLong(pyValue));
        case MI_SINT32:
            return MI::MIValue::FromSint32((MI_Sint32)PyInt_AsLong(pyValue));
        case MI_UINT64:
            return MI::MIValue::FromUint64((MI_Uint64)PyInt_AsLong(pyValue));
        case MI_SINT64:
            return MI::MIValue::FromSint64((MI_Sint64)PyInt_AsLong(pyValue));
        case MI_REAL32:
            return MI::MIValue::FromReal32((MI_Real32)PyInt_AsLong(pyValue));
        case MI_REAL64:
            return MI::MIValue::FromReal64((MI_Real64)PyInt_AsLong(pyValue));
        case MI_STRING:
            return Py2StrMIValue(pyValue);
        default:
            throw MI::TypeConversionException();
        }
    }
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyString_Type)))
    {
        switch (valueType)
        {
        case MI_STRING:
            return MI::MIValue::FromString(std::string(PyString_AsString(pyValue)));
        case MI_SINT8:
        case MI_UINT8:
        case MI_SINT16:
        case MI_UINT16:
        case MI_CHAR16:
        case MI_SINT32:
        case MI_UINT32:
        case MI_SINT64:
        case MI_UINT64:
        case MI_REAL32:
        case MI_REAL64:
            return Str2PyLong2MI(PyString_AsString(pyValue), valueType);
        default:
            throw MI::TypeConversionException();
        }
    }
#endif
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyUnicode_Type)))
    {
        switch (valueType)
        {
        case MI_STRING:
            return MI::MIValue::FromString(Py2WString(pyValue));
        case MI_SINT8:
        case MI_UINT8:
        case MI_SINT16:
        case MI_UINT16:
        case MI_CHAR16:
        case MI_SINT32:
        case MI_UINT32:
        case MI_SINT64:
        case MI_UINT64:
        case MI_REAL32:
        case MI_REAL64:
        {
            auto str = Py2WString(pyValue);
            std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
            return Str2PyLong2MI((char*)cv.to_bytes(str).c_str(), valueType);
        }
        default:
            throw MI::TypeConversionException();
        }
    }
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&InstanceType)))
    {
        switch (valueType)
        {
        case MI_INSTANCE:
            // TODO: Set the same ScopeContextOwner as the container instance / class
            return MI::MIValue::FromInstance(*((Instance*)pyValue)->instance);
        case MI_REFERENCE:
            // TODO: Set the same ScopeContextOwner as the container instance / class
            return MI::MIValue::FromReference(*((Instance*)pyValue)->instance);
        default:
            throw MI::TypeConversionException();
        }
    }
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyTuple_Type)) ||
             PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyList_Type)))
    {
        bool isTuple = PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyTuple_Type)) != 0;
        Py_ssize_t size = 0;
        if (isTuple)
        {
            size = PyTuple_Size(pyValue);
        }
        else
        {
            size = PyList_Size(pyValue);
        }

        MI_Type itemType = (MI_Type)(valueType ^ MI_ARRAY);
        auto value = MI::MIValue::CreateArray((unsigned)size, valueType);

        for (Py_ssize_t i = 0; i < size; i++)
        {
            PyObject* pyObj = NULL;
            if (isTuple)
            {
                pyObj = PyTuple_GetItem(pyValue, i);
            }
            else
            {
                pyObj = PyList_GetItem(pyValue, i);
            }

            auto& tmpValue = Py2MI(pyObj, itemType);
            value->SetArrayItem(*tmpValue, (unsigned)i);
        }
        return value;
    }
    else
    {
        switch (valueType)
        {
        case MI_STRING:
            return Py2StrMIValue(pyValue);
        default:
            throw MI::TypeConversionException();
        }
    }
}
Example #18
0
static gboolean
gplp_func_desc_load (GOPluginService *service,
		     char const *name,
		     GnmFuncDescriptor *res)
{
	ServiceLoaderDataFunctionGroup *loader_data;
	PyObject *fn_info_obj;

	g_return_val_if_fail (IS_GNM_PLUGIN_SERVICE_FUNCTION_GROUP (service), FALSE);
	g_return_val_if_fail (name != NULL, FALSE);

	loader_data = g_object_get_data (G_OBJECT (service), "loader_data");
	SWITCH_TO_PLUGIN (go_plugin_service_get_plugin (service));
	fn_info_obj = PyDict_GetItemString (loader_data->python_fn_info_dict,
					    (gchar *) name);
	if (fn_info_obj == NULL) {
		gnm_python_clear_error_if_needed (SERVICE_GET_LOADER (service)->py_object);
		return FALSE;
	}

	if (PyTuple_Check (fn_info_obj)) {
		PyObject *python_args, *python_arg_names;
		PyObject *python_fn;

		if (PyTuple_Size (fn_info_obj) == 3 &&
		    (python_args = PyTuple_GetItem (fn_info_obj, 0)) != NULL &&
			PyString_Check (python_args) &&
		    (python_arg_names = PyTuple_GetItem (fn_info_obj, 1)) != NULL &&
		    PyString_Check (python_arg_names) &&
		    (python_fn = PyTuple_GetItem (fn_info_obj, 2)) != NULL &&
		    PyFunction_Check (python_fn)) {
			res->arg_spec	= PyString_AsString (python_args);
#if 0
			res->arg_names  = PyString_AsString (python_arg_names);
#endif
			res->help	= python_function_get_gnumeric_help (
				loader_data->python_fn_info_dict, python_fn, name);
			res->fn_args	= &call_python_function_args;
			res->fn_nodes	= NULL;
			res->linker	= NULL;
			res->unlinker	= NULL;
			res->impl_status = GNM_FUNC_IMPL_STATUS_UNIQUE_TO_GNUMERIC;
			res->test_status = GNM_FUNC_TEST_STATUS_UNKNOWN;
			return TRUE;
		}

		gnm_python_clear_error_if_needed (SERVICE_GET_LOADER (service)->py_object);
		return FALSE;
	}

	if (PyFunction_Check (fn_info_obj)) {
		res->arg_spec	= "";
		res->help	= python_function_get_gnumeric_help (
			loader_data->python_fn_info_dict, fn_info_obj, name);
		res->fn_args	= NULL;
		res->fn_nodes	= &call_python_function_nodes;
		res->linker	= NULL;
		res->unlinker	= NULL;
		res->impl_status = GNM_FUNC_IMPL_STATUS_UNIQUE_TO_GNUMERIC;
		res->test_status = GNM_FUNC_TEST_STATUS_UNKNOWN;
		return TRUE;
	}

	gnm_python_clear_error_if_needed (SERVICE_GET_LOADER (service)->py_object);
	return FALSE;
}
Example #19
0
static PyObject *swi_swi(PyObject *self,PyObject *args)
{ PyObject *name,*format,*result,*v;
  int swino,carry,rno=0,j,n;
  char *swiname,*fmt,*outfmt;
  _kernel_swi_regs r;
  PyBlockObject *ao;
  if(args==NULL||!PyTuple_Check(args)||(n=PyTuple_Size(args))<2)
  { PyErr_BadArgument(); return NULL;}
  name=PyTuple_GetItem(args,0);
  if(!PyArg_Parse(name,"i",&swino))
  { PyErr_Clear();
    if(!PyArg_Parse(name,"s",&swiname)) return NULL;
    e=xos_swi_number_from_string(swiname,&swino);
    if(e) return swi_oserror();
  }
  format=PyTuple_GetItem(args,1);
  if(!PyArg_Parse(format,"s",&fmt)) return NULL;
  j=2;
  for(;;fmt++)
  { switch(*fmt)
    { case '.': rno++;continue;
      case ';':case 0: goto swicall;
      case '0':case '1':case '2':case '3':case '4':
      case '5':case '6':case '7':case '8':case '9':
        r.r[rno++]=*fmt-'0';continue;
      case '-':r.r[rno++]=-1;continue;
    }
    if(j>=n) return swi_error("Too few arguments");
    v=PyTuple_GetItem(args,j++);
    switch(*fmt)
    { case 'i':if(!PyArg_Parse(v,"i",&r.r[rno])) return NULL;
               break;
      case 's':if(!PyArg_Parse(v,"s",(char**)(&r.r[rno]))) return NULL;
               break;
      case 'b':if(!PyArg_Parse(v,"O",(PyObject**)&ao)) return NULL;
               if(!PyBlock_Check(v)) return swi_error("Not a block");
               r.r[rno]=(int)(ao->block);
               break;
      case 'e':if(!PyArg_Parse(v,"O",(PyObject**)&ao)) return NULL;
               if(!PyBlock_Check(v)) return swi_error("Not a block");
               r.r[rno]=(int)(ao->block)+ao->length;
               break;
      default:return swi_error("Odd format character");
    }
    rno++;
  }
  swicall:e=(os_error*)_kernel_swi_c(swino,&r,&r,&carry);
  if(e) return swi_oserror();
  if(*fmt==0) { Py_INCREF(Py_None);return Py_None;}
  n=0;
  for(outfmt=++fmt;*outfmt;outfmt++)  switch(*outfmt)
  { case 'i':case 's':case '*':n++;break;
    case '.':break;
    default:return swi_error("Odd format character");
  }
  if(n==0) { Py_INCREF(Py_None);return Py_None;}
  if(n!=1)
  { result=PyTuple_New(n);
    if(!result) return NULL;
  }
  rno=0;j=0;
  for(;*fmt;fmt++)
  {  switch(*fmt)
    { case 'i':v=PyInt_FromLong((long)r.r[rno++]); break;
      case 's':v=PyString_FromString((char*)(r.r[rno++])); break;
      case '.':rno++; continue;
      case '*':v=PyInt_FromLong((long)carry); break;
    }
    if(!v) goto fail;
    if(n==1) return v;
    PyTuple_SetItem(result,j,v);
    j++;
  }
  return result;
  fail:Py_DECREF(result);return 0;
}
Example #20
0
NUITKA_MAY_BE_UNUSED static inline void RAISE_EXCEPTION_WITH_TRACEBACK( PyObject **exception_type, PyObject **exception_value, PyTracebackObject **exception_tb )
{
    CHECK_OBJECT( *exception_type );
    CHECK_OBJECT( *exception_value );

    if ( *exception_tb == (PyTracebackObject *)Py_None )
    {
        Py_DECREF( *exception_tb );
        *exception_tb = NULL;
    }

    // Non-empty tuple exceptions are the first element.
    while (unlikely( PyTuple_Check( *exception_type ) && PyTuple_Size( *exception_type ) > 0 ))
    {
        *exception_type = PyTuple_GET_ITEM( *exception_type, 0 );
    }

    if ( PyExceptionClass_Check( *exception_type ) )
    {
        NORMALIZE_EXCEPTION( exception_type, exception_value, exception_tb );
#if PYTHON_VERSION >= 270
        if (unlikely( !PyExceptionInstance_Check( *exception_value ) ))
        {
            PyErr_Format(
                PyExc_TypeError,
                "calling %s() should have returned an instance of BaseException, not '%s'",
                ((PyTypeObject *)*exception_type)->tp_name,
                Py_TYPE( *exception_value )->tp_name
            );

            Py_DECREF( *exception_type );
            Py_XDECREF( *exception_value );
            Py_XDECREF( *exception_tb );

            FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
        }
#endif

        return;
    }
    else if ( PyExceptionInstance_Check( *exception_type ) )
    {
        if (unlikely( *exception_value != NULL && *exception_value != Py_None ))
        {
            PyErr_Format(
                PyExc_TypeError,
                "instance exception may not have a separate value"
            );

            Py_DECREF( *exception_type );
            Py_XDECREF( *exception_value );
            Py_XDECREF( *exception_tb );

            FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );

            return;
        }

        // The type is rather a value, so we are overriding it here.
        *exception_value = *exception_type;
        *exception_type = PyExceptionInstance_Class( *exception_type );
        Py_INCREF( *exception_type );

        return;
    }
    else
    {
        PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
        FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
        return;
    }
}
Example #21
0
//============================================================================
// FUNCTION        : Log_Call
//============================================================================
static PyObject* Log_Call( PyObject* self, PyObject* args, PyObject* kargs )
{
    char* message     = (char*)"";
    LogSeverity sev   = LOG_INFO;
    LogLevel    level = LOG_PROC;

    int size = PyTuple_Size(args);
    if (size==1)
    {
        if (!PyArg_ParseTuple(args,"s", &message))
        {
            THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
        }
        if (kargs != NULL)
        {
            if (PyDict_Contains( kargs, KEY_SEVERITY ))
            {
                std::string value = PYSTR(PyDict_GetItemString( kargs, "severity" ));
                sev = str_to_sev.find(value)->second;

            }
            if (PyDict_Contains( kargs, KEY_LEVEL ))
            {
                std::string value = PYSTR(PyDict_GetItemString( kargs, "level" ));
                level = str_to_lev.find(value)->second;
            }
        }
    }
    else if (size == 2)
    {
        char* psev = (char*) "";
        if (!PyArg_ParseTuple(args,"ss", &message, &psev))
        {
            THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
        }
        if (kargs != NULL)
        {
            if (PyDict_Contains( kargs, KEY_LEVEL ))
            {
                std::string value = PYSTR(PyDict_GetItemString( kargs, "level" ));
                level = str_to_lev.find(value)->second;
            }
        }
        sev = str_to_sev.find(STR(psev))->second;
    }
    else if (size == 3)
    {
        char* psev = (char*) "";
        char* plev = (char*) "";
        if (!PyArg_ParseTuple(args,"sss", &message, &psev, &plev))
        {
            THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
        }
        sev = str_to_sev.find(STR(psev))->second;
        level = str_to_lev.find(STR(plev))->second;
    }
    else
    {
        THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
    }
    SPELLlog::instance().log(message, sev, level);
    Py_RETURN_NONE;
}
Example #22
0
NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_TYPE( PyObject **exception_type, PyObject **exception_value, PyTracebackObject **exception_tb )
{
    *exception_value = NULL;
    *exception_tb = NULL;

#if PYTHON_VERSION < 300
    // Next, repeatedly, replace a tuple exception with its first item
    while( PyTuple_Check( *exception_type ) && PyTuple_Size( *exception_type ) > 0 )
    {
         PyObject *tmp = *exception_type;
         *exception_type = PyTuple_GET_ITEM( *exception_type, 0 );
         Py_INCREF( *exception_type );
         Py_DECREF( tmp );
    }
#endif

    if ( PyExceptionClass_Check( *exception_type ) )
    {
        NORMALIZE_EXCEPTION( exception_type, exception_value, exception_tb );
#if PYTHON_VERSION >= 270
        if (unlikely( !PyExceptionInstance_Check( *exception_value ) ))
        {
            PyErr_Format(
                PyExc_TypeError,
                "calling %s() should have returned an instance of BaseException, not '%s'",
                ((PyTypeObject *)*exception_type)->tp_name,
                Py_TYPE( *exception_value )->tp_name
            );

            Py_DECREF( *exception_type );
            Py_DECREF( *exception_value );

            FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
            return;
        }
#endif

#if PYTHON_VERSION >= 300
        CHAIN_EXCEPTION( *exception_value );
#endif
        return;
    }
    else if ( PyExceptionInstance_Check( *exception_type ) )
    {
        *exception_value = *exception_type;
        *exception_type = PyExceptionInstance_Class( *exception_type );
        Py_INCREF( *exception_type );

#if PYTHON_VERSION >= 300
        CHAIN_EXCEPTION( *exception_value );

        // TODO: Ever true?
        if ( *exception_tb )
        {
            PyTracebackObject *prev = (PyTracebackObject *)PyException_GetTraceback( *exception_value );

            if ( prev != NULL )
            {
                assert( (*exception_tb)->tb_next == NULL );
                (*exception_tb)->tb_next = prev;
            }

            PyException_SetTraceback( *exception_value, (PyObject *)(*exception_tb ? *exception_tb : (PyTracebackObject *)Py_None ) );
        }

        *exception_tb = (PyTracebackObject *)PyException_GetTraceback( *exception_value );
#endif

        return;
    }
    else
    {
        Py_DECREF( *exception_type );

        PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( *exception_type )->tp_name );
        FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
        return;
    }
}
Example #23
0
static PyObject *searchio_createIndex(PyObject *self, PyObject *args)
{
    /* grab the filename, number of documents, and our index */
    const char *filename = NULL;
    uint32_t numDocuments = 0;
    PyObject *index = NULL;
    
    if (!PyArg_ParseTuple(args, "sIO", &filename, &numDocuments, &index))
        return NULL;
    
    /* open the index file */
    int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC);
    if (fd == -1)
        return PyErr_SetFromErrno(PyExc_IOError);
    
    fchmod(fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
    size_t totalWritten = 0;
    
    /* get the number of terms in the index */
    Py_ssize_t numTermsPy = PyDict_Size(index);
    uint32_t numTerms = 0;
    if (numTermsPy > 0 && numTermsPy < UINT32_MAX)
        numTerms = (uint32_t)numTermsPy;
    else
    {
        PyErr_SetString(PyExc_MemoryError, "the number of terms is greater than UINT32_MAX (or less than 0)");
        return NULL;
    }
    
    /* write a document header */
    searchio_index_header_t header = {htonl(numDocuments), htonl(numTerms), 0};
    totalWritten += write(fd, (void *)&header, sizeof(header));
    
    /* loop once over index to write term entries */
    PyObject *indexKeys = PyDict_Keys(index);
    Py_ssize_t indexKeyLen = PyList_Size(indexKeys);
    
    uint32_t postingsOffset = 0;
    uint32_t keyIdx;
    for (keyIdx = 0; keyIdx < indexKeyLen; keyIdx++)
    {
        PyObject *key = PyList_GetItem(indexKeys, keyIdx);
        PyObject *value = PyDict_GetItem(index, key);
        
        /* create a term entry */
        searchio_index_term_t term;
        term.postingsOffset = htonl(postingsOffset);
        
        /* pull out the term, its df, and a reference to the postings list */
        const char *termStr = PyString_AS_STRING(key);
        /*PyObject *pydf = PyList_GetItem(value, 0);
        PyObject *postings = PyList_GetItem(value, 1);*/
        PyObject *postings = value;
        Py_ssize_t postingsLen = PyList_Size(postings);
        
        /* fill in the header */
        size_t termLen = strlen(termStr);
        /* term.df = htonl(PyInt_AsUnsignedLongMask(pydf)); */
        term.df = htonl((uint32_t)postingsLen);
        term.numDocumentsInPostings = htonl((uint32_t)postingsLen);
        term.termLength = htons((uint16_t)termLen);
        
        /* write out the header, and its term */
        totalWritten += write(fd, (void *)&term, sizeof(term));
        totalWritten += write(fd, termStr, termLen);
        
        /* determine the on-disk size of the posting list */
        uint32_t totalSize = 0;
        Py_ssize_t i;
        for (i = 0; i < postingsLen; i++)
        {
            PyObject *entryTuple = PyList_GetItem(postings, i);
            PyObject *positions = PyTuple_GetItem(entryTuple, 2);
            Py_ssize_t positionLen = PyTuple_Size(positions);
            
            /* on-disk size is size of a posting struct, plus sizeof(uint32_t) * positions */
            totalSize += (uint32_t)sizeof(searchio_index_posting_t) + (uint32_t)(positionLen * sizeof(uint32_t));
        }
        
        /* increment the postings offset */
        postingsOffset += totalSize;
    }
    
    /* update the postings offset */
    header.postingsStart = htonl(totalWritten);
    
    /* loop again to write postings lists */
    for (keyIdx = 0; keyIdx < indexKeyLen; keyIdx++)
    {
        PyObject *key = PyList_GetItem(indexKeys, keyIdx);
        PyObject *value = PyDict_GetItem(index, key);
        
        /* get the postings list and its length */
        /* PyObject *postings = PyList_GetItem(value, 1); */
        PyObject *postings = value;
        Py_ssize_t postingsLen = PyList_Size(postings);
        
        /* loop over each entry in the postings list and write it out */
        Py_ssize_t i;
        for (i = 0; i < postingsLen; i++)
        {
            /* pull out some values */
            PyObject *entryTuple = PyList_GetItem(postings, i);
            PyObject *pypageID = PyTuple_GetItem(entryTuple, 0);
            PyObject *pywf = PyTuple_GetItem(entryTuple, 1);
            PyObject *positions = PyTuple_GetItem(entryTuple, 2);
            Py_ssize_t positionsLen = PyTuple_Size(positions);
            
            /* create a header */
            searchio_index_posting_t posting;
            posting.pageID = htonl((uint32_t)PyInt_AsUnsignedLongMask(pypageID));
            posting.wf = htonl((uint32_t)(PyFloat_AsDouble(pywf) * SEARCHIO_WF_SCALE));
            posting.numPositions = htonl((uint32_t)positionsLen);
            
            /* write the header */
            write(fd, (void *)&posting, sizeof(posting));
            
            /* write each of the positions */
            Py_ssize_t j;
            for (j = 0; j < positionsLen; j++)
            {
                PyObject *item = PyTuple_GetItem(positions, j);
                uint32_t p = htonl((uint32_t)PyInt_AsUnsignedLongMask(item));
                write(fd, (void *)&p, sizeof(p));
            }
        }
    }
    
    /* rewrite the header with correct offsets */
    lseek(fd, 0, SEEK_SET);
    write(fd, (void *)&header, sizeof(header));
    
    /* close the index */
    close(fd);
    
    /* no meaningful return value here */
    Py_RETURN_NONE;
}
Example #24
0
/**
 *******************************************************************************************************
 * Callback for as_info_foreach().
 *
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param node                  The current as_node object for which the
 *                              callback is fired by c client.
 * @param req                   The info request string.
 * @param res                   The info response string for current node.
 * @pram udata                  The callback udata containing the host_lookup
 *                              array and the return zval to be populated with
 *                              an entry for current node's info response with
 *                              the node's ID as the key.
 *
 * Returns true if callback is successful, Otherwise false.
 *******************************************************************************************************
 */
static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata)
{
	PyObject * py_err = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_out = NULL;
	foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata;
	struct sockaddr_in* addr = NULL;


	if ( err && err->code != AEROSPIKE_OK ) {
		as_error_update(err, err->code, NULL);
        goto CLEANUP;
	}
	else if ( res != NULL ) {
		char * out = strchr(res,'\t');
		if ( out != NULL ) {
			out++;
			py_out = PyString_FromString(out);
		}
		else {
			py_out = PyString_FromString(res);
		}
	}

	if ( py_err == NULL ) {
		Py_INCREF(Py_None);
		py_err = Py_None;
	}

	if ( py_out == NULL ) {
		Py_INCREF(Py_None);
		py_out = Py_None;
	}

	PyObject * py_res = PyTuple_New(2);
	PyTuple_SetItem(py_res, 0, py_err);
	PyTuple_SetItem(py_res, 1, py_out);

	if(udata_ptr->host_lookup_p) {
		PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p;
			if ( py_hosts && PyList_Check(py_hosts) ) {
				addr = as_node_get_address((as_node *)node);
				int size = (int) PyList_Size(py_hosts);
				for ( int i = 0; i < size && i < AS_CONFIG_HOSTS_SIZE; i++ ) {
					char * host_addr = NULL;
					int port = -1;
					PyObject * py_host = PyList_GetItem(py_hosts, i);
					if ( PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2 ) {
						PyObject * py_addr = PyTuple_GetItem(py_host,0);
						PyObject * py_port = PyTuple_GetItem(py_host,1);
						if (PyUnicode_Check(py_addr)) {
							py_ustr = PyUnicode_AsUTF8String(py_addr);
							host_addr = PyString_AsString(py_ustr);
						} else if ( PyString_Check(py_addr) ) {
							host_addr = PyString_AsString(py_addr);
						} else {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect");
							if (py_res) {
								Py_DECREF(py_res);
							}
							return false;
						}
						if ( PyInt_Check(py_port) ) {
							port = (uint16_t) PyInt_AsLong(py_port);
						}
						else if ( PyLong_Check(py_port) ) {
							port = (uint16_t) PyLong_AsLong(py_port);
						} else {
							break;
						}
						char ip_port[IP_PORT_MAX_LEN];
						inet_ntop(addr->sin_family, &(addr->sin_addr), ip_port, INET_ADDRSTRLEN);
						if( (!strcmp(host_addr,ip_port)) && (port
												== ntohs(addr->sin_port))) {
							PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
							PyDict_SetItemString(py_nodes, node->name, py_res);
						}	
					}
				}
			} else if ( !PyList_Check( py_hosts )){
				as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Hosts should be specified in a list.");
				goto CLEANUP;
			}
	} else {
		PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
		PyDict_SetItemString(py_nodes, node->name, py_res);
	}
	Py_DECREF(py_res);
CLEANUP:
	if ( udata_ptr->error.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject( &udata_ptr->error, &py_err);
		PyObject *exception_type = raise_exception(&udata_ptr->error);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return true;
}
PyObject * dataconv_WriteFromOutTuple(PyObject *self, PyObject *args)
{
	PyObject *obArgTypes;
	PyObject *obArgType;
	PyObject *obRetValues;
	PyObject *obPtr;
	PyObject *obOutValue;
	VARTYPE vtArgType;
	BYTE *pbArgs;
	BYTE *pbArg;
	Py_ssize_t cArgs;
	UINT uiIndirectionLevel = 0;
	Py_ssize_t i;
	
	if (!PyArg_ParseTuple(args, "OOO:WriteFromOutTuple", &obRetValues, &obArgTypes, &obPtr))
		return NULL;

	pbArgs = (BYTE *)PyLong_AsVoidPtr(obPtr);
	assert(pbArgs);
	if (!pbArgs)
		return NULL;

	// Nothing to do, oh darn.
	if (obRetValues == Py_None || obArgTypes == Py_None)
	{
		Py_INCREF(Py_None);
		return Py_None;
	}

	if (!PyTuple_Check(obArgTypes))
	{
		PyErr_SetString(PyExc_TypeError, "OLE type description - expecting a tuple");
		return NULL;
	}

	cArgs = PyTuple_Size(obArgTypes);
	if (!PyTuple_Check(obRetValues) && (UINT)PyTuple_Size(obRetValues) != cArgs)
	{
		PyErr_Format(PyExc_TypeError, "Expecting a tuple of length %d or None.", cArgs);
		return NULL;
	}
	
	for(i = 0 ; i < cArgs; i++)
	{
		obArgType = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 0);
		vtArgType = (VARTYPE)PyInt_AS_LONG(obArgType);


		// The following types aren't supported:
		// SAFEARRAY *: This requires support for SAFEARRAYs as a
		//              Python extensions type so we can update the SAFEARRAY
		//              in place.
		// VT_LPWSTR:   This just hasn't been written yet.
		// VT_LPSTR:    This just hasn't been written yet.
		// VT_LPWSTR | VT_BYREF:
		// VT_LPSTR  | VT_BYREF:
		//              These can't be supported since we don't know the correct
		//              memory allocation policy.

		// Find the start of the argument.
		pbArg = pbArgs + PyInt_AS_LONG(PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 1));
		obOutValue = PyTuple_GET_ITEM(obRetValues, i);
	
		if (vtArgType & VT_ARRAY)
		{
			VARENUM rawVT = (VARENUM)(vtArgType & VT_TYPEMASK);
			if (vtArgType & VT_BYREF)
			{
				SAFEARRAY **ppsa = *(SAFEARRAY ***)pbArg;
				SAFEARRAY *psa;
				if (!VALID_BYREF_MISSING(obOutValue))
				{
					if (!PyCom_SAFEARRAYFromPyObject(obOutValue, ppsa, rawVT))
					{
						goto Error;
					}
				}
				else
				{
					SAFEARRAYBOUND rgsabound[1];
					rgsabound[0].lLbound = 0;
					rgsabound[0].cElements = 1;
					psa = SafeArrayCreate(rawVT, 1, rgsabound);
					*ppsa = psa;
				}
			}
			else
			{
				// We can't convert this in place... Ack...
				PyErr_SetString(
					PyExc_TypeError,
					"Inplace SAFEARRAY mucking isn't allowed, doh!");
				goto Error;
				
				SAFEARRAY *psa = *(SAFEARRAY **)pbArg;
				// Here we're updating an existing SafeArray.
				// so we need to handle it very carefully....
				SafeArrayDestroy(psa);
				if (!PyCom_SAFEARRAYFromPyObject(obOutValue, &psa, rawVT))
					return NULL;
			}
		}
			
		// All done with safe array handling.

		PyObject *obUse = NULL;

		switch (vtArgType) {
		case VT_VARIANT | VT_BYREF:
		{
			VARIANT *pvar = *(VARIANT **)pbArg;
			VariantClear(pvar);
			if (!VALID_BYREF_MISSING(obOutValue)) {
				PyCom_VariantFromPyObject(obOutValue, pvar);
			}
			else
			{
				V_VT(pvar) = VT_NULL;
			}
			break;
		}
		case VT_BSTR:
		{
			// This is the normal "BSTR" case, we can't
			// allocate a new BSTR we have to back patch the one
			// thats already there...
			BSTR bstr = *(BSTR *)pbArg;
			BSTR bstrT;
			UINT cch = SysStringLen(bstr);
			if ( PyString_Check(obOutValue) || PyUnicode_Check(obOutValue) )
			{
				if ( !PyWinObject_AsBstr(obOutValue, &bstrT) )
				{
					goto Error;
				}
			}
			else
			{
				// Use str(object) instead!
				obUse = PyObject_Str(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				if ( !PyWinObject_AsBstr(obUse, &bstrT) )
				{
					goto Error;
				}
			}
			
			if (SysStringLen(bstrT) > cch)
			{
				PyErr_Format(
					PyExc_ValueError,
					"Return value[%d] with type BSTR was "
					"longer than the input value: %d",
					i,
					cch);
				goto Error;
			}
				
			// Ok, now we know theres enough room in the source BSTR to
			// modify the sucker in place.
			wcscpy(bstr, bstrT);

			// Free the temp BSTR.
			SysFreeString(bstrT);
			break;
		}
		case VT_BSTR | VT_BYREF:
		{
			BSTR *pbstr = *(BSTR **)pbArg;
			BSTR bstrT = NULL;
			SysFreeString(*pbstr);

			*pbstr = NULL;
			
			if ( PyString_Check(obOutValue) || PyUnicode_Check(obOutValue) )
			{
				if ( !PyWinObject_AsBstr(obOutValue, &bstrT) )
				{
					goto Error;
				}
			}
			else
			{
				// Use str(object) instead!
				obUse = PyObject_Str(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				if (!PyWinObject_AsBstr(obUse, &bstrT) )
				{
					goto Error;
				}
			}
			*pbstr = bstrT;
			break;
		}
		case VT_ERROR | VT_BYREF:
		case VT_HRESULT | VT_BYREF:
		case VT_I4 | VT_BYREF:
		{
			INT *pi = *(INT **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pi = PyInt_AsLong(obUse);
			if (*pi == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI4 | VT_BYREF:
		{
			UINT *pui = *(UINT **)pbArg;
			// special care here as we could be > sys.maxint,
			// in which case we must work with longs.
			// Avoiding PyInt_AsUnsignedLongMask as it doesn't
			// exist in 2.2.
			if (PyLong_Check(obOutValue)) {
				*pui = PyLong_AsUnsignedLong(obOutValue);
			} else {
				// just do the generic "number" thing.
				obUse = PyNumber_Int(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				*pui = (UINT)PyInt_AsLong(obUse);
			}
			if (*pui == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_I2 | VT_BYREF:
		{
			short *ps = *(short **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*ps = (short)PyInt_AsLong(obUse);
			if (*ps == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI2 | VT_BYREF:
		{
			unsigned short *pus = *(unsigned short **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pus = (unsigned short)PyInt_AsLong(obUse);
			if (*pus == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_I1 | VT_BYREF:
		{
			signed char *pb = *(signed char **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pb = (signed char)PyInt_AsLong(obUse);
			if (*pb == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI1 | VT_BYREF:
		{
			BYTE *pb = *(BYTE **)pbArg;
			BYTE *pbOutBuffer = NULL;
			if (PyString_Check(obOutValue))
			{
				pbOutBuffer = (BYTE *)PyString_AS_STRING(obOutValue);
				Py_ssize_t cb = PyString_GET_SIZE(obOutValue);
				memcpy(pb, pbOutBuffer, cb);
			}
			// keep this after string check since string can act as buffers
			else if (obOutValue->ob_type->tp_as_buffer)
			{
				DWORD cb;
				if (!PyWinObject_AsReadBuffer(obOutValue, (void **)&pbOutBuffer, &cb))
					goto Error;
				memcpy(pb, pbOutBuffer, cb);
			}
			else
			{
				obUse = PyNumber_Int(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				*pb = (BYTE)PyInt_AsLong(obUse);
				if (*pb == (UINT)-1 && PyErr_Occurred())
					goto Error;
			}
			break;
		}
		case VT_BOOL | VT_BYREF:
		{
			VARIANT_BOOL *pbool = *(VARIANT_BOOL **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pbool = PyInt_AsLong(obUse) ? VARIANT_TRUE : VARIANT_FALSE;
			if (*pbool == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_R8 | VT_BYREF:
		{
			double *pdbl = *(double **)pbArg;
			obUse = PyNumber_Float(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pdbl = PyFloat_AsDouble(obUse);
			break;
		}
		case VT_R4 | VT_BYREF:
		{
			float *pfloat = *(float **)pbArg;
			obUse = PyNumber_Float(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pfloat = (float)PyFloat_AsDouble(obUse);
			break;
		}
		case VT_DISPATCH | VT_BYREF:
		{
			PyObject *obIID = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 3);
			IID iid = IID_IDispatch;
			if (obIID != NULL && obIID!=Py_None)
				PyWinObject_AsIID(obIID, &iid);
			IDispatch **pdisp = *(IDispatch ***)pbArg;
			if (!PyCom_InterfaceFromPyInstanceOrObject(
				obOutValue,
				iid,
				(void **)pdisp,
				TRUE))
			{
				goto Error;
			}
			// COM Reference added by InterfaceFrom...
			break;
		}
		case VT_UNKNOWN | VT_BYREF:
		{
			PyObject *obIID = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 3);
			IID iid = IID_IUnknown;
			if (obIID != NULL && obIID!=Py_None)
				PyWinObject_AsIID(obIID, &iid);
			IUnknown **punk = *(IUnknown ***)pbArg;
			if (!PyCom_InterfaceFromPyInstanceOrObject(
				obOutValue,
				iid,
				(void **)punk, TRUE))
			{
				goto Error;
			}
			// COM Reference added by InterfaceFrom...
			break;
		}
		case VT_DATE | VT_BYREF:
		{
			DATE *pdbl = *(DATE **)pbArg;
			if ( !PyWinObject_AsDATE(obOutValue, pdbl) )
			{
				goto Error;
			}
			break;
		}
		case VT_CY | VT_BYREF:
		{
			CY *pcy = *(CY **)pbArg;
			if (!PyObject_AsCurrency(obOutValue, pcy))
				goto Error;
			break;
		}
		case VT_I8 | VT_BYREF:
		{
			LARGE_INTEGER *pi64 = *(LARGE_INTEGER **)pbArg;
			if (!PyWinObject_AsLARGE_INTEGER(obOutValue, pi64))
			{
				goto Error;
			}
			break;
		}
		case VT_UI8 | VT_BYREF:
		{
			ULARGE_INTEGER *pui64 = *(ULARGE_INTEGER **)pbArg;
			if (!PyWinObject_AsULARGE_INTEGER(obOutValue, pui64))
			{
				goto Error;
			}
			break;
		}
		default:
			// could try default, but this error indicates we need to
			// beef up the VARIANT support, rather than default.
			PyErr_Format(PyExc_TypeError, "The VARIANT type is unknown (0x%x).",
			             vtArgType);
			goto Error;
		}
		
		Py_XDECREF(obUse);
	}

	Py_INCREF(Py_None);
	return Py_None;
Error:
	return NULL;
}
Example #26
0
/*
 * For each positional argument and each argument in a possible "out"
 * keyword, look for overrides of the standard ufunc behaviour, i.e.,
 * non-default __array_ufunc__ methods.
 *
 * Returns the number of overrides, setting corresponding objects
 * in PyObject array ``with_override`` and the corresponding
 * __array_ufunc__ methods in ``methods`` (both using new references).
 *
 * Only the first override for a given class is returned.
 *
 * returns -1 on failure.
 */
NPY_NO_EXPORT int
PyUFunc_WithOverride(PyObject *args, PyObject *kwds,
                     PyObject **with_override, PyObject **methods)
{
    int i;
    int num_override_args = 0;
    int narg, nout = 0;
    PyObject *out_kwd_obj;
    PyObject **arg_objs, **out_objs;

    narg = PyTuple_Size(args);
    if (narg < 0) {
        return -1;
    }
    arg_objs = PySequence_Fast_ITEMS(args);

    nout = get_out_objects(kwds, &out_kwd_obj, &out_objs);
    if (nout < 0) {
        return -1;
    }

    for (i = 0; i < narg + nout; ++i) {
        PyObject *obj;
        int j;
        int new_class = 1;

        if (i < narg) {
            obj = arg_objs[i];
        }
        else {
            obj = out_objs[i - narg];
        }
        /*
         * Have we seen this class before?  If so, ignore.
         */
        for (j = 0; j < num_override_args; j++) {
            new_class = (Py_TYPE(obj) != Py_TYPE(with_override[j]));
            if (!new_class) {
                break;
            }
        }
        if (new_class) {
            /*
             * Now see if the object provides an __array_ufunc__. However, we should
             * ignore the base ndarray.__ufunc__, so we skip any ndarray as well as
             * any ndarray subclass instances that did not override __array_ufunc__.
             */
            PyObject *method = get_non_default_array_ufunc(obj);
            if (method == NULL) {
                continue;
            }
            if (method == Py_None) {
                PyErr_Format(PyExc_TypeError,
                             "operand '%.200s' does not support ufuncs "
                             "(__array_ufunc__=None)",
                             obj->ob_type->tp_name);
                Py_DECREF(method);
                goto fail;
            }
            Py_INCREF(obj);
            with_override[num_override_args] = obj;
            methods[num_override_args] = method;
            ++num_override_args;
        }
    }
    return num_override_args;

fail:
    for (i = 0; i < num_override_args; i++) {
        Py_DECREF(with_override[i]);
        Py_DECREF(methods[i]);
    }
    return -1;
}
PyCodeObject *
PyCode_New(int argcount, int nlocals, int stacksize, int flags,
           PyObject *code, PyObject *consts, PyObject *names,
           PyObject *varnames, PyObject *freevars, PyObject *cellvars,
           PyObject *filename, PyObject *name, int firstlineno,
           PyObject *lnotab)
{
    PyCodeObject *co;
    Py_ssize_t i;
    /* Check argument types */
    if (argcount < 0 || nlocals < 0 ||
        code == NULL ||
        consts == NULL || !PyTuple_Check(consts) ||
        names == NULL || !PyTuple_Check(names) ||
        varnames == NULL || !PyTuple_Check(varnames) ||
        freevars == NULL || !PyTuple_Check(freevars) ||
        cellvars == NULL || !PyTuple_Check(cellvars) ||
        name == NULL || !PyString_Check(name) ||
        filename == NULL || !PyString_Check(filename) ||
        lnotab == NULL || !PyString_Check(lnotab) ||
        !PyObject_CheckReadBuffer(code)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    intern_strings(names);
    intern_strings(varnames);
    intern_strings(freevars);
    intern_strings(cellvars);
    /* Intern selected string constants */
    for (i = PyTuple_Size(consts); --i >= 0; ) {
        PyObject *v = PyTuple_GetItem(consts, i);
        if (!PyString_Check(v))
            continue;
        if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
            continue;
        PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
    }
    co = PyObject_NEW(PyCodeObject, &PyCode_Type);
    if (co != NULL) {
        co->co_argcount = argcount;
        co->co_nlocals = nlocals;
        co->co_stacksize = stacksize;
        co->co_flags = flags;
        Py_INCREF(code);
        co->co_code = code;
        Py_INCREF(consts);
        co->co_consts = consts;
        Py_INCREF(names);
        co->co_names = names;
        Py_INCREF(varnames);
        co->co_varnames = varnames;
        Py_INCREF(freevars);
        co->co_freevars = freevars;
        Py_INCREF(cellvars);
        co->co_cellvars = cellvars;
        Py_INCREF(filename);
        co->co_filename = filename;
        Py_INCREF(name);
        co->co_name = name;
        co->co_firstlineno = firstlineno;
        Py_INCREF(lnotab);
        co->co_lnotab = lnotab;
        co->co_zombieframe = NULL;
    }
    return co;
}
Example #28
0
static void
pyg_signal_class_closure_marshal(GClosure *closure,
				 GValue *return_value,
				 guint n_param_values,
				 const GValue *param_values,
				 gpointer invocation_hint,
				 gpointer marshal_data)
{
    PyGILState_STATE state;
    GObject *object;
    PyObject *object_wrapper;
    GSignalInvocationHint *hint = (GSignalInvocationHint *)invocation_hint;
    gchar *method_name, *tmp;
    PyObject *method;
    PyObject *params, *ret;
    guint i, len;

    state = pyglib_gil_state_ensure();

    g_return_if_fail(invocation_hint != NULL);
    /* get the object passed as the first argument to the closure */
    object = g_value_get_object(&param_values[0]);
    g_return_if_fail(object != NULL && G_IS_OBJECT(object));

    /* get the wrapper for this object */
    object_wrapper = pygobject_new(object);
    g_return_if_fail(object_wrapper != NULL);

    /* construct method name for this class closure */
    method_name = g_strconcat("do_", g_signal_name(hint->signal_id), NULL);

    /* convert dashes to underscores.  For some reason, g_signal_name
     * seems to convert all the underscores in the signal name to
       dashes??? */
    for (tmp = method_name; *tmp != '\0'; tmp++)
	if (*tmp == '-') *tmp = '_';

    method = PyObject_GetAttrString(object_wrapper, method_name);
    g_free(method_name);

    if (!method) {
	PyErr_Clear();
	Py_DECREF(object_wrapper);
	pyglib_gil_state_release(state);
	return;
    }
    Py_DECREF(object_wrapper);

    /* construct Python tuple for the parameter values; don't copy boxed values
       initially because we'll check after the call to see if a copy is needed. */
    params = PyTuple_New(n_param_values - 1);
    for (i = 1; i < n_param_values; i++) {
	PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);

	/* error condition */
	if (!item) {
	    Py_DECREF(params);
	    pyglib_gil_state_release(state);
	    return;
	}
	PyTuple_SetItem(params, i - 1, item);
    }

    ret = PyObject_CallObject(method, params);

    /* Copy boxed values if others ref them, this needs to be done regardless of
       exception status. */
    len = PyTuple_Size(params);
    for (i = 0; i < len; i++) {
	PyObject *item = PyTuple_GetItem(params, i);
	if (item != NULL && PyObject_TypeCheck(item, &PyGBoxed_Type)
	    && item->ob_refcnt != 1) {
	    PyGBoxed* boxed_item = (PyGBoxed*)item;
	    if (!boxed_item->free_on_dealloc) {
		boxed_item->boxed = g_boxed_copy(boxed_item->gtype, boxed_item->boxed);
		boxed_item->free_on_dealloc = TRUE;
	    }
	}
    }

    if (ret == NULL) {
	PyErr_Print();
	Py_DECREF(method);
	Py_DECREF(params);
	pyglib_gil_state_release(state);
	return;
    }
    Py_DECREF(method);
    Py_DECREF(params);
    if (return_value)
	pyg_value_from_pyobject(return_value, ret);
    Py_DECREF(ret);
    pyglib_gil_state_release(state);
}
Example #29
0
int bld_py_sector_setattr(PyObject *self, char *attr_name, PyObject *value)
{
        int active;
        PyObject *on_enter, *on_leave, *on_hit, *on_walk_on, *on_walk_out;
        double active_surf_x, active_surf_y, active_surf_z;
        int too_steep, action_area;
        double too_steep_angle;
        int num_pieces;
        double piece_x, piece_y, piece_z;
        const char *piece_name;
        PyObject *piece_x_obj, *piece_y_obj, *piece_z_obj;
        PyObject *break_info, *piece_obj, *piece_coord_obj, *piece_name_obj;
        int code;

        PyErr_Clear();
        if (value == NULL) {
                PyErr_SetString(
                        PyExc_AttributeError, "can't delete Sector attributes"
                );
                return -1;
        }

        if (!strcmp(attr_name, "Active")) {
                if (!PyArg_Parse(value, "i", &active)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                code = SetSectorIntProperty(
                        ((bld_py_sector_t *)self)->sectorID, SEC_INT_ACTIVE, 0,
                        active
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "OnEnter")) {
                if(!PyArg_Parse(value, "O", &on_enter)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                if (!PyCallable_Check(on_enter))
                        on_enter = NULL;

                code = SetSectorFuncProperty(
                        ((bld_py_sector_t *)self)->sectorID, SEC_FNC_ON_ENTER,
                        0, on_enter
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "OnLeave")) {
                if (!PyArg_Parse(value, "O", &on_leave)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                if (!PyCallable_Check(on_leave))
                        on_leave = NULL;

                code = SetSectorFuncProperty(
                        ((bld_py_sector_t *)self)->sectorID, SEC_FNC_ON_LEAVE,
                        0, on_leave
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "OnHit")) {
                if (!PyArg_Parse(value, "O", &on_hit)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                if (!PyCallable_Check(on_hit))
                        on_hit = NULL;

                code = SetSectorFuncProperty(
                        ((bld_py_sector_t *)self)->sectorID, SEC_FNC_ON_HIT, 0,
                        on_hit
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "OnWalkOn")) {
                if (!PyArg_Parse(value, "O", &on_walk_on)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                if (!PyCallable_Check(on_walk_on))
                        on_walk_on = NULL;

                code = SetSectorFuncProperty(
                        ((bld_py_sector_t *)self)->sectorID,
                        SEC_FNC_ON_WALK_ON, 0, on_walk_on
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "ActiveSurface")) {
                if (!PyArg_Parse(
                        value, "(ddd)", &active_surf_x, &active_surf_y,
                        &active_surf_z
                )) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                code = SetSectorVectorProperty(
                        ((bld_py_sector_t *)self)->sectorID,
                        SEC_VEC_ACTIVE_SURFACE, 0, active_surf_x, active_surf_y,
                        active_surf_z
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "OnWalkOut")) {
                if (!PyArg_Parse(value, "O", &on_walk_out)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                if (!PyCallable_Check(on_walk_out))
                        on_walk_out = NULL;

                code = SetSectorFuncProperty(
                        ((bld_py_sector_t *)self)->sectorID,
                        SEC_FNC_ON_WALK_OUT, 0, on_walk_out
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "TooSteep")) {
                if (!PyArg_Parse(value, "i", &too_steep)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                code = SetSectorIntProperty(
                        ((bld_py_sector_t *)self)->sectorID, SEC_INT_TOO_STEEP,
                        0, too_steep
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "TooSteepAngle")) {
                if (!PyArg_Parse(value, "d", &too_steep_angle)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                code = SetSectorFloatProperty(
                        ((bld_py_sector_t *)self)->sectorID,
                        SEC_FLT_TOO_STEEP_ANGLE, 0, too_steep_angle
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        if (!strcmp(attr_name, "BreakInfo")) {
                int i;

                if (!PyArg_Parse(value, "O", &break_info)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                if (!PyTuple_Check(break_info)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                num_pieces = PyTuple_Size(break_info);

                SetSectorIntProperty(
                        ((bld_py_sector_t *)self)->sectorID, SEC_INT_NUM_PIECES,
                        0, num_pieces
                );

                for(i = 0; i < num_pieces; i++) {
                        piece_obj = PyTuple_GET_ITEM(break_info, i);

                        piece_name_obj = PyTuple_GET_ITEM(piece_obj, 0);
                        piece_coord_obj = PyTuple_GET_ITEM(piece_obj, 1);

                        piece_x_obj = PyTuple_GET_ITEM(piece_coord_obj, 0);
                        piece_y_obj = PyTuple_GET_ITEM(piece_coord_obj, 1);
                        piece_z_obj = PyTuple_GET_ITEM(piece_coord_obj, 2);

                        piece_name = PyString_AsString(piece_name_obj);
                        piece_x = PyFloat_AsDouble(piece_x_obj);
                        piece_y = PyFloat_AsDouble(piece_y_obj);
                        piece_z = PyFloat_AsDouble(piece_z_obj);

                        SetSectorVectorProperty(
                                ((bld_py_sector_t *)self)->sectorID,
                                SEC_VEC_PIECE, i, piece_x, piece_y, piece_z
                        );

                        SetSectorStringProperty(
                                ((bld_py_sector_t *)self)->sectorID,
                                SEC_STR_PIECE_NAME, i, piece_name
                        );
                }

                return 0;
        }

        if (!strcmp(attr_name, "ActionArea")) {
                if (!PyArg_Parse(value, "i", &action_area)) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                code = SetSectorIntProperty(
                        ((bld_py_sector_t *)self)->sectorID,
                        SEC_INT_ACTION_AREA, 0, action_area
                );
                if (code != 1) {
                        PyErr_SetString(PyExc_AttributeError, "Invalid Param.");
                        return -1;
                }

                return 0;
        }

        PyErr_SetString(PyExc_AttributeError, "Not implemented");
        return -1;
}
Example #30
0
static int
add_all_headers(write_bucket *bucket, PyObject *fast_headers, int hlen, client_t *client)
{
    int i;
    PyObject *tuple = NULL;
    PyObject *obj1 = NULL, *obj2 = NULL;
    PyObject *bytes1 = NULL, *bytes2 = NULL;
    char *name = NULL, *value = NULL;
    Py_ssize_t namelen, valuelen;
#ifdef PY3
    int o;
#endif

    if(likely(fast_headers != NULL)){
        for (i = 0; i < hlen; i++) {

            tuple = PySequence_Fast_GET_ITEM(fast_headers, i);

            if (unlikely( !PyTuple_Check(tuple))) {
                PyErr_Format(PyExc_TypeError, "list of tuple values "
                             "expected, value of type %.200s found",
                             tuple->ob_type->tp_name);
                goto error;
            }


            if (unlikely(PyTuple_GET_SIZE(tuple) != 2)) {
                PyErr_Format(PyExc_ValueError, "tuple of length 2 "
                             "expected, length is %d",
                             (int)PyTuple_Size(tuple));
                goto error;
            }

            obj1 = PyTuple_GET_ITEM(tuple, 0);
            obj2 = PyTuple_GET_ITEM(tuple, 1);
            if(unlikely(!obj1)){
                goto error;
            }
            if(unlikely(!obj2)){
                goto error;
            }
            bytes1 = wsgi_to_bytes(obj1);
            if(unlikely(PyBytes_AsStringAndSize(bytes1, &name, &namelen) == -1)){
                goto error;
            }

            //value
            bytes2 = wsgi_to_bytes(obj2);
            if(unlikely(PyBytes_AsStringAndSize(bytes2, &value, &valuelen) == -1)){
                goto error;
            }

            if (unlikely(strchr(name, ':') != 0)) {
                PyErr_Format(PyExc_ValueError, "header name may not contains ':'"
                             "response header with name '%s' and value '%s'",
                             name, value);
                goto error;
            }

            if (unlikely(strchr(name, '\n') != 0 || strchr(value, '\n') != 0)) {
                PyErr_Format(PyExc_ValueError, "embedded newline in "
                             "response header with name '%s' and value '%s'",
                             name, value);
                goto error;
            }

            if (!strcasecmp(name, "Server") || !strcasecmp(name, "Date")) {
                continue;
            }

            if (client->content_length_set != 1 && !strcasecmp(name, "Content-Length")) {
                char *v = value;
                long l = 0;

                errno = 0;
                l = strtol(v, &v, 10);
                if (*v || errno == ERANGE || l < 0) {
                    PyErr_SetString(PyExc_ValueError,
                                    "invalid content length");
                    goto error;
                }

                client->content_length_set = 1;
                client->content_length = l;
            }
            DEBUG("response header %s:%d : %s:%d",name, (int)namelen, value, (int)valuelen);
            add_header(bucket, name, namelen, value, valuelen);
#ifdef PY3
            //keep bytes string 
            o = PyList_Append(bucket->temp1, bytes1);
            if(o != -1){
                o = PyList_Append(bucket->temp1, bytes2);
                if(o == -1){
                    goto error;
                }
            }else{
                goto error;
            }
#endif
            Py_XDECREF(bytes1);
            Py_XDECREF(bytes2);
        }

    }else{
        RDEBUG("WARN header is lost...");
    }

    return 1;
error:
    if (PyErr_Occurred()){
        /* write_error_log(__FILE__, __LINE__); */
        call_error_logger();
    }
    Py_XDECREF(bytes1);
    Py_XDECREF(bytes2);
    return -1;
}