示例#1
0
static PyObject* pyGBufferGroup_getNumIdxBuffers(pyGBufferGroup* self) {
    return PyInt_FromLong(self->fThis->getNumIdxBuffers());
}
示例#2
0
	int spyceRequest(webs_t wp, char_t *lpath)
	{
		// initialize python first
		if(!spyInitialized)
		{
			g_pythonParser.Initialize();

			PyEval_AcquireLock();
			PyInterpreterState * mainInterpreterState = g_pythonParser.getMainThreadState()->interp;
			spyThreadState = PyThreadState_New(mainInterpreterState);
			PyThreadState_Swap(spyThreadState);

			PyObject* pName = PyString_FromString("spyceXbmc");
			PyObject* pModule = PyImport_Import(pName);
			Py_XDECREF(pName);

			if(!pModule) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
			else
			{
				PyObject* pDict = PyModule_GetDict(pModule);
				Py_XDECREF(pModule);
				spyFunc = PyDict_GetItemString(pDict, "ParseFile");
				if(!spyFunc) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
				
				else spyInitialized = true;
			}

			PyThreadState_Swap(NULL);
			PyEval_ReleaseLock();
			if(!spyInitialized)
			{
				PyThreadState_Clear(spyThreadState);
				PyThreadState_Delete(spyThreadState);
				g_pythonParser.Finalize();
				return -1;		
			}
			
		}

		PyEval_AcquireLock();
		PyThreadState_Swap(spyThreadState);

		std::string strRequestMethod;
		std::string strQuery = wp->query;
		std::string strCookie;
		int iContentLength = 0;
		
		if (strlen(wp->query) > 0)
		{
			if(wp->flags & WEBS_POST_REQUEST)	strRequestMethod = "POST";
			else if (wp->flags & WEBS_HEAD_REQUEST) strRequestMethod = "HEAD";
			else strRequestMethod = "GET";
		}

		if (wp->flags & WEBS_COOKIE) strCookie = wp->cookie;
		iContentLength = strQuery.length();

		// create enviroment and parse file
		PyObject* pEnv = PyDict_New();
		PyObject* pREQUEST_METHOD = PyString_FromString(strRequestMethod.c_str());
		PyObject* pCONTENT_LENGTH = PyInt_FromLong(iContentLength);
		PyObject* pQUERY_STRING = PyString_FromString(strQuery.c_str());
		PyObject* pHTTP_COOKIE = PyString_FromString(strCookie.c_str());
		PyObject* pCONTENT_TYPE = PyString_FromString(wp->type);
		PyObject* pHTTP_HOST = PyString_FromString(wp->host);
		PyObject* pHTTP_USER_AGENT = PyString_FromString(wp->userAgent ? wp->userAgent : "");
		PyObject* pHTTP_CONNECTION = PyString_FromString((wp->flags & WEBS_KEEP_ALIVE)? "Keep-Alive" : "");

		PyDict_SetItemString(pEnv, "REQUEST_METHOD", pREQUEST_METHOD);
		PyDict_SetItemString(pEnv, "CONTENT_LENGTH", pCONTENT_LENGTH);
		PyDict_SetItemString(pEnv, "QUERY_STRING", pQUERY_STRING);
		PyDict_SetItemString(pEnv, "HTTP_COOKIE", pHTTP_COOKIE);
		//PyDict_SetItemString(pEnv, "CONTENT_TYPE", pCONTENT_TYPE);
		PyDict_SetItemString(pEnv, "HTTP_HOST", pHTTP_HOST);
		PyDict_SetItemString(pEnv, "HTTP_USER_AGENT", pHTTP_USER_AGENT);
		PyDict_SetItemString(pEnv, "HTTP_CONNECTION", pHTTP_CONNECTION);

		PyObject* pResult = PyObject_CallFunction(spyFunc, (char*)"sO", lpath, pEnv);

		Py_XDECREF(pREQUEST_METHOD);
		Py_XDECREF(pCONTENT_LENGTH);
		Py_XDECREF(pQUERY_STRING);
		Py_XDECREF(pHTTP_COOKIE);
		Py_XDECREF(pCONTENT_TYPE);
		Py_XDECREF(pHTTP_HOST);
		Py_XDECREF(pHTTP_USER_AGENT);
		Py_XDECREF(pHTTP_CONNECTION);

		Py_XDECREF(pEnv);

		if(!pResult) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
		else
		{
			char* cResult = PyString_AsString(pResult);
			websWriteBlock(wp, cResult, strlen(cResult));
			Py_XDECREF(pResult);
		}

		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();

	/*
	*	Common exit and cleanup
	*/
		if (websValid(wp)) {
			websPageClose(wp);
		}
		return 0;
	}
