Example #1
0
// this code is heavily adapted from the paint license, which is in
// the file paint.license (BSD compatible) included in this
// distribution.  TODO, add license file to MANIFEST.in and CVS
Py::Object _png_module::write_png(const Py::Tuple& args)
{
    args.verify_length(4, 5);

    FILE *fp = NULL;
    bool close_file = false;
    Py::Object buffer_obj = Py::Object(args[0]);
    PyObject* buffer = buffer_obj.ptr();
    if (!PyObject_CheckReadBuffer(buffer))
    {
        throw Py::TypeError("First argument must be an rgba buffer.");
    }

    const void* pixBufferPtr = NULL;
    Py_ssize_t pixBufferLength = 0;
    if (PyObject_AsReadBuffer(buffer, &pixBufferPtr, &pixBufferLength))
    {
        throw Py::ValueError("Couldn't get data from read buffer.");
    }

    png_byte* pixBuffer = (png_byte*)pixBufferPtr;
    int width = (int)Py::Int(args[1]);
    int height = (int)Py::Int(args[2]);

    if (pixBufferLength < width * height * 4)
    {
        throw Py::ValueError("Buffer and width, height don't seem to match.");
    }

    Py::Object py_fileobj = Py::Object(args[3]);
#if PY3K
    int fd = PyObject_AsFileDescriptor(py_fileobj.ptr());
    PyErr_Clear();
#endif
    if (py_fileobj.isString())
    {
        std::string fileName = Py::String(py_fileobj);
        const char *file_name = fileName.c_str();
        if ((fp = fopen(file_name, "wb")) == NULL)
        {
            throw Py::RuntimeError(
                Printf("Could not open file %s", file_name).str());
        }
        close_file = true;
    }
#if PY3K
    else if (fd != -1)
    {
        fp = fdopen(fd, "w");
    }
#else
    else if (PyFile_CheckExact(py_fileobj.ptr()))
    {
        fp = PyFile_AsFile(py_fileobj.ptr());
    }
#endif
    else
    {
        PyObject* write_method = PyObject_GetAttrString(
            py_fileobj.ptr(), "write");
        if (!(write_method && PyCallable_Check(write_method)))
        {
            Py_XDECREF(write_method);
            throw Py::TypeError(
                "Object does not appear to be a 8-bit string path or a Python file-like object");
        }
        Py_XDECREF(write_method);
    }

    png_bytep *row_pointers = NULL;
    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;

    try
    {
        struct png_color_8_struct sig_bit;
        png_uint_32 row;

        row_pointers = new png_bytep[height];
        for (row = 0; row < (png_uint_32)height; ++row)
        {
            row_pointers[row] = pixBuffer + row * width * 4;
        }

        png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
        if (png_ptr == NULL)
        {
            throw Py::RuntimeError("Could not create write struct");
        }

        info_ptr = png_create_info_struct(png_ptr);
        if (info_ptr == NULL)
        {
            throw Py::RuntimeError("Could not create info struct");
        }

        if (setjmp(png_jmpbuf(png_ptr)))
        {
            throw Py::RuntimeError("Error building image");
        }

        if (fp)
        {
            png_init_io(png_ptr, fp);
        }
        else
        {
            png_set_write_fn(png_ptr, (void*)py_fileobj.ptr(),
                             &write_png_data, &flush_png_data);
        }
        png_set_IHDR(png_ptr, info_ptr,
                     width, height, 8,
                     PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
                     PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

        // Save the dpi of the image in the file
        if (args.size() == 5)
        {
            double dpi = Py::Float(args[4]);
            size_t dots_per_meter = (size_t)(dpi / (2.54 / 100.0));
            png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
        }

        // this a a color image!
        sig_bit.gray = 0;
        sig_bit.red = 8;
        sig_bit.green = 8;
        sig_bit.blue = 8;
        /* if the image has an alpha channel then */
        sig_bit.alpha = 8;
        png_set_sBIT(png_ptr, info_ptr, &sig_bit);

        png_write_info(png_ptr, info_ptr);
        png_write_image(png_ptr, row_pointers);
        png_write_end(png_ptr, info_ptr);
    }
    catch (...)
    {
        if (png_ptr && info_ptr)
        {
            png_destroy_write_struct(&png_ptr, &info_ptr);
        }
        delete [] row_pointers;
        if (fp && close_file)
        {
            fclose(fp);
        }
        /* Changed calls to png_destroy_write_struct to follow
           http://www.libpng.org/pub/png/libpng-manual.txt.
           This ensures the info_ptr memory is released.
        */
        throw;
    }

    png_destroy_write_struct(&png_ptr, &info_ptr);
    delete [] row_pointers;
#if PY3K
    if (fp)
    {
        fflush(fp);
    }
#endif
    if (fp && close_file)
    {
        fclose(fp);
    }

    if (PyErr_Occurred()) {
        throw Py::Exception();
    } else {
        return Py::Object();
    }
}
Example #2
0
/**
 * This emits the error signal and resets the error state
 * of the python interpreter.
 */
void PythonScript::emit_error()
{
    // gil is necessary so other things don't continue
    GlobalInterpreterLock gil;

    // return early if nothing happened
    if (!PyErr_Occurred())
        return;

    // get the error information out
    PyObject *exception(NULL), *value(NULL), *traceback(NULL);
    PyErr_Fetch(&exception, &value, &traceback);

    // special check for system exceptions
    if (bool(exception)
            && PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)
            && PyObject_HasAttrString(exception, "code"))
    {
        // value is the return code handed to sys.exit
        long code = 0;
        if (bool(value) && PyInt_Check(value))
        {
            code = PyInt_AsLong(value);
        }

        // if we are returning 0 then cleanup and return
        if (code == 0)
        {
            // maybe shouldn't clear the error, but for now this
            // is the agreed upon behavior
            PyErr_Clear();
            Py_XDECREF(traceback);
            Py_XDECREF(exception);
            Py_XDECREF(value);
            emit finished(MSG_FINISHED);
            return;
        }
    }

    // prework on the exception handling
    PyErr_NormalizeException(&exception, &value, &traceback);
    PyErr_Clear();

    // convert the traceback into something useful
    int lineNumber = 0;
    QString filename;
    if (traceback)
    {
        PyTracebackObject* tb = (PyTracebackObject*)traceback;
        lineNumber = tb->tb_lineno;
        filename = PyString_AsString(tb->tb_frame->f_code->co_filename);
    }

    // the error message is the full (formated) traceback
    PyObject *str_repr = PyObject_Str(value);
    QString message;
    QTextStream msgStream(&message);
    if( value && str_repr )
    {
        if(exception == PyExc_SyntaxError)
        {
            msgStream << constructSyntaxErrorStr(value);
        }
        else
        {
            QString excTypeName(value->ob_type->tp_name); // This is fully qualified with the module name
            excTypeName = excTypeName.section(".", -1);
            msgStream << excTypeName << ": " << PyString_AsString(str_repr);
        }

    }
    else
    {
        msgStream << "Unknown exception has occurred.";
    }
    tracebackToMsg(msgStream, (PyTracebackObject *)(traceback));
    msgStream << "\n";

    Py_XDECREF(traceback);
    Py_XDECREF(exception);
    Py_XDECREF(value);

    emit error(msgStream.readAll(), filename, lineNumber);
}
Example #3
0
/**
 * Compile the code
 */
PyObject *PythonScript::compileToByteCode(bool for_eval)
{
    // Support for the convenient col() and cell() functions.
    // This can't be done anywhere else, because we need access to the local
    // variables self, i and j.
    if( context() )
    {
        if( context()->inherits("Table") )
        {
            // A bit of a hack, but we need either IndexError or len() from __builtins__.
            PyDict_SetItemString(localDict, "__builtins__",
                                 PyDict_GetItemString(pythonEnv()->globalDict(), "__builtins__"));
            PyObject *ret = PyRun_String(
                                "def col(c,*arg):\n"
                                "\ttry: return self.cell(c,arg[0])\n"
                                "\texcept(IndexError): return self.cell(c,i)\n"
                                "def cell(c,r):\n"
                                "\treturn self.cell(c,r)\n"
                                "def tablecol(t,c):\n"
                                "\treturn self.folder().rootFolder().table(t,True).cell(c,i)\n"
                                "def _meth_table_col_(t,c):\n"
                                "\treturn t.cell(c,i)\n"
                                "self.__class__.col = _meth_table_col_",
                                Py_file_input, localDict, localDict);
            if (ret)
                Py_DECREF(ret);
            else
                PyErr_Print();
        }
        else if(context()->inherits("Matrix"))
        {
            // A bit of a hack, but we need either IndexError or len() from __builtins__.
            PyDict_SetItemString(localDict, "__builtins__",
                                 PyDict_GetItemString(pythonEnv()->globalDict(), "__builtins__"));
            PyObject *ret = PyRun_String(
                                "def cell(*arg):\n"
                                "\ttry: return self.cell(arg[0],arg[1])\n"
                                "\texcept(IndexError): return self.cell(i,j)\n",
                                Py_file_input, localDict, localDict);
            if (ret)
                Py_DECREF(ret);
            else
                PyErr_Print();
        }
    }
    bool success(false);
    // Simplest case: Code is a single expression
    PyObject *compiledCode = Py_CompileString(codeString().c_str(), identifier().c_str(), Py_file_input);

    if( compiledCode )
    {
        success = true;
    }
    else if (for_eval)
    {
        // Code contains statements (or errors) and we want to get a return
        // value from it.
        // So we wrap the code into a function definition,
        // execute that (as Py_file_input) and store the function object in PyCode.
        // See http://mail.python.org/pipermail/python-list/2001-June/046940.html
        // for why there isn't an easier way to do this in Python.
        PyErr_Clear(); // silently ignore errors
        PyObject *key(NULL), *value(NULL);
        Py_ssize_t i(0);
        QString signature = "";
        while(PyDict_Next(localDict, &i, &key, &value))
        {
            signature.append(PyString_AsString(key)).append(",");
        }
        signature.truncate(signature.length()-1);
        std::string fdef = "def __doit__("+signature.toStdString()+"):\n";
        fdef += codeString();
        compiledCode = Py_CompileString(fdef.c_str(), identifier().c_str(), Py_file_input);
        if( compiledCode )
        {
            PyObject *tmp = PyDict_New();
            Py_XDECREF(PyEval_EvalCode((PyCodeObject*)compiledCode, localDict, tmp));
            Py_DECREF(compiledCode);
            compiledCode = PyDict_GetItemString(tmp,"__doit__");
            Py_XINCREF(compiledCode);
            Py_DECREF(tmp);
        }
        success = (compiledCode != NULL);
    }
    else
    {
    }

    if(success)
    {
        m_CodeFileObject = ((PyCodeObject*)(compiledCode))->co_filename;
    }
    else
    {
        compiledCode = NULL;
        m_CodeFileObject = NULL;
    }
    return compiledCode;
}
static PyObject *
meshFromShape(PyObject *self, PyObject *args, PyObject* kwds)
{
    try {
        PyObject *shape;

        static char* kwds_maxLength[] = {"Shape", "MaxLength",NULL};
        PyErr_Clear();
        double maxLength=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!d", kwds_maxLength,
                                        &(Part::TopoShapePy::Type), &shape, &maxLength)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setMaxLength(maxLength);
            mesher.setRegular(true);
            return new Mesh::MeshPy(mesher.createMesh());
        }

        static char* kwds_maxArea[] = {"Shape", "MaxArea",NULL};
        PyErr_Clear();
        double maxArea=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!d", kwds_maxArea,
                                        &(Part::TopoShapePy::Type), &shape, &maxArea)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setMaxArea(maxArea);
            mesher.setRegular(true);
            return new Mesh::MeshPy(mesher.createMesh());
        }

        static char* kwds_localLen[] = {"Shape", "LocalLength",NULL};
        PyErr_Clear();
        double localLen=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!d", kwds_localLen,
                                        &(Part::TopoShapePy::Type), &shape, &localLen)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setLocalLength(localLen);
            mesher.setRegular(true);
            return new Mesh::MeshPy(mesher.createMesh());
        }

        static char* kwds_deflection[] = {"Shape", "Deflection",NULL};
        PyErr_Clear();
        double deflection=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!d", kwds_deflection,
                                        &(Part::TopoShapePy::Type), &shape, &deflection)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setDeflection(deflection);
            mesher.setRegular(true);
            return new Mesh::MeshPy(mesher.createMesh());
        }

        static char* kwds_minmaxLen[] = {"Shape", "MinLength","MaxLength",NULL};
        PyErr_Clear();
        double minLen=0, maxLen=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!dd", kwds_minmaxLen,
                                        &(Part::TopoShapePy::Type), &shape, &minLen, &maxLen)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setMinMaxLengths(minLen, maxLen);
            mesher.setRegular(true);
            return new Mesh::MeshPy(mesher.createMesh());
        }

