예제 #1
0
static gboolean
_pygi_closure_convert_arguments (PyGIInvokeState *state,
                                 PyGIClosureCache *closure_cache)
{
    PyGICallableCache *cache = (PyGICallableCache *) closure_cache;
    gssize n_in_args = 0;
    gssize i;

    for (i = 0; i < _pygi_callable_cache_args_len (cache); i++) {
        PyGIArgCache *arg_cache;

        arg_cache = g_ptr_array_index (cache->args_cache, i);

        if (arg_cache->direction & PYGI_DIRECTION_TO_PYTHON) {
            PyObject *value;

            if (cache->user_data_index == i) {
                if (state->user_data == NULL) {
                    /* user_data can be NULL for connect functions which don't accept
                     * user_data or as the default for user_data in the middle of function
                     * arguments.
                     */
                    Py_INCREF (Py_None);
                    value = Py_None;
                } else {
                    /* Extend the callbacks args with user_data as variable args. */
                    gssize j, user_data_len;
                    PyObject *py_user_data = state->user_data;

                    if (!PyTuple_Check (py_user_data)) {
                        PyErr_SetString (PyExc_TypeError, "expected tuple for callback user_data");
                        return FALSE;
                    }

                    user_data_len = PyTuple_Size (py_user_data);
                    _PyTuple_Resize (&state->py_in_args,
                                     state->n_py_in_args + user_data_len - 1);

                    for (j = 0; j < user_data_len; j++, n_in_args++) {
                        value = PyTuple_GetItem (py_user_data, j);
                        Py_INCREF (value);
                        PyTuple_SET_ITEM (state->py_in_args, n_in_args, value);
                    }
                    /* We can assume user_data args are never going to be inout,
                     * so just continue here.
                     */
                    continue;
                }
            } else if (arg_cache->meta_type != PYGI_META_ARG_TYPE_PARENT) {
                continue;
            } else {
                value = arg_cache->to_py_marshaller (state,
                                                     cache,
                                                     arg_cache,
                                                     &state->args[i].arg_value);

                if (value == NULL) {
                    pygi_marshal_cleanup_args_to_py_parameter_fail (state,
                                                                    cache,
                                                                    i);
                    return FALSE;
                }
            }

            PyTuple_SET_ITEM (state->py_in_args, n_in_args, value);
            n_in_args++;
        }
    }

    if (_PyTuple_Resize (&state->py_in_args, n_in_args) == -1)
        return FALSE;

    return TRUE;
}
예제 #2
0
파일: row.c 프로젝트: corona10/pyston
PyObject* pysqlite_row_item(pysqlite_Row* self, Py_ssize_t idx)
{
   PyObject* item = PyTuple_GetItem(self->data, idx);
   Py_XINCREF(item);
   return item;
}
예제 #3
0
파일: gevent.c 프로젝트: sashka/uwsgi
PyObject *py_uwsgi_gevent_request(PyObject * self, PyObject * args) {

	PyObject *ret;
	PyObject *py_wsgi_req = PyTuple_GetItem(args, 0);
	struct wsgi_request *wsgi_req = (struct wsgi_request *) PyLong_AsLong(py_wsgi_req);
	int status ;

	PyObject *current_greenlet = GET_CURRENT_GREENLET;
	PyObject *greenlet_switch = PyObject_GetAttrString(current_greenlet, "switch");

	uwsgi.wsgi_req = wsgi_req;

	// create a watcher for request socket
	PyObject *watcher = PyObject_CallMethod(ugevent.hub_loop, "io", "ii", wsgi_req->poll.fd, 1);
	if (!watcher) goto clear1;

	// a timer to implement timeoit (thanks Denis)
	PyObject *timer = PyObject_CallMethod(ugevent.hub_loop, "timer", "i", uwsgi.shared->options[UWSGI_OPTION_SOCKET_TIMEOUT]);
	if (!timer) goto clear0;

	for(;;) {
		// wait for data in the socket
		PyObject *ret = uwsgi_gevent_wait(watcher, timer, greenlet_switch);
		if (!ret) goto clear_and_stop;

		// do not forget to overwrite this pointer each time !!!
		uwsgi.wsgi_req = wsgi_req;

		// we can safely decref here as watcher and timer has got a +1 for start() method
		Py_DECREF(ret);
		if (ret == timer) {
			uwsgi_log( "timeout. skip request.\n");
			goto clear_and_stop;
		}
		else if (ret == watcher) {

			status = wsgi_req->socket->proto(wsgi_req);
			if (status < 0) {
				goto clear_and_stop;
			}
			else if (status == 0) {
				stop_the_watchers;
				break;
			}
		}
		else {
			uwsgi_log("unrecognized gevent event !!!\n");
			goto clear_and_stop;
		}

		stop_the_watchers;
	}

	for(;;) {
		uwsgi.wsgi_req = wsgi_req;
		wsgi_req->async_status = uwsgi.p[wsgi_req->uh.modifier1]->request(wsgi_req);
		if (wsgi_req->async_status <= UWSGI_OK) {
			goto clear;
		}
		// switch after each yield
		GEVENT_SWITCH;
	}

	goto clear;

clear_and_stop:

	stop_the_watchers;

clear:
	Py_DECREF(timer);
clear0:
	Py_DECREF(watcher);
clear1:
	Py_DECREF(greenlet_switch);
	Py_DECREF(current_greenlet);
	uwsgi_close_request(wsgi_req);

	uwsgi.wsgi_req = wsgi_req;

	free_req_queue;

	Py_INCREF(Py_None);
	return Py_None;


}
예제 #4
0
static int image_init(PyImage *self,
                      PyObject *args,
                      PyObject *kwargs)
{
    PyObject *initial;
    int location = OSL_IN_VRAM;
    int pf = OSL_PF_8888;

    if (!PyArg_ParseTuple(args, "O|ii:__init__", &initial, &location, &pf))
       return -1;

    self->location = location;

    if (PyString_Check(initial))
    {
       // Load from file

       char *filename = PyString_AsString(initial);

       self->pImg = oslLoadImageFile(filename, location, pf);

       if (!self->pImg)
       {
          PyErr_SetString(osl_Error, "Could not load image.");
          return -1;
       }
    }
    else if (PyTuple_Check(initial))
    {
       int w, h;

       if (PyTuple_Size(initial) != 2)
       {
          PyErr_SetString(PyExc_TypeError, "Image dimension must be a 2-tuple");
          return -1;
       }

       if (!PyInt_Check(PyTuple_GetItem(initial, 0)))
       {
          PyErr_SetString(PyExc_TypeError, "Image width must be an integer");
          return -1;
       }

       if (!PyInt_Check(PyTuple_GetItem(initial, 1)))
       {
          PyErr_SetString(PyExc_TypeError, "Image height must be an integer");
          return -1;
       }

       w = PyInt_AsLong(PyTuple_GetItem(initial, 0));
       h = PyInt_AsLong(PyTuple_GetItem(initial, 1));

       self->pImg = oslCreateImage(w, h, location, pf);

       if (!self->pImg)
       {
          PyErr_SetString(osl_Error, "Could not create image");
          return -1;
       }
    }
    else
    {
       PyErr_SetString(PyExc_TypeError, "First argument must be a filename or a 2-tuple");
       return -1;
    }

    if (location == OSL_IN_VRAM)
    {
       FREEIMG *pFree = (FREEIMG*)malloc(sizeof(FREEIMG));

       pFree->bDelete = 0;
       pFree->pImg = self->pImg;
       pFree->next = (void*)pCurrent;
       pCurrent = pFree;
    }

    return 0;
}
예제 #5
0
int uwsgi_response_subhandler_web3(struct wsgi_request *wsgi_req) {

	PyObject *pychunk;

	// ok its a yield
	if (!wsgi_req->async_placeholder) {
		if (PyTuple_Check((PyObject *)wsgi_req->async_result)) {
			if (PyTuple_Size((PyObject *)wsgi_req->async_result) != 3) { 
				uwsgi_log("invalid Web3 response.\n"); 
				goto clear; 
			} 



			wsgi_req->async_placeholder = PyTuple_GetItem((PyObject *)wsgi_req->async_result, 0); 
			Py_INCREF((PyObject *)wsgi_req->async_placeholder);

			PyObject *spit_args = PyTuple_New(2);

			PyObject *status = PyTuple_GetItem((PyObject *)wsgi_req->async_result, 1);
			Py_INCREF(status);
			PyTuple_SetItem(spit_args, 0, status);

			PyObject *headers = PyTuple_GetItem((PyObject *)wsgi_req->async_result, 2);
			Py_INCREF(headers);
			PyTuple_SetItem(spit_args, 1, headers);

			if (py_uwsgi_spit(Py_None, spit_args) == NULL) { 
				PyErr_Print();
				Py_DECREF(spit_args);
				goto clear; 
			} 

			// send the headers if not already sent
        		if (!wsgi_req->headers_sent && wsgi_req->headers_hvec > 0) {
                		uwsgi_python_do_send_headers(wsgi_req);
        		}

			Py_DECREF(spit_args);

			if (PyString_Check((PyObject *)wsgi_req->async_placeholder)) {
				char *content = PyString_AsString(wsgi_req->async_placeholder);
				size_t content_len = PyString_Size(wsgi_req->async_placeholder);
				UWSGI_RELEASE_GIL
                		wsgi_req->response_size += wsgi_req->socket->proto_write(wsgi_req, content, content_len);
				UWSGI_GET_GIL
				uwsgi_py_check_write_errors {
                        		uwsgi_py_write_exception(wsgi_req);
                		}
                		goto clear;
        		}

			PyObject *tmp = (PyObject *)wsgi_req->async_placeholder;

			wsgi_req->async_placeholder = PyObject_GetIter( (PyObject *)wsgi_req->async_placeholder );

			Py_DECREF(tmp);

			if (!wsgi_req->async_placeholder) {
				goto clear;
			}
#ifdef UWSGI_ASYNC
			if (uwsgi.async > 1) {
				return UWSGI_AGAIN;
			}
#endif
		}
		else {
예제 #6
0
// Register signal change callback
// First argument should be the signal handle
// Second argument is the function to call
// Remaining arguments and keyword arguments are to be passed to the callback
static PyObject *register_value_change_callback(PyObject *self, PyObject *args) //, PyObject *keywds)
{
    FENTER

    PyObject *fArgs;
    PyObject *function;
    gpi_sim_hdl sig_hdl;
    gpi_sim_hdl hdl;
    unsigned int edge;

    p_callback_data callback_data_p;

    Py_ssize_t numargs = PyTuple_Size(args);

    if (numargs < 3) {
        fprintf(stderr, "Attempt to register value change callback without enough arguments!\n");
        return NULL;
    }

    PyObject *pSihHdl = PyTuple_GetItem(args, 0);
    if (!gpi_sim_hdl_converter(pSihHdl, &sig_hdl)) {
        return NULL;
    }

    // Extract the callback function
    function = PyTuple_GetItem(args, 1);
    if (!PyCallable_Check(function)) {
        fprintf(stderr, "Attempt to register value change callback without passing a callable callback!\n");
        return NULL;
    }
    Py_INCREF(function);

    PyObject *pedge = PyTuple_GetItem(args, 2);
    edge = (unsigned int)PyLong_AsLong(pedge);

    // Remaining args for function
    fArgs = PyTuple_GetSlice(args, 3, numargs);   // New reference
    if (fArgs == NULL) {
        return NULL;
    }


    callback_data_p = (p_callback_data)malloc(sizeof(s_callback_data));
    if (callback_data_p == NULL) {
        return PyErr_NoMemory();
    }

    // Set up the user data (no more python API calls after this!)
    // Causes segfault?
    callback_data_p->_saved_thread_state = PyThreadState_Get();//PyThreadState_Get();
    callback_data_p->id_value = COCOTB_ACTIVE_ID;
    callback_data_p->function = function;
    callback_data_p->args = fArgs;
    callback_data_p->kwargs = NULL;

    hdl = gpi_register_value_change_callback((gpi_function_t)handle_gpi_callback,
                                             callback_data_p,
                                             sig_hdl,
                                             edge);

    // Check success
    PyObject *rv = PyLong_FromVoidPtr(hdl);
    FEXIT

    return rv;
}
예제 #7
0
파일: send.c 프로젝트: kotan-kn/pdvms
void pyobj_send(t_outlet*const outlet,PyObject*const value)
{
	if(!value);
	else if(value==Py_True)
		outlet_bang(outlet);
	else if(value==Py_False)
		outlet_symbol(outlet,&s_);
	else if(PyInt_Check(value))
		outlet_float(outlet,PyInt_AsLong(value));
	else if(PyFloat_Check(value))
		outlet_float(outlet,PyFloat_AsDouble(value));
	else if(PyString_Check(value))
		outlet_symbol(outlet,gensym(PyString_AsString(value)));
	else if(PyDict_Check(value))
	{
	}
	else if(PyList_Check(value))
	{
		register int k,K;
		Py_ssize_t size=PyList_Size(value);
		t_atom*atom=(t_atom*)calloc(sizeof(t_atom),size);
		for(k=0,K=size;k<K;++k)
		{
			PyObject*obj=PyList_GetItem(value,k);
			if(!obj)
				SETSYMBOL(atom+k,&s_);
			else if(obj==Py_True)
				SETFLOAT(atom+k,1);
			else if(obj==Py_False)
				SETSYMBOL(atom+k,&s_);
			else if(PyInt_Check(obj))
				SETFLOAT(atom+k,PyInt_AsLong(obj));
			else if(PyFloat_Check(obj))
				SETFLOAT(atom+k,PyFloat_AsDouble(obj));
			else
				SETSYMBOL(atom+k,&s_);
		}
		outlet_list(outlet,gensym("list"),size,atom);
	}
	else if(PyTuple_Check(value))
	{
		register int k,K;
		Py_ssize_t size=PyTuple_Size(value);
		t_atom*atom=(t_atom*)calloc(sizeof(t_atom),size);
		for(k=0,K=size;k<K;++k)
		{
			PyObject*obj=PyTuple_GetItem(value,k);
			if(!obj)
				SETSYMBOL(atom+k,&s_);
			else if(obj==Py_True)
				SETFLOAT(atom+k,1);
			else if(obj==Py_False)
				SETSYMBOL(atom+k,&s_);
			else if(PyInt_Check(obj))
				SETFLOAT(atom+k,PyInt_AsLong(obj));
			else if(PyFloat_Check(obj))
				SETFLOAT(atom+k,PyFloat_AsDouble(obj));
			else
				SETSYMBOL(atom+k,&s_);
		}
		outlet_list(outlet,gensym("list"),size,atom);
	}
}
예제 #8
0
/**
 ******************************************************************************************************
 * Returns data for a particular request string to AerospikeClient_InfoNode
 *
 * @param self                  AerospikeClient object
 * @param request_str_p         Request string sent from the python client
 * @param py_host               Optional host sent from the python client
 * @param py_policy             The policy sent from the python client
 *
 * Returns information about a host.
 ********************************************************************************************************/
static PyObject * AerospikeClient_InfoNode_Invoke(
	AerospikeClient * self,
	PyObject * py_request_str, PyObject * py_host, PyObject * py_policy) {

	PyObject * py_response = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_ustr1 = NULL;
	as_policy_info info_policy;
	as_policy_info* info_policy_p = NULL;
	char* address = (char *) self->as->config.hosts[0].addr;
	long port_no = self->as->config.hosts[0].port;
	char* response_p = NULL;
	as_status status = AEROSPIKE_OK;

	as_error err;
	as_error_init(&err);

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

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

	if (py_policy) {
		if( PyDict_Check(py_policy) ) {
			pyobject_to_policy_info(&err, py_policy, &info_policy, &info_policy_p,
					&self->as->config.policies.info);
			if (err.code != AEROSPIKE_OK) {
				goto CLEANUP;
			}
		} else {
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Policy should be a dictionary");
			goto CLEANUP;
		}
	}

	if ( py_host ) {
		if ( PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2) {
			PyObject * py_addr = PyTuple_GetItem(py_host,0);
			PyObject * py_port = PyTuple_GetItem(py_host,1);

			if ( PyString_Check(py_addr) ) {
				address = PyString_AsString(py_addr);
			} else if (PyUnicode_Check(py_addr)) {
				py_ustr = PyUnicode_AsUTF8String(py_addr);
				address = PyString_AsString(py_ustr);
			}
			if ( PyInt_Check(py_port) ) {
				port_no = (uint16_t) PyInt_AsLong(py_port);
			}
			else if ( PyLong_Check(py_port) ) {
				port_no = (uint16_t) PyLong_AsLong(py_port);
			}
		} else if ( !PyTuple_Check(py_host)){
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Host should be a specified in form of Tuple.");
			goto CLEANUP;
		}
	}

	char * request_str_p = NULL;
	if (PyUnicode_Check(py_request_str)) {
		py_ustr1 = PyUnicode_AsUTF8String(py_request_str);
		request_str_p = PyString_AsString(py_ustr1);
	} else if (PyString_Check(py_request_str)) {
		request_str_p = PyString_AsString(py_request_str);
	} else {
		as_error_update(&err, AEROSPIKE_ERR_PARAM, "Request should be of string type");
		goto CLEANUP;
	}

	status = aerospike_info_host(self->as, &err, info_policy_p,
		(const char *) address, (uint16_t) port_no, request_str_p,
		&response_p);
	if( err.code == AEROSPIKE_OK ) {
		if (response_p && status == AEROSPIKE_OK){
			py_response = PyString_FromString(response_p);
			free(response_p);
		} else if ( response_p == NULL){
			as_error_update(&err, AEROSPIKE_ERR_CLIENT, "Invalid info operation");
			goto CLEANUP;
		} else if ( status != AEROSPIKE_OK ){
			as_error_update(&err, status, "Info operation failed");
			goto CLEANUP;
		}
	} else {
		as_error_update(&err, err.code, NULL);
		goto CLEANUP;
	}

CLEANUP:

	if (py_ustr) {
		Py_DECREF(py_ustr);
	}
	if (py_ustr1) {
		Py_DECREF(py_ustr1);
	}

	if ( err.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(&err, &py_err);
		PyObject *exception_type = raise_exception(&err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return py_response;
}
예제 #9
0
static char *
Merge(PyObject *args)
{
	PyObject *tmp = NULL;
	char *argvStore[ARGSZ];
	char **argv = NULL;
	int fvStore[ARGSZ];
	int *fv = NULL;
	int argc = 0, fvc = 0, i;
	char *res = NULL;

	if (!(tmp = PyList_New(0)))
	    return NULL;

	argv = argvStore;
	fv = fvStore;

	if (args == NULL)
		argc = 0;

	else if (!PyTuple_Check(args)) {
		argc = 1;
		fv[0] = 0;
		if (!(argv[0] = AsString(args, tmp)))
			goto finally;
	}
	else {
		argc = PyTuple_Size(args);

		if (argc > ARGSZ) {
			argv = (char **)ckalloc(argc * sizeof(char *));
			fv = (int *)ckalloc(argc * sizeof(int));
			if (argv == NULL || fv == NULL) {
				PyErr_NoMemory();
				goto finally;
			}
		}

		for (i = 0; i < argc; i++) {
			PyObject *v = PyTuple_GetItem(args, i);
			if (PyTuple_Check(v)) {
				fv[i] = 1;
				if (!(argv[i] = Merge(v)))
					goto finally;
				fvc++;
			}
			else if (v == Py_None) {
				argc = i;
				break;
			}
			else {
				fv[i] = 0;
				if (!(argv[i] = AsString(v, tmp)))
					goto finally;
				fvc++;
			}
		}
	}
	res = Tcl_Merge(argc, argv);
	if (res == NULL)
		PyErr_SetString(Tkinter_TclError, "merge failed");

  finally:
	for (i = 0; i < fvc; i++)
		if (fv[i]) {
			ckfree(argv[i]);
		}
	if (argv != argvStore)
		ckfree(FREECAST argv);
	if (fv != fvStore)
		ckfree(FREECAST fv);

	Py_DECREF(tmp);
	return res;
}
예제 #10
0
파일: buffer.c 프로젝트: 87/numpy
static int
_buffer_format_string(PyArray_Descr *descr, _tmp_string_t *str,
                      PyArrayObject* arr, Py_ssize_t *offset,
                      char *active_byteorder)
{
    int k;
    char _active_byteorder = '@';
    Py_ssize_t _offset = 0;

    if (active_byteorder == NULL) {
        active_byteorder = &_active_byteorder;
    }
    if (offset == NULL) {
        offset = &_offset;
    }

    if (descr->subarray) {
        PyObject *item, *subarray_tuple;
        Py_ssize_t total_count = 1;
        Py_ssize_t dim_size;
        char buf[128];
        int old_offset;
        int ret;

        if (PyTuple_Check(descr->subarray->shape)) {
            subarray_tuple = descr->subarray->shape;
            Py_INCREF(subarray_tuple);
        }
        else {
            subarray_tuple = Py_BuildValue("(O)", descr->subarray->shape);
        }

        _append_char(str, '(');
        for (k = 0; k < PyTuple_GET_SIZE(subarray_tuple); ++k) {
            if (k > 0) {
                _append_char(str, ',');
            }
            item = PyTuple_GET_ITEM(subarray_tuple, k);
            dim_size = PyNumber_AsSsize_t(item, NULL);

            PyOS_snprintf(buf, sizeof(buf), "%ld", (long)dim_size);
            _append_str(str, buf);
            total_count *= dim_size;
        }
        _append_char(str, ')');

        Py_DECREF(subarray_tuple);

        old_offset = *offset;
        ret = _buffer_format_string(descr->subarray->base, str, arr, offset,
                                    active_byteorder);
        *offset = old_offset + (*offset - old_offset) * total_count;
        return ret;
    }
    else if (PyDataType_HASFIELDS(descr)) {
        int base_offset = *offset;

        _append_str(str, "T{");
        for (k = 0; k < PyTuple_GET_SIZE(descr->names); ++k) {
            PyObject *name, *item, *offset_obj, *tmp;
            PyArray_Descr *child;
            char *p;
            Py_ssize_t len;
            int new_offset;

            name = PyTuple_GET_ITEM(descr->names, k);
            item = PyDict_GetItem(descr->fields, name);

            child = (PyArray_Descr*)PyTuple_GetItem(item, 0);
            offset_obj = PyTuple_GetItem(item, 1);
            new_offset = base_offset + PyInt_AsLong(offset_obj);

            /* Insert padding manually */
            if (*offset > new_offset) {
                PyErr_SetString(PyExc_RuntimeError,
                                "This should never happen: Invalid offset in "
                                "buffer format string generation. Please "
                                "report a bug to the Numpy developers.");
                return -1;
            }
            while (*offset < new_offset) {
                _append_char(str, 'x');
                ++*offset;
            }

            /* Insert child item */
            _buffer_format_string(child, str, arr, offset,
                                  active_byteorder);

            /* Insert field name */
#if defined(NPY_PY3K)
            /* FIXME: XXX -- should it use UTF-8 here? */
            tmp = PyUnicode_AsUTF8String(name);
#else
            tmp = name;
#endif
            if (tmp == NULL || PyBytes_AsStringAndSize(tmp, &p, &len) < 0) {
                PyErr_SetString(PyExc_ValueError, "invalid field name");
                return -1;
            }
            _append_char(str, ':');
            while (len > 0) {
                if (*p == ':') {
                    Py_DECREF(tmp);
                    PyErr_SetString(PyExc_ValueError,
                                    "':' is not an allowed character in buffer "
                                    "field names");
                    return -1;
                }
                _append_char(str, *p);
                ++p;
                --len;
            }
            _append_char(str, ':');
#if defined(NPY_PY3K)
            Py_DECREF(tmp);
#endif
        }
        _append_char(str, '}');
    }
    else {
        int is_standard_size = 1;
        int is_native_only_type = (descr->type_num == NPY_LONGDOUBLE ||
                                   descr->type_num == NPY_CLONGDOUBLE);
#if NPY_SIZEOF_LONG_LONG != 8
        is_native_only_type = is_native_only_type || (
            descr->type_num == NPY_LONGLONG ||
            descr->type_num == NPY_ULONGLONG);
#endif

        *offset += descr->elsize;

        if (descr->byteorder == '=' &&
                _is_natively_aligned_at(descr, arr, *offset)) {
            /* Prefer native types, to cater for Cython */
            is_standard_size = 0;
            if (*active_byteorder != '@') {
                _append_char(str, '@');
                *active_byteorder = '@';
            }
        }
        else if (descr->byteorder == '=' && is_native_only_type) {
            /* Data types that have no standard size */
            is_standard_size = 0;
            if (*active_byteorder != '^') {
                _append_char(str, '^');
                *active_byteorder = '^';
            }
        }
        else if (descr->byteorder == '<' || descr->byteorder == '>' ||
                 descr->byteorder == '=') {
            is_standard_size = 1;
            if (*active_byteorder != descr->byteorder) {
                _append_char(str, descr->byteorder);
                *active_byteorder = descr->byteorder;
            }

            if (is_native_only_type) {
                /* It's not possible to express native-only data types
                   in non-native npy_byte orders */
                PyErr_Format(PyExc_ValueError,
                             "cannot expose native-only dtype '%c' in "
                             "non-native byte order '%c' via buffer interface",
                             descr->type, descr->byteorder);
            }
        }

        switch (descr->type_num) {
        case NPY_BOOL:         if (_append_char(str, '?')) return -1; break;
        case NPY_BYTE:         if (_append_char(str, 'b')) return -1; break;
        case NPY_UBYTE:        if (_append_char(str, 'B')) return -1; break;
        case NPY_SHORT:        if (_append_char(str, 'h')) return -1; break;
        case NPY_USHORT:       if (_append_char(str, 'H')) return -1; break;
        case NPY_INT:          if (_append_char(str, 'i')) return -1; break;
        case NPY_UINT:         if (_append_char(str, 'I')) return -1; break;
        case NPY_LONG:
            if (is_standard_size && (NPY_SIZEOF_LONG == 8)) {
                if (_append_char(str, 'q')) return -1;
            }
            else {
                if (_append_char(str, 'l')) return -1;
            }
            break;
        case NPY_ULONG:
            if (is_standard_size && (NPY_SIZEOF_LONG == 8)) {
                if (_append_char(str, 'Q')) return -1;
            }
            else {
                if (_append_char(str, 'L')) return -1;
            }
            break;
        case NPY_LONGLONG:     if (_append_char(str, 'q')) return -1; break;
        case NPY_ULONGLONG:    if (_append_char(str, 'Q')) return -1; break;
        case NPY_HALF:         if (_append_char(str, 'e')) return -1; break;
        case NPY_FLOAT:        if (_append_char(str, 'f')) return -1; break;
        case NPY_DOUBLE:       if (_append_char(str, 'd')) return -1; break;
        case NPY_LONGDOUBLE:   if (_append_char(str, 'g')) return -1; break;
        case NPY_CFLOAT:       if (_append_str(str, "Zf")) return -1; break;
        case NPY_CDOUBLE:      if (_append_str(str, "Zd")) return -1; break;
        case NPY_CLONGDOUBLE:  if (_append_str(str, "Zg")) return -1; break;
        /* XXX: datetime */
        /* XXX: timedelta */
        case NPY_OBJECT:       if (_append_char(str, 'O')) return -1; break;
        case NPY_STRING: {
            char buf[128];
            PyOS_snprintf(buf, sizeof(buf), "%ds", descr->elsize);
            if (_append_str(str, buf)) return -1;
            break;
        }
        case NPY_UNICODE: {
            /* Numpy Unicode is always 4-byte */
            char buf[128];
            assert(descr->elsize % 4 == 0);
            PyOS_snprintf(buf, sizeof(buf), "%dw", descr->elsize / 4);
            if (_append_str(str, buf)) return -1;
            break;
        }
        case NPY_VOID: {
            /* Insert padding bytes */
            char buf[128];
            PyOS_snprintf(buf, sizeof(buf), "%dx", descr->elsize);
            if (_append_str(str, buf)) return -1;
            break;
        }
        default:
            PyErr_Format(PyExc_ValueError,
                         "cannot include dtype '%c' in a buffer",
                         descr->type);
            return -1;
        }
    }

    return 0;
}
예제 #11
0
파일: pyloader.cpp 프로젝트: gatgui/lwc
 bool addType(const char *name, PyObject *klass) {
   
   bool singleton = false;
   std::string desc;
   
   PyObject *sg = PyObject_GetAttrString(klass, "Singleton");
   if (!sg) {
     PyErr_Clear();
   } else {
     if (PyBool_Check(sg)) {
       singleton = (sg == Py_True);
     }
     Py_DECREF(sg);
   }
   
   PyObject *de = PyObject_GetAttrString(klass, "Description");
   if (!de) {
     PyErr_Clear();
   } else {
     if (PyString_Check(de)) {
       desc = PyString_AsString(de);
     }
     Py_DECREF(de);
   }
   
   PyObject *mt = PyObject_GetAttrString(klass, "Methods");
   
   if (!mt || !PyDict_Check(mt)) {
     std::cout << "pyloader: Missing \"Methods\" class member" << std::endl;
     Py_XDECREF(mt);
     return false;
   }
   
   if (PyDict_Size(mt) == 0) {
     std::cout << "pyloader: No keys in \"Methods\" dict" << std::endl;
     Py_DECREF(mt);
     return false;
   }
   
   lwc::MethodsTable *typeMethods = 0;
   
   PyObject *key;
   PyObject *value;
   Py_ssize_t pos = 0;
   
   while (PyDict_Next(mt, &pos, &key, &value)) {
     
     if (!PyString_Check(key) || !PyTuple_Check(value)) {
       std::cout << "pyloader: \"Methods\" must be a dict of tuples" << std::endl;
       continue;
     }
     
     bool add = true;
     char *mname = PyString_AsString(key);
     char *mdesc = NULL;
     
     long n = PyTuple_Size(value);
     if (n < 1 || n > 2) {
       std::cout << "pyloader: \"Methods\" dict values must be tuples with 1 to 2 elements" << std::endl;
       continue;
     }
     
     PyObject *args = PyTuple_GetItem(value, 0);
     if (!PyList_Check(args)) {
       std::cout << "pyloader: \"Methods\" dict values' tuple first element must be a list" << std::endl;
       continue;
     }
     
     if (n == 2) {
       PyObject *pdesc = PyTuple_GetItem(value, 1);
       if (!PyString_Check(pdesc)) {
         std::cout << "pyloader: \"Methods\" dict values' tuple second element must be a string" << std::endl;
         continue;
       }
       mdesc = PyString_AsString(pdesc);
     }
     
     lwc::Method meth;
     
     if (mdesc) {
       meth.setDescription(mdesc);
     }
     
     n = PyList_Size(args);
     
     for (long i=0; i<n; ++i) {
       PyObject *arg = PyList_GetItem(args, i);
       Py_ssize_t ts = PyTuple_Size(arg);
       if (!PyTuple_Check(arg) || ts < 2 || ts > 6) {
         std::cout << "pyloader: Arguments must be tuples with 2 to 6 elements" << std::endl;
         add = false;
         break;
       }
       lwc::Argument a;
       a.setDir(lwc::Direction(PyInt_AsLong(PyTuple_GetItem(arg, 0))));
       a.setType(lwc::Type(PyInt_AsLong(PyTuple_GetItem(arg, 1))));
       if (ts >= 3) {
         a.setArraySizeArg(PyInt_AsLong(PyTuple_GetItem(arg, 2)));
       }
       if (ts >= 4) {
         PyObject *ahd = PyTuple_GetItem(arg, 3);
         if (!PyBool_Check(ahd)) {
           std::cout << "pyloader: Argument's tuple 4th element must be a boolean" << std::endl;
           add = false;
           break;
         }
         if (ahd == Py_True) {
           if (ts < 5) {
             std::cout << "pyloader: Argument is missing default value" << std::endl;
             add = false;
             break;
           } else {
             PyObject *pdv = PyTuple_GetItem(arg, 4);
             py::SetArgDefault(a, pdv);
           }
         }
         // hasDefault (yes, no)
         // if yes -> must have at least 5
       }
       if (ts >= 6) {
         PyObject *aname = PyTuple_GetItem(arg, 5);
         if (!PyString_Check(aname)) {
           std::cout << "pyloader: Arguments name must be a string" << std::endl;
           add = false;
           break;
         }
         a.setName(PyString_AsString(aname));
       }
       try {
         meth.addArg(a);
       } catch (std::exception &e) {
         std::cout << "pyloader: " << e.what() << std::endl;
         add = false;
         break;
       }
     }
     
     if (!add) {
       std::cout << "pyloader: Skipped method (1) \"" << mname << "\" for type \"" << name << "\"" << std::endl;
       continue;
     
     } else {
       if (!typeMethods) {
         PyTypeObject *to = (PyTypeObject*) klass;
         Py_ssize_t nbases = PyTuple_Size(to->tp_bases);
         if (nbases > 1) {
           std::cout << "pyloader: Skipped type \"" << name << "\" (Multiple inheritance not supported)" << std::endl;
           return false;
         }
         if (nbases == 1 && PyTuple_GetItem(to->tp_bases, 0) != (PyObject*)&py::PyLWCObjectType) {
           PyObject *pto = PyTuple_GetItem(to->tp_bases, 0);
           std::map<std::string, TypeEntry>::iterator it = mTypes.begin();
           while (it != mTypes.end()) {
             if (it->second.klass == pto) {
               typeMethods = new lwc::MethodsTable(it->second.methods);
               break;
             }
             ++it;
           }
           if (!typeMethods) {
             std::cout << "pyloader: Skipped type \"" << name << "\" (Super class not registered yet)" << std::endl;
             return false;
           }
         } else {
           typeMethods = new lwc::MethodsTable();
         }
       }
       try {
         typeMethods->addMethod(mname, meth);
       } catch (std::runtime_error &e) {
         std::cout << "pyloader: Skipped method (2) \"" << mname << "\" for type \"" << name << "\"" << std::endl;
         std::cout << e.what() << std::endl;
         continue;
       }
     }
   }
   
   Py_DECREF(mt);
   
   if (typeMethods) {
     if (typeMethods->numMethods() == 0) {
       std::cout << "pyloader: MethodsTable is empty for type \"" << name << "\"" << std::endl;
       delete typeMethods;
       return false;
     } else {
       TypeEntry te;
       Py_INCREF(klass);
       te.klass = klass;
       te.singleton = singleton;
       te.methods = typeMethods;
       te.desc = desc;
       mTypes[name] = te;
       return true;
     }
   } else {
     std::cout << "pyloader: MethodsTable not allocated for type \"" << name << "\"" << std::endl;
     return false;
   }
   
 }
예제 #12
0
파일: zipimport.c 프로젝트: cpcloud/cpython
/* Get the code object associated with the module specified by
   'fullname'. */
static PyObject *
get_module_code(ZipImporter *self, PyObject *fullname,
                int *p_ispackage, PyObject **p_modpath)
{
    PyObject *code = NULL, *toc_entry, *subname;
    PyObject *path, *fullpath = NULL;
    struct st_zip_searchorder *zso;

    subname = get_subname(fullname);
    if (subname == NULL)
        return NULL;

    path = make_filename(self->prefix, subname);
    Py_DECREF(subname);
    if (path == NULL)
        return NULL;

    for (zso = zip_searchorder; *zso->suffix; zso++) {
        code = NULL;

        fullpath = PyUnicode_FromFormat("%U%s", path, zso->suffix);
        if (fullpath == NULL)
            goto exit;

        if (Py_VerboseFlag > 1)
            PySys_FormatStderr("# trying %U%c%U\n",
                               self->archive, (int)SEP, fullpath);
        toc_entry = PyDict_GetItem(self->files, fullpath);
        if (toc_entry != NULL) {
            time_t mtime = 0;
            int ispackage = zso->type & IS_PACKAGE;
            int isbytecode = zso->type & IS_BYTECODE;

            if (isbytecode) {
                mtime = get_mtime_of_source(self, fullpath);
                if (mtime == (time_t)-1 && PyErr_Occurred()) {
                    goto exit;
                }
            }
            Py_CLEAR(fullpath);
            if (p_ispackage != NULL)
                *p_ispackage = ispackage;
            code = get_code_from_data(self, ispackage,
                                      isbytecode, mtime,
                                      toc_entry);
            if (code == Py_None) {
                /* bad magic number or non-matching mtime
                   in byte code, try next */
                Py_DECREF(code);
                continue;
            }
            if (code != NULL && p_modpath != NULL) {
                *p_modpath = PyTuple_GetItem(toc_entry, 0);
                Py_INCREF(*p_modpath);
            }
            goto exit;
        }
        else
            Py_CLEAR(fullpath);
    }
    PyErr_Format(ZipImportError, "can't find module %R", fullname);
exit:
    Py_DECREF(path);
    Py_XDECREF(fullpath);
    return code;
}
예제 #13
0
static PyObject * oXformProperty_setValues(PyObject * self, PyObject * args)
{
   ALEMBIC_TRY_STATEMENT

   oXformProperty * prop = (oXformProperty*)self;
   if(prop->mArchive == NULL)
   {
      PyErr_SetString(getError(), "Archive already closed!");
      return NULL;
   }

   PyObject * tuple = NULL;
   if(!PyArg_ParseTuple(args, "O", &tuple))
   {
      PyErr_SetString(getError(), "No sample tuple specified!");
      return NULL;
   }
   if(!PyTuple_Check(tuple) && !PyList_Check(tuple))
   {
      PyErr_SetString(getError(), "Sample tuple argument is not a tuple!");
      return NULL;
   }

   /*if(prop->mMembers->mXformSchema.getNumSamples() >= prop->mMaxNbSamples)
   {
      PyErr_SetString(getError(), "Already stored the maximum number of samples!");
      return NULL;
   }*/

   size_t nbItems = 0;
   if(PyTuple_Check(tuple))
      nbItems = PyTuple_Size(tuple);
   else
      nbItems = PyList_Size(tuple);

   if(nbItems != 16)
   {
      PyErr_SetString(getError(), "Sample tuple should contain 16 items!");
      return NULL;
   }

   std::vector<double> values(16);
   for(size_t i=0;i<16;i++)
   {
      PyObject * item = NULL;
      if(PyTuple_Check(tuple))
         item = PyTuple_GetItem(tuple,i);
      else
         item = PyList_GetItem(tuple,i);
      if(!PyArg_Parse(item,"d",&values[i]))
      {
         PyErr_SetString(getError(), "Some item of the sample tuple is not a floating point number!");
         return NULL;
      }
   }

   Imath::M44d matrix(values[0],values[1],values[2],values[3],values[4],values[5],values[6],values[7],
                      values[8],values[9],values[10],values[11],values[12],values[13],values[14],values[15]);
   prop->mMembers->mSample.setInheritsXforms(true);
   prop->mMembers->mSample.setMatrix(matrix);
   prop->mMembers->mXformSchema.set(prop->mMembers->mSample);

   return Py_BuildValue("I",prop->mMembers->mXformSchema.getNumSamples());
   ALEMBIC_PYOBJECT_CATCH_STATEMENT
}
예제 #14
0
static gboolean
_pygi_marshal_from_py_interface_callback (PyGIInvokeState   *state,
                                          PyGICallableCache *callable_cache,
                                          PyGIArgCache      *arg_cache,
                                          PyObject          *py_arg,
                                          GIArgument        *arg,
                                          gpointer          *cleanup_data)
{
    GICallableInfo *callable_info;
    PyGICClosure *closure;
    PyGIArgCache *user_data_cache = NULL;
    PyGIArgCache *destroy_cache = NULL;
    PyGICallbackCache *callback_cache;
    PyObject *py_user_data = NULL;

    callback_cache = (PyGICallbackCache *)arg_cache;

    if (callback_cache->user_data_index > 0) {
        user_data_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->user_data_index);
        if (user_data_cache->py_arg_index < state->n_py_in_args) {
            /* py_user_data is a borrowed reference. */
            py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
            if (!py_user_data)
                return FALSE;
            /* NULL out user_data if it was not supplied and the default arg placeholder
             * was used instead.
             */
            if (py_user_data == _PyGIDefaultArgPlaceholder) {
                py_user_data = NULL;
            } else if (callable_cache->user_data_varargs_index < 0) {
                /* For non-variable length user data, place the user data in a
                 * single item tuple which is concatenated to the callbacks arguments.
                 * This allows callback input arg marshaling to always expect a
                 * tuple for user data. Note the
                 */
                py_user_data = Py_BuildValue("(O)", py_user_data, NULL);
            } else {
                /* increment the ref borrowed from PyTuple_GetItem above */
                Py_INCREF (py_user_data);
            }
        }
    }

    if (py_arg == Py_None) {
        return TRUE;
    }

    if (!PyCallable_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError,
                      "Callback needs to be a function or method not %s",
                      py_arg->ob_type->tp_name);

        return FALSE;
    }

    callable_info = (GICallableInfo *)callback_cache->interface_info;

    closure = _pygi_make_native_closure (callable_info, callback_cache->scope, py_arg, py_user_data);
    arg->v_pointer = closure->closure;

    /* always decref the user data as _pygi_make_native_closure adds its own ref */
    Py_XDECREF (py_user_data);

    /* The PyGICClosure instance is used as user data passed into the C function.
     * The return trip to python will marshal this back and pull the python user data out.
     */
    if (user_data_cache != NULL) {
        state->args[user_data_cache->c_arg_index].arg_value.v_pointer = closure;
    }

    /* Setup a GDestroyNotify callback if this method supports it along with
     * a user data field. The user data field is a requirement in order
     * free resources and ref counts associated with this arguments closure.
     * In case a user data field is not available, show a warning giving
     * explicit information and setup a dummy notification to avoid a crash
     * later on in _pygi_destroy_notify_callback_closure.
     */
    if (callback_cache->destroy_notify_index > 0) {
        destroy_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->destroy_notify_index);
    }

    if (destroy_cache) {
        if (user_data_cache != NULL) {
            state->args[destroy_cache->c_arg_index].arg_value.v_pointer = _pygi_invoke_closure_free;
        } else {
            char *full_name = pygi_callable_cache_get_full_name (callable_cache);
            gchar *msg = g_strdup_printf("Callables passed to %s will leak references because "
                                         "the method does not support a user_data argument. "
                                         "See: https://bugzilla.gnome.org/show_bug.cgi?id=685598",
                                         full_name);
            g_free (full_name);
            if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 2)) {
                g_free(msg);
                _pygi_invoke_closure_free(closure);
                return FALSE;
            }
            g_free(msg);
            state->args[destroy_cache->c_arg_index].arg_value.v_pointer = _pygi_destroy_notify_dummy;
        }
    }

    /* Use the PyGIClosure as data passed to cleanup for GI_SCOPE_TYPE_CALL. */
    *cleanup_data = closure;

    return TRUE;
}
예제 #15
0
static PyObject *
cpmaximum(PyObject *self, PyObject *args)
{
     PyObject *image     = NULL; /* the image ndarray */
     PyObject *cimage    = NULL; /* a contiguous version of the array */
     PyObject *structure = NULL; /* the structure ndarray */
     PyObject *cstructure= NULL; /* a contiguous version of the structure */
     PyObject *im_shape  = NULL; /* the image shape sequence */
     PyObject *str_shape = NULL; /* the structure shape sequence */
     PyObject *offset    = NULL; /* 2-tuple giving the x and y offset of the origin of the structuring element */
     long     height     = 0;    /* the image height */
     long     width      = 0;    /* the image width */
     long     strheight  = 0;    /* the structuring element height */
     long     strwidth   = 0;    /* the structuring element width */
     PyObject *output    = NULL; /* the output ndarray */
     double   *imdata    = NULL; /* the image data */
     char     *strdata   = NULL; /* the structure data (really boolean) */
     double   *out_data  = NULL; /* the output data */
     const char *error   = NULL;
     PyObject **shapes[] = { &im_shape, &im_shape, &str_shape, &str_shape };
     long     *slots[]   = { &width, &height, &strwidth, &strheight };
     int      indices[]  = { 0,1,0,1 };
     int      i          = 0;
     int      j          = 0;
     int      k          = 0;
     int      l          = 0;
     npy_intp dims[2];
     long     xoff       = 0;
     long     yoff       = 0;

     image = PySequence_GetItem(args,0);
     if (! image) {
          error = "Failed to get image from arguments";
          goto exit;
     }
     cimage = PyArray_ContiguousFromAny(image, NPY_DOUBLE,2,2);
     if (! cimage) {
          error = "Failed to make a contiguous array from first argument";
          goto exit;
     }
     structure = PySequence_GetItem(args,1);
     if (! structure) {
          error = "Failed to get structuring element from arguments";
          goto exit;
     }
     cstructure = PyArray_ContiguousFromAny(structure, NPY_BOOL,2,2);
     if (! cstructure) {
          error = "Failed to make a contiguous array from second argument";
          goto exit;
     }
     im_shape = PyObject_GetAttrString(cimage,"shape");
     if (! im_shape) {
          error = "Failed to get image.shape";
          goto exit;
     }
     if (! PyTuple_Check(im_shape)) {
          error = "image.shape not a tuple";
          goto exit;
     }
     if (PyTuple_Size(im_shape) != 2) {
          error = "image is not 2D";
          goto exit;
     }

     str_shape = PyObject_GetAttrString(cstructure,"shape");
     if (! str_shape) {
          error = "Failed to get structure.shape";
          goto exit;
     }
     if (! PyTuple_Check(str_shape)) {
          error = "structure.shape not a tuple";
          goto exit;
     }
     if (PyTuple_Size(str_shape) != 2) {
          error = "structure is not 2D";
          goto exit;
     }
     for (i=0;i<4;i++) {
          PyObject *obDim = PyTuple_GetItem(*shapes[i],indices[i]);
          *(slots[i]) = PyInt_AsLong(obDim);
          if (PyErr_Occurred()) {
               error = "Array shape is not a tuple of integers";
               goto exit;
          }
     }
     imdata = (double *)PyArray_DATA(cimage);
     if (! imdata) {
          error = "Failed to get image data";
          goto exit;
     }
     strdata = (char *)PyArray_DATA(cstructure);
     if (! strdata) {
          error = "Failed to get structure data";
          goto exit;
     }
     offset = PySequence_GetItem(args,2);
     if (! offset) {
          error = "Failed to get offset into structure from args";
          goto exit;
     }
     if (! PyTuple_Check(offset)) {
          error = "offset is not a tuple";
          goto exit;
     } else {
          PyObject *temp = PyTuple_GetItem(offset,0);
          if (! temp) {
               error = "Failed to get x offset from tuple";
               goto exit;
          }
          xoff = PyInt_AsLong(temp);
          if (PyErr_Occurred()) {
               error = "Offset X is not an integer";
               goto exit;
          }
          temp = PyTuple_GetItem(offset,1);
          if (! temp) {
               error = "Failed to get y offset from tuple";
               goto exit;
          }
          yoff = PyInt_AsLong(temp);
          if (PyErr_Occurred()) {
               error = "Offset Y is not an integer";
               goto exit;
          }
     }
     
     dims[0] = width;
     dims[1] = height;
     output = PyArray_SimpleNew(2, dims, NPY_DOUBLE);
     if (! output) {
          error = "Failed to create output array";
          goto exit;
     }
     out_data = (double *)PyArray_DATA(output);
     memcpy(out_data,imdata,height*width*sizeof(double));

     for (j=0;j<height;j++) {
          for (i=0;i<width;i++,imdata++) {
               char *strptr = strdata;
               double value = - 1000000; /* was INFINITY but Unix doesn't like */
               if (i-xoff < 0 ||
                   j-yoff < 0 ||
                   i+strwidth-xoff >= width ||
                   j+strheight-yoff >= height) {
                    /* A corner case (literally) - check limit as we go */
                    for (l=-yoff;l<strheight-yoff;l++) {
                         double *imdata_ptr = imdata + l*width-xoff;
                         for (k=-xoff;k<strwidth-xoff;k++,imdata_ptr++) {
                              double data;
                              if (! *strptr++) continue;
                              if (i+k < 0) continue;
                              if (i+k >= width) continue;
                              if (j+l < 0) continue;
                              if (j+l >= width) continue;
                              data = *imdata_ptr;
                              if (data > value)
                                   value = data;
                         }
                    }
               } else {
                    /* Don't worry about corners and go faster */
                    for (l=-yoff;l<strheight-yoff;l++) {
                         double *imdata_ptr = imdata + l*width-xoff;
                         for (k=-xoff;k<strwidth-xoff;k++,imdata_ptr++) {
                              double data;
                              if (! *strptr++) continue;
                              data = *imdata_ptr;
                              if (data > value)
                                   value = data;
                         }
                    }
               }
               *out_data++ = value;
          }
     }
     

  exit:
     if (image) {
          Py_DECREF(image);
     }
     if (cimage) {
          Py_DECREF(cimage);
     }
     if (structure) {
          Py_DECREF(structure);
     }
     if (cstructure) {
          Py_DECREF(cstructure);
     }
     if (im_shape) {
          Py_DECREF(im_shape);
     }
     if (str_shape) {
          Py_DECREF(str_shape);
     }
     if (offset) {
          Py_DECREF(offset);
     }

     if (error) {
          if (output) {
               Py_DECREF(output);
          }
          output = PyString_FromString(error);
          if (! output) {
               Py_RETURN_NONE;
          }
     }
     return output;
}
예제 #16
0
static PyObject *
Tkapp_Call(PyObject *self, PyObject *args)
{
	Tcl_Obj *objStore[ARGSZ];
	Tcl_Obj **objv = NULL;
	int objc = 0, i;
	PyObject *res = NULL;
	Tcl_Interp *interp = Tkapp_Interp(self);
	/* Could add TCL_EVAL_GLOBAL if wrapped by GlobalCall... */
	int flags = TCL_EVAL_DIRECT;

	objv = objStore;

	if (args == NULL)
		objc = 0;

	else if (!PyTuple_Check(args)) {
		objc = 1;
		objv[0] = AsObj(args);
		if (objv[0] == 0)
			goto finally;
		Tcl_IncrRefCount(objv[0]);
	}
	else {
		objc = PyTuple_Size(args);

		if (objc > ARGSZ) {
			objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
			if (objv == NULL) {
				PyErr_NoMemory();
				goto finally;
			}
		}

		for (i = 0; i < objc; i++) {
			PyObject *v = PyTuple_GetItem(args, i);
			if (v == Py_None) {
				objc = i;
				break;
			}
			objv[i] = AsObj(v);
			if (!objv[i])
				goto finally;
			Tcl_IncrRefCount(objv[i]);
		}
	}

	ENTER_TCL

	i = Tcl_EvalObjv(interp, objc, objv, flags);

	ENTER_OVERLAP
	if (i == TCL_ERROR)
		Tkinter_Error(self);
	else {
		/* We could request the object result here, but doing
		   so would confuse applications that expect a string. */
		char *s = Tcl_GetStringResult(interp);
		char *p = s;
		/* If the result contains any bytes with the top bit set,
		   it's UTF-8 and we should decode it to Unicode */
		while (*p != '\0') {
			if (*p & 0x80)
				break;
			p++;
		}
		if (*p == '\0')
			res = PyString_FromStringAndSize(s, (int)(p-s));
		else {
			/* Convert UTF-8 to Unicode string */
			p = strchr(p, '\0');
			res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
			if (res == NULL) {
			    PyErr_Clear();
			    res = PyString_FromStringAndSize(s, (int)(p-s));
			}
		}
	}

	LEAVE_OVERLAP_TCL

  finally:
	for (i = 0; i < objc; i++)
		Tcl_DecrRefCount(objv[i]);
	if (objv != objStore)
		ckfree(FREECAST objv);
	return res;
}
/* Hall of shame, wasted time debugging the code below
 * 20min - Johan 2009-02-19
 */
