static PyObject *
subprocess_fork_exec(PyObject* self, PyObject *args)
{
    PyObject *gc_module = NULL;
    PyObject *executable_list, *py_fds_to_keep;
    PyObject *env_list, *preexec_fn;
    PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
    PyObject *preexec_fn_args_tuple = NULL;
    int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
    int errpipe_read, errpipe_write, close_fds, restore_signals;
    int call_setsid;
    PyObject *cwd_obj, *cwd_obj2;
    const char *cwd;
    pid_t pid;
    int need_to_reenable_gc = 0;
    char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
    Py_ssize_t arg_num;
#ifdef WITH_THREAD
    int import_lock_held = 0;
#endif

    if (!PyArg_ParseTuple(
            args, "OOpOOOiiiiiiiiiiO:fork_exec",
            &process_args, &executable_list, &close_fds, &py_fds_to_keep,
            &cwd_obj, &env_list,
            &p2cread, &p2cwrite, &c2pread, &c2pwrite,
            &errread, &errwrite, &errpipe_read, &errpipe_write,
            &restore_signals, &call_setsid, &preexec_fn))
        return NULL;

    if (close_fds && errpipe_write < 3) {  /* precondition */
        PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
        return NULL;
    }
    if (PySequence_Length(py_fds_to_keep) < 0) {
        PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep");
        return NULL;
    }
    if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
        PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
        return NULL;
    }

    /* We need to call gc.disable() when we'll be calling preexec_fn */
    if (preexec_fn != Py_None) {
        PyObject *result;
        _Py_IDENTIFIER(isenabled);
        _Py_IDENTIFIER(disable);

        gc_module = PyImport_ImportModule("gc");
        if (gc_module == NULL)
            return NULL;
        result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        need_to_reenable_gc = PyObject_IsTrue(result);
        Py_DECREF(result);
        if (need_to_reenable_gc == -1) {
            Py_DECREF(gc_module);
            return NULL;
        }
        result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        Py_DECREF(result);
    }

    exec_array = _PySequence_BytesToCharpArray(executable_list);
    if (!exec_array)
        goto cleanup;

    /* Convert args and env into appropriate arguments for exec() */
    /* These conversions are done in the parent process to avoid allocating
       or freeing memory in the child process. */
    if (process_args != Py_None) {
        Py_ssize_t num_args;
        /* Equivalent to:  */
        /*  tuple(PyUnicode_FSConverter(arg) for arg in process_args)  */
        fast_args = PySequence_Fast(process_args, "argv must be a tuple");
        if (fast_args == NULL)
            goto cleanup;
        num_args = PySequence_Fast_GET_SIZE(fast_args);
        converted_args = PyTuple_New(num_args);
        if (converted_args == NULL)
            goto cleanup;
        for (arg_num = 0; arg_num < num_args; ++arg_num) {
            PyObject *borrowed_arg, *converted_arg;
            borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
            if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
                goto cleanup;
            PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
        }

        argv = _PySequence_BytesToCharpArray(converted_args);
        Py_CLEAR(converted_args);
        Py_CLEAR(fast_args);
        if (!argv)
            goto cleanup;
    }

    if (env_list != Py_None) {
        envp = _PySequence_BytesToCharpArray(env_list);
        if (!envp)
            goto cleanup;
    }

    if (preexec_fn != Py_None) {
        preexec_fn_args_tuple = PyTuple_New(0);
        if (!preexec_fn_args_tuple)
            goto cleanup;
#ifdef WITH_THREAD
        _PyImport_AcquireLock();
        import_lock_held = 1;
#endif
    }

    if (cwd_obj != Py_None) {
        if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
            goto cleanup;
        cwd = PyBytes_AsString(cwd_obj2);
    } else {
        cwd = NULL;
        cwd_obj2 = NULL;
    }

    pid = fork();
    if (pid == 0) {
        /* Child process */
        /*
         * Code from here to _exit() must only use async-signal-safe functions,
         * listed at `man 7 signal` or
         * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
         */

        if (preexec_fn != Py_None) {
            /* We'll be calling back into Python later so we need to do this.
             * This call may not be async-signal-safe but neither is calling
             * back into Python.  The user asked us to use hope as a strategy
             * to avoid deadlock... */
            PyOS_AfterFork();
        }

        child_exec(exec_array, argv, envp, cwd,
                   p2cread, p2cwrite, c2pread, c2pwrite,
                   errread, errwrite, errpipe_read, errpipe_write,
                   close_fds, restore_signals, call_setsid,
                   py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
        _exit(255);
        return NULL;  /* Dead code to avoid a potential compiler warning. */
    }
    Py_XDECREF(cwd_obj2);

    if (pid == -1) {
        /* Capture the errno exception before errno can be clobbered. */
        PyErr_SetFromErrno(PyExc_OSError);
    }
#ifdef WITH_THREAD
    if (preexec_fn != Py_None
        && _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) {
        PyErr_SetString(PyExc_RuntimeError,
                        "not holding the import lock");
        pid = -1;
    }
    import_lock_held = 0;
#endif

    /* Parent process */
    if (envp)
        _Py_FreeCharPArray(envp);
    if (argv)
        _Py_FreeCharPArray(argv);
    _Py_FreeCharPArray(exec_array);

    /* Reenable gc in the parent process (or if fork failed). */
    if (_enable_gc(need_to_reenable_gc, gc_module)) {
        pid = -1;
    }
    Py_XDECREF(preexec_fn_args_tuple);
    Py_XDECREF(gc_module);

    if (pid == -1)
        return NULL;  /* fork() failed.  Exception set earlier. */

    return PyLong_FromPid(pid);

cleanup:
#ifdef WITH_THREAD
    if (import_lock_held)
        _PyImport_ReleaseLock();
#endif
    if (envp)
        _Py_FreeCharPArray(envp);
    if (argv)
        _Py_FreeCharPArray(argv);
    if (exec_array)
        _Py_FreeCharPArray(exec_array);
    Py_XDECREF(converted_args);
    Py_XDECREF(fast_args);
    Py_XDECREF(preexec_fn_args_tuple);
    _enable_gc(need_to_reenable_gc, gc_module);
    Py_XDECREF(gc_module);
    return NULL;
}
Exemple #2
0
PyObject *
libxml_xmlXPathObjectPtrWrap(xmlXPathObjectPtr obj)
{
    PyObject *ret;

#ifdef DEBUG
    printf("libxml_xmlXPathObjectPtrWrap: ctxt = %p\n", obj);
#endif
    if (obj == NULL) {
        Py_INCREF(Py_None);
        return (Py_None);
    }
    switch (obj->type) {
        case XPATH_XSLT_TREE: {
            if ((obj->nodesetval == NULL) ||
		(obj->nodesetval->nodeNr == 0) ||
		(obj->nodesetval->nodeTab == NULL)) {
                ret = PyList_New(0);
	    } else {
		int i, len = 0;
		xmlNodePtr node;

		node = obj->nodesetval->nodeTab[0]->children;
		while (node != NULL) {
		    len++;
		    node = node->next;
		}
		ret = PyList_New(len);
		node = obj->nodesetval->nodeTab[0]->children;
		for (i = 0;i < len;i++) {
                    PyList_SetItem(ret, i, libxml_xmlNodePtrWrap(node));
		    node = node->next;
		}
	    }
	    /*
	     * Return now, do not free the object passed down
	     */
	    return (ret);
	}
        case XPATH_NODESET:
            if ((obj->nodesetval == NULL)
                || (obj->nodesetval->nodeNr == 0)) {
                ret = PyList_New(0);
	    } else {
                int i;
                xmlNodePtr node;

                ret = PyList_New(obj->nodesetval->nodeNr);
                for (i = 0; i < obj->nodesetval->nodeNr; i++) {
                    node = obj->nodesetval->nodeTab[i];
                    /* TODO: try to cast directly to the proper node type */
                    PyList_SetItem(ret, i, libxml_xmlNodePtrWrap(node));
                }
            }
            break;
        case XPATH_BOOLEAN:
            ret = PyInt_FromLong((long) obj->boolval);
            break;
        case XPATH_NUMBER:
            ret = PyFloat_FromDouble(obj->floatval);
            break;
        case XPATH_STRING:
            ret = PyString_FromString((char *) obj->stringval);
            break;
        case XPATH_POINT:
        {
            PyObject *node;
            PyObject *indexIntoNode;
            PyObject *tuple;

            node = libxml_xmlNodePtrWrap(obj->user);
            indexIntoNode = PyInt_FromLong((long) obj->index);

            tuple = PyTuple_New(2);
            PyTuple_SetItem(tuple, 0, node);
            PyTuple_SetItem(tuple, 1, indexIntoNode);

            ret = tuple;
            break;
        }
        case XPATH_RANGE:
        {
            unsigned short bCollapsedRange;

            bCollapsedRange = ( (obj->user2 == NULL) ||
		                ((obj->user2 == obj->user) && (obj->index == obj->index2)) );
            if ( bCollapsedRange ) {
                PyObject *node;
                PyObject *indexIntoNode;
                PyObject *tuple;
                PyObject *list;

                list = PyList_New(1);

                node = libxml_xmlNodePtrWrap(obj->user);
                indexIntoNode = PyInt_FromLong((long) obj->index);

                tuple = PyTuple_New(2);
                PyTuple_SetItem(tuple, 0, node);
                PyTuple_SetItem(tuple, 1, indexIntoNode);

                PyList_SetItem(list, 0, tuple);

                ret = list;
            } else {
                PyObject *node;
                PyObject *indexIntoNode;
                PyObject *tuple;
                PyObject *list;

                list = PyList_New(2);

                node = libxml_xmlNodePtrWrap(obj->user);
                indexIntoNode = PyInt_FromLong((long) obj->index);

                tuple = PyTuple_New(2);
                PyTuple_SetItem(tuple, 0, node);
                PyTuple_SetItem(tuple, 1, indexIntoNode);

                PyList_SetItem(list, 0, tuple);

                node = libxml_xmlNodePtrWrap(obj->user2);
                indexIntoNode = PyInt_FromLong((long) obj->index2);

                tuple = PyTuple_New(2);
                PyTuple_SetItem(tuple, 0, node);
                PyTuple_SetItem(tuple, 1, indexIntoNode);

                PyList_SetItem(list, 1, tuple);

                ret = list;
            }
            break;
        }
        case XPATH_LOCATIONSET:
        {
            xmlLocationSetPtr set;

            set = obj->user;
            if ( set && set->locNr > 0 ) {
                int i;
                PyObject *list;

                list = PyList_New(set->locNr);

                for (i=0; i<set->locNr; i++) {
                    xmlXPathObjectPtr setobj;
                    PyObject *pyobj;

                    setobj = set->locTab[i]; /*xmlXPathObjectPtr setobj*/

                    pyobj = libxml_xmlXPathObjectPtrWrap(setobj);
                    /* xmlXPathFreeObject(setobj) is called */
                    set->locTab[i] = NULL;

                    PyList_SetItem(list, i, pyobj);
                }
                set->locNr = 0;
                ret = list;
            } else {
                Py_INCREF(Py_None);
                ret = Py_None;
            }
            break;
        }
        default:
#ifdef DEBUG
            printf("Unable to convert XPath object type %d\n", obj->type);
#endif
            Py_INCREF(Py_None);
            ret = Py_None;
    }
    xmlXPathFreeObject(obj);
    return (ret);
}
Exemple #3
0
static PyObject *__pyx_f_6ssdeep_6ssdeep_hash_bytes(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_buf = 0;
  char (*__pyx_v_utext);
  PyObject *__pyx_v_res;
  PyObject *__pyx_r;
  char (*__pyx_1);
  PyObject *__pyx_2 = 0;
  PyObject *__pyx_3 = 0;
  PyObject *__pyx_4 = 0;
  int __pyx_5;
  PyObject *__pyx_6 = 0;
  static char *__pyx_argnames[] = {"buf",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_buf)) return 0;
  Py_INCREF(__pyx_v_self);
  Py_INCREF(__pyx_v_buf);
  __pyx_v_res = Py_None; Py_INCREF(__pyx_v_res);

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":42 */
  __pyx_1 = PyString_AsString(__pyx_v_buf); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;}
  __pyx_v_utext = __pyx_1;

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":43 */
  __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_len); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_INCREF(__pyx_v_buf);
  PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_buf);
  __pyx_4 = PyObject_CallObject(__pyx_2, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  __pyx_5 = PyInt_AsLong(__pyx_4); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_DECREF(__pyx_4); __pyx_4 = 0;
  __pyx_2 = PyString_FromString(fuzzy_hash_data(__pyx_v_utext,__pyx_5)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_DECREF(__pyx_v_res);
  __pyx_v_res = __pyx_2;
  __pyx_2 = 0;

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":44 */
  __pyx_5 = PySequence_Contains(__pyx_v_res, __pyx_k5p); if (__pyx_5 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
  if (__pyx_5) {

    /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":45 */
    __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n_SsdeepException); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    __pyx_4 = __Pyx_GetName(__pyx_b, __pyx_n_replace); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    __pyx_2 = PyTuple_New(2); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    Py_INCREF(__pyx_k6p);
    PyTuple_SET_ITEM(__pyx_2, 0, __pyx_k6p);
    Py_INCREF(__pyx_k7p);
    PyTuple_SET_ITEM(__pyx_2, 1, __pyx_k7p);
    __pyx_6 = PyObject_CallObject(__pyx_4, __pyx_2); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    Py_DECREF(__pyx_2); __pyx_2 = 0;
    __Pyx_Raise(__pyx_3, __pyx_v_res, __pyx_6);
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    goto __pyx_L2;
  }
  /*else*/ {
    Py_INCREF(__pyx_v_res);
    __pyx_r = __pyx_v_res;
    goto __pyx_L0;
  }
  __pyx_L2:;

  __pyx_r = Py_None; Py_INCREF(__pyx_r);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_3);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_6);
  __Pyx_AddTraceback("ssdeep.ssdeep.hash_bytes");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_res);
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_buf);
  return __pyx_r;
}
Exemple #4
0
/**
 *******************************************************************************************************
 * Callback for as_info_foreach().
 *
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param node                  The current as_node object for which the
 *                              callback is fired by c client.
 * @param req                   The info request string.
 * @param res                   The info response string for current node.
 * @pram udata                  The callback udata containing the host_lookup
 *                              array and the return zval to be populated with
 *                              an entry for current node's info response with
 *                              the node's ID as the key.
 *
 * Returns true if callback is successful, Otherwise false.
 *******************************************************************************************************
 */