#if defined (HAVE_NETGEN)
        static char* kwds_fineness[] = {"Shape", "Fineness", "SecondOrder", "Optimize", "AllowQuad",NULL};
        PyErr_Clear();
        int fineness=0, secondOrder=0, optimize=1, allowquad=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!i|iii", kwds_fineness,
                                        &(Part::TopoShapePy::Type), &shape, &fineness,
                                        &secondOrder, &optimize, &allowquad)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Netgen);
            mesher.setFineness(fineness);
            mesher.setSecondOrder(secondOrder > 0);
            mesher.setOptimize(optimize > 0);
            mesher.setQuadAllowed(allowquad > 0);
            return new Mesh::MeshPy(mesher.createMesh());
        }

        static char* kwds_user[] = {"Shape", "GrowthRate", "SegPerEdge", "SegPerRadius", "SecondOrder", "Optimize", "AllowQuad",NULL};
        PyErr_Clear();
        double growthRate=0, nbSegPerEdge=0, nbSegPerRadius=0;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O!|dddiii", kwds_user,
                                        &(Part::TopoShapePy::Type), &shape,
                                        &growthRate, &nbSegPerEdge, &nbSegPerRadius,
                                        &secondOrder, &optimize, &allowquad)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
            mesher.setMethod(MeshPart::Mesher::Netgen);
            mesher.setGrowthRate(growthRate);
            mesher.setNbSegPerEdge(nbSegPerEdge);
            mesher.setNbSegPerRadius(nbSegPerRadius);
            mesher.setSecondOrder(secondOrder > 0);
            mesher.setOptimize(optimize > 0);
            mesher.setQuadAllowed(allowquad > 0);
            return new Mesh::MeshPy(mesher.createMesh());
        }
#endif

        PyErr_Clear();
        if (PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &shape)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->_Shape);
#if defined (HAVE_NETGEN)
            mesher.setMethod(MeshPart::Mesher::Netgen);
#else
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setRegular(true);
#endif
            return new Mesh::MeshPy(mesher.createMesh());
        }
    }
    catch (const Base::Exception& e) {
        PyErr_SetString(PyExc_Exception, e.what());
        return 0;
    }

    PyErr_SetString(PyExc_Exception,"Wrong arguments");
    return 0;
}
Example #5
0
static foreign_t python_run_script(term_t cmd, term_t fun) {
  char si[256], sf[256];
  size_t len = 255, len1 = 255;
  PyObject *pName, *pModule, *pFunc;
  PyObject *pArgs = NULL, *pValue;
  char *s;

  s = si;
  if (PL_get_nchars(cmd, &len, &s, CVT_ALL | CVT_EXCEPTION) &&
      (s = sf) != NULL &&
      PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) {

#if PY_MAJOR_VERSION < 3
    pName = PyString_FromString("rbm");
#else
    // asssumes UTF-8
    pName = PyUnicode_FromString("rbm");
#endif
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    PyErr_Clear();
    Py_DECREF(pName);

    if (pModule != NULL) {
      pFunc = PyObject_GetAttrString(pModule, sf);
      /* pFunc is a new reference */

      if (pFunc && PyCallable_Check(pFunc)) {
        pValue = PyObject_CallObject(pFunc, pArgs);
        if (pValue != NULL) {
          Py_DECREF(pValue);
        } else {
          Py_DECREF(pFunc);
          Py_DECREF(pModule);
          PyErr_Print();
          fprintf(stderr, "Call failed\n");
          {
            return false;
          }
        }
      } else {
        if (PyErr_Occurred())
          PyErr_Print();
        fprintf(stderr, "Cannot find function \"%s\"\n", sf);
      }
      Py_XDECREF(pFunc);
      Py_DECREF(pModule);
    } else {
      PyErr_Print();
      {
        return false;
      }
    }
    {
      return true;
    }
  }
  {
    return false;
  }
}
Example #6
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;
}
static PyObject *
math_ldexp(PyObject *self, PyObject *args)
{
	double x, r;
	PyObject *oexp;
	long exp;
	if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
		return NULL;

	if (PyLong_Check(oexp)) {
		/* on overflow, replace exponent with either LONG_MAX
		   or LONG_MIN, depending on the sign. */
		exp = PyLong_AsLong(oexp);
		if (exp == -1 && PyErr_Occurred()) {
			if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
				if (Py_SIZE(oexp) < 0) {
					exp = LONG_MIN;
				}
				else {
					exp = LONG_MAX;
				}
				PyErr_Clear();
			}
			else {
				/* propagate any unexpected exception */
				return NULL;
			}
		}
	}
	else {
		PyErr_SetString(PyExc_TypeError,
				"Expected an int or long as second argument "
				"to ldexp.");
		return NULL;
	}

	if (x == 0. || !Py_IS_FINITE(x)) {
		/* NaNs, zeros and infinities are returned unchanged */
		r = x;
		errno = 0;
	} else if (exp > INT_MAX) {
		/* overflow */
		r = copysign(Py_HUGE_VAL, x);
		errno = ERANGE;
	} else if (exp < INT_MIN) {
		/* underflow to +-0 */
		r = copysign(0., x);
		errno = 0;
	} else {
		errno = 0;
		PyFPE_START_PROTECT("in math_ldexp", return 0);
		r = ldexp(x, (int)exp);
		PyFPE_END_PROTECT(r);
		if (Py_IS_INFINITY(r))
			errno = ERANGE;
	}

	if (errno && is_error(r))
		return NULL;
	return PyFloat_FromDouble(r);
}
Example #8
0
/*
 * Convert a Python object to the values needed to create a voidptr.
 */
static int vp_convertor(PyObject *arg, struct vp_values *vp)
{
    void *ptr;
    SIP_SSIZE_T size = -1;
    int rw = TRUE;

    if (arg == Py_None)
        ptr = NULL;
#if defined(SIP_USE_PYCAPSULE)
    else if (PyCapsule_CheckExact(arg))
        ptr = PyCapsule_GetPointer(arg, NULL);
#endif
#if defined(SIP_SUPPORT_PYCOBJECT)
    else if (PyCObject_Check(arg))
        ptr = PyCObject_AsVoidPtr(arg);
#endif
    else if (PyObject_TypeCheck(arg, &sipVoidPtr_Type))
    {
        ptr = ((sipVoidPtrObject *)arg)->voidptr;
        size = ((sipVoidPtrObject *)arg)->size;
        rw = ((sipVoidPtrObject *)arg)->rw;
    }
#if PY_VERSION_HEX >= 0x02060300
    else if (PyObject_CheckBuffer(arg))
    {
        Py_buffer view;

        if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) < 0)
            return 0;

        ptr = view.buf;
        size = view.len;
        rw = !view.readonly;

        PyBuffer_Release(&view);
    }
#endif
#if PY_VERSION_HEX < 0x03000000
    else if (PyObject_AsReadBuffer(arg, (const void **)&ptr, &size) >= 0)
    {
        rw = (Py_TYPE(arg)->tp_as_buffer->bf_getwritebuffer != NULL);
    }
#endif
    else
    {
        PyErr_Clear();
        ptr = PyLong_AsVoidPtr(arg);

        if (PyErr_Occurred())
        {
#if defined(SIP_USE_PYCAPSULE)
#if defined(SIP_SUPPORT_PYCOBJECT)
            PyErr_SetString(PyExc_TypeError, "a single integer, Capsule, CObject, None, bytes-like object or another sip.voidptr object is required");
#else
            PyErr_SetString(PyExc_TypeError, "a single integer, Capsule, None, bytes-like object or another sip.voidptr object is required");
#endif
#else
            PyErr_SetString(PyExc_TypeError, "a single integer, CObject, None, bytes-like object or another sip.voidptr object is required");
#endif
            return 0;
        }
    }

    vp->voidptr = ptr;
    vp->size = size;
    vp->rw = rw;

    return 1;
}
Example #9
0
/**
 * Set one or more options in a decoder instance.
 *
 * Handled options are removed from the hash.
 *
 * @param di Decoder instance.
 * @param options A GHashTable of options to set.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 */
SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
				GHashTable *options)
{
	PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
	PyObject *py_optlist, *py_classval;
	Py_UNICODE *py_ustr;
	unsigned long long int val_ull;
	int num_optkeys, ret, size, i;
	char *key, *value;

	if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
		/* Decoder has no options. */
		if (g_hash_table_size(options) == 0) {
			/* No options provided. */
			return SRD_OK;
		} else {
			srd_err("Protocol decoder has no options.");
			return SRD_ERR_ARG;
		}
		return SRD_OK;
	}

	ret = SRD_ERR_PYTHON;
	key = NULL;
	py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
	py_optlist = py_classval = NULL;
	py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");

	/* All of these are synthesized objects, so they're good. */
	py_dec_optkeys = PyDict_Keys(py_dec_options);
	num_optkeys = PyList_Size(py_dec_optkeys);
	if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
		goto err_out;
	for (i = 0; i < num_optkeys; i++) {
		/* Get the default class value for this option. */
		py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
		if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
			goto err_out;
		if (!(py_classval = PyList_GetItem(py_optlist, 1)))
			goto err_out;
		if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
			srd_err("Options of type %s are not yet supported.",
				Py_TYPE(py_classval)->tp_name);
			goto err_out;
		}

		if ((value = g_hash_table_lookup(options, key))) {
			/* An override for this option was provided. */
			if (PyUnicode_Check(py_classval)) {
				if (!(py_optval = PyUnicode_FromString(value))) {
					/* Some UTF-8 encoding error. */
					PyErr_Clear();
					goto err_out;
				}
			} else if (PyLong_Check(py_classval)) {
				if (!(py_optval = PyLong_FromString(value, NULL, 0))) {
					/* ValueError Exception */
					PyErr_Clear();
					srd_err("Option %s has invalid value "
						"%s: expected integer.",
						key, value);
					goto err_out;
				}
			}
			g_hash_table_remove(options, key);
		} else {
			/* Use the class default for this option. */
			if (PyUnicode_Check(py_classval)) {
				/* Make a brand new copy of the string. */
				py_ustr = PyUnicode_AS_UNICODE(py_classval);
				size = PyUnicode_GET_SIZE(py_classval);
				py_optval = PyUnicode_FromUnicode(py_ustr, size);
			} else if (PyLong_Check(py_classval)) {
				/* Make a brand new copy of the integer. */
				val_ull = PyLong_AsUnsignedLongLong(py_classval);
				if (val_ull == (unsigned long long)-1) {
					/* OverFlowError exception */
					PyErr_Clear();
					srd_err("Invalid integer value for %s: "
						"expected integer.", key);
					goto err_out;
				}
				if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
					goto err_out;
			}
		}

		/*
		 * If we got here, py_optval holds a known good new reference
		 * to the instance option to set.
		 */
		if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
			goto err_out;
	}

	ret = SRD_OK;

err_out:
	Py_XDECREF(py_optlist);
	Py_XDECREF(py_di_options);
	Py_XDECREF(py_dec_optkeys);
	Py_XDECREF(py_dec_options);
	g_free(key);
	if (PyErr_Occurred())
		srd_exception_catch("Stray exception in srd_inst_option_set().");

	return ret;
}
Example #10
0
	k3d::bool_t execute(const k3d::string_t& ScriptName, const k3d::string_t& Script, context& Context, output_t* Stdout, output_t* Stderr)
	{
		k3d::bool_t succeeded = true;

		try
		{
			boost::scoped_ptr<k3d::python::file_signal> stdout_signal;
			boost::scoped_ptr<k3d::python::file_signal> stderr_signal;

			if(Stdout)
			{
				stdout_signal.reset(new k3d::python::file_signal());
				stdout_signal->connect_output_signal(*Stdout);
				PySys_SetObject(const_cast<char*>("stdout"), boost::python::object(*stdout_signal).ptr());
			}

			if(Stderr)
			{
				stderr_signal.reset(new k3d::python::file_signal());
				stderr_signal->connect_output_signal(*Stderr);
				PySys_SetObject(const_cast<char*>("stderr"), boost::python::object(*stderr_signal).ptr());
			}

			m_local_dict["context"] = Context;

			// The embedded python interpreter cannot handle DOS line-endings, see http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
			k3d::string_t script = Script;
			script.erase(std::remove(script.begin(), script.end(), '\r'), script.end());

			PyDict_Update(m_local_dict.ptr(), PyObject_GetAttrString(PyImport_AddModule("__main__"), "__dict__"));
			
			PyObject* const result = PyRun_String(const_cast<char*>(script.c_str()), Py_file_input, m_local_dict.ptr(), m_local_dict.ptr());
			if(result)
			{
				Py_DECREF(result);
				if(Py_FlushLine())
					PyErr_Clear();
			}
			else
			{
				PyErr_Print();
			}

			Context = boost::python::extract<k3d::iscript_engine::context>(m_local_dict["context"])();

			succeeded = result ? true : false;
		}
		catch(std::exception& e)
		{
			k3d::log() << error << k3d_file_reference << ": " << e.what() << std::endl;
			succeeded = false;
		}
		catch(...)
		{
			k3d::log() << error << k3d_file_reference << ": " << "Unknown exception" << std::endl;
			succeeded = false;
		}

		if(Stdout)
		      PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));

		if(Stderr)
		      PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));

		return succeeded;
	}
