Esempio n. 1
0
PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args)
{
    PyObject* key = args;
    pysqlite_Node* node;
    pysqlite_Node* ptr;
    PyObject* data;

    node = (pysqlite_Node*)PyDict_GetItem(self->mapping, key);
    if (node) {
        /* an entry for this key already exists in the cache */

        /* increase usage counter of the node found */
        if (node->count < LONG_MAX) {
            node->count++;
        }

        /* if necessary, reorder entries in the cache by swapping positions */
        if (node->prev && node->count > node->prev->count) {
            ptr = node->prev;

            while (ptr->prev && node->count > ptr->prev->count) {
                ptr = ptr->prev;
            }

            if (node->next) {
                node->next->prev = node->prev;
            } else {
                self->last = node->prev;
            }
            if (node->prev) {
                node->prev->next = node->next;
            }
            if (ptr->prev) {
                ptr->prev->next = node;
            } else {
                self->first = node;
            }

            node->next = ptr;
            node->prev = ptr->prev;
            if (!node->prev) {
                self->first = node;
            }
            ptr->prev = node;
        }
    } else {
        /* There is no entry for this key in the cache, yet. We'll insert a new
         * entry in the cache, and make space if necessary by throwing the
         * least used item out of the cache. */

        if (PyDict_Size(self->mapping) == self->size) {
            if (self->last) {
                node = self->last;

                if (PyDict_DelItem(self->mapping, self->last->key) != 0) {
                    return NULL;
                }

                if (node->prev) {
                    node->prev->next = NULL;
                }
                self->last = node->prev;
                node->prev = NULL;

                Py_DECREF(node);
            }
        }

        data = PyObject_CallFunction(self->factory, "O", key);

        if (!data) {
            return NULL;
        }

        node = pysqlite_new_node(key, data);
        if (!node) {
            return NULL;
        }
        node->prev = self->last;

        Py_DECREF(data);

        if (PyDict_SetItem(self->mapping, key, (PyObject*)node) != 0) {
            Py_DECREF(node);
            return NULL;
        }

        if (self->last) {
            self->last->next = node;
        } else {
            self->first = node;
        }
        self->last = node;
    }

    Py_INCREF(node->data);
    return node->data;
}
Esempio n. 2
0
char* sendAndRecieve(const char* url) {
	Py_Initialize();

	PyObject *pArgs, *pValue, *pFunc;
	PyObject *pGlobal = PyDict_New();
	PyObject *pLocal;

	PyRun_SimpleString("import types,sys");

	//create the new module in python
	PyRun_SimpleString("mymod = types.ModuleType(\"mymod\")");

	//add it to the sys modules so that it can be imported by other modules
	PyRun_SimpleString("sys.modules[\"mymod\"] = mymod");

	//import sys so that path will be available in mymod so that other/newly created modules can be imported
	PyRun_SimpleString("exec 'import sys' in mymod.__dict__");

	//import it to the current python interpreter
	PyObject *pNewMod = PyImport_Import(PyString_FromString("mymod"));

	//Get the dictionary object from my module so I can pass this to PyRun_String
	pLocal = PyModule_GetDict(pNewMod);

	//import urllib2 to global namespace
	PyMapping_SetItemString(pGlobal, "urllib2",
			PyImport_ImportModule("urllib2"));

	//Define my function in the newly created module
	pValue =
			PyRun_String("def get(url):\n\treturn urllib2.urlopen(url).read()\n", Py_file_input, pGlobal, pLocal);
	Py_DECREF(pValue);

	//Get a pointer to the function I just defined
	pFunc = PyObject_GetAttrString(pNewMod, "get");
	if (pFunc == NULL) {
#ifdef DEBUG
		PyErr_Print();
#endif
		return NULL;
	}

	//Build a tuple to hold my arguments (just the number 4 in this case)
	pArgs = PyTuple_New(1);
	pValue = PyString_FromString(url);
	PyTuple_SetItem(pArgs, 0, pValue);

	//Call my function, passing it the number four
	pValue = PyObject_CallObject(pFunc, pArgs);
	if (pValue == NULL) {
#ifdef DEBUG
		PyErr_Print();
#endif
		return NULL;
	}

	Py_DECREF(pArgs);
	char* result = PyString_AsString(pValue);
	if (result == NULL) {
#ifdef DEBUG
		PyErr_Print();
#endif
		return NULL;
	}

	Py_DECREF(pValue);
	Py_XDECREF(pFunc);
	Py_DECREF(pNewMod);
	Py_Finalize();

	return result;
}
Esempio n. 3
0
void XBPyThread::Process()
{
  CLog::Log(LOGDEBUG,"Python thread: start processing");

  int m_Py_file_input = Py_file_input;

  // get the global lock
  PyEval_AcquireLock();
  PyThreadState* state = Py_NewInterpreter();
  if (!state)
  {
    PyEval_ReleaseLock();
    CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!");
    return;
  }
  // swap in my thread state
  PyThreadState_Swap(state);

  m_pExecuter->InitializeInterpreter();

  CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source);

  // get path from script file name and add python path's
  // this is used for python so it will search modules from script path first
  CStdString scriptDir;
  CUtil::GetDirectory(_P(m_source), scriptDir);
  CUtil::RemoveSlashAtEnd(scriptDir);
  CStdString path = scriptDir;

  // add on any addon modules the user has installed
  ADDON::VECADDONS addons;
  ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons);
  for (unsigned int i = 0; i < addons.size(); ++i)
    path += PY_PATH_SEP + _P(addons[i]->LibPath());

  // and add on whatever our default path is
  path += PY_PATH_SEP;

#if (defined USE_EXTERNAL_PYTHON)
  {
    // we want to use sys.path so it includes site-packages
    // if this fails, default to using Py_GetPath
    PyObject *sysMod(PyImport_ImportModule("sys")); // must call Py_DECREF when finished
    PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete
    PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete

    if( pathObj && PyList_Check(pathObj) )
    {
      for( int i = 0; i < PyList_Size(pathObj); i++ )
      {
        PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete
        if( e && PyString_Check(e) )
        {
            path += PyString_AsString(e); // returns internal data, don't delete or modify
            path += PY_PATH_SEP;
        }
      }
    }
    else
    {
      path += Py_GetPath();
    }
    Py_DECREF(sysMod); // release ref to sysMod
  }
#else
  path += Py_GetPath();