static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata)
{
	PyObject * py_err = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_out = NULL;
	foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata;
	struct sockaddr_in* addr = NULL;


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

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

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

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

	if(udata_ptr->host_lookup_p) {
		PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p;
			if ( py_hosts && PyList_Check(py_hosts) ) {
				addr = as_node_get_address((as_node *)node);
				int size = (int) PyList_Size(py_hosts);
				for ( int i = 0; i < size && i < AS_CONFIG_HOSTS_SIZE; i++ ) {
					char * host_addr = NULL;
					int port = -1;
					PyObject * py_host = PyList_GetItem(py_hosts, i);
					if ( PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2 ) {
						PyObject * py_addr = PyTuple_GetItem(py_host,0);
						PyObject * py_port = PyTuple_GetItem(py_host,1);
						if (PyUnicode_Check(py_addr)) {
							py_ustr = PyUnicode_AsUTF8String(py_addr);
							host_addr = PyStr_AsString(py_ustr);
						} else if ( PyStr_Check(py_addr) ) {
							host_addr = PyStr_AsString(py_addr);
						} else {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect");
							if (py_res) {
								Py_DECREF(py_res);
							}
							return false;
						}
						if ( PyInt_Check(py_port) ) {
							port = (uint16_t) PyInt_AsLong(py_port);
						}
						else if ( PyLong_Check(py_port) ) {
							port = (uint16_t) PyLong_AsLong(py_port);
						} else {
							break;
						}
						char ip_port[IP_PORT_MAX_LEN];
						inet_ntop(addr->sin_family, &(addr->sin_addr), ip_port, INET_ADDRSTRLEN);
						if( (!strcmp(host_addr,ip_port)) && (port
												== ntohs(addr->sin_port))) {
							PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
							PyDict_SetItemString(py_nodes, node->name, py_res);
						}	
					}
				}
			} else if ( !PyList_Check( py_hosts )){
				as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Hosts should be specified in a list.");
				goto CLEANUP;
			}
	} else {
		PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
		PyDict_SetItemString(py_nodes, node->name, py_res);
	}
	Py_DECREF(py_res);
CLEANUP:
	if ( udata_ptr->error.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject( &udata_ptr->error, &py_err);
		PyObject *exception_type = raise_exception(&udata_ptr->error);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return true;
}
static PyObject *PythonQtInstanceWrapper_richcompare(PythonQtInstanceWrapper* wrapper, PyObject* other, int code)
{
  bool validPtrs = false;
  bool areSamePtrs = false;
  if (PyObject_TypeCheck((PyObject*)wrapper, &PythonQtInstanceWrapper_Type)) {
    if (PyObject_TypeCheck(other, &PythonQtInstanceWrapper_Type)) {
      validPtrs = true;
      PythonQtInstanceWrapper* w1 = wrapper;
      PythonQtInstanceWrapper* w2 = (PythonQtInstanceWrapper*)other;
      // check pointers directly
      if (w1->_wrappedPtr != NULL) {
        if (w1->_wrappedPtr == w2->_wrappedPtr) {
          areSamePtrs = true;
        }
      } else if (w1->_obj == w2->_obj) {
        areSamePtrs = true;
      }
    } else if (other == Py_None) {
      validPtrs = true;
      if (wrapper->_obj || wrapper->_wrappedPtr) {
        areSamePtrs = false;
      } else {
        areSamePtrs = true;
      }
    }
  }

  if ((wrapper->classInfo()->typeSlots() & PythonQt::Type_RichCompare) == 0) {
    // shortcut if richcompare is not supported:
    if (validPtrs && code == Py_EQ) {
      return PythonQtConv::GetPyBool(areSamePtrs);
    } else if (validPtrs && code == Py_NE) {
      return PythonQtConv::GetPyBool(!areSamePtrs);
    }
    Py_INCREF(Py_NotImplemented);
    return Py_NotImplemented;
  }

  QByteArray memberName;
  switch (code) {
  case Py_LT:
    {
      static QByteArray name = "__lt__";
      memberName = name;
    }
    break;

  case Py_LE:
    {
      static QByteArray name = "__le__";
      memberName = name;
    }
    break;

  case Py_EQ:
    {
      static QByteArray name = "__eq__";
      memberName = name;
    }
    break;

  case Py_NE:
    {
      static QByteArray name = "__ne__";
      memberName = name;
    }
    break;

  case Py_GT:
    {
      static QByteArray name = "__gt__";
      memberName = name;
    }
    break;

  case Py_GE:
    {
      static QByteArray name = "__ge__";
      memberName = name;
    }
    break;
  }

  PythonQtMemberInfo opSlot = wrapper->classInfo()->member(memberName);
  if (opSlot._type == PythonQtMemberInfo::Slot) {
    // TODO get rid of tuple
    PyObject* args = PyTuple_New(1);
    Py_INCREF(other);
    PyTuple_SET_ITEM(args, 0, other);
    PyObject* result = PythonQtSlotFunction_CallImpl(wrapper->classInfo(), wrapper->_obj, opSlot._slot, args, NULL, wrapper->_wrappedPtr);
    Py_DECREF(args);
    if (result == NULL) {
      // special handling of EQ and NE, if call fails we just return EQ == false / NE == true.
      if (code == Py_EQ) {
        PyErr_Clear();
        Py_INCREF(Py_False);
        return Py_False;
      } else if (code == Py_NE) {
        PyErr_Clear();
        Py_INCREF(Py_True);
        return Py_True;
      }
    }
    return result;
  } else {
    // not implemented, let python try something else!
    Py_INCREF(Py_NotImplemented);
    return Py_NotImplemented;
  }
}
Exemple #6
0
static PyObject *__pyx_pf_5hello_say_hello_to(PyObject *__pyx_self, PyObject *__pyx_v_name) {
  int __pyx_v_n;
  int __pyx_v_m;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  PyObject *__pyx_t_2 = NULL;
  int __pyx_lineno = 0;
  const char *__pyx_filename = NULL;
  int __pyx_clineno = 0;
  __Pyx_RefNannySetupContext("say_hello_to");
  __pyx_self = __pyx_self;

  /* "hello.pyx":2
 * def say_hello_to(name):
 *     cdef int n = 18932808299             # <<<<<<<<<<<<<<
 *     cdef int m = n*n
 *     print("Hello %s! %s" % (name,m))
 */
  __pyx_v_n = 18932808299;

  /* "hello.pyx":3
 * def say_hello_to(name):
 *     cdef int n = 18932808299
 *     cdef int m = n*n             # <<<<<<<<<<<<<<
 *     print("Hello %s! %s" % (name,m))
 */
  __pyx_v_m = (__pyx_v_n * __pyx_v_n);

  /* "hello.pyx":4
 *     cdef int n = 18932808299
 *     cdef int m = n*n
 *     print("Hello %s! %s" % (name,m))             # <<<<<<<<<<<<<<
 */
  __pyx_t_1 = PyInt_FromLong(__pyx_v_m); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_2));
  __Pyx_INCREF(__pyx_v_name);
  PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_name);
  __Pyx_GIVEREF(__pyx_v_name);
  PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1);
  __Pyx_GIVEREF(__pyx_t_1);
  __pyx_t_1 = 0;
  __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_1));
  __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0;
  if (__Pyx_PrintOne(0, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;

  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_AddTraceback("hello.say_hello_to", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}
int c_function(int *n, float **mat)
{
  PyObject *pModule  = NULL;
  PyObject *pFunc = NULL;
  PyObject *pArg = NULL;
  PyObject *pRet = NULL;
  PyObject *pName = NULL;

  size_t size = *n;
  npy_intp *dim;
  int i, j;

  dim = (npy_intp *) malloc(sizeof(npy_intp)*(size));

  for (i=0; i < size; i++) dim[i] = size;

  Py_Initialize();

  if (!Py_IsInitialized())
  {
    fprintf(stderr, "nao foi possivel inicializar o python!\n");
    return -1;
  }

  init_numpy(); 

  PyObject* pMat = PyArray_NewFromDescr(
     &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 
     2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL);

  Py_INCREF(pMat);

  pName = PyString_FromString("function");
  pModule = PyImport_Import(pName);

  pFunc = PyObject_GetAttrString(pModule, "py_function");

  if(!PyCallable_Check(pFunc))
  {
    printf("func not callable!\n");
    return -1;
  }

  pArg = PyTuple_New (2);
  PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size));
  PyTuple_SetItem(pArg, 1, pMat);

  pRet = PyObject_CallObject(pFunc, pArg);

  printf("py ret: %s\n", PyString_AsString(pRet));

  Py_DECREF (pMat);
  Py_DECREF (pName);
  Py_DECREF (pModule);
  Py_DECREF (pFunc);
  Py_DECREF (pArg);
  Py_DECREF (pRet);

  Py_Finalize();

  return 0;
}
void plPythonSDLModifier::SetItemIdx(const char* key, int idx, PyObject* value, hsBool sendImmediate)
{
    if (!value)
    {
        PyLoggedAssert(0, "[SDL] Trying to set a value to nil");
        return;
    }

    SDLMap::iterator it = fMap.find(key);

    if (it == fMap.end())
    {
        PyLoggedAssert(0, "[SDL] Tried to set a nonexistent SDL value");
        return;
    }

    PyObject* pyTuple = it->second.obj;
    int size = it->second.size;

    if (size != 0 && idx >= size)
    {
        PyLoggedAssert(0, "[SDL] Trying to resize a SDL value that can't be");
        return;
    }

    if (pyTuple && pyTuple->ob_refcnt != 1)
    {
        // others already have references to the tuple and expect it to be immutable, must make a copy
        int n = PyTuple_Size(pyTuple);
        PyObject* newTuple = PyTuple_New(n);
        for (int j = 0; j < n; j++)
        {
            PyObject* item = PyTuple_GetItem(pyTuple, j);
            Py_INCREF(item);
            PyTuple_SetItem(newTuple, j, item);
        }
        Py_DECREF(pyTuple);
        pyTuple = newTuple;
        it->second.obj = newTuple;
    }

    if (pyTuple)
    {
        if (PyTuple_Size(pyTuple) <= idx)
        {
            int oldsize = PyTuple_Size(pyTuple);
            _PyTuple_Resize(&pyTuple, idx+1);
            // initialize the tuple elements to None, because Python don't like NULLs
            int j;
            for ( j=oldsize; j<idx+1; j++ )
            {
                Py_INCREF(Py_None);
                PyTuple_SetItem(pyTuple, j, Py_None);
            }
            // _PyTuple_Resize may have changed pyTuple
            it->second.obj = pyTuple;
        }
    }
    else
    {
        int newSize = (size == 0) ? idx+1 : size;
        pyTuple = PyTuple_New(newSize);
        // initialize the tuple elements to None, because Python don't like NULLs
        int j;
        for ( j=0; j<newSize; j++ )
        {
            Py_INCREF(Py_None);
            PyTuple_SetItem(pyTuple, j, Py_None);
        }
        it->second.obj = pyTuple;
    }

    Py_XINCREF(value);  // PyTuple_SetItem doesn't increment the ref count
    PyTuple_SetItem(pyTuple, idx, value);

    IDirtySynchState(key, sendImmediate);
}
Exemple #9
0
/**
 * _pygi_argument_to_object:
 * @arg: The argument to convert to an object.
 * @type_info: Type info for @arg
 * @transfer:
 *
 * If the argument is of type array, it must be encoded in a GArray, by calling
 * _pygi_argument_to_array(). This logic can not be folded into this method
 * as determining array lengths may require access to method call arguments.
 *
 * Returns: A PyObject representing @arg
 */