Example #11
0
void example18() {
    py::module main_module = py::module::import("__main__");
    py::object main_namespace = main_module.attr("__dict__");

    bool ok = false;

    main_module.def("call_test", [&]() -> int {
        ok = true;
        return 42;
    });

    cout << "eval_statements test" << endl;

    auto result = py::eval<py::eval_statements>(
            "print('Hello World!');\n"
            "x = call_test();", main_namespace);

    if (ok && result == py::none())
        cout << "eval_statements passed" << endl;
    else
        cout << "eval_statements failed" << endl;

    cout << "eval test" << endl;

    py::object val = py::eval("x", main_namespace);

    if (val.cast<int>() == 42)
        cout << "eval passed" << endl;
    else
        cout << "eval failed" << endl;

    ok = false;
    cout << "eval_single_statement test" << endl;

    py::eval<py::eval_single_statement>(
        "y = call_test();", main_namespace);

    if (ok)
        cout << "eval_single_statement passed" << endl;
    else
        cout << "eval_single_statement failed" << endl;

    cout << "eval_file test" << endl;

    int val_out;
    main_module.def("call_test2", [&](int value) {val_out = value;});

    try {
        result = py::eval_file("example18_call.py", main_namespace);
    } catch (...) {
        result = py::eval_file("example/example18_call.py", main_namespace);
    }

    if (val_out == 42 && result == py::none())
        cout << "eval_file passed" << endl;
    else
        cout << "eval_file failed" << endl;

    ok = false;
    cout << "eval failure test" << endl;
    try {
        py::eval("nonsense code ...");
    } catch (py::error_already_set &) {
        PyErr_Clear();
        ok = true;
    }

    if (ok)
        cout << "eval failure test passed" << endl;
    else
        cout << "eval failure test failed" << endl;

    ok = false;
    cout << "eval_file failure test" << endl;
    try {
        py::eval_file("nonexisting file");
    } catch (std::exception &) {
        ok = true;
    }

    if (ok)
        cout << "eval_file failure test passed" << endl;
    else
        cout << "eval_file failure test failed" << endl;
}
Example #12
0
static int convertTo_QVector_1900(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QVector<GLuint> **sipCppPtr = reinterpret_cast<QVector<GLuint> **>(sipCppPtrV);

#line 54 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtGui/qpygui_qvector.sip"
    PyObject *iter = PyObject_GetIter(sipPy);

    if (!sipIsErr)
    {
        Py_XDECREF(iter);

        return (iter
#if PY_MAJOR_VERSION < 3
                && !PyString_Check(sipPy)
#endif
                && !PyUnicode_Check(sipPy));
    }

    if (!iter)
    {
        *sipIsErr = 1;

        return 0;
    }

    QVector<unsigned> *qv = new QVector<unsigned>;

    for (SIP_SSIZE_T i = 0; ; ++i)
    {
        PyErr_Clear();
        PyObject *itm = PyIter_Next(iter);

        if (!itm)
        {
            if (PyErr_Occurred())
            {
                delete qv;
                Py_DECREF(iter);
                *sipIsErr = 1;

                return 0;
            }

            break;
        }

        PyErr_Clear();
        unsigned long val = PyLong_AsUnsignedLongMask(itm);

        if (PyErr_Occurred())
        {
            PyErr_Format(PyExc_TypeError,
                    "index " SIP_SSIZE_T_FORMAT " has type '%s' but 'int' is expected",
                    i, Py_TYPE(itm)->tp_name);

            Py_DECREF(itm);
            delete qv;
            Py_DECREF(iter);
            *sipIsErr = 1;

            return 0;
        }

        qv->append(val);

        Py_DECREF(itm);
    }

    Py_DECREF(iter);

    *sipCppPtr = qv;

    return sipGetState(sipTransferObj);
#line 137 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtGui/sipQtGuiQVector1900.cpp"
}
Example #13
0
PyObject *PyRecord::getattro(PyObject *self, PyObject *obname)
{
	PyObject *res;
	PyRecord *pyrec = (PyRecord *)self;
	char *name=PYWIN_ATTR_CONVERT(obname);
	if (name==NULL)
		return NULL;
	if (strcmp(name, "__members__")==0) {
		ULONG cnames = 0;
		HRESULT hr = pyrec->pri->GetFieldNames(&cnames, NULL);
		if (FAILED(hr))
			return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
		BSTR *strs = (BSTR *)malloc(sizeof(BSTR) * cnames);
		if (strs==NULL)
			return PyErr_NoMemory();
		hr = pyrec->pri->GetFieldNames(&cnames, strs);
		if (FAILED(hr)) {
			free(strs);
			return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
		}
		res = PyList_New(cnames);
		for (ULONG i=0;i<cnames && res != NULL;i++) {
			PyObject *item = PyWinCoreString_FromString(strs[i]);
			SysFreeString(strs[i]);
			if (item==NULL) {
				Py_DECREF(res);
				res = NULL;
			} else
				PyList_SET_ITEM(res, i, item); // ref count swallowed.
		}
		free(strs);
		return res;
	}

	res = PyObject_GenericGetAttr(self, obname);
	if (res != NULL)
		return res;

	PyErr_Clear();
	WCHAR *wname;
	if (!PyWinObject_AsWCHAR(obname, &wname))
		return NULL;

	VARIANT vret;
	VariantInit(&vret);
	void *sub_data = NULL;

	PY_INTERFACE_PRECALL;
	HRESULT hr = pyrec->pri->GetFieldNoCopy(pyrec->pdata, wname, &vret, &sub_data);
	PyWinObject_FreeWCHAR(wname);
	PY_INTERFACE_POSTCALL;

	if (FAILED(hr)) {
		if (hr == TYPE_E_FIELDNOTFOUND){
			// This is slightly suspect - throwing a unicode
			// object for an AttributeError in py2k - but this
			// is the value we asked COM for, so it makes sense...
			// (and PyErr_Format doesn't handle unicode in py2x)
			PyErr_SetObject(PyExc_AttributeError, obname);
			return NULL;
			}
		return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
	}

	// Short-circuit sub-structs and arrays here, so we dont allocate a new chunk
	// of memory and copy it - we need sub-structs to persist.
	if (V_VT(&vret)==(VT_BYREF | VT_RECORD))
		return new PyRecord(V_RECORDINFO(&vret), V_RECORD(&vret), pyrec->owner);
	else if (V_VT(&vret)==(VT_BYREF | VT_ARRAY | VT_RECORD)) {
		SAFEARRAY *psa = *V_ARRAYREF(&vret);
		int d = SafeArrayGetDim(psa);
		if (sub_data==NULL)
			return PyErr_Format(PyExc_RuntimeError, "Did not get a buffer for the array!");
		if (SafeArrayGetDim(psa) != 1)
			return PyErr_Format(PyExc_TypeError, "Only support single dimensional arrays of records");
		IRecordInfo *sub = NULL;
		long ubound, lbound, nelems;
		int i;
		BYTE *this_data;
		PyObject *ret_tuple = NULL;
		ULONG element_size = 0;
		hr = SafeArrayGetUBound(psa, 1, &ubound);
		if (FAILED(hr)) goto array_end;
		hr = SafeArrayGetLBound(psa, 1, &lbound);
		if (FAILED(hr)) goto array_end;
		hr = SafeArrayGetRecordInfo(psa, &sub);
		if (FAILED(hr)) goto array_end;
		hr = sub->GetSize(&element_size);
		if (FAILED(hr)) goto array_end;
		nelems = ubound-lbound;
		ret_tuple = PyTuple_New(nelems);
		if (ret_tuple==NULL) goto array_end;
		this_data = (BYTE *)sub_data;
		for (i=0;i<nelems;i++) {
			PyTuple_SET_ITEM(ret_tuple, i, new PyRecord(sub, this_data, pyrec->owner));
			this_data += element_size;
		}
array_end:
		if (sub)
			sub->Release();
		if (FAILED(hr)) 
			return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
		return ret_tuple;
	}

	// This default conversion we use is a little slow (but it will do!)
	// For arrays, the pparray->pvData member is *not* set, since the actual data
	// pointer from the record is returned in sub_data, so set it here.
	if (V_ISARRAY(&vret) && V_ISBYREF(&vret))
		(*V_ARRAYREF(&vret))->pvData = sub_data;
	PyObject *ret = PyCom_PyObjectFromVariant(&vret);

//	VariantClear(&vret);
	return ret;
}
static PyObject *DoPyRead_Buffer(nsIInputStream *pI, PyObject *obBuffer, PRUint32 n)
{
	PRUint32 nread;
	void *buf;
#ifndef VBOX /* unsafe cast on 64-bit hosts. */
	PRUint32 buf_len;
	if (PyObject_AsWriteBuffer(obBuffer, &buf, (Py_ssize_t *)&buf_len) != 0) {
#else   /* VBOX */
# if PY_VERSION_HEX >= 0x02050000 || defined(PY_SSIZE_T_MIN)
        Py_ssize_t buf_len;
# else
        int buf_len;
# endif /* VBOX */
	if (PyObject_AsWriteBuffer(obBuffer, &buf, &buf_len) != 0) {
#endif
		PyErr_Clear();
		PyErr_SetString(PyExc_TypeError, "The buffer object does not have a write buffer!");
		return NULL;
	}
	if (n==(PRUint32)-1) {
		n = buf_len;
	} else {
		if (n > buf_len) {
			NS_WARNING("Warning: PyIInputStream::read() was passed an integer size greater than the size of the passed buffer!  Buffer size used.\n");
			n = buf_len;
		}
	}
	nsresult r;
	Py_BEGIN_ALLOW_THREADS;
	r = pI->Read((char *)buf, n, &nread);
	Py_END_ALLOW_THREADS;
	if ( NS_FAILED(r) )
		return PyXPCOM_BuildPyException(r);
	return PyInt_FromLong(nread);
}

static PyObject *DoPyRead_Size(nsIInputStream *pI, PRUint32 n)
{
	if (n==(PRUint32)-1) {
		nsresult r;
		Py_BEGIN_ALLOW_THREADS;
		r = pI->Available(&n);
		Py_END_ALLOW_THREADS;
		if (NS_FAILED(r))
			return PyXPCOM_BuildPyException(r);
	}
	if (n==0) { // mozilla will assert if we alloc zero bytes.
#if PY_MAJOR_VERSION <= 2
		return PyBuffer_New(0);
#else
		return PyBytes_FromString("");
#endif
	}
	char *buf = (char *)nsMemory::Alloc(n);
	if (buf==NULL) {
		PyErr_NoMemory();
		return NULL;
	}
	nsresult r;
	PRUint32 nread;
	Py_BEGIN_ALLOW_THREADS;
	r = pI->Read(buf, n, &nread);
	Py_END_ALLOW_THREADS;
	PyObject *rc = NULL;
	if ( NS_SUCCEEDED(r) ) {
#if PY_MAJOR_VERSION <= 2
		rc = PyBuffer_New(nread);
		if (rc != NULL) {
			void *ob_buf;
#ifndef VBOX /* unsafe cast on 64-bit hosts. */
			PRUint32 buf_len;
			if (PyObject_AsWriteBuffer(rc, &ob_buf, (Py_ssize_t *)&buf_len) != 0) {
#else   /* VBOX */
# if PY_VERSION_HEX >= 0x02050000 || defined(PY_SSIZE_T_MIN)
                        Py_ssize_t buf_len;
# else
                        int buf_len;
# endif /* VBOX */
			if (PyObject_AsWriteBuffer(rc, &ob_buf, &buf_len) != 0) {
#endif
				// should never fail - we just created it!
				return NULL;
			}
			if (buf_len != nread) {
				PyErr_SetString(PyExc_RuntimeError, "New buffer isnt the size we create it!");
				return NULL;
			}
			memcpy(ob_buf, buf, nread);
		}
#else
        rc = PyBytes_FromStringAndSize(buf, nread);
#endif
	} else
		PyXPCOM_BuildPyException(r);
	nsMemory::Free(buf);
	return rc;
}

static PyObject *PyRead(PyObject *self, PyObject *args)
{
	PyObject *obBuffer = NULL;
	PRUint32 n = (PRUint32)-1;

	nsIInputStream *pI = GetI(self);
	if (pI==NULL)
		return NULL;
	if (PyArg_ParseTuple(args, "|i", (int *)&n))
		// This worked - no args, or just an int.
		return DoPyRead_Size(pI, n);
	// try our other supported arg format.
	PyErr_Clear();
	if (!PyArg_ParseTuple(args, "O|i", &obBuffer, (int *)&n)) {
		PyErr_Clear();
		PyErr_SetString(PyExc_TypeError, "'read()' must be called as (buffer_ob, int_size=-1) or (int_size=-1)");
		return NULL;
	}
	return DoPyRead_Buffer(pI, obBuffer, n);
}


struct PyMethodDef
PyMethods_IInputStream[] =
{
	{ "read", PyRead, 1},
	// The rest are handled as normal
	{NULL}
};
Example #15
0
void
PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
{
    PyObject *exc, *v, *tb, *tmp;
    _Py_IDENTIFIER(filename);
    _Py_IDENTIFIER(lineno);
    _Py_IDENTIFIER(msg);
    _Py_IDENTIFIER(offset);
    _Py_IDENTIFIER(print_file_and_line);
    _Py_IDENTIFIER(text);

    /* add attributes for the line number and filename for the error */
    PyErr_Fetch(&exc, &v, &tb);
    PyErr_NormalizeException(&exc, &v, &tb);
    /* XXX check that it is, indeed, a syntax error. It might not
     * be, though. */
    tmp = PyLong_FromLong(lineno);
    if (tmp == NULL)
        PyErr_Clear();
    else {
        if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
            PyErr_Clear();
        Py_DECREF(tmp);
    }
    if (col_offset >= 0) {
        tmp = PyLong_FromLong(col_offset);
        if (tmp == NULL)
            PyErr_Clear();
        else {
            if (_PyObject_SetAttrId(v, &PyId_offset, tmp))
                PyErr_Clear();
            Py_DECREF(tmp);
        }
    }
    if (filename != NULL) {
        if (_PyObject_SetAttrId(v, &PyId_filename, filename))
            PyErr_Clear();

        tmp = PyErr_ProgramTextObject(filename, lineno);
        if (tmp) {
            if (_PyObject_SetAttrId(v, &PyId_text, tmp))
                PyErr_Clear();
            Py_DECREF(tmp);
        }
    }
    if (_PyObject_SetAttrId(v, &PyId_offset, Py_None)) {
        PyErr_Clear();
    }
    if (exc != PyExc_SyntaxError) {
        if (!_PyObject_HasAttrId(v, &PyId_msg)) {
            tmp = PyObject_Str(v);
            if (tmp) {
                if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
                    PyErr_Clear();
                Py_DECREF(tmp);
            } else {
                PyErr_Clear();
            }
        }
        if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
            if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
                                    Py_None))
                PyErr_Clear();
        }
    }
    PyErr_Restore(exc, v, tb);
}
void StarSystem::UpdateUnitPhysics( bool firstframe )
{
    static bool phytoggle  = true;
    static int  batchcount = SIM_QUEUE_SIZE-1;
    double aitime = 0;
    double phytime = 0;
    double collidetime     = 0;
    double flattentime     = 0;
    double bolttime = 0;
    targetpick   = 0;
    aggfire      = 0;
    numprocessed = 0;
    stats.CheckVitals( this );
    if (phytoggle) {
        for (++batchcount; batchcount > 0; --batchcount) {
            //BELOW COMMENTS ARE NO LONGER IN SYNCH
            //NOTE: Randomization is necessary to preserve scattering - otherwise, whenever a
            //unit goes from low-priority to high-priority and back to low-priority, they
            //get synchronized and start producing peaks.
            //NOTE2: But... randomization must come only on priority changes. Otherwise, it may
            //interfere with subunit scheduling. Luckily, all units that make use of subunit
            //scheduling also require a constant base priority, since otherwise priority changes
            //will wreak havoc with subunit interpolation. Luckily again, we only need
            //randomization on priority changes, so we're fine.
            try {
                Unit *unit = NULL;
                for (un_iter iter = physics_buffer[current_sim_location].createIterator(); (unit = *iter); ++iter) {
                    int priority  = UnitUtil::getPhysicsPriority( unit );
                    //Doing spreading here and only on priority changes, so as to make AI easier
                    int predprior = unit->predicted_priority;
                    //If the priority has really changed (not an initial scattering, because prediction doesn't match)
                    if (priority != predprior) {
                        if (predprior == 0)
                            //Validate snapshot of current interpolated state (this is a reschedule)
                            unit->curr_physical_state = unit->cumulative_transformation;
                        //Save priority value as prediction for next scheduling, but don't overwrite yet.
                        predprior = priority;
                        //Scatter, so as to achieve uniform distribution
                        priority  = 1+( ( (unsigned int) vsrandom.genrand_int32() )%priority );
                    }
                    float backup = SIMULATION_ATOM;
                    theunitcounter   = theunitcounter+1;
                    SIMULATION_ATOM *= priority;
                    unit->sim_atom_multiplier = priority;
                    double aa = queryTime();
                    unit->ExecuteAI();
                    double bb = queryTime();
                    unit->ResetThreatLevel();
                    //FIXME "firstframe"-- assume no more than 2 physics updates per frame.
                    unit->UpdatePhysics( identity_transformation, identity_matrix, Vector( 0,
                                                                                           0,
                                                                                           0 ), priority
                                         == 1 ? firstframe : true, &this->gravitationalUnits(), unit );
                    double cc = queryTime();
                    aitime  += bb-aa;
                    phytime += cc-bb;
                    SIMULATION_ATOM = backup;
                    unit->predicted_priority = predprior;
                }
            }
            catch (const boost::python::error_already_set) {
                if ( PyErr_Occurred() ) {
                    PyErr_Print();
                    PyErr_Clear();
                    fflush( stderr );
                    fflush( stdout );
                } throw;
            }
            double c0  = queryTime();
            Bolt::UpdatePhysics( this );
            double cc  = queryTime();
            last_collisions.clear();
            double fl0 = queryTime();
            collidemap[Unit::UNIT_BOLT]->flatten();
            if (Unit::NUM_COLLIDE_MAPS > 1)
                collidemap[Unit::UNIT_ONLY]->flatten( *collidemap[Unit::UNIT_BOLT] );
            flattentime = queryTime()-fl0;
            Unit *unit;
            for (un_iter iter = physics_buffer[current_sim_location].createIterator(); (unit = *iter);) {
                int   priority = unit->sim_atom_multiplier;
                float backup   = SIMULATION_ATOM;
                SIMULATION_ATOM *= priority;
                unsigned int newloc = (current_sim_location+priority)%SIM_QUEUE_SIZE;
                unit->CollideAll();
                SIMULATION_ATOM = backup;
                if (newloc == current_sim_location)
                    ++iter;
                else
                    iter.moveBefore( physics_buffer[newloc] );
            }
            double dd = queryTime();
            collidetime += dd-cc;
            bolttime    += cc-c0;
            current_sim_location = (current_sim_location+1)%SIM_QUEUE_SIZE;
            ++physicsframecounter;
            totalprocessed += theunitcounter;
            theunitcounter  = 0;
        }
    } else {
        Unit *unit = NULL;
        for (un_iter iter = getUnitList().createIterator(); (unit = *iter); ++iter) {
            unit->ExecuteAI();
            last_collisions.clear();
            unit->UpdatePhysics( identity_transformation, identity_matrix, Vector( 0,
                                                                                   0,
                                                                                   0 ), firstframe,
                                 &this->gravitationalUnits(), unit );
            unit->CollideAll();
        }
    }
}
Example #17
0
int
PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v)
{
	PyObject *oldv;

	addr += l->offset;

	if ((l->flags & READONLY))
	{
		PyErr_SetString(PyExc_TypeError, "readonly attribute");
		return -1;
	}
	if ((l->flags & PY_WRITE_RESTRICTED) && PyEval_GetRestricted()) {
		PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
		return -1;
	}
	if (v == NULL) {
		if (l->type == T_OBJECT_EX) {
			/* Check if the attribute is set. */
			if (*(PyObject **)addr == NULL) {
				PyErr_SetString(PyExc_AttributeError, l->name);
				return -1;
			}
		}
		else if (l->type != T_OBJECT) {
			PyErr_SetString(PyExc_TypeError,
							"can't delete numeric/char attribute");
			return -1;
		}
	}
	switch (l->type) {
	case T_BOOL:{
		if (!PyBool_Check(v)) {
			PyErr_SetString(PyExc_TypeError,
							"attribute value type must be bool");
			return -1;
		}
		if (v == Py_True)
			*(char*)addr = (char) 1;
		else
			*(char*)addr = (char) 0;
		break;
		}
	case T_BYTE:{
		long long_val = PyInt_AsLong(v);
		if ((long_val == -1) && PyErr_Occurred())
			return -1;
		*(char*)addr = (char)long_val;
		/* XXX: For compatibility, only warn about truncations
		   for now. */
		if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN))
			WARN("Truncation of value to char");
		break;
		}
	case T_UBYTE:{
		long long_val = PyInt_AsLong(v);
		if ((long_val == -1) && PyErr_Occurred())
			return -1;
		*(unsigned char*)addr = (unsigned char)long_val;
		if ((long_val > UCHAR_MAX) || (long_val < 0))
			WARN("Truncation of value to unsigned char");
		break;
		}
	case T_SHORT:{
		long long_val = PyInt_AsLong(v);
		if ((long_val == -1) && PyErr_Occurred())
			return -1;
		*(short*)addr = (short)long_val;
		if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN))
			WARN("Truncation of value to short");
		break;
		}
	case T_USHORT:{
		long long_val = PyInt_AsLong(v);
		if ((long_val == -1) && PyErr_Occurred())
			return -1;
		*(unsigned short*)addr = (unsigned short)long_val;
		if ((long_val > USHRT_MAX) || (long_val < 0))
			WARN("Truncation of value to unsigned short");
		break;
		}
	case T_INT:{
		long long_val = PyInt_AsLong(v);
		if ((long_val == -1) && PyErr_Occurred())
			return -1;
		*(int *)addr = (int)long_val;
		if ((long_val > INT_MAX) || (long_val < INT_MIN))
			WARN("Truncation of value to int");
		break;
		}
	case T_UINT:{
		unsigned long ulong_val = PyLong_AsUnsignedLong(v);
		if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) {
			/* XXX: For compatibility, accept negative int values
			   as well. */
			PyErr_Clear();
			ulong_val = PyLong_AsLong(v);
			if ((ulong_val == (unsigned long)-1) &&
				PyErr_Occurred())
				return -1;
			*(unsigned int *)addr = (unsigned int)ulong_val;
			WARN("Writing negative value into unsigned field");
		} else
			*(unsigned int *)addr = (unsigned int)ulong_val;
		if (ulong_val > UINT_MAX)
			WARN("Truncation of value to unsigned int");
		break;
		}
	case T_LONG:{
		*(long*)addr = PyLong_AsLong(v);
		if ((*(long*)addr == -1) && PyErr_Occurred())
			return -1;
		break;
		}
	case T_ULONG:{
		*(unsigned long*)addr = PyLong_AsUnsignedLong(v);
		if ((*(unsigned long*)addr == (unsigned long)-1)
			&& PyErr_Occurred()) {
			/* XXX: For compatibility, accept negative int values
			   as well. */
			PyErr_Clear();
			*(unsigned long*)addr = PyLong_AsLong(v);
			if ((*(unsigned long*)addr == (unsigned long)-1)
				&& PyErr_Occurred())
				return -1;
			WARN("Writing negative value into unsigned field");
		}
		break;
		}
	case T_PYSSIZET:{
		*(Py_ssize_t*)addr = PyInt_AsSsize_t(v);
		if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1)
			&& PyErr_Occurred())
						return -1;
		break;
		}
	case T_FLOAT:{
		double double_val = PyFloat_AsDouble(v);
		if ((double_val == -1) && PyErr_Occurred())
			return -1;
		*(float*)addr = (float)double_val;
		break;
		}
	case T_DOUBLE:
		*(double*)addr = PyFloat_AsDouble(v);
		if ((*(double*)addr == -1) && PyErr_Occurred())
			return -1;
		break;
	case T_OBJECT:
	case T_OBJECT_EX:
		Py_XINCREF(v);
		oldv = *(PyObject **)addr;
		*(PyObject **)addr = v;