#endif

  // set current directory and python's path.
  if (m_argv != NULL)
    PySys_SetArgv(m_argc, m_argv);

  CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str());

  PySys_SetPath((char *)path.c_str());

  CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str());

  PyObject* module = PyImport_AddModule((char*)"__main__");
  PyObject* moduleDict = PyModule_GetDict(module);

  // when we are done initing we store thread state so we can be aborted
  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  // we need to check if we was asked to abort before we had inited
  bool stopping = false;
  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = state;
    stopping = m_stopping;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  xbp_chdir(scriptDir.c_str());

  if (!stopping)
  {
    if (m_type == 'F')
    {
      // run script from file
      FILE *fp = fopen_utf8(_P(m_source).c_str(), "r");
      if (fp)
      {
        PyObject *f = PyString_FromString(_P(m_source).c_str());
        PyDict_SetItemString(moduleDict, "__file__", f);
        Py_DECREF(f);
        PyRun_File(fp, _P(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict);
        fclose(fp);
      }
      else
        CLog::Log(LOGERROR, "%s not found!", m_source);
    }
    else
    {
      //run script
      PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict);
    }
  }

  if (!PyErr_Occurred())
    CLog::Log(LOGINFO, "Scriptresult: Success");
  else if (PyErr_ExceptionMatches(PyExc_SystemExit))
    CLog::Log(LOGINFO, "Scriptresult: Aborted");
  else
  {
    PyObject* exc_type;
    PyObject* exc_value;
    PyObject* exc_traceback;
    PyObject* pystring;
    pystring = NULL;

    PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
    if (exc_type == 0 && exc_value == 0 && exc_traceback == 0)
    {
      CLog::Log(LOGINFO, "Strange: No Python exception occured");
    }
    else
    {
      if (exc_type != NULL && (pystring = PyObject_Str(exc_type)) != NULL && (PyString_Check(pystring)))
      {
          PyObject *tracebackModule;

          CLog::Log(LOGINFO, "-->Python script returned the following error<--");
          CLog::Log(LOGERROR, "Error Type: %s", PyString_AsString(PyObject_Str(exc_type)));
          if (PyObject_Str(exc_value))
            CLog::Log(LOGERROR, "Error Contents: %s", PyString_AsString(PyObject_Str(exc_value)));

          tracebackModule = PyImport_ImportModule((char*)"traceback");
          if (tracebackModule != NULL)
          {
            PyObject *tbList, *emptyString, *strRetval;

            tbList = PyObject_CallMethod(tracebackModule, (char*)"format_exception", (char*)"OOO", exc_type, exc_value == NULL ? Py_None : exc_value, exc_traceback == NULL ? Py_None : exc_traceback);
            emptyString = PyString_FromString("");
            strRetval = PyObject_CallMethod(emptyString, (char*)"join", (char*)"O", tbList);

            CLog::Log(LOGERROR, "%s", PyString_AsString(strRetval));

            Py_DECREF(tbList);
            Py_DECREF(emptyString);
            Py_DECREF(strRetval);
            Py_DECREF(tracebackModule);
          }
          CLog::Log(LOGINFO, "-->End of Python script error report<--");
      }
      else
      {
        pystring = NULL;
        CLog::Log(LOGINFO, "<unknown exception type>");
      }

      CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
      if (pDlgToast)
      {
        CStdString desc;
        CStdString path;
        CStdString script;
        CUtil::Split(m_source, path, script);
        if (script.Equals("default.py"))
        {
          CStdString path2;
          CUtil::RemoveSlashAtEnd(path);
          CUtil::Split(path, path2, script);
        }

        desc.Format(g_localizeStrings.Get(2100), script);
        pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc);
      }
    }

    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value); // caller owns all 3
    Py_XDECREF(exc_traceback); // already NULL'd out
    Py_XDECREF(pystring);
  }

  PyObject *m = PyImport_AddModule((char*)"xbmc");
  if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
    CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested");

  // make sure all sub threads have finished
  for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;)
  {
    if(s == state)
    {
      s = s->next;
      continue;
    }
    if(old != s)
    {
      CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id);
      old = s;
    }
    Py_BEGIN_ALLOW_THREADS
    Sleep(100);
    Py_END_ALLOW_THREADS
    s = state->interp->tstate_head;
  }

  // pending calls must be cleared out
  PyXBMC_ClearPendingCalls(state);

  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = NULL;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  m_pExecuter->DeInitializeInterpreter();

  Py_EndInterpreter(state);
  PyThreadState_Swap(NULL);

  PyEval_ReleaseLock();
}
Esempio n. 4
0
//-------------------------------------------------------------------------------------
void Base::addPersistentsDataToStream(uint32 flags, MemoryStream* s)
{
	std::vector<ENTITY_PROPERTY_UID> log;

	// 再将base中存储属性取出
	PyObject* pydict = PyObject_GetAttrString(this, "__dict__");

	// 先将celldata中的存储属性取出
	ScriptDefModule::PROPERTYDESCRIPTION_MAP& propertyDescrs = pScriptModule_->getPersistentPropertyDescriptions();
	ScriptDefModule::PROPERTYDESCRIPTION_MAP::const_iterator iter = propertyDescrs.begin();

	if(pScriptModule_->hasCell())
	{
		addPositionAndDirectionToStream(*s);
	}

	for(; iter != propertyDescrs.end(); ++iter)
	{
		PropertyDescription* propertyDescription = iter->second;
		std::vector<ENTITY_PROPERTY_UID>::const_iterator finditer = 
			std::find(log.begin(), log.end(), propertyDescription->getUType());

		if(finditer != log.end())
			continue;

		const char* attrname = propertyDescription->getName();
		if(propertyDescription->isPersistent() && (flags & propertyDescription->getFlags()) > 0)
		{
			PyObject *key = PyUnicode_FromString(attrname);

			if(cellDataDict_ != NULL && PyDict_Contains(cellDataDict_, key) > 0)
			{
				PyObject* pyVal = PyDict_GetItemString(cellDataDict_, attrname);
				if(!propertyDescription->getDataType()->isSameType(pyVal))
				{
					CRITICAL_MSG(fmt::format("{}::addPersistentsDataToStream: {} persistent({}) type(curr_py: {} != {}) error.\n",
						this->scriptName(), this->id(), attrname, (pyVal ? pyVal->ob_type->tp_name : "unknown"), propertyDescription->getDataType()->getName()));
				}
				else
				{
					(*s) << propertyDescription->getUType();
					log.push_back(propertyDescription->getUType());
					propertyDescription->addPersistentToStream(s, pyVal);
					DEBUG_PERSISTENT_PROPERTY("addCellPersistentsDataToStream", attrname);
				}
			}
			else if(PyDict_Contains(pydict, key) > 0)
			{
				PyObject* pyVal = PyDict_GetItem(pydict, key);
				if(!propertyDescription->getDataType()->isSameType(pyVal))
				{
					CRITICAL_MSG(fmt::format("{}::addPersistentsDataToStream: {} persistent({}) type(curr_py: {} != {}) error.\n",
						this->scriptName(), this->id(), attrname, (pyVal ? pyVal->ob_type->tp_name : "unknown"), propertyDescription->getDataType()->getName()));
				}
				else
				{
	    			(*s) << propertyDescription->getUType();
					log.push_back(propertyDescription->getUType());
	    			propertyDescription->addPersistentToStream(s, pyVal);
					DEBUG_PERSISTENT_PROPERTY("addBasePersistentsDataToStream", attrname);
				}
			}
			else
			{
				WARNING_MSG(fmt::format("{}::addPersistentsDataToStream: {} not found Persistent({}), use default values!\n",
					this->scriptName(), this->id(), attrname));

				(*s) << propertyDescription->getUType();
				log.push_back(propertyDescription->getUType());
				propertyDescription->addPersistentToStream(s, NULL);
			}

			Py_DECREF(key);
		}

		SCRIPT_ERROR_CHECK();
	}

	Py_XDECREF(pydict);
	SCRIPT_ERROR_CHECK();
}
Esempio n. 5
0
static PyObject * oscillAnglesOfHKLs(PyObject * self, PyObject * args)
{
  PyArrayObject *hkls, *rMat_c, *bMat,
		*vInv_s, *beamVec, *etaVec;
  PyFloatObject *chi, *wavelength;
  PyArrayObject *oangs0, *oangs1;
  PyObject *return_tuple;

  int dhkls, drc, dbm, dvi, dbv, dev;
  npy_intp npts, dims[2];

  double *hkls_Ptr, chi_d,
	 *rMat_c_Ptr, *bMat_Ptr, wavelen_d,
	 *vInv_s_Ptr, *beamVec_Ptr, *etaVec_Ptr;
  double *oangs0_Ptr, *oangs1_Ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOOOOOO",
			 &hkls, &chi,
			 &rMat_c, &bMat, &wavelength,
			 &vInv_s, &beamVec, &etaVec)) return(NULL);
  if ( hkls    == NULL || chi == NULL ||
       rMat_c  == NULL || bMat == NULL || wavelength == NULL ||
       vInv_s  == NULL || beamVec == NULL || etaVec == NULL ) return(NULL);

  /* Verify shape of input arrays */
  dhkls = PyArray_NDIM(hkls);
  drc   = PyArray_NDIM(rMat_c);
  dbm   = PyArray_NDIM(bMat);
  dvi   = PyArray_NDIM(vInv_s);
  dbv   = PyArray_NDIM(beamVec);
  dev   = PyArray_NDIM(etaVec);
  assert( dhkls == 2 && drc == 2 && dbm == 2 &&
	  dvi   == 1 && dbv == 1 && dev == 1);

  /* Verify dimensions of input arrays */
  npts = PyArray_DIMS(hkls)[0];

  assert( PyArray_DIMS(hkls)[1]    == 3 );
  assert( PyArray_DIMS(rMat_c)[0]  == 3 && PyArray_DIMS(rMat_c)[1] == 3 );
  assert( PyArray_DIMS(bMat)[0]    == 3 && PyArray_DIMS(bMat)[1]   == 3 );
  assert( PyArray_DIMS(vInv_s)[0]  == 6 );
  assert( PyArray_DIMS(beamVec)[0] == 3 );
  assert( PyArray_DIMS(etaVec)[0]  == 3 );

  /* Allocate arrays for return values */
  dims[0] = npts; dims[1] = 3;
  oangs0 = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);
  oangs1 = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);

  /* Grab data pointers into various arrays */
  hkls_Ptr    = (double*)PyArray_DATA(hkls);

  chi_d       = PyFloat_AsDouble((PyObject*)chi);
  wavelen_d   = PyFloat_AsDouble((PyObject*)wavelength);

  rMat_c_Ptr  = (double*)PyArray_DATA(rMat_c);
  bMat_Ptr    = (double*)PyArray_DATA(bMat);

  vInv_s_Ptr  = (double*)PyArray_DATA(vInv_s);

  beamVec_Ptr = (double*)PyArray_DATA(beamVec);
  etaVec_Ptr  = (double*)PyArray_DATA(etaVec);

  oangs0_Ptr  = (double*)PyArray_DATA(oangs0);
  oangs1_Ptr  = (double*)PyArray_DATA(oangs1);

  /* Call the computational routine */
  oscillAnglesOfHKLs_cfunc(npts, hkls_Ptr, chi_d,
			   rMat_c_Ptr, bMat_Ptr, wavelen_d,
			   vInv_s_Ptr, beamVec_Ptr, etaVec_Ptr,
			   oangs0_Ptr, oangs1_Ptr);

  /* Build and return the list data structure */
  return_tuple = Py_BuildValue("OO",oangs0,oangs1);
  Py_DECREF(oangs1);
  Py_DECREF(oangs0);

  return return_tuple;
}
Esempio n. 6
0
PyObject *Client_gets(PyClient *self, PyObject *args)
{
  //[ ] def gets(self, key, default = None):

  char *pKey;
  size_t cbKey;
  char *pData;
  size_t cbData;
  UINT64 cas;
  int flags;

  if (!PyArg_ParseTuple (args, "s#", &pKey, &cbKey))
  {
    return NULL;
  }

  self->client->getsBegin();

  self->client->getKeyWrite(pKey, cbKey);
  self->client->getFlush();

  bool bError = false;

  if (!self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError))
  {
    if (bError)
    {
      if (!PyErr_Occurred())
      {
        return PyErr_Format(PyExc_RuntimeError, "umemcache: %s", self->client->getError());
      }
      return NULL;
    }

    Py_RETURN_NONE;
  }



  PyObject *otuple = PyTuple_New(3);
  PyObject *ovalue = PyString_FromStringAndSize(pData, cbData);
  PyObject *oflags = PyInt_FromLong(flags);
  PyObject *ocas = PyLong_FromUnsignedLongLong(cas);

  PyTuple_SET_ITEM(otuple, 0, ovalue);
  PyTuple_SET_ITEM(otuple, 1, oflags);
  PyTuple_SET_ITEM(otuple, 2, ocas);

  while (self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError));

  if (bError)
  {
    Py_DECREF(otuple);

    if (!PyErr_Occurred())
    {
      return PyErr_Format(PyExc_RuntimeError, "umemcache: %s", self->client->getError());
    }

    return NULL;
  }

  return otuple;
}
Esempio n. 7
0
KX_VertexProxy::~KX_VertexProxy()
{
	/* see bug [#27071] */
	Py_DECREF(m_mesh->GetProxy());
}
Esempio n. 8
0
FunctionMacro::~FunctionMacro()
{
    Py_DECREF(m_callable);
    Py_DECREF((PyObject*)m_preprocessor);
}
Esempio n. 9
0
int
set_str_list(
    const char* propname,
    PyObject* value,
    Py_ssize_t len,
    Py_ssize_t maxlen,
    char (*dest)[72]) {

  PyObject*  str      = NULL;
  Py_ssize_t input_len;
  Py_ssize_t i        = 0;

  if (check_delete(propname, value)) {
    return -1;
  }

  if (maxlen == 0) {
    maxlen = 68;
  }

  if (!PySequence_Check(value)) {
    PyErr_Format(
        PyExc_TypeError,
        "'%s' must be a sequence of strings",
        propname);
    return -1;
  }

  if (PySequence_Size(value) != len) {
    PyErr_Format(
        PyExc_ValueError,
        "len(%s) must be %u",
        propname,
        (unsigned int)len);
    return -1;
  }

  /* We go through the list twice, once to verify that the list is
     in the correct format, and then again to do the data copy.  This
     way, we won't partially copy the contents and then throw an
     exception. */
  for (i = 0; i < len; ++i) {
    str = PySequence_GetItem(value, i);
    if (str == NULL) {
      return -1;
    }

    if (!(PyBytes_CheckExact(str) || PyUnicode_CheckExact(str))) {
      PyErr_Format(
          PyExc_TypeError,
          "'%s' must be a sequence of bytes or strings",
          propname);
      Py_DECREF(str);
      return -1;
    }

    input_len = PySequence_Size(str);
    if (input_len > maxlen) {
      PyErr_Format(
          PyExc_TypeError,
          "Each entry in '%s' must be less than %u characters",
          propname, (unsigned int)maxlen);
      Py_DECREF(str);
      return -1;
    } else if (input_len == -1) {
      Py_DECREF(str);
      return -1;
    }

    Py_DECREF(str);
  }

  for (i = 0; i < len; ++i) {
    str = PySequence_GetItem(value, i);
    if (str == NULL) {
      /* Theoretically, something has gone really wrong here, since
         we've already verified the list. */
      PyErr_Clear();
      PyErr_Format(
          PyExc_RuntimeError,
          "Input values have changed underneath us.  Something is seriously wrong.");
      return -1;
    }

    if (set_string(propname, str, dest[i], maxlen)) {
      PyErr_Clear();
      PyErr_Format(
          PyExc_RuntimeError,
          "Input values have changed underneath us.  Something is seriously wrong.");
      Py_DECREF(str);
      return -1;
    }

    Py_DECREF(str);
  }

  return 0;
}
Esempio n. 10
0
// This implements the pyqtSlot decorator.
PyObject *qpycore_pyqtslot(PyObject *args, PyObject *kwds)
{
    const char *name_str = 0;
    PyObject *res_obj = 0;
    int revision = 0;
    static const char *kwlist[] = {"name", "result", "revision", 0};

    static PyObject *no_args = 0;

    if (!no_args)
    {
        no_args = PyTuple_New(0);

        if (!no_args)
            return 0;
    }

    if (!PyArg_ParseTupleAndKeywords(no_args, kwds, "|sOi:pyqtSlot",
            const_cast<char **>(kwlist), &name_str, &res_obj, &revision))
        return 0;

    Chimera::Signature *parsed_sig = Chimera::parse(args, name_str,
            "a pyqtSlot type argument");

    if (!parsed_sig)
        return 0;

    // Sticking the revision here is an awful hack, but it saves creating
    // another data structure wrapped in a capsule.
    parsed_sig->revision = revision;

    // Parse any result type.
    if (res_obj)
    {
        parsed_sig->result = Chimera::parse(res_obj);

        if (!parsed_sig->result)
        {
            Chimera::raiseParseException(res_obj, "a pyqtSlot result");
            delete parsed_sig;
            return 0;
        }
    }

    // Wrap the parsed signature in a Python object.
    PyObject *sig_obj = Chimera::Signature::toPyObject(parsed_sig);

    if (!sig_obj)
        return 0;

    // Create the decorator function itself.  We stash the arguments in "self".
    // This may be an abuse, but it seems to be Ok.
    static PyMethodDef deco_method = {
#if PY_VERSION_HEX >= 0x02050000
        "_deco", decorator, METH_O, 0
#else
        const_cast<char *>("_deco"), decorator, METH_O, 0
#endif
    };

    PyObject *obj = PyCFunction_New(&deco_method, sig_obj);
    Py_DECREF(sig_obj);

    return obj;
}
Esempio n. 11
0
/**
 * pyglib_gerror_exception_check:
 * @error: a standard GLib GError ** output parameter
 *
 * Checks to see if a GError exception has been raised, and if so
 * translates the python exception to a standard GLib GError.  If the
 * raised exception is not a GError then PyErr_Print() is called.
 *
 * Returns: 0 if no exception has been raised, -1 if it is a
 * valid glib.GError, -2 otherwise.
 */