示例#3
0
static PyObject *t_resourcebundle_getType(t_resourcebundle *self)
{
    return PyInt_FromLong((long) self->object->getType());
}
示例#4
0
static int
Snmp_updatereactor(void)
{
	int maxfd = 0, block = 0, fd, result, i;
	PyObject *keys, *key, *tmp;
	SnmpReaderObject *reader;
	fd_set fdset;
	struct timeval timeout;
	double to;

	FD_ZERO(&fdset);
	block = 1;		/* This means we don't have a timeout
				   planned. block will be reset to 0
				   if we need to setup a timeout. */
	snmp_select_info(&maxfd, &fdset, &timeout, &block);
	for (fd = 0; fd < maxfd; fd++) {
		if (FD_ISSET(fd, &fdset)) {
			result = PyDict_Contains(SnmpFds, PyInt_FromLong(fd));
			if (result == -1)
				return -1;
			if (!result) {
				/* Add this fd to the reactor */
				if ((reader = (SnmpReaderObject *)
					PyObject_CallObject((PyObject *)&SnmpReaderType,
					    NULL)) == NULL)
					return -1;
				reader->fd = fd;
				if ((key =
					PyInt_FromLong(fd)) == NULL) {
					Py_DECREF(reader);
					return -1;
				}
				if (PyDict_SetItem(SnmpFds, key, (PyObject*)reader) != 0) {
					Py_DECREF(reader);
					Py_DECREF(key);
					return -1;
				}
				Py_DECREF(key);
				if ((tmp = PyObject_CallMethod(reactor,
					    "addReader", "O", (PyObject*)reader)) ==
				    NULL) {
					Py_DECREF(reader);
					return -1;
				}
				Py_DECREF(tmp);
				Py_DECREF(reader);
			}
		}
	}
	if ((keys = PyDict_Keys(SnmpFds)) == NULL)
		return -1;
	for (i = 0; i < PyList_Size(keys); i++) {
		if ((key = PyList_GetItem(keys, i)) == NULL) {
			Py_DECREF(keys);
			return -1;
		}
		fd = PyInt_AsLong(key);
		if (PyErr_Occurred()) {
			Py_DECREF(keys);
			return -1;
		}
		if ((fd >= maxfd) || (!FD_ISSET(fd, &fdset))) {
			/* Delete this fd from the reactor */
			if ((reader = (SnmpReaderObject*)PyDict_GetItem(SnmpFds,
				    key)) == NULL) {
				Py_DECREF(keys);
				return -1;
			}
			if ((tmp = PyObject_CallMethod(reactor,
				    "removeReader", "O", (PyObject*)reader)) == NULL) {
				Py_DECREF(keys);
				return -1;
			}
			Py_DECREF(tmp);
			if (PyDict_DelItem(SnmpFds, key) == -1) {
				Py_DECREF(keys);
				return -1;
			}
		}
	}
	Py_DECREF(keys);
	/* Setup timeout */
	if (timeoutId) {
		if ((tmp = PyObject_CallMethod(timeoutId, "cancel", NULL)) == NULL) {
			/* Don't really know what to do. It seems better to
			 * raise an exception at this point. */
			Py_CLEAR(timeoutId);
			return -1;
		}
		Py_DECREF(tmp);
		Py_CLEAR(timeoutId);
	}
	if (!block) {
		to = (double)timeout.tv_sec +
		    (double)timeout.tv_usec/(double)1000000;
		if ((timeoutId = PyObject_CallMethod(reactor, "callLater", "dO",
			    to, timeoutFunction)) == NULL) {
			return -1;
		}
	}
	return 0;
}
示例#5
0
文件: py-arch.c 项目: Xilinx/gdb
static PyObject *
archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw)
{
  static char *keywords[] = { "start_pc", "end_pc", "count", NULL };
  CORE_ADDR start, end = 0;
  CORE_ADDR pc;
  gdb_py_ulongest start_temp;
  long count = 0, i;
  PyObject *result_list, *end_obj = NULL, *count_obj = NULL;
  struct gdbarch *gdbarch = NULL;

  ARCHPY_REQUIRE_VALID (self, gdbarch);

  if (!PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO", keywords,
                                    &start_temp, &end_obj, &count_obj))
    return NULL;

  start = start_temp;
  if (end_obj)
    {
      /* Make a long logic check first.  In Python 3.x, internally,
	 all integers are represented as longs.  In Python 2.x, there
	 is still a differentiation internally between a PyInt and a
	 PyLong.  Explicitly do this long check conversion first. In
	 GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
	 to be done first to ensure we do not lose information in the
	 conversion process.  */
      if (PyLong_Check (end_obj))
        end = PyLong_AsUnsignedLongLong (end_obj);
      else if (PyInt_Check (end_obj))
        /* If the end_pc value is specified without a trailing 'L', end_obj will
           be an integer and not a long integer.  */
        end = PyInt_AsLong (end_obj);
      else
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'end_pc' should be a (long) integer."));

          return NULL;
        }

      if (end < start)
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_ValueError,
                           _("Argument 'end_pc' should be greater than or "
                             "equal to the argument 'start_pc'."));

          return NULL;
        }
    }
  if (count_obj)
    {
      count = PyInt_AsLong (count_obj);
      if (PyErr_Occurred () || count < 0)
        {
          Py_DECREF (count_obj);
          Py_XDECREF (end_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'count' should be an non-negative "
                             "integer."));

          return NULL;
        }
    }

  result_list = PyList_New (0);
  if (result_list == NULL)
    return NULL;

  for (pc = start, i = 0;
       /* All args are specified.  */
       (end_obj && count_obj && pc <= end && i < count)
       /* end_pc is specified, but no count.  */
       || (end_obj && count_obj == NULL && pc <= end)
       /* end_pc is not specified, but a count is.  */
       || (end_obj == NULL && count_obj && i < count)
       /* Both end_pc and count are not specified.  */
       || (end_obj == NULL && count_obj == NULL && pc == start);)
    {
      int insn_len = 0;
      char *as = NULL;
      struct ui_file *memfile = mem_fileopen ();
      PyObject *insn_dict = PyDict_New ();
      volatile struct gdb_exception except;

      if (insn_dict == NULL)
        {
          Py_DECREF (result_list);
          ui_file_delete (memfile);

          return NULL;
        }
      if (PyList_Append (result_list, insn_dict))
        {
          Py_DECREF (result_list);
          Py_DECREF (insn_dict);
          ui_file_delete (memfile);

          return NULL;  /* PyList_Append Sets the exception.  */
        }

      TRY_CATCH (except, RETURN_MASK_ALL)
        {
          insn_len = gdb_print_insn (gdbarch, pc, memfile, NULL);
        }
      if (except.reason < 0)
        {
          Py_DECREF (result_list);
          ui_file_delete (memfile);

	  gdbpy_convert_exception (except);
	  return NULL;
        }

      as = ui_file_xstrdup (memfile, NULL);
      if (PyDict_SetItemString (insn_dict, "addr",
                                gdb_py_long_from_ulongest (pc))
          || PyDict_SetItemString (insn_dict, "asm",
                                   PyString_FromString (*as ? as : "<unknown>"))
          || PyDict_SetItemString (insn_dict, "length",
                                   PyInt_FromLong (insn_len)))
        {
          Py_DECREF (result_list);

          ui_file_delete (memfile);
          xfree (as);

          return NULL;
        }

      pc += insn_len;
      i++;
      ui_file_delete (memfile);
      xfree (as);
    }