PyObject *
_pygi_argument_to_object (GIArgument  *arg,
                          GITypeInfo *type_info,
                          GITransfer transfer)
{
    GITypeTag type_tag;
    PyObject *object = NULL;

    type_tag = g_type_info_get_tag (type_info);
    object = _pygi_marshal_to_py_basic_type (arg, type_tag, transfer);
    if (object)
        return object;

    switch (type_tag) {
        case GI_TYPE_TAG_VOID:
        {
            if (g_type_info_is_pointer (type_info)) {
                g_warn_if_fail (transfer == GI_TRANSFER_NOTHING);
                object = PyLong_FromVoidPtr (arg->v_pointer);
            }
            break;
        }
        case GI_TYPE_TAG_ARRAY:
        {
            /* Arrays are assumed to be packed in a GArray */
            GArray *array;
            GITypeInfo *item_type_info;
            GITypeTag item_type_tag;
            GITransfer item_transfer;
            gsize i, item_size;

            if (arg->v_pointer == NULL)
                return PyList_New (0);
            
            item_type_info = g_type_info_get_param_type (type_info, 0);
            g_assert (item_type_info != NULL);

            item_type_tag = g_type_info_get_tag (item_type_info);
            item_transfer = transfer == GI_TRANSFER_CONTAINER ? GI_TRANSFER_NOTHING : transfer;
            
            array = arg->v_pointer;
            item_size = g_array_get_element_size (array);
            
            if (G_UNLIKELY (item_size > sizeof(GIArgument))) {
                g_critical ("Stack overflow protection. "
                            "Can't copy array element into GIArgument.");
                return PyList_New (0);
            }

            if (item_type_tag == GI_TYPE_TAG_UINT8) {
                /* Return as a byte array */
                object = PYGLIB_PyBytes_FromStringAndSize (array->data, array->len);
            } else {
                object = PyList_New (array->len);
                if (object == NULL) {
                    g_critical ("Failure to allocate array for %u items", array->len);
                    g_base_info_unref ( (GIBaseInfo *) item_type_info);
                    break;
                }

                for (i = 0; i < array->len; i++) {
                    GIArgument item = { 0 };
                    PyObject *py_item;
                    
                    memcpy (&item, array->data + i * item_size, item_size);

                    py_item = _pygi_argument_to_object (&item, item_type_info, item_transfer);
                    if (py_item == NULL) {
                        Py_CLEAR (object);
                        _PyGI_ERROR_PREFIX ("Item %zu: ", i);
                        break;
                    }

                    PyList_SET_ITEM (object, i, py_item);
                }
            }

            g_base_info_unref ( (GIBaseInfo *) item_type_info);
            break;
        }
        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info;
            GIInfoType info_type;

            info = g_type_info_get_interface (type_info);
            info_type = g_base_info_get_type (info);

            switch (info_type) {
                case GI_INFO_TYPE_CALLBACK:
                {
                    g_assert_not_reached();
                }
                case GI_INFO_TYPE_BOXED:
                case GI_INFO_TYPE_STRUCT:
                case GI_INFO_TYPE_UNION:
                {
                    PyObject *py_type;
                    GType g_type = g_registered_type_info_get_g_type ( (GIRegisteredTypeInfo *) info);
                    gboolean is_foreign = (info_type == GI_INFO_TYPE_STRUCT) &&
                                          (g_struct_info_is_foreign ((GIStructInfo *) info));

                    /* Special case variant and none to force loading from py module. */
                    if (g_type == G_TYPE_VARIANT || g_type == G_TYPE_NONE) {
                        py_type = _pygi_type_import_by_gi_info (info);
                    } else {
                        py_type = _pygi_type_get_from_g_type (g_type);
                    }

                    object = pygi_arg_struct_to_py_marshal (arg,
                                                            info, /*interface_info*/
                                                            g_type,
                                                            py_type,
                                                            transfer,
                                                            FALSE, /*is_allocated*/
                                                            is_foreign);

                    Py_XDECREF (py_type);
                    break;
                }
                case GI_INFO_TYPE_ENUM:
                case GI_INFO_TYPE_FLAGS:
                {
                    GType type;

                    type = g_registered_type_info_get_g_type ( (GIRegisteredTypeInfo *) info);

                    if (type == G_TYPE_NONE) {
                        /* An enum with a GType of None is an enum without GType */
                        PyObject *py_type = _pygi_type_import_by_gi_info (info);
                        PyObject *py_args = NULL;

                        if (!py_type)
                            return NULL;

                        py_args = PyTuple_New (1);
                        if (PyTuple_SetItem (py_args, 0, PyLong_FromLong (arg->v_int)) != 0) {
                            Py_DECREF (py_args);
                            Py_DECREF (py_type);
                            return NULL;
                        }

                        object = PyObject_CallFunction (py_type, "i", arg->v_int);

                        Py_DECREF (py_args);
                        Py_DECREF (py_type);

                    } else if (info_type == GI_INFO_TYPE_ENUM) {
                        object = pyg_enum_from_gtype (type, arg->v_int);
                    } else {
                        object = pyg_flags_from_gtype (type, arg->v_uint);
                    }

                    break;
                }
                case GI_INFO_TYPE_INTERFACE:
                case GI_INFO_TYPE_OBJECT:
                    object = pygi_arg_gobject_to_py_called_from_c (arg, transfer);

                    break;
                default:
                    g_assert_not_reached();
            }

            g_base_info_unref (info);
            break;
        }
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        {
            GSList *list;
            gsize length;
            GITypeInfo *item_type_info;
            GITransfer item_transfer;
            gsize i;

            list = arg->v_pointer;
            length = g_slist_length (list);

            object = PyList_New (length);
            if (object == NULL) {
                break;
            }

            item_type_info = g_type_info_get_param_type (type_info, 0);
            g_assert (item_type_info != NULL);

            item_transfer = transfer == GI_TRANSFER_CONTAINER ? GI_TRANSFER_NOTHING : transfer;

            for (i = 0; list != NULL; list = g_slist_next (list), i++) {
                GIArgument item;
                PyObject *py_item;

                item.v_pointer = list->data;

                py_item = _pygi_argument_to_object (&item, item_type_info, item_transfer);
                if (py_item == NULL) {
                    Py_CLEAR (object);
                    _PyGI_ERROR_PREFIX ("Item %zu: ", i);
                    break;
                }

                PyList_SET_ITEM (object, i, py_item);
            }

            g_base_info_unref ( (GIBaseInfo *) item_type_info);
            break;
        }
        case GI_TYPE_TAG_GHASH:
        {
            GITypeInfo *key_type_info;
            GITypeInfo *value_type_info;
            GITransfer item_transfer;
            GHashTableIter hash_table_iter;
            GIArgument key;
            GIArgument value;

            if (arg->v_pointer == NULL) {
                object = Py_None;
                Py_INCREF (object);
                break;
            }

            object = PyDict_New();
            if (object == NULL) {
                break;
            }

            key_type_info = g_type_info_get_param_type (type_info, 0);
            g_assert (key_type_info != NULL);
            g_assert (g_type_info_get_tag (key_type_info) != GI_TYPE_TAG_VOID);

            value_type_info = g_type_info_get_param_type (type_info, 1);
            g_assert (value_type_info != NULL);
            g_assert (g_type_info_get_tag (value_type_info) != GI_TYPE_TAG_VOID);

            item_transfer = transfer == GI_TRANSFER_CONTAINER ? GI_TRANSFER_NOTHING : transfer;

            g_hash_table_iter_init (&hash_table_iter, (GHashTable *) arg->v_pointer);
            while (g_hash_table_iter_next (&hash_table_iter, &key.v_pointer, &value.v_pointer)) {
                PyObject *py_key;
                PyObject *py_value;
                int retval;

                py_key = _pygi_argument_to_object (&key, key_type_info, item_transfer);
                if (py_key == NULL) {
                    break;
                }

                _pygi_hash_pointer_to_arg (&value, g_type_info_get_tag (value_type_info));
                py_value = _pygi_argument_to_object (&value, value_type_info, item_transfer);
                if (py_value == NULL) {
                    Py_DECREF (py_key);
                    break;
                }

                retval = PyDict_SetItem (object, py_key, py_value);

                Py_DECREF (py_key);
                Py_DECREF (py_value);

                if (retval < 0) {
                    Py_CLEAR (object);
                    break;
                }
            }

            g_base_info_unref ( (GIBaseInfo *) key_type_info);
            g_base_info_unref ( (GIBaseInfo *) value_type_info);
            break;
        }
        case GI_TYPE_TAG_ERROR:
        {
            GError *error = (GError *) arg->v_pointer;
            if (error != NULL && transfer == GI_TRANSFER_NOTHING) {
                /* If we have not been transferred the ownership we must copy
                 * the error, because pygi_error_check() is going to free it.
                 */
                error = g_error_copy (error);
            }

            if (pygi_error_check (&error)) {
                PyObject *err_type;
                PyObject *err_value;
                PyObject *err_trace;
                PyErr_Fetch (&err_type, &err_value, &err_trace);
                Py_XDECREF (err_type);
                Py_XDECREF (err_trace);
                object = err_value;
            } else {
                object = Py_None;
                Py_INCREF (object);
                break;
            }
            break;
        }
        default:
        {
            g_assert_not_reached();
        }
    }

    return object;
}
Exemple #10
0
static PyObject *__pyx_f_11closestpair_closest_pair(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyListObject *__pyx_v_points = 0;
  float __pyx_v_min_d;
  PyObject *__pyx_v_min_p1;
  PyObject *__pyx_v_min_p2;
  PyObject *__pyx_v_i;
  PyObject *__pyx_v_point;
  PyObject *__pyx_v_point2;
  PyObject *__pyx_v_d;
  PyObject *__pyx_v_split;
  PyObject *__pyx_v_d1;
  PyObject *__pyx_v_p11;
  PyObject *__pyx_v_p12;
  PyObject *__pyx_v_d2;
  PyObject *__pyx_v_p21;
  PyObject *__pyx_v_p22;
  PyObject *__pyx_v_points_in_strip;
  PyObject *__pyx_v_split_at;
  PyObject *__pyx_v_max_i;
  PyObject *__pyx_v_sd;
  PyObject *__pyx_r;
  Py_ssize_t __pyx_1;
  int __pyx_2;
  PyObject *__pyx_3 = 0;
  PyObject *__pyx_4 = 0;
  PyObject *__pyx_5 = 0;
  PyObject *__pyx_6 = 0;
  PyObject *__pyx_7 = 0;
  PyObject *__pyx_8 = 0;
  PyObject *__pyx_9 = 0;
  PyObject *__pyx_10 = 0;
  float __pyx_11;
  int __pyx_12;
  Py_ssize_t __pyx_13;
  static char *__pyx_argnames[] = {"points",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_points)) return 0;
  Py_INCREF(__pyx_v_points);
  __pyx_v_min_p1 = Py_None; Py_INCREF(Py_None);
  __pyx_v_min_p2 = Py_None; Py_INCREF(Py_None);
  __pyx_v_i = Py_None; Py_INCREF(Py_None);
  __pyx_v_point = Py_None; Py_INCREF(Py_None);
  __pyx_v_point2 = Py_None; Py_INCREF(Py_None);
  __pyx_v_d = Py_None; Py_INCREF(Py_None);
  __pyx_v_split = Py_None; Py_INCREF(Py_None);
  __pyx_v_d1 = Py_None; Py_INCREF(Py_None);
  __pyx_v_p11 = Py_None; Py_INCREF(Py_None);
  __pyx_v_p12 = Py_None; Py_INCREF(Py_None);
  __pyx_v_d2 = Py_None; Py_INCREF(Py_None);
  __pyx_v_p21 = Py_None; Py_INCREF(Py_None);
  __pyx_v_p22 = Py_None; Py_INCREF(Py_None);
  __pyx_v_points_in_strip = Py_None; Py_INCREF(Py_None);
  __pyx_v_split_at = Py_None; Py_INCREF(Py_None);
  __pyx_v_max_i = Py_None; Py_INCREF(Py_None);
  __pyx_v_sd = Py_None; Py_INCREF(Py_None);
  if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_points), (&PyList_Type), 1, "points")) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; goto __pyx_L1;}

  /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":15 */
  __pyx_1 = PyObject_Length(((PyObject *)__pyx_v_points)); if (__pyx_1 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;}
  __pyx_2 = (__pyx_1 < 2);
  if (__pyx_2) {
    __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;}
    Py_INCREF(__pyx_k1p);
    PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k1p);
    __pyx_4 = PyObject_CallObject(PyExc_ValueError, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;}
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    __Pyx_Raise(__pyx_4, 0, 0);
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;}
    goto __pyx_L2;
  }
  __pyx_1 = PyObject_Length(((PyObject *)__pyx_v_points)); if (__pyx_1 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;}
  __pyx_2 = 2 <= __pyx_1;
  if (__pyx_2) {
    __pyx_2 = __pyx_1 <= 6;
  }
  if (__pyx_2) {

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":18 */
    __pyx_v_min_d = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":19 */
    Py_INCREF(Py_None);
    Py_DECREF(__pyx_v_min_p1);
    __pyx_v_min_p1 = Py_None;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":20 */
    Py_INCREF(Py_None);
    Py_DECREF(__pyx_v_min_p2);
    __pyx_v_min_p2 = Py_None;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":21 */
    __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
    Py_INCREF(((PyObject *)__pyx_v_points));
    PyTuple_SET_ITEM(__pyx_3, 0, ((PyObject *)__pyx_v_points));
    __pyx_4 = PyObject_CallObject(((PyObject *)(&PyEnum_Type)), __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    __pyx_3 = PyObject_GetIter(__pyx_4); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    for (;;) {
      __pyx_4 = PyIter_Next(__pyx_3);
      if (!__pyx_4) {
        if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
        break;
      }
      __pyx_5 = PyObject_GetIter(__pyx_4); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      __pyx_4 = __Pyx_UnpackItem(__pyx_5); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
      Py_DECREF(__pyx_v_i);
      __pyx_v_i = __pyx_4;
      __pyx_4 = 0;
      __pyx_4 = __Pyx_UnpackItem(__pyx_5); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
      Py_DECREF(__pyx_v_point);
      __pyx_v_point = __pyx_4;
      __pyx_4 = 0;
      if (__Pyx_EndUnpack(__pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
      Py_DECREF(__pyx_5); __pyx_5 = 0;
      __pyx_4 = PyInt_FromLong(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
      __pyx_5 = PyNumber_Add(__pyx_v_i, __pyx_4); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      __pyx_1 = PyInt_AsSsize_t(__pyx_5); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
      Py_DECREF(__pyx_5); __pyx_5 = 0;
      __pyx_4 = PySequence_GetSlice(((PyObject *)__pyx_v_points), __pyx_1, PY_SSIZE_T_MAX); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
      __pyx_5 = PyObject_GetIter(__pyx_4); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      for (;;) {
        __pyx_4 = PyIter_Next(__pyx_5);
        if (!__pyx_4) {
          if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
          break;
        }
        Py_DECREF(__pyx_v_point2);
        __pyx_v_point2 = __pyx_4;
        __pyx_4 = 0;

        /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":23 */
        __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_distance); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        __pyx_6 = PySequence_GetItem(__pyx_v_point, 0); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        __pyx_7 = PySequence_GetItem(__pyx_v_point, 1); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        __pyx_8 = PySequence_GetItem(__pyx_v_point2, 0); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        __pyx_9 = PySequence_GetItem(__pyx_v_point2, 1); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        __pyx_10 = PyTuple_New(4); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        PyTuple_SET_ITEM(__pyx_10, 0, __pyx_6);
        PyTuple_SET_ITEM(__pyx_10, 1, __pyx_7);
        PyTuple_SET_ITEM(__pyx_10, 2, __pyx_8);
        PyTuple_SET_ITEM(__pyx_10, 3, __pyx_9);
        __pyx_6 = 0;
        __pyx_7 = 0;
        __pyx_8 = 0;
        __pyx_9 = 0;
        __pyx_6 = PyObject_CallObject(__pyx_4, __pyx_10); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
        Py_DECREF(__pyx_4); __pyx_4 = 0;
        Py_DECREF(__pyx_10); __pyx_10 = 0;
        Py_DECREF(__pyx_v_d);
        __pyx_v_d = __pyx_6;
        __pyx_6 = 0;

        /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":24 */
        __pyx_2 = (__pyx_v_min_d == 0);
        if (!__pyx_2) {
          __pyx_7 = PyFloat_FromDouble(__pyx_v_min_d); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; goto __pyx_L1;}
          if (PyObject_Cmp(__pyx_7, __pyx_v_d, &__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; goto __pyx_L1;}
          __pyx_2 = __pyx_2 > 0;
          Py_DECREF(__pyx_7); __pyx_7 = 0;
        }
        if (__pyx_2) {

          /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":25 */
          __pyx_11 = PyFloat_AsDouble(__pyx_v_d); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; goto __pyx_L1;}
          __pyx_v_min_d = __pyx_11;

          /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":26 */
          Py_INCREF(__pyx_v_point);
          Py_DECREF(__pyx_v_min_p1);
          __pyx_v_min_p1 = __pyx_v_point;

          /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":27 */
          Py_INCREF(__pyx_v_point2);
          Py_DECREF(__pyx_v_min_p2);
          __pyx_v_min_p2 = __pyx_v_point2;
          goto __pyx_L7;
        }
        __pyx_L7:;
      }
      Py_DECREF(__pyx_5); __pyx_5 = 0;
    }
    Py_DECREF(__pyx_3); __pyx_3 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":28 */
    __pyx_8 = PyFloat_FromDouble(__pyx_v_min_d); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; goto __pyx_L1;}
    __pyx_9 = PyTuple_New(3); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; goto __pyx_L1;}
    PyTuple_SET_ITEM(__pyx_9, 0, __pyx_8);
    Py_INCREF(__pyx_v_min_p1);
    PyTuple_SET_ITEM(__pyx_9, 1, __pyx_v_min_p1);
    Py_INCREF(__pyx_v_min_p2);
    PyTuple_SET_ITEM(__pyx_9, 2, __pyx_v_min_p2);
    __pyx_8 = 0;
    __pyx_r = __pyx_9;
    __pyx_9 = 0;
    goto __pyx_L0;
    goto __pyx_L2;
  }
  /*else*/ {

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":30 */
    __pyx_12 = PyList_Sort(((PyObject *)__pyx_v_points)); if (__pyx_12 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; goto __pyx_L1;}

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":32 */
    __pyx_1 = PyObject_Length(((PyObject *)__pyx_v_points)); if (__pyx_1 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;}
    __pyx_4 = PyInt_FromSsize_t((__pyx_1 / 2)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;}
    __pyx_10 = PyTuple_New(1); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;}
    PyTuple_SET_ITEM(__pyx_10, 0, __pyx_4);
    __pyx_4 = 0;
    __pyx_6 = PyObject_CallObject(((PyObject *)(&PyInt_Type)), __pyx_10); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;}
    Py_DECREF(__pyx_10); __pyx_10 = 0;
    Py_DECREF(__pyx_v_split);
    __pyx_v_split = __pyx_6;
    __pyx_6 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":33 */
    __pyx_7 = __Pyx_GetName(__pyx_m, __pyx_n_closest_pair); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    __pyx_1 = PyInt_AsSsize_t(__pyx_v_split); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    __pyx_5 = PySequence_GetSlice(((PyObject *)__pyx_v_points), 0, __pyx_1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    PyTuple_SET_ITEM(__pyx_3, 0, __pyx_5);
    __pyx_5 = 0;
    __pyx_8 = PyObject_CallObject(__pyx_7, __pyx_3); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    Py_DECREF(__pyx_7); __pyx_7 = 0;
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    __pyx_9 = PyObject_GetIter(__pyx_8); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    Py_DECREF(__pyx_8); __pyx_8 = 0;
    __pyx_4 = __Pyx_UnpackItem(__pyx_9); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    Py_DECREF(__pyx_v_d1);
    __pyx_v_d1 = __pyx_4;
    __pyx_4 = 0;
    __pyx_10 = __Pyx_UnpackItem(__pyx_9); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    Py_DECREF(__pyx_v_p11);
    __pyx_v_p11 = __pyx_10;
    __pyx_10 = 0;
    __pyx_6 = __Pyx_UnpackItem(__pyx_9); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    Py_DECREF(__pyx_v_p12);
    __pyx_v_p12 = __pyx_6;
    __pyx_6 = 0;
    if (__Pyx_EndUnpack(__pyx_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    Py_DECREF(__pyx_9); __pyx_9 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":34 */
    __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_n_closest_pair); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    __pyx_1 = PyInt_AsSsize_t(__pyx_v_split); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    __pyx_7 = PySequence_GetSlice(((PyObject *)__pyx_v_points), __pyx_1, PY_SSIZE_T_MAX); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    PyTuple_SET_ITEM(__pyx_3, 0, __pyx_7);
    __pyx_7 = 0;
    __pyx_8 = PyObject_CallObject(__pyx_5, __pyx_3); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    Py_DECREF(__pyx_5); __pyx_5 = 0;
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    __pyx_4 = PyObject_GetIter(__pyx_8); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    Py_DECREF(__pyx_8); __pyx_8 = 0;
    __pyx_10 = __Pyx_UnpackItem(__pyx_4); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    Py_DECREF(__pyx_v_d2);
    __pyx_v_d2 = __pyx_10;
    __pyx_10 = 0;
    __pyx_6 = __Pyx_UnpackItem(__pyx_4); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    Py_DECREF(__pyx_v_p21);
    __pyx_v_p21 = __pyx_6;
    __pyx_6 = 0;
    __pyx_9 = __Pyx_UnpackItem(__pyx_4); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    Py_DECREF(__pyx_v_p22);
    __pyx_v_p22 = __pyx_9;
    __pyx_9 = 0;
    if (__Pyx_EndUnpack(__pyx_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":35 */
    __pyx_7 = __Pyx_GetName(__pyx_b, __pyx_n_min); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; goto __pyx_L1;}
    __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; goto __pyx_L1;}
    Py_INCREF(__pyx_v_d1);
    PyTuple_SET_ITEM(__pyx_5, 0, __pyx_v_d1);
    Py_INCREF(__pyx_v_d2);
    PyTuple_SET_ITEM(__pyx_5, 1, __pyx_v_d2);
    __pyx_3 = PyObject_CallObject(__pyx_7, __pyx_5); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; goto __pyx_L1;}
    Py_DECREF(__pyx_7); __pyx_7 = 0;
    Py_DECREF(__pyx_5); __pyx_5 = 0;
    Py_DECREF(__pyx_v_d);
    __pyx_v_d = __pyx_3;
    __pyx_3 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":37 */
    __pyx_8 = PyList_New(0); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;}
    Py_DECREF(__pyx_v_points_in_strip);
    __pyx_v_points_in_strip = __pyx_8;
    __pyx_8 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":38 */
    __pyx_10 = PyInt_FromLong(1); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    __pyx_6 = PyNumber_Subtract(__pyx_v_split, __pyx_10); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    Py_DECREF(__pyx_10); __pyx_10 = 0;
    __pyx_9 = PyObject_GetItem(((PyObject *)__pyx_v_points), __pyx_6); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    __pyx_4 = PySequence_GetItem(__pyx_9, 0); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    Py_DECREF(__pyx_9); __pyx_9 = 0;
    __pyx_7 = PyObject_GetItem(((PyObject *)__pyx_v_points), __pyx_v_split); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    __pyx_5 = PySequence_GetItem(__pyx_7, 0); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    Py_DECREF(__pyx_7); __pyx_7 = 0;
    __pyx_3 = PyNumber_Add(__pyx_4, __pyx_5); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    Py_DECREF(__pyx_5); __pyx_5 = 0;
    __pyx_8 = PyFloat_FromDouble(2.0); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    __pyx_10 = PyNumber_Divide(__pyx_3, __pyx_8); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;}
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    Py_DECREF(__pyx_8); __pyx_8 = 0;
    Py_DECREF(__pyx_v_split_at);
    __pyx_v_split_at = __pyx_10;
    __pyx_10 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":39 */
    __pyx_6 = PyObject_GetIter(((PyObject *)__pyx_v_points)); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; goto __pyx_L1;}
    for (;;) {
      __pyx_9 = PyIter_Next(__pyx_6);
      if (!__pyx_9) {
        if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; goto __pyx_L1;}
        break;
      }
      Py_DECREF(__pyx_v_point);
      __pyx_v_point = __pyx_9;
      __pyx_9 = 0;

      /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":40 */
      __pyx_7 = PySequence_GetItem(__pyx_v_point, 0); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; goto __pyx_L1;}
      __pyx_4 = PyNumber_Subtract(__pyx_v_split_at, __pyx_v_d); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; goto __pyx_L1;}
      if (PyObject_Cmp(__pyx_7, __pyx_4, &__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; goto __pyx_L1;}
      __pyx_2 = __pyx_2 < 0;
      Py_DECREF(__pyx_7); __pyx_7 = 0;
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      if (__pyx_2) {
        goto __pyx_L8;
        goto __pyx_L10;
      }
      __pyx_5 = PySequence_GetItem(__pyx_v_point, 0); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;}
      __pyx_3 = PyNumber_Add(__pyx_v_split_at, __pyx_v_d); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;}
      if (PyObject_Cmp(__pyx_5, __pyx_3, &__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;}
      __pyx_2 = __pyx_2 > 0;
      Py_DECREF(__pyx_5); __pyx_5 = 0;
      Py_DECREF(__pyx_3); __pyx_3 = 0;
      if (__pyx_2) {
        goto __pyx_L9;
        goto __pyx_L10;
      }
      __pyx_L10:;

      /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":44 */
      __pyx_8 = PyObject_GetAttr(__pyx_v_points_in_strip, __pyx_n_append); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      __pyx_10 = PySequence_GetItem(__pyx_v_point, 1); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      __pyx_9 = PySequence_GetItem(__pyx_v_point, 0); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      __pyx_7 = PySequence_GetItem(__pyx_v_point, 2); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      __pyx_4 = PyTuple_New(3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      PyTuple_SET_ITEM(__pyx_4, 0, __pyx_10);
      PyTuple_SET_ITEM(__pyx_4, 1, __pyx_9);
      PyTuple_SET_ITEM(__pyx_4, 2, __pyx_7);
      __pyx_10 = 0;
      __pyx_9 = 0;
      __pyx_7 = 0;
      __pyx_5 = PyTuple_New(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      PyTuple_SET_ITEM(__pyx_5, 0, __pyx_4);
      __pyx_4 = 0;
      __pyx_3 = PyObject_CallObject(__pyx_8, __pyx_5); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
      Py_DECREF(__pyx_8); __pyx_8 = 0;
      Py_DECREF(__pyx_5); __pyx_5 = 0;
      Py_DECREF(__pyx_3); __pyx_3 = 0;
      __pyx_L8:;
    }
    __pyx_L9:;
    Py_DECREF(__pyx_6); __pyx_6 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":46 */
    __pyx_10 = PyObject_GetAttr(__pyx_v_points_in_strip, __pyx_n_sort); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;}
    __pyx_9 = PyObject_CallObject(__pyx_10, 0); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;}
    Py_DECREF(__pyx_10); __pyx_10 = 0;
    Py_DECREF(__pyx_9); __pyx_9 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":48 */
    __pyx_v_min_d = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":49 */
    Py_INCREF(Py_None);
    Py_DECREF(__pyx_v_min_p1);
    __pyx_v_min_p1 = Py_None;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":50 */
    Py_INCREF(Py_None);
    Py_DECREF(__pyx_v_min_p2);
    __pyx_v_min_p2 = Py_None;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":51 */
    __pyx_1 = PyObject_Length(__pyx_v_points_in_strip); if (__pyx_1 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; goto __pyx_L1;}
    __pyx_7 = PyInt_FromSsize_t(__pyx_1); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; goto __pyx_L1;}
    Py_DECREF(__pyx_v_max_i);
    __pyx_v_max_i = __pyx_7;
    __pyx_7 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":52 */
    __pyx_4 = PyTuple_New(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
    Py_INCREF(__pyx_v_points_in_strip);
    PyTuple_SET_ITEM(__pyx_4, 0, __pyx_v_points_in_strip);
    __pyx_8 = PyObject_CallObject(((PyObject *)(&PyEnum_Type)), __pyx_4); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    __pyx_5 = PyObject_GetIter(__pyx_8); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
    Py_DECREF(__pyx_8); __pyx_8 = 0;
    for (;;) {
      __pyx_3 = PyIter_Next(__pyx_5);
      if (!__pyx_3) {
        if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
        break;
      }
      __pyx_6 = PyObject_GetIter(__pyx_3); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
      Py_DECREF(__pyx_3); __pyx_3 = 0;
      __pyx_10 = __Pyx_UnpackItem(__pyx_6); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
      Py_DECREF(__pyx_v_i);
      __pyx_v_i = __pyx_10;
      __pyx_10 = 0;
      __pyx_9 = __Pyx_UnpackItem(__pyx_6); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
      Py_DECREF(__pyx_v_point);
      __pyx_v_point = __pyx_9;
      __pyx_9 = 0;
      if (__Pyx_EndUnpack(__pyx_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;}
      Py_DECREF(__pyx_6); __pyx_6 = 0;
      __pyx_7 = PyInt_FromLong(1); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      __pyx_4 = PyNumber_Add(__pyx_v_i, __pyx_7); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_DECREF(__pyx_7); __pyx_7 = 0;
      __pyx_1 = PyInt_AsSsize_t(__pyx_4); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      __pyx_8 = __Pyx_GetName(__pyx_b, __pyx_n_min); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      __pyx_3 = PyInt_FromLong(7); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      __pyx_10 = PyNumber_Add(__pyx_v_i, __pyx_3); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_DECREF(__pyx_3); __pyx_3 = 0;
      __pyx_9 = PyTuple_New(2); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_INCREF(__pyx_v_max_i);
      PyTuple_SET_ITEM(__pyx_9, 0, __pyx_v_max_i);
      PyTuple_SET_ITEM(__pyx_9, 1, __pyx_10);
      __pyx_10 = 0;
      __pyx_6 = PyObject_CallObject(__pyx_8, __pyx_9); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_DECREF(__pyx_8); __pyx_8 = 0;
      Py_DECREF(__pyx_9); __pyx_9 = 0;
      __pyx_13 = PyInt_AsSsize_t(__pyx_6); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_DECREF(__pyx_6); __pyx_6 = 0;
      __pyx_7 = PySequence_GetSlice(__pyx_v_points_in_strip, __pyx_1, __pyx_13); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      __pyx_4 = PyObject_GetIter(__pyx_7); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
      Py_DECREF(__pyx_7); __pyx_7 = 0;
      for (;;) {
        __pyx_3 = PyIter_Next(__pyx_4);
        if (!__pyx_3) {
          if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;}
          break;
        }
        Py_DECREF(__pyx_v_point2);
        __pyx_v_point2 = __pyx_3;
        __pyx_3 = 0;

        /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":54 */
        __pyx_10 = __Pyx_GetName(__pyx_m, __pyx_n_distance); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        __pyx_8 = PySequence_GetItem(__pyx_v_point, 0); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        __pyx_9 = PySequence_GetItem(__pyx_v_point, 1); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        __pyx_6 = PySequence_GetItem(__pyx_v_point2, 0); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        __pyx_7 = PySequence_GetItem(__pyx_v_point2, 1); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        __pyx_3 = PyTuple_New(4); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        PyTuple_SET_ITEM(__pyx_3, 0, __pyx_8);
        PyTuple_SET_ITEM(__pyx_3, 1, __pyx_9);
        PyTuple_SET_ITEM(__pyx_3, 2, __pyx_6);
        PyTuple_SET_ITEM(__pyx_3, 3, __pyx_7);
        __pyx_8 = 0;
        __pyx_9 = 0;
        __pyx_6 = 0;
        __pyx_7 = 0;
        __pyx_8 = PyObject_CallObject(__pyx_10, __pyx_3); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; goto __pyx_L1;}
        Py_DECREF(__pyx_10); __pyx_10 = 0;
        Py_DECREF(__pyx_3); __pyx_3 = 0;
        Py_DECREF(__pyx_v_sd);
        __pyx_v_sd = __pyx_8;
        __pyx_8 = 0;

        /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":55 */
        __pyx_2 = (__pyx_v_min_d == 0);
        if (!__pyx_2) {
          __pyx_9 = PyFloat_FromDouble(__pyx_v_min_d); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; goto __pyx_L1;}
          if (PyObject_Cmp(__pyx_9, __pyx_v_sd, &__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; goto __pyx_L1;}
          __pyx_2 = __pyx_2 > 0;
          Py_DECREF(__pyx_9); __pyx_9 = 0;
        }
        if (__pyx_2) {

          /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":56 */
          __pyx_11 = PyFloat_AsDouble(__pyx_v_sd); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; goto __pyx_L1;}
          __pyx_v_min_d = __pyx_11;

          /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":57 */
          __pyx_6 = PySequence_GetItem(__pyx_v_point, 1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
          __pyx_7 = PySequence_GetItem(__pyx_v_point, 0); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
          __pyx_10 = PySequence_GetItem(__pyx_v_point, 2); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
          __pyx_3 = PyTuple_New(3); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
          PyTuple_SET_ITEM(__pyx_3, 0, __pyx_6);
          PyTuple_SET_ITEM(__pyx_3, 1, __pyx_7);
          PyTuple_SET_ITEM(__pyx_3, 2, __pyx_10);
          __pyx_6 = 0;
          __pyx_7 = 0;
          __pyx_10 = 0;
          Py_DECREF(__pyx_v_min_p1);
          __pyx_v_min_p1 = __pyx_3;
          __pyx_3 = 0;

          /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":58 */
          __pyx_8 = PySequence_GetItem(__pyx_v_point2, 1); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; goto __pyx_L1;}
          __pyx_9 = PySequence_GetItem(__pyx_v_point2, 0); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; goto __pyx_L1;}
          __pyx_6 = PySequence_GetItem(__pyx_v_point2, 2); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; goto __pyx_L1;}
          __pyx_7 = PyTuple_New(3); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; goto __pyx_L1;}
          PyTuple_SET_ITEM(__pyx_7, 0, __pyx_8);
          PyTuple_SET_ITEM(__pyx_7, 1, __pyx_9);
          PyTuple_SET_ITEM(__pyx_7, 2, __pyx_6);
          __pyx_8 = 0;
          __pyx_9 = 0;
          __pyx_6 = 0;
          Py_DECREF(__pyx_v_min_p2);
          __pyx_v_min_p2 = __pyx_7;
          __pyx_7 = 0;
          goto __pyx_L15;
        }
        __pyx_L15:;
      }
      Py_DECREF(__pyx_4); __pyx_4 = 0;
    }
    Py_DECREF(__pyx_5); __pyx_5 = 0;

    /* "/home/andrew/Programs/cluster/clusterer/closestpair.pyx":59 */
    __pyx_2 = (__pyx_v_min_d != 0);
    if (__pyx_2) {
      __pyx_10 = PyFloat_FromDouble(__pyx_v_min_d); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; goto __pyx_L1;}
      if (PyObject_Cmp(__pyx_10, __pyx_v_d, &__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; goto __pyx_L1;}
      __pyx_2 = __pyx_2 < 0;
      Py_DECREF(__pyx_10); __pyx_10 = 0;
    }
    if (__pyx_2) {
      __pyx_3 = PyFloat_FromDouble(__pyx_v_min_d); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; goto __pyx_L1;}
      __pyx_8 = PyTuple_New(3); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; goto __pyx_L1;}
      PyTuple_SET_ITEM(__pyx_8, 0, __pyx_3);
      Py_INCREF(__pyx_v_min_p1);
      PyTuple_SET_ITEM(__pyx_8, 1, __pyx_v_min_p1);
      Py_INCREF(__pyx_v_min_p2);
      PyTuple_SET_ITEM(__pyx_8, 2, __pyx_v_min_p2);
      __pyx_3 = 0;
      __pyx_r = __pyx_8;
      __pyx_8 = 0;
      goto __pyx_L0;
      goto __pyx_L16;
    }
    if (PyObject_Cmp(__pyx_v_d1, __pyx_v_d2, &__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; goto __pyx_L1;}
    __pyx_2 = __pyx_2 < 0;
    if (__pyx_2) {
      __pyx_9 = PyTuple_New(3); if (!__pyx_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; goto __pyx_L1;}
      Py_INCREF(__pyx_v_d1);
      PyTuple_SET_ITEM(__pyx_9, 0, __pyx_v_d1);
      Py_INCREF(__pyx_v_p11);
      PyTuple_SET_ITEM(__pyx_9, 1, __pyx_v_p11);
      Py_INCREF(__pyx_v_p12);
      PyTuple_SET_ITEM(__pyx_9, 2, __pyx_v_p12);
      __pyx_r = __pyx_9;
      __pyx_9 = 0;
      goto __pyx_L0;
      goto __pyx_L16;
    }
    /*else*/ {
      __pyx_6 = PyTuple_New(3); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; goto __pyx_L1;}
      Py_INCREF(__pyx_v_d2);
      PyTuple_SET_ITEM(__pyx_6, 0, __pyx_v_d2);
      Py_INCREF(__pyx_v_p21);
      PyTuple_SET_ITEM(__pyx_6, 1, __pyx_v_p21);
      Py_INCREF(__pyx_v_p22);
      PyTuple_SET_ITEM(__pyx_6, 2, __pyx_v_p22);
      __pyx_r = __pyx_6;
      __pyx_6 = 0;
      goto __pyx_L0;
    }
    __pyx_L16:;
  }
  __pyx_L2:;

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_3);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_5);
  Py_XDECREF(__pyx_6);
  Py_XDECREF(__pyx_7);
  Py_XDECREF(__pyx_8);
  Py_XDECREF(__pyx_9);
  Py_XDECREF(__pyx_10);
  __Pyx_AddTraceback("closestpair.closest_pair");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_min_p1);
  Py_DECREF(__pyx_v_min_p2);
  Py_DECREF(__pyx_v_i);
  Py_DECREF(__pyx_v_point);
  Py_DECREF(__pyx_v_point2);
  Py_DECREF(__pyx_v_d);
  Py_DECREF(__pyx_v_split);
  Py_DECREF(__pyx_v_d1);
  Py_DECREF(__pyx_v_p11);
  Py_DECREF(__pyx_v_p12);
  Py_DECREF(__pyx_v_d2);
  Py_DECREF(__pyx_v_p21);
  Py_DECREF(__pyx_v_p22);
  Py_DECREF(__pyx_v_points_in_strip);
  Py_DECREF(__pyx_v_split_at);
  Py_DECREF(__pyx_v_max_i);
  Py_DECREF(__pyx_v_sd);
  Py_DECREF(__pyx_v_points);
  return __pyx_r;
}
Exemple #11
0
static krb5_error_code
lookup(void *blob, enum locate_service_type svc, const char *realm,
       int socktype, int family,
       int (*cbfunc)(void *, int, struct sockaddr *), void *cbdata)
{
    PyObject *py_result, *svcarg, *realmarg, *arglist;
    int listsize, i, x;
    struct addrinfo aihints, *airesult;
    int thissocktype;

//    fprintf(stderr, "%s:%d: lookup(%d,%s,%d,%d)\n", F, __LINE__,
//          svc, realm, socktype, family);
    sctx = blob;                /* XXX: Not thread safe!  */
    i = CALL_INIT_FUNCTION (my_init);
    if (i) {
#if 0
        fprintf(stderr, "%s:%d: module initialization failed\n", F, __LINE__);
#endif
        return i;
    }
    if (locatefn == 0)
        return KRB5_PLUGIN_NO_HANDLE;
    svcarg = PyInt_FromLong (svc);
    /* error? */
    realmarg = PyString_FromString ((char *) realm);
    /* error? */
    arglist = PyTuple_New (4);
    /* error? */

    PyTuple_SetItem (arglist, 0, svcarg);
    PyTuple_SetItem (arglist, 1, realmarg);
    PyTuple_SetItem (arglist, 2, PyInt_FromLong (socktype));
    PyTuple_SetItem (arglist, 3, PyInt_FromLong (family));
    /* references handed off, no decref */

    py_result = PyObject_CallObject (locatefn, arglist);
    Py_DECREF (arglist);
    if (PyErr_Occurred()) {
        fprintf(stderr,"%s:%d: python error\n", F, __LINE__);
        PyErr_Print();
        krb5_set_error_message(blob, -1,
                               "Python evaluation error, see stderr");
        return -1;
    }
    if (py_result == 0) {
        fprintf(stderr, "%s:%d: returned null object\n", F, __LINE__);
        return -1;
    }
    if (py_result == Py_False)
        return KRB5_PLUGIN_NO_HANDLE;
    if (! PyList_Check (py_result)) {
        Py_DECREF (py_result);
        fprintf(stderr, "%s:%d: returned non-list, non-False\n", F, __LINE__);
        krb5_set_error_message(blob, -1,
                               "Python script error -- returned non-list, non-False result");
        return -1;
    }
    listsize = PyList_Size (py_result);
    /* allocate */
    memset(&aihints, 0, sizeof(aihints));
    aihints.ai_flags = AI_NUMERICHOST;
    aihints.ai_family = family;
    for (i = 0; i < listsize; i++) {
        PyObject *answer, *field;
        char *hoststr, *portstr, portbuf[3*sizeof(long) + 4];
        int cbret;

        answer = PyList_GetItem (py_result, i);
        if (! PyTuple_Check (answer)) {
            krb5_set_error_message(blob, -1,
                                   "Python script error -- returned item %d not a tuple", i);
            /* leak?  */
            return -1;
        }
        if (PyTuple_Size (answer) != 3) {
            krb5_set_error_message(blob, -1,
                                   "Python script error -- returned tuple %d size %d should be 3",
                                   i, PyTuple_Size (answer));
            /* leak?  */
            return -1;
        }
        field = PyTuple_GetItem (answer, 0);
        if (! PyString_Check (field)) {
            /* leak?  */
            krb5_set_error_message(blob, -1,
                                   "Python script error -- first component of tuple %d is not a string",
                                   i);
            return -1;
        }
        hoststr = PyString_AsString (field);
        field = PyTuple_GetItem (answer, 1);
        if (PyString_Check (field)) {
            portstr = PyString_AsString (field);
        } else if (PyInt_Check (field)) {
            snprintf(portbuf, sizeof(portbuf), "%ld", PyInt_AsLong (field));
            portstr = portbuf;
        } else {
            krb5_set_error_message(blob, -1,
                                   "Python script error -- second component of tuple %d neither a string nor an integer",
                                   i);
            /* leak?  */
            return -1;
        }
        field = PyTuple_GetItem (answer, 2);
        if (! PyInt_Check (field)) {
            krb5_set_error_message(blob, -1,
                                   "Python script error -- third component of tuple %d not an integer",
                                   i);
            /* leak?  */
            return -1;
        }
        thissocktype = PyInt_AsLong (field);
        switch (thissocktype) {
        case SOCK_STREAM:
        case SOCK_DGRAM:
            /* okay */
            if (socktype != 0 && socktype != thissocktype) {
                krb5_set_error_message(blob, -1,
                                       "Python script error -- tuple %d has socket type %d, should only have %d",
                                       i, thissocktype, socktype);
                /* leak?  */
                return -1;
            }
            break;
        default:
            /* 0 is not acceptable */
            krb5_set_error_message(blob, -1,
                                   "Python script error -- tuple %d has invalid socket type %d",
                                   i, thissocktype);
            /* leak?  */
            return -1;
        }
        aihints.ai_socktype = thissocktype;
        aihints.ai_flags = AI_ADDRCONFIG;
        x = getaddrinfo (hoststr, portstr, &aihints, &airesult);
        if (x != 0)
            continue;
        cbret = cbfunc(cbdata, airesult->ai_socktype, airesult->ai_addr);
        freeaddrinfo(airesult);
        if (cbret != 0)
            break;
    }
    Py_DECREF (py_result);
    return 0;
}
Exemple #12
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc, JSONObjectEncoder *enc)
{
  PyObject *obj, *exc, *toDictFunc, *iter;
  TypeContext *pc;
  PRINTMARK();
  if (!_obj) {
    tc->type = JT_INVALID;
    return;
  }

  obj = (PyObject*) _obj;

  tc->prv = PyObject_Malloc(sizeof(TypeContext));
  pc = (TypeContext *) tc->prv;
  if (!pc)
  {
    tc->type = JT_INVALID;
    PyErr_NoMemory();
    return;
  }
  pc->newObj = NULL;
  pc->dictObj = NULL;
  pc->itemValue = NULL;
  pc->itemName = NULL;
  pc->iterator = NULL;
  pc->attrList = NULL;
  pc->index = 0;
  pc->size = 0;
  pc->longValue = 0;

  if (PyIter_Check(obj))
  {
    PRINTMARK();
    goto ISITERABLE;
  }

  if (PyBool_Check(obj))
  {
    PRINTMARK();
    tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
    return;
  }
  else
  if (PyLong_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyLongToINT64;
    tc->type = JT_LONG;
    GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

    exc = PyErr_Occurred();
    if (!exc)
    {
        return;
    }

    if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
    {
      PyErr_Clear();
      pc->PyTypeToJSON = PyLongToUINT64;
      tc->type = JT_ULONG;
      GET_TC(tc)->unsignedLongValue = PyLong_AsUnsignedLongLong(obj);

      exc = PyErr_Occurred();
      if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
      {
        PRINTMARK();
        goto INVALID;
      }
    }

    return;
  }
  else
  if (PyInt_Check(obj))
  {
    PRINTMARK();
#ifdef _LP64
    pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
    pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
    return;
  }
  else
  if (PyString_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyUnicode_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyFloat_Check(obj) || (type_decimal && PyObject_IsInstance(obj, type_decimal)))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
    return;
  }
  else
  if (PyDateTime_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (PyDate_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (obj == Py_None)
  {
    PRINTMARK();
    tc->type = JT_NULL;
    return;
  }

ISITERABLE:
  if (PyDict_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_OBJECT;
    SetupDictIter(obj, pc, enc);
    Py_INCREF(obj);
    return;
  }
  else
  if (PyList_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterEnd = List_iterEnd;
    pc->iterNext = List_iterNext;
    pc->iterGetValue = List_iterGetValue;
    pc->iterGetName = List_iterGetName;
    GET_TC(tc)->index =  0;
    GET_TC(tc)->size = PyList_GET_SIZE( (PyObject *) obj);
    return;
  }
  else
  if (PyTuple_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterEnd = Tuple_iterEnd;
    pc->iterNext = Tuple_iterNext;
    pc->iterGetValue = Tuple_iterGetValue;
    pc->iterGetName = Tuple_iterGetName;
    GET_TC(tc)->index = 0;
    GET_TC(tc)->size = PyTuple_GET_SIZE( (PyObject *) obj);
    GET_TC(tc)->itemValue = NULL;

    return;
  }
  /*
  else
  if (PyAnySet_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = NULL;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }
  */

  toDictFunc = PyObject_GetAttrString(obj, "toDict");

  if (toDictFunc)
  {
    PyObject* tuple = PyTuple_New(0);
    PyObject* toDictResult = PyObject_Call(toDictFunc, tuple, NULL);
    Py_DECREF(tuple);
    Py_DECREF(toDictFunc);

    if (toDictResult == NULL)
    {
      PyErr_Clear();
      tc->type = JT_NULL;
      return;
    }

    if (!PyDict_Check(toDictResult))
    {
      Py_DECREF(toDictResult);
      tc->type = JT_NULL;
      return;
    }

    PRINTMARK();
    tc->type = JT_OBJECT;
    SetupDictIter(toDictResult, pc, enc);
    return;
  }

  PRINTMARK();
  PyErr_Clear();

  iter = PyObject_GetIter(obj);

  if (iter != NULL)
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterator = iter;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }

  PRINTMARK();
  PyErr_Clear();

  PRINTMARK();
  tc->type = JT_OBJECT;
  GET_TC(tc)->attrList = PyObject_Dir(obj);
  
  if (GET_TC(tc)->attrList == NULL)
  {
    PyErr_Clear();
    goto INVALID;
  }

  GET_TC(tc)->index = 0;
  GET_TC(tc)->size = PyList_GET_SIZE(GET_TC(tc)->attrList);
  PRINTMARK();
  
  pc->iterEnd = Dir_iterEnd;
  pc->iterNext = Dir_iterNext;
  pc->iterGetValue = Dir_iterGetValue;
  pc->iterGetName = Dir_iterGetName;
  return;

INVALID:
  PRINTMARK();
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
static int python_function(REQUEST *request, PyObject *pFunc,
			   const char *funcname)
{
	VALUE_PAIR      *vp;
	PyObject	*pRet = NULL;
	PyObject	*pArgs = NULL;
	int		tuplelen;
	int		ret;
	
	PyGILState_STATE gstate;
	
	/* Return with "OK, continue" if the function is not defined. */
	if (pFunc == NULL)
		return RLM_MODULE_OK;
	
	/* Default return value is "OK, continue" */
	ret = RLM_MODULE_OK;
	
	/*
	 *	We will pass a tuple containing (name, value) tuples
	 *	We can safely use the Python function to build up a
	 *	tuple, since the tuple is not used elsewhere.
	 *
	 *	Determine the size of our tuple by walking through the packet.
	 *	If request is NULL, pass None.
	 */
	tuplelen = 0;
	if (request != NULL) {
		for (vp = request->packet->vps; vp; vp = vp->next)
			tuplelen++;
	}

	gstate = PyGILState_Ensure();
	
	if (tuplelen == 0) {
		Py_INCREF(Py_None);
		pArgs = Py_None;
	} else {
		int i = 0;
		if ((pArgs = PyTuple_New(tuplelen)) == NULL)
			goto failed;

		for (vp = request->packet->vps;
		     vp != NULL;
		     vp = vp->next, i++) {
			PyObject *pPair;
			
			/* The inside tuple has two only: */
			if ((pPair = PyTuple_New(2)) == NULL)
				goto failed;
			
			if (python_populate_vptuple(pPair, vp) == 0) {
				/* Put the tuple inside the container */
				PyTuple_SET_ITEM(pArgs, i, pPair);
			} else {
				Py_INCREF(Py_None);
				PyTuple_SET_ITEM(pArgs, i, Py_None);
				Py_DECREF(pPair);
			}
		}
	}
	
	/* Call Python function. */
	pRet = PyObject_CallFunctionObjArgs(pFunc, pArgs, NULL);
	
	if (pRet == NULL)
		goto failed;
	
	if (request == NULL)
		goto okay;

	/*
	 *	The function returns either:
	 *  1. (returnvalue, replyTuple, configTuple), where
	 *   - returnvalue is one of the constants RLM_*
	 *   - replyTuple and configTuple are tuples of string
	 *      tuples of size 2
	 *
	 *  2. the function return value alone
	 *
	 *  3. None - default return value is set
	 *
	 * xxx This code is messy!
	 */
	if (PyTuple_CheckExact(pRet)) {
		PyObject *pTupleInt;
		
		if (PyTuple_GET_SIZE(pRet) != 3) {
			radlog(L_ERR, "rlm_python:%s: tuple must be (return, replyTuple, configTuple)", funcname);
			goto failed;
		}
		
		pTupleInt = PyTuple_GET_ITEM(pRet, 0);
		if (!PyInt_CheckExact(pTupleInt)) {
			radlog(L_ERR, "rlm_python:%s: first tuple element not an integer", funcname);
			goto failed;
		}
		/* Now have the return value */
		ret = PyInt_AsLong(pTupleInt);
		/* Reply item tuple */
		python_vptuple(&request->reply->vps,
			       PyTuple_GET_ITEM(pRet, 1), funcname);
		/* Config item tuple */
		python_vptuple(&request->config_items,
			       PyTuple_GET_ITEM(pRet, 2), funcname);

	} else if (PyInt_CheckExact(pRet)) {
		/* Just an integer */
		ret = PyInt_AsLong(pRet);

	} else if (pRet == Py_None) {
		/* returned 'None', return value defaults to "OK, continue." */
		ret = RLM_MODULE_OK;
	} else {
		/* Not tuple or None */
		radlog(L_ERR, "rlm_python:%s: function did not return a tuple or None", funcname);
		goto failed;
	}

 okay:
	Py_DECREF(pArgs);
	Py_DECREF(pRet);
	PyGILState_Release(gstate);
	return ret;
	
 failed:
	python_error();
	Py_XDECREF(pArgs);
	Py_XDECREF(pRet);
	PyGILState_Release(gstate);
	
	return -1;
}
Exemple #14
0
static PyObject *
internal_parse_depset(PyObject *dep_str, char **ptr, int *has_conditionals,
	PyObject *element_func,
	PyObject *and_func, PyObject *or_func,
	PyObject *parent_func,
	char initial_frame)
{
	char *start = *ptr;
	char *p = NULL;
	PyObject *restrictions = NULL;
	PyObject *item = NULL;
	PyObject *tmp = NULL;

	// should just use alloca here.

	#define PARSE_DEPSET_STACK_STORAGE 16
	PyObject *stack_restricts[PARSE_DEPSET_STACK_STORAGE];
	Py_ssize_t item_count = 0, tup_size = PARSE_DEPSET_STACK_STORAGE;
	Py_ssize_t item_size = 1;

	SKIP_SPACES(start);
	p = start;
	while('\0' != *start) {
		start = p;
		SKIP_NONSPACES(p);
		if('(' == *start) {
			// new and frame.
			if(!and_func) {
				Err_SetParse(dep_str, "this depset doesn't support and blocks",
				start, p);
				goto internal_parse_depset_error;
			}
			if(p - start != 1) {
				Err_SetParse(dep_str,
					"either a space or end of string is required after (",
					start, p);
				goto internal_parse_depset_error;
			}
			if(!(tmp = internal_parse_depset(dep_str, &p, has_conditionals,
				element_func, and_func, or_func, and_func, 0)))
				goto internal_parse_depset_error;

			if(tmp == Py_None) {
				Py_DECREF(tmp);
				Err_SetParse(dep_str, "empty payload", start, p);
				goto internal_parse_depset_error;
			} else if(!PyTuple_CheckExact(tmp)) {
				item = tmp;
			} else {
				item = PyObject_CallObject(and_func, tmp);
				Py_DECREF(tmp);
				if(!item)
					goto internal_parse_depset_error;
			}

		} else if(')' == *start) {
			// end of a frame
			if(initial_frame) {
				Err_SetParse(dep_str, ") found without matching (",
					NULL, NULL);
				goto internal_parse_depset_error;
			}
			if(p - start != 1) {
				Err_SetParse(dep_str,
					"either a space or end of string is required after )",
					start, p);
				goto internal_parse_depset_error;
			}

			if(!*p)
				p--;
			break;

		} else if('?' == p[-1]) {
			// use conditional
			if (p - start == 1 || ('!' == *start && p - start == 2)) {
				Err_SetParse(dep_str, "empty use conditional", start, p);
				goto internal_parse_depset_error;
			}
			char *conditional_end = p - 1;
			SKIP_SPACES(p);
			if ('(' != *p) {
				Err_SetParse(dep_str,
					"( has to be the next token for a conditional",
					start, p);
				goto internal_parse_depset_error;
			} else if(!isspace(*(p + 1)) || '\0' == p[1]) {
				Err_SetParse(dep_str,
					"( has to be followed by whitespace",
					start, p);
				goto internal_parse_depset_error;
			}
			p++;
			if(!(tmp = internal_parse_depset(dep_str, &p, has_conditionals,
				element_func, and_func, or_func, NULL, 0)))
				goto internal_parse_depset_error;

			if(tmp == Py_None) {
				Py_DECREF(tmp);
				Err_SetParse(dep_str, "empty payload", start, p);
				goto internal_parse_depset_error;

			} else if(!PyTuple_CheckExact(tmp)) {
				item = PyTuple_New(1);
				if(!tmp) {
					Py_DECREF(item);
					goto internal_parse_depset_error;
				}
				PyTuple_SET_ITEM(item, 0, tmp);
				tmp = item;
			}
			item = make_use_conditional(start, conditional_end, tmp);
			Py_DECREF(tmp);
			if(!item)
				goto internal_parse_depset_error;
			*has_conditionals = 1;

		} else if ('|' == *start) {
			if('|' != start[1] || !or_func) {
				Err_SetParse(dep_str,
					"stray |, or this depset doesn't support or blocks",
					NULL, NULL);
				goto internal_parse_depset_error;
			}

			if(p - start != 2) {
				Err_SetParse(dep_str, "|| must have space followed by a (",
					start, p);
				goto internal_parse_depset_error;
			}
			SKIP_SPACES(p);
			if ('(' != *p || (!isspace(*(p + 1)) && '\0' != p[1])) {
				Err_SetParse(dep_str,
					"( has to be the next token for a conditional",
					start, p);
				goto internal_parse_depset_error;
			}
			p++;
			if(!(tmp = internal_parse_depset(dep_str, &p, has_conditionals,
				element_func, and_func, or_func, NULL, 0)))
				goto internal_parse_depset_error;

			if(tmp == Py_None) {
				Py_DECREF(tmp);
				Err_SetParse(dep_str, "empty payload", start, p);
				goto internal_parse_depset_error;
			} else if (!PyTuple_CheckExact(tmp)) {
				item = tmp;
			} else {
				item = PyObject_CallObject(or_func, tmp);
				Py_DECREF(tmp);
				if(!item)
					goto internal_parse_depset_error;
			}
		} else {
			item = PyObject_CallFunction(element_func, "s#", start, p - start);
			if(!item) {
				Err_WrapException(dep_str, start, p);
				goto internal_parse_depset_error;
			}
			assert(!PyErr_Occurred());
		}

		// append it.
		if(item_count + item_size > tup_size) {
			while(tup_size < item_count + item_size)
				tup_size <<= 1;
			if(!restrictions) {
				// switch over.
				if(!(restrictions = PyTuple_New(tup_size))) {
					Py_DECREF(item);
					goto internal_parse_depset_error;
				}
				Py_ssize_t x = 0;
				for(; x < item_count; x++) {
					PyTuple_SET_ITEM(restrictions, x,
						stack_restricts[x]);
				}
			} else if(_PyTuple_Resize(&restrictions, tup_size)) {
				Py_DECREF(item);
				goto internal_parse_depset_error;
			}
			// now we're using restrictions.
		}
		if(restrictions) {
			if(item_size == 1) {
				PyTuple_SET_ITEM(restrictions, item_count++, item);
			} else {
				Py_ssize_t x = 0;
				for(; x < item_size; x++) {
					Py_INCREF(PyTuple_GET_ITEM(item, x));
					PyTuple_SET_ITEM(restrictions, item_count + x,
						PyTuple_GET_ITEM(item, x));
				}
				item_count += x;
				item_size = 1;
				// we're done with the tuple, already stole the items from it.
				Py_DECREF(item);
			}
		} else {
			if(item_size == 1) {
				stack_restricts[item_count++] = item;
			} else {
				Py_ssize_t x = 0;
				for(;x < item_size; x++) {
					Py_INCREF(PyTuple_GET_ITEM(item, x));
					stack_restricts[item_count + x] = PyTuple_GET_ITEM(item, x);
				}
				item_count += item_size;
				item_size = 1;
				// we're done with the tuple, already stole the items from it.
				Py_DECREF(item);
			}
		}
		SKIP_SPACES(p);
		start = p;
	}

	if(initial_frame) {
		if(*p) {
			Err_SetParse(dep_str, "stray ')' encountered", start, p);
			goto internal_parse_depset_error;
		}
	} else {
		if('\0' == *p) {
			Err_SetParse(dep_str, "depset lacks closure", *ptr, p);
			goto internal_parse_depset_error;
		}
		p++;
	}

	if(!restrictions) {
		if(item_count == 0) {
			restrictions = Py_None;
			Py_INCREF(restrictions);
		} else if(item_count == 1) {
			restrictions = stack_restricts[0];
		} else {
			restrictions = PyTuple_New(item_count);
			if(!restrictions)
				goto internal_parse_depset_error;
			Py_ssize_t x =0;
			for(;x < item_count; x++) {
				PyTuple_SET_ITEM(restrictions, x,
					stack_restricts[x]);
			}
		}
	} else if(item_count < tup_size) {
		if(_PyTuple_Resize(&restrictions, item_count))
			goto internal_parse_depset_error;
	}
	*ptr = p;
	return restrictions;

	internal_parse_depset_error:
	if(item_count) {
		if(!restrictions) {
			item_count--;
			while(item_count >= 0) {
				Py_DECREF(stack_restricts[item_count]);
				item_count--;
			}
		} else
			Py_DECREF(restrictions);
	}
	// dealloc.
	return NULL;
}
Exemple #15
0
static PyObject* _compose_go(PyComposeObject* self, PyObject* exc_type, PyObject* exc_value, PyObject* exc_tb) {
    Py_XINCREF(exc_type);
    Py_XINCREF(exc_value);
    Py_XINCREF(exc_tb);

    if(!self->started)
        self->started = 1;

    self->paused_on_step = 0;

    while(self->generators_top > self->generators_base) {
        PyObject* generator = *(self->generators_top - 1); // take over ownership from stack
        PyObject* response = NULL;
        PyObject* message = NULL;

        if(exc_type) { // exception
            if(PyErr_GivenExceptionMatches(exc_type, PyExc_GeneratorExit)) {
                PyObject* result = PyObject_CallMethod(generator, "close", NULL); // new ref

                if(result) {
                    Py_CLEAR(result);
                    PyErr_Restore(exc_type, exc_value, exc_tb); //steals refs
                    exc_type = exc_value = exc_tb = NULL;
                }

            } else
                response =
                    PyObject_CallMethod(generator, "throw", "OOO",
                                        exc_type,
                                        exc_value ? exc_value : Py_None,
                                        exc_tb ? exc_tb : Py_None); // new ref

            Py_CLEAR(exc_type);
            Py_CLEAR(exc_value);
            Py_CLEAR(exc_tb);

        } else { // normal message
            message = messages_next(self); // new ref
            response = PyObject_CallMethod(generator, "send", "(O)", message); // new ref
            Py_CLEAR(message);
        }
    
        if(response) { // normal response
            if(is_generator(response)) {

                if(generator_invalid(response)) {
                    PyErr_Fetch(&exc_type, &exc_value, &exc_tb); // new refs
                    Py_CLEAR(response);
                    continue;
                }

                if(!generators_push(self, response)) {
                    Py_CLEAR(response);
                    return NULL;
                }

                if(self->stepping) {
                    Py_CLEAR(response);
                    self->paused_on_step = 1;
                    Py_INCREF(&PyYield_Type);
                    return (PyObject*) &PyYield_Type;
                }
                messages_insert(self, Py_None);

            } else if(response != Py_None || messages_empty(self)) {
                self->expect_data = response == Py_None;
                return response;
            }

            Py_CLEAR(response);

        } else { // exception thrown
            *self->generators_top-- = NULL;
            PyErr_Fetch(&exc_type, &exc_value, &exc_tb); // new refs

            if(PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) {
                Py_CLEAR(exc_tb);
                Py_CLEAR(exc_type);
                int ok = _compose_handle_stopiteration(self, exc_value);
                Py_CLEAR(exc_value);

                if(!ok)
                    PyErr_Fetch(&exc_type, &exc_value, &exc_tb); // new refs
            }

            Py_CLEAR(generator);
        }
    }

    if(exc_type) {
        PyErr_Restore(exc_type, exc_value, exc_tb); // steals refs
        exc_type = exc_value = exc_tb = NULL;
        return NULL;
    }

    // if any messages are left, 'return' them by StopIteration
    int n = _messages_size(self);

    if(n) {
        PyObject* args = PyTuple_New(n); // new ref
        int i;

        for(i = 0; i < n; i++) {
            PyTuple_SetItem(args, i, messages_next(self)); // steals ref
        }

        PyObject* sie = PyObject_Call(PyExc_StopIteration, args, NULL); // new ref
        PyErr_SetObject(PyExc_StopIteration, sie);
        Py_DECREF(sie);
        Py_DECREF(args);

    } else
        PyErr_SetNone(PyExc_StopIteration);
    return NULL;
}
Exemple #16
0
// @object PyTRUSTEE|A dictionary representing a TRUSTEE structure.
// @prop int|TrusteeForm|
// @prop int|TrusteeType|
// @prop object|Identifier|Depends on the value of TrusteeForm (string or sid)
// @prop object|MultipleTrustee|default is None
// @prop object|MultipleTrusteeOperation|default is None
BOOL PyWinObject_AsTRUSTEE(PyObject *obtrustee, TRUSTEE_W *ptrustee)
{
	static char *trustee_items[]={"TrusteeForm","TrusteeType","Identifier","MultipleTrustee","MultipleTrusteeOperation",0};
	static char* err_msg="Trustee must be a dictionary containing {MultipleTrustee,MultipleTrusteeOperation,TrusteeForm,TrusteeType,Identifier}";
	BOOL bsuccess=TRUE;
	PyObject *obMultipleTrustee=Py_None, *obIdentifier=NULL;
	PyObject *trustee_dict=mapping_to_dict(obtrustee);
	if (trustee_dict==NULL)
		return FALSE;

	ZeroMemory(ptrustee,sizeof(TRUSTEE_W));
	ptrustee->MultipleTrusteeOperation=NO_MULTIPLE_TRUSTEE;
	ptrustee->pMultipleTrustee=NULL;
	PyObject *dummy_tuple=PyTuple_New(0);
	bsuccess=PyArg_ParseTupleAndKeywords(dummy_tuple, trustee_dict, "llO|Ol", trustee_items, 
		&ptrustee->TrusteeForm, &ptrustee->TrusteeType, &obIdentifier, &obMultipleTrustee, &ptrustee->MultipleTrusteeOperation);
	Py_DECREF(dummy_tuple);
	if (!bsuccess)
		PyErr_SetString(PyExc_TypeError,err_msg);
	else{
		ptrustee->MultipleTrusteeOperation=NO_MULTIPLE_TRUSTEE;
		ptrustee->pMultipleTrustee=NULL;
		/* Multiple trustees not currently supported according to SDK
		if ((obMultipleTrustee!=NULL)&&(obMultipleTrustee!=Py_None)){
			// hope nobody ever creates one that chains back to itself......
			ptrustee->pMultipleTrustee=new(TRUSTEE_W);
			bsuccess=(PyWinObject_AsTRUSTEE(obMultipleTrustee,ptrustee->pMultipleTrustee));
			}
		*/
		switch (ptrustee->TrusteeForm){
			case TRUSTEE_IS_SID:{
				if (!PyWinObject_AsSID(obIdentifier,(PSID *)&ptrustee->ptstrName,FALSE)){
					PyErr_SetString(PyExc_TypeError,"Identifier must be PySID object when TrusteeForm = TRUSTEE_IS_SID");
					bsuccess=FALSE;
					}
				break;
				}
			case TRUSTEE_IS_NAME:{
				if (!PyWinObject_AsWCHAR(obIdentifier,&ptrustee->ptstrName,FALSE)){
					PyErr_SetString(PyExc_TypeError,"Identifier must be string/unicode when TrusteeForm = TRUSTEE_IS_NAME");
					bsuccess=FALSE;
					}
				break;
				}
#if WINVER >= 0x0501
			case TRUSTEE_IS_OBJECTS_AND_SID:
			case TRUSTEE_IS_OBJECTS_AND_NAME:{
				// still need to add TRUSTEE_IS_OBJECTS_AND_SID and TRUSTEE_IS_OBJECTS_AND_NAME
				PyErr_SetString(PyExc_NotImplementedError, "TrusteeForm not yet supported");
				bsuccess=FALSE;
				break;
				}
#else
			#pragma message( \
				"NOTE: You are building with an early Platform SDK - not all" \
				"TRUSTEE operations on SIDs will be supported")
#endif // WINVER
			default:{
				PyErr_SetString(PyExc_ValueError, "Invalid value for TrusteeForm");
				bsuccess=FALSE;
				}
			}
		}
	Py_DECREF(trustee_dict);
	return bsuccess;
}
Exemple #17
0
PyObject* PythonTools::call( std::string _script, std::string _func,
                             PyObject* args )
{
    if ( !init )
    {
        gravUtil::logError( "PythonTools::call: PyTools not initialized\n" );
        return NULL;
    }

    PyObject *func, *result;

    func = PyDict_GetItemString( main_d, entryFunc.c_str() );

    if ( func == NULL )
    {
        PyErr_Print();
        gravUtil::logError( "PythonTools::call: Failed to load function "
                "\"%s\"\n", entryFunc.c_str() );
        return NULL;
    }
    Py_INCREF( func );
    if ( ! PyCallable_Check(func) )
    {
        PyErr_Print();
        gravUtil::logError( "PythonTools::call: Attribute \"%s\" is not "
                "callable\n", entryFunc.c_str() );
        Py_DECREF( func );
        return NULL;
    }

    PyObject* entryArgs;
    if ( args == NULL )
    {
        entryArgs = PyTuple_New( 2 );
        PyTuple_SetItem( entryArgs, 0, PyString_FromString( _script.c_str() ) );
        PyTuple_SetItem( entryArgs, 1, PyString_FromString( _func.c_str() ) );
    }
    else if ( PyTuple_Check( args ) )
    {
        int num = 2 + PyTuple_Size( args );
        entryArgs = PyTuple_New( num );
        PyTuple_SetItem( entryArgs, 0, PyString_FromString( _script.c_str() ) );
        PyTuple_SetItem( entryArgs, 1, PyString_FromString( _func.c_str() ) );
        for( int i = 0; i < PyTuple_Size( args ); i++ )
        {
            PyObject* temp = PyTuple_GetItem( args, i );
            Py_INCREF( temp );
            // because setitem will steal temp, and getitem returns borrowed, we
            // need to incref...?
            PyTuple_SetItem( entryArgs, i+2, temp );
        }
    }
    else
    {
        entryArgs = PyTuple_New( 3 );
        PyTuple_SetItem( entryArgs, 0, PyString_FromString( _script.c_str() ) );
        PyTuple_SetItem( entryArgs, 1, PyString_FromString( _func.c_str() ) );
        PyTuple_SetItem( entryArgs, 2, args );
    }

    result = PyObject_CallObject( func, entryArgs );

    if ( result == NULL )
    {
        PyErr_Print();
        gravUtil::logError( "PythonTools::call: Call failed\n" );
        Py_DECREF( func );
        Py_DECREF( entryArgs );
        return NULL;
    }

    Py_DECREF( func );
    Py_DECREF( entryArgs );
    return result;
}
Exemple #18
0
int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */

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

    if (pModule != NULL) {
        pFunc = PyDict_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}