gboolean
pyglib_gerror_exception_check(GError **error)
{
    PyObject *type, *value, *traceback;
    PyObject *py_message, *py_domain, *py_code;
    const char *bad_gerror_message;

    PyErr_Fetch(&type, &value, &traceback);
    if (type == NULL)
        return 0;
    PyErr_NormalizeException(&type, &value, &traceback);
    if (value == NULL) {
        PyErr_Restore(type, value, traceback);
        PyErr_Print();
        return -2;
    }
    if (!value ||
	!PyErr_GivenExceptionMatches(type,
				     (PyObject *) _PyGLib_API->gerror_exception)) {
        PyErr_Restore(type, value, traceback);
        PyErr_Print();
        return -2;
    }
    Py_DECREF(type);
    Py_XDECREF(traceback);

    py_message = PyObject_GetAttrString(value, "message");
    if (!py_message || !PYGLIB_PyUnicode_Check(py_message)) {
        bad_gerror_message = "gi._glib.GError instances must have a 'message' string attribute";
        goto bad_gerror;
    }

    py_domain = PyObject_GetAttrString(value, "domain");
    if (!py_domain || !PYGLIB_PyUnicode_Check(py_domain)) {
        bad_gerror_message = "gi._glib.GError instances must have a 'domain' string attribute";
        Py_DECREF(py_message);
        goto bad_gerror;
    }

    py_code = PyObject_GetAttrString(value, "code");
    if (!py_code || !PYGLIB_PyLong_Check(py_code)) {
        bad_gerror_message = "gi._glib.GError instances must have a 'code' int attribute";
        Py_DECREF(py_message);
        Py_DECREF(py_domain);
        goto bad_gerror;
    }

    g_set_error(error, g_quark_from_string(PYGLIB_PyUnicode_AsString(py_domain)),
                PYGLIB_PyLong_AsLong(py_code), "%s", PYGLIB_PyUnicode_AsString(py_message));

    Py_DECREF(py_message);
    Py_DECREF(py_code);
    Py_DECREF(py_domain);
    return -1;

bad_gerror:
    Py_DECREF(value);
    g_set_error(error, g_quark_from_static_string("pyglib"), 0, "%s", bad_gerror_message);
    PyErr_SetString(PyExc_ValueError, bad_gerror_message);
    PyErr_Print();
    return -2;
}
Esempio n. 12
0
// This is the decorator function that saves the C++ signature as a function
// attribute.
static PyObject *decorator(PyObject *self, PyObject *f)
{
    Chimera::Signature *parsed_sig = Chimera::Signature::fromPyObject(self);
    const QByteArray &sig = parsed_sig->signature;

    // Use the function name if there isn't already one.
    if (sig.startsWith('('))
    {
        // Get the function's name.
        PyObject *nobj = PyObject_GetAttr(f, qpycore_dunder_name);

        if (!nobj)
            return 0;

        PyObject *ascii_obj = nobj;
        const char *ascii = sipString_AsASCIIString(&ascii_obj);
        Py_DECREF(nobj);

        if (!ascii)
            return 0;

        parsed_sig->signature.prepend(ascii);
        parsed_sig->py_signature.prepend(ascii);
        Py_DECREF(ascii_obj);
    }

    // See if the function has already been decorated.
    PyObject *decorations = PyObject_GetAttr(f, qpycore_dunder_pyqtsignature);
    int rc;

    if (decorations)
    {
        // Insert the new decoration at the head of the existing ones so that
        // the list order matches the order they appear in the script.
        rc = PyList_Insert(decorations, 0, self);
    }
    else
    {
        PyErr_Clear();

        decorations = PyList_New(1);

        if (!decorations)
            return 0;

        Py_INCREF(self);
        PyList_SetItem(decorations, 0, self);

        // Save the new decoration.
        rc = PyObject_SetAttr(f, qpycore_dunder_pyqtsignature, decorations);
    }

    Py_DECREF(decorations);

    if (rc < 0)
        return 0;

    // Return the function.
    Py_INCREF(f);
    return f;
}
Esempio n. 13
0
static PyObject *
Net_train(Net *self, PyObject *args, PyObject *kwds)
{
    const char *text;
    Py_ssize_t text_len = 0;
    PyObject *target_class;
    int target_index;
    float leakage = -1;
    uint ignore_start = 0;

    static char *kwlist[] = {"text",                 /* s# */
                             "target_class",         /* O | */
                             "leakage",              /* f  */
                             "ignore_start",         /* I  */
                             NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s#O|fI", kwlist,
            &text,
            &text_len,
            &target_class,
            &leakage,
            &ignore_start
        )){
        return NULL;
    }
    if (text_len < 2 + ignore_start){
        return PyErr_Format(PyExc_ValueError, "The text is not long enough");
    }
    PyObject *target_py_int = PyDict_GetItem(self->class_name_lut, target_class);
    if (target_py_int == NULL){
        PyObject *r = PyObject_Repr(target_class);
        PyObject *e = PyErr_Format(PyExc_KeyError, "unknown class: %s",
                                   PyString_AS_STRING(r));
        Py_DECREF(r);
        return e;
    }
    target_index = PyInt_AsLong(target_py_int);

    if (leakage < 0){
        leakage = -leakage / self->n_classes;
    }
    if (ignore_start){
        rnn_char_multitext_spin(self->net, (u8*)text, ignore_start,
            self->images.input_ppm, self->images.error_ppm,
            self->images.periodic_pgm_dump_string, self->periodic_pgm_period);
        text += ignore_start;
        text_len -= ignore_start;
    }

    rnn_char_multitext_train(self->net, (u8*)text, text_len,
        self->alphabet->alphabet->len, target_index, leakage,
        self->report, self->learning_method, self->momentum,
        self->batch_size, self->images.input_ppm, self->images.error_ppm,
        self->images.periodic_pgm_dump_string, self->periodic_pgm_period);
    if (self->report){
        RnnCharProgressReport *r = self->report;
        char *s = PyString_AsString(target_class);
        printf("%8d t%.1f %d/s %s\n", self->net->generation,
            r->training_entropy, (int)r->per_second, s);
    }
    return Py_BuildValue("");
}
Esempio n. 14
0
// originally copied from Py3's builtin_next()
static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) {
    PyObject* next;
    iternextfunc iternext = Py_TYPE(iterator)->tp_iternext;
#if CYTHON_COMPILING_IN_CPYTHON
    if (unlikely(!iternext)) {
#else
    if (unlikely(!iternext) || unlikely(!PyIter_Check(iterator))) {
#endif
        PyErr_Format(PyExc_TypeError,
            "%.200s object is not an iterator", Py_TYPE(iterator)->tp_name);
        return NULL;
    }
    next = iternext(iterator);
    if (likely(next))
        return next;
#if CYTHON_COMPILING_IN_CPYTHON
#if PY_VERSION_HEX >= 0x03010000 || (PY_MAJOR_VERSION < 3 && PY_VERSION_HEX >= 0x02070000)
    if (unlikely(iternext == &_PyObject_NextNotImplemented))
        return NULL;
#endif
#endif
    if (defval) {
        PyObject* exc_type = PyErr_Occurred();
        if (exc_type) {
            if (unlikely(exc_type != PyExc_StopIteration) &&
                    !PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))
                return NULL;
            PyErr_Clear();
        }
        Py_INCREF(defval);
        return defval;
    }
    if (!PyErr_Occurred())
        PyErr_SetNone(PyExc_StopIteration);
    return NULL;
}