static PyObject *
pygi_collect_attributes (PyObject *self,
			 PyObject *args)
{
  char *tag_name;
  PyObject *attributes;
  int indent, indent_len, i, j, self_indent;
  char *indent_char;
  gboolean first;
  GString *attr_value = NULL;
  int len;
  PyObject *result = NULL;

  if (!PyArg_ParseTuple(args, "sO!isi",
			&tag_name, &PyList_Type, &attributes,
			&self_indent, &indent_char,
			&indent))
    return NULL;

  if (attributes == Py_None || !PyList_Size(attributes))
    return PyUnicode_DecodeUTF8("", 0, "strict");

  len = calc_attrs_length(attributes, indent, self_indent);
  if (len < 0)
    return NULL;
  if (len > 79)
    indent_len = self_indent + strlen(tag_name) + 1;
  else
    indent_len = 0;

  first = TRUE;
  attr_value = g_string_new ("");

  for (i = 0; i < PyList_Size (attributes); ++i)
    {
      PyObject *tuple, *pyvalue;
      char *attr, *value, *escaped;

      tuple = PyList_GetItem (attributes, i);

      if (!PyTuple_Check (tuple))
        {
          PyErr_SetString(PyExc_TypeError,
                          "attribute item must be a tuple");
	  goto out;
        }

      if (!PyTuple_Size (tuple) == 2)
        {
          PyErr_SetString(PyExc_IndexError,
                          "attribute item must be a tuple of length 2");
	  goto out;
        }

      if (PyTuple_GetItem(tuple, 1) == Py_None)
	continue;

      /* this leaks, but we exit after, so */
      if (!PyArg_ParseTuple(tuple, "sO", &attr, &pyvalue))
	goto out;

      if (PyUnicode_Check(pyvalue)) {
        PyObject *s = PyUnicode_AsUTF8String(pyvalue);
        if (!s)
	  goto out;
        value = PyString_AsString(s);
        Py_DECREF(s);
      } else if (PyString_Check(pyvalue)) {
        value = PyString_AsString(pyvalue);
      } else {
        PyErr_SetString(PyExc_TypeError,
                        "value must be string or unicode");
	goto out;
      }

      if (indent_len && !first)
	{
	  g_string_append_c (attr_value, '\n');
	  for (j = 0; j < indent_len; j++)
	    g_string_append_c (attr_value, ' ');
	}
      g_string_append_c (attr_value, ' ');
      g_string_append (attr_value, attr);
      g_string_append_c (attr_value, '=');
      g_string_append_c (attr_value, '\"');
      escaped = g_markup_escape_text (value, -1);
      g_string_append (attr_value, escaped);
      g_string_append_c (attr_value, '\"');
      if (first)
	first = FALSE;
  }

  result = PyUnicode_DecodeUTF8 (attr_value->str, attr_value->len, "strict");
 out:
  if (attr_value != NULL)
    g_string_free (attr_value, TRUE);
  return result;
}
예제 #18
0
static PyObject *
Tkapp_Call(PyObject *self, PyObject *args)
{
	/* This is copied from Merge() */
	PyObject *tmp = NULL;
	char *argvStore[ARGSZ];
	char **argv = NULL;
	int fvStore[ARGSZ];
	int *fv = NULL;
	int argc = 0, fvc = 0, i;
	PyObject *res = NULL; /* except this has a different type */
	Tcl_CmdInfo info; /* and this is added */
	Tcl_Interp *interp = Tkapp_Interp(self); /* and this too */

	if (!(tmp = PyList_New(0)))
	    return NULL;

	argv = argvStore;
	fv = fvStore;

	if (args == NULL)
		argc = 0;

	else if (!PyTuple_Check(args)) {
		argc = 1;
		fv[0] = 0;
		if (!(argv[0] = AsString(args, tmp)))
			goto finally;
	}
	else {
		argc = PyTuple_Size(args);

		if (argc > ARGSZ) {
			argv = (char **)ckalloc(argc * sizeof(char *));
			fv = (int *)ckalloc(argc * sizeof(int));
			if (argv == NULL || fv == NULL) {
				PyErr_NoMemory();
				goto finally;
			}
		}

		for (i = 0; i < argc; i++) {
			PyObject *v = PyTuple_GetItem(args, i);
			if (PyTuple_Check(v)) {
				fv[i] = 1;
				if (!(argv[i] = Merge(v)))
					goto finally;
				fvc++;
			}
			else if (v == Py_None) {
				argc = i;
				break;
			}
			else {
				fv[i] = 0;
				if (!(argv[i] = AsString(v, tmp)))
					goto finally;
				fvc++;
			}
		}
	}
	/* End code copied from Merge() */

	/* All this to avoid a call to Tcl_Merge() and the corresponding call
	   to Tcl_SplitList() inside Tcl_Eval()...  It can save a bundle! */
	if (Py_VerboseFlag >= 2) {
		for (i = 0; i < argc; i++)
			PySys_WriteStderr("%s ", argv[i]);
	}
	ENTER_TCL
	info.proc = NULL;
	if (argc < 1 ||
	    !Tcl_GetCommandInfo(interp, argv[0], &info) ||
	    info.proc == NULL)
	{
		char *cmd;
		cmd = Tcl_Merge(argc, argv);
		i = Tcl_Eval(interp, cmd);
		ckfree(cmd);
	}
	else {
		Tcl_ResetResult(interp);
		i = (*info.proc)(info.clientData, interp, argc, argv);
	}
	ENTER_OVERLAP
	if (info.proc == NULL && Py_VerboseFlag >= 2)
		PySys_WriteStderr("... use TclEval ");
	if (i == TCL_ERROR) {
		if (Py_VerboseFlag >= 2)
			PySys_WriteStderr("... error: '%s'\n",
				Tcl_GetStringResult(interp));
		Tkinter_Error(self);
	}
	else {
		if (Py_VerboseFlag >= 2)
			PySys_WriteStderr("-> '%s'\n", Tcl_GetStringResult(interp));
		res = PyString_FromString(Tcl_GetStringResult(interp));
	}
	LEAVE_OVERLAP_TCL

	/* Copied from Merge() again */
  finally:
	for (i = 0; i < fvc; i++)
		if (fv[i]) {
			ckfree(argv[i]);
		}
	if (argv != argvStore)
		ckfree(FREECAST argv);
	if (fv != fvStore)
		ckfree(FREECAST fv);

	Py_DECREF(tmp);
	return res;
}
예제 #19
0
static int p_iterenv (void *data, int x, char **rk, char **rv)
{
  WRAPPER_DATA *wrap = (WRAPPER_DATA *)data;
  PyObject *items;
  PyObject *env_list;
  PyObject *result;
  PyObject *k, *v;

  items = PyObject_GetAttrString(wrap->p_env, "items");
  if (items == NULL)
  {
    ne_warn ("p_iterenv: Unable to get items method");
    PyErr_Clear();
    return -1;
  }
  env_list = PyEval_CallObject(items, NULL);
  Py_DECREF(items);
  if (env_list == NULL)
  {
    ne_warn ("p_iterenv: Unable to call items method");
    PyErr_Clear();
    return -1;
  }
  if (x >= PyList_Size(env_list))
  {
    *rk = NULL;
    *rv = NULL;
    Py_DECREF(env_list); 
    return 0;
  }
  result = PyList_GetItem (env_list, x);
  if (result == NULL)
  {
    ne_warn ("p_iterenv: Unable to get env %d", x);
    Py_DECREF(env_list); 
    PyErr_Clear();
    return -1;
  }
  k = PyTuple_GetItem (result, 0);
  v = PyTuple_GetItem (result, 1);
  if (k == NULL || v == NULL)
  {
    ne_warn ("p_iterenv: Unable to get k,v %p,%p", k, v); 
    Py_DECREF(env_list); 
    PyErr_Clear();
    return -1;
  }
  *rk = strdup(PyString_AsString(k));
  *rv = strdup(PyString_AsString(v));
  if (*rk == NULL || *rv == NULL)
  {
    if (*rk) free (*rk);
    if (*rv) free (*rv);
    Py_DECREF(env_list); 
    PyErr_Clear();
    return -1;
  }

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

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

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

        // do all quick rejects first (no loops)
        if (x->nd != y->nd) {
            // number of dimensions doesn't match
            return 1;
            // note that a (1 x X) array can never equal a single
            // dimensional array of length X.
        }
        if (x->descr->type_num != y->descr->type_num) {
            // type of elements doesn't match
            return 1;
        }
        if (x->descr->type_num == PyArray_OBJECT) {
            objectCompare = 1;
        }
        elementSize = x->descr->elsize;
        if (elementSize != y->descr->elsize) {
            // size of elements doesn't match (shouldn't happen if
            // types match!)
            return 1;
        }
        for (i = x->nd - 1; i >= 0; i--) {
            if (x->dimensions[i] != y->dimensions[i])
                // shapes don't match
                return 1;
        }
        // we do a lot of these, so handle them early
        if (x->nd == 1 && !objectCompare && x->strides[0]==elementSize && y->strides[0]==elementSize) {
            // contiguous one dimensional array of non-objects
            return memcmp(x->data, y->data, elementSize * x->dimensions[0]) ? 1 : 0;
        }
        if (x->nd == 0) {
            // scalar, just compare one element
            if (objectCompare) {
                return _same_vals_helper(*(PyObject **)x->data, *(PyObject **)y->data);
            } else {
                return memcmp(x->data, y->data, elementSize) ? 1 : 0;
            }
        }
        // If we decide we can't do alloca() for some reason, we can
        // either have a fixed maximum dimensionality, or use alloc
        // and free.
        indices = (int *)alloca(sizeof(int) * x->nd);
        for (i = x->nd - 1; i >= 0; i--) {
            indices[i] = 0;
        }
        topDimension = x->dimensions[0];
        while (indices[0] < topDimension) {
            xdata = x->data;
            ydata = y->data;
            for (i = 0; i < x->nd; i++) {
                xdata += indices[i] * x->strides[i];
                ydata += indices[i] * y->strides[i];
            }
            if (objectCompare) {
                if (_same_vals_helper(*(PyObject **)xdata, *(PyObject **)ydata)) {
                    return 1;
                }
            } else if (memcmp(xdata, ydata, elementSize) != 0) {
                // element mismatch
                return 1;
            }
            // step to next element
            for (i = x->nd - 1; i>=0; i--) {
                indices[i]++;
                if (i == 0 || indices[i] < x->dimensions[i]) {
                    break;
                }
                indices[i] = 0;
            }
        }
        // all elements match
        return 0;
    }
