Esempio n. 1
0
PyObject *
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
{
	PyTypeObject *tp = obj->ob_type;
	PyObject *descr = NULL;
	PyObject *res = NULL;
	descrgetfunc f;
	Py_ssize_t dictoffset;
	PyObject **dictptr;

	if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
		/* The Unicode to string conversion is done here because the
		   existing tp_setattro slots expect a string object as name
		   and we wouldn't want to break those. */
		if (PyUnicode_Check(name)) {
			name = PyUnicode_AsEncodedString(name, NULL, NULL);
			if (name == NULL)
				return NULL;
		}
		else
#endif
		{
			PyErr_Format(PyExc_TypeError,
				     "attribute name must be string, not '%.200s'",
				     name->ob_type->tp_name);
			return NULL;
		}
	}
	else
		Py_INCREF(name);

	if (tp->tp_dict == NULL) {
		if (PyType_Ready(tp) < 0)
			goto done;
	}

	/* Inline _PyType_Lookup */
	{
		Py_ssize_t i, n;
		PyObject *mro, *base, *dict;

		/* Look in tp_dict of types in MRO */
		mro = tp->tp_mro;
		assert(mro != NULL);
		assert(PyTuple_Check(mro));
		n = PyTuple_GET_SIZE(mro);
		for (i = 0; i < n; i++) {
			base = PyTuple_GET_ITEM(mro, i);
			if (PyClass_Check(base))
				dict = ((PyClassObject *)base)->cl_dict;
			else {
				assert(PyType_Check(base));
				dict = ((PyTypeObject *)base)->tp_dict;
			}
			assert(dict && PyDict_Check(dict));
			descr = PyDict_GetItem(dict, name);
			if (descr != NULL)
				break;
		}
	}

	Py_XINCREF(descr);

	f = NULL;
	if (descr != NULL &&
	    PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
		f = descr->ob_type->tp_descr_get;
		if (f != NULL && PyDescr_IsData(descr)) {
			res = f(descr, obj, (PyObject *)obj->ob_type);
			Py_DECREF(descr);
			goto done;
		}
	}

	/* Inline _PyObject_GetDictPtr */
	dictoffset = tp->tp_dictoffset;
	if (dictoffset != 0) {
		PyObject *dict;
		if (dictoffset < 0) {
			Py_ssize_t tsize;
			size_t size;

			tsize = ((PyVarObject *)obj)->ob_size;
			if (tsize < 0)
				tsize = -tsize;
			size = _PyObject_VAR_SIZE(tp, tsize);

			dictoffset += (long)size;
			assert(dictoffset > 0);
			assert(dictoffset % SIZEOF_VOID_P == 0);
		}
		dictptr = (PyObject **) ((char *)obj + dictoffset);
		dict = *dictptr;
		if (dict != NULL) {
			Py_INCREF(dict);
			res = PyDict_GetItem(dict, name);
			if (res != NULL) {
				Py_INCREF(res);
				Py_XDECREF(descr);
                                Py_DECREF(dict);
				goto done;
			}
                        Py_DECREF(dict);
		}
	}

	if (f != NULL) {
		res = f(descr, obj, (PyObject *)obj->ob_type);
		Py_DECREF(descr);
		goto done;
	}

	if (descr != NULL) {
		res = descr;
		/* descr was already increfed above */
		goto done;
	}

	PyErr_Format(PyExc_AttributeError,
		     "'%.50s' object has no attribute '%.400s'",
		     tp->tp_name, PyString_AS_STRING(name));
  done:
	Py_DECREF(name);
	return res;
}
Esempio n. 2
0
static PyObject *
func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
{
    PyCodeObject *code;
    PyObject *globals;
    PyObject *name = Py_None;
    PyObject *defaults = Py_None;
    PyObject *closure = Py_None;
    PyFunctionObject *newfunc;
    Py_ssize_t nfree, nclosure;
    static char *kwlist[] = {"code", "globals", "name",
                             "argdefs", "closure", 0};

    if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
                          kwlist,
                          &PyCode_Type, &code,
                          &PyDict_Type, &globals,
                          &name, &defaults, &closure))
        return NULL;
    if (name != Py_None && !PyUnicode_Check(name)) {
        PyErr_SetString(PyExc_TypeError,
                        "arg 3 (name) must be None or string");
        return NULL;
    }
    if (defaults != Py_None && !PyTuple_Check(defaults)) {
        PyErr_SetString(PyExc_TypeError,
                        "arg 4 (defaults) must be None or tuple");
        return NULL;
    }
    nfree = PyTuple_GET_SIZE(code->co_freevars);
    if (!PyTuple_Check(closure)) {
        if (nfree && closure == Py_None) {
            PyErr_SetString(PyExc_TypeError,
                            "arg 5 (closure) must be tuple");
            return NULL;
        }
        else if (closure != Py_None) {
            PyErr_SetString(PyExc_TypeError,
                "arg 5 (closure) must be None or tuple");
            return NULL;
        }
    }

    /* check that the closure is well-formed */
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
    if (nfree != nclosure)
        return PyErr_Format(PyExc_ValueError,
                            "%U requires closure of length %zd, not %zd",
                            code->co_name, nfree, nclosure);
    if (nclosure) {
        Py_ssize_t i;
        for (i = 0; i < nclosure; i++) {
            PyObject *o = PyTuple_GET_ITEM(closure, i);
            if (!PyCell_Check(o)) {
                return PyErr_Format(PyExc_TypeError,
                    "arg 5 (closure) expected cell, found %s",
                                    o->ob_type->tp_name);
            }
        }
    }

    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
                                                 globals);
    if (newfunc == NULL)
        return NULL;

    if (name != Py_None) {
        Py_INCREF(name);
        Py_SETREF(newfunc->func_name, name);
    }
    if (defaults != Py_None) {
        Py_INCREF(defaults);
        newfunc->func_defaults  = defaults;
    }
    if (closure != Py_None) {
        Py_INCREF(closure);
        newfunc->func_closure = closure;
    }

    return (PyObject *)newfunc;
}
Esempio n. 3
0
static PyObject *Py_write_png(PyObject *self, PyObject *args, PyObject *kwds)
{
    numpy::array_view<unsigned char, 3> buffer;
    PyObject *filein;
    double dpi = 0;
    const char *names[] = { "buffer", "file", "dpi", NULL };

    // We don't need strict contiguity, just for each row to be
    // contiguous, and libpng has special handling for getting RGB out
    // of RGBA, ARGB or BGR. But the simplest thing to do is to
    // enforce contiguity using array_view::converter_contiguous.
    if (!PyArg_ParseTupleAndKeywords(args,
                                     kwds,
                                     "O&O|d:write_png",
                                     (char **)names,
                                     &buffer.converter_contiguous,
                                     &buffer,
                                     &filein,
                                     &dpi)) {
        return NULL;
    }

    png_uint_32 width = (png_uint_32)buffer.dim(1);
    png_uint_32 height = (png_uint_32)buffer.dim(0);
    int channels = buffer.dim(2);
    std::vector<png_bytep> row_pointers(height);
    for (png_uint_32 row = 0; row < (png_uint_32)height; ++row) {
        row_pointers[row] = (png_bytep)buffer[row].data();
    }

    FILE *fp = NULL;
    mpl_off_t offset = 0;
    bool close_file = false;
    bool close_dup_file = false;
    PyObject *py_file = NULL;

    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;
    struct png_color_8_struct sig_bit;
    int png_color_type;

    switch (channels) {
    case 1:
        png_color_type = PNG_COLOR_TYPE_GRAY;
        break;
    case 3:
        png_color_type = PNG_COLOR_TYPE_RGB;
        break;
    case 4:
        png_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
        break;
    default:
        PyErr_SetString(PyExc_ValueError,
                        "Buffer must be an NxMxD array with D in 1, 3, 4 "
                        "(grayscale, RGB, RGBA)");
        goto exit;
    }

    if (PyBytes_Check(filein) || PyUnicode_Check(filein)) {
        if ((py_file = mpl_PyFile_OpenFile(filein, (char *)"wb")) == NULL) {
            goto exit;
        }
        close_file = true;
    } else {
        py_file = filein;
    }

    if ((fp = mpl_PyFile_Dup(py_file, (char *)"wb", &offset))) {
        close_dup_file = true;
    } else {
        PyErr_Clear();
        PyObject *write_method = PyObject_GetAttrString(py_file, "write");
        if (!(write_method && PyCallable_Check(write_method))) {
            Py_XDECREF(write_method);
            PyErr_SetString(PyExc_TypeError,
                            "Object does not appear to be a 8-bit string path or "
                            "a Python file-like object");
            goto exit;
        }
        Py_XDECREF(write_method);
    }

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png_ptr == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Could not create write struct");
        goto exit;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Could not create info struct");
        goto exit;
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
        PyErr_SetString(PyExc_RuntimeError, "libpng signaled error");
        goto exit;
    }

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

    // Save the dpi of the image in the file
    if (dpi > 0.0) {
        png_uint_32 dots_per_meter = (png_uint_32)(dpi / (2.54 / 100.0));
        png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
    }

    sig_bit.alpha = 0;
    switch (png_color_type) {
    case PNG_COLOR_TYPE_GRAY:
        sig_bit.gray = 8;
        sig_bit.red = 0;
        sig_bit.green = 0;
        sig_bit.blue = 0;
        break;
    case PNG_COLOR_TYPE_RGB_ALPHA:
        sig_bit.alpha = 8;
    // fall through
    case PNG_COLOR_TYPE_RGB:
        sig_bit.gray = 0;
        sig_bit.red = 8;
        sig_bit.green = 8;
        sig_bit.blue = 8;
        break;
    default:
        PyErr_SetString(PyExc_RuntimeError, "internal error, bad png_color_type");
        goto exit;
    }
    png_set_sBIT(png_ptr, info_ptr, &sig_bit);

    png_write_info(png_ptr, info_ptr);
    png_write_image(png_ptr, &row_pointers[0]);
    png_write_end(png_ptr, info_ptr);