/////////////// IterFinish.proto ///////////////

static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/

/////////////// IterFinish ///////////////

// When PyIter_Next(iter) has returned NULL in order to signal termination,
// this function does the right cleanup and returns 0 on success.  If it
// detects an error that occurred in the iterator, it returns -1.

static CYTHON_INLINE int __Pyx_IterFinish(void) {
#if CYTHON_COMPILING_IN_CPYTHON
    PyThreadState *tstate = PyThreadState_GET();
    PyObject* exc_type = tstate->curexc_type;
    if (unlikely(exc_type)) {
        if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) {
            PyObject *exc_value, *exc_tb;
            exc_value = tstate->curexc_value;
            exc_tb = tstate->curexc_traceback;
            tstate->curexc_type = 0;
            tstate->curexc_value = 0;
            tstate->curexc_traceback = 0;
            Py_DECREF(exc_type);
            Py_XDECREF(exc_value);
            Py_XDECREF(exc_tb);
            return 0;
        } else {
            return -1;
        }
    }
    return 0;
#else
    if (unlikely(PyErr_Occurred())) {
        if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) {
            PyErr_Clear();
            return 0;
        } else {
            return -1;
        }
    }
    return 0;
#endif
}
Esempio n. 15
0
static PyObject* spherematch_kdtree_rangesearch(PyObject* self,
                                                PyObject* args) {
    double* X;
    PyObject* rtn;
    npy_intp dims[1];
    long i;
    kdtree_t* kd;
    int D, N;
    PyObject* pyO;
    PyObject* pyI;
    PyObject* pyInds;
    PyObject* pyDists = NULL;
    PyArray_Descr* dtype = PyArray_DescrFromType(NPY_DOUBLE);
    int req = NPY_C_CONTIGUOUS | NPY_ALIGNED | NPY_NOTSWAPPED
        | NPY_ELEMENTSTRIDES;
    double radius;
    kdtree_qres_t* res;
    int getdists, sortdists;
    int opts;

    if (!PyArg_ParseTuple(args, "lOdii", &i, &pyO, &radius,
                          &getdists, &sortdists)) {
        PyErr_SetString(PyExc_ValueError, "need five args: kdtree identifier (int), query point (numpy array of floats), radius (double), get distances (int 0/1), sort distances (int 0/1)");
        return NULL;
    }
    // Nasty!
    kd = (kdtree_t*)i;
    D = kd->ndim;

    if (sortdists) {
        getdists = 1;
    }

    Py_INCREF(dtype);
    pyI = PyArray_FromAny(pyO, dtype, 1, 1, req, NULL);
    if (!pyI) {
        PyErr_SetString(PyExc_ValueError, "Failed to convert query point array to np array of float");
        Py_XDECREF(dtype);
        return NULL;
    }
    N = (int)PyArray_DIM(pyI, 0);
    if (N != D) {
        PyErr_SetString(PyExc_ValueError, "Query point must have size == dimension of tree");
        Py_DECREF(pyI);
        Py_DECREF(dtype);
        return NULL;
    }

    X = PyArray_DATA(pyI);

    opts = 0;
    if (getdists) {
        opts |= KD_OPTIONS_COMPUTE_DISTS;
    }
    if (sortdists) {
        opts |= KD_OPTIONS_SORT_DISTS;
    }

    res = kdtree_rangesearch_options(kd, X, radius*radius, opts);
    N = res->nres;
    dims[0] = N;
    res->inds = realloc(res->inds, N * sizeof(uint32_t));
    pyInds = PyArray_SimpleNewFromData(1, dims, NPY_UINT32, res->inds);
    res->inds = NULL;

    if (getdists) {
        res->sdists = realloc(res->sdists, N * sizeof(double));
        pyDists = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, res->sdists);
        res->sdists = NULL;
    }

    kdtree_free_query(res);

    Py_DECREF(pyI);
    Py_DECREF(dtype);
    if (getdists) {
        rtn = Py_BuildValue("(OO)", pyInds, pyDists);
        Py_DECREF(pyDists);
    } else {
        rtn = Py_BuildValue("O", pyInds);
    }
    Py_DECREF(pyInds);
    return rtn;
}
Esempio n. 16
0
int
set_pscards(
    /*@unused@*/ const char* propname,
    PyObject* value,
    struct pscard** ps,
    int *nps,
    int *npsmax) {

  PyObject*   subvalue  = NULL;
  Py_ssize_t  i         = 0;
  Py_ssize_t  size      = 0;
  int         ival      = 0;
  int         mval      = 0;
  const char* strvalue  = 0;
  void*       newmem    = NULL;

  if (!PySequence_Check(value))
    return -1;
  size = PySequence_Size(value);
  if (size > 0x7fffffff) {
    /* Must be a 32-bit size */
    return -1;
  }

  if (size > (Py_ssize_t)*npsmax) {
    newmem = malloc(sizeof(struct pscard) * size);
    if (newmem == NULL) {
      PyErr_SetString(PyExc_MemoryError, "Could not allocate memory.");
      return -1;
    }
    free(*ps);
    *ps = newmem;
    *npsmax = (int)size;
  }

  /* Verify the entire list for correct types first, so we don't have
     to undo anything copied into the canonical array. */
  for (i = 0; i < size; ++i) {
    subvalue = PySequence_GetItem(value, i);
    if (subvalue == NULL) {
      return -1;
    }
    if (!PyArg_ParseTuple(subvalue, "iis", &ival, &mval, &strvalue)) {
      Py_DECREF(subvalue);
      return -1;
    }
    Py_DECREF(subvalue);
  }

  for (i = 0; i < size; ++i) {
    subvalue = PySequence_GetItem(value, i);
    if (subvalue == NULL) {
      return -1;
    }
    if (!PyArg_ParseTuple(subvalue, "iis", &ival, &mval, &strvalue)) {
      Py_DECREF(subvalue);
      return -1;
    }
    Py_DECREF(subvalue);

    (*ps)[i].i = ival;
    (*ps)[i].m = mval;
    strncpy((*ps)[i].value, strvalue, 72);
    (*ps)[i].value[71] = '\0';
    (*nps) = (int)(i + 1);
  }

  return 0;
}
Esempio n. 17
0
static PyObject* spherematch_nn2(PyObject* self, PyObject* args) {
  int i, j, NY, N;
  long p1, p2;
  kdtree_t *kd1, *kd2;
  npy_intp dims[1];
  PyObject* I;
  PyObject* J;
  PyObject* dist2s;
  PyObject* counts = NULL;
  int *pi;
  int *pj;
  int *pc = NULL;
  double *pd;
  double rad;
  anbool notself;
  anbool docount;
  int* tempinds;
  int* tempcount = NULL;
  int** ptempcount = NULL;
  double* tempd2;
  PyObject* rtn;

  // So that ParseTuple("b") with a C "anbool" works
  assert(sizeof(anbool) == sizeof(unsigned char));

  if (!PyArg_ParseTuple(args, "lldbb", &p1, &p2, &rad, &notself, &docount)) {
    PyErr_SetString(PyExc_ValueError, "need five args: two kdtree identifiers (ints), search radius, notself (bool) and docount (bool)");
    return NULL;
  }
  // Nasty!
  kd1 = (kdtree_t*)p1;
  kd2 = (kdtree_t*)p2;

  // quick check for no-overlap case
  if (kdtree_node_node_mindist2_exceeds(kd1, 0, kd2, 0, rad*rad)) {
    // allocate empty return arrays
    dims[0] = 0;
    I = PyArray_SimpleNew(1, dims, NPY_INT);
    J = PyArray_SimpleNew(1, dims, NPY_INT);
    dist2s = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
	if (docount) {
	  counts = PyArray_SimpleNew(1, dims, NPY_INT);
	  rtn = Py_BuildValue("(OOOO)", I, J, dist2s, counts);
	  Py_DECREF(counts);
	} else {
	  rtn = Py_BuildValue("(OOO)", I, J, dist2s);
	}
    Py_DECREF(I);
    Py_DECREF(J);
    Py_DECREF(dist2s);
    return rtn;
  }

  NY = kdtree_n(kd2);

  tempinds = (int*)malloc(NY * sizeof(int));
  tempd2 = (double*)malloc(NY * sizeof(double));
  if (docount) {
	tempcount = (int*)calloc(NY, sizeof(int));
    ptempcount = &tempcount;
  }

  dualtree_nearestneighbour(kd1, kd2, rad*rad, &tempd2, &tempinds, ptempcount, notself);

  // count number of matches
  N = 0;
  for (i=0; i<NY; i++)
    if (tempinds[i] != -1)
      N++;

  // allocate return arrays
  dims[0] = N;
  I = PyArray_SimpleNew(1, dims, NPY_INT);
  J = PyArray_SimpleNew(1, dims, NPY_INT);
  dist2s = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
  pi = PyArray_DATA(I);
  pj = PyArray_DATA(J);
  pd = PyArray_DATA(dist2s);
  if (docount) {
    counts = PyArray_SimpleNew(1, dims, NPY_INT);
    pc = PyArray_DATA(counts);
  }

  j = 0;
  for (i=0; i<NY; i++) {
    if (tempinds[i] == -1)
      continue;
    pi[j] = kdtree_permute(kd1, tempinds[i]);
    pj[j] = kdtree_permute(kd2, i);
    pd[j] = tempd2[i];
    if (docount)
      pc[j] = tempcount[i];
    j++;
  }

  free(tempinds);
  free(tempd2);
  free(tempcount);

  if (docount) {
    rtn = Py_BuildValue("(OOOO)", I, J, dist2s, counts);
    Py_DECREF(counts);
  } else {
    rtn = Py_BuildValue("(OOO)", I, J, dist2s);
  }
  Py_DECREF(I);
  Py_DECREF(J);
  Py_DECREF(dist2s);
  return rtn;
}
Esempio n. 18
0
int
set_pvcards(
    /*@propname@*/ const char* propname,
    PyObject* value,
    struct pvcard** pv,
    int *npv,
    int *npvmax) {

  PyObject*  subvalue  = NULL;
  int        i         = 0;
  Py_ssize_t size      = 0;
  int        ival      = 0;
  int        mval      = 0;
  double     dblvalue  = 0.0;
  void*      newmem    = NULL;

  if (!PySequence_Check(value)) {
    return -1;
  }
  size = PySequence_Size(value);
  if (size > 0x7fffffff) {
    return -1;
  }

  if (size > (Py_ssize_t)*npvmax) {
    newmem = malloc(sizeof(struct pvcard) * size);
    if (newmem == NULL) {
      PyErr_SetString(PyExc_MemoryError, "Could not allocate memory.");
      return -1;
    }
    free(*pv);
    *pv = newmem;
    *npvmax = (int)size;
  }

  /* Verify the entire list for correct types first, so we don't have
     to undo anything copied into the canonical array. */
  for (i = 0; i < size; ++i) {
    subvalue = PySequence_GetItem(value, i);
    if (subvalue == NULL) {
      return -1;
    }
    if (!PyArg_ParseTuple(subvalue, "iid", &ival, &mval, &dblvalue)) {
      Py_DECREF(subvalue);
      return -1;
    }
    Py_DECREF(subvalue);
  }

  for (i = 0; i < size; ++i) {
    subvalue = PySequence_GetItem(value, i);
    if (subvalue == NULL) {
      return -1;
    }
    if (!PyArg_ParseTuple(subvalue, "iid", &ival, &mval, &dblvalue)) {
      Py_DECREF(subvalue);
      return -1;
    }
    Py_DECREF(subvalue);

    (*pv)[i].i = ival;
    (*pv)[i].m = mval;
    (*pv)[i].value = dblvalue;
    (*npv) = i + 1;
  }

  return 0;
}
Esempio n. 19
0
PyObject *Client_gets_multi(PyClient *self, PyObject *okeys)
{
  //[ ] def gets_multi(self, keys):

  char *pKey;
  size_t cbKey;
  char *pData;
  size_t cbData;
  UINT64 cas;
  int flags;

  self->client->getBegin();

  PyObject *iterator = PyObject_GetIter(okeys);

  if (iterator == NULL)
  {
    return NULL;
  }

  PyObject *arg;

  while ( (arg = PyIter_Next(iterator)))
  {
    PyObject *ostr;

    if (PyString_Check(arg))
    {
      ostr = arg;
    }
    else
    {
      ostr = PyObject_Str(arg);
    }

    self->client->getKeyWrite(PyString_AS_STRING(ostr), PyString_GET_SIZE(ostr));
    if (ostr != arg)
    {
      Py_DECREF(ostr);
    }

    Py_DECREF(arg);
  }

  Py_DECREF(iterator);
  self->client->getFlush();

  PyObject *odict = PyDict_New();

  bool bError = false;

  while (self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError))
  {
    PyObject *okey  = PyString_FromStringAndSize(pKey, cbKey);
    PyObject *otuple = PyTuple_New(3);
    PyObject *ovalue = PyString_FromStringAndSize(pData, cbData);
    PyObject *oflags = PyInt_FromLong(flags);
    PyObject *ocas = PyLong_FromUnsignedLongLong(cas);

    PyTuple_SET_ITEM(otuple, 0, ovalue);
    PyTuple_SET_ITEM(otuple, 1, oflags);
    PyTuple_SET_ITEM(otuple, 2, ocas);
    PyDict_SetItem (odict, okey, otuple);

    Py_DECREF(otuple);
    Py_DECREF(okey);
  }

  if (bError)
  {
    Py_DECREF(odict);

    if (!PyErr_Occurred())
    {
      return PyErr_Format(PyExc_RuntimeError, "umemcache: %s", self->client->getError());
    }

    return NULL;
  }

  return odict;
}
Esempio n. 20
0
//-------------------------------------------------------------------------------------
bool MethodDescription::checkArgs(PyObject* args)
{
	if (args == NULL || !PyTuple_Check(args))
	{
		PyErr_Format(PyExc_AssertionError, "Method::checkArgs: method[%s] args is not a tuple.\n", 
			getName());

		PyErr_PrintEx(0);
		return false;
	}
	
	int offset = (isExposed() == true && g_componentType == CELLAPP_TYPE && isCell()) ? 1 : 0;
	uint8 argsSize = argTypes_.size();
	uint8 giveArgsSize = PyTuple_Size(args);

	if (giveArgsSize != argsSize + offset)
	{
		PyErr_Format(PyExc_AssertionError, "Method::checkArgs: method[%s] requires exactly %d argument%s%s; %d given", 
				getName(),
				argsSize,
				(offset > 0) ? " + exposed(1)" : "",
				(argsSize == 1) ? "" : "s",
				PyTuple_Size(args));

		PyErr_PrintEx(0);
		return false;
	}	
	
	
	// 检查是否是一个exposed方法
	if(offset > 0)
	{
		PyObject* pyExposed = PyTuple_GetItem(args, 0);
		if (!PyLong_Check(pyExposed))
		{
			PyObject* pyeid = PyObject_GetAttrString(pyExposed, "id");
			if (pyeid == NULL || !PyLong_Check(pyeid))
			{
				Py_XDECREF(pyeid);
				PyErr_Format( PyExc_TypeError,
					"Method::checkArgs: method[%s] requires None, an id, or an object with an "
					"id as its first agument", getName());

				PyErr_PrintEx(0);
				return false;
			}
			
			Py_DECREF(pyeid);
		}
	}	
	
	for(uint8 i=0; i <argsSize; i++)
	{
		PyObject* pyArg = PyTuple_GetItem(args, i + offset);
		if (!argTypes_[i]->isSameType(pyArg))
		{
			PyObject* pExample = argTypes_[i]->parseDefaultStr("");
			PyErr_Format(PyExc_AssertionError,
				"Method::checkArgs: method[%s] argument %d: Expected %s, %s found",
				getName(),
				i+1,
				pExample->ob_type->tp_name,
				pyArg != NULL ? pyArg->ob_type->tp_name : "NULL");
			
			PyErr_PrintEx(0);
			Py_DECREF(pExample);
			return false;
		}
	}

	return true;
}
Esempio n. 21
0
/* Helper function for typy_fields which converts a single field to a
   dictionary.  Returns NULL on error.  */