// Todo: Maybe here is a smarter update policy possible via index-by-address-lookup
		updateJyGCHeadLinks((PyObject*) (addr-l->offset), AS_JY(addr-l->offset));
		Py_XDECREF(oldv);
		break;
	case T_CHAR:
		if (PyString_Check(v) && PyString_Size(v) == 1) {
			*(char*)addr = PyString_AsString(v)[0];
		}
		else {
			PyErr_BadArgument();
			return -1;
		}
		break;
	case T_STRING:
	case T_STRING_INPLACE:
		PyErr_SetString(PyExc_TypeError, "readonly attribute");
		return -1;
#ifdef HAVE_LONG_LONG
	case T_LONGLONG:{
		PY_LONG_LONG value;
		*(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v);
		if ((value == -1) && PyErr_Occurred())
			return -1;
		break;
		}
	case T_ULONGLONG:{
		unsigned PY_LONG_LONG value;
		/* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong
			doesn't ??? */
		if (PyLong_Check(v))
			*(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v);
		else
			*(unsigned PY_LONG_LONG*)addr = value = PyInt_AsLong(v);
		if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred())
			return -1;
		break;
		}
#endif /* HAVE_LONG_LONG */
	default:
		PyErr_Format(PyExc_SystemError,
					 "bad memberdescr type for %s", l->name);
		return -1;
	}
	return 0;
}
Example #18
0
PyObject* NS(ErrorSet)(
  PyObject  *self
)
{
  SETUP_context
  PyObject *typeO = NULL, *valueO=NULL, *tbO = NULL, *retO = Py_None;

  PyThreadState *tstate = PyThreadState_Get();

  if (tstate->curexc_type == NULL || tstate->curexc_type == Py_None) {
    typeO = tstate->exc_type;
    valueO = tstate->exc_value;
    tbO = tstate->exc_traceback;
  } else {
    typeO = tstate->curexc_type;
    valueO = tstate->curexc_value;
    tbO = tstate->curexc_traceback;
  }
  Py_XINCREF(typeO);
  Py_XINCREF(valueO);
  Py_XINCREF(tbO);
  PyErr_Clear();

  {
    PyObject *valO = NULL ;

    if (typeO == Py_None || typeO == NULL) {
      MqErrorC (context, __func__, -1, "No active exception to reraise");

    } else if (PyErr_GivenExceptionMatches(typeO,NS(MqSException))) {

      MqErrorSet (context, 
	(MQ_INT) PyLong_AsLong(PyObject_GetAttrString(typeO,"num")),
	(enum MqErrorE) PyLong_AsLong(PyObject_GetAttrString(typeO,"code")),
	(MQ_CST const) PyBytes_AsString(PyUnicode_AsUTF8String(PyObject_GetAttrString(typeO,"text"))),
	NULL
      );

    } else if (valueO) {
      PyObject *tmod = NULL, *strO = NULL, *lstO = NULL;
      PyErrorCheckNT(end1,  tmod = PyImport_ImportModule("traceback"));
      if (tbO) {
	PyErr_NormalizeException(&typeO, &valueO, &tbO);
	PyErrorCheckNT(end1,  lstO = PyObject_CallMethod(tmod, "format_exception", "OOO", typeO, valueO, tbO));
      } else {
	PyErrorCheckNT(end1,  lstO = PyObject_CallMethod(tmod, "format_exception_only", "OO", typeO, valueO));
      }
      PyErrorCheckNT(end1,  strO = PyC2O(""));
      PyErrorCheckNT(end1,  valO = PyObject_CallMethod(strO, "join", "O", lstO));
end1:
      Py_XDECREF(tmod);
      Py_XDECREF(lstO);
      Py_XDECREF(strO);
      if (valO != NULL) {
	PyObject *strO=NULL, *utf8=NULL;

	PyErrorCheckNT(end2, strO = PyObject_Str(valO));
	PyErrorCheckNT(end2, utf8 = PyUnicode_AsUTF8String(strO));
	MqErrorC(context, __func__, -1, PyBytes_AsString(utf8));
end2:
	Py_XDECREF(utf8);
	Py_XDECREF(strO);
      }
      if (MqErrorGetCodeI(context) != MQ_ERROR)
	MqErrorV(context, __func__, -1, "%s: python error", PyExceptionClass_Name(typeO));
    }
  }

  Py_XDECREF(typeO);
  Py_XDECREF(valueO);
  Py_XDECREF(tbO);
  Py_XINCREF(retO);

  return retO;
}
Example #19
0
void python_handle_exception(const char *fmt, ...)
{
	PyObject *pResult;
	const char *msg;
	char *buf;
	size_t buflen, msglen;
	PyObject *exception, *v, *tb, *args;
	PyObject *line;
	int i;
	char *srcbuf;
	int exc_exit = 0;
	va_list ap;

	// We don't want to generate traceback when no errors occurred
	if (!PyErr_Occurred())
		return;

	if (fmt == NULL)
		srcbuf = NULL;
	else {
		va_start(ap, fmt);
		srcbuf = make_message(fmt, ap);
		va_end(ap);
	}

	PyErr_Fetch(&exception, &v, &tb);
	PyErr_Clear();
	if (exception == NULL) {
		LM_ERR("Can't get traceback, PyErr_Fetch() has failed.\n");
		if (srcbuf) pkg_free(srcbuf);
		return;
	}

	PyErr_NormalizeException(&exception, &v, &tb);
	if (exception == NULL) {
		LM_ERR("Can't get traceback, PyErr_NormalizeException() has failed.\n");
		if (srcbuf) pkg_free(srcbuf);
		return;
	}

	exc_exit = PyErr_GivenExceptionMatches(exception, PyExc_SystemExit);
	args = PyTuple_Pack(3, exception, v, tb ? tb : Py_None);
	Py_XDECREF(exception);
	Py_XDECREF(v);
	Py_XDECREF(tb);
	if (args == NULL) {
		LM_ERR("Can't get traceback, PyTuple_Pack() has failed.\n");
		if (srcbuf) pkg_free(srcbuf);
		return;
	}

	pResult = PyObject_CallObject(format_exc_obj, args);
	Py_DECREF(args);
	if (pResult == NULL) {
		LM_ERR("Can't get traceback, traceback.format_exception() has failed.\n");
		if (srcbuf) pkg_free(srcbuf);
		return;
	}

	buflen = 1;
	buf = (char *)pkg_realloc(NULL, buflen * sizeof(char));
	if (!buf)
	{
		LM_ERR("Can't allocate memory (%lu bytes), pkg_realloc() has failed."
				" Not enough memory.\n", (unsigned long)(buflen * sizeof(char *)));
		if (srcbuf) pkg_free(srcbuf);
		return;
	}
	memset(buf, 0, buflen * sizeof(char));

	for (i = 0; i < PySequence_Size(pResult); i++) {
		line = PySequence_GetItem(pResult, i);
		if (line == NULL) {
			LM_ERR("Can't get traceback, PySequence_GetItem() has failed.\n");
			Py_DECREF(pResult);
			if (buf)
				pkg_free(buf);
			if (srcbuf) pkg_free(srcbuf);
			return;
		}

		msg = PyString_AsString(line);

		if (msg == NULL) {
			LM_ERR("Can't get traceback, PyString_AsString() has failed.\n");
			Py_DECREF(line);
			Py_DECREF(pResult);
			if (buf)
				pkg_free(buf);
			if (srcbuf) pkg_free(srcbuf);
			return;
		}

		msglen = strlen(msg);
		buflen += ++msglen;

		buf = (char *)pkg_reallocxf(buf, buflen * sizeof(char));
		if (!buf)
		{
			LM_ERR("Can't allocate memory (%lu bytes), pkg_realloc() has failed."
					" Not enough memory.\n", (unsigned long)(buflen * sizeof(char *)));
			Py_DECREF(line);
			Py_DECREF(pResult);
			if (srcbuf) pkg_free(srcbuf);
			return;
		}

		strncat(buf, msg, msglen >= buflen ? buflen-1 : msglen);

		Py_DECREF(line);
	}

	if (srcbuf == NULL) {
		if(exc_exit) {
			LM_DBG("Unhandled exception in the Python code:\n%s", buf);
		} else {
			LM_ERR("Unhandled exception in the Python code:\n%s", buf);
		}
	} else {
		if(exc_exit) {
			LM_DBG("%s: Unhandled exception in the Python code:\n%s", srcbuf, buf);
		} else {
			LM_ERR("%s: Unhandled exception in the Python code:\n%s", srcbuf, buf);
		}
	}

	if (buf)
		pkg_free(buf);

	if (srcbuf)
		pkg_free(srcbuf);

	Py_DECREF(pResult);
}
Example #20
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;
}
/*NUMPY_API
 * PyArray_IntpFromSequence
 * Returns the number of dimensions or -1 if an error occurred.
 * vals must be large enough to hold maxvals
 */