Exemple #19
0
  /* "hello.pyx":4
 *     cdef int n = 18932808299
 *     cdef int m = n*n
 *     print("Hello %s! %s" % (name,m))             # <<<<<<<<<<<<<<
 */
  __pyx_t_1 = PyInt_FromLong(__pyx_v_m); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_2));
  __Pyx_INCREF(__pyx_v_name);
  PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_name);
  __Pyx_GIVEREF(__pyx_v_name);
  PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1);
  __Pyx_GIVEREF(__pyx_t_1);
  __pyx_t_1 = 0;
  __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_1));
  __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0;
  if (__Pyx_PrintOne(0, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;

  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_AddTraceback("hello.say_hello_to", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static PyMethodDef __pyx_methods[] = {
  {0, 0, 0, 0}
};

#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
    PyModuleDef_HEAD_INIT,
    __Pyx_NAMESTR("hello"),
    0, /* m_doc */
    -1, /* m_size */
    __pyx_methods /* m_methods */,
    NULL, /* m_reload */
    NULL, /* m_traverse */
    NULL, /* m_clear */
    NULL /* m_free */
};
#endif

static __Pyx_StringTabEntry __pyx_string_tab[] = {
  {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0},
  {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1},
  {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1},
  {&__pyx_n_s__hello, __pyx_k__hello, sizeof(__pyx_k__hello), 0, 0, 1, 1},
  {&__pyx_n_s__say_hello_to, __pyx_k__say_hello_to, sizeof(__pyx_k__say_hello_to), 0, 0, 1, 1},
  {0, 0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
  return 0;
}

static int __Pyx_InitCachedConstants(void) {
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants");
  __Pyx_RefNannyFinishContext();
  return 0;
}

static int __Pyx_InitGlobals(void) {
  if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  return 0;
  __pyx_L1_error:;
  return -1;
}

#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC inithello(void); /*proto*/
PyMODINIT_FUNC inithello(void)
#else
PyMODINIT_FUNC PyInit_hello(void); /*proto*/
PyMODINIT_FUNC PyInit_hello(void)
#endif
{
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannyDeclarations
  #if CYTHON_REFNANNY
  __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
  if (!__Pyx_RefNanny) {
      PyErr_Clear();
      __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
      if (!__Pyx_RefNanny)
          Py_FatalError("failed to import 'refnanny' module");
  }
  #endif
  __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_hello(void)");
  if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #ifdef __pyx_binding_PyCFunctionType_USED
  if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #endif
  /*--- Library function declarations ---*/
  /*--- Threads initialization code ---*/
  #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
  #ifdef WITH_THREAD /* Python build with threading support? */
  PyEval_InitThreads();
  #endif
  #endif
  /*--- Module creation code ---*/
  #if PY_MAJOR_VERSION < 3
  __pyx_m = Py_InitModule4(__Pyx_NAMESTR("hello"), __pyx_methods, 0, 0, PYTHON_API_VERSION);
  #else
  __pyx_m = PyModule_Create(&__pyx_moduledef);
  #endif
  if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  #if PY_MAJOR_VERSION < 3
  Py_INCREF(__pyx_m);
  #endif
  __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME));
  if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  /*--- Initialize various global constants etc. ---*/
  if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  if (__pyx_module_is_main_hello) {
    if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  }
  /*--- Builtin init code ---*/
  if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Constants init code ---*/
  if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Global init code ---*/
  /*--- Variable export code ---*/
  /*--- Function export code ---*/
  /*--- Type init code ---*/
  /*--- Type import code ---*/
  /*--- Variable import code ---*/
  /*--- Function import code ---*/
  /*--- Execution code ---*/

  /* "hello.pyx":1
 * def say_hello_to(name):             # <<<<<<<<<<<<<<
 *     cdef int n = 18932808299
 *     cdef int m = n*n
 */
  __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_5hello_say_hello_to, NULL, __pyx_n_s__hello); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  if (PyObject_SetAttr(__pyx_m, __pyx_n_s__say_hello_to, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_1));
  if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  if (__pyx_m) {
    __Pyx_AddTraceback("init hello", __pyx_clineno, __pyx_lineno, __pyx_filename);
    Py_DECREF(__pyx_m); __pyx_m = 0;
  } else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_ImportError, "init hello");
  }
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  #if PY_MAJOR_VERSION < 3
  return;
  #else
  return __pyx_m;
  #endif
}
Exemple #20
0
/* Delaunay implementation methyod.  If hide_qhull_errors is 1 then qhull error
 * messages are discarded; if it is 0 then they are written to stderr. */