#if 0
    XX({
        if (typ1 == &PyInstance_Type) {
            PyInstanceObject *x = (PyInstanceObject *) v1;
            PyObject_Print(x->in_class->cl_name, stdout, 0);
        } else {
            PyObject_Print((PyObject*)typ1, stdout, 0);
        }
        if (typ1->tp_compare == NULL)
            printf(" (rich comparison)");
        printf("\n");
    });
예제 #21
0
static PyObject *
method_sendfile(PyObject *self, PyObject *args)
{
    int fd, s, sts;
    off_t offset, sbytes;
    size_t nbytes;
    PyObject *headers;
    struct iovec *header_iovs;
    struct iovec *footer_iovs;
    struct sf_hdtr hdtr;

    headers = NULL;

    if (!PyArg_ParseTuple(args, "iiLi|O:sendfile", &fd, &s, &offset, &nbytes, &headers))
        return NULL;

    if (headers != NULL) {
        int i, listlen;
        PyObject *string;
        char *buf;
        int headerlist_len;
        int headerlist_string = 0;
        int footerlist_len;
        int footerlist_string = 0;
        PyObject *headerlist;
        PyObject *footerlist;

        if (PyTuple_Check(headers) && PyTuple_Size(headers) > 1) {
            //printf("arg is tuple length %d\n", PyTuple_Size(headers));
            headerlist = PyTuple_GetItem(headers, 0);
            if (PyList_Check(headerlist)) {
                headerlist_len = PyList_Size(headerlist);
            } else if (PyString_Check(headerlist)) {
                headerlist_string = 1;
                headerlist_len = 1;
            } else {
                headerlist_len = 0;
            }

            footerlist = PyTuple_GetItem(headers, 1);
            if (PyList_Check(footerlist)) {
                //printf("footer is list\n");
                footerlist_len = PyList_Size(footerlist);
            } else if (PyString_Check(footerlist)) {
                //printf("footer is string\n");
                footerlist_string = 1;
                footerlist_len = 1;
            } else {
                //printf("footer is invalid\n");
                footerlist_len = 0;
            }
        } else {
            if (PyTuple_Check(headers)) {
                headerlist = PyTuple_GetItem(headers, 0);
            } else {
                headerlist = headers;
            }
            if (PyList_Check(headerlist)) {
            	headerlist_len = PyList_Size(headerlist);
            } else if (PyString_Check(headerlist)) {
                headerlist_string = 1;
                headerlist_len = 1;
            } else {
                headerlist_len = 0;
            }

            footerlist_len = 0;
            footer_iovs = 0;
        }
        //printf("header list size and type: %d, %d\nfooter list size and type: %d, %d\n", headerlist_len, headerlist_string, footerlist_len, footerlist_string);

        header_iovs = (struct iovec*) malloc( sizeof(struct iovec) * headerlist_len );
        for (i=0; i < headerlist_len; i++) {
            if (headerlist_string) {
                //printf("found string\n");
                string = headerlist;
            } else {
                //printf("found list\n");
                string = PyList_GET_ITEM(headerlist, i);                
            }
            buf = (char *) PyString_AsString(string);                
            //printf("buf: %s\n", buf);
            header_iovs[i].iov_base = buf;
            header_iovs[i].iov_len = PyString_GET_SIZE(string);
        }

        footer_iovs = (struct iovec*) malloc( sizeof(struct iovec) * footerlist_len );
        for (i=0; i < footerlist_len; i++) {
            if (footerlist_string) {
                //printf("found string\n");
                string = footerlist;
            } else {
                //printf("found list\n");
                string = PyList_GET_ITEM(footerlist, i);                
            }
            buf = (char *) PyString_AsString(string);
            //printf("buf: %s\n", buf);
            footer_iovs[i].iov_base = buf;
            footer_iovs[i].iov_len = PyString_GET_SIZE(string);
        }

        hdtr.headers = header_iovs;
        hdtr.hdr_cnt = headerlist_len;
        hdtr.trailers = footer_iovs;
        hdtr.trl_cnt = footerlist_len;

	Py_BEGIN_ALLOW_THREADS;
        sts = sendfile(s, fd, (off_t) offset, (size_t) nbytes, &hdtr, (off_t *) &sbytes, 0);
	Py_END_ALLOW_THREADS;
        free(header_iovs);
        free(footer_iovs);
    } else {
	Py_BEGIN_ALLOW_THREADS;
        sts = sendfile(s, fd, (off_t) offset, (size_t) nbytes, NULL, (off_t *) &sbytes, 0);
	Py_END_ALLOW_THREADS;
    }
    if (sts == -1) {
        if (errno == EAGAIN || errno == EINTR) {
            return Py_BuildValue("LL", offset + nbytes, sbytes);
        } else {
            PyErr_SetFromErrno(PyExc_OSError);
            return NULL;
        }
    } else {
        return Py_BuildValue("LL", offset + nbytes, sbytes);
    }
}
예제 #22
0
파일: dr_wide.c 프로젝트: gcross/QC-Talks
PyObject* draw_path_wide_stroke( PyObject* self, PyObject* args )
{
    PyObject* pobj;
    PyObject* plist = NULL;
    PyObject* cacheobj = NULL;
    int i;
    int size;
    PyObject* item;

    int displaylist = -1;
    
    int cset = 0;    // is there a current point?
    int drawn = 0;
    double cx, cy;
    double tx, ty;
    double sx, sy;
    double queue[3][4], start[4];
    int qpos = 0;
    
    double c[8];
    int j;
    double width;

    if ( !PyArg_ParseTuple( args, "Od", &pobj, &width ) )
	return NULL;

    delete_invalid_lists( pobj );

    cacheobj = PyObject_GetAttrString( pobj, "_widestroke_list" );
    if ( cacheobj )
    {
	if ( PyTuple_Check( cacheobj ) &&
	     PyTuple_Size( cacheobj ) == 2 )
	{
	    displaylist = PyInt_AsLong( PyTuple_GetItem( cacheobj, 0 ) );
	    if ( PyFloat_AsDouble( PyTuple_GetItem( cacheobj, 1 ) ) == width )
	    {
		glCallList( displaylist );
	    }
	    else
	    {
		// cached object is for a different stroke width
		// reuse the same display list number

		cacheobj = NULL;
	    }
	}
	else
	    cacheobj = NULL;
    }

    if ( cacheobj == NULL )
    {
	PyErr_Clear();  // don't care if attribute was not found
	
	plist = PyObject_GetAttrString( pobj, "raw" );
	if ( plist == NULL || !PyList_Check( plist ) )
	{
	    Py_XDECREF( cacheobj );
	    Py_XDECREF( plist );
	    PyErr_SetString( DrawError, "bad path object" );
	    return NULL;
	}

	if ( displaylist == -1 )
	    displaylist = glGenLists( 1 );
	
	PyObject_SetAttrString( pobj, "_widestroke_list", Py_BuildValue( "id", displaylist, width ) );
	glNewList( displaylist, GL_COMPILE_AND_EXECUTE );
	
	// first, convert the path to a list of points and segments
	
	size = PyList_Size( plist );
	
	for ( i = 0; i < size; ++i )
	{
	    item = PyList_GetItem( plist, i );
	    
	    switch( PyInt_AsLong( PyList_GetItem( item, 0 ) ) )
	    {
		case S_CLOSE:
		    if ( fabs(cx-sx) > EPSILON || fabs(cy-sy) > EPSILON )
		    {
			wide_line_segment( width, cx, cy, sx, sy, queue[(qpos+1)%3], queue[qpos] );
			
			if ( drawn )
			    wide_join( queue[(qpos+2)%3], queue[(qpos+1)%3] );
			else
			    memcpy( start, queue[(qpos+1)%3], 4 * sizeof( double ) );
			qpos = (qpos+1) % 3;
		    }

		    if ( drawn )
			wide_join( queue[(qpos+2)%3], start );
		    
		    cset = 0;
		    break;
		    
		case S_MOVE:
		    sx = cx = PyFloat_AsDouble( PyList_GetItem( item, 1 ) );
		    sy = cy = PyFloat_AsDouble( PyList_GetItem( item, 2 ) );
		    
		    cset = 1;
		    drawn = 0;
		    break;
		    
		case S_LINE:
		    tx = PyFloat_AsDouble( PyList_GetItem( item, 1 ) );
		    ty = PyFloat_AsDouble( PyList_GetItem( item, 2 ) );
		    if ( fabs(tx-cx) < EPSILON && fabs(ty-cy) < EPSILON )
			break;

		    wide_line_segment( width, cx, cy, tx, ty, queue[(qpos+1)%3], queue[qpos] );

		    if ( drawn )
			wide_join( queue[(qpos+2)%3], queue[(qpos+1)%3] );
		    else
		    {
			memcpy( start, queue[(qpos+1)%3], 4 * sizeof( double ) );
			drawn = 1;
		    }
		    qpos = (qpos+1) % 3;
		    
		    
		    cx = tx;
		    cy = ty;
		
		    break;

		case S_CURVE:
		    c[0] = cx;
		    c[1] = cy;
		    for ( j = 0; j < 6; ++j )
			c[j+2] = PyFloat_AsDouble( PyList_GetItem( item, j+1 ) );
		    cx = c[6];
		    cy = c[7];

		    wide_curve_segment( width, 4, c, queue[(qpos+1)%3], queue[qpos] );
		
		    if ( drawn )
			wide_join( queue[(qpos+2)%3], queue[(qpos+1)%3] );
		    else
		    {
			memcpy( start, queue[(qpos+1)%3], 4 * sizeof( double ) );
			drawn = 1;
		    }
		    qpos = (qpos+1) % 3;
		    
		    break;

		case S_QCURVE:
		    c[0] = cx;
		    c[1] = cy;
		    for ( j = 0; j < 4; ++j )
			c[j+2] = PyFloat_AsDouble( PyList_GetItem( item, j+1 ) );
		    cx = c[4];
		    cy = c[5];

		    wide_curve_segment( width, 3, c, queue[(qpos+1)%3], queue[qpos] );
		
		    if ( drawn )
			wide_join( queue[(qpos+2)%3], queue[(qpos+1)%3] );
		    else
		    {
			memcpy( start, queue[(qpos+1)%3], 4 * sizeof( double ) );
			drawn = 1;
		    }
		    qpos = (qpos+1) % 3;
		    
		    break;
	    }
	}


	glEndList();
    }

    Py_XDECREF( plist );
    Py_XDECREF( cacheobj );

    Py_INCREF( Py_None );
    return Py_None;
}
예제 #23
0
/**
 *******************************************************************************************************
 * Callback for as_info_foreach().
 *
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param node                  The current as_node object for which the
 *                              callback is fired by c client.
 * @param req                   The info request string.
 * @param res                   The info response string for current node.
 * @pram udata                  The callback udata containing the host_lookup
 *                              array and the return zval to be populated with
 *                              an entry for current node's info response with
 *                              the node's ID as the key.
 *
 * Returns true if callback is successful, Otherwise false.
 *******************************************************************************************************
 */