static PyObject *
convert_field (struct type *type, int field)
{
  PyObject *result = field_new ();
  PyObject *arg;

  if (!result)
    return NULL;

  if (!field_is_static (&TYPE_FIELD (type, field)))
    {
      arg = PyLong_FromLong (TYPE_FIELD_BITPOS (type, field));
      if (!arg)
	goto fail;

      if (PyObject_SetAttrString (result, "bitpos", arg) < 0)
	goto failarg;
    }

  if (TYPE_FIELD_NAME (type, field))
    arg = PyString_FromString (TYPE_FIELD_NAME (type, field));
  else
    {
      arg = Py_None;
      Py_INCREF (arg);
    }
  if (!arg)
    goto fail;
  if (PyObject_SetAttrString (result, "name", arg) < 0)
    goto failarg;

  arg = TYPE_FIELD_ARTIFICIAL (type, field) ? Py_True : Py_False;
  Py_INCREF (arg);
  if (PyObject_SetAttrString (result, "artificial", arg) < 0)
    goto failarg;

  if (TYPE_CODE (type) == TYPE_CODE_CLASS)
    arg = field < TYPE_N_BASECLASSES (type) ? Py_True : Py_False;
  else
    arg = Py_False;
  Py_INCREF (arg);
  if (PyObject_SetAttrString (result, "is_base_class", arg) < 0)
    goto failarg;

  arg = PyLong_FromLong (TYPE_FIELD_BITSIZE (type, field));
  if (!arg)
    goto fail;
  if (PyObject_SetAttrString (result, "bitsize", arg) < 0)
    goto failarg;

  /* A field can have a NULL type in some situations.  */
  if (TYPE_FIELD_TYPE (type, field) == NULL)
    {
      arg = Py_None;
      Py_INCREF (arg);
    }
  else
    arg = type_to_type_object (TYPE_FIELD_TYPE (type, field));
  if (!arg)
    goto fail;
  if (PyObject_SetAttrString (result, "type", arg) < 0)
    goto failarg;

  return result;

 failarg:
  Py_DECREF (arg);
 fail:
  Py_DECREF (result);
  return NULL;
}
Esempio n. 22
0
static PyObject *
io_open(PyObject *self, PyObject *args, PyObject *kwds)
{
    char *kwlist[] = {"file", "mode", "buffering",
                      "encoding", "errors", "newline",
                      "closefd", NULL};
    PyObject *file;
    char *mode = "r";
    int buffering = -1, closefd = 1;
    char *encoding = NULL, *errors = NULL, *newline = NULL;
    unsigned i;

    int reading = 0, writing = 0, appending = 0, updating = 0;
    int text = 0, binary = 0, universal = 0;

    char rawmode[5], *m;
    int line_buffering, isatty;

    PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist,
                                     &file, &mode, &buffering,
                                     &encoding, &errors, &newline,
                                     &closefd)) {
        return NULL;
    }

    if (!PyUnicode_Check(file) &&
	!PyBytes_Check(file) &&
	!PyNumber_Check(file)) {
        PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
        return NULL;
    }

    /* Decode mode */
    for (i = 0; i < strlen(mode); i++) {
        char c = mode[i];

        switch (c) {
        case 'r':
            reading = 1;
            break;
        case 'w':
            writing = 1;
            break;
        case 'a':
            appending = 1;
            break;
        case '+':
            updating = 1;
            break;
        case 't':
            text = 1;
            break;
        case 'b':
            binary = 1;
            break;
        case 'U':
            universal = 1;
            reading = 1;
            break;
        default:
            goto invalid_mode;
        }

        /* c must not be duplicated */
        if (strchr(mode+i+1, c)) {
          invalid_mode:
            PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
            return NULL;
        }

    }

    m = rawmode;
    if (reading)   *(m++) = 'r';
    if (writing)   *(m++) = 'w';
    if (appending) *(m++) = 'a';
    if (updating)  *(m++) = '+';
    *m = '\0';

    /* Parameters validation */
    if (universal) {
        if (writing || appending) {
            PyErr_SetString(PyExc_ValueError,
                            "can't use U and writing mode at once");
            return NULL;
        }
        reading = 1;
    }

    if (text && binary) {
        PyErr_SetString(PyExc_ValueError,
                        "can't have text and binary mode at once");
        return NULL;
    }

    if (reading + writing + appending > 1) {
        PyErr_SetString(PyExc_ValueError,
                        "must have exactly one of read/write/append mode");
        return NULL;
    }

    if (binary && encoding != NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "binary mode doesn't take an encoding argument");
        return NULL;
    }

    if (binary && errors != NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "binary mode doesn't take an errors argument");
        return NULL;
    }

    if (binary && newline != NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "binary mode doesn't take a newline argument");
        return NULL;
    }

    /* Create the Raw file stream */
    raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type,
				"Osi", file, rawmode, closefd);
    if (raw == NULL)
        return NULL;

    modeobj = PyUnicode_FromString(mode);
    if (modeobj == NULL)
        goto error;

    /* buffering */
    {
        PyObject *res = PyObject_CallMethod(raw, "isatty", NULL);
        if (res == NULL)
            goto error;
        isatty = PyLong_AsLong(res);
        Py_DECREF(res);
        if (isatty == -1 && PyErr_Occurred())
            goto error;
    }

    if (buffering == 1 || (buffering < 0 && isatty)) {
        buffering = -1;
        line_buffering = 1;
    }
    else
        line_buffering = 0;

    if (buffering < 0) {
        buffering = DEFAULT_BUFFER_SIZE;
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
        {
            struct stat st;
            long fileno;
            PyObject *res = PyObject_CallMethod(raw, "fileno", NULL);
            if (res == NULL)
                goto error;

            fileno = PyLong_AsLong(res);
            Py_DECREF(res);
            if (fileno == -1 && PyErr_Occurred())
                goto error;

            if (fstat(fileno, &st) >= 0 && st.st_blksize > 1)
                buffering = st.st_blksize;
        }
#endif
    }
    if (buffering < 0) {
        PyErr_SetString(PyExc_ValueError,
                        "invalid buffering size");
        goto error;
    }

    /* if not buffering, returns the raw file object */
    if (buffering == 0) {
        if (!binary) {
            PyErr_SetString(PyExc_ValueError,
                            "can't have unbuffered text I/O");
            goto error;
        }

        Py_DECREF(modeobj);
        return raw;
    }

    /* wraps into a buffered file */
    {
        PyObject *Buffered_class;

        if (updating)
            Buffered_class = (PyObject *)&PyBufferedRandom_Type;
        else if (writing || appending)
            Buffered_class = (PyObject *)&PyBufferedWriter_Type;
        else if (reading)
            Buffered_class = (PyObject *)&PyBufferedReader_Type;
        else {
            PyErr_Format(PyExc_ValueError,
                         "unknown mode: '%s'", mode);
            goto error;
        }

        buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
    }
    Py_CLEAR(raw);
    if (buffer == NULL)
        goto error;


    /* if binary, returns the buffered file */
    if (binary) {
        Py_DECREF(modeobj);
        return buffer;
    }

    /* wraps into a TextIOWrapper */
    wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
				    "Osssi",
				    buffer,
				    encoding, errors, newline,
				    line_buffering);
    Py_CLEAR(buffer);
    if (wrapper == NULL)
        goto error;

    if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0)
        goto error;
    Py_DECREF(modeobj);
    return wrapper;

  error:
    Py_XDECREF(raw);
    Py_XDECREF(modeobj);
    Py_XDECREF(buffer);
    Py_XDECREF(wrapper);
    return NULL;
}
Esempio n. 23
0
/*
    Takes a list cartesian (x, y) pairs in the detector coordinates and calculates
    the associated reciprocal lattice (G) vectors and (bragg angle, azimuth) pairs
    with respect to the specified beam and azimth (eta) reference directions

    Required Arguments:
    xy_det -- (n, 2) ndarray or list-like input of n detector (x, y) points
    rMat_d -- (3, 3) ndarray, the COB taking DETECTOR FRAME components to LAB FRAME
    rMat_s -- (3, 3) ndarray, the COB taking SAMPLE FRAME components to LAB FRAME
    tVec_d -- (3, 1) ndarray, the translation vector connecting LAB to DETECTOR
    tVec_s -- (3, 1) ndarray, the translation vector connecting LAB to SAMPLE
    tVec_c -- (3, 1) ndarray, the translation vector connecting SAMPLE to CRYSTAL

    Optional Keyword Arguments:
    beamVec -- (1, 3) mdarray containing the incident beam direction components in the LAB FRAME
    etaVec  -- (1, 3) mdarray containing the reference azimuth direction components in the LAB FRAME

    Outputs:
    (n, 2) ndarray containing the (tTh, eta) pairs associated with each (x, y)
    (n, 3) ndarray containing the associated G vector directions in the LAB FRAME
    associated with gVecs
*/
static PyObject * detectorXYToGvec(PyObject * self, PyObject * args)
{
  PyArrayObject *xy_det, *rMat_d, *rMat_s,
		*tVec_d, *tVec_s, *tVec_c,
		*beamVec, *etaVec;
  PyArrayObject *tTh, *eta, *gVec_l;
  PyObject *inner_tuple, *outer_tuple;

  int dxy, drd, drs, dtd, dts, dtc, dbv, dev;
  npy_intp npts, dims[2];

  double *xy_Ptr, *rMat_d_Ptr, *rMat_s_Ptr,
	 *tVec_d_Ptr, *tVec_s_Ptr, *tVec_c_Ptr,
	 *beamVec_Ptr, *etaVec_Ptr;
  double *tTh_Ptr, *eta_Ptr, *gVec_l_Ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOOOOOO",
			 &xy_det,
			 &rMat_d, &rMat_s,
			 &tVec_d, &tVec_s, &tVec_c,
			 &beamVec, &etaVec)) return(NULL);
  if ( xy_det  == NULL || rMat_d == NULL || rMat_s == NULL ||
       tVec_d  == NULL || tVec_s == NULL || tVec_c == NULL ||
       beamVec == NULL || etaVec == NULL ) return(NULL);

  /* Verify shape of input arrays */
  dxy = PyArray_NDIM(xy_det);
  drd = PyArray_NDIM(rMat_d);
  drs = PyArray_NDIM(rMat_s);
  dtd = PyArray_NDIM(tVec_d);
  dts = PyArray_NDIM(tVec_s);
  dtc = PyArray_NDIM(tVec_c);
  dbv = PyArray_NDIM(beamVec);
  dev = PyArray_NDIM(etaVec);
  assert( dxy == 2 && drd == 2 && drs == 2 &&
	  dtd == 1 && dts == 1 && dtc == 1 &&
	  dbv == 1 && dev == 1);

  /* Verify dimensions of input arrays */
  npts = PyArray_DIMS(xy_det)[0];

  assert( PyArray_DIMS(xy_det)[1]  == 2 );
  assert( PyArray_DIMS(rMat_d)[0]  == 3 && PyArray_DIMS(rMat_d)[1] == 3 );
  assert( PyArray_DIMS(rMat_s)[0]  == 3 && PyArray_DIMS(rMat_s)[1] == 3 );
  assert( PyArray_DIMS(tVec_d)[0]  == 3 );
  assert( PyArray_DIMS(tVec_s)[0]  == 3 );
  assert( PyArray_DIMS(tVec_c)[0]  == 3 );
  assert( PyArray_DIMS(beamVec)[0] == 3 );
  assert( PyArray_DIMS(etaVec)[0]  == 3 );

  /* Allocate arrays for return values */
  dims[0] = npts; dims[1] = 3;
  gVec_l = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);

  tTh    = (PyArrayObject*)PyArray_EMPTY(1,&npts,NPY_DOUBLE,0);
  eta    = (PyArrayObject*)PyArray_EMPTY(1,&npts,NPY_DOUBLE,0);

  /* Grab data pointers into various arrays */
  xy_Ptr      = (double*)PyArray_DATA(xy_det);
  gVec_l_Ptr  = (double*)PyArray_DATA(gVec_l);

  tTh_Ptr     = (double*)PyArray_DATA(tTh);
  eta_Ptr     = (double*)PyArray_DATA(eta);

  rMat_d_Ptr  = (double*)PyArray_DATA(rMat_d);
  rMat_s_Ptr  = (double*)PyArray_DATA(rMat_s);

  tVec_d_Ptr  = (double*)PyArray_DATA(tVec_d);
  tVec_s_Ptr  = (double*)PyArray_DATA(tVec_s);
  tVec_c_Ptr  = (double*)PyArray_DATA(tVec_c);

  beamVec_Ptr = (double*)PyArray_DATA(beamVec);
  etaVec_Ptr  = (double*)PyArray_DATA(etaVec);

  /* Call the computational routine */
  detectorXYToGvec_cfunc(npts, xy_Ptr,
			 rMat_d_Ptr, rMat_s_Ptr,
			 tVec_d_Ptr, tVec_s_Ptr, tVec_c_Ptr,
			 beamVec_Ptr, etaVec_Ptr,
			 tTh_Ptr, eta_Ptr, gVec_l_Ptr);

  /* Build and return the nested data structure */
  /* Note that Py_BuildValue with 'O' increases reference count */
  inner_tuple = Py_BuildValue("OO",tTh,eta);
  outer_tuple = Py_BuildValue("OO", inner_tuple, gVec_l);
  Py_DECREF(inner_tuple);
  Py_DECREF(tTh);
  Py_DECREF(eta);
  Py_DECREF(gVec_l);
  return outer_tuple;
}
Esempio n. 24
0
PyMODINIT_FUNC
PyInit__io(void)
{
    PyObject *m = PyModule_Create(&_PyIO_Module);
    _PyIO_State *state = NULL;
    if (m == NULL)
        return NULL;
    state = IO_MOD_STATE(m);
    state->initialized = 0;

    /* put os in the module state */
    state->os_module = PyImport_ImportModule("os");
    if (state->os_module == NULL)
        goto fail;

#define ADD_TYPE(type, name) \
    if (PyType_Ready(type) < 0) \
        goto fail; \
    Py_INCREF(type); \
    if (PyModule_AddObject(m, name, (PyObject *)type) < 0) {  \
        Py_DECREF(type); \
        goto fail; \
    }

    /* DEFAULT_BUFFER_SIZE */
    if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
        goto fail;

    /* UnsupportedOperation inherits from ValueError and IOError */
    state->unsupported_operation = PyObject_CallFunction(
        (PyObject *)&PyType_Type, "s(OO){}",
        "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
    if (state->unsupported_operation == NULL)
        goto fail;
    Py_INCREF(state->unsupported_operation);
    if (PyModule_AddObject(m, "UnsupportedOperation",
                           state->unsupported_operation) < 0)
        goto fail;

    /* BlockingIOError */
    _PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError;
    ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError");

    /* Concrete base types of the IO ABCs.
       (the ABCs themselves are declared through inheritance in io.py)
    */
    ADD_TYPE(&PyIOBase_Type, "_IOBase");
    ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
    ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
    ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");

    /* Implementation of concrete IO objects. */
    /* FileIO */
    PyFileIO_Type.tp_base = &PyRawIOBase_Type;
    ADD_TYPE(&PyFileIO_Type, "FileIO");

    /* BytesIO */
    PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBytesIO_Type, "BytesIO");
    if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
        goto fail;

    /* StringIO */
    PyStringIO_Type.tp_base = &PyTextIOBase_Type;
    ADD_TYPE(&PyStringIO_Type, "StringIO");

    /* BufferedReader */
    PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");

    /* BufferedWriter */
    PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");

    /* BufferedRWPair */
    PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");

    /* BufferedRandom */
    PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");

    /* TextIOWrapper */
    PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
    ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");

    /* IncrementalNewlineDecoder */
    ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");

    /* Interned strings */
    if (!(_PyIO_str_close = PyUnicode_InternFromString("close")))
        goto fail;
    if (!(_PyIO_str_closed = PyUnicode_InternFromString("closed")))
        goto fail;
    if (!(_PyIO_str_decode = PyUnicode_InternFromString("decode")))
        goto fail;
    if (!(_PyIO_str_encode = PyUnicode_InternFromString("encode")))
        goto fail;
    if (!(_PyIO_str_fileno = PyUnicode_InternFromString("fileno")))
        goto fail;
    if (!(_PyIO_str_flush = PyUnicode_InternFromString("flush")))
        goto fail;
    if (!(_PyIO_str_getstate = PyUnicode_InternFromString("getstate")))
        goto fail;
    if (!(_PyIO_str_isatty = PyUnicode_InternFromString("isatty")))
        goto fail;
    if (!(_PyIO_str_newlines = PyUnicode_InternFromString("newlines")))
        goto fail;
    if (!(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
        goto fail;
    if (!(_PyIO_str_read = PyUnicode_InternFromString("read")))
        goto fail;
    if (!(_PyIO_str_read1 = PyUnicode_InternFromString("read1")))
        goto fail;
    if (!(_PyIO_str_readable = PyUnicode_InternFromString("readable")))
        goto fail;
    if (!(_PyIO_str_readinto = PyUnicode_InternFromString("readinto")))
        goto fail;
    if (!(_PyIO_str_readline = PyUnicode_InternFromString("readline")))
        goto fail;
    if (!(_PyIO_str_reset = PyUnicode_InternFromString("reset")))
        goto fail;
    if (!(_PyIO_str_seek = PyUnicode_InternFromString("seek")))
        goto fail;
    if (!(_PyIO_str_seekable = PyUnicode_InternFromString("seekable")))
        goto fail;
    if (!(_PyIO_str_setstate = PyUnicode_InternFromString("setstate")))
        goto fail;
    if (!(_PyIO_str_tell = PyUnicode_InternFromString("tell")))
        goto fail;
    if (!(_PyIO_str_truncate = PyUnicode_InternFromString("truncate")))
        goto fail;
    if (!(_PyIO_str_write = PyUnicode_InternFromString("write")))
        goto fail;
    if (!(_PyIO_str_writable = PyUnicode_InternFromString("writable")))
        goto fail;
    
    if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
        goto fail;
    if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
        goto fail;
    if (!(_PyIO_zero = PyLong_FromLong(0L)))
        goto fail;

    state->initialized = 1;

    return m;

  fail:
    Py_XDECREF(state->os_module);
    Py_XDECREF(state->unsupported_operation);
    Py_DECREF(m);
    return NULL;
}
Esempio n. 25
0
void python_to_mathematica_object(PyObject *obj)
{
    if(PyBool_Check(obj)) {
        if(obj==Py_True)
            MLPutSymbol(stdlink, "True");
        else
            MLPutSymbol(stdlink, "False");
        return;
    }
    if(PyInt_Check(obj)) {
        MLPutLongInteger(stdlink, PyInt_AsLong(obj));
        return;
    }
    if(PyLong_Check(obj)) {
#ifdef PYTHON25
        Py_ssize_t length;
#else
        int length;
#endif
        char *str, *mat_expr;
        PyObject *long_as_str;
        
        long_as_str = PyObject_CallMethod(obj, "__str__", NULL);
        PyString_AsStringAndSize(long_as_str, &str, &length);
        
        MLPutFunction(stdlink, "ToExpression", 1);
        MLPutString(stdlink, str);

        Py_DECREF(long_as_str);
        return;
    }
    if(obj==Py_None) {
        MLPutSymbol(stdlink, "Null");
        return;
    }
    if(PyFloat_Check(obj)) {
        MLPutDouble(stdlink, (double)PyFloat_AsDouble(obj));
        return;
    }
    if(PyComplex_Check(obj)) {
        MLPutFunction(stdlink, "Complex", 2);
        MLPutDouble(stdlink, (double)PyComplex_RealAsDouble(obj));
        MLPutDouble(stdlink, (double)PyComplex_ImagAsDouble(obj));
        return;
    }
    if(PyString_Check(obj)) {
        char *str;
#ifdef PYTHON25
        Py_ssize_t length;
#else
        int length;
#endif
        
        PyString_AsStringAndSize(obj, &str, &length);
        
        MLPutByteString(stdlink, (unsigned char *)str, length);
        return;
    }

    if(PyUnicode_Check(obj)) {
        MLPutUnicodeString(stdlink,
            PyUnicode_AsUnicode(obj),
            PyUnicode_GetSize(obj) );
        return;
    }
    if(PyTuple_Check(obj)) {
        
        mat_process_iterable_object(obj, "Can't get iterator for 'tuple'");

        return;
    }
    if(PyList_Check(obj)) {
    
        mat_process_iterable_object(obj, "Can't get iterator for 'list'");

        return;
    }
#ifndef PYTHON23
    if(PyObject_TypeCheck(obj, &PySet_Type)) {
    
        mat_process_iterable_object(obj, "Can't get iterator for 'set'");
    
        return;
    }
#endif
    if(PyDict_Check(obj)) {
        PyObject *items;
        
        items = PyDict_Items(obj);
        python_to_mathematica_object(items);
        Py_DECREF(items);

        return;
    }
    
    // This should ideally print info, like type of the object, that
    // can't be converted.
    MLPutString(stdlink, "Object type can't be converted!");
}
Esempio n. 26
0
static PyObject* spherematch_match(PyObject* self, PyObject* args) {
    size_t i, N;
    long p1, p2;
    kdtree_t *kd1, *kd2;
    double rad;
    struct dualtree_results dtresults;
    PyArrayObject* inds;
    npy_intp dims[2];
    PyArrayObject* dists;
	anbool notself;
	anbool permute;
	PyObject* rtn;
	
	// So that ParseTuple("b") with a C "anbool" works
	assert(sizeof(anbool) == sizeof(unsigned char));

    if (!PyArg_ParseTuple(args, "lldbb", &p1, &p2, &rad, &notself, &permute)) {
        PyErr_SetString(PyExc_ValueError, "spherematch_c.match: need five args: two kdtree identifiers (ints), search radius (float), notself (boolean), permuted (boolean)");
        return NULL;
    }
	//printf("Notself = %i\n", (int)notself);
    // Nasty!
    kd1 = (kdtree_t*)p1;
    kd2 = (kdtree_t*)p2;

    dtresults.inds1 = il_new(256);
    dtresults.inds2 = il_new(256);
    dtresults.dists = dl_new(256);
    dualtree_rangesearch(kd1, kd2, 0.0, rad, notself, NULL,
                         callback_dualtree, &dtresults,
                         NULL, NULL);

    N = il_size(dtresults.inds1);
    dims[0] = N;
    dims[1] = 2;

    inds =  (PyArrayObject*)PyArray_SimpleNew(2, dims, PyArray_INT);
    dims[1] = 1;
    dists = (PyArrayObject*)PyArray_SimpleNew(2, dims, PyArray_DOUBLE);
    for (i=0; i<N; i++) {
      int index;
      int* iptr;
      double* dptr;
      iptr = PyArray_GETPTR2(inds, i, 0);
      index = il_get(dtresults.inds1, i);
      if (permute)
        index = kdtree_permute(kd1, index);
      *iptr = index;
      iptr = PyArray_GETPTR2(inds, i, 1);
      index = il_get(dtresults.inds2, i);
      if (permute)
        index = kdtree_permute(kd2, index);
      *iptr = index;
      dptr = PyArray_GETPTR2(dists, i, 0);
      *dptr = dl_get(dtresults.dists, i);
    }

    il_free(dtresults.inds1);
    il_free(dtresults.inds2);
    dl_free(dtresults.dists);

    rtn = Py_BuildValue("(OO)", inds, dists);
    Py_DECREF(inds);
    Py_DECREF(dists);
    return rtn;
}
Esempio n. 27
0
PyObject *
LDAP_get_option(LDAPObject *self, int option)
{
    int res;
    int intval;
    struct timeval *tv;
    LDAPAPIInfo apiinfo;
    LDAPControl **lcs;
    LDAPControl *lc;
    char *strval;
    PyObject *extensions, *v, *tup;
    Py_ssize_t i, num_extensions, num_controls;
    LDAP *ld;

    ld = self ? self->ldap : NULL;

    switch(option) {
    case LDAP_OPT_API_INFO:
	    apiinfo.ldapai_info_version = LDAP_API_INFO_VERSION;
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option( ld, option, &apiinfo );
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
    
	    /* put the extensions into tuple form */
	    num_extensions = 0;
	    while (apiinfo.ldapai_extensions[num_extensions])
		num_extensions++;
	    extensions = PyTuple_New(num_extensions);
	    for (i = 0; i < num_extensions; i++)
		PyTuple_SET_ITEM(extensions, i,
		    PyString_FromString(apiinfo.ldapai_extensions[i]));

	    /* return api info as a dictionary */
	    v = Py_BuildValue("{s:i, s:i, s:i, s:s, s:i, s:O}",
		    "info_version",     apiinfo.ldapai_info_version,
		    "api_version",      apiinfo.ldapai_api_version,
		    "protocol_version", apiinfo.ldapai_protocol_version,
		    "vendor_name",      apiinfo.ldapai_vendor_name,
		    "vendor_version",   apiinfo.ldapai_vendor_version,
		    "extensions",       extensions);

	    if (apiinfo.ldapai_vendor_name)
		ldap_memfree(apiinfo.ldapai_vendor_name);
	    for (i = 0; i < num_extensions; i++)
		ldap_memfree(apiinfo.ldapai_extensions[i]);
	    ldap_memfree(apiinfo.ldapai_extensions);
	    Py_DECREF(extensions);

	    return v;

#ifdef HAVE_SASL
    case LDAP_OPT_X_SASL_SSF:
#endif
    case LDAP_OPT_REFERRALS:
    case LDAP_OPT_RESTART:
    case LDAP_OPT_DEREF:
    case LDAP_OPT_SIZELIMIT:
    case LDAP_OPT_TIMELIMIT:
    case LDAP_OPT_PROTOCOL_VERSION:
    case LDAP_OPT_ERROR_NUMBER:
    case LDAP_OPT_DEBUG_LEVEL:
#ifdef HAVE_TLS
    case LDAP_OPT_X_TLS:
    case LDAP_OPT_X_TLS_REQUIRE_CERT:
#ifdef LDAP_OPT_X_TLS_CRLCHECK
    case LDAP_OPT_X_TLS_CRLCHECK:
#endif
#ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
    case LDAP_OPT_X_TLS_PROTOCOL_MIN:
#endif
#endif
#ifdef HAVE_SASL
    case LDAP_OPT_X_SASL_SSF_MIN:
    case LDAP_OPT_X_SASL_SSF_MAX:
#endif
#ifdef LDAP_OPT_X_SASL_NOCANON
    case LDAP_OPT_X_SASL_NOCANON:
#endif
#ifdef LDAP_OPT_CONNECT_ASYNC
    case LDAP_OPT_CONNECT_ASYNC:
#endif
#ifdef LDAP_OPT_X_KEEPALIVE_IDLE
    case LDAP_OPT_X_KEEPALIVE_IDLE:
#endif
#ifdef LDAP_OPT_X_KEEPALIVE_PROBES
    case LDAP_OPT_X_KEEPALIVE_PROBES:
#endif
#ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
    case LDAP_OPT_X_KEEPALIVE_INTERVAL:
#endif
	    /* Integer-valued options */
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &intval);
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
	    return PyInt_FromLong(intval);

    case LDAP_OPT_HOST_NAME:
    case LDAP_OPT_URI:
#ifdef LDAP_OPT_DEFBASE
    case LDAP_OPT_DEFBASE:
#endif
    case LDAP_OPT_ERROR_STRING:
    case LDAP_OPT_MATCHED_DN:
#ifdef HAVE_TLS
    case LDAP_OPT_X_TLS_CACERTFILE:
    case LDAP_OPT_X_TLS_CACERTDIR:
    case LDAP_OPT_X_TLS_CERTFILE:
    case LDAP_OPT_X_TLS_KEYFILE:
    case LDAP_OPT_X_TLS_CIPHER_SUITE:
    case LDAP_OPT_X_TLS_RANDOM_FILE:
    case LDAP_OPT_X_TLS_DHFILE:
#ifdef LDAP_OPT_X_TLS_CRLFILE
    case LDAP_OPT_X_TLS_CRLFILE:
#endif
#ifdef LDAP_OPT_X_TLS_PACKAGE
    case LDAP_OPT_X_TLS_PACKAGE:
#endif
#endif
#ifdef HAVE_SASL
    case LDAP_OPT_X_SASL_SECPROPS:
    case LDAP_OPT_X_SASL_MECH:
    case LDAP_OPT_X_SASL_REALM:
    case LDAP_OPT_X_SASL_AUTHCID:
    case LDAP_OPT_X_SASL_AUTHZID:
#ifdef LDAP_OPT_X_SASL_USERNAME
    case LDAP_OPT_X_SASL_USERNAME:
#endif
#endif
	    /* String-valued options */
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &strval);
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
	    if (strval == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	    }
	    v = PyString_FromString(strval);
	    ldap_memfree(strval);
	    return v;

    case LDAP_OPT_TIMEOUT:
    case LDAP_OPT_NETWORK_TIMEOUT:
	    /* Double-valued timeval options */
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &tv);
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
	    if (tv == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	    }
	    v = PyFloat_FromDouble(
              (double) tv->tv_sec + ( (double) tv->tv_usec / 1000000.0 )
            );
	    ldap_memfree(tv);
	    return v;

    case LDAP_OPT_SERVER_CONTROLS:
    case LDAP_OPT_CLIENT_CONTROLS:
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &lcs);
	    if (self) LDAP_END_ALLOW_THREADS(self);

	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");

            if (lcs == NULL)
                return PyList_New(0);
            
            /* Get the number of controls */
            num_controls = 0;
            while (lcs[num_controls])
                num_controls++;

            /* We'll build a list of controls, with each control a tuple */
            v = PyList_New(num_controls);
            for (i = 0; i < num_controls; i++) {
                lc = lcs[i];
                tup = Py_BuildValue("(sbs)", 
                                    lc->ldctl_oid,
                                    lc->ldctl_iscritical,
                                    lc->ldctl_value.bv_val);
                PyList_SET_ITEM(v, i, tup);
            }
            
            ldap_controls_free(lcs);

            return v;
            
    default:
	    PyErr_Format(PyExc_ValueError, "unknown option %d", option);
	    return NULL;
    }
}
Esempio n. 28
0
static PyObject* spherematch_nn(PyObject* self, PyObject* args) {
    int i, NY;
    long p1, p2;
    kdtree_t *kd1, *kd2;
    npy_intp dims[1];
    PyArrayObject* inds;
    PyArrayObject* dist2s;
    int *pinds;
    double *pdist2s;
    double rad;
	anbool notself;
	int* tempinds;
	PyObject* rtn;

	// So that ParseTuple("b") with a C "anbool" works
	assert(sizeof(anbool) == sizeof(unsigned char));

    if (!PyArg_ParseTuple(args, "lldb", &p1, &p2, &rad, &notself)) {
        PyErr_SetString(PyExc_ValueError, "need three args: two kdtree identifiers (ints), and search radius");
        return NULL;
    }
    // Nasty!
    kd1 = (kdtree_t*)p1;
    kd2 = (kdtree_t*)p2;

    NY = kdtree_n(kd2);

    dims[0] = NY;
    inds   = (PyArrayObject*)PyArray_SimpleNew(1, dims, PyArray_INT);
    dist2s = (PyArrayObject*)PyArray_SimpleNew(1, dims, PyArray_DOUBLE);
    assert(PyArray_ITEMSIZE(inds) == sizeof(int));
    assert(PyArray_ITEMSIZE(dist2s) == sizeof(double));

	// YUCK!
	tempinds = (int*)malloc(NY * sizeof(int));
	double* tempdists = (double*)malloc(NY * sizeof(double));

    pinds   = tempinds; //PyArray_DATA(inds);
    //pdist2s = PyArray_DATA(dist2s);
	pdist2s = tempdists;

    dualtree_nearestneighbour(kd1, kd2, rad*rad, &pdist2s, &pinds, NULL, notself);

	// now we have to apply kd1's permutation array!
	for (i=0; i<NY; i++)
		if (pinds[i] != -1)
			pinds[i] = kdtree_permute(kd1, pinds[i]);


	pinds = PyArray_DATA(inds);
    pdist2s = PyArray_DATA(dist2s);

	for (i=0; i<NY; i++) {
		pinds[i] = -1;
		pdist2s[i] = HUGE_VAL;
	}
	// and apply kd2's permutation array!
	for (i=0; i<NY; i++) {
		if (tempinds[i] != -1) {
			int j = kdtree_permute(kd2, i);
			pinds[j] = tempinds[i];
			pdist2s[j] = tempdists[i];
		}
	}
	free(tempinds);
	free(tempdists);

	rtn = Py_BuildValue("(OO)", inds, dist2s);
	Py_DECREF(inds);
	Py_DECREF(dist2s);
	return rtn;
}
Esempio n. 29
0
static int convertTo_QJsonArray(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QJsonArray **sipCppPtr = reinterpret_cast<QJsonArray **>(sipCppPtrV);

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

    if (!sipIsErr)
    {
        Py_XDECREF(iter);

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

    if (!iter)
    {
        *sipIsErr = 1;

        return 0;
    }

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

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

                return 0;
            }

            break;
        }

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

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

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

            return 0;
        }

        ql->append(*t);

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

    *sipCppPtr = ql;
 
    return sipGetState(sipTransferObj);