static PyObject*
delaunay_impl(int npoints, const double* x, const double* y,
              int hide_qhull_errors)
{
    coordT* points = NULL;
    facetT* facet;
    int i, ntri, max_facet_id;
    FILE* error_file = NULL;    /* qhull expects a FILE* to write errors to. */
    int exitcode;               /* Value returned from qh_new_qhull(). */
    int* tri_indices = NULL;    /* Maps qhull facet id to triangle index. */
    int indices[3];
    int curlong, totlong;       /* Memory remaining after qh_memfreeshort. */
    PyObject* tuple;            /* Return tuple (triangles, neighbors). */
    const int ndim = 2;
    npy_intp dims[2];
    PyArrayObject* triangles = NULL;
    PyArrayObject* neighbors = NULL;
    int* triangles_ptr;
    int* neighbors_ptr;

    /* Allocate points. */
    points = (coordT*)malloc(npoints*ndim*sizeof(coordT));
    if (points == NULL) {
        PyErr_SetString(PyExc_MemoryError,
                        "Could not allocate points array in qhull.delaunay");
        goto error_before_qhull;
    }

    /* Prepare points array to pass to qhull. */
    for (i = 0; i < npoints; ++i) {
        points[2*i  ] = x[i];
        points[2*i+1] = y[i];
    }

    /* qhull expects a FILE* to write errors to. */
    if (hide_qhull_errors) {
        /* qhull errors are ignored by writing to OS-equivalent of /dev/null.
         * Rather than have OS-specific code here, instead it is determined by
         * setupext.py and passed in via the macro MPL_DEVNULL. */
        error_file = fopen(STRINGIFY(MPL_DEVNULL), "w");
        if (error_file == NULL) {
            PyErr_SetString(PyExc_RuntimeError,
                            "Could not open devnull in qhull.delaunay");
            goto error_before_qhull;
        }
    }
    else {
        /* qhull errors written to stderr. */
        error_file = stderr;
    }

    /* Perform Delaunay triangulation. */
    exitcode = qh_new_qhull(ndim, npoints, points, False,
                            "qhull d Qt Qbb Qc Qz", NULL, error_file);
    if (exitcode != qh_ERRnone) {
        PyErr_Format(PyExc_RuntimeError,
                     "Error in qhull Delaunay triangulation calculation: %s (exitcode=%d)%s",
                     qhull_error_msg[exitcode], exitcode,
                     hide_qhull_errors ? "; use python verbose option (-v) to see original qhull error." : "");
        goto error;
    }

    /* Split facets so that they only have 3 points each. */
    qh_triangulate();

    /* Determine ntri and max_facet_id.
       Note that libqhull uses macros to iterate through collections. */
    ntri = 0;
    FORALLfacets {
        if (!facet->upperdelaunay)
            ++ntri;
    }

    max_facet_id = qh facet_id - 1;

    /* Create array to map facet id to triangle index. */
    tri_indices = (int*)malloc((max_facet_id+1)*sizeof(int));
    if (tri_indices == NULL) {
        PyErr_SetString(PyExc_MemoryError,
                        "Could not allocate triangle map in qhull.delaunay");
        goto error;
    }

    /* Allocate python arrays to return. */
    dims[0] = ntri;
    dims[1] = 3;
    triangles = (PyArrayObject*)PyArray_SimpleNew(ndim, dims, PyArray_INT);
    if (triangles == NULL) {
        PyErr_SetString(PyExc_MemoryError,
                        "Could not allocate triangles array in qhull.delaunay");
        goto error;
    }

    neighbors = (PyArrayObject*)PyArray_SimpleNew(ndim, dims, PyArray_INT);
    if (neighbors == NULL) {
        PyErr_SetString(PyExc_MemoryError,
                        "Could not allocate neighbors array in qhull.delaunay");
        goto error;
    }

    triangles_ptr = (int*)PyArray_DATA(triangles);
    neighbors_ptr = (int*)PyArray_DATA(neighbors);

    /* Determine triangles array and set tri_indices array. */
    i = 0;
    FORALLfacets {
        if (!facet->upperdelaunay) {
            tri_indices[facet->id] = i++;
            get_facet_vertices(facet, indices);
            *triangles_ptr++ = (facet->toporient ? indices[0] : indices[2]);
            *triangles_ptr++ = indices[1];
            *triangles_ptr++ = (facet->toporient ? indices[2] : indices[0]);
        }
        else
            tri_indices[facet->id] = -1;
    }

    /* Determine neighbors array. */
    FORALLfacets {
        if (!facet->upperdelaunay) {
            get_facet_neighbours(facet, tri_indices, indices);
            *neighbors_ptr++ = (facet->toporient ? indices[2] : indices[0]);
            *neighbors_ptr++ = (facet->toporient ? indices[0] : indices[2]);
            *neighbors_ptr++ = indices[1];
        }
    }

    /* Clean up. */
    qh_freeqhull(!qh_ALL);
    qh_memfreeshort(&curlong, &totlong);
    if (curlong || totlong)
        PyErr_WarnEx(PyExc_RuntimeWarning,
                     "Qhull could not free all allocated memory", 1);
    if (hide_qhull_errors)
        fclose(error_file);
    free(tri_indices);
    free(points);

    tuple = PyTuple_New(2);
    PyTuple_SetItem(tuple, 0, (PyObject*)triangles);
    PyTuple_SetItem(tuple, 1, (PyObject*)neighbors);
    return tuple;

error:
    /* Clean up. */
    Py_XDECREF(triangles);
    Py_XDECREF(neighbors);
    qh_freeqhull(!qh_ALL);
    qh_memfreeshort(&curlong, &totlong);
    /* Don't bother checking curlong and totlong as raising error anyway. */
    if (hide_qhull_errors)
        fclose(error_file);
    free(tri_indices);

error_before_qhull:
    free(points);

    return NULL;
}
//-------------------------------------------------------------------------------------
PyObject* ScriptVector2::seq_slice(PyObject* self, Py_ssize_t startIndex, Py_ssize_t endIndex)
{
	if(startIndex < 0)
		startIndex = 0;

	if(endIndex > VECTOR_SIZE)
		endIndex = VECTOR_SIZE;

	if(endIndex < startIndex)
		endIndex = startIndex;

	ScriptVector2* sv = static_cast<ScriptVector2*>(self);
	Vector2& my_v = sv->getVector();
	PyObject* pyResult = NULL;

	int length = endIndex - startIndex;

	if (length == VECTOR_SIZE)
	{
		pyResult = sv;
		Py_INCREF(pyResult);
	}
	else
		switch(length)
		{
			case 0:
				pyResult = PyTuple_New(0);
				break;
			case 1:
				pyResult = PyTuple_New(1);
				PyTuple_SET_ITEM(pyResult, 0, PyFloat_FromDouble(sv->getVector()[static_cast<int>(startIndex)]));
				break;
			case 2:
			{
				Vector2 v;
				
				for(int i = startIndex; i < endIndex; ++i){
					v[i - static_cast<int>(startIndex)] = my_v[i];
				}

				pyResult = new ScriptVector2(v);
				break;
			}
			case 3:
			{
				Vector3 v;
				for (int i = startIndex; i < endIndex; ++i){
					v[i - static_cast<int>(startIndex)] = my_v[i];
				}

				pyResult = new ScriptVector3(v);
				break;
			}
			default:
				PyErr_Format(PyExc_IndexError, "Bad slice indexes [%d, %d] for Vector%d", startIndex, endIndex, VECTOR_SIZE);
				PyErr_PrintEx(0);
				break;
		}

	return pyResult;
}
Exemple #22
0
/* This function is called by the tp_dealloc handler to clear weak references.
 *
 * This iterates through the weak references for 'object' and calls callbacks
 * for those references which have one.  It returns when all callbacks have
 * been attempted.
 */