示例#6
0
PyObject *scribus_pagecount(PyObject* /* self */)
{
	if(!checkHaveDocument())
		return NULL;
	return PyInt_FromLong(static_cast<long>(ScCore->primaryMainWindow()->doc->Pages->count()));
}
示例#7
0
static int
Snmp_handle(int operation, netsnmp_session *session, int reqid,
    netsnmp_pdu *response, void *magic)
{
	PyObject *key, *defer, *results = NULL, *resultvalue = NULL,
	    *resultoid = NULL, *tmp;
	struct ErrorException *e;
	struct variable_list *vars;
	int i;
	long long counter64;
	SnmpObject *self;

	if ((key = PyInt_FromLong(reqid)) == NULL)
		/* Unknown session, don't know what to do... */
		return 1;
	self = (SnmpObject *)magic;
	if ((defer = PyDict_GetItem(self->defers, key)) == NULL)
		return 1;
	Py_INCREF(defer);
	PyDict_DelItem(self->defers, key);
	Py_DECREF(key);
	/* We have our deferred object. We will be able to trigger callbacks and
	 * errbacks */
	if (operation == NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE) {
		if (response->errstat != SNMP_ERR_NOERROR) {
			for (e = SnmpErrorToException; e->name; e++) {
				if (e->error == response->errstat) {
					PyErr_SetString(e->exception, snmp_errstring(e->error));
					goto fireexception;
				}
			}
			PyErr_Format(SnmpException, "unknown error %ld", response->errstat);
			goto fireexception;
		}
	} else {
		PyErr_SetString(SnmpException, "Timeout");
		goto fireexception;
	}
	if ((results = PyDict_New()) == NULL)
		goto fireexception;
	for (vars = response->variables; vars;
	     vars = vars->next_variable) {
	/* Let's handle the value */
		switch (vars->type) {
		case SNMP_NOSUCHOBJECT:
			PyErr_SetString(SnmpNoSuchObject, "No such object was found");
			goto fireexception;
		case SNMP_NOSUCHINSTANCE:
			PyErr_SetString(SnmpNoSuchInstance, "No such instance exists");
			goto fireexception;
		case SNMP_ENDOFMIBVIEW:
			if (PyDict_Size(results) == 0) {
				PyErr_SetString(SnmpEndOfMibView,
				    "End of MIB was reached");
				goto fireexception;
			} else
				continue;
		case ASN_INTEGER:
			resultvalue = PyLong_FromLong(*vars->val.integer);
			break;
		case ASN_UINTEGER:
		case ASN_TIMETICKS:
		case ASN_GAUGE:
		case ASN_COUNTER:
			resultvalue = PyLong_FromUnsignedLong(
				(unsigned long)*vars->val.integer);
			break;
		case ASN_OCTET_STR:
			resultvalue = PyString_FromStringAndSize(
				(char*)vars->val.string, vars->val_len);
			break;
		case ASN_BIT_STR:
			resultvalue = PyString_FromStringAndSize(
				(char*)vars->val.bitstring, vars->val_len);
			break;
		case ASN_OBJECT_ID:
			if ((resultvalue = PyTuple_New(
					vars->val_len/sizeof(oid))) == NULL)
				goto fireexception;
			for (i = 0; i < vars->val_len/sizeof(oid); i++) {
				if ((tmp = PyLong_FromLong(
						vars->val.objid[i])) == NULL)
					goto fireexception;
				PyTuple_SetItem(resultvalue, i, tmp);
			}
			if ((resultvalue = Snmp_oid2string(resultvalue)) == NULL)
				goto fireexception;
			break;
		case ASN_IPADDRESS:
			if (vars->val_len < 4) {
				PyErr_Format(SnmpException, "IP address is too short (%zd < 4)",
				    vars->val_len);
				goto fireexception;
			}
			resultvalue = PyString_FromFormat("%d.%d.%d.%d",
			    vars->val.string[0],
			    vars->val.string[1],
			    vars->val.string[2],
			    vars->val.string[3]);
			break;
		case ASN_COUNTER64:
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
		case ASN_OPAQUE_U64:
		case ASN_OPAQUE_I64:
		case ASN_OPAQUE_COUNTER64:
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
			counter64 = ((unsigned long long)(vars->val.counter64->high) << 32) +
			    (unsigned long long)(vars->val.counter64->low);
			resultvalue = PyLong_FromUnsignedLongLong(counter64);
			break;
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
		case ASN_OPAQUE_FLOAT:
			resultvalue = PyFloat_FromDouble(*vars->val.floatVal);
			break;
		case ASN_OPAQUE_DOUBLE:
			resultvalue = PyFloat_FromDouble(*vars->val.doubleVal);
			break;
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
		default:
			PyErr_Format(SnmpException, "unknown type returned (%d)",
			    vars->type);
			goto fireexception;
		}
		if (resultvalue == NULL) goto fireexception;

		/* And now, the OID */
		if ((resultoid = PyTuple_New(vars->name_length)) == NULL)
			goto fireexception;
		for (i = 0; i < vars->name_length; i++) {
			if ((tmp = PyLong_FromLong(vars->name[i])) == NULL)
				goto fireexception;
			PyTuple_SetItem(resultoid, i, tmp);
		}
		if ((resultoid = Snmp_oid2string(resultoid)) == NULL)
			goto fireexception;

		/* Put into dictionary */
		PyDict_SetItem(results, resultoid, resultvalue);
		Py_CLEAR(resultoid);
		Py_CLEAR(resultvalue);
	}
	if ((tmp = PyObject_GetAttrString(defer, "callback")) == NULL)
		goto fireexception;
	Py_DECREF(PyObject_CallMethod(reactor, "callLater", "iOO", 0, tmp, results));
	Py_DECREF(tmp);
	Py_DECREF(results);
	Py_DECREF(defer);
	Py_DECREF(self);
	return 1;

fireexception:
	Snmp_invokeerrback(defer);
	Py_XDECREF(results);
	Py_XDECREF(resultvalue);
	Py_XDECREF(resultoid);
	Py_DECREF(defer);
	Py_DECREF(self);
	return 1;
}
示例#8
0
static PyObject*
_cd_getnumtracks (PyObject *self, void *closure)
{
    ASSERT_CDROM_OPEN(self, NULL);
    return PyInt_FromLong (((PyCD*)self)->cd->numtracks);
}
示例#9
0
static PyObject*
_cd_getcurframe (PyObject *self, void *closure)
{
    ASSERT_CDROM_OPEN(self, NULL);
    return PyInt_FromLong (((PyCD*)self)->cd->cur_frame);
}
示例#10
0
static PyObject*
_cd_getindex (PyObject *self, void *closure)
{
    ASSERT_CDROM_INIT(NULL);
    return PyInt_FromLong (((PyCD*)self)->index);
}
示例#11
0
static PyObject*
_cd_getstatus (PyObject *self, void *closure)
{
    ASSERT_CDROM_OPEN(self, NULL);
    return PyInt_FromLong (SDL_CDStatus (((PyCD*)self)->cd));
}
示例#12
0
文件: baas2.c 项目: jwilk/Pyrex
/* Implementation of baas2 */