static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata)
{
	PyObject * py_err = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_out = NULL;
	foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata;
	as_address* addr = NULL;

	// Need to make sure we have the GIL since we're back in python land now
	PyGILState_STATE gil_state = PyGILState_Ensure();

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

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

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

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

	if (udata_ptr->host_lookup_p) {
		PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p;
			if (py_hosts && PyList_Check(py_hosts)) {
				addr = as_node_get_address((as_node *)node);
				int size = (int) PyList_Size(py_hosts);
				for (int i = 0; i < size; i++) {
					char * host_addr = NULL;
					int port = -1;
					PyObject * py_host = PyList_GetItem(py_hosts, i);
					if (PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2) {
						PyObject * py_addr = PyTuple_GetItem(py_host,0);
						PyObject * py_port = PyTuple_GetItem(py_host,1);
						if (PyUnicode_Check(py_addr)) {
							py_ustr = PyUnicode_AsUTF8String(py_addr);
							host_addr = PyBytes_AsString(py_ustr);
						} else if (PyString_Check(py_addr)) {
							host_addr = PyString_AsString(py_addr);
						} else {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect");
							if (py_res) {
								Py_DECREF(py_res);
							}
							PyGILState_Release(gil_state);
							return false;
						}
						if (PyInt_Check(py_port)) {
							port = (uint16_t) PyInt_AsLong(py_port);
						}
						else if (PyLong_Check(py_port)) {
							port = (uint16_t) PyLong_AsLong(py_port);
						} else {
							break;
						}
						char ip_port[IP_PORT_MAX_LEN];
						// If the address is longer than the max length of an ipv6 address, raise an error and exit
						if (strnlen(host_addr, INET6_ADDRSTRLEN) >= INET6_ADDRSTRLEN) {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is too long");
							if (py_res) {
								Py_DECREF(py_res);
							}
							goto CLEANUP;
						}
						sprintf(ip_port, "%s:%d", host_addr, port);
						if ( !strcmp(ip_port, addr->name) ) {
							PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
							PyDict_SetItemString(py_nodes, node->name, py_res);
						} else {
							sprintf(ip_port, "[%s]:%d", host_addr, port);
							if ( !strcmp(ip_port, addr->name) ) {
								PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
								PyDict_SetItemString(py_nodes, node->name, py_res);
							}
						}
					}

					if (py_ustr) {
						Py_DECREF(py_ustr);
						py_ustr = NULL;
					}
				}
			} else if (!PyList_Check(py_hosts)) {
				as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Hosts should be specified in a list.");
				goto CLEANUP;
			}
	} else {
		PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
		PyDict_SetItemString(py_nodes, node->name, py_res);
	}

	Py_DECREF(py_res);

CLEANUP:
	if (py_ustr) {
		Py_DECREF(py_ustr);
	}
	if (udata_ptr->error.code != AEROSPIKE_OK) {
		PyObject * py_err = NULL;
		error_to_pyobject( &udata_ptr->error, &py_err);
		PyObject *exception_type = raise_exception(&udata_ptr->error);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		PyGILState_Release(gil_state);
		return NULL;
	}
	if (err->code != AEROSPIKE_OK) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		PyGILState_Release(gil_state);
		return NULL;
	}

	PyGILState_Release(gil_state);
	return true;
}
예제 #24
0
파일: NumberVar.c 프로젝트: 15580056814/hue
//-----------------------------------------------------------------------------
// NumberVar_GetFormatAndTextFromDecimal()
//   Return the number format and text to use for the Decimal object.
//-----------------------------------------------------------------------------
static int NumberVar_GetFormatAndTextFromDecimal(
    PyObject *tupleValue,               // decimal as_tuple() value
    PyObject **textObj,                 // text string for conversion
    PyObject **formatObj)               // format for conversion
{
    long numDigits, scale, i, sign, length, digit;
    char *textValue, *format, *textPtr, *formatPtr;
    PyObject *digits;

    // acquire basic information from the value tuple
    sign = PyInt_AsLong(PyTuple_GET_ITEM(tupleValue, 0));
    if (PyErr_Occurred())
        return -1;
    digits = PyTuple_GET_ITEM(tupleValue, 1);
    scale = PyInt_AsLong(PyTuple_GET_ITEM(tupleValue, 2));
    if (PyErr_Occurred())
        return -1;
    numDigits = PyTuple_GET_SIZE(digits);

    // allocate memory for the string and format to use in conversion
    length = numDigits + abs(scale) + 3;
    textValue = textPtr = PyMem_Malloc(length);
    if (!textValue) {
        PyErr_NoMemory();
        return -1;
    }
    format = formatPtr = PyMem_Malloc(length);
    if (!format) {
        PyMem_Free(textValue);
        PyErr_NoMemory();
        return -1;
    }

    // populate the string and format
    if (sign)
        *textPtr++ = '-';
    for (i = 0; i < numDigits + scale; i++) {
        *formatPtr++ = '9';
        if (i < numDigits) {
            digit = PyInt_AsLong(PyTuple_GetItem(digits, i));
            if (PyErr_Occurred()) {
                PyMem_Free(textValue);
                return -1;
            }
        }
        else digit = 0;
        *textPtr++ = '0' + (char) digit;
    }
    if (scale < 0) {
        *formatPtr++ = 'D';
        *textPtr++ = '.';
        for (i = scale; i < 0; i++) {
            *formatPtr++ = '9';
            if (numDigits + i < 0)
                digit = 0;
            else {
                digit = PyInt_AsLong(PyTuple_GetItem(digits, numDigits + i));
                if (PyErr_Occurred()) {
                    PyMem_Free(textValue);
                    return -1;
                }
            }
            *textPtr++ = '0' + (char) digit;
        }
    }
    *formatPtr = '\0';
    *textPtr = '\0';
    *textObj = cxString_FromAscii(textValue);
    PyMem_Free(textValue);
    if (!*textObj) {
        PyMem_Free(format);
        return -1;
    }
    *formatObj = cxString_FromAscii(format);
    PyMem_Free(format);
    if (!*formatObj) {
        Py_DECREF(*textObj);
        return -1;
    }

    return 0;
}
예제 #25
0
static PyObject *
CalcVector(PyRPosObject *self, PyObject *args, PyObject *kwds)
{
  PyObject *location=NULL,*list=NULL, *timetuple=NULL;
  double lat=0,lon=0,mag, azm;
  double clat, clon;
  char *radarcode;
  int stid;
  struct RadarNetwork *network;
  struct Radar *radar;
  struct RadarSite *site;
  static char *kwlist[] = {"mag","azm","location","radarcode","radarid",NULL};
  char *envstr=NULL;
  FILE *fp;
  int yr,mo,dy,hr,mt;
  double sc;
  yr=2008;
  mo=7;
  dy=12;
  hr=12;
  mt=0;
  sc=0; 

  radarcode="kod";
  stid=-1;

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "dd|Osi", kwlist, 
                                      &mag,&azm,&location,&radarcode,&stid))
     return NULL; 

  if ( timetuple != NULL) {
    if (PyDateTime_Check(timetuple)) {	
      yr=PyDateTime_GET_YEAR(timetuple);   
      mo=PyDateTime_GET_MONTH(timetuple);  
      dy=PyDateTime_GET_DAY(timetuple);   
      hr=PyDateTime_DATE_GET_HOUR(timetuple);   
      mt=PyDateTime_DATE_GET_MINUTE(timetuple);   
      sc=PyDateTime_DATE_GET_SECOND(timetuple);   
    }
  } 

  if ( location != NULL) {
    if (PyTuple_Check(location) && PyTuple_Size(location)==2) {	
      lat=PyFloat_AS_DOUBLE(PyTuple_GetItem(location,0));
      lon=PyFloat_AS_DOUBLE(PyTuple_GetItem(location,1));
    }
  } else {
    envstr=getenv("SD_RADAR");
    if (envstr==NULL) {
      fprintf(stderr,"Environment variable 'SD_RADAR' must be defined.\n");
      exit(-1);
    }

    fp=fopen(envstr,"r");

    if (fp==NULL) {
      fprintf(stderr,"Could not locate radar information file.\n");
      exit(-1);
    }

    network=RadarLoad(fp);
    fclose(fp); 

    if (network==NULL) {
      fprintf(stderr,"Failed to read radar information.\n");
      exit(-1);
    }

    envstr=getenv("SD_HDWPATH");
    if (envstr==NULL) {
      fprintf(stderr,"Environment variable 'SD_HDWPATH' must be defined.\n");
      exit(-1);
    }

    RadarLoadHardware(envstr,network);

    if (stid==-1) {
      stid=RadarGetID(network,radarcode);
    } 
    radar=RadarGetRadar(network,stid);
    site=RadarYMDHMSGetSite(radar,yr,mo,dy,hr,mt,(int) sc);
    lat=site->geolat;
    lon=site->geolon;
  }
  RPosCalcVector(lat,lon,mag,azm,&clat,&clon);
  list = PyList_New(0);
  PyList_Append(list,Py_BuildValue("d",clat));
  PyList_Append(list,Py_BuildValue("d",clon));

  return list;  

}
예제 #26
0
static bool
pyobj2doc(PyObject *object, rapidjson::Document& doc)
{
    if (PyBool_Check(object)) {
        if (Py_True == object) {
	        doc.SetBool(true);
        }
        else {
	        doc.SetBool(false);
        }
    }
    else if (Py_None == object) {
        doc.SetNull();
    }
    else if (PyFloat_Check(object)) {
        doc.SetDouble(PyFloat_AsDouble(object));
    }
    else if (PyInt_Check(object)) {
        doc.SetInt64(PyLong_AsLong(object));
    }
    else if (PyString_Check(object)) {
        doc.SetString(PyString_AsString(object), PyString_GET_SIZE(object));
    }
    else if (PyUnicode_Check(object)) {
        PyObject *utf8_item;
        utf8_item = PyUnicode_AsUTF8String(object);
        if (!utf8_item) {
            PyErr_SetString(PyExc_RuntimeError, "codec error.");
            return false;
        }
#ifdef PY3
        doc.SetString(PyBytes_AsString(utf8_item), PyBytes_GET_SIZE(utf8_item), doc.GetAllocator());
#else
        doc.SetString(PyString_AsString(utf8_item), PyString_GET_SIZE(utf8_item), doc.GetAllocator());
#endif
        Py_XDECREF(utf8_item);
    }
    else if (PyTuple_Check(object)) {
        int len = PyTuple_Size(object), i;
        doc.SetArray();
        rapidjson::Value _v;
        for (i = 0; i < len; ++i) {
            PyObject *elm = PyTuple_GetItem(object, i);
            if (false == pyobj2doc(elm, _v, doc)) {
                return false;
            }
            doc.PushBack(_v, doc.GetAllocator());
        }
    }
    else if (PyList_Check(object)) {
        int len = PyList_Size(object), i;
        doc.SetArray();
        rapidjson::Value _v;
        for (i = 0; i < len; ++i) {
            PyObject *elm = PyList_GetItem(object, i);
            if (false == pyobj2doc(elm, _v, doc)) {
                return false;
            }
            doc.PushBack(_v, doc.GetAllocator());
        }
    }
    else if (PyDict_Check(object)) {
        doc.SetObject();
        PyObject *key, *value;
        Py_ssize_t pos = 0;
        while (PyDict_Next(object, &pos, &key, &value)) {
            if (false == pyobj2doc_pair(key, value, doc)) {
                return false;
            }
        }
    }
    else {
        PyErr_SetString(PyExc_RuntimeError, "invalid python object");
        return false;
    }

    return true;
}
예제 #27
0
파일: row.c 프로젝트: corona10/pyston
PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
    Py_ssize_t _idx;
    char* key;
    int nitems, i;
    char* compare_key;

    char* p1;
    char* p2;

    PyObject* item;

    if (PyInt_Check(idx)) {
        _idx = PyInt_AsLong(idx);
        if (_idx < 0)
           _idx += PyTuple_GET_SIZE(self->data);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyLong_Check(idx)) {
        _idx = PyNumber_AsSsize_t(idx, PyExc_IndexError);
        if (_idx == -1 && PyErr_Occurred())
            return NULL;
        if (_idx < 0)
           _idx += PyTuple_GET_SIZE(self->data);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyString_Check(idx)) {
        key = PyString_AsString(idx);

        nitems = PyTuple_Size(self->description);

        for (i = 0; i < nitems; i++) {
            compare_key = PyString_AsString(PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0));
            if (!compare_key) {
                return NULL;
            }

            p1 = key;
            p2 = compare_key;

            while (1) {
                if ((*p1 == (char)0) || (*p2 == (char)0)) {
                    break;
                }

                if ((*p1 | 0x20) != (*p2 | 0x20)) {
                    break;
                }

                p1++;
                p2++;
            }

            if ((*p1 == (char)0) && (*p2 == (char)0)) {
                /* found item */
                item = PyTuple_GetItem(self->data, i);
                Py_INCREF(item);
                return item;
            }

        }

        PyErr_SetString(PyExc_IndexError, "No item with that key");
        return NULL;
    } else if (PySlice_Check(idx)) {
        PyErr_SetString(PyExc_ValueError, "slices not implemented, yet");
        return NULL;
    } else {
        PyErr_SetString(PyExc_IndexError, "Index must be int or string");
        return NULL;
    }
}
예제 #28
0
static PyObject *LuaCall(LuaStateObject *state, PyObject *args)
{
    PyObject *ret = NULL;
    PyObject *arg;
    int nargs, rc, i;

    assert(PyTuple_Check(args));

    /* Note: Convert tuple length from 64-bit to 32-bit */
    nargs = (int)PyTuple_Size(args);
    for (i = 0; i != nargs; i++) {
        arg = PyTuple_GetItem(args, i);
        if (arg == NULL) {
            PyErr_Format(PyExc_TypeError,
                         "failed to get tuple item #%d", i);
            lua_settop(state->LuaState, 0);
            return NULL;
        }
        rc = e_py_convert(state->LuaState, arg, 0);
        if (!rc) {
            PyErr_Format(PyExc_TypeError,
                         "failed to convert argument #%d", i);
            lua_settop(state->LuaState, 0);
            return NULL;
        }
    }

    if (lua_pcall(state->LuaState, nargs, LUA_MULTRET, 0) != 0) {
        PyErr_Format(PyExc_Exception,
                     "error: %s", lua_tostring(state->LuaState, -1));
        return NULL;
    }

    nargs = lua_gettop(state->LuaState);
    if (nargs == 1) {
        ret = LuaConvert(state, 1);
        if (!ret) {
            PyErr_SetString(PyExc_TypeError,
                            "failed to convert return");
            lua_settop(state->LuaState, 0);
            return NULL;
        }
    } else if (nargs > 1) {
        ret = PyTuple_New(nargs);
        if (!ret) {
            PyErr_SetString(PyExc_RuntimeError,
                            "failed to create return tuple");
            lua_settop(state->LuaState, 0);
            return NULL;
        }
        for (i = 0; i != nargs; i++) {
            arg = LuaConvert(state, i+1);
            if (!arg) {
                PyErr_Format(PyExc_TypeError,
                             "failed to convert return #%d", i);
                lua_settop(state->LuaState, 0);
                Py_DECREF(ret);
                return NULL;
            }
            PyTuple_SetItem(ret, i, arg);
        }
    } else {
        Py_INCREF(Py_None);
        ret = Py_None;
    }

    lua_settop(state->LuaState, 0);

    return ret;
}
예제 #29
0
파일: gevent.c 프로젝트: sashka/uwsgi
void gevent_loop() {

	struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;

	if (uwsgi.async < 2) {
		uwsgi_log("the gevent loop engine requires async mode (--async <n>)\n");
		exit(1);
	}


	PyObject *gevent_dict = get_uwsgi_pydict("gevent");
	if (!gevent_dict) uwsgi_pyexit;

	PyObject *gevent_version = PyDict_GetItemString(gevent_dict, "version_info");
	if (!gevent_version) uwsgi_pyexit;

	if (PyInt_AsLong(PyTuple_GetItem(gevent_version, 0)) < 1) {
		uwsgi_log("uWSGI requires at least gevent 1.x version\n");
		exit(1);
	}

	ugevent.spawn = PyDict_GetItemString(gevent_dict, "spawn");
	if (!ugevent.spawn) uwsgi_pyexit;

	ugevent.greenlet_switch = PyDict_GetItemString(gevent_dict, "sleep");
	if (!ugevent.greenlet_switch) uwsgi_pyexit;

	ugevent.greenlet_switch_args = PyTuple_New(0);
	Py_INCREF(ugevent.greenlet_switch_args);
	

	PyObject *gevent_get_hub = PyDict_GetItemString(gevent_dict, "get_hub");

	ugevent.hub = python_call(gevent_get_hub, PyTuple_New(0), 0, NULL);
	if (!ugevent.hub) uwsgi_pyexit;

	ugevent.get_current = PyDict_GetItemString(gevent_dict, "getcurrent");
	if (!ugevent.get_current) uwsgi_pyexit;

	ugevent.get_current_args = PyTuple_New(0);
	Py_INCREF(ugevent.get_current_args);
	

	ugevent.hub_loop = PyObject_GetAttrString(ugevent.hub, "loop");
	if (!ugevent.hub_loop) uwsgi_pyexit;

	// this is the watcher for server socket
	PyObject *watcher = PyObject_CallMethod(ugevent.hub_loop, "io", "ii", uwsgi_sock->fd, 1);
	if (!watcher) uwsgi_pyexit;

	// main greenlet waiting for connection
	PyObject *uwsgi_gevent_main = PyCFunction_New(uwsgi_gevent_main_def, NULL);
	Py_INCREF(uwsgi_gevent_main);

	// greenlet to run at each request
	PyObject *uwsgi_request_greenlet = PyCFunction_New(uwsgi_gevent_request_def, NULL);
	Py_INCREF(uwsgi_request_greenlet);

	// pre-fill the greenlet args
	ugevent.greenlet_args = PyTuple_New(2);
	PyTuple_SetItem(ugevent.greenlet_args, 0, uwsgi_request_greenlet);

	if (uwsgi.signal_socket > -1) {
		// and these are the watcher for signal sockets

		PyObject *signal_watcher = PyObject_CallMethod(ugevent.hub_loop, "io", "ii", uwsgi.signal_socket, 1);
        	if (!signal_watcher) uwsgi_pyexit;

		PyObject *my_signal_watcher = PyObject_CallMethod(ugevent.hub_loop, "io", "ii", uwsgi.my_signal_socket, 1);
        	if (!my_signal_watcher) uwsgi_pyexit;

		PyObject *uwsgi_greenlet_signal = PyCFunction_New(uwsgi_gevent_signal_def, NULL);
        	Py_INCREF(uwsgi_greenlet_signal);

		PyObject *uwsgi_greenlet_my_signal = PyCFunction_New(uwsgi_gevent_my_signal_def, NULL);
        	Py_INCREF(uwsgi_greenlet_my_signal);

		PyObject *uwsgi_greenlet_signal_handler = PyCFunction_New(uwsgi_gevent_signal_handler_def, NULL);
        	Py_INCREF(uwsgi_greenlet_signal_handler);

		ugevent.signal_args = PyTuple_New(2);
		PyTuple_SetItem(ugevent.signal_args, 0, uwsgi_greenlet_signal_handler);

		// start the two signal watchers
		if (!PyObject_CallMethod(signal_watcher, "start", "O", uwsgi_greenlet_signal)) uwsgi_pyexit;
		if (!PyObject_CallMethod(my_signal_watcher, "start", "O", uwsgi_greenlet_my_signal)) uwsgi_pyexit;

	}
	
	// start the main greenlet
	PyObject_CallMethod(watcher, "start", "O", uwsgi_gevent_main);

	if (!PyObject_CallMethod(ugevent.hub, "join", NULL)) {
		PyErr_Print();
	}

	uwsgi_log("the gevent Hub is no more :(\n");

}
예제 #30
0
/**
 ***********************************************************************
 *
 * Callback method, invoked by aerospike_batch_get_bins
 *
 * *********************************************************************
 **/