exit:

    if (png_ptr && info_ptr) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
    }

    if (close_dup_file) {
        mpl_PyFile_DupClose(py_file, fp, offset);
    }

    if (close_file) {
        mpl_PyFile_CloseFile(py_file);
        Py_DECREF(py_file);
    }

    if (PyErr_Occurred()) {
        return NULL;
    } else {
        Py_RETURN_NONE;
    }
}
static PyObject *fparse_function_1_new_of_module_Crypto$Random( Nuitka_FunctionObject *self, PyObject **args, Py_ssize_t args_size, PyObject *kw )
{
    assert( kw == NULL || PyDict_Check( kw ) );

    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_size = kw ? PyDict_Size( kw ) : 0;
    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_found = 0;
    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_only_found = 0;
    Py_ssize_t args_given = args_size;
    PyObject *_python_par_args = NULL;
    PyObject *_python_par_kwargs = NULL;

    if ( kw == NULL )
    {
        _python_par_kwargs = PyDict_New();
    }
    else
    {
        if ( ((PyDictObject *)kw)->ma_used > 0 )
        {
#if PYTHON_VERSION < 330
            _python_par_kwargs = _PyDict_NewPresized( ((PyDictObject *)kw)->ma_used  );

            for ( int i = 0; i <= ((PyDictObject *)kw)->ma_mask; i++ )
            {
                PyDictEntry *entry = &((PyDictObject *)kw)->ma_table[ i ];

                if ( entry->me_value != NULL )
                {

#if PYTHON_VERSION < 300
                    if (unlikely( !PyString_Check( entry->me_key ) && !PyUnicode_Check( entry->me_key ) ))
#else
                    if (unlikely( !PyUnicode_Check( entry->me_key ) ))
#endif
                    {
                        PyErr_Format( PyExc_TypeError, "new() keywords must be strings" );
                        goto error_exit;
                    }

                    int res = PyDict_SetItem( _python_par_kwargs, entry->me_key, entry->me_value );

                    if (unlikely( res == -1 ))
                    {
                        goto error_exit;
                    }
                }
            }
#else
        if ( _PyDict_HasSplitTable( (PyDictObject *)kw) )
        {
            PyDictObject *mp = (PyDictObject *)kw;

            PyObject **newvalues = PyMem_NEW( PyObject *, mp->ma_keys->dk_size );
            assert (newvalues != NULL);

            PyDictObject *split_copy = PyObject_GC_New( PyDictObject, &PyDict_Type );
            assert( split_copy != NULL );

            split_copy->ma_values = newvalues;
            split_copy->ma_keys = mp->ma_keys;
            split_copy->ma_used = mp->ma_used;

            mp->ma_keys->dk_refcnt += 1;

            Nuitka_GC_Track( split_copy );

            Py_ssize_t size = mp->ma_keys->dk_size;
            for ( Py_ssize_t i = 0; i < size; i++ )
            {
                PyDictKeyEntry *entry = &split_copy->ma_keys->dk_entries[ i ];

                if (unlikely( !PyUnicode_Check( entry->me_key ) ))
                {
                    PyErr_Format( PyExc_TypeError, "new() keywords must be strings" );
                    goto error_exit;
                }

                split_copy->ma_values[ i ] = INCREASE_REFCOUNT_X( mp->ma_values[ i ] );
            }

            _python_par_kwargs = (PyObject *)split_copy;
        }
        else
        {
Esempio n. 5
0
/*
 * Returns a copy of the given string (8-bit or Unicode) with the XML
 * control characters converted to XML character entities.
 *
 * If an 8-bit string is passed in, an 8-bit string is returned.  If a
 * Unicode string is passed in, a Unicode string is returned.
 */
static PyObject*
_escape_xml(PyObject* self, PyObject *args, PyObject *kwds,
            const char** escapes)
{
    PyObject* input_obj;
    PyObject* output_obj;
    int count = 0;
    Py_UNICODE* uinput = NULL;
    char* input = NULL;
    Py_ssize_t input_len;
    Py_UNICODE* uoutput = NULL;
    char* output = NULL;
    Py_UNICODE* up = NULL;
    char* p = NULL;
    Py_ssize_t i;
    const char** esc;
    const char* ent;

    if (!PyArg_ParseTuple(args, "O:escape_xml", &input_obj)) {
        return NULL;
    }

    if (PyUnicode_Check(input_obj)) {
        uinput = PyUnicode_AsUnicode(input_obj);
        if (uinput == NULL) {
            return NULL;
        }

        input_len = PyUnicode_GetSize(input_obj);

        for (i = 0; i < input_len; ++i) {
            for (esc = escapes; ; esc += 2) {
                if (uinput[i] > (Py_UNICODE)**esc) {
                    break;
                } else if (uinput[i] == (Py_UNICODE)**esc) {
                    ++count;
                    break;
                }
            }
        }

        if (count) {
            uoutput = malloc((input_len + 1 + count * 5) * sizeof(Py_UNICODE));
            if (uoutput == NULL) {
                PyErr_SetString(PyExc_MemoryError, "Out of memory");
                return NULL;
            }

            up = uoutput;
            for (i = 0; i < input_len; ++i) {
                for (esc = escapes; ; esc += 2) {
                    if (uinput[i] > (Py_UNICODE)**esc) {
                        *(up++) = uinput[i];
                        break;
                    } else if (uinput[i] == (Py_UNICODE)**esc) {
                        for (ent = *(esc + 1); *ent != '\0'; ++ent) {
                            *(up++) = (Py_UNICODE)*ent;
                        }
                        break;
                    }
                }
            }

            *up = 0;

            output_obj = PyUnicode_FromUnicode(uoutput, up - uoutput);
            free(uoutput);
            return output_obj;
        }
    } else if (PyBytes_Check(input_obj)) {
        if (PyBytes_AsStringAndSize(input_obj, &input, &input_len) == -1) {
            return NULL;
        }

        for (i = 0; i < input_len; ++i) {
            for (esc = escapes; ; esc += 2) {
                if (input[i] > **esc) {
                    break;
                } else if (input[i] == **esc) {
                    ++count;
                    break;
                }
            }
        }

        if (count) {
            output = malloc((input_len + 1 + count * 5) * sizeof(char));
            if (output == NULL) {
                PyErr_SetString(PyExc_MemoryError, "Out of memory");
                return NULL;
            }

            p = output;
            for (i = 0; i < input_len; ++i) {
                for (esc = escapes; ; esc += 2) {
                    if (input[i] > **esc) {
                        *(p++) = input[i];
                        break;
                    } else if (input[i] == **esc) {
                        for (ent = *(esc + 1); *ent != '\0'; ++ent) {
                            *(p++) = *ent;
                        }
                        break;
                    }
                }
            }

            *p = 0;

            output_obj = PyBytes_FromStringAndSize(output, p - output);
            free(output);
            return output_obj;
        }
    } else {
        #ifdef IS_PY3K
        PyErr_SetString(PyExc_TypeError, "must be str or bytes");
        #else
        PyErr_SetString(PyExc_TypeError, "must be str or unicode");
        #endif
        return NULL;
    }

    Py_INCREF(input_obj);
    return input_obj;
}
Esempio n. 6
0
static PyObject *AscanfCall( ascanf_Function *af, PyObject *arglist, long repeats, int asarray, int deref,
						PAO_Options *opts, char *caller )
{ int fargs= 0, aargc= 0, volatile_args= 0;
  double result= 0, *aresult=NULL;
  static double *AARGS= NULL;
  static char *ATYPE= NULL;
  static ascanf_Function *LAF= NULL;
  static size_t LAFN= 0;
  double *aargs= NULL;
  char *atype= NULL;
  ascanf_Function *laf= NULL, *af_array= NULL;
  size_t lafN= 0;
  PyObject *ret= NULL;
  static ascanf_Function *nDindex= NULL;
  int aV = ascanf_verbose;

	if( arglist ){
		if( PyList_Check(arglist) ){
			if( !(arglist= PyList_AsTuple(arglist)) ){
 				PyErr_SetString( XG_PythonError, "unexpected failure converting argument list to tuple" );
// 				PyErr_SetString( PyExc_RuntimeError, "unexpected failure converting argument list to tuple" );
				return(NULL);
			}
		}
		if( !PyTuple_Check(arglist) ){
			PyErr_SetString(
 				XG_PythonError,
// 				PyExc_SyntaxError,
				"arguments to the ascanf method should be passed as a tuple or list\n"
				" NB: a 1-element tuple is specified as (value , ) !!\n"
			);
			return(NULL);
		}

		aargc= PyTuple_Size(arglist);
	}
	else{
		aargc= 0;
	}
	if( !af ){
		goto PAC_ESCAPE;
	}
	if( af->type!= _ascanf_procedure && af->Nargs> 0 ){
	  /* procedures can have as many arguments as MaxArguments, which is probably too much to allocate here.
	   \ However, we know how many arguments a function can get (if all's well...), and we can assure that
	   \ it will have space for those arguments
	   \ 20061015: unless it also has MaxArguments, i.e. Nargs<0 ...
	   */
		fargs= af->Nargs;
	}
	{ long n= (aargc+fargs+1)*2;
		if( opts->call_reentrant ){
			lafN= n;
			aargs= (double*) calloc( lafN, sizeof(double) );
			atype= (char*)  calloc( lafN, sizeof(char) );
			if( !aargs || !atype || !(laf= (ascanf_Function*) calloc( lafN, sizeof(ascanf_Function) )) ){
				PyErr_NoMemory();
				return(NULL);
			}
		}
		else{
			if( !LAF ){
				LAFN= n;
				AARGS= (double*) calloc( LAFN, sizeof(double) );
				ATYPE= (char*) calloc( LAFN, sizeof(char) );
				if( !AARGS || !ATYPE || !(LAF= (ascanf_Function*) calloc( LAFN, sizeof(ascanf_Function) )) ){
					PyErr_NoMemory();
					return(NULL);
				}
			}
			else if( n> LAFN ){
				AARGS= (double*) realloc( AARGS, n * sizeof(double) );
				ATYPE= (char*) realloc( ATYPE, n * sizeof(char) );
				if( !AARGS || !ATYPE || !(LAF= (ascanf_Function*) realloc( LAF, n * sizeof(ascanf_Function) )) ){
					PyErr_NoMemory();
					return(NULL);
				}
				else{
					for( ; LAFN< n; LAFN++ ){
						AARGS[LAFN]= 0;
						memset( &LAF[LAFN], 0, sizeof(ascanf_Function) );
					}
				}
				LAFN= n;
			}
			aargs= AARGS;
			atype= ATYPE;
			laf= LAF;
			lafN= LAFN;
		}
	}

	{ int a= 0, i;
		if( opts->verbose > 1 ){
			ascanf_verbose = 1;
		}
		if( af->type== _ascanf_array ){
			if( !nDindex ){
				nDindex= Py_getNamedAscanfVariable("nDindex");
			}
			if( nDindex ){
				af_array= af;
				aargs[a]= (af->own_address)? af->own_address : take_ascanf_address(af);
				af= nDindex;
				a+= 1;
			}
		}
		for( i= 0; i< aargc; i++, a++ ){
		  PyObject *arg= PyTuple_GetItem(arglist, i);
		  ascanf_Function *aaf;

			if( PyFloat_Check(arg) ){
				aargs[a]= PyFloat_AsDouble(arg);
				atype[a]= 1;
			}
#ifdef USE_COBJ
			else if( PyCObject_Check(arg) ){
				if( (aaf= PyCObject_AsVoidPtr(arg)) && (PyCObject_GetDesc(arg)== aaf->function) ){
					aargs[a]= (aaf->own_address)? aaf->own_address : take_ascanf_address(aaf);
					atype[a]= 2;
				}
				else{
 					PyErr_SetString( XG_PythonError, "unsupported PyCObject type does not contain ascanf pointer" );
// 					PyErr_SetString( PyExc_TypeError, "unsupported PyCObject type does not contain ascanf pointer" );
					goto PAC_ESCAPE;
				}
			}
#else
			else if( PyAscanfObject_Check(arg) ){
				if( (aaf= PyAscanfObject_AsAscanfFunction(arg)) ){
					aargs[a]= (aaf->own_address)? aaf->own_address : take_ascanf_address(aaf);
					atype[a]= 2;
				}
				else{
 					PyErr_SetString( XG_PythonError, "invalid PyAscanfObject type does not contain ascanf pointer" );
// 					PyErr_SetString( PyExc_TypeError, "invalid PyAscanfObject type does not contain ascanf pointer" );
					goto PAC_ESCAPE;
				}
			}
#endif
			else if( PyInt_Check(arg) || PyLong_Check(arg) ){
				aargs[a]= PyInt_AsLong(arg);
				atype[a]= 3;
			}
			else if( PyBytes_Check(arg)
#ifdef IS_PY3K
				|| PyUnicode_Check(arg)
#endif
			){
			  static char *AFname= "AscanfCall-Static-StringPointer";
			  ascanf_Function *saf= &laf[a];
				memset( saf, 0, sizeof(ascanf_Function) );
				saf->type= _ascanf_variable;
				saf->function= ascanf_Variable;
				if( !(saf->name= PyObject_Name(arg)) ){
					saf->name= XGstrdup(AFname);
				}
				saf->is_address= saf->take_address= True;
				saf->is_usage= saf->take_usage= True;
				saf->internal= True;
#ifdef IS_PY3K
				if( PyUnicode_Check(arg) ){
				  PyObject *bytes = NULL;
				  char *str = NULL;
					PYUNIC_TOSTRING( arg, bytes, str );
					if( !str ){
						if( bytes ){
							Py_XDECREF(bytes);
						}
						goto PAC_ESCAPE;
					}
					saf->usage= parse_codes( XGstrdup(str) );
					Py_XDECREF(bytes);
				}
				else
#endif
				{
					saf->usage= parse_codes( XGstrdup( PyBytes_AsString(arg) ) );
				}
				aargs[a]= take_ascanf_address(saf);
				atype[a]= 4;
				if( i && af_array ){
					volatile_args+= 1;
				}
			}
			else if( PyArray_Check(arg)
				|| PyTuple_Check(arg)
				|| PyList_Check(arg)
			){
			  static char *AFname= "AscanfCall-Static-ArrayPointer";
			  ascanf_Function *saf= &laf[a];
			  PyArrayObject *parray;
				atype[a]= 6;
				if( PyList_Check(arg) ){
					if( !(arg= PyList_AsTuple(arg)) ){
 						PyErr_SetString( XG_PythonError, "unexpected failure converting argument to tuple" );
// 						PyErr_SetString( PyExc_RuntimeError, "unexpected failure converting argument to tuple" );
						goto PAC_ESCAPE;
/* 						return(NULL);	*/
					}
					else{
						atype[a]= 5;
					}
				}
				memset( saf, 0, sizeof(ascanf_Function) );
				saf->type= _ascanf_array;
				saf->function= ascanf_Variable;
				if( !(saf->name= PyObject_Name(arg)) ){
					saf->name= XGstrdup(AFname);
				}
				saf->is_address= saf->take_address= True;
				saf->internal= True;
				if( a ){
					saf->car= &laf[a-1];
				}
				else{
					saf->car= &laf[lafN-1];
				}
				if( PyTuple_Check(arg) ){
					saf->N= PyTuple_Size(arg);
					parray= NULL;
				}
				else{
					saf->N= PyArray_Size(arg);
					parray= (PyArrayObject*) arg;
					atype[a]= 7;
				}
				if( (saf->array= (double*) malloc( saf->N * sizeof(double) )) ){
				  int j;
					if( parray ){
					  PyArrayObject* xd= NULL;
					  double *PyArrayBuf= NULL;
					  PyArrayIterObject *it;
						if( (xd = (PyArrayObject*) PyArray_ContiguousFromObject( (PyObject*) arg, PyArray_DOUBLE, 0, 0 )) ){
							PyArrayBuf= (double*)PyArray_DATA(xd); /* size would be N*sizeof(double) */
						}
						else{
							it= (PyArrayIterObject*) PyArray_IterNew(arg);
						}
						if( PyArrayBuf ){
// 							for( j= 0; j< saf->N; j++ ){
// 								  /* 20061016: indices used to be i?!?! */
// 								saf->array[j]= PyArrayBuf[j];
// 							}
							if( saf->array != PyArrayBuf ){
								memcpy( saf->array, PyArrayBuf, saf->N * sizeof(double) );
							}
						}
						else{
							for( j= 0; j< saf->N; j++ ){
								saf->array[j]= PyFloat_AsDouble( PyArray_DESCR(parray)->f->getitem( it->dataptr, arg) );
								PyArray_ITER_NEXT(it);
							}
						}
						if( xd ){
							Py_XDECREF(xd);
						}
						else{
							Py_DECREF(it);
						}
					}
					else{
						for( j= 0; j< saf->N; j++ ){
							saf->array[j]= PyFloat_AsDouble( PyTuple_GetItem(arg,j) );
						}
					}
					aargs[a]= take_ascanf_address(saf);
					if( i && af_array ){
						volatile_args+= 1;
					}
				}
				else{
					PyErr_NoMemory();
					goto PAC_ESCAPE;
				}
			}
#if 0
			else{
 				PyErr_SetString( XG_PythonError, "arguments should be scalars, strings, arrays or ascanf pointers" );
// 				PyErr_SetString( PyExc_SyntaxError, "arguments should be scalars, strings, arrays or ascanf pointers" );
				goto PAC_ESCAPE;
			}
#else
			else{
			  static char *AFname= "AscanfCall-Static-PyObject";
			  ascanf_Function *saf= &laf[a];
				memset( saf, 0, sizeof(ascanf_Function) );
				saf->function= ascanf_Variable;
				saf->internal= True;
				saf= make_ascanf_python_object( saf, arg, "AscanfCall" );
				if( !saf->name ){
					if( saf->PyObject_Name ){
						saf->name= XGstrdup(saf->PyObject_Name);
					}
					else{
						saf->name= XGstrdup(AFname);
					}
				}
				aargs[a]= take_ascanf_address(saf);
				atype[a]= 4;
				if( i && af_array ){
					volatile_args+= 1;
				}
			}
#endif
		}
		if( a> aargc ){
			aargc= a;
		}
	}
Esempio n. 7
0
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
	if (value == Py_None) {
		*(wchar_t **)ptr = NULL;
		Py_INCREF(value);
		return value;
	}
	if (PyString_Check(value)) {
		value = PyUnicode_FromEncodedObject(value,
						    conversion_mode_encoding,
						    conversion_mode_errors);
		if (!value)
			return NULL;
	} else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
		Py_INCREF(Py_None);
		return Py_None;
	} else if (!PyUnicode_Check(value)) {
		PyErr_Format(PyExc_TypeError,
			     "unicode string or integer address expected instead of %s instance",
			     value->ob_type->tp_name);
		return NULL;
	} else
		Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
	/* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
	   type.  So we can copy directly.  Hm, are unicode objects always NUL
	   terminated in Python, internally?
	 */
	*(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
	return value;
#else
	{
		/* We must create a wchar_t* buffer from the unicode object,
		   and keep it alive */
		PyObject *keep;
		wchar_t *buffer;

		int size = PyUnicode_GET_SIZE(value);
		size += 1; /* terminating NUL */
		size *= sizeof(wchar_t);
		buffer = (wchar_t *)PyMem_Malloc(size);
		if (!buffer)
			return PyErr_NoMemory();
		memset(buffer, 0, size);
		keep = PyCObject_FromVoidPtr(buffer, PyMem_Free);
		if (!keep) {
			PyMem_Free(buffer);
			return NULL;
		}
		*(wchar_t **)ptr = (wchar_t *)buffer;
		if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
					       buffer, PyUnicode_GET_SIZE(value))) {
			Py_DECREF(value);
			Py_DECREF(keep);
			return NULL;
		}
		Py_DECREF(value);
		return keep;
	}
#endif
}
Esempio n. 8
0
PyObject *
option(PyObject *self, PyObject *args)
{
    long option;
    int error;
    PyObject *py_option;

    py_option = PyTuple_GetItem(args, 0);
    if (!py_option)
        return NULL;

    if (!PyInt_Check(py_option))
        return Error_type_error(
            "option should be an integer, got %.200s", py_option);

    option = PyInt_AsLong(py_option);

    switch (option) {

        case GIT_OPT_GET_MWINDOW_SIZE:
        {
            size_t size;

            error = git_libgit2_opts(GIT_OPT_GET_MWINDOW_SIZE, &size);
            if (error < 0)
                return Error_set(error);

            return PyInt_FromSize_t(size);
        }

        case GIT_OPT_SET_MWINDOW_SIZE:
        {
            size_t size;
            PyObject *py_size;

            py_size = PyTuple_GetItem(args, 1);
            if (!py_size)
                return NULL;

            if (!PyInt_Check(py_size))
                return Error_type_error(
                    "size should be an integer, got %.200s", py_size);

            size = PyInt_AsSize_t(py_size);
            error = git_libgit2_opts(GIT_OPT_SET_MWINDOW_SIZE, size);
            if (error  < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_GET_MWINDOW_MAPPED_LIMIT:
        {
            size_t limit;

            error = git_libgit2_opts(GIT_OPT_GET_MWINDOW_MAPPED_LIMIT, &limit);
            if (error < 0)
                return Error_set(error);

            return PyInt_FromSize_t(limit);
        }

        case GIT_OPT_SET_MWINDOW_MAPPED_LIMIT:
        {
            size_t limit;
            PyObject *py_limit;

            py_limit = PyTuple_GetItem(args, 1);
            if (!py_limit)
                return NULL;

            if (PyInt_Check(py_limit)) {
                limit = PyInt_AsSize_t(py_limit);
            } else if (PyLong_Check(py_limit)) {
                limit = PyLong_AsSize_t(py_limit);
            } else {
                return Error_type_error(
                    "limit should be an integer, got %.200s", py_limit);
            }

            error = git_libgit2_opts(GIT_OPT_SET_MWINDOW_MAPPED_LIMIT, limit);
            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_GET_SEARCH_PATH:
        {
            PyObject *py_level;

            py_level = PyTuple_GetItem(args, 1);
            if (!py_level)
                return NULL;

            if (!PyInt_Check(py_level))
                return Error_type_error(
                    "level should be an integer, got %.200s", py_level);

            return get_search_path(PyInt_AsLong(py_level));
        }

        case GIT_OPT_SET_SEARCH_PATH:
        {
            PyObject *py_level, *py_path, *tpath;
            const char *path;
            int err;

            py_level = PyTuple_GetItem(args, 1);
            if (!py_level)
                return NULL;

            py_path = PyTuple_GetItem(args, 2);
            if (!py_path)
                return NULL;

            if (!PyInt_Check(py_level))
                return Error_type_error(
                    "level should be an integer, got %.200s", py_level);

            path = py_str_borrow_c_str(&tpath, py_path, NULL);
            if (!path)
                return NULL;

            err = git_libgit2_opts(
                GIT_OPT_SET_SEARCH_PATH, PyInt_AsLong(py_level), path);
            Py_DECREF(tpath);

            if (err < 0)
                return Error_set(err);

            Py_RETURN_NONE;
        }

        case GIT_OPT_SET_CACHE_OBJECT_LIMIT:
        {
            size_t limit;
            int object_type;
            PyObject *py_object_type, *py_limit;

            py_object_type = PyTuple_GetItem(args, 1);
            if (!py_object_type)
                return NULL;

            py_limit = PyTuple_GetItem(args, 2);
            if (!py_limit)
                return NULL;

            if (!PyInt_Check(py_limit))
                return Error_type_error(
                    "limit should be an integer, got %.200s", py_limit);

            object_type = PyInt_AsLong(py_object_type);
            limit = PyInt_AsSize_t(py_limit);
            error = git_libgit2_opts(
                GIT_OPT_SET_CACHE_OBJECT_LIMIT, object_type, limit);

            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_SET_CACHE_MAX_SIZE:
        {
            size_t max_size;
            PyObject *py_max_size;

            py_max_size = PyTuple_GetItem(args, 1);
            if (!py_max_size)
                return NULL;

            if (!PyInt_Check(py_max_size))
                return Error_type_error(
                    "max_size should be an integer, got %.200s", py_max_size);

            max_size = PyInt_AsSize_t(py_max_size);
            error = git_libgit2_opts(GIT_OPT_SET_CACHE_MAX_SIZE, max_size);
            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_GET_CACHED_MEMORY:
        {
            size_t current;
            size_t allowed;
            PyObject* tup = PyTuple_New(2);

            error = git_libgit2_opts(GIT_OPT_GET_CACHED_MEMORY, &current, &allowed);
            if (error < 0)
                return Error_set(error);

            PyTuple_SetItem(tup, 0, PyInt_FromLong(current));
            PyTuple_SetItem(tup, 1, PyInt_FromLong(allowed));

            return tup;
        }

        case GIT_OPT_SET_SSL_CERT_LOCATIONS:
        {
            PyObject *py_file, *py_dir;
            const char *file_path, *dir_path;
            int err;

            py_file = PyTuple_GetItem(args, 1);
            py_dir = PyTuple_GetItem(args, 2);

            /* py_file and py_dir are only valid if they are strings */
            if (PyUnicode_Check(py_file) || PyBytes_Check(py_file)) {
                file_path = py_str_to_c_str(py_file, Py_FileSystemDefaultEncoding);
            } else {
                file_path = NULL;
            }

            if (PyUnicode_Check(py_dir) || PyBytes_Check(py_dir)) {
                dir_path = py_str_to_c_str(py_dir, Py_FileSystemDefaultEncoding);
            } else {
                dir_path = NULL;
            }

            err = git_libgit2_opts(GIT_OPT_SET_SSL_CERT_LOCATIONS, file_path, dir_path);

            if (err < 0)
                return Error_set(err);

            Py_RETURN_NONE;
        }

        // int enabled
        case GIT_OPT_ENABLE_CACHING:
        case GIT_OPT_ENABLE_STRICT_OBJECT_CREATION:
        case GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION:
        case GIT_OPT_ENABLE_OFS_DELTA:
        case GIT_OPT_ENABLE_FSYNC_GITDIR:
        case GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION:
        case GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY:
        {
            PyObject *py_enabled;
            int enabled;

            py_enabled = PyTuple_GetItem(args, 1);
            if (!py_enabled)
                return NULL;

            if (!PyInt_Check(py_enabled))
                return Error_type_error("expected integer, got %.200s", py_enabled);

            enabled = PyInt_AsSize_t(py_enabled);
            error = git_libgit2_opts(option, enabled);
            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        // Not implemented
        case GIT_OPT_GET_TEMPLATE_PATH:
        case GIT_OPT_SET_TEMPLATE_PATH:
        case GIT_OPT_SET_USER_AGENT:
        case GIT_OPT_SET_SSL_CIPHERS:
        case GIT_OPT_GET_USER_AGENT:
        case GIT_OPT_GET_WINDOWS_SHAREMODE:
        case GIT_OPT_SET_WINDOWS_SHAREMODE:
        case GIT_OPT_SET_ALLOCATOR:
        case GIT_OPT_GET_PACK_MAX_OBJECTS:
        case GIT_OPT_SET_PACK_MAX_OBJECTS:
        {
            Py_INCREF(Py_NotImplemented);
            return Py_NotImplemented;
        }

    }

    PyErr_SetString(PyExc_ValueError, "unknown/unsupported option value");
    return NULL;
}
Esempio n. 9
0
static PyObject *Py_write_png(PyObject *self, PyObject *args, PyObject *kwds)
{
    numpy::array_view<unsigned char, 3> buffer;
    PyObject *filein;
    double dpi = 0;
    const char *names[] = { "buffer", "file", "dpi", NULL };

    if (!PyArg_ParseTupleAndKeywords(args,
                                     kwds,
                                     "O&O|d:write_png",
                                     (char **)names,
                                     &buffer.converter,
                                     &buffer,
                                     &filein,
                                     &dpi)) {
        return NULL;
    }

    png_uint_32 width = (png_uint_32)buffer.dim(1);
    png_uint_32 height = (png_uint_32)buffer.dim(0);
    std::vector<png_bytep> row_pointers(height);
    for (png_uint_32 row = 0; row < (png_uint_32)height; ++row) {
        row_pointers[row] = (png_bytep)buffer[row].data();
    }

    FILE *fp = NULL;
    mpl_off_t offset = 0;
    bool close_file = false;
    bool close_dup_file = false;
    PyObject *py_file = NULL;

    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;
    struct png_color_8_struct sig_bit;

    if (buffer.dim(2) != 4) {
        PyErr_SetString(PyExc_ValueError, "Buffer must be RGBA NxMx4 array");
        goto exit;
    }

    if (PyBytes_Check(filein) || PyUnicode_Check(filein)) {
        if ((py_file = mpl_PyFile_OpenFile(filein, (char *)"wb")) == NULL) {
            goto exit;
        }
        close_file = true;
    } else {
        py_file = filein;
    }

    if ((fp = mpl_PyFile_Dup(py_file, (char *)"wb", &offset))) {
        close_dup_file = true;
    } else {
        PyErr_Clear();
        PyObject *write_method = PyObject_GetAttrString(py_file, "write");
        if (!(write_method && PyCallable_Check(write_method))) {
            Py_XDECREF(write_method);
            PyErr_SetString(PyExc_TypeError,
                            "Object does not appear to be a 8-bit string path or "
                            "a Python file-like object");
            goto exit;
        }
        Py_XDECREF(write_method);
    }

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png_ptr == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Could not create write struct");
        goto exit;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Could not create info struct");
        goto exit;
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
        PyErr_SetString(PyExc_RuntimeError, "Error setting jumps");
        goto exit;
    }

    if (fp) {
        png_init_io(png_ptr, fp);
    } else {
        png_set_write_fn(png_ptr, (void *)py_file, &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 (dpi > 0.0) {
        png_uint_32 dots_per_meter = (png_uint_32)(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[0]);
    png_write_end(png_ptr, info_ptr);

exit:

    if (png_ptr && info_ptr) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
    }

    if (close_dup_file) {
        mpl_PyFile_DupClose(py_file, fp, offset);
    }

    if (close_file) {
        mpl_PyFile_CloseFile(py_file);
        Py_DECREF(py_file);
    }

    if (PyErr_Occurred()) {
        return NULL;
    } else {
        Py_RETURN_NONE;
    }
}
Esempio n. 10
0
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
   with    LOAD_CONST binop(c1,c2)
   The consts table must still be in list form so that the
   new constant can be appended.
   Called with codestr pointing to the first LOAD_CONST.
   Abandons the transformation if the folding fails (i.e.  1+'a').
   If the new constant is a sequence, only folds when the size
   is below a threshold value.  That keeps pyc files from
   becoming large in the presence of code like:  (None,)*1000.
*/
static int
fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst, *v, *w;
    Py_ssize_t len_consts, size;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);
    assert(codestr[3] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
    opcode = codestr[6];
    switch (opcode) {
        case BINARY_POWER:
            newconst = PyNumber_Power(v, w, Py_None);
            break;
        case BINARY_MULTIPLY:
            newconst = PyNumber_Multiply(v, w);
            break;
        case BINARY_DIVIDE:
            /* Cannot fold this operation statically since
               the result can depend on the run-time presence
               of the -Qnew flag */
            return 0;
        case BINARY_TRUE_DIVIDE:
            newconst = PyNumber_TrueDivide(v, w);
            break;
        case BINARY_FLOOR_DIVIDE:
            newconst = PyNumber_FloorDivide(v, w);
            break;
        case BINARY_MODULO:
            newconst = PyNumber_Remainder(v, w);
            break;
        case BINARY_ADD:
            newconst = PyNumber_Add(v, w);
            break;
        case BINARY_SUBTRACT:
            newconst = PyNumber_Subtract(v, w);
            break;
        case BINARY_SUBSCR:
            newconst = PyObject_GetItem(v, w);
            /* #5057: if v is unicode, there might be differences between
               wide and narrow builds in cases like u'\U00012345'[0].
               Wide builds will return a non-BMP char, whereas narrow builds
               will return a surrogate.  In both the cases skip the
               optimization in order to produce compatible pycs.
             */
            if (newconst != NULL &&
                PyUnicode_Check(v) && PyUnicode_Check(newconst)) {
                Py_UNICODE ch = PyUnicode_AS_UNICODE(newconst)[0];
#ifdef Py_UNICODE_WIDE
                if (ch > 0xFFFF) {
#else
                if (ch >= 0xD800 && ch <= 0xDFFF) {
#endif
                    Py_DECREF(newconst);
                    return 0;
                }
            }
            break;
        case BINARY_LSHIFT:
            newconst = PyNumber_Lshift(v, w);
            break;
        case BINARY_RSHIFT:
            newconst = PyNumber_Rshift(v, w);
            break;
        case BINARY_AND:
            newconst = PyNumber_And(v, w);
            break;
        case BINARY_XOR:
            newconst = PyNumber_Xor(v, w);
            break;
        case BINARY_OR:
            newconst = PyNumber_Or(v, w);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected binary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        PyErr_Clear();
        return 0;
    }
    size = PyObject_Size(newconst);
    if (size == -1)
        PyErr_Clear();
    else if (size > 20) {
        Py_DECREF(newconst);
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP NOP NOP NOP LOAD_CONST newconst */
    memset(codestr, NOP, 4);
    codestr[4] = LOAD_CONST;
    SETARG(codestr, 4, len_consts);
    return 1;
}

static int
fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst=NULL, *v;
    Py_ssize_t len_consts;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    opcode = codestr[3];
    switch (opcode) {
        case UNARY_NEGATIVE:
            /* Preserve the sign of -0.0 */
            if (PyObject_IsTrue(v) == 1)
                newconst = PyNumber_Negative(v);
            break;
        case UNARY_CONVERT:
            newconst = PyObject_Repr(v);
            break;
        case UNARY_INVERT:
            newconst = PyNumber_Invert(v);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected unary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        PyErr_Clear();
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP LOAD_CONST newconst */
    codestr[0] = NOP;
    codestr[1] = LOAD_CONST;
    SETARG(codestr, 1, len_consts);
    return 1;
}
Esempio n. 11
0
bool JPyString::checkUnicode(PyObject* obj)
{
	return PyUnicode_Check(obj);
}
Esempio n. 12
0
char *py_strerror(char *buf, size_t len)
{
	PyObject *type, *value, *trace;
	PyObject *frame, *code;
	PyObject *str = NULL, *line_no, *file_name;
	PyObject *fname_ascii = NULL, *msg_ascii = NULL;
	char *msg, *fname = NULL, *slash;
	long lineno = -1;

	PyErr_Fetch(&type, &value, &trace);
	PyErr_NormalizeException(&type, &value, &trace);

	/* message */
	str = PyObject_Str(value);
	if (str == NULL) {
		snprintf(buf, len, "(could not get message)");
		goto decref;
	}
	if (PyUnicode_Check(str)) {
		msg_ascii = PyUnicode_AsASCIIString(str);
		msg = PyBytes_AsString(msg_ascii);
	} else if (PyBytes_Check(str)) {
		msg = PyBytes_AsString(str);
	} else {
		snprintf(buf, len, "(could not decode message)");
		Py_DECREF(str);
		goto decref;
	}
	Py_DECREF(str);

	if (trace == NULL) {
		snprintf(buf, len, "(no trace) %s", msg);
		goto decref_msg_ascii;
	}

	/* file name */
	frame = PyObject_GetAttrString(trace, "tb_frame");
	if (frame == NULL) {
		snprintf(buf, len, "(could not get frame) %s", msg);
		goto decref_msg_ascii;
	}
	code = PyObject_GetAttrString(frame, "f_code");
	Py_DECREF(frame);
	if (code == NULL) {
		snprintf(buf, len, "(could not get frame code) %s", msg);
		goto decref_msg_ascii;
	}
	file_name = PyObject_GetAttrString(code, "co_filename");
	Py_DECREF(code);
	if (file_name == NULL) {
		snprintf(buf, len, "(could not get filename) %s", msg);
		goto decref_msg_ascii;
	}
	str = PyObject_Str(file_name);
	Py_DECREF(file_name);
	if (str == NULL) {
		snprintf(buf, len, "(could not get filename str) %s", msg);
		goto decref_msg_ascii;
	}
	fname_ascii = PyUnicode_AsASCIIString(str);
	Py_DECREF(str);
	if (fname_ascii == NULL) {
		snprintf(buf, len, "(could not get filename ascii) %s", msg);
		goto decref_msg_ascii;
	}
	fname = PyBytes_AsString(fname_ascii);
	if ((slash = strrchr(fname, '/')) != NULL)
		fname = slash + 1;

	/* line number */
	line_no = PyObject_GetAttrString(trace, "tb_lineno");
	if (line_no == NULL) {
		snprintf(buf, len, "%s: (could not get lineno) %s", fname, msg);
		goto decref_fname_ascii;
	}
	if (!PyLong_Check(line_no)) {
		snprintf(buf, len, "%s: (lineno is not an integer) %s",
			 fname, msg);
		Py_DECREF(line_no);
		goto decref_fname_ascii;;
	}
	lineno = PyLong_AsLong(line_no);
	Py_DECREF(line_no);

	snprintf(buf, len, "%s[%ld]: %s", fname, lineno, msg);

decref_fname_ascii:
	Py_XDECREF(fname_ascii);
decref_msg_ascii:
	Py_XDECREF(msg_ascii);
decref:
	buf[len - 1] = '\0';
	Py_DECREF(type);
	Py_DECREF(value);
	Py_XDECREF(trace); /* may be NULL? */

	return buf;
}
Esempio n. 13
0
static int
encode_common(PyObject *src, pycbc_pybuffer *dst, lcb_U32 flags)
{
    PyObject *bytesobj;
    Py_ssize_t plen;
    int rv;

    if (flags == PYCBC_FMT_UTF8) {
#if PY_MAJOR_VERSION == 2
        if (PyString_Check(src)) {
#else
        if (0) {
#endif
            bytesobj = src;
            Py_INCREF(bytesobj);
        } else {
            if (!PyUnicode_Check(src)) {
                PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING,
                                   0, "Must be unicode or string", src);
                return -1;
            }
            bytesobj = PyUnicode_AsUTF8String(src);
        }
    } else if (flags == PYCBC_FMT_BYTES) {
        if (PyBytes_Check(src) || PyByteArray_Check(src)) {
            bytesobj = src;
            Py_INCREF(bytesobj);
        } else {
            PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING, 0,
                               "Must be bytes or bytearray", src);
            return -1;
        }

    } else {
        PyObject *args = NULL;
        PyObject *helper;

        if (flags == PYCBC_FMT_PICKLE) {
            helper = pycbc_helpers.pickle_encode;

        } else if (flags == PYCBC_FMT_JSON) {
            helper = pycbc_helpers.json_encode;

        } else {
            PYCBC_EXC_WRAP(PYCBC_EXC_ARGUMENTS, 0, "Unrecognized format");
            return -1;
        }

        args = PyTuple_Pack(1, src);
        bytesobj = PyObject_CallObject(helper, args);
        Py_DECREF(args);

        if (!bytesobj) {
            PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING,
                               0, "Couldn't encode value", src);
            return -1;
        }

        if (!PyBytes_Check(bytesobj)) {
            PyObject *old = bytesobj;
            bytesobj = convert_to_bytesobj(old);
            Py_DECREF(old);
            if (!bytesobj) {
                return -1;
            }
        }
    }

    if (PyByteArray_Check(bytesobj)) {
        dst->buffer = PyByteArray_AS_STRING(bytesobj);
        plen = PyByteArray_GET_SIZE(bytesobj);
        rv = 0;
    } else {
        rv = PyBytes_AsStringAndSize(bytesobj, (char**)&dst->buffer, &plen);
    }

    if (rv < 0) {
        Py_DECREF(bytesobj);
        PYCBC_EXC_WRAP(PYCBC_EXC_ENCODING, 0, "Couldn't encode value");
        return -1;
    }

    dst->pyobj = bytesobj;
    dst->length = plen;
    return 0;
}


static int
decode_common(PyObject **vp, const char *buf, size_t nbuf, lcb_uint32_t flags)
{
    PyObject *decoded = NULL;

    /* Strip away non-common-flag info if we are indeed common flags */
    if (flags & PYCBC_FMT_COMMON_MASK) {
        flags &= PYCBC_FMT_COMMON_MASK;
    }

    #define FMT_MATCHES(fmtbase) \
        (flags == PYCBC_FMT_COMMON_##fmtbase) || \
        (flags == PYCBC_FMT_LEGACY_##fmtbase)

    if (FMT_MATCHES(UTF8)) {
        decoded = convert_to_string(buf, nbuf, CONVERT_MODE_UTF8_ONLY);
        if (!decoded) {
            return -1;
        }

    } else if (FMT_MATCHES(BYTES)) {
        GT_BYTES:
        decoded = convert_to_string(buf, nbuf, CONVERT_MODE_BYTES_ONLY);
        pycbc_assert(decoded);

    } else {
        PyObject *converter = NULL;
        PyObject *args = NULL;
        PyObject *first_arg = NULL;

        if (FMT_MATCHES(PICKLE)) {
            converter = pycbc_helpers.pickle_decode;
            first_arg = convert_to_string(buf, nbuf, CONVERT_MODE_BYTES_ONLY);
            pycbc_assert(first_arg);

        } else if (FMT_MATCHES(JSON)) {
            converter = pycbc_helpers.json_decode;
            first_arg = convert_to_string(buf, nbuf, CONVERT_MODE_UTF8_ONLY);

            if (!first_arg) {
                return -1;
            }

        } else {
            PyErr_Warn(PyExc_UserWarning, "Unrecognized flags. Forcing bytes");
            goto GT_BYTES;
        }

        pycbc_assert(first_arg);
        args = PyTuple_Pack(1, first_arg);
        decoded = PyObject_CallObject(converter, args);

        Py_DECREF(args);
        Py_DECREF(first_arg);
    }

    if (!decoded) {
        PyObject *bytes_tmp = PyBytes_FromStringAndSize(buf, nbuf);
        PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING, 0, "Failed to decode bytes",
                           bytes_tmp);
        Py_XDECREF(bytes_tmp);
        return -1;
    }

    *vp = decoded;
    return 0;

    #undef FMT_MATCHES
}
Esempio n. 14
0
int
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
{
	PyTypeObject *tp = obj->ob_type;
	PyObject *descr;
	descrsetfunc f;
	PyObject **dictptr;
	int res = -1;

	if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
		/* The Unicode to string conversion is done here because the
		   existing tp_setattro slots expect a string object as name
		   and we wouldn't want to break those. */
		if (PyUnicode_Check(name)) {
			name = PyUnicode_AsEncodedString(name, NULL, NULL);
			if (name == NULL)
				return -1;
		}
		else
#endif
		{
			PyErr_Format(PyExc_TypeError,
				     "attribute name must be string, not '%.200s'",
				     name->ob_type->tp_name);
			return -1;
		}
	}
	else
		Py_INCREF(name);

	if (tp->tp_dict == NULL) {
		if (PyType_Ready(tp) < 0)
			goto done;
	}

	descr = _PyType_Lookup(tp, name);
	f = NULL;
	if (descr != NULL &&
	    PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
		f = descr->ob_type->tp_descr_set;
		if (f != NULL && PyDescr_IsData(descr)) {
			res = f(descr, obj, value);
			goto done;
		}
	}

	dictptr = _PyObject_GetDictPtr(obj);
	if (dictptr != NULL) {
		PyObject *dict = *dictptr;
		if (dict == NULL && value != NULL) {
			dict = PyDict_New();
			if (dict == NULL)
				goto done;
			*dictptr = dict;
		}
		if (dict != NULL) {
			Py_INCREF(dict);
			if (value == NULL)
				res = PyDict_DelItem(dict, name);
			else
				res = PyDict_SetItem(dict, name, value);
			if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
				PyErr_SetObject(PyExc_AttributeError, name);
			Py_DECREF(dict);
			goto done;
		}
	}

	if (f != NULL) {
		res = f(descr, obj, value);
		goto done;
	}

	if (descr == NULL) {
		PyErr_Format(PyExc_AttributeError,
			     "'%.100s' object has no attribute '%.200s'",
			     tp->tp_name, PyString_AS_STRING(name));
		goto done;
	}

	PyErr_Format(PyExc_AttributeError,
		     "'%.50s' object attribute '%.400s' is read-only",
		     tp->tp_name, PyString_AS_STRING(name));
  done:
	Py_DECREF(name);
	return res;
}
Esempio n. 15
0
/* trigger subhandler
 *
 * the python function is expected to return Py_None if the tuple is
 * acceptable and unmodified.  Otherwise it should return a PyString
 * object who's value is SKIP, or MODIFY.  SKIP means don't perform
 * this action.  MODIFY means the tuple has been modified, so update
 * tuple and perform action.  SKIP and MODIFY assume the trigger fires
 * BEFORE the event and is ROW level.  postgres expects the function
 * to take no arguments and return an argument of type trigger.
 */
HeapTuple
PLy_exec_trigger(FunctionCallInfo fcinfo, PLyProcedure *proc)
{
	HeapTuple	rv = NULL;
	PyObject   *volatile plargs = NULL;
	PyObject   *volatile plrv = NULL;
	TriggerData *tdata;

	Assert(CALLED_AS_TRIGGER(fcinfo));

	/*
	 * Input/output conversion for trigger tuples.  Use the result TypeInfo
	 * variable to store the tuple conversion info.  We do this over again on
	 * each call to cover the possibility that the relation's tupdesc changed
	 * since the trigger was last called. PLy_input_tuple_funcs and
	 * PLy_output_tuple_funcs are responsible for not doing repetitive work.
	 */
	tdata = (TriggerData *) fcinfo->context;

	PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
	PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);

	PG_TRY();
	{
		plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
		plrv = PLy_procedure_call(proc, "TD", plargs);

		Assert(plrv != NULL);

		/*
		 * Disconnect from SPI manager
		 */
		if (SPI_finish() != SPI_OK_FINISH)
			elog(ERROR, "SPI_finish failed");

		/*
		 * return of None means we're happy with the tuple
		 */
		if (plrv != Py_None)
		{
			char	   *srv;

			if (PyString_Check(plrv))
				srv = PyString_AsString(plrv);
			else if (PyUnicode_Check(plrv))
				srv = PLyUnicode_AsString(plrv);
			else
			{
				ereport(ERROR,
						(errcode(ERRCODE_DATA_EXCEPTION),
					errmsg("unexpected return value from trigger procedure"),
						 errdetail("Expected None or a string.")));
				srv = NULL;		/* keep compiler quiet */
			}

			if (pg_strcasecmp(srv, "SKIP") == 0)
				rv = NULL;
			else if (pg_strcasecmp(srv, "MODIFY") == 0)
			{
				TriggerData *tdata = (TriggerData *) fcinfo->context;

				if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
					TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
					rv = PLy_modify_tuple(proc, plargs, tdata, rv);
				else
					ereport(WARNING,
							(errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
			}
			else if (pg_strcasecmp(srv, "OK") != 0)
			{
				/*
				 * accept "OK" as an alternative to None; otherwise, raise an
				 * error
				 */
				ereport(ERROR,
						(errcode(ERRCODE_DATA_EXCEPTION),
					errmsg("unexpected return value from trigger procedure"),
						 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
			}
		}
	}
	PG_CATCH();
	{
		Py_XDECREF(plargs);
		Py_XDECREF(plrv);

		PG_RE_THROW();
	}
	PG_END_TRY();

	Py_DECREF(plargs);
	Py_DECREF(plrv);

	return rv;
}
Esempio n. 16
0
PyObject *py_uwsgi_spit(PyObject * self, PyObject * args) {
    PyObject *headers, *head;
    PyObject *h_key, *h_value;
    PyObject *exc_info = NULL;
    size_t i;

    struct wsgi_request *wsgi_req = py_current_wsgi_req();

    // avoid double sending of headers
    if (wsgi_req->headers_sent) {
        return PyErr_Format(PyExc_IOError, "headers already sent");
    }

    // this must be done before headers management
    if (PyTuple_Size(args) > 2) {
        exc_info = PyTuple_GetItem(args, 2);
        if (exc_info && exc_info != Py_None) {
            PyObject *exc_type = PyTuple_GetItem(exc_info, 0);
            PyObject *exc_val = PyTuple_GetItem(exc_info, 1);
            PyObject *exc_tb = PyTuple_GetItem(exc_info, 2);

            if (!exc_type || !exc_val || !exc_tb) {
                return NULL;
            }

            Py_INCREF(exc_type);
            Py_INCREF(exc_val);
            Py_INCREF(exc_tb);
            // in this way, error will be reported to the log
            PyErr_Restore(exc_type, exc_val, exc_tb);

            // the error is reported, let's continue...
            // return NULL
        }
    }

    head = PyTuple_GetItem(args, 0);
    if (!head) {
        return PyErr_Format(PyExc_TypeError, "start_response() takes at least 2 arguments");
    }

#ifdef PYTHREE
    // check for web3
    if ((self != Py_None && !PyUnicode_Check(head)) || (self == Py_None && !PyBytes_Check(head))) {
#else
    if (!PyString_Check(head)) {
#endif
        return PyErr_Format(PyExc_TypeError, "http status must be a string");
    }

    char *status_line = NULL;
    size_t status_line_len = 0;
#ifdef PYTHREE
    PyObject *zero = NULL;
    PyObject *zero2 = NULL;
    if (self != Py_None) {
        zero = PyUnicode_AsASCIIString(head);
        if (!zero) {
            return PyErr_Format(PyExc_TypeError, "http status string must be encodable in latin1");
        }
        status_line = PyBytes_AsString(zero);
        status_line_len = PyBytes_Size(zero);
    }
    else {
        status_line = PyBytes_AsString(head);
        status_line_len = PyBytes_Size(head);
    }
#else
    status_line = PyString_AsString(head);
    status_line_len = PyString_Size(head);
#endif
    if (uwsgi_response_prepare_headers(wsgi_req, status_line, status_line_len)) {
#ifdef PYTHREE
        Py_DECREF(zero);
#endif
        goto end;
    }

#ifdef PYTHREE
    Py_DECREF(zero);
#endif

    headers = PyTuple_GetItem(args, 1);
    if (!headers) {
        return PyErr_Format(PyExc_TypeError, "start_response() takes at least 2 arguments");
    }

    if (!PyList_Check(headers)) {
        return PyErr_Format(PyExc_TypeError, "http headers must be in a python list");
    }

    size_t h_count = PyList_Size(headers);

    for (i = 0; i < h_count; i++) {
        head = PyList_GetItem(headers, i);
        if (!head) {
            return NULL;
        }
        if (!PyTuple_Check(head)) {
            return PyErr_Format(PyExc_TypeError, "http header must be defined in a tuple");
        }
        h_key = PyTuple_GetItem(head, 0);
        if (!h_key) {
            return PyErr_Format(PyExc_TypeError, "http header must be a 2-item tuple");
        }
#ifdef PYTHREE
        if ((self != Py_None && !PyUnicode_Check(h_key)) || (self == Py_None && !PyBytes_Check(h_key))) {
#else
        if (!PyString_Check(h_key)) {
#endif
            return PyErr_Format(PyExc_TypeError, "http header key must be a string");
        }
        h_value = PyTuple_GetItem(head, 1);
        if (!h_value) {
            return PyErr_Format(PyExc_TypeError, "http header must be a 2-item tuple");
        }
#ifdef PYTHREE
        if ((self != Py_None && !PyUnicode_Check(h_value)) || (self == Py_None && !PyBytes_Check(h_value))) {
#else
        if (!PyString_Check(h_value)) {
#endif
            return PyErr_Format(PyExc_TypeError, "http header value must be a string");
        }


        char *k = NULL;
        size_t kl = 0;
        char *v = NULL;
        size_t vl = 0;

#ifdef PYTHREE
        if (self != Py_None) {
            zero = PyUnicode_AsASCIIString(h_key);
            if (!zero) {
                return PyErr_Format(PyExc_TypeError, "http header must be encodable in latin1");
            }
            k = PyBytes_AsString(zero);
            kl = PyBytes_Size(zero);
        }
        else {
            k = PyBytes_AsString(h_key);
            kl = PyBytes_Size(h_key);
        }
#else
        k = PyString_AsString(h_key);
        kl = PyString_Size(h_key);
#endif

#ifdef PYTHREE
        if (self != Py_None) {
            zero2 = PyUnicode_AsASCIIString(h_value);
            if (!zero2) {
                return PyErr_Format(PyExc_TypeError, "http header must be encodable in latin1");
            }
            v = PyBytes_AsString(zero2);
            vl = PyBytes_Size(zero2);
        }
        else {
            v = PyBytes_AsString(h_value);
            vl = PyBytes_Size(h_value);
        }
#else
        v = PyString_AsString(h_value);
        vl = PyString_Size(h_value);
#endif

        if (uwsgi_response_add_header(wsgi_req, k, kl, v, vl)) {
#ifdef PYTHREE
            Py_DECREF(zero);
            Py_DECREF(zero2);
#endif
            return PyErr_Format(PyExc_TypeError, "unable to add header to the response");
        }

#ifdef PYTHREE
        Py_DECREF(zero);
        Py_DECREF(zero2);
#endif

    }

    if (up.start_response_nodelay) {
        UWSGI_RELEASE_GIL
        if (uwsgi_response_write_headers_do(wsgi_req)) {
            UWSGI_GET_GIL
            return PyErr_Format(PyExc_IOError, "unable to directly send headers");
        }
        UWSGI_GET_GIL
    }

end:
    Py_INCREF(up.wsgi_writeout);
    return up.wsgi_writeout;
}
Esempio n. 17
0
static HeapTuple
PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
				 HeapTuple otup)
{
	PyObject   *volatile plntup;
	PyObject   *volatile plkeys;
	PyObject   *volatile plval;
	HeapTuple	rtup;
	int			natts,
				i,
				attn,
				atti;
	int		   *volatile modattrs;
	Datum	   *volatile modvalues;
	char	   *volatile modnulls;
	TupleDesc	tupdesc;
	ErrorContextCallback plerrcontext;

	plerrcontext.callback = plpython_trigger_error_callback;
	plerrcontext.previous = error_context_stack;
	error_context_stack = &plerrcontext;

	plntup = plkeys = plval = NULL;
	modattrs = NULL;
	modvalues = NULL;
	modnulls = NULL;

	PG_TRY();
	{
		if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
			ereport(ERROR,
					(errmsg("TD[\"new\"] deleted, cannot modify row")));
		Py_INCREF(plntup);
		if (!PyDict_Check(plntup))
			ereport(ERROR,
					(errmsg("TD[\"new\"] is not a dictionary")));

		plkeys = PyDict_Keys(plntup);
		natts = PyList_Size(plkeys);

		modattrs = (int *) palloc(natts * sizeof(int));
		modvalues = (Datum *) palloc(natts * sizeof(Datum));
		modnulls = (char *) palloc(natts * sizeof(char));

		tupdesc = tdata->tg_relation->rd_att;

		for (i = 0; i < natts; i++)
		{
			PyObject   *platt;
			char	   *plattstr;

			platt = PyList_GetItem(plkeys, i);
			if (PyString_Check(platt))
				plattstr = PyString_AsString(platt);
			else if (PyUnicode_Check(platt))
				plattstr = PLyUnicode_AsString(platt);
			else
			{
				ereport(ERROR,
						(errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
				plattstr = NULL;	/* keep compiler quiet */
			}
			attn = SPI_fnumber(tupdesc, plattstr);
			if (attn == SPI_ERROR_NOATTRIBUTE)
				ereport(ERROR,
						(errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
								plattstr)));
			atti = attn - 1;

			plval = PyDict_GetItem(plntup, platt);
			if (plval == NULL)
				elog(FATAL, "Python interpreter is probably corrupted");

			Py_INCREF(plval);

			modattrs[i] = attn;

			if (tupdesc->attrs[atti]->attisdropped)
			{
				modvalues[i] = (Datum) 0;
				modnulls[i] = 'n';
			}
			else if (plval != Py_None)
			{
				PLyObToDatum *att = &proc->result.out.r.atts[atti];

				modvalues[i] = (att->func) (att,
											tupdesc->attrs[atti]->atttypmod,
											plval);
				modnulls[i] = ' ';
			}
			else
			{
				modvalues[i] =
					InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
									  NULL,
									proc->result.out.r.atts[atti].typioparam,
									  tupdesc->attrs[atti]->atttypmod);
				modnulls[i] = 'n';
			}

			Py_DECREF(plval);
			plval = NULL;
		}

		rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
							   modattrs, modvalues, modnulls);
		if (rtup == NULL)
			elog(ERROR, "SPI_modifytuple failed: error %d", SPI_result);
	}
	PG_CATCH();
	{
		Py_XDECREF(plntup);
		Py_XDECREF(plkeys);
		Py_XDECREF(plval);

		if (modnulls)
			pfree(modnulls);
		if (modvalues)
			pfree(modvalues);
		if (modattrs)
			pfree(modattrs);

		PG_RE_THROW();
	}
	PG_END_TRY();

	Py_DECREF(plntup);
	Py_DECREF(plkeys);

	pfree(modattrs);
	pfree(modvalues);
	pfree(modnulls);

	error_context_stack = plerrcontext.previous;

	return rtup;
}
static int convertTo_QList_0100QLowEnergyDescriptor(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QList<QLowEnergyDescriptor> **sipCppPtr = reinterpret_cast<QList<QLowEnergyDescriptor> **>(sipCppPtrV);

#line 66 "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<QLowEnergyDescriptor> *ql = new QList<QLowEnergyDescriptor>;
 
    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;
        }

        int state;
        QLowEnergyDescriptor *t = reinterpret_cast<QLowEnergyDescriptor *>(
                sipForceConvertToType(itm, sipType_QLowEnergyDescriptor, sipTransferObj,
                        SIP_NOT_NONE, &state, sipIsErr));

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

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

            return 0;
        }

        ql->append(*t);

        sipReleaseType(t, sipType_QLowEnergyDescriptor, state);
        Py_DECREF(itm);
    }
 
    Py_DECREF(iter);

    *sipCppPtr = ql;
 
    return sipGetState(sipTransferObj);
#line 142 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtBluetooth/sipQtBluetoothQList0100QLowEnergyDescriptor.cpp"
}
Esempio n. 19
0
static int set_options(void)
{
    int_t pos=0;
    PyObject *param, *key, *value;
    char err_str[100];
#if PY_MAJOR_VERSION < 3
    char *keystr; 
#endif

    CHOL(defaults)(&Common);
    Common.print = 0;
    Common.supernodal = 2;

    if (!(param = PyObject_GetAttrString(cholmod_module, "options")) ||
        ! PyDict_Check(param)) {
        PyErr_SetString(PyExc_AttributeError, "missing cholmod.options"
            "dictionary");
        return 0;
    }
    while (PyDict_Next(param, &pos, &key, &value))
#if PY_MAJOR_VERSION >= 3
        if (PyUnicode_Check(key)) {
            const char *keystr = _PyUnicode_AsString(key);
            if (!strcmp("supernodal", keystr) && PyLong_Check(value))
                Common.supernodal = (int) PyLong_AsLong(value);
            else if (!strcmp("print", keystr) && PyLong_Check(value))
                Common.print = (int) PyLong_AsLong(value);
            else if (!strcmp("nmethods", keystr) && PyLong_Check(value))
                Common.nmethods = (int) PyLong_AsLong(value);
            else if (!strcmp("postorder", keystr) &&
                PyBool_Check(value))
                Common.postorder = (int) PyLong_AsLong(value);
            else if (!strcmp("dbound", keystr) && PyFloat_Check(value))
                Common.dbound = (double) PyFloat_AsDouble(value);
            else {
                sprintf(err_str, "invalid value for CHOLMOD parameter:" \
                   " %-.20s", keystr);
                PyErr_SetString(PyExc_ValueError, err_str);
                Py_DECREF(param);
                return 0;
            }
        }
#else
        if ((keystr = PyString_AsString(key))) {
            if (!strcmp("supernodal", keystr) && PyInt_Check(value))
                Common.supernodal = (int) PyInt_AsLong(value);
            else if (!strcmp("print", keystr) && PyInt_Check(value))
                Common.print = (int) PyInt_AsLong(value);
            else if (!strcmp("nmethods", keystr) && PyInt_Check(value))
                Common.nmethods = (int) PyInt_AsLong(value);
            else if (!strcmp("postorder", keystr) &&
                PyBool_Check(value))
                Common.postorder = (int) PyInt_AsLong(value);
            else if (!strcmp("dbound", keystr) && PyFloat_Check(value))
                Common.dbound = (double) PyFloat_AsDouble(value);
            else {
                sprintf(err_str, "invalid value for CHOLMOD parameter:" \
                   " %-.20s", keystr);
                PyErr_SetString(PyExc_ValueError, err_str);
                Py_DECREF(param);
                return 0;
            }
        }
#endif
    Py_DECREF(param);
    return 1;
}
Esempio n. 20
0
File: player.cpp Progetto: foen/xbmc
  // play a file or python playlist
  PyObject* Player_Play(Player *self, PyObject *args, PyObject *kwds)
  {
    PyObject *pObject = NULL;
    PyObject *pObjectListItem = NULL;
    char bWindowed = false;
    static const char *keywords[] = { "item", "listitem", "windowed", NULL };

    if (!PyArg_ParseTupleAndKeywords(
      args,
      kwds,
      (char*)"|OOb",
      (char**)keywords,
      &pObject,
      &pObjectListItem,
      &bWindowed))
    {
      return NULL;
    }

    // set fullscreen or windowed
    g_settings.m_bStartVideoWindowed = (0 != bWindowed);

    // force a playercore before playing
    g_application.m_eForcedNextPlayer = self->playerCore;

    if (pObject == NULL)
    {
      // play current file in playlist
      if (g_playlistPlayer.GetCurrentPlaylist() != self->iPlayList)
      {
        g_playlistPlayer.SetCurrentPlaylist(self->iPlayList);
      }
      g_application.getApplicationMessenger().PlayListPlayerPlay(g_playlistPlayer.GetCurrentSong());
    }
    else if ((PyString_Check(pObject) || PyUnicode_Check(pObject)) && pObjectListItem != NULL && ListItem_CheckExact(pObjectListItem))
    {
      // an optional listitem was passed
      ListItem* pListItem = NULL;
      pListItem = (ListItem*)pObjectListItem;

      // set m_strPath to the passed url
      pListItem->item->m_strPath = PyString_AsString(pObject);

      g_application.getApplicationMessenger().PlayFile((const CFileItem)*pListItem->item, false);
    }
    else if (PyString_Check(pObject) || PyUnicode_Check(pObject))
    {
      CFileItem item(PyString_AsString(pObject), false);
      g_application.getApplicationMessenger().MediaPlay(item.m_strPath);
    }
    else if (PlayList_Check(pObject))
    {
      // play a python playlist (a playlist from playlistplayer.cpp)
      PlayList* pPlayList = (PlayList*)pObject;
      self->iPlayList = pPlayList->iPlayList;
      g_playlistPlayer.SetCurrentPlaylist(pPlayList->iPlayList);
      g_application.getApplicationMessenger().PlayListPlayerPlay();
    }

    Py_INCREF(Py_None);
    return Py_None;
  }
Esempio n. 21
0
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
    if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
            __Pyx_sys_getdefaultencoding_not_ascii && 
#endif
            PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
        char* defenc_c;
        // borrowed, cached reference
        PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
        if (!defenc) return NULL;
        defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        {
            char* end = defenc_c + PyBytes_GET_SIZE(defenc);
            char* c;
            for (c = defenc_c; c < end; c++) {
                if ((unsigned char) (*c) >= 128) {
                    // raise the error
                    PyUnicode_AsASCIIString(o);
                    return NULL;
                }
            }
        }
#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/
        *length = PyBytes_GET_SIZE(defenc);
        return defenc_c;
#else /* PY_VERSION_HEX < 0x03030000 */
        if (PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        if (PyUnicode_IS_ASCII(o)) {
            // cached for the lifetime of the object
            *length = PyUnicode_GET_DATA_SIZE(o);
            return PyUnicode_AsUTF8(o);
        } else {
            // raise the error
            PyUnicode_AsASCIIString(o);
            return NULL;
        }
#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
        return PyUnicode_AsUTF8AndSize(o, length);
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
#endif /* PY_VERSION_HEX < 0x03030000 */
    } else
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII  || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */

#if PY_VERSION_HEX >= 0x02060000
    if (PyByteArray_Check(o)) {
        *length = PyByteArray_GET_SIZE(o);
        return PyByteArray_AS_STRING(o);
    } else
#endif
    {
        char* result;
        int r = PyBytes_AsStringAndSize(o, &result, length);
        if (unlikely(r < 0)) {
            return NULL;
        } else {
            return result;
        }
    }
}
Esempio n. 22
0
File: type.c Progetto: zillow/ctds
static PyObject* translate_to_ucs2(PyObject* o)
{
    PyObject* translated = NULL;
    Py_ssize_t len;
    wchar_t* unicode;

    assert(PyUnicode_Check(o));
#if PY_MAJOR_VERSION < 3
    len = PyUnicode_GetSize(o);
    do
    {
        unicode = tds_mem_malloc((size_t)len * sizeof(wchar_t));
        if (!unicode)
        {
            PyErr_NoMemory();
            break;
        }
        if (-1 == PyUnicode_AsWideChar((PyUnicodeObject*)o, unicode, len))
        {
            break;
        }
    }
    while (0);
#else /* if PY_MAJOR_VERSION < 3 */
    unicode = PyUnicode_AsWideCharString(o, &len);
#endif /* else if PY_MAJOR_VERSION < 3 */

    if (!PyErr_Occurred())
    {
        Py_ssize_t ixsrc, ixdst = 0;
        for (ixsrc = 0; ixsrc < len; ++ixsrc, ++ixdst)
        {
#if defined(WCHAR_T_UCS4)
            if (0xFFFF < unicode[ixsrc])
#else /* if defined(WCHAR_T_UCS4) */
            if (Py_UNICODE_IS_SURROGATE(unicode[ixsrc]))
#endif /* else if defined(WCHAR_T_UCS4) */
            {
                static const char s_fmt[] =
                    "Unicode codepoint U+%08X is not representable in UCS-2; replaced with U+FFFD";
                char buffer[ARRAYSIZE(s_fmt) + 8 /* for codepoint chars */];
#if defined(WCHAR_T_UCS4)
                uint32_t codepoint = (uint32_t)unicode[ixsrc];
#else /* if defined(WCHAR_T_UCS4) */
                uint32_t codepoint;
                assert(((ixsrc + 1) < len) && Py_UNICODE_IS_SURROGATE(unicode[ixsrc + 1]));
                codepoint = Py_UNICODE_JOIN_SURROGATES(unicode[ixsrc], unicode[ixsrc + 1]);
                ++ixsrc;
#endif /* else if defined(WCHAR_T_UCS4) */
                (void)sprintf(buffer, s_fmt, codepoint);
                if (0 != PyErr_WarnEx(PyExc_UnicodeWarning, buffer, 1))
                {
                    break;
                }

                unicode[ixdst] = 0xFFFD; /* unicode replacement character */
            }
#if !defined(WCHAR_T_UCS4)
            else
            {
                unicode[ixdst] = unicode[ixsrc];
            }
#endif /* if !defined(WCHAR_T_UCS4) */
        }

        if (!PyErr_Occurred())
        {
            translated = PyUnicode_FromWideChar(unicode, ixdst);
        }
    }
#if PY_MAJOR_VERSION < 3
    tds_mem_free(unicode);
#else /* if PY_MAJOR_VERSION < 3 */
    PyMem_Free(unicode);
#endif /* else if PY_MAJOR_VERSION < 3 */

    return translated;
}
Esempio n. 23
0
NPY_NO_EXPORT int
PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
                              PyArray_Descr **out_dtype, int string_type)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
    Py_buffer buffer_view;
    /* types for sequence handling */
    PyObject ** objects;
    PyObject * seq;
    PyTypeObject * common_type;

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* See if it's a python None */
    if (obj == Py_None) {
        dtype = PyArray_DescrFromType(NPY_OBJECT);
        if (dtype == NULL) {
            goto fail;
        }
        Py_INCREF(dtype);
        goto promote_types;
    }
    /* Check if it's a NumPy scalar */
    else if (PyArray_IsScalar(obj, Generic)) {
        if (!string_type) {
            dtype = PyArray_DescrFromScalar(obj);
            if (dtype == NULL) {
                goto fail;
            }
        }
        else {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        if (string_type) {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* PEP 3118 buffer interface */
    if (PyObject_CheckBuffer(obj) == 1) {
        memset(&buffer_view, 0, sizeof(Py_buffer));
        if (PyObject_GetBuffer(obj, &buffer_view,
                               PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
            PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

            PyErr_Clear();
            dtype = _descriptor_from_pep3118_format(buffer_view.format);
            PyBuffer_Release(&buffer_view);
            if (dtype) {
                goto promote_types;
            }
        }
        else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
                 PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

            PyErr_Clear();
            dtype = PyArray_DescrNewFromType(NPY_VOID);
            dtype->elsize = buffer_view.itemsize;
            PyBuffer_Release(&buffer_view);
            goto promote_types;
        }
        else {
            PyErr_Clear();
        }
    }

    /* The array interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
#if defined(NPY_PY3K)
            PyObject *tmp = NULL;
#endif
            typestr = PyDict_GetItemString(ip, "typestr");
#if defined(NPY_PY3K)
            /* Allow unicode type strings */
            if (PyUnicode_Check(typestr)) {
                tmp = PyUnicode_AsASCIIString(typestr);
                typestr = tmp;
            }
#endif
            if (typestr && PyBytes_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr));
#if defined(NPY_PY3K)
                if (tmp == typestr) {
                    Py_DECREF(tmp);
                }
#endif
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The array struct interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array__");
    if (ip != NULL) {
        Py_DECREF(ip);
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
     */
    if (maxdims == 0 || !PySequence_Check(obj)) {
        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /* Recursive case, first check the sequence contains only one type */
    seq = PySequence_Fast(obj, "Could not convert object to sequence");
    if (seq == NULL) {
        goto fail;
    }
    size = PySequence_Fast_GET_SIZE(seq);
    objects = PySequence_Fast_ITEMS(seq);
    common_type = size > 0 ? Py_TYPE(objects[0]) : NULL;
    for (i = 1; i < size; ++i) {
        if (Py_TYPE(objects[i]) != common_type) {
            common_type = NULL;
            break;
        }
    }

    /* all types are the same and scalar, one recursive call is enough */
    if (common_type != NULL && !string_type &&
            (common_type == &PyFloat_Type ||
/* TODO: we could add longs if we add a range check */
#if !defined(NPY_PY3K)
             common_type == &PyInt_Type ||
#endif
             common_type == &PyBool_Type ||
             common_type == &PyComplex_Type)) {
        size = 1;
    }

    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        int res = PyArray_DTypeFromObjectHelper(objects[i], maxdims - 1,
                                                out_dtype, string_type);
        if (res < 0) {
            Py_DECREF(seq);
            goto fail;
        }
        else if (res > 0) {
            Py_DECREF(seq);
            return res;
        }
    }

    Py_DECREF(seq);

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        if (!string_type && dtype->type_num == NPY_STRING) {
            Py_DECREF(dtype);
            return RETRY_WITH_STRING;
        }
        if (!string_type && dtype->type_num == NPY_UNICODE) {
            Py_DECREF(dtype);
            return RETRY_WITH_UNICODE;
        }
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_UNICODE &&
                (*out_dtype)->type_num != NPY_UNICODE) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_UNICODE;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_STRING &&
                (*out_dtype)->type_num != NPY_STRING) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_STRING;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}

#undef RETRY_WITH_STRING
#undef RETRY_WITH_UNICODE

/* new reference */
NPY_NO_EXPORT PyArray_Descr *
_array_typedescr_fromstr(char *c_str)
{
    PyArray_Descr *descr = NULL;
    PyObject *stringobj = PyString_FromString(c_str);

    if (stringobj == NULL) {
        return NULL;
    }
    if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) {
        Py_DECREF(stringobj);
        return NULL;
    }
    Py_DECREF(stringobj);
    return descr;
}


NPY_NO_EXPORT char *
index2ptr(PyArrayObject *mp, npy_intp i)
{
    npy_intp dim0;

    if (PyArray_NDIM(mp) == 0) {
        PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed");
        return NULL;
    }
    dim0 = PyArray_DIMS(mp)[0];
    if (check_and_adjust_index(&i, dim0, 0, NULL) < 0)
        return NULL;
    if (i == 0) {
        return PyArray_DATA(mp);
    }
    return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0];
}
Esempio n. 24
0
File: type.c Progetto: zillow/ctds
static int SqlNVarChar_init(PyObject* self, PyObject* args, PyObject* kwargs)
{
    const char* utf8bytes = NULL;
    size_t nutf8bytes = 0;
    PyObject* encoded;
    enum TdsType tdstype;

    PyObject* unicode = NULL;
    size_t nchars = 0;
    Py_ssize_t size = (Py_ssize_t)-1;
    static char* s_kwlist[] =
    {
        "value",
        "size",
        NULL
    };
    /* Z# would be ideal here, but is not supported prior to Python 3. */
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|n", s_kwlist, &unicode, &size))
    {
        return -1;
    }

    if (Py_None == unicode)
    {
        /* `None` passed as argument. */
        encoded = PyTuple_GET_ITEM(args, 0);
        Py_INCREF(encoded);
        utf8bytes = NULL;
    }
    else if (PyUnicode_Check(unicode))
    {
        encoded = encode_for_dblib(unicode, &utf8bytes, &nutf8bytes, &nchars);
        if (!encoded)
        {
            return -1;
        }
    }
    else
    {
        PyErr_SetObject(PyExc_TypeError, unicode);
        return -1;
    }
    /*
        FreeTDS doesn't have good support for NCHAR types prior
        to 0.95. Fallback to VARCHAR with somewhat crippled
        functionality.
    */
#if defined(CTDS_USE_NCHARS)
    tdstype = (nchars > TDS_NCHAR_MAX_SIZE) ? TDSNTEXT : TDSNVARCHAR;
#else /* if defined(CTDS_USE_NCHARS) */
    tdstype = (nchars > TDS_CHAR_MAX_SIZE) ? TDSTEXT : TDSVARCHAR;
#endif /* else if defined(CTDS_USE_NCHARS) */

    SqlType_init_variable(self,
                          encoded,
                          tdstype,
                          /*
                              If the size is not explicitly specified, infer it from the value.
                              The NVARCHAR type size must be >= 1.
                          */
                          (int)MAX(1, (((Py_ssize_t)-1 == size) ? nchars : (size_t)size)),
                          (void*)utf8bytes,
                          nutf8bytes,
                          NULL);

    Py_DECREF(encoded);

    return 0;
}
Esempio n. 25
0
AerospikeQuery * AerospikeQuery_Select(AerospikeQuery * self, PyObject * args, PyObject * kwds)
{
	TRACE();

	int nbins = (int) PyTuple_Size(args);
	char * bin = NULL;
	PyObject * py_ubin = 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;
	}

	as_query_select_init(&self->query, nbins);

	for ( int i = 0; i < nbins; i++ ) {
		PyObject * py_bin = PyTuple_GetItem(args, i);
		if (PyUnicode_Check(py_bin)){
			py_ubin = PyUnicode_AsUTF8String(py_bin);
			bin = PyBytes_AsString(py_ubin);
		}
		else if (PyString_Check(py_bin)) {
			// TRACE();
			bin = PyString_AsString(py_bin);
		} else if (PyByteArray_Check(py_bin)) {
			bin = PyByteArray_AsString(py_bin);
		} else {
			// TRACE();
			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;
		}

		as_query_select(&self->query, bin);

		if (py_ubin){
			Py_DECREF(py_ubin);
			py_ubin = 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;
}
Esempio n. 26
0
static PyObject *
complex_subtype_from_string(PyTypeObject *type, PyObject *v)
{
	const char *s, *start;
	char *end;
	double x=0.0, y=0.0, z;
	int got_bracket=0;
	char s_buffer[256];
	Py_ssize_t len;

	if (PyUnicode_Check(v)) {
		if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
			PyErr_SetString(PyExc_ValueError,
				 "complex() literal too large to convert");
			return NULL;
		}
		if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
					    PyUnicode_GET_SIZE(v),
					    s_buffer,
					    NULL))
			return NULL;
		s = s_buffer;
		len = strlen(s);
	}
	else if (PyObject_AsCharBuffer(v, &s, &len)) {
		PyErr_SetString(PyExc_TypeError,
				"complex() arg is not a string");
		return NULL;
	}

	/* position on first nonblank */
	start = s;
	while (Py_ISSPACE(*s))
		s++;
	if (*s == '(') {
		/* Skip over possible bracket from repr(). */
		got_bracket = 1;
		s++;
		while (Py_ISSPACE(*s))
			s++;
	}

	/* a valid complex string usually takes one of the three forms:

	     <float>                  - real part only
	     <float>j                 - imaginary part only
	     <float><signed-float>j   - real and imaginary parts

	   where <float> represents any numeric string that's accepted by the
	   float constructor (including 'nan', 'inf', 'infinity', etc.), and
	   <signed-float> is any string of the form <float> whose first
	   character is '+' or '-'.

	   For backwards compatibility, the extra forms

	     <float><sign>j
	     <sign>j
	     j

	   are also accepted, though support for these forms may be removed from
	   a future version of Python.
	*/

	/* first look for forms starting with <float> */
	z = PyOS_string_to_double(s, &end, NULL);
	if (z == -1.0 && PyErr_Occurred()) {
		if (PyErr_ExceptionMatches(PyExc_ValueError))
			PyErr_Clear();
		else
			return NULL;
	}
	if (end != s) {
		/* all 4 forms starting with <float> land here */
		s = end;
		if (*s == '+' || *s == '-') {
			/* <float><signed-float>j | <float><sign>j */
			x = z;
			y = PyOS_string_to_double(s, &end, NULL);
			if (y == -1.0 && PyErr_Occurred()) {
				if (PyErr_ExceptionMatches(PyExc_ValueError))
					PyErr_Clear();
				else
					return NULL;
			}
			if (end != s)
				/* <float><signed-float>j */
				s = end;
			else {
				/* <float><sign>j */
				y = *s == '+' ? 1.0 : -1.0;
				s++;
			}
			if (!(*s == 'j' || *s == 'J'))
				goto parse_error;
			s++;
		}
		else if (*s == 'j' || *s == 'J') {
			/* <float>j */
			s++;
			y = z;
		}
		else
			/* <float> */
			x = z;
	}
	else {
		/* not starting with <float>; must be <sign>j or j */
		if (*s == '+' || *s == '-') {
			/* <sign>j */
			y = *s == '+' ? 1.0 : -1.0;
			s++;
		}
		else
			/* j */
			y = 1.0;
		if (!(*s == 'j' || *s == 'J'))
			goto parse_error;
		s++;
	}

	/* trailing whitespace and closing bracket */
	while (Py_ISSPACE(*s))
		s++;
	if (got_bracket) {
		/* if there was an opening parenthesis, then the corresponding
		   closing parenthesis should be right here */
		if (*s != ')')
			goto parse_error;
		s++;
		while (Py_ISSPACE(*s))
			s++;
	}

	/* we should now be at the end of the string */
	if (s-start != len)
		goto parse_error;

	return complex_subtype_from_doubles(type, x, y);

  parse_error:
	PyErr_SetString(PyExc_ValueError,
			"complex() arg is a malformed string");
	return NULL;
}
Esempio n. 27
0
static PyObject *_read_png(PyObject *filein, bool float_result)
{
    png_byte header[8]; // 8 is the maximum size that can be checked
    FILE *fp = NULL;
    mpl_off_t offset = 0;
    bool close_file = false;
    bool close_dup_file = false;
    PyObject *py_file = NULL;
    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;
    int num_dims;
    std::vector<png_bytep> row_pointers;
    png_uint_32 width = 0;
    png_uint_32 height = 0;
    int bit_depth;
    PyObject *result = NULL;

    // TODO: Remove direct calls to Numpy API here

    if (PyBytes_Check(filein) || PyUnicode_Check(filein)) {
        if ((py_file = mpl_PyFile_OpenFile(filein, (char *)"rb")) == NULL) {
            goto exit;
        }
        close_file = true;
    } else {
        py_file = filein;
    }

    if ((fp = mpl_PyFile_Dup(py_file, (char *)"rb", &offset))) {
        close_dup_file = true;
    } else {
        PyErr_Clear();
        PyObject *read_method = PyObject_GetAttrString(py_file, "read");
        if (!(read_method && PyCallable_Check(read_method))) {
            Py_XDECREF(read_method);
            PyErr_SetString(PyExc_TypeError,
                            "Object does not appear to be a 8-bit string path or "
                            "a Python file-like object");
            goto exit;
        }
        Py_XDECREF(read_method);
    }

    if (fp) {
        if (fread(header, 1, 8, fp) != 8) {
            PyErr_SetString(PyExc_IOError, "error reading PNG header");
            goto exit;
        }
    } else {
        _read_png_data(py_file, header, 8);
    }

    if (png_sig_cmp(header, 0, 8)) {
        PyErr_SetString(PyExc_ValueError, "invalid PNG header");
        goto exit;
    }

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

    if (!png_ptr) {
        PyErr_SetString(PyExc_RuntimeError, "png_create_read_struct failed");
        goto exit;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        PyErr_SetString(PyExc_RuntimeError, "png_create_info_struct failed");
        goto exit;
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
        PyErr_SetString(PyExc_RuntimeError, "Error setting jump");
        goto exit;
    }

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

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

    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);
        bit_depth = 8;
    }

    // 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);

    row_pointers.resize(height);
    for (png_uint_32 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[0]);

    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
    }

    if (float_result) {
        double max_value = (1 << bit_depth) - 1;

        numpy::array_view<float, 3> A(dimensions);

        for (png_uint_32 y = 0; y < height; y++) {
            png_byte *row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++) {
                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++) {
                        A(y, x, p) = (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++) {
                        A(y, x, p) = (float)(ptr[p]) / max_value;
                    }
                }
            }
        }

        result = A.pyobj();
    } else if (bit_depth == 16) {
        numpy::array_view<png_uint_16, 3> A(dimensions);

        for (png_uint_32 y = 0; y < height; y++) {
            png_byte *row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++) {
                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++) {
                    A(y, x, p) = ptr[p];
                }
            }
        }

        result = A.pyobj();
    } else if (bit_depth == 8) {
        numpy::array_view<png_byte, 3> A(dimensions);

        for (png_uint_32 y = 0; y < height; y++) {
            png_byte *row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++) {
                png_byte *ptr = &(row[x * dimensions[2]]);
                for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++) {
                    A(y, x, p) = ptr[p];
                }
            }
        }

        result = A.pyobj();
    } else {
        PyErr_SetString(PyExc_RuntimeError, "image has unknown bit depth");
        goto exit;
    }

    // free the png memory
    png_read_end(png_ptr, info_ptr);

    // For gray, return an x by y array, not an x by y by 1
    num_dims = (png_get_color_type(png_ptr, info_ptr) & PNG_COLOR_MASK_COLOR) ? 3 : 2;

    if (num_dims == 2) {
        PyArray_Dims dims = {dimensions, 2};
        PyObject *reshaped = PyArray_Newshape((PyArrayObject *)result, &dims, NPY_CORDER);
        Py_DECREF(result);
        result = reshaped;
    }