static PyObject *__pyx_f_5baas2_bar(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyObject *__pyx_f_5baas2_bar(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  int __pyx_v_a;
  int __pyx_v_b;
  PyObject *__pyx_v_values;
  PyObject *__pyx_v_dummy;
  PyObject *__pyx_v_tup;
  PyObject *__pyx_r;
  PyObject *__pyx_1 = 0;
  PyObject *__pyx_2 = 0;
  PyObject *__pyx_3 = 0;
  int __pyx_4;
  static char *__pyx_argnames[] = {0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
  __pyx_v_values = Py_None; Py_INCREF(Py_None);
  __pyx_v_dummy = Py_None; Py_INCREF(Py_None);
  __pyx_v_tup = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/baas/baas2.pyx":4 */
  __pyx_1 = PyInt_FromLong(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}
  __pyx_2 = PyInt_FromLong(2); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}
  __pyx_3 = PyTuple_New(2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}
  PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1);
  PyTuple_SET_ITEM(__pyx_3, 1, __pyx_2);
  __pyx_1 = 0;
  __pyx_2 = 0;
  Py_DECREF(__pyx_v_values);
  __pyx_v_values = __pyx_3;
  __pyx_3 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/baas/baas2.pyx":5 */
  __pyx_1 = PyFloat_FromDouble(1.0); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;}
  Py_DECREF(__pyx_v_dummy);
  __pyx_v_dummy = __pyx_1;
  __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/baas/baas2.pyx":7 */
  __pyx_2 = PyInt_FromLong(0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  __pyx_3 = PyObject_GetItem(__pyx_v_values, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  __pyx_4 = PyInt_AsLong(__pyx_2); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  __pyx_v_a = __pyx_4;

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/baas/baas2.pyx":8 */
  __pyx_1 = PyInt_FromLong(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_2 = PyObject_GetItem(__pyx_v_values, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  __pyx_4 = PyInt_AsLong(__pyx_3); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  __pyx_v_b = __pyx_4;

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/baas/baas2.pyx":10 */
  __pyx_1 = PyInt_FromLong(__pyx_v_a); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; goto __pyx_L1;}
  __pyx_2 = PyInt_FromLong(__pyx_v_b); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; goto __pyx_L1;}
  __pyx_3 = PyTuple_New(2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; goto __pyx_L1;}
  PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1);
  PyTuple_SET_ITEM(__pyx_3, 1, __pyx_2);
  __pyx_1 = 0;
  __pyx_2 = 0;
  Py_DECREF(__pyx_v_tup);
  __pyx_v_tup = __pyx_3;
  __pyx_3 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/baas/baas2.pyx":11 */
  if (__Pyx_PrintItem(__pyx_v_tup) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; goto __pyx_L1;}
  if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; goto __pyx_L1;}

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_3);
  __Pyx_AddTraceback("baas2.bar");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_values);
  Py_DECREF(__pyx_v_dummy);
  Py_DECREF(__pyx_v_tup);
  return __pyx_r;
}
示例#13
0
static PyObject* pyGBufferGroup_getStride(pyGBufferGroup* self, void*) {
    return PyInt_FromLong(self->fThis->getStride());
}
示例#14
0
static PyObject* pyGBufferGroup_getSkinWeights(pyGBufferGroup* self, void*) {
    return PyInt_FromLong(self->fThis->getSkinWeights());
}
示例#15
0
// @object PyADSVALUE|A tuple:
// @tupleitem 0|object|value|The value as a Python object.
// @tupleitem 1|int|type|The AD type of the value.
PyObject *PyADSIObject_FromADSVALUE(ADSVALUE &v)
{
	PyObject *ob = NULL;
	switch (v.dwType) {
		case ADSTYPE_DN_STRING:
			ob = PyWinObject_FromWCHAR(v.DNString);
			break;
		case ADSTYPE_CASE_EXACT_STRING:
			ob = PyWinObject_FromWCHAR(v.CaseExactString);
			break;
		case ADSTYPE_CASE_IGNORE_STRING:
			ob = PyWinObject_FromWCHAR(v.CaseIgnoreString);
			break;
		case ADSTYPE_PRINTABLE_STRING:
			ob = PyWinObject_FromWCHAR(v.PrintableString);
			break;
		case ADSTYPE_NUMERIC_STRING:
			ob = PyWinObject_FromWCHAR(v.NumericString);
			break;
		case ADSTYPE_BOOLEAN:
			ob = v.Boolean ? Py_True : Py_False;
			Py_INCREF(ob);
			break;
		case ADSTYPE_INTEGER:
			ob = PyInt_FromLong(v.Integer);
			break;
		case ADSTYPE_OCTET_STRING:
			{
			void *buf;
			DWORD bufSize = v.OctetString.dwLength;
			if (!(ob=PyBuffer_New(bufSize)))
				return NULL;
			if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
				Py_DECREF(ob);
				return NULL;
				}
			memcpy(buf, v.OctetString.lpValue, bufSize);
			}
			break;
		case ADSTYPE_UTC_TIME:
			ob = PyWinObject_FromSYSTEMTIME(v.UTCTime);
			break;
		case ADSTYPE_LARGE_INTEGER:
			ob = PyWinObject_FromLARGE_INTEGER(v.LargeInteger);
			break;
		case ADSTYPE_OBJECT_CLASS:
			ob = PyWinObject_FromWCHAR(v.ClassName);
			break;
		case ADSTYPE_PROV_SPECIFIC:
			{
			void *buf;
			DWORD bufSize = v.ProviderSpecific.dwLength;
			if (!(ob=PyBuffer_New(bufSize)))
				return NULL;
			if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
				Py_DECREF(ob);
				return NULL;
			}
			memcpy(buf, v.ProviderSpecific.lpValue, bufSize);
			break;
			}
		case ADSTYPE_NT_SECURITY_DESCRIPTOR:
			{
			// Get a pointer to the security descriptor.
			PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)(v.SecurityDescriptor.lpValue);
			DWORD SDSize = v.SecurityDescriptor.dwLength;
			// eeek - we don't pass the length - pywintypes relies on
			// GetSecurityDescriptorLength - make noise if this may bite us.
			if (SDSize != GetSecurityDescriptorLength(pSD))
				PyErr_Warn(PyExc_RuntimeWarning, "Security-descriptor size mis-match");
			ob = PyWinObject_FromSECURITY_DESCRIPTOR(pSD);
			break;
			}
		default:
			{
			char msg[100];
			sprintf(msg, "Unknown ADS type code 0x%x - None will be returned", v.dwType);
			PyErr_Warn(PyExc_RuntimeWarning, msg);
			ob = Py_None;
			Py_INCREF(ob);
		}
	}
	if (ob==NULL)
		return NULL;
	PyObject *ret = Py_BuildValue("Oi", ob, (int)v.dwType);
	Py_DECREF(ob);
	return ret;
}
示例#16
0
PyMODINIT_FUNC initkerberos(void)
{
    PyObject *m,*d;

    m = Py_InitModule("kerberos", KerberosMethods);

    d = PyModule_GetDict(m);

    /* create the base exception class */
    if (!(KrbException_class = PyErr_NewException("kerberos.KrbError", NULL, NULL)))
        goto error;
    PyDict_SetItemString(d, "KrbError", KrbException_class);
    Py_INCREF(KrbException_class);

    /* ...and the derived exceptions */
    if (!(BasicAuthException_class = PyErr_NewException("kerberos.BasicAuthError", KrbException_class, NULL)))
        goto error;
    Py_INCREF(BasicAuthException_class);
    PyDict_SetItemString(d, "BasicAuthError", BasicAuthException_class);

    if (!(PwdChangeException_class = PyErr_NewException("kerberos.PwdChangeError", KrbException_class, NULL)))
        goto error;
    Py_INCREF(PwdChangeException_class);
    PyDict_SetItemString(d, "PwdChangeError", PwdChangeException_class);

    if (!(GssException_class = PyErr_NewException("kerberos.GSSError", KrbException_class, NULL)))
        goto error;
    Py_INCREF(GssException_class);
    PyDict_SetItemString(d, "GSSError", GssException_class);

    PyDict_SetItemString(d, "AUTH_GSS_COMPLETE", PyInt_FromLong(AUTH_GSS_COMPLETE));
    PyDict_SetItemString(d, "AUTH_GSS_CONTINUE", PyInt_FromLong(AUTH_GSS_CONTINUE));

    PyDict_SetItemString(d, "GSS_C_DELEG_FLAG", PyInt_FromLong(GSS_C_DELEG_FLAG));
    PyDict_SetItemString(d, "GSS_C_MUTUAL_FLAG", PyInt_FromLong(GSS_C_MUTUAL_FLAG));
    PyDict_SetItemString(d, "GSS_C_REPLAY_FLAG", PyInt_FromLong(GSS_C_REPLAY_FLAG));
    PyDict_SetItemString(d, "GSS_C_SEQUENCE_FLAG", PyInt_FromLong(GSS_C_SEQUENCE_FLAG));
    PyDict_SetItemString(d, "GSS_C_CONF_FLAG", PyInt_FromLong(GSS_C_CONF_FLAG));
    PyDict_SetItemString(d, "GSS_C_INTEG_FLAG", PyInt_FromLong(GSS_C_INTEG_FLAG));
    PyDict_SetItemString(d, "GSS_C_ANON_FLAG", PyInt_FromLong(GSS_C_ANON_FLAG));
    PyDict_SetItemString(d, "GSS_C_PROT_READY_FLAG", PyInt_FromLong(GSS_C_PROT_READY_FLAG));
    PyDict_SetItemString(d, "GSS_C_TRANS_FLAG", PyInt_FromLong(GSS_C_TRANS_FLAG));

error:
    if (PyErr_Occurred())
        PyErr_SetString(PyExc_ImportError, "kerberos: init failed");
}
示例#17
0
PyObject *scribus_actualpage(PyObject* /* self */)
{
	if(!checkHaveDocument())
		return NULL;
	return PyInt_FromLong(static_cast<long>(ScCore->primaryMainWindow()->doc->currentPageNumber() + 1));
}
示例#18
0
void
conn_notifies_process(connectionObject *self)
{
    PGnotify *pgn = NULL;
    PyObject *notify = NULL;
    PyObject *pid = NULL, *channel = NULL, *payload = NULL;
    PyObject *tmp = NULL;

    static PyObject *append;

    if (!append) {
        if (!(append = Text_FromUTF8("append"))) {
            goto error;
        }
    }

    while ((pgn = PQnotifies(self->pgconn)) != NULL) {

        Dprintf("conn_notifies_process: got NOTIFY from pid %d, msg = %s",
                (int) pgn->be_pid, pgn->relname);

        if (!(pid = PyInt_FromLong((long)pgn->be_pid))) {
            goto error;
        }
        if (!(channel = conn_text_from_chars(self, pgn->relname))) {
            goto error;
        }
        if (!(payload = conn_text_from_chars(self, pgn->extra))) {
            goto error;
        }

        if (!(notify = PyObject_CallFunctionObjArgs((PyObject *)&notifyType,
                       pid, channel, payload, NULL))) {
            goto error;
        }

        Py_DECREF(pid);
        pid = NULL;
        Py_DECREF(channel);
        channel = NULL;
        Py_DECREF(payload);
        payload = NULL;

        if (!(tmp = PyObject_CallMethodObjArgs(
                        self->notifies, append, notify, NULL))) {
            goto error;
        }
        Py_DECREF(tmp);
        tmp = NULL;

        Py_DECREF(notify);
        notify = NULL;
        PQfreemem(pgn);
        pgn = NULL;
    }
    return;  /* no error */

error:
    if (pgn) {
        PQfreemem(pgn);
    }
    Py_XDECREF(tmp);
    Py_XDECREF(notify);
    Py_XDECREF(pid);
    Py_XDECREF(channel);
    Py_XDECREF(payload);

    /* TODO: callers currently don't expect an error from us */
    PyErr_Clear();

}
示例#19
0
static PyObject *
make_public_browseable (WCSdpServicePyObject *self)
{
    SDP_RETURN_CODE result = self->sdpservice->MakePublicBrowseable ();
    return PyInt_FromLong (result);
}
示例#20
0
文件: sys.cpp 项目: FashGek/pyston
Box* sysGetRecursionLimit() {
    return PyInt_FromLong(Py_GetRecursionLimit());
}
示例#21
0
static PyObject*
Snmp_op(SnmpObject *self, PyObject *args, int op)
{
	PyObject *roid, *oids, *item, *deferred = NULL, *req = NULL;
	char *aoid, *next;
	oid poid[MAX_OID_LEN];
	struct snmp_pdu *pdu=NULL;
	int maxrepetitions = 10, norepeaters = 0;
	int i, oidlen, reqid;
	size_t arglen;

	if (op == SNMP_MSG_GETBULK) {
		if (!PyArg_ParseTuple(args, "O|ii",
			&roid, &maxrepetitions, &norepeaters))
			return NULL;
	} else {
		if (!PyArg_ParseTuple(args, "O", &roid))
			return NULL;
	}

	/* Turn the first argument into a tuple */
	if (!PyTuple_Check(roid) && !PyList_Check(roid) && !PyString_Check(roid)) {
		PyErr_SetString(PyExc_TypeError,
		    "argument should be a string, a list or a tuple");
		return NULL;
	}
	if (PyString_Check(roid)) {
		if ((oids = PyTuple_Pack(1, roid)) == NULL)
			return NULL;
	} else if (PyList_Check(roid)) {
		if ((oids = PyList_AsTuple(roid)) == NULL)
			return NULL;
	} else {
		oids = roid;
		Py_INCREF(oids);
	}
	
	Py_INCREF(self);
	arglen = PyTuple_Size(oids);
	pdu = snmp_pdu_create(op);
	if (op == SNMP_MSG_GETBULK) {
		pdu->max_repetitions = maxrepetitions;
		pdu->non_repeaters = norepeaters;
	}
	for (i = 0; i < arglen; i++) {
		if ((item = PyTuple_GetItem(oids, i)) == NULL)
			goto operror;
		if (!PyString_Check(item)) {
			PyErr_Format(PyExc_TypeError,
			    "element %d should be a string", i);
			goto operror;
		}
		aoid = PyString_AsString(item);
		oidlen = 0;
		while (aoid && (*aoid != '\0')) {
			if (aoid[0] == '.')
				aoid++;
			if (oidlen >= MAX_OID_LEN) {
				PyErr_Format(PyExc_ValueError,
				    "element %d is too large for OID", i);
				goto operror;
			}
			poid[oidlen++] = strtoull(aoid, &next, 10);
			if (aoid == next) {
				PyErr_Format(PyExc_TypeError,
				    "element %d is not a valid OID: %s", i, aoid);
				goto operror;
			}
			aoid = next;
		}
		snmp_add_null_var(pdu, poid, oidlen);
	}
	self->ss->callback = Snmp_handle;
	self->ss->callback_magic = self;
	if ((deferred = PyObject_CallMethod(DeferModule,
		    "Deferred", NULL)) == NULL)
		goto operror;
	if (!snmp_send(self->ss, pdu)) {
		Snmp_raise_error(self->ss);
		/* Instead of raising, we will fire errback */
		Snmp_invokeerrback(deferred);
		Py_DECREF(self);
		Py_DECREF(oids);
		snmp_free_pdu(pdu);
		return deferred;
	}
	reqid = pdu->reqid;
	pdu = NULL;		/* Avoid to free it when future errors occurs */

	/* We create a Deferred object and put it in a dictionary using
	 * pdu->reqid to be able to call its callbacks later. */
	if ((req = PyInt_FromLong(reqid)) == NULL)
		goto operror;
	if (PyDict_SetItem(self->defers, req, deferred) != 0) {
		Py_DECREF(req);
		goto operror;
	}
	Py_DECREF(req);
	if (Snmp_updatereactor() == -1)
		goto operror;
	Py_DECREF(oids);
	return deferred;
	
operror:
	Py_XDECREF(deferred);
	Py_DECREF(self);
	Py_DECREF(oids);
	snmp_free_pdu(pdu);
	return NULL;
}
示例#22
0
文件: sys.cpp 项目: FashGek/pyston
void setupSys() {
    sys_modules_dict = new BoxedDict();
    gc::registerPermanentRoot(sys_modules_dict);

    // This is ok to call here because we've already created the sys_modules_dict
    sys_module = createModule("sys");

    sys_module->giveAttr("modules", sys_modules_dict);

    BoxedList* sys_path = new BoxedList();
    sys_module->giveAttr("path", sys_path);

    sys_module->giveAttr("argv", new BoxedList());

    sys_module->giveAttr("stdout", new BoxedFile(stdout, "<stdout>", "w"));
    sys_module->giveAttr("stdin", new BoxedFile(stdin, "<stdin>", "r"));
    sys_module->giveAttr("stderr", new BoxedFile(stderr, "<stderr>", "w"));
    sys_module->giveAttr("__stdout__", sys_module->getattr(internStringMortal("stdout")));
    sys_module->giveAttr("__stdin__", sys_module->getattr(internStringMortal("stdin")));
    sys_module->giveAttr("__stderr__", sys_module->getattr(internStringMortal("stderr")));

    sys_module->giveAttr(
        "exc_info", new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)sysExcInfo, BOXED_TUPLE, 0), "exc_info"));
    sys_module->giveAttr("exc_clear",
                         new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)sysExcClear, NONE, 0), "exc_clear"));
    sys_module->giveAttr("exit", new BoxedBuiltinFunctionOrMethod(
                                     boxRTFunction((void*)sysExit, NONE, 1, 1, false, false), "exit", { None }));

    sys_module->giveAttr("warnoptions", new BoxedList());
    sys_module->giveAttr("py3kwarning", False);
    sys_module->giveAttr("byteorder", boxString(isLittleEndian() ? "little" : "big"));

    sys_module->giveAttr("platform", boxString(Py_GetPlatform()));

    sys_module->giveAttr("executable", boxString(Py_GetProgramFullPath()));

    sys_module->giveAttr("_getframe",
                         new BoxedFunction(boxRTFunction((void*)sysGetFrame, UNKNOWN, 1, 1, false, false), { NULL }));
    sys_module->giveAttr(
        "getdefaultencoding",
        new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)sysGetDefaultEncoding, STR, 0), "getdefaultencoding"));

    sys_module->giveAttr("getfilesystemencoding",
                         new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)sysGetFilesystemEncoding, STR, 0),
                                                          "getfilesystemencoding"));

    sys_module->giveAttr(
        "getrecursionlimit",
        new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)sysGetRecursionLimit, UNKNOWN, 0), "getrecursionlimit"));

    sys_module->giveAttr("meta_path", new BoxedList());
    sys_module->giveAttr("path_hooks", new BoxedList());
    sys_module->giveAttr("path_importer_cache", new BoxedDict());

    // As we don't support compile() etc yet force 'dont_write_bytecode' to true.
    sys_module->giveAttr("dont_write_bytecode", True);

    sys_module->giveAttr("prefix", boxString(Py_GetPrefix()));
    sys_module->giveAttr("exec_prefix", boxString(Py_GetExecPrefix()));

    sys_module->giveAttr("copyright",
                         boxString("Copyright 2014-2015 Dropbox.\nAll Rights Reserved.\n\nCopyright (c) 2001-2014 "
                                   "Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 "
                                   "BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for "
                                   "National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) "
                                   "1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved."));

    sys_module->giveAttr("version", boxString(generateVersionString()));
    sys_module->giveAttr("hexversion", boxInt(PY_VERSION_HEX));
    // TODO: this should be a "sys.version_info" object, not just a tuple (ie can access fields by name)
    sys_module->giveAttr("version_info",
                         BoxedTuple::create({ boxInt(PYTHON_VERSION_MAJOR), boxInt(PYTHON_VERSION_MINOR),
                                              boxInt(PYTHON_VERSION_MICRO), boxString("beta"), boxInt(0) }));

    sys_module->giveAttr("maxint", boxInt(PYSTON_INT_MAX));
    sys_module->giveAttr("maxsize", boxInt(PY_SSIZE_T_MAX));

    sys_flags_cls = new (0) BoxedHeapClass(object_cls, BoxedSysFlags::gcHandler, 0, 0, sizeof(BoxedSysFlags), false,
                                           static_cast<BoxedString*>(boxString("flags")));
    sys_flags_cls->giveAttr("__new__",
                            new BoxedFunction(boxRTFunction((void*)BoxedSysFlags::__new__, UNKNOWN, 1, 0, true, true)));