NPY_NO_EXPORT int
PyArray_IntpFromSequence(PyObject *seq, intp *vals, int maxvals)
{
    int nd, i;
    PyObject *op, *err;

    /*
     * Check to see if sequence is a single integer first.
     * or, can be made into one
     */
    if ((nd=PySequence_Length(seq)) == -1) {
        if (PyErr_Occurred()) PyErr_Clear();
#if SIZEOF_LONG >= SIZEOF_INTP
        if (!(op = PyNumber_Int(seq))) {
            return -1;
        }
#else
        if (!(op = PyNumber_Long(seq))) {
            return -1;
        }
#endif
        nd = 1;
#if SIZEOF_LONG >= SIZEOF_INTP
        vals[0] = (intp ) PyInt_AsLong(op);
#else
        vals[0] = (intp ) PyLong_AsLongLong(op);
#endif
        Py_DECREF(op);

        /*
         * Check wether there was an error - if the error was an overflow, raise
         * a ValueError instead to be more helpful
         */
        if(vals[0] == -1) {
            err = PyErr_Occurred();
            if (err  &&
                PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
                PyErr_SetString(PyExc_ValueError,
                        "Maximum allowed dimension exceeded");
            }
            if(err != NULL) {
                return -1;
            }
        }
    }
    else {
        for (i = 0; i < MIN(nd,maxvals); i++) {
            op = PySequence_GetItem(seq, i);
            if (op == NULL) {
                return -1;
            }
#if SIZEOF_LONG >= SIZEOF_INTP
            vals[i]=(intp )PyInt_AsLong(op);
#else
            vals[i]=(intp )PyLong_AsLongLong(op);
#endif
            Py_DECREF(op);

            /*
             * Check wether there was an error - if the error was an overflow,
             * raise a ValueError instead to be more helpful
             */
            if(vals[0] == -1) {
                err = PyErr_Occurred();
                if (err  &&
                    PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
                    PyErr_SetString(PyExc_ValueError,
                            "Maximum allowed dimension exceeded");
                }
                if(err != NULL) {
                    return -1;
                }
            }
        }
    }
    return nd;
}
Example #22
0
// Handle the getting of a lazy attribute, ie. a native Qt signal.
int qpycore_get_lazy_attr(const sipTypeDef *td, PyObject *dict)
{
    pyqt4ClassTypeDef *ctd = (pyqt4ClassTypeDef *)td;
    const pyqt4QtSignal *sigs = ctd->qt4_signals;

    // Handle the trvial case.
    if (!sigs)
        return 0;

    QByteArray default_name;
    qpycore_pyqtSignal *default_signal = 0;

    do
    {
        // See if we have come to the end of the current signal.
        if (default_signal && !is_signal_name(sigs->signature, default_name.constData(), default_name.size()))
        {
            if (PyDict_SetItemString(dict, default_name.constData(), (PyObject *)default_signal) < 0)
                return -1;

            default_signal = 0;
        }

        bool fatal;

        qpycore_pyqtSignal *sig = qpycore_pyqtSignal_New(sigs->signature,
                &fatal);

        if (!sig)
        {
            if (fatal)
                return -1;

            PyErr_Clear();
            continue;
        }

        sig->docstring = sigs->docstring;

        // See if this is a new default.
        if (default_signal)
        {
            sig->default_signal = default_signal;
            append_overload(sig);
        }
        else
        {
            sig->non_signals = sigs->non_signals;

            default_signal = sig->default_signal = sig;

            // Get the name.
            default_name = sig->signature->name().mid(1);
        }
    }
    while ((++sigs)->signature);

    // Save the last one, if any (in case of a non-fatal error).
    if (!default_signal)
        return 0;

    return PyDict_SetItemString(dict, default_name.constData(), (PyObject *)default_signal);
}
Example #23
0
static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
                              term_t tf) {
  PyObject *pF;
  PyObject *pArgs, *pKeywords;
  PyObject *pValue;
  int i, arity;
  atom_t aname;
  foreign_t out;
  term_t targ = PL_new_term_ref();

  pF = term_to_python(tin, true);
  PyErr_Clear();
  if (pF == NULL) {
    {
      return false;
    }
  }
  if (PL_is_atom(targs)) {
    pArgs = NULL;
  } else {

    if (!PL_get_name_arity(targs, &aname, &arity)) {
      {
        return false;
      }
    }
    if (arity == 1 && PL_get_arg(1, targs, targ) && PL_is_variable(targ)) {
      /* ignore (_) */
      pArgs = NULL;
    } else {

      pArgs = PyTuple_New(arity);
      if (!pArgs) {
        return false;
      }
      for (i = 0; i < arity; i++) {
        PyObject *pArg;
        if (!PL_get_arg(i + 1, targs, targ)) {
          return false;
        }
        pArg = term_to_python(targ, true);
        if (pArg == NULL) {
          return false;
        }
        /* pArg reference stolen here: */
        PyTuple_SetItem(pArgs, i, pArg);
      }
    }
  }
  if (PL_is_atom(keywds)) {
    pKeywords = NULL;
  } else {
    pKeywords = term_to_python(keywds, true);
  }
  if (PyCallable_Check(pF)) {
    pValue = PyEval_CallObjectWithKeywords(pF, pArgs, pKeywords);
    //   PyObject_Print(pF,stderr,0);fprintf(stderr, "\n");
    // PyObject_Print(pArgs,stderr,0);fprintf(stderr, " ");
    // PyObject_Print(pKeywords,stderr,0);fprintf(stderr, "\n");
    if (!pValue)
      PyErr_Print();
    else
      Py_IncRef(pValue);
  } else if (pArgs == NULL) {
    pValue = pF;

    if (pF) {
      Py_IncRef(pValue);
    }
  } else {
    PyErr_Print();
    {
      return false;
    }
  }
  if (pArgs)
    Py_DECREF(pArgs);
  Py_DECREF(pF);
  if (pValue == NULL) {
    return false;
  }
  out = python_to_ptr(pValue, tf);
  return out;
}
Example #24
0
PyObject *
PyObject_Dir(PyObject *arg)
{
	/* Set exactly one of these non-NULL before the end. */
	PyObject *result = NULL;	/* result list */
	PyObject *masterdict = NULL;	/* result is masterdict.keys() */

	/* If NULL arg, return the locals. */
	if (arg == NULL) {
		PyObject *locals = PyEval_GetLocals();
		if (locals == NULL)
			goto error;
		result = PyDict_Keys(locals);
		if (result == NULL)
			goto error;
	}

	/* Elif this is some form of module, we only want its dict. */
	else if (PyModule_Check(arg)) {
		masterdict = PyObject_GetAttrString(arg, "__dict__");
		if (masterdict == NULL)
			goto error;
		if (!PyDict_Check(masterdict)) {
			PyErr_SetString(PyExc_TypeError,
					"module.__dict__ is not a dictionary");
			goto error;
		}
	}

	/* Elif some form of type or class, grab its dict and its bases.
	   We deliberately don't suck up its __class__, as methods belonging
	   to the metaclass would probably be more confusing than helpful. */
	else if (PyType_Check(arg) || PyClass_Check(arg)) {
		masterdict = PyDict_New();
		if (masterdict == NULL)
			goto error;
		if (merge_class_dict(masterdict, arg) < 0)
			goto error;
	}

	/* Else look at its dict, and the attrs reachable from its class. */
	else {
		PyObject *itsclass;
		/* Create a dict to start with.  CAUTION:  Not everything
		   responding to __dict__ returns a dict! */
		masterdict = PyObject_GetAttrString(arg, "__dict__");
		if (masterdict == NULL) {
			PyErr_Clear();
			masterdict = PyDict_New();
		}
		else if (!PyDict_Check(masterdict)) {
			Py_DECREF(masterdict);
			masterdict = PyDict_New();
		}
		else {
			/* The object may have returned a reference to its
			   dict, so copy it to avoid mutating it. */
			PyObject *temp = PyDict_Copy(masterdict);
			Py_DECREF(masterdict);
			masterdict = temp;
		}
		if (masterdict == NULL)
			goto error;

		/* Merge in __members__ and __methods__ (if any).
		   XXX Would like this to go away someday; for now, it's
		   XXX needed to get at im_self etc of method objects. */
		if (merge_list_attr(masterdict, arg, "__members__") < 0)
			goto error;
		if (merge_list_attr(masterdict, arg, "__methods__") < 0)
			goto error;

		/* Merge in attrs reachable from its class.
		   CAUTION:  Not all objects have a __class__ attr. */
		itsclass = PyObject_GetAttrString(arg, "__class__");
		if (itsclass == NULL)
			PyErr_Clear();
		else {
			int status = merge_class_dict(masterdict, itsclass);
			Py_DECREF(itsclass);
			if (status < 0)
				goto error;
		}
	}

	assert((result == NULL) ^ (masterdict == NULL));
	if (masterdict != NULL) {
		/* The result comes from its keys. */
		assert(result == NULL);
		result = PyDict_Keys(masterdict);
		if (result == NULL)
			goto error;
	}

	assert(result);
	if (PyList_Sort(result) != 0)
		goto error;
	else
		goto normal_return;

  error:
	Py_XDECREF(result);
	result = NULL;
	/* fall through */
  normal_return:
  	Py_XDECREF(masterdict);
	return result;
}
Example #25
0
py_state_t *py_state_new(const char *script,
      unsigned is_file, const char *pyclass)
{
   py_state_t *handle;
   PyObject *hook;

   RARCH_LOG("Initializing Python runtime ...\n");
   PyImport_AppendInittab("rarch", &PyInit_Retro);
   Py_Initialize();
   RARCH_LOG("Initialized Python runtime.\n");

   handle = (py_state_t*)calloc(1, sizeof(*handle));
   hook = NULL;

   handle->main = PyImport_AddModule("__main__");
   if (!handle->main)
      goto error;
   Py_INCREF(handle->main);

   if (is_file)
   {
      /* Have to hack around the fact that the FILE struct
       * isn't standardized across environments.
       * PyRun_SimpleFile() breaks on Windows because it's
       * compiled with MSVC. */
      ssize_t len;
      char *script_ = NULL;
      bool ret      = filestream_read_file
         (script, (void**)&script_, &len);

      if (!ret || len < 0)
      {
         RARCH_ERR("Python: Failed to read script\n");
         free(script_);
         goto error;
      }

      PyRun_SimpleString(script_);
      free(script_);
   }
   else
   {
      char *script_ = align_program(script);
      if (script_)
      {
         PyRun_SimpleString(script_);
         free(script_);
      }
   }

   RARCH_LOG("Python: Script loaded.\n");
   handle->dict = PyModule_GetDict(handle->main);
   if (!handle->dict)
   {
      RARCH_ERR("Python: PyModule_GetDict() failed.\n");
      goto error;
   }
   Py_INCREF(handle->dict);

   hook = PyDict_GetItemString(handle->dict, pyclass);
   if (!hook)
   {
      RARCH_ERR("Python: PyDict_GetItemString() failed.\n");
      goto error;
   }

   handle->inst = PyObject_CallFunction(hook, NULL);
   if (!handle->inst)
   {
      RARCH_ERR("Python: PyObject_CallFunction() failed.\n");
      goto error;
   }
   Py_INCREF(handle->inst);

   return handle;

error:
   PyErr_Print();
   PyErr_Clear();
   py_state_free(handle);
   return NULL;
}
Example #26
0
void
PyErr_SetObject(PyObject *exception, PyObject *value)
{
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *exc_value;
    PyObject *tb = NULL;

    if (exception != NULL &&
        !PyExceptionClass_Check(exception)) {
        PyErr_Format(PyExc_SystemError,
                     "exception %R not a BaseException subclass",
                     exception);
        return;
    }
    Py_XINCREF(value);
    exc_value = tstate->exc_value;
    if (exc_value != NULL && exc_value != Py_None) {
        /* Implicit exception chaining */
        Py_INCREF(exc_value);
        if (value == NULL || !PyExceptionInstance_Check(value)) {
            /* We must normalize the value right now */
            PyObject *args, *fixed_value;

            /* Issue #23571: PyEval_CallObject() must not be called with an
               exception set */
            PyErr_Clear();

            if (value == NULL || value == Py_None)
                args = PyTuple_New(0);
            else if (PyTuple_Check(value)) {
                Py_INCREF(value);
                args = value;
            }
            else
                args = PyTuple_Pack(1, value);
            fixed_value = args ?
                PyEval_CallObject(exception, args) : NULL;
            Py_XDECREF(args);
            Py_XDECREF(value);
            if (fixed_value == NULL)
                return;
            value = fixed_value;
        }
        /* Avoid reference cycles through the context chain.
           This is O(chain length) but context chains are
           usually very short. Sensitive readers may try
           to inline the call to PyException_GetContext. */
        if (exc_value != value) {
            PyObject *o = exc_value, *context;
            while ((context = PyException_GetContext(o))) {
                Py_DECREF(context);
                if (context == value) {
                    PyException_SetContext(o, NULL);
                    break;
                }
                o = context;
            }
            PyException_SetContext(value, exc_value);
        } else {
            Py_DECREF(exc_value);
        }
    }
    if (value != NULL && PyExceptionInstance_Check(value))
        tb = PyException_GetTraceback(value);
    Py_XINCREF(exception);
    PyErr_Restore(exception, value, tb);
}
Example #27
0
/**
 * Evaluate the code and return the value
 * @return
 */