#line 139 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtCore/sipQtCoreQJsonArray.cpp"
}
Esempio n. 30
0
void
PySfEvent_InitConst()
{
	PyObject *obj;
	obj = PyInt_FromLong(sf::Event::KeyReleased);
	PyDict_SetItemString(PySfEventType.tp_dict, "KeyReleased", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::LostFocus);
	PyDict_SetItemString(PySfEventType.tp_dict, "LostFocus", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::GainedFocus);
	PyDict_SetItemString(PySfEventType.tp_dict, "GainedFocus", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::KeyPressed);
	PyDict_SetItemString(PySfEventType.tp_dict, "KeyPressed", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::MouseWheelMoved);
	PyDict_SetItemString(PySfEventType.tp_dict, "MouseWheelMoved", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::TextEntered);
	PyDict_SetItemString(PySfEventType.tp_dict, "TextEntered", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::MouseMoved);
	PyDict_SetItemString(PySfEventType.tp_dict, "MouseMoved", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::JoyButtonPressed);
	PyDict_SetItemString(PySfEventType.tp_dict, "JoyButtonPressed", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::MouseButtonReleased);
	PyDict_SetItemString(PySfEventType.tp_dict, "MouseButtonReleased", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::Closed);
	PyDict_SetItemString(PySfEventType.tp_dict, "Closed", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::MouseButtonPressed);
	PyDict_SetItemString(PySfEventType.tp_dict, "MouseButtonPressed", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::JoyMoved);
	PyDict_SetItemString(PySfEventType.tp_dict, "JoyMoved", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::JoyButtonReleased);
	PyDict_SetItemString(PySfEventType.tp_dict, "JoyButtonReleased", obj);
	Py_DECREF(obj);
	obj = PyInt_FromLong(sf::Event::Resized);
	PyDict_SetItemString(PySfEventType.tp_dict, "Resized", obj);
	Py_DECREF(obj);
}