#define ADD(name)                                                                                                      \
    sys_flags_cls->giveAttr(STRINGIFY(name),                                                                           \
                            new BoxedMemberDescriptor(BoxedMemberDescriptor::OBJECT, offsetof(BoxedSysFlags, name)))
    ADD(division_warning);
    ADD(bytes_warning);
    ADD(no_user_site);
    ADD(optimize);
#undef ADD

#define SET_SYS_FROM_STRING(key, value) sys_module->giveAttr((key), (value))
#ifdef Py_USING_UNICODE
    SET_SYS_FROM_STRING("maxunicode", PyInt_FromLong(PyUnicode_GetMax()));
#endif

    sys_flags_cls->tp_mro = BoxedTuple::create({ sys_flags_cls, object_cls });
    sys_flags_cls->freeze();

    for (auto& md : sys_methods) {
        sys_module->giveAttr(md.ml_name, new BoxedCApiFunction(&md, sys_module));
    }

    sys_module->giveAttr("__displayhook__", sys_module->getattr(internStringMortal("displayhook")));
    sys_module->giveAttr("flags", new BoxedSysFlags());
}
示例#23
0
static PyObject*
SnmpReader_fileno(SnmpReaderObject *self)
{
	return PyInt_FromLong(self->fd);
}
示例#24
0
static PyObject* pyControlKeyEventData_getControlKey(pyControlKeyEventData* self, void*) {
    return PyInt_FromLong(self->fThis->getControlKey());
}
示例#25
0
static PyObject* pyEncryptedStream_getEncType(pyEncryptedStream* self) {
    return PyInt_FromLong(self->fThis->getEncType());
}
示例#26
0
static void gevent_loop() {

	if (!uwsgi.has_threads && uwsgi.mywid == 1) {
		uwsgi_log("!!! Running gevent without threads IS NOT recommended, enable them with --enable-threads !!!\n");
	}

	if (uwsgi.shared->options[UWSGI_OPTION_SOCKET_TIMEOUT] < 30) {
		uwsgi_log("!!! Running gevent with a socket-timeout lower than 30 seconds is not recommended, tune it with --socket-timeout !!!\n");
	}

	// get the GIL
	UWSGI_GET_GIL

	up.gil_get = gil_gevent_get;
	up.gil_release = gil_gevent_release;

	uwsgi.wait_write_hook = uwsgi_gevent_wait_write_hook;
	uwsgi.wait_read_hook = uwsgi_gevent_wait_read_hook;

	struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;

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

	uwsgi.current_wsgi_req = uwsgi_gevent_current_wsgi_req;

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

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

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

	// call gevent.monkey.patch_all() if requested
	if (ugevent.monkey) {
		PyObject *gevent_monkey_dict = get_uwsgi_pydict("gevent.monkey");
		if (!gevent_monkey_dict) uwsgi_pyexit;
		PyObject *gevent_monkey_patch_all = PyDict_GetItemString(gevent_monkey_dict, "patch_all");
        	if (!gevent_monkey_patch_all) uwsgi_pyexit;
		PyObject *ret = python_call(gevent_monkey_patch_all, PyTuple_New(0), 0, NULL);
		if (!ret) uwsgi_pyexit;
	}

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

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

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

	ugevent.greenlet_switch_args = PyTuple_New(0);
	Py_INCREF(ugevent.greenlet_switch_args);
	
	PyObject *gevent_get_hub = PyDict_GetItemString(gevent_dict, "get_hub");

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

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

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

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

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

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

	// pre-fill the greenlet args
	ugevent.greenlet_args = PyTuple_New(2);
	PyTuple_SetItem(ugevent.greenlet_args, 0, uwsgi_request_greenlet);
		
	if (uwsgi.signal_socket > -1) {
		// and these are the watcher for signal sockets

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

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

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

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

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

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

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

	}

	// start a greenlet for each socket
	ugevent.watchers = uwsgi_malloc(sizeof(PyObject *) * uwsgi_count_sockets(uwsgi.sockets));
	int i = 0;
	while(uwsgi_sock) {
		// this is the watcher for server socket
		ugevent.watchers[i] = PyObject_CallMethod(ugevent.hub_loop, "io", "ii", uwsgi_sock->fd, 1);
		if (!ugevent.watchers[i]) uwsgi_pyexit;
	
		// start the main greenlet
		PyObject_CallMethod(ugevent.watchers[i], "start", "Ol", uwsgi_gevent_main,(long)uwsgi_sock);
		uwsgi_sock = uwsgi_sock->next;
		i++;
	}

	// patch goodbye_cruel_world
	uwsgi.gbcw_hook = uwsgi_gevent_gbcw;

	// map SIGHUP with gevent.signal
	PyObject *ge_signal_tuple = PyTuple_New(2);
	PyTuple_SetItem(ge_signal_tuple, 0, PyInt_FromLong(SIGHUP));
	PyObject *uwsgi_gevent_unix_signal_handler = PyCFunction_New(uwsgi_gevent_unix_signal_handler_def, NULL);
        Py_INCREF(uwsgi_gevent_unix_signal_handler);
	PyTuple_SetItem(ge_signal_tuple, 1, uwsgi_gevent_unix_signal_handler);

	python_call(ugevent.signal, ge_signal_tuple, 0, NULL);

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

	if (uwsgi.workers[uwsgi.mywid].manage_next_request == 0) {
		uwsgi_log("goodbye to the gevent Hub on worker %d (pid: %d)\n", uwsgi.mywid, uwsgi.mypid);
		if (ugevent.destroy) {
			exit(0);
		}
		exit(UWSGI_RELOAD_CODE);
	}

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

}
示例#27
0
文件: ceval.c 项目: Oxyd76/cleese
static PyObject *
eval_frame(PyFrameObject *f)
{
	LOG("> eval_frame\n");
	PyObject **stack_pointer; /* Next free slot in value stack */
	register unsigned char *next_instr;
	register int opcode=0;	/* Current opcode */
	register int oparg=0;	/* Current opcode argument, if any */
	register enum why_code why; /* Reason for block stack unwind */
	register int err;	/* Error status -- nonzero if error */
	register PyObject *x;	/* Result object -- NULL if error */
	register PyObject *v;	/* Temporary objects popped off stack */
	register PyObject *w;
	register PyObject **fastlocals, **freevars;
	PyObject *retval = NULL;	/* Return value */
	PyThreadState *tstate = PyThreadState_GET();
	PyCodeObject *co;

	unsigned char *first_instr;
	PyObject *names;
	PyObject *consts;

/* Tuple access macros */

#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))

/* Code access macros */

#define INSTR_OFFSET()	(next_instr - first_instr)
#define NEXTOP()	(*next_instr++)
#define NEXTARG()	(next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
#define JUMPTO(x)	(next_instr = first_instr + (x))
#define JUMPBY(x)	(next_instr += (x))

/* OpCode prediction macros
	Some opcodes tend to come in pairs thus making it possible to predict
	the second code when the first is run.  For example, COMPARE_OP is often
	followed by JUMP_IF_FALSE or JUMP_IF_TRUE.  And, those opcodes are often
	followed by a POP_TOP.

	Verifying the prediction costs a single high-speed test of register
	variable against a constant.  If the pairing was good, then the
	processor has a high likelihood of making its own successful branch
	prediction which results in a nearly zero overhead transition to the
	next opcode.

	A successful prediction saves a trip through the eval-loop including
	its two unpredictable branches, the HASARG test and the switch-case.
*/

#define PREDICT(op)		if (*next_instr == op) goto PRED_##op
#define PREDICTED(op)		PRED_##op: next_instr++
#define PREDICTED_WITH_ARG(op)	PRED_##op: oparg = (next_instr[2]<<8) + \
				next_instr[1]; next_instr += 3

/* Stack manipulation macros */

#define STACK_LEVEL()	(stack_pointer - f->f_valuestack)
#define EMPTY()		(STACK_LEVEL() == 0)
#define TOP()		(stack_pointer[-1])
#define SECOND()	(stack_pointer[-2])
#define THIRD() 	(stack_pointer[-3])
#define FOURTH()	(stack_pointer[-4])
#define SET_TOP(v)	(stack_pointer[-1] = (v))
#define SET_SECOND(v)	(stack_pointer[-2] = (v))
#define SET_THIRD(v)	(stack_pointer[-3] = (v))
#define SET_FOURTH(v)	(stack_pointer[-4] = (v))
#define BASIC_STACKADJ(n)	(stack_pointer += n)
#define BASIC_PUSH(v)	(*stack_pointer++ = (v))
#define BASIC_POP()	(*--stack_pointer)

#define PUSH(v)		BASIC_PUSH(v)
#define POP()		BASIC_POP()
#define STACKADJ(n)	BASIC_STACKADJ(n)

/* Local variable macros */

#define GETLOCAL(i)	(fastlocals[i])

/* The SETLOCAL() macro must not DECREF the local variable in-place and
   then store the new value; it must copy the old value to a temporary
   value, then store the new value, and then DECREF the temporary value.
   This is because it is possible that during the DECREF the frame is
   accessed by other code (e.g. a __del__ method or gc.collect()) and the
   variable would be pointing to already-freed memory. */
#define SETLOCAL(i, value)	do { PyObject *tmp = GETLOCAL(i); \
				     GETLOCAL(i) = value; \
                                     Py_XDECREF(tmp); } while (0)