QVariant PythonScript::evaluateImpl()
{
    GlobalInterpreterLock gil;
    PyObject *compiledCode = this->compileToByteCode(true);
    if(!compiledCode)
    {
        return QVariant("");
    }
    PyObject *pyret;
    beginStdoutRedirect();
    if (PyCallable_Check(compiledCode)) {
        PyObject *empty_tuple = PyTuple_New(0);
        pyret = PyObject_Call(compiledCode, empty_tuple, localDict);
        Py_DECREF(empty_tuple);
    }
    else
    {
        pyret = PyEval_EvalCode((PyCodeObject*)compiledCode, localDict, localDict);
    }
    endStdoutRedirect();
    if (!pyret)
    {
        if (PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_ZeroDivisionError))
        {
            PyErr_Clear(); // silently ignore errors
            return QVariant("");
        }
        else
        {
            emit_error();
            return QVariant();
        }
    }

    QVariant qret = QVariant();
    /* None */
    if (pyret == Py_None)
    {
        qret = QVariant("");
    }
    /* numeric types */
    else if (PyFloat_Check(pyret))
    {
        qret = QVariant(PyFloat_AS_DOUBLE(pyret));
    }
    else if (PyInt_Check(pyret))
    {
        qret = QVariant((qlonglong)PyInt_AS_LONG(pyret));
    }
    else if (PyLong_Check(pyret))
    {
        qret = QVariant((qlonglong)PyLong_AsLongLong(pyret));
    }
    else if (PyNumber_Check(pyret))
    {
        PyObject *number = PyNumber_Float(pyret);
        if (number)
        {
            qret = QVariant(PyFloat_AS_DOUBLE(number));
            Py_DECREF(number);
        }
    }
    /* bool */
    else if (PyBool_Check(pyret))
    {
        qret = QVariant(pyret==Py_True, 0);
    }
    // could handle advanced types (such as PyList->QValueList) here if needed
    /* fallback: try to convert to (unicode) string */
    if(!qret.isValid())
    {
        PyObject *pystring = PyObject_Unicode(pyret);
        if (pystring)
        {
            PyObject *asUTF8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring), (int)PyUnicode_GET_DATA_SIZE(pystring), NULL);
            Py_DECREF(pystring);
            if (asUTF8)
            {
                qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8)));
                Py_DECREF(asUTF8);
            }
            else if ((pystring = PyObject_Str(pyret)))
            {
                qret = QVariant(QString(PyString_AS_STRING(pystring)));
                Py_DECREF(pystring);
            }
        }
    }

    Py_DECREF(pyret);
    if (PyErr_Occurred())
    {
        if (PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_ZeroDivisionError))
        {
            PyErr_Clear(); // silently ignore errors
            return  QVariant("");
        }
        else
        {
            emit_error();
        }
        return QVariant();
    }
    return qret;
}
Example #28
0
/* Call when an exception has occurred but there is no way for Python
   to handle it.  Examples: exception in __del__ or during GC. */