void
PyObject_ClearWeakRefs(PyObject *object)
{
    PyWeakReference **list;

    if (object == NULL
        || !PyType_SUPPORTS_WEAKREFS(Py_TYPE(object))
        || object->ob_refcnt != 0) {
        PyErr_BadInternalCall();
        return;
    }
    list = GET_WEAKREFS_LISTPTR(object);
    /* Remove the callback-less basic and proxy references */
    if (*list != NULL && (*list)->wr_callback == NULL) {
        clear_weakref(*list);
        if (*list != NULL && (*list)->wr_callback == NULL)
            clear_weakref(*list);
    }
    if (*list != NULL) {
        PyWeakReference *current = *list;
        Py_ssize_t count = _PyWeakref_GetWeakrefCount(current);
        int restore_error = PyErr_Occurred() ? 1 : 0;
        PyObject *err_type, *err_value, *err_tb;

        if (restore_error)
            PyErr_Fetch(&err_type, &err_value, &err_tb);
        if (count == 1) {
            PyObject *callback = current->wr_callback;

            current->wr_callback = NULL;
            clear_weakref(current);
            if (callback != NULL) {
                if (current->ob_refcnt > 0)
                    handle_callback(current, callback);
                Py_DECREF(callback);
            }
        }
        else {
            PyObject *tuple;
            Py_ssize_t i = 0;

            tuple = PyTuple_New(count * 2);
            if (tuple == NULL) {
                if (restore_error)
                    PyErr_Fetch(&err_type, &err_value, &err_tb);
                return;
            }

            for (i = 0; i < count; ++i) {
                PyWeakReference *next = current->wr_next;

                if (current->ob_refcnt > 0)
                {
                    Py_INCREF(current);
                    PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
                    PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
                }
                else {
                    Py_DECREF(current->wr_callback);
                }
                current->wr_callback = NULL;
                clear_weakref(current);
                current = next;
            }
            for (i = 0; i < count; ++i) {
                PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1);

                /* The tuple may have slots left to NULL */
                if (callback != NULL) {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i * 2);
                    handle_callback((PyWeakReference *)item, callback);
                }
            }
            Py_DECREF(tuple);
        }
        if (restore_error)
            PyErr_Restore(err_type, err_value, err_tb);
    }
}
Exemple #23
0
static PyObject*
_create_dict_from_event (SDL_Event *event, int release)
{
    PyObject *val = NULL;
    PyObject *dict = PyDict_New ();
    if (!dict)
        return NULL;

    if (event->type >= SDL_USEREVENT && event->type < SDL_NUMEVENTS)
    {
        if (event->user.code == PYGAME_USEREVENT_CODE &&
                event->user.data1 == (void*)PYGAME_USEREVENT)
        {
            /* It comes from pygame, it goes to pygame. */
            PyObject *vdict = (PyObject*) event->user.data2;
            if (PyDict_Update (dict, vdict) == -1)
                goto failed;
            if (release)
            {
                Py_DECREF (vdict);
            }
            return dict;
        }
        else
        {
            /* It comes from some SDL stuff, it goes to pygame. */
            if (!_set_item (dict, "code", PyInt_FromLong (event->user.code)))
                goto failed;
#if PY_VERSION_HEX >= 0x03010000
            if (!_set_item (dict, "data1",
                            PyCapsule_New (event->user.data1, "data1", NULL)))
                goto failed;
            if (!_set_item (dict, "data2",
                            PyCapsule_New (event->user.data2, "data2", NULL)))
                goto failed;
#else
            if (!_set_item (dict, "data1",
                            PyCObject_FromVoidPtr (event->user.data1, NULL)))
                goto failed;
            if (!_set_item (dict, "data2",
                            PyCObject_FromVoidPtr (event->user.data2, NULL)))
                goto failed;
#endif
        }
        return dict;
    }

    switch (event->type)
    {
    case SDL_ACTIVEEVENT:
        if (!_set_item (dict, "gain", PyInt_FromLong (event->active.gain)))
            goto failed;
        if (!_set_item (dict, "state", PyInt_FromLong (event->active.state)))
            goto failed;
        break;

    case SDL_KEYDOWN:
    case SDL_KEYUP:
        if (!_set_item (dict, "state", PyInt_FromLong (event->key.state)))
            goto failed;
        if (!_set_item (dict, "scancode",
                        PyInt_FromLong (event->key.keysym.scancode)))
            goto failed;
        if (!_set_item (dict, "key",
                        PyLong_FromUnsignedLong (event->key.keysym.sym)))
            goto failed;
        if (!_set_item (dict, "sym",
                        PyLong_FromUnsignedLong (event->key.keysym.sym)))
            goto failed;
        if (!_set_item (dict, "mod",
                        PyLong_FromUnsignedLong (event->key.keysym.mod)))
            goto failed;
        /* if SDL_EnableUNICODE() == 0, unicode will be a 0 character */
        if (!_set_item (dict, "unicode",
                        PyUnicode_FromOrdinal (event->key.keysym.unicode)))
            goto failed;
        break;

    case SDL_MOUSEMOTION:
        if (!_set_item (dict, "state", PyInt_FromLong (event->motion.state)))
            goto failed;
        if (!_set_item (dict, "x", PyInt_FromLong (event->motion.x)))
            goto failed;
        if (!_set_item (dict, "y", PyInt_FromLong (event->motion.y)))
            goto failed;
        if (!_set_item (dict, "xrel", PyInt_FromLong (event->motion.xrel)))
            goto failed;
        if (!_set_item (dict, "yrel", PyInt_FromLong (event->motion.yrel)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->motion.x, event->motion.y);
        if (!val)
            goto failed;
        if (!_set_item (dict, "pos", val))
            goto failed;
        val = Py_BuildValue ("(ii)", event->motion.xrel, event->motion.yrel);
        if (!val)
            goto failed;
        if (!_set_item (dict, "rel", val))
            goto failed;
        val = PyTuple_New (3);
        if (!val)
            return NULL;
        PyTuple_SET_ITEM (val, 0,
                          PyBool_FromLong (event->motion.state & SDL_BUTTON(1)));
        PyTuple_SET_ITEM (val, 1,
                          PyBool_FromLong (event->motion.state & SDL_BUTTON(2)));
        PyTuple_SET_ITEM (val, 2,
                          PyBool_FromLong (event->motion.state & SDL_BUTTON(3)));
        if (!_set_item (dict, "buttons", val))
            goto failed;
        break;

    case SDL_MOUSEBUTTONDOWN:
    case SDL_MOUSEBUTTONUP:
        if (!_set_item (dict, "button", PyInt_FromLong (event->button.button)))
            goto failed;
        if (!_set_item (dict, "x", PyInt_FromLong (event->button.x)))
            goto failed;
        if (!_set_item (dict, "y", PyInt_FromLong (event->button.y)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->button.x, event->button.y);
        if (!val)
            goto failed;
        if (!_set_item (dict, "pos", val))
            goto failed;
        if (!_set_item (dict, "state", PyInt_FromLong (event->button.state)))
            goto failed;
        break;

    case SDL_JOYAXISMOTION:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jaxis.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jaxis.which)))
            goto failed;
        if (!_set_item (dict, "axis", PyInt_FromLong (event->jaxis.axis)))
            goto failed;
        if (!_set_item (dict, "value", PyInt_FromLong (event->jaxis.value)))
            goto failed;
        break;

    case SDL_JOYBALLMOTION:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jball.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jball.which)))
            goto failed;
        if (!_set_item (dict, "ball", PyInt_FromLong (event->jball.ball)))
            goto failed;
        if (!_set_item (dict, "xrel", PyInt_FromLong (event->jball.xrel)))
            goto failed;
        if (!_set_item (dict, "yrel", PyInt_FromLong (event->jball.yrel)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->jball.xrel, event->jball.yrel);
        if (!val)
            goto failed;
        if (!_set_item (dict, "rel", val))
            goto failed;
        break;

    case SDL_JOYHATMOTION:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jhat.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jhat.which)))
            goto failed;
        if (!_set_item (dict, "hat", PyInt_FromLong (event->jhat.hat)))
            goto failed;
        if (!_set_item (dict, "value", PyInt_FromLong (event->jhat.value)))
            goto failed;
        break;

    case SDL_JOYBUTTONDOWN:
    case SDL_JOYBUTTONUP:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jbutton.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jbutton.which)))
            goto failed;
        if (!_set_item (dict, "button", PyInt_FromLong (event->jbutton.button)))
            goto failed;
        if (!_set_item (dict, "state", PyInt_FromLong (event->jbutton.state)))
            goto failed;
        break;

    case SDL_VIDEORESIZE:
        if (!_set_item (dict, "w", PyInt_FromLong (event->resize.w)))
            goto failed;
        if (!_set_item (dict, "h", PyInt_FromLong (event->resize.h)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->resize.w, event->resize.h);
        if (!val)
            goto failed;
        if (!_set_item (dict, "size", val))
            goto failed;
        break;

    case SDL_SYSWMEVENT:
#if defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI)
        if (!_set_item (dict, "hwnd",
                        PyInt_FromLong ((long) event->syswm.msg->hwnd)))
            goto failed;
        if (!_set_item (dict, "msg", PyInt_FromLong (event->syswm.msg->msg)))
            goto failed;
        if (!_set_item (dict, "wparam",
                        PyInt_FromLong (event->syswm.msg->wParam)))
            goto failed;
        if (!_set_item (dict, "lparam",
                        PyInt_FromLong (event-> syswm.msg->lParam)))
            goto failed;
#elif defined(SDL_VIDEO_DRIVER_X11)
        if (!_set_item (dict,  "event", Text_FromUTF8AndSize
                        ((char*) &(event->syswm.msg->event.xevent), sizeof (XEvent))))
            goto failed;
#endif
        break;
    case SDL_QUIT:
        break;
    case SDL_VIDEOEXPOSE:
        break;
    default:
        break;
    }

    return dict;