static bool batch_select_cb(const as_batch_read* results, uint32_t n, void* udata)
{
    // Typecast udata back to PyObject
    LocalData *data = (LocalData *) udata;
    PyObject * py_recs = data->py_recs;

    // Initialize error object
    as_error err;

    as_error_init(&err);

    // Loop over results array
    for ( uint32_t i =0; i < n; i++ ) {

        PyObject * rec = NULL;
        PyObject * py_rec = NULL;
        PyObject * p_key = NULL;
        py_rec = PyTuple_New(3);
        p_key = PyTuple_New(4);

        if ( results[i].key->ns && strlen(results[i].key->ns) > 0 ) {
            PyTuple_SetItem(p_key, 0, PyString_FromString(results[i].key->ns));
        }

        if ( results[i].key->set && strlen(results[i].key->set) > 0 ) {
            PyTuple_SetItem(p_key, 1, PyString_FromString(results[i].key->set));
        }

        if(results[i].key->valuep) {
            switch(((as_val*)(results[i].key->valuep))->type) {
            case AS_INTEGER:
                PyTuple_SetItem(p_key, 2, PyInt_FromLong((long)results[i].key->value.integer.value));
                break;

            case AS_STRING:
                PyTuple_SetItem(p_key, 2, PyString_FromString((const char *)results[i].key->value.string.value));
                break;

            default:
                break;
            }
        } else {
            Py_INCREF(Py_None);
            PyTuple_SetItem(p_key, 2, Py_None);
        }

        if (results[i].key->digest.init) {
            PyTuple_SetItem(p_key, 3, PyByteArray_FromStringAndSize((char *) results[i].key->digest.value, AS_DIGEST_VALUE_SIZE));
        }

        PyTuple_SetItem(py_rec, 0, p_key);
        // Check record status
        if ( results[i].result == AEROSPIKE_OK ) {

            record_to_pyobject(data->client, &err, &results[i].record, results[i].key, &rec);
            PyObject *py_obj = PyTuple_GetItem(rec, 1);
            Py_INCREF(py_obj);
            PyTuple_SetItem(py_rec, 1, py_obj);
            py_obj = PyTuple_GetItem(rec, 2);
            Py_INCREF(py_obj);
            PyTuple_SetItem(py_rec, 2, py_obj);
            // Set return value in return Dict
            if ( PyList_SetItem( py_recs, i, py_rec ) ) {
                return false;
            }
            Py_DECREF(rec);
        } else if( results[i].result == AEROSPIKE_ERR_RECORD_NOT_FOUND ) {

            Py_INCREF(Py_None);
            PyTuple_SetItem(py_rec, 1, Py_None);
            Py_INCREF(Py_None);
            PyTuple_SetItem(py_rec, 2, Py_None);
            if ( PyList_SetItem( py_recs, i, py_rec)) {
                return false;
            }
        }
    }
    return true;
}