void
PyErr_WriteUnraisable(PyObject *obj)
{
    _Py_IDENTIFIER(__module__);
    PyObject *f, *t, *v, *tb;
    PyObject *moduleName = NULL;
    char* className;

    PyErr_Fetch(&t, &v, &tb);

    f = _PySys_GetObjectId(&PyId_stderr);
    if (f == NULL || f == Py_None)
        goto done;

    if (obj) {
        if (PyFile_WriteString("Exception ignored in: ", f) < 0)
            goto done;
        if (PyFile_WriteObject(obj, f, 0) < 0) {
            PyErr_Clear();
            if (PyFile_WriteString("<object repr() failed>", f) < 0) {
                goto done;
            }
        }
        if (PyFile_WriteString("\n", f) < 0)
            goto done;
    }

    if (PyTraceBack_Print(tb, f) < 0)
        goto done;

    if (!t)
        goto done;

    assert(PyExceptionClass_Check(t));
    className = PyExceptionClass_Name(t);
    if (className != NULL) {
        char *dot = strrchr(className, '.');
        if (dot != NULL)
            className = dot+1;
    }

    moduleName = _PyObject_GetAttrId(t, &PyId___module__);
    if (moduleName == NULL) {
        PyErr_Clear();
        if (PyFile_WriteString("<unknown>", f) < 0)
            goto done;
    }
    else {
        if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0) {
            if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
                goto done;
            if (PyFile_WriteString(".", f) < 0)
                goto done;
        }
    }
    if (className == NULL) {
        if (PyFile_WriteString("<unknown>", f) < 0)
            goto done;
    }
    else {
        if (PyFile_WriteString(className, f) < 0)
            goto done;
    }

    if (v && v != Py_None) {
        if (PyFile_WriteString(": ", f) < 0)
            goto done;
        if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
            PyErr_Clear();
            if (PyFile_WriteString("<exception str() failed>", f) < 0) {
                goto done;
            }
        }
    }
    if (PyFile_WriteString("\n", f) < 0)
        goto done;

done:
    Py_XDECREF(moduleName);
    Py_XDECREF(t);
    Py_XDECREF(v);
    Py_XDECREF(tb);
    PyErr_Clear(); /* Just in case */
}
static int convertTo_QList_0101QOpenGLShader(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QList<QOpenGLShader*> **sipCppPtr = reinterpret_cast<QList<QOpenGLShader*> **>(sipCppPtrV);

#line 175 "sip/QtCore/qpycore_qlist.sip"
    PyObject *iter = PyObject_GetIter(sipPy);

    if (!sipIsErr)
    {
        Py_XDECREF(iter);

        return (iter
#if PY_MAJOR_VERSION < 3
                && !PyString_Check(sipPy)
#endif
                && !PyUnicode_Check(sipPy));
    }

    if (!iter)
    {
        *sipIsErr = 1;

        return 0;
    }

    QList<QOpenGLShader *> *ql = new QList<QOpenGLShader *>;
 
    for (SIP_SSIZE_T i = 0; ; ++i)
    {
        PyErr_Clear();
        PyObject *itm = PyIter_Next(iter);

        if (!itm)
        {
            if (PyErr_Occurred())
            {
                delete ql;
                Py_DECREF(iter);
                *sipIsErr = 1;

                return 0;
            }

            break;
        }

        QOpenGLShader *t = reinterpret_cast<QOpenGLShader *>(
                sipForceConvertToType(itm, sipType_QOpenGLShader, sipTransferObj, 0,
                        0, sipIsErr));
 
        if (*sipIsErr)
        {
            PyErr_Format(PyExc_TypeError,
                    "index " SIP_SSIZE_T_FORMAT " has type '%s' but 'QOpenGLShader' is expected",
                    i, Py_TYPE(itm)->tp_name);

            Py_DECREF(itm);
            delete ql;
            Py_DECREF(iter);

            return 0;
        }

        ql->append(t);

        Py_DECREF(itm);
    }

    Py_DECREF(iter);
 
    *sipCppPtr = ql;
 
    return sipGetState(sipTransferObj);
#line 140 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtGui/sipQtGuiQList0101QOpenGLShader.cpp"
}
Example #30
0
PyObject*
_png_module::_read_png(const Py::Object& py_fileobj, const bool float_result)
{
    png_byte header[8];   // 8 is the maximum size that can be checked
    FILE* fp = NULL;
    bool close_file = false;

#if PY3K
    int fd = PyObject_AsFileDescriptor(py_fileobj.ptr());
    PyErr_Clear();
#endif

    if (py_fileobj.isString())
    {
        std::string fileName = Py::String(py_fileobj);
        const char *file_name = fileName.c_str();
        if ((fp = fopen(file_name, "rb")) == NULL)
        {
            throw Py::RuntimeError(
                Printf("Could not open file %s for reading", file_name).str());
        }
        close_file = true;
    }
#if PY3K
    else if (fd != -1) {
        fp = fdopen(fd, "r");
    }
#else
    else if (PyFile_CheckExact(py_fileobj.ptr()))
    {
        fp = PyFile_AsFile(py_fileobj.ptr());
    }
#endif
    else
    {
        PyObject* read_method = PyObject_GetAttrString(py_fileobj.ptr(), "read");
        if (!(read_method && PyCallable_Check(read_method)))
        {
            Py_XDECREF(read_method);
            throw Py::TypeError("Object does not appear to be a 8-bit string path or a Python file-like object");
        }
        Py_XDECREF(read_method);
    }

    if (fp)
    {
        if (fread(header, 1, 8, fp) != 8)
        {
            throw Py::RuntimeError(
                "_image_module::readpng: error reading PNG header");
        }
    }
    else
    {
        _read_png_data(py_fileobj.ptr(), header, 8);
    }
    if (png_sig_cmp(header, 0, 8))
    {
        throw Py::RuntimeError(
            "_image_module::readpng: file not recognized as a PNG file");
    }

    /* initialize stuff */
    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (!png_ptr)
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  png_create_read_struct failed");
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr)
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  png_create_info_struct failed");
    }

    if (setjmp(png_jmpbuf(png_ptr)))
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  error during init_io");
    }

    if (fp)
    {
        png_init_io(png_ptr, fp);
    }
    else
    {
        png_set_read_fn(png_ptr, (void*)py_fileobj.ptr(), &read_png_data);
    }
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);

    png_uint_32 width = png_get_image_width(png_ptr, info_ptr);
    png_uint_32 height = png_get_image_height(png_ptr, info_ptr);

    int bit_depth = png_get_bit_depth(png_ptr, info_ptr);

    // Unpack 1, 2, and 4-bit images
    if (bit_depth < 8)
        png_set_packing(png_ptr);

    // If sig bits are set, shift data
    png_color_8p sig_bit;
    if ((png_get_color_type(png_ptr, info_ptr) != PNG_COLOR_TYPE_PALETTE) &&
        png_get_sBIT(png_ptr, info_ptr, &sig_bit))
    {
        png_set_shift(png_ptr, sig_bit);
    }

    // Convert big endian to little
    if (bit_depth == 16)
    {
        png_set_swap(png_ptr);
    }

    // Convert palletes to full RGB
    if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_PALETTE)
    {
        png_set_palette_to_rgb(png_ptr);
    }

    // If there's an alpha channel convert gray to RGB
    if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_GRAY_ALPHA)
    {
        png_set_gray_to_rgb(png_ptr);
    }

    png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);

    /* read file */
    if (setjmp(png_jmpbuf(png_ptr)))
    {
        throw Py::RuntimeError(
            "_image_module::readpng: error during read_image");
    }

    png_bytep *row_pointers = new png_bytep[height];
    png_uint_32 row;

    for (row = 0; row < height; row++)
    {
        row_pointers[row] = new png_byte[png_get_rowbytes(png_ptr,info_ptr)];
    }

    png_read_image(png_ptr, row_pointers);

    npy_intp dimensions[3];
    dimensions[0] = height;  //numrows
    dimensions[1] = width;   //numcols
    if (png_get_color_type(png_ptr, info_ptr) & PNG_COLOR_MASK_ALPHA)
    {
        dimensions[2] = 4;     //RGBA images
    }
    else if (png_get_color_type(png_ptr, info_ptr) & PNG_COLOR_MASK_COLOR)
    {
        dimensions[2] = 3;     //RGB images
    }
    else
    {
        dimensions[2] = 1;     //Greyscale images
    }
    //For gray, return an x by y array, not an x by y by 1
    int num_dims  = (png_get_color_type(png_ptr, info_ptr)
                                & PNG_COLOR_MASK_COLOR) ? 3 : 2;

    PyArrayObject *A = NULL;
    if (float_result) {
        double max_value = (1 << ((bit_depth < 8) ? 8 : bit_depth)) - 1;

        A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_FLOAT);

        if (A == NULL)
        {
            throw Py::MemoryError("Could not allocate image array");
        }

        for (png_uint_32 y = 0; y < height; y++)
        {
            png_byte* row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++)
            {
                size_t offset = y * A->strides[0] + x * A->strides[1];
                if (bit_depth == 16)
                {
                    png_uint_16* ptr = &reinterpret_cast<png_uint_16*>(row)[x * dimensions[2]];
                    for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                    {
                        *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
                    }
                }
                else
                {
                    png_byte* ptr = &(row[x * dimensions[2]]);
                    for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                    {
                        *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
                    }
                }
            }
        }
    } else {
        A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_UBYTE);

        if (A == NULL)
        {
            throw Py::MemoryError("Could not allocate image array");
        }

        for (png_uint_32 y = 0; y < height; y++)
        {
            png_byte* row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++)
            {
                size_t offset = y * A->strides[0] + x * A->strides[1];
                if (bit_depth == 16)
                {
                    png_uint_16* ptr = &reinterpret_cast<png_uint_16*>(row)[x * dimensions[2]];
                    for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                    {
                        *(png_byte*)(A->data + offset + p*A->strides[2]) = ptr[p] >> 8;
                    }
                }
                else
                {
                    png_byte* ptr = &(row[x * dimensions[2]]);
                    for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                    {
                        *(png_byte*)(A->data + offset + p*A->strides[2]) = ptr[p];
                    }
                }
            }
        }