exit:
    if (png_ptr && info_ptr) {
#ifndef png_infopp_NULL
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
#else
        png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
#endif
    }

    if (close_dup_file) {
        mpl_PyFile_DupClose(py_file, fp, offset);
    }

    if (close_file) {
        mpl_PyFile_CloseFile(py_file);
        Py_DECREF(py_file);
    }

    for (png_uint_32 row = 0; row < height; row++) {
        delete[] row_pointers[row];
    }

    if (PyErr_Occurred()) {
        Py_XDECREF(result);
        return NULL;
    } else {
        return result;
    }
}
Esempio n. 28
0
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *r, *i, *tmp, *f;
	PyNumberMethods *nbr, *nbi = NULL;
	Py_complex cr, ci;
	int own_r = 0;
	int cr_is_complex = 0;
	int ci_is_complex = 0;
	static PyObject *complexstr;
	static char *kwlist[] = {"real", "imag", 0};

	r = Py_False;
	i = NULL;
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
					 &r, &i))
		return NULL;

	/* Special-case for a single argument when type(arg) is complex. */
	if (PyComplex_CheckExact(r) && i == NULL &&
	    type == &PyComplex_Type) {
		/* Note that we can't know whether it's safe to return
		   a complex *subclass* instance as-is, hence the restriction
		   to exact complexes here.  If either the input or the
		   output is a complex subclass, it will be handled below 
		   as a non-orthogonal vector.  */
		Py_INCREF(r);
		return r;
	}
	if (PyUnicode_Check(r)) {
		if (i != NULL) {
			PyErr_SetString(PyExc_TypeError,
					"complex() can't take second arg"
					" if first is a string");
			return NULL;
		}
		return complex_subtype_from_string(type, r);
	}
	if (i != NULL && PyUnicode_Check(i)) {
		PyErr_SetString(PyExc_TypeError,
				"complex() second arg can't be a string");
		return NULL;
	}

	/* XXX Hack to support classes with __complex__ method */
	if (complexstr == NULL) {
		complexstr = PyUnicode_InternFromString("__complex__");
		if (complexstr == NULL)
			return NULL;
	}
	f = PyObject_GetAttr(r, complexstr);
	if (f == NULL)
		PyErr_Clear();
	else {
		PyObject *args = PyTuple_New(0);
		if (args == NULL)
			return NULL;
		r = PyEval_CallObject(f, args);
		Py_DECREF(args);
		Py_DECREF(f);
		if (r == NULL)
			return NULL;
		own_r = 1;
	}
	nbr = r->ob_type->tp_as_number;
	if (i != NULL)
		nbi = i->ob_type->tp_as_number;
	if (nbr == NULL || nbr->nb_float == NULL ||
	    ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
		PyErr_SetString(PyExc_TypeError,
			   "complex() argument must be a string or a number");
		if (own_r) {
			Py_DECREF(r);
		}
		return NULL;
	}

	/* If we get this far, then the "real" and "imag" parts should
	   both be treated as numbers, and the constructor should return a
	   complex number equal to (real + imag*1j).

 	   Note that we do NOT assume the input to already be in canonical
	   form; the "real" and "imag" parts might themselves be complex
	   numbers, which slightly complicates the code below. */
	if (PyComplex_Check(r)) {
		/* Note that if r is of a complex subtype, we're only
		   retaining its real & imag parts here, and the return
		   value is (properly) of the builtin complex type. */
		cr = ((PyComplexObject*)r)->cval;
		cr_is_complex = 1;
		if (own_r) {
			Py_DECREF(r);
		}
	}
	else {
		/* The "real" part really is entirely real, and contributes
		   nothing in the imaginary direction.  
		   Just treat it as a double. */
		tmp = PyNumber_Float(r);
		if (own_r) {
			/* r was a newly created complex number, rather
			   than the original "real" argument. */
			Py_DECREF(r);
		}
		if (tmp == NULL)
			return NULL;
		if (!PyFloat_Check(tmp)) {
			PyErr_SetString(PyExc_TypeError,
					"float(r) didn't return a float");
			Py_DECREF(tmp);
			return NULL;
		}
		cr.real = PyFloat_AsDouble(tmp);
		cr.imag = 0.0; /* Shut up compiler warning */
		Py_DECREF(tmp);
	}
	if (i == NULL) {
		ci.real = 0.0;
	}
	else if (PyComplex_Check(i)) {
		ci = ((PyComplexObject*)i)->cval;
		ci_is_complex = 1;
	} else {
		/* The "imag" part really is entirely imaginary, and
		   contributes nothing in the real direction.
		   Just treat it as a double. */
		tmp = (*nbi->nb_float)(i);
		if (tmp == NULL)
			return NULL;
		ci.real = PyFloat_AsDouble(tmp);
		Py_DECREF(tmp);
	}
	/*  If the input was in canonical form, then the "real" and "imag"
	    parts are real numbers, so that ci.imag and cr.imag are zero.
	    We need this correction in case they were not real numbers. */

	if (ci_is_complex) {
		cr.real -= ci.imag;
	}
	if (cr_is_complex) {
		ci.real += cr.imag;
	}
	return complex_subtype_from_doubles(type, cr.real, ci.real);
}
Esempio n. 29
0
static int
_view_kind(PyObject *obj, void *view_kind_vptr)
{
    unsigned long ch;
    _pc_view_kind_t *view_kind_ptr = (_pc_view_kind_t *)view_kind_vptr;

    if (PyUnicode_Check(obj)) {
        if (PyUnicode_GET_SIZE(obj) != 1) {
            PyErr_SetString(PyExc_TypeError,
                            "expected a length 1 string for argument 3");
            return 0;
        }
        ch = *PyUnicode_AS_UNICODE(obj);
    }
    else if (Bytes_Check(obj)) {
        if (Bytes_GET_SIZE(obj) != 1) {
            PyErr_SetString(PyExc_TypeError,
                            "expected a length 1 string for argument 3");
            return 0;
        }
        ch = *Bytes_AS_STRING(obj);
    }
    else {
        PyErr_Format(PyExc_TypeError,
                     "expected a length one string for argument 3: got '%s'",
                     Py_TYPE(obj)->tp_name);
        return 0;
    }
    switch (ch) {

    case 'R':
    case 'r':
        *view_kind_ptr = VIEWKIND_RED;
        break;
    case 'G':
    case 'g':
        *view_kind_ptr = VIEWKIND_GREEN;
        break;
    case 'B':
    case 'b':
        *view_kind_ptr = VIEWKIND_BLUE;
        break;
    case 'A':
    case 'a':
        *view_kind_ptr = VIEWKIND_ALPHA;
        break;
    case 'C':
    case 'c':
        *view_kind_ptr = VIEWKIND_COLORKEY;
        break;
    case 'P':
    case 'p':
        *view_kind_ptr = VIEWKIND_RGB;
        break;
    default:
        PyErr_Format(PyExc_TypeError,
                     "unrecognized view kind '%c' for argument 3", (int)ch);
        return 0;
    }
    return 1;
}
Esempio n. 30
0
static PyObject *
namespace_repr(_PyNamespaceObject *ns)
{
    int i, loop_error = 0;
    PyObject *pairs = NULL, *d = NULL, *keys = NULL, *keys_iter = NULL;
    PyObject *key;
    PyObject *separator, *pairsrepr, *repr = NULL;

    i = Py_ReprEnter((PyObject *)ns);
    if (i != 0) {
        return i > 0 ? PyUnicode_FromString("namespace(...)") : NULL;
    }

    pairs = PyList_New(0);
    if (pairs == NULL)
        goto error;

    d = ((_PyNamespaceObject *)ns)->ns_dict;
    assert(d != NULL);
    Py_INCREF(d);

    keys = PyDict_Keys(d);
    if (keys == NULL)
        goto error;
    if (PyList_Sort(keys) != 0)
        goto error;

    keys_iter = PyObject_GetIter(keys);
    if (keys_iter == NULL)
        goto error;

    while ((key = PyIter_Next(keys_iter)) != NULL) {
        if (PyUnicode_Check(key) && PyUnicode_GET_SIZE(key) > 0) {
            PyObject *value, *item;

            value = PyDict_GetItem(d, key);
            assert(value != NULL);

            item = PyUnicode_FromFormat("%S=%R", key, value);
            if (item == NULL) {
                loop_error = 1;
            }
            else {
                loop_error = PyList_Append(pairs, item);
                Py_DECREF(item);
            }
        }

        Py_DECREF(key);
        if (loop_error)
            goto error;
    }

    separator = PyUnicode_FromString(", ");
    if (separator == NULL)
        goto error;

    pairsrepr = PyUnicode_Join(separator, pairs);
    Py_DECREF(separator);
    if (pairsrepr == NULL)
        goto error;

    repr = PyUnicode_FromFormat("%s(%S)",
                                ((PyObject *)ns)->ob_type->tp_name, pairsrepr);
    Py_DECREF(pairsrepr);

error:
    Py_XDECREF(pairs);
    Py_XDECREF(d);
    Py_XDECREF(keys);
    Py_XDECREF(keys_iter);
    Py_ReprLeave((PyObject *)ns);

    return repr;
}