failed:
    Py_XDECREF (val);
    Py_XDECREF (dict);
    return NULL;
}
Exemple #24
0
PyObject *ServiceType_Sigalrm(PyObject *self, PyObject *ignore) {
  PyObject *args = PyTuple_New(1);
  PyTuple_SET_ITEM(args, 0, PyString_FromString("a"));
  return ServiceType_Control(self, args);
}
Exemple #25
0
PyObject *pv_getter_pvval(pvobject * self, void *closure)
{

	if (self->chanId == NULL || ca_state(self->chanId) != cs_conn
	    || self->buff == NULL) {
		PYCA_ERR("pvval: indef");
	}

	int i;
	dbr_plaintype data;
	int dim = ca_element_count(self->chanId);
	chtype type = xxx_ca_field_type(self->chanId);
	PyObject *returnvalue = NULL;

	/* build the returned tuple */
	if (dim > 1)
		returnvalue = PyTuple_New(dim);

	switch (type) {
	case DBR_STRING:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyString_FromString(data.s));
		} else
			returnvalue =
			    PyString_FromString(((struct dbr_time_string *)
						 self->buff)->value);
		break;
	case DBR_DOUBLE:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyFloat_FromDouble(data.d));
		} else
			returnvalue =
			    PyFloat_FromDouble(((struct dbr_time_double *)
						self->buff)->value);
		break;
	case DBR_LONG:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyLong_FromLong(data.l));
		} else
			returnvalue = PyLong_FromLong(((struct dbr_time_long *)
						       self->buff)->value);
		break;
	case DBR_SHORT:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyInt_FromLong(data.i));
		} else
			returnvalue = PyInt_FromLong(((struct dbr_time_short *)
						      self->buff)->value);
		break;
	case DBR_CHAR:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyInt_FromLong(data.c));
		} else
			returnvalue = PyInt_FromLong(((struct dbr_time_char *)
						      self->buff)->value);
		break;
	case DBR_ENUM:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyInt_FromLong(data.e));
		} else
			returnvalue = PyInt_FromLong(((struct dbr_time_enum *)
						      self->buff)->value);
		break;
	case DBR_FLOAT:
		if (dim > 1)
			for (i = 0; i < dim; i++) {
				ca_module_utilsextract(self->buff,
						       xxx_ca_field_type
						       (self->chanId), i,
						       &data);
				PyTuple_SetItem(returnvalue, i,
						PyFloat_FromDouble(data.f));
		} else
			returnvalue =
			    PyFloat_FromDouble(((struct dbr_time_float *)
						self->buff)->value);
		break;
	default:
		PYCA_ERR("pvval: invalid");
		break;
	}

	return returnvalue;
}
Exemple #26
0
PyObject*
_PyCode_ConstantKey(PyObject *op)
{
    PyObject *key;

    /* Py_None and Py_Ellipsis are singleton */
    if (op == Py_None || op == Py_Ellipsis
       || PyLong_CheckExact(op)
       || PyBool_Check(op)
       || PyBytes_CheckExact(op)
       || PyUnicode_CheckExact(op)
          /* code_richcompare() uses _PyCode_ConstantKey() internally */
       || PyCode_Check(op)) {
        key = PyTuple_Pack(2, Py_TYPE(op), op);
    }
    else if (PyFloat_CheckExact(op)) {
        double d = PyFloat_AS_DOUBLE(op);
        /* all we need is to make the tuple different in either the 0.0
         * or -0.0 case from all others, just to avoid the "coercion".
         */
        if (d == 0.0 && copysign(1.0, d) < 0.0)
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
        else
            key = PyTuple_Pack(2, Py_TYPE(op), op);
    }
    else if (PyComplex_CheckExact(op)) {
        Py_complex z;
        int real_negzero, imag_negzero;
        /* For the complex case we must make complex(x, 0.)
           different from complex(x, -0.) and complex(0., y)
           different from complex(-0., y), for any x and y.
           All four complex zeros must be distinguished.*/
        z = PyComplex_AsCComplex(op);
        real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
        imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
        /* use True, False and None singleton as tags for the real and imag
         * sign, to make tuples different */
        if (real_negzero && imag_negzero) {
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
        }
        else if (imag_negzero) {
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
        }
        else if (real_negzero) {
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
        }
        else {
            key = PyTuple_Pack(2, Py_TYPE(op), op);
        }
    }
    else if (PyTuple_CheckExact(op)) {
        Py_ssize_t i, len;
        PyObject *tuple;

        len = PyTuple_GET_SIZE(op);
        tuple = PyTuple_New(len);
        if (tuple == NULL)
            return NULL;

        for (i=0; i < len; i++) {
            PyObject *item, *item_key;

            item = PyTuple_GET_ITEM(op, i);
            item_key = _PyCode_ConstantKey(item);
            if (item_key == NULL) {
                Py_DECREF(tuple);
                return NULL;
            }

            PyTuple_SET_ITEM(tuple, i, item_key);
        }

        key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
        Py_DECREF(tuple);
    }
    else if (PyFrozenSet_CheckExact(op)) {
        Py_ssize_t pos = 0;
        PyObject *item;
        Py_hash_t hash;
        Py_ssize_t i, len;
        PyObject *tuple, *set;

        len = PySet_GET_SIZE(op);
        tuple = PyTuple_New(len);
        if (tuple == NULL)
            return NULL;

        i = 0;
        while (_PySet_NextEntry(op, &pos, &item, &hash)) {
            PyObject *item_key;

            item_key = _PyCode_ConstantKey(item);
            if (item_key == NULL) {
                Py_DECREF(tuple);
                return NULL;
            }

            assert(i < len);
            PyTuple_SET_ITEM(tuple, i, item_key);
            i++;
        }
        set = PyFrozenSet_New(tuple);
        Py_DECREF(tuple);
        if (set == NULL)
            return NULL;

        key = PyTuple_Pack(3, Py_TYPE(op), op, set);
        Py_DECREF(set);
        return key;
    }
    else {
        /* for other types, use the object identifier as a unique identifier
         * to ensure that they are seen as unequal. */
        PyObject *obj_id = PyLong_FromVoidPtr(op);
        if (obj_id == NULL)
            return NULL;

        key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
        Py_DECREF(obj_id);
    }
    return key;
}
Exemple #27
0
static PyObject *
code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
    int argcount;
    int kwonlyargcount;
    int nlocals;
    int stacksize;
    int flags;
    PyObject *co = NULL;
    PyObject *code;
    PyObject *consts;
    PyObject *names, *ournames = NULL;
    PyObject *varnames, *ourvarnames = NULL;
    PyObject *freevars = NULL, *ourfreevars = NULL;
    PyObject *cellvars = NULL, *ourcellvars = NULL;
    PyObject *filename;
    PyObject *name;
    int firstlineno;
    PyObject *lnotab;

    if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
                          &argcount, &kwonlyargcount,
                              &nlocals, &stacksize, &flags,
                          &code,
                          &PyTuple_Type, &consts,
                          &PyTuple_Type, &names,
                          &PyTuple_Type, &varnames,
                          &filename, &name,
                          &firstlineno, &lnotab,
                          &PyTuple_Type, &freevars,
                          &PyTuple_Type, &cellvars))
        return NULL;

    if (argcount < 0) {
        PyErr_SetString(
            PyExc_ValueError,
            "code: argcount must not be negative");
        goto cleanup;
    }

    if (kwonlyargcount < 0) {
        PyErr_SetString(
            PyExc_ValueError,
            "code: kwonlyargcount must not be negative");
        goto cleanup;
    }
    if (nlocals < 0) {
        PyErr_SetString(
            PyExc_ValueError,
            "code: nlocals must not be negative");
        goto cleanup;
    }

    ournames = validate_and_copy_tuple(names);
    if (ournames == NULL)
        goto cleanup;
    ourvarnames = validate_and_copy_tuple(varnames);
    if (ourvarnames == NULL)
        goto cleanup;
    if (freevars)
        ourfreevars = validate_and_copy_tuple(freevars);
    else
        ourfreevars = PyTuple_New(0);
    if (ourfreevars == NULL)
        goto cleanup;
    if (cellvars)
        ourcellvars = validate_and_copy_tuple(cellvars);
    else
        ourcellvars = PyTuple_New(0);
    if (ourcellvars == NULL)
        goto cleanup;

    co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
                                nlocals, stacksize, flags,
                                code, consts, ournames, ourvarnames,
                                ourfreevars, ourcellvars, filename,
                                name, firstlineno, lnotab);
  cleanup:
    Py_XDECREF(ournames);
    Py_XDECREF(ourvarnames);
    Py_XDECREF(ourfreevars);
    Py_XDECREF(ourcellvars);
    return co;
}
Exemple #28
0
static
PyObject* NRT_adapt_ndarray_to_python(arystruct_t* arystruct, int ndim,
                                      int writeable, PyArray_Descr *descr) {
    PyArrayObject *array;
    MemInfoObject *miobj = NULL;
    PyObject *args;
    npy_intp *shape, *strides;
    int flags = 0;

    if (!PyArray_DescrCheck(descr)) {
        PyErr_Format(PyExc_TypeError,
                     "expected dtype object, got '%.200s'",
                     Py_TYPE(descr)->tp_name);
        return NULL;
    }

    if (arystruct->parent) {
        PyObject *obj = try_to_return_parent(arystruct, ndim, descr);
        if (obj)
            return obj;
    }

    if (arystruct->meminfo) {
        /* wrap into MemInfoObject */
        miobj = PyObject_New(MemInfoObject, &MemInfoType);
        args = PyTuple_New(1);
        /* SETITEM steals reference */
        PyTuple_SET_ITEM(args, 0, PyLong_FromVoidPtr(arystruct->meminfo));
        if (MemInfo_init(miobj, args, NULL)) {
            return NULL;
        }
        Py_DECREF(args);
    }

    shape = arystruct->shape_and_strides;
    strides = shape + ndim;
    Py_INCREF((PyObject *) descr);
    array = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type, descr, ndim,
                                                   shape, strides, arystruct->data,
                                                   flags, (PyObject *) miobj);

    if (array == NULL)
        return NULL;

    /* Set writable */