/* Start of code */

	if (f == NULL)
		return NULL;

	/* push frame */
	if (++tstate->recursion_depth > recursion_limit) {
		--tstate->recursion_depth;
		/* ERROR */
		tstate->frame = f->f_back;
		return NULL;
	}

	tstate->frame = f;

	/* tracing elided */

	co = f->f_code;
	names = co->co_names;
	consts = co->co_consts;
	fastlocals = f->f_localsplus;
	freevars = f->f_localsplus + f->f_nlocals;

	_PyCode_GETCODEPTR(co, &first_instr);

	/* An explanation is in order for the next line.

	   f->f_lasti now refers to the index of the last instruction
	   executed.  You might think this was obvious from the name, but
	   this wasn't always true before 2.3!  PyFrame_New now sets
	   f->f_lasti to -1 (i.e. the index *before* the first instruction)
	   and YIELD_VALUE doesn't fiddle with f_lasti any more.  So this
	   does work.  Promise. */
	next_instr = first_instr + f->f_lasti + 1;
	stack_pointer = f->f_stacktop;

	f->f_stacktop = NULL;	/* remains NULL unless yield suspends frame */

	why = WHY_NOT;
	err = 0;
	x = Py_None;	/* Not a reference, just anything non-NULL */
	w = NULL;

	for (;;) {

	  /* @@@ pending calls elided */

	fast_next_opcode:
		f->f_lasti = INSTR_OFFSET();

		/* Extract opcode and argument */

		opcode = NEXTOP();
		if (HAS_ARG(opcode))
			oparg = NEXTARG();

		/* Main switch on opcode */

		switch (opcode) {

		/* BEWARE!
		   It is essential that any operation that fails sets either
		   x to NULL, err to nonzero, or why to anything but WHY_NOT,
		   and that no operation that succeeds does this! */

		/* case STOP_CODE: this is an error! */

		case LOAD_CONST:
			x = GETITEM(consts, oparg);
			Py_INCREF(x);
			PUSH(x);
			goto fast_next_opcode;

		case BINARY_ADD:
			w = POP();
			v = TOP();
			if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
				/* INLINE: int + int */
				register long a, b, i;
				a = PyInt_AS_LONG(v);
				b = PyInt_AS_LONG(w);
				i = a + b;
				if ((i^a) < 0 && (i^b) < 0)
					goto slow_add;
				x = PyInt_FromLong(i);
			}
			else {
			  slow_add:
				Py_FatalError("slow add not supported.");
			}
			Py_DECREF(v);
			Py_DECREF(w);
			SET_TOP(x);
			if (x != NULL) continue;
			break;

		case PRINT_ITEM:
			v = POP();

			PyObject_Print(v);
			Py_DECREF(v);
			break;

		case PRINT_NEWLINE:
			printf("\n");
			break;

		case RETURN_VALUE:
			retval = POP();
			why = WHY_RETURN;
			break;

		default:
		  Py_FatalError("unknown opcode");
		} /* switch */

		if (why == WHY_NOT) {
			if (err == 0 && x != NULL) {
					continue; /* Normal, fast path */
			}
			why = WHY_EXCEPTION;
			x = Py_None;
			err = 0;
		}

		/* End the loop if we still have an error (or return) */

		if (why != WHY_NOT)
			break;

	} /* main loop */

	if (why != WHY_YIELD) {
		/* Pop remaining stack entries -- but when yielding */
		while (!EMPTY()) {
			v = POP();
			Py_XDECREF(v);
		}
	}

	if (why != WHY_RETURN && why != WHY_YIELD)
		retval = NULL;

	/* pop frame */
	--tstate->recursion_depth;
	tstate->frame = f->f_back;

	return retval;
}
示例#28
0
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGOleCommandTarget::QueryStatus(
		/* [unique][in] */ const GUID * pguidCmdGroup,
		/* [in] */ ULONG cCmds,
		/* [out][in][size_is] */ OLECMD prgCmds[],
		/* [unique][out][in] */ OLECMDTEXT * pCmdText)
{
	PY_GATEWAY_METHOD;
	PyObject *obGUID;
	if (pguidCmdGroup == NULL) {
		obGUID = Py_None;
		Py_INCREF(obGUID);
	} else {
		obGUID = PyWinObject_FromIID(*pguidCmdGroup);
	}
	PyObject *cmds = PyList_New(cCmds);
	if (!cmds) {
		Py_DECREF(obGUID);
		MAKE_PYCOM_GATEWAY_FAILURE_CODE("QueryStatus");
	}
	for (ULONG i=0;i<cCmds;i++) {
		PyList_SET_ITEM(cmds, i,
				Py_BuildValue("ll", prgCmds[i].cmdID, prgCmds[i].cmdf));
	}
	PyObject *obText;
	if (!pCmdText) {
		obText = Py_None;
		Py_INCREF(Py_None);
	} else
		obText = PyInt_FromLong(pCmdText->cmdtextf);
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("QueryStatus", &result, "NNN", obGUID, cmds, obText);
	if (FAILED(hr)) return hr;

	BOOL ok = PyArg_ParseTuple(result, "OO", &cmds, &obText);
	if (ok) {
		if (pCmdText == NULL) {
			if (obText != Py_None) {
				PyErr_SetString(PyExc_ValueError,
						"String value returned but caller didn't request it (check the 3rd param!)");
				ok = FALSE;
			}
		} else {
			PyWin_AutoFreeBstr tempString;
			ok = PyWinObject_AsAutoFreeBstr(obText, &tempString);
			if (ok) {
				UINT strLen = SysStringLen(tempString);
				UINT nwrite = min(strLen, pCmdText->cwBuf);
				wcsncpy(pCmdText->rgwz, (WCHAR *)(BSTR)tempString,
					nwrite);
				pCmdText->cwActual = nwrite;
			}
		}
	}
	if (ok) {
		if (!PySequence_Check(cmds)) {
			PyErr_SetString(PyExc_TypeError, "OLECMD objects must be a sequence");
			ok = FALSE;
		}
		if (ok && (UINT)PySequence_Length(cmds) != cCmds) {
			PyErr_Format(PyExc_ValueError, "Sequence must have %d items (got %d)",
				     cCmds, PySequence_Length(cmds));
			ok = FALSE;
			
		}
		if (ok)
			ok = FillOLECMDsWithSequence(prgCmds, cCmds, cmds);
	}
	Py_DECREF(result);
	if (!ok)
		hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("QueryStatus");
	return hr;
}
示例#29
0
static PyObject *t_locale_getLCID(t_locale *self)
{
    return PyInt_FromLong(self->object->getLCID());
}
示例#30
0
static int Printer_init(Printer *self, PyObject * /*args*/, PyObject * /*kwds*/)
{
// pool system for installed printers
// most code is stolen and little adopted from druck.cpp
	PyObject *allPrinters = PyList_New(0);
	if (allPrinters){
		Py_DECREF(self->allPrinters);
		self->allPrinters = allPrinters;
	}
	QStringList printers = PrinterUtil::getPrinterNames();
	for (int i = 0; i < printers.count(); ++i)
	{
		QString prn = printers[i];
		if (prn.isEmpty())
			continue;
		PyObject *tmppr = PyString_FromString(prn.toLocal8Bit().constData());
		if (tmppr){
			PyList_Append(self->allPrinters, tmppr);
			Py_DECREF(tmppr);
		}
	}
	PyObject *tmp2 = PyString_FromString("File");
	PyList_Append(self->allPrinters, tmp2);
	Py_DECREF(tmp2);
// as defaut set to print into file
	PyObject *printer = NULL;
	printer = PyString_FromString("File");
	if (printer){
		Py_DECREF(self->printer);
		self->printer = printer;
	}
// set defaul name of file to print into
	QString tf = ScCore->primaryMainWindow()->doc->PDF_Options.fileName;
	if (tf.isEmpty()) {
		QFileInfo fi = QFileInfo(ScCore->primaryMainWindow()->doc->DocName);
		tf = fi.path()+"/"+fi.baseName()+".pdf";
	}
	PyObject *file = NULL;
	file = PyString_FromString(tf.toAscii());
	if (file){
		Py_DECREF(self->file);
		self->file = file;
	} else {
		PyErr_SetString(PyExc_SystemError, "Can not initialize 'file' attribute");
		return -1;
	}
// alternative printer commands default to ""
	PyObject *cmd = NULL;
	cmd = PyString_FromString("");
	if (cmd){
		Py_DECREF(self->cmd);
		self->cmd = cmd;
	}
// if document exist when created Printer instance
// set to print all pages
	PyObject *pages = NULL;
	int num = 0;
	if (ScCore->primaryMainWindow()->HaveDoc)
		// which one should I use ???
		// new = ScCore->primaryMainWindow()->view->Pages.count()
		num = ScCore->primaryMainWindow()->doc->Pages->count();
	pages = PyList_New(num);
	if (pages){
		Py_DECREF(self->pages);
		self->pages = pages;
	}
	for (int i = 0; i<num; i++) {
		PyObject *tmp=NULL;
		tmp = PyInt_FromLong((long)i+1L); // instead of 1 put here first page number
		if (tmp)
			PyList_SetItem(self->pages, i, tmp);
	}
// do not print separation
	PyObject *separation = NULL;
	separation = PyString_FromString("No");
	if (separation){
		Py_DECREF(self->separation);
		self->separation = separation;
	}
// print in color
	self->color = 1;
// do not use ICC Profile
	self->useICC = 0;
// use PostScrip level 3
	self->pslevel = 3;
// do not mirror pages
	self->mph = 0;
// do not mirror pages
	self->mpv = 0;
// apply Under Color Removal as default
	self->ucr = 1;
// number of copies
	self->copies = 1;
	return 0;
}