#if NPY_API_VERSION >= 0x00000007
    if (writeable) {
        PyArray_ENABLEFLAGS(array, NPY_ARRAY_WRITEABLE);
    }
    else {
        PyArray_CLEARFLAGS(array, NPY_ARRAY_WRITEABLE);
    }
#else
    if (writeable) {
        array->flags |= NPY_WRITEABLE;
    }
    else {
        array->flags &= ~NPY_WRITEABLE;
    }
#endif

    if (miobj) {
        /* Set the MemInfoObject as the base object */
#if NPY_API_VERSION >= 0x00000007
        if (-1 == PyArray_SetBaseObject(array,
                                        (PyObject *) miobj))
        {
            Py_DECREF(array);
            Py_DECREF(miobj);
            return NULL;
        }
#else
        PyArray_BASE(array) = (PyObject *) miobj;
#endif

    }
    return (PyObject *) array;
}
Exemple #29
0
static PyObject *__pyx_f_6ssdeep_6ssdeep_hash_file(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_filename = 0;
  PyObject *__pyx_v_res;
  PyObject *__pyx_r;
  char (*__pyx_1);
  PyObject *__pyx_2 = 0;
  int __pyx_3;
  PyObject *__pyx_4 = 0;
  PyObject *__pyx_5 = 0;
  PyObject *__pyx_6 = 0;
  static char *__pyx_argnames[] = {"filename",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_filename)) return 0;
  Py_INCREF(__pyx_v_self);
  Py_INCREF(__pyx_v_filename);
  __pyx_v_res = Py_None; Py_INCREF(__pyx_v_res);

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":33 */
  __pyx_1 = PyString_AsString(__pyx_v_filename); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
  __pyx_2 = PyString_FromString(fuzzy_hash(__pyx_1)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
  Py_DECREF(__pyx_v_res);
  __pyx_v_res = __pyx_2;
  __pyx_2 = 0;

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":35 */
  __pyx_3 = PySequence_Contains(__pyx_v_res, __pyx_k2p); if (__pyx_3 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; goto __pyx_L1;}
  if (__pyx_3) {

    /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":36 */
    __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_SsdeepException); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    __pyx_4 = PyObject_GetAttr(__pyx_v_res, __pyx_n_replace); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    Py_INCREF(__pyx_k3p);
    PyTuple_SET_ITEM(__pyx_5, 0, __pyx_k3p);
    Py_INCREF(__pyx_k4p);
    PyTuple_SET_ITEM(__pyx_5, 1, __pyx_k4p);
    __pyx_6 = PyObject_CallObject(__pyx_4, __pyx_5); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    Py_DECREF(__pyx_5); __pyx_5 = 0;
    __Pyx_Raise(__pyx_2, __pyx_6, 0);
    Py_DECREF(__pyx_2); __pyx_2 = 0;
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    goto __pyx_L2;
  }
  /*else*/ {
    Py_INCREF(__pyx_v_res);
    __pyx_r = __pyx_v_res;
    goto __pyx_L0;
  }
  __pyx_L2:;

  __pyx_r = Py_None; Py_INCREF(__pyx_r);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_5);
  Py_XDECREF(__pyx_6);
  __Pyx_AddTraceback("ssdeep.ssdeep.hash_file");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_res);
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_filename);
  return __pyx_r;
}
static PyObject* RangeIterator_next(RangeIterator  *iter)
{

    VERBOSE("%s", "Entering RangeIterator_next...");
    if (iter->_db == 0 || !leveldb_iter_valid(iter->_iterator)) {
        RangeIterator_clean(iter);
        return 0;
    }
    if (iter->_to != NULL) {
        const char *tkey; /* c style key */
        size_t key_len; /* key length */
        if (iter->_iterator != NULL) {
            tkey = leveldb_iter_key(iter->_iterator, &key_len);
        } else return NULL;

        int limit_len = (strlen(iter->_to) > key_len) ? key_len: strlen(iter->_to);

        int c = memcmp(iter->_to, tkey, limit_len);
        if (!(0 <= c)) {
            VERBOSE("%s", "Invalid iterator................................");
            RangeIterator_clean(iter);
            return 0;
        }
    }


    // get key and (optional) value
    const char *ckey; /* c style key */
    size_t key_len; /* key length */
    if (iter->_iterator != NULL) {
        ckey = leveldb_iter_key(iter->_iterator, &key_len);
    } else return NULL;

    VERBOSE("The key is %s, length is %d", ckey, key_len);
    PyObject* key = PyString_FromStringAndSize(ckey, key_len);
    PyObject* value = 0;
    PyObject* ret = key;

    if (key == 0) return 0;

    const char *cvalue; /* c style value */
    size_t value_len; /* value length */
    if (iter->_iterator != NULL) {
        cvalue = leveldb_iter_value(iter->_iterator, &value_len);
    } else return NULL;
    if (iter->_include_value) {
        value = PyString_FromStringAndSize(cvalue, value_len);

        if (value == 0) {
            Py_XDECREF(key);
            return 0;
        }
    }

    // key/value pairs are returned as 2-tuples
    if (value != NULL) {
        ret = PyTuple_New(2);

        if (ret == 0) {
            Py_DECREF(key);
            Py_XDECREF(value);
            return 0;
        }

        PyTuple_SET_ITEM(ret, 0, key);
        PyTuple_SET_ITEM(ret, 1, value);
    }

    // get next value
    leveldb_iter_next(iter->_iterator);

    // return k/v pair or single key
    return ret;
}