예제 #1
0
static int igraphmodule_i_filehandle_init_cpython_2(igraphmodule_filehandle_t* handle,
        PyObject* object, char* mode) {
    FILE* fp;
    PyObject* fileno_method;
    PyObject* fileno_result;
    int fileno = -1;

    if (object == 0) {
        PyErr_SetString(PyExc_TypeError, "trying to convert a null object "
                "to a file handle");
        return 1;
    }

    handle->object = 0;
    handle->need_close = 0;

    if (PyBaseString_Check(object)) {
        /* We have received a string; we need to open the file denoted by this
         * string now and mark that we opened the file ourselves (so we need
         * to close it when igraphmodule_filehandle_destroy is invoked). */
        handle->object = PyFile_FromString(PyString_AsString(object), mode);
        if (handle->object == 0) {
            /* Could not open the file; just return an error code because an
             * exception was raised already */
            return 1;
        }
        /* Remember that we need to close the file ourselves */
        handle->need_close = 1;
        /* Get a FILE* object from the file */
        fp = PyFile_AsFile(handle->object);
    } else if (PyFile_Check(object)) {
        /* This is a file-like object; store a reference for it and
         * we will handle it later */
        handle->object = object;
        Py_INCREF(handle->object);
        /* Get a FILE* object from the file */
        fp = PyFile_AsFile(handle->object);
    } else {
        /* Check whether the object has a fileno() method. If so, we convert
         * that to a file descriptor and then fdopen() it */
        fileno_method = PyObject_GetAttrString(object, "fileno");
        if (fileno_method != 0) {
            if (PyCallable_Check(fileno_method)) {
                fileno_result = PyObject_CallObject(fileno_method, 0);
                Py_DECREF(fileno_method);
                if (fileno_result != 0) {
                    if (PyInt_Check(fileno_result)) {
                        fileno = (int)PyInt_AsLong(fileno_result);
                        Py_DECREF(fileno_result);
                    } else {
                        Py_DECREF(fileno_result);
                        PyErr_SetString(PyExc_TypeError,
                                "fileno() method of file-like object should return "
                                "an integer");
                        return 1;
                    }
                } else {
                    /* Exception set already by PyObject_CallObject() */
                    return 1;
                }
            } else {
                Py_DECREF(fileno_method);
                PyErr_SetString(PyExc_TypeError,
                        "fileno() attribute of file-like object must be callable");
                return 1;
            }
        } else {
            PyErr_SetString(PyExc_TypeError, "expected filename or file-like object");
                return 1;
        }

        if (fileno > 0) {
            fp = fdopen(fileno, mode);
        } else {
            PyErr_SetString(PyExc_ValueError, "fileno() method returned invalid "
                    "file descriptor");
            return 1;
        }
    }

    handle->fp = fp;
    if (handle->fp == 0) {
        igraphmodule_filehandle_destroy(handle);
        /* This already called Py_DECREF(handle->object), no need to call it */
        PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly");
        return 1;
    }

    return 0;
}
예제 #2
0
파일: main.c 프로젝트: yampolskiy/sslscan
/**
 * Parse commandline args
 */
int parse_args(int argc, char *argv[], struct sslCheckOptions *options)
{
	PyObject *py_tmp;
	int i;

	PyObject *py_config_set = PyObject_GetAttrString(options->py_config, "set_value");

	// Get program parameters
	for (i = 1; i < argc; i++)
	{
		if (strcmp("--help", argv[i]) == 0) {
			print_help(argv[0], options);
			return 0;
		}

		if ((strncmp("--help-output=", argv[i], 14) == 0) && (strlen(argv[i]) > 14)) {
			py_tmp = Py_BuildValue("(s)", argv[i] + 14);
			return py_call_function(options->py_output_handler, "print_help_verbose", py_tmp, NULL);
		}

		if (strcmp("--help-outputs", argv[i]) == 0) {
			return py_call_function(options->py_output_handler, "print_help", NULL, NULL);
		}

		if (strcmp("--help-output-list", argv[i]) == 0) {
			return py_call_function(options->py_output_handler, "print_list", NULL, NULL);
		}

		if ((strncmp("--targets=", argv[i], 10) == 0) && (strlen(argv[i]) > 10)) {
			options->targets = argv[i] + 10;
			continue;
		}

		if ((strcmp("--ipv4", argv[i]) == 0)) {
			options->forceAddressFamily = FORCE_AF_INET4;
			continue;
		}

		if ((strcmp("--ipv6", argv[i]) == 0)) {
			options->forceAddressFamily = FORCE_AF_INET6;
			continue;
		}

		if ((strncmp("--localip=", argv[i], 10) == 0) && (strlen(argv[i]) > 10)) {
			options->bindLocalAddress = true;
			strncpy(options->localAddress, argv[i] + 10, sizeof(options->localAddress));
			continue;
		}

		if ((strncmp("--connection_delay=", argv[i], 19) == 0) && (strlen(argv[i]) > 19)) {
			options->connection_delay = strtol(argv[i] + 19, NULL, 10);
			continue;
		}

		if (strcmp("--no-failed", argv[i]) == 0) {
			options->noFailed = true;
			continue;
		}

		if (strcmp("--version", argv[i]) == 0) {
			print_version();
			return 0;
		}

		if (strncmp("--xml=", argv[i], 6) == 0) {
			//ToDo
			//xmlArg = i;
			continue;
		}

		if (strcmp("--verbose", argv[i]) == 0) {
			options->verbose = true;
			continue;
		}

		if (strcmp("-p", argv[i]) == 0) {
			options->pout = true;
			continue;
		}

		// Client Certificates
		if (strncmp("--certs=", argv[i], 8) == 0) {
			options->clientCertsFile = argv[i] +8;
			continue;
		}

		// Private Key File
		if (strncmp("--pk=", argv[i], 5) == 0) {
			options->privateKeyFile = argv[i] +5;
			continue;
		}

		// Private Key Password
		if (strncmp("--pkpass="******"--renegotiation", argv[i]) == 0) {
			options->reneg = true;
			continue;
		}

		// StartTLS... FTP
		if (strcmp("--starttls-ftp", argv[i]) == 0) {
			options->ssl_versions = tls_v10;
			options->starttls_ftp = true;
			continue;
		}

		// StartTLS... IMAP
		if (strcmp("--starttls-imap", argv[i]) == 0) {
			options->ssl_versions = tls_v10;
			options->starttls_imap = true;
			continue;
		}

		// StartTLS... POP3
		if (strcmp("--starttls-pop3", argv[i]) == 0) {
			options->ssl_versions = tls_v10;
			options->starttls_pop3 = true;
			continue;
		}

		// StartTLS... SMTP
		if (strcmp("--starttls-smtp", argv[i]) == 0) {
			options->ssl_versions = tls_v10;
			options->starttls_smtp = true;
			continue;
		}

		// StartTLS... XMPP
		if (strcmp("--starttls-xmpp", argv[i]) == 0) {
			options->ssl_versions = tls_v10;
			options->starttls_xmpp = true;
			continue;
		}

		// XMPP... Domain
		if (strncmp("--xmpp-domain=", argv[i], 14) == 0) {
			options->xmpp_domain = argv[i] +14;
			continue;
		}

#ifndef OPENSSL_NO_SSL2
		if (strcmp("--ssl2", argv[i]) == 0) {
			options->ssl_versions = ssl_v2;
			continue;
		}
#endif // #ifndef OPENSSL_NO_SSL2

		if (strcmp("--ssl3", argv[i]) == 0) {
			options->ssl_versions = ssl_v3;
			continue;
		}

		if (strcmp("--tls1", argv[i]) == 0) {
			options->ssl_versions = tls_v10;
			continue;
		}

#if OPENSSL_VERSION_NUMBER >= 0x1000008fL || OPENSSL_VERSION_NUMBER >= 0x1000100fL
		if (strcmp("--tls11", argv[i]) == 0) {
			options->ssl_versions = tls_v11;
			continue;
		}

		if (strcmp("--tls12", argv[i]) == 0) {
			options->ssl_versions = tls_v12;
			continue;
		}
#endif // #if OPENSSL_VERSION_NUMBER >= 0x1000008fL || OPENSSL_VERSION_NUMBER >= 0x1000100fL

		if (strcmp("--no_ssl2", argv[i]) == 0) {
			options->ssl_versions &= ~ssl_v2;
			continue;
		}

		if (strcmp("--no_ssl3", argv[i]) == 0) {
			options->ssl_versions &= ~ssl_v3;
			continue;
		}

		if (strcmp("--no_tls1", argv[i]) == 0) {
			options->ssl_versions &= ~tls_v10;
			continue;
		}

		if (strcmp("--no_tls11", argv[i]) == 0) {
			options->ssl_versions &= ~tls_v11;
			continue;
		}

		if (strcmp("--no_tls12", argv[i]) == 0) {
			options->ssl_versions &= ~tls_v12;
			continue;
		}

		if (strcmp("--bugs", argv[i]) == 0) {
			options->sslbugs = 1;
			continue;
		}

		else if (strncmp("--scan_mode=", argv[i], 12) == 0) {
			if (strcmp("fast", argv[i] + 12) == 0) {
				options->scan_mode = SSLSCAN_SCAN_MODE_FAST;
				continue;
			}

			if (strcmp("full", argv[i] + 12) == 0) {
				options->scan_mode = SSLSCAN_SCAN_MODE_FULL;
				continue;
			}

			// ToDo: print error msg
			print_help(argv[0], options);
			return 0;
		}

		// SSL HTTP Get...
		else if (strcmp("--http", argv[i]) == 0) {
			options->http = 1;
			continue;
		}

		if (strncmp("--output=", argv[i], 9) == 0) {
			if(options->py_output_handler == NULL) {
				printf("No output handler");
				continue;
			}

			PyObject *py_func = PyObject_GetAttrString(options->py_output_handler, "load_from_string");
			PyObject *py_args = PyTuple_New(1);
			PyTuple_SetItem(py_args, 0, PyUnicode_FromString(argv[i] + 9));
			PyObject *py_result = PyObject_CallObject(py_func, py_args);
			if(py_result == NULL) {
				PyErr_Print();
			}
			continue;
		}

		if (strncmp("--", argv[i], 2) == 0) {
			PyObject *py_result;
			PyObject *py_args = PyTuple_New(1);
			PyTuple_SetItem(py_args, 0, PyUnicode_FromString(argv[i] + 2));
			py_call_function(options->py_config, "set_value_from_string", py_args, &py_result);
			if (PyObject_RichCompareBool(py_result, PyBool_FromLong(1), Py_EQ) == 1)
				continue;
		}

		// Host
		if (strncmp("--", argv[i], 2) != 0) {
			// Get host...
			parseHostString(argv[i], options);
			continue;
		}

		printf("Unknown option: '%s'\n", argv[i]);
		print_help(argv[0], options);
		// ToDo: define error codes
		return 1;
	}
	return 0;
}
예제 #3
0
TerrainChunk* terrain_chunk_read(Reader* r, int version) {
    PyObject* block_type_table = NULL;

    TerrainChunk* tc = (TerrainChunk*)PyObject_CallObject((PyObject*)&TerrainChunkType, NULL);
    FAIL_IF(tc == NULL);

    tc->version = version;
    tc->save = calloc(sizeof(TerrainChunkSave), 1);

    READ(tc->save->save_id);
    FAIL_IF(read_register_object(r, tc->save->save_id, (PyObject*)tc) < 0);
    READ(tc->stable_id);


    if (version >= 5) {
        READ(tc->flags);
    }

    uint16_t buf[1 << (3 * CHUNK_BITS)];
    READ(buf);

    block_type_table = read_block_type_table(r);
    FAIL_IF(block_type_table == NULL);
    for (int i = 0; i < 1 << (3 * CHUNK_BITS); ++i) {
        PyObject* key = PyLong_FromLong(buf[i]);
        FAIL_IF(key == NULL);

        PyObject* value = PyDict_GetItem(block_type_table, key);
        if (value == NULL) {
            Py_DECREF(key);
            goto fail;
        }

        Py_INCREF(value);
        if (PyList_SetItem(tc->blocks, i, value) < 0) {
            // XXX: SetItem does steal the reference even on failure, right?
            Py_DECREF(key);
            goto fail;
        }
    }
    Py_DECREF(block_type_table);
    block_type_table = NULL;


    // No script extras for TerrainChunk yet.
    if (version >= 999999) {
        tc->save->extra_raw = extra_read(r, version);
        FAIL_IF(tc->save->extra_raw  == NULL);
    } else {
        Py_INCREF(Py_None);
        tc->save->extra_raw = Py_None;
    }


    uint32_t count;
    READ(count);
    for (uint32_t i = 0; i < count; ++i) {
        Structure* obj = structure_read(r, version);
        FAIL_IF(obj == NULL);
        FAIL_IF(PyList_Append(tc->child_structures, (PyObject*)obj) == -1);
    }

    return tc;

fail:
    SET_EXC();
    Py_XDECREF(tc);
    Py_XDECREF(block_type_table);
    return NULL;
}
예제 #4
0
PyObject* objToJSONFile(PyObject* self, PyObject *args, PyObject *kwargs)
{
	PyObject *data;
	PyObject *file;
	PyObject *string;
	PyObject *write;
	PyObject *argtuple;

	PRINTMARK();

	if (!PyArg_ParseTuple (args, "OO", &data, &file)) {
		return NULL;
	}

	if (!PyObject_HasAttrString (file, "write"))
	{
		PyErr_Format (PyExc_TypeError, "expected file");
		return NULL;
	}

	write = PyObject_GetAttrString (file, "write");

	if (!PyCallable_Check (write)) {
		Py_XDECREF(write);
		PyErr_Format (PyExc_TypeError, "expected file");
		return NULL;
	}

	argtuple = PyTuple_Pack(1, data);

	string = objToJSON (self, argtuple, kwargs);

	if (string == NULL)
	{
		Py_XDECREF(write);
		Py_XDECREF(argtuple);
		return NULL;
	}

	argtuple = PyTuple_Pack (1, string);
	if (argtuple == NULL)
	{
		Py_XDECREF(write);
		return NULL;
	}
	if (PyObject_CallObject (write, argtuple) == NULL)
	{
		Py_XDECREF(write);
		Py_XDECREF(argtuple);
		return NULL;
	}

	Py_XDECREF(write);
	Py_XDECREF(argtuple);
	Py_XDECREF(string);

	PRINTMARK();

	Py_RETURN_NONE;
	

}
예제 #5
0
static PyObject *aqbanking_Account_transactions(aqbanking_Account* self, PyObject *args, PyObject *kwds)
{
	int rv;
	double tmpDateTime = 0;
	const char *bank_code;
	const char *account_no;
#if PY_VERSION_HEX >= 0x03030000
	bank_code = PyUnicode_AsUTF8(self->bank_code);
	account_no = PyUnicode_AsUTF8(self->no);
#else
	PyObject *s = _PyUnicode_AsDefaultEncodedString(self->bank_code, NULL);
	bank_code = PyBytes_AS_STRING(s);
	s = _PyUnicode_AsDefaultEncodedString(self->no, NULL);
	account_no = PyBytes_AS_STRING(s);
#endif
	GWEN_TIME *gwTime;
	const char *dateFrom=NULL, *dateTo=NULL;
	static char *kwlist[] = {"dateFrom", "dateTo", NULL};
	if (! PyArg_ParseTupleAndKeywords(args, kwds, "|ss", kwlist, &dateFrom, &dateTo))
	{
		return NULL;
	}

	AB_ACCOUNT *a;
	AB_JOB *job = 0;
	AB_JOB_LIST2 *jl = 0;
	AB_IMEXPORTER_CONTEXT *ctx = 0;
	AB_IMEXPORTER_ACCOUNTINFO *ai;
	/*aqbanking_Transaction *trans = NULL;*/
	PyObject *transList = PyList_New(0);

	// Valid data set?
	if (self->no == NULL)
	{
		PyErr_SetString(PyExc_AttributeError, "no");
	}
	if (self->bank_code == NULL)
	{
		PyErr_SetString(PyExc_AttributeError, "bank_code");
	}

	// Initialize aqbanking.
	rv = AB_create(self);
	if (rv > 0)
	{
		Py_DECREF(transList);
		return NULL;
	}

	// Let us find the account!
	a = AB_Banking_GetAccountByCodeAndNumber(self->ab, bank_code, account_no);
	if (!a)
	{
		PyErr_SetString(AccountNotFound, "Could not find the given account! ");
		Py_DECREF(transList);
		return NULL;
	}

	// Create job and execute it.
	job = AB_JobGetTransactions_new(a);
	if (dateFrom != NULL)
	{
		gwTime = GWEN_Time_fromString(dateFrom, "YYYYMMDD");
		AB_JobGetTransactions_SetFromTime(job, gwTime);
	}
	if (dateTo != NULL)
	{
		gwTime = GWEN_Time_fromString(dateTo, "YYYYMMDD");
		AB_JobGetTransactions_SetToTime(job, gwTime);
	}
	// Check for availability
	rv = AB_Job_CheckAvailability(job);
	if (rv) {
		PyErr_SetString(ExecutionFailed, "Transaction retrieval is not supported!");
		Py_DECREF(transList);
		return NULL;
	}

	jl = AB_Job_List2_new();
	AB_Job_List2_PushBack(jl, job);
	ctx = AB_ImExporterContext_new();
	rv = AB_Banking_ExecuteJobs(self->ab, jl, ctx);

	if (rv)
	{
		PyErr_SetString(ExecutionFailed, "Could not retrieve transactions!");
		Py_DECREF(transList);
		return NULL;
	}

	// With success. No process the result.
	ai = AB_ImExporterContext_GetFirstAccountInfo (ctx);
	while(ai)
	{
		const AB_TRANSACTION *t;
		
		t = AB_ImExporterAccountInfo_GetFirstTransaction(ai);
		while(t) {
			const AB_VALUE *v;
			AB_TRANSACTION_STATUS state;

			v=AB_Transaction_GetValue(t);
			if (v) {
				const GWEN_STRINGLIST *sl;
				const GWEN_TIME *tdtime;
				const char *purpose;
				const char *remoteName;
				aqbanking_Transaction *trans = (aqbanking_Transaction*) PyObject_CallObject((PyObject *) &aqbanking_TransactionType, NULL);

				/* The purpose (memo field) might contain multiple lines.
				 * Therefore AqBanking stores the purpose in a string list
				 * of which the first entry is used in this tutorial */
				sl = AB_Transaction_GetPurpose(t);
				if (sl)
				{
					purpose = GWEN_StringList_FirstString(sl);
					if (purpose == NULL) {
						purpose = "";
					}
				}
				else
				{
					purpose = "";
				}

#ifdef DEBUGSTDERR
				fprintf(stderr, "[%-10d]: [%-10s/%-10s][%-10s/%-10s] %-32s (%.2f %s)\n",
						AB_Transaction_GetUniqueId(t),
						AB_Transaction_GetRemoteIban(t),
						AB_Transaction_GetRemoteBic(t),
						AB_Transaction_GetRemoteAccountNumber(t),
						AB_Transaction_GetRemoteBankCode(t),
						purpose,
						AB_Value_GetValueAsDouble(v),
						AB_Value_GetCurrency(v)
				);
#endif

				tdtime = AB_Transaction_GetDate(t);
				tmpDateTime = PyLong_AsDouble(PyLong_FromSize_t(GWEN_Time_Seconds(tdtime)));
				trans->date = PyDate_FromTimestamp(Py_BuildValue("(O)", PyFloat_FromDouble(tmpDateTime)));
				tdtime = AB_Transaction_GetValutaDate(t);
				tmpDateTime = PyLong_AsDouble(PyLong_FromSize_t(GWEN_Time_Seconds(tdtime)));
				trans->valutaDate = PyDate_FromTimestamp(Py_BuildValue("(O)", PyFloat_FromDouble(tmpDateTime)));
				trans->purpose = PyUnicode_FromString(purpose);

				// Local user
				if (AB_Transaction_GetLocalAccountNumber(t) == NULL) {
					trans->localAccount = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->localAccount = PyUnicode_FromString(AB_Transaction_GetLocalAccountNumber(t));
				}
				if (AB_Transaction_GetLocalBankCode(t) == NULL) {
					trans->localBank = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->localBank = PyUnicode_FromString(AB_Transaction_GetLocalBankCode(t));
				}
				if (AB_Transaction_GetLocalIban(t) == NULL) {
					trans->localIban = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->localIban = PyUnicode_FromString(AB_Transaction_GetLocalIban(t));
				}
				if (AB_Transaction_GetLocalBic(t) == NULL) {
					trans->localBic = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->localBic = PyUnicode_FromString(AB_Transaction_GetLocalBic(t));
				}
				if (AB_Transaction_GetLocalName(t) == NULL) {
					trans->localName = Py_None;
					Py_INCREF(Py_None);
				} else {
				        trans->localName = PyUnicode_FromString(AB_Transaction_GetLocalName(t));
				}

				// Remote user
				if (AB_Transaction_GetRemoteAccountNumber(t) == NULL) {
					trans->remoteAccount = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->remoteAccount = PyUnicode_FromString(AB_Transaction_GetRemoteAccountNumber(t));
				}
				if (AB_Transaction_GetRemoteBankCode(t) == NULL) {
					trans->remoteBank = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->remoteBank = PyUnicode_FromString(AB_Transaction_GetRemoteBankCode(t));
				}
				if (AB_Transaction_GetRemoteIban(t) == NULL) {
					trans->remoteIban = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->remoteIban = PyUnicode_FromString(AB_Transaction_GetRemoteIban(t));
				}
				if (AB_Transaction_GetRemoteBic(t) == NULL) {
					trans->remoteBic = Py_None;
					Py_INCREF(Py_None);
				} else {
					trans->remoteBic = PyUnicode_FromString(AB_Transaction_GetRemoteBic(t));
				}
				if (AB_Transaction_GetRemoteName(t) == NULL) {
					trans->remoteName = Py_None;
					Py_INCREF(Py_None);
				} else {
					sl = AB_Transaction_GetRemoteName(t);
					remoteName = GWEN_StringList_FirstString(sl);
					if (remoteName == NULL) {
						trans->remoteName = Py_None;
					} else {
						trans->remoteName = PyUnicode_FromString(remoteName);
					}
				}

				trans->value = PyFloat_FromDouble(AB_Value_GetValueAsDouble(v));
				trans->currency = PyUnicode_FromString("EUR");
				trans->uniqueId = PyLong_FromLong(AB_Transaction_GetUniqueId(t));
				if (AB_Transaction_GetTransactionText(t) == NULL) {
					trans->transactionText = PyUnicode_FromString("");
				} else {
					trans->transactionText = PyUnicode_FromString(AB_Transaction_GetTransactionText(t));
				}
				trans->transactionCode = PyLong_FromLong(AB_Transaction_GetTransactionCode(t));
				trans->textKey = PyLong_FromLong(AB_Transaction_GetTextKey(t));
				trans->textKeyExt = PyLong_FromLong(AB_Transaction_GetTextKeyExt(t));
				if (AB_Transaction_GetMandateId(t) == NULL) {
					trans->sepaMandateId = Py_None;
				} else {
					trans->sepaMandateId = PyUnicode_FromString(AB_Transaction_GetMandateId(t));
				}
				if (AB_Transaction_GetCustomerReference(t) == NULL) {
					trans->customerReference = PyUnicode_FromString("");
				} else {
					trans->customerReference = PyUnicode_FromString(AB_Transaction_GetCustomerReference(t));
				}
				if (AB_Transaction_GetBankReference(t) == NULL) {
					trans->bankReference = PyUnicode_FromString("");
				} else {
					trans->bankReference = PyUnicode_FromString(AB_Transaction_GetBankReference(t));
				}
				if (AB_Transaction_GetEndToEndReference(t) == NULL) {
					trans->endToEndReference = PyUnicode_FromString("");
				} else {
					trans->endToEndReference = PyUnicode_FromString(AB_Transaction_GetEndToEndReference(t));
				}
				trans->state = 0;
				state = AB_Transaction_GetStatus(t);
				switch(state)
				{
					case AB_Transaction_StatusUnknown:
						trans->state = -1;
						break;
					case AB_Transaction_StatusNone:
						trans->state = 0;
						break;
					case AB_Transaction_StatusAccepted:
						trans->state = 1;
						break;
					case AB_Transaction_StatusRejected:
						trans->state = 2;
						break;
					case AB_Transaction_StatusPending:
						trans->state = 4;
						break;
					case AB_Transaction_StatusSending:
						trans->state = 8;
						break;
					case AB_Transaction_StatusAutoReconciled:
						trans->state = 16;
						break;
					case AB_Transaction_StatusManuallyReconciled:
						trans->state = 32;
						break;
					case AB_Transaction_StatusRevoked:
						trans->state = 64;
						break;
					case AB_Transaction_StatusAborted:
						trans->state = 128;
						break;
				}

				PyList_Append(transList, (PyObject *)trans);
				Py_DECREF(trans);
			}
			t = AB_ImExporterAccountInfo_GetNextTransaction(ai);
		} 
		ai = AB_ImExporterContext_GetNextAccountInfo(ctx);
	}

	// Free jobs.
	AB_Job_free(job);
	AB_Job_List2_free(jl);
	AB_ImExporterContext_free(ctx);

	// Exit aqbanking.
	rv = AB_free(self);
	if (rv > 0)
	{
		//Py_XDECREF(trans);
		Py_DECREF(transList);
		return NULL;
	}

	return transList;
}
예제 #6
0
CString CGenethonDoc::runTest2(PyObject *pModule, CString& function) {

    CString output = CString();
    CString format = CString();
    PyObject *pDict, *pFunc;
    PyObject *pValue, *pArgTuple;
    PyObject *ptype, *pvalue, *ptraceback;

    int i;

    // Set the path to include the current directory in case the module is located there. Found from
    // http://stackoverflow.com/questions/7624529/python-c-api-doesnt-load-module
    // and http://stackoverflow.com/questions/7283964/embedding-python-into-c-importing-modules


    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, function);   //Get the function by its name
        // pFunc is a new reference

        if (pFunc && PyCallable_Check(pFunc)) {

            //Set up a tuple that will contain the function arguments. In this case, the
            //function requires two tuples, so we set up a tuple of size 2.
            pArgTuple = PyTuple_New(2);


            PyObject* s1 = PySequence_Tuple(PyUnicode_FromString("ASBSDBASJBB"));
            PyObject* s2 = PySequence_Tuple(PyUnicode_FromString("ASHADKBBJSS"));
            PyObject* s3 = PySequence_Tuple(PyUnicode_FromString("ABSFDHSGJAS"));

            PyObject* a = PyTuple_Pack(3, s1, s2, s3);
            PyTuple_SetItem(pArgTuple, 0, a);

            // color matrix
            PyObject *l = PyList_New(3);
            for (size_t i = 0; i<3; i++) {
                PyObject *li = PyList_New(11);
                for (size_t j = 0; j < 11; j++) {
                    pValue = PyLong_FromLong(0);
                    PyList_SetItem(li, j, pValue);
                }
                PyList_SetItem(l, i, li);
            }
//			PyObject *av = Py_BuildValue("(O)", l);
            PyTuple_SetItem(pArgTuple, 1, l);

            //Call the python function
            pValue = PyObject_CallObject(pFunc, pArgTuple);

            for (size_t i = 0; i<3; i++) {
                PyObject *li = PyList_GetItem(l, i);
                output.Append("[");
                for (size_t j = 0; j < 11; j++) {
                    PyObject *pListV = PyList_GetItem(li, j);
                    long lon = PyLong_AsLong(pListV);
                    format.Format("%ld,", lon);
                    output.Append(format.GetString());
//					Py_DECREF(pListV);
                }
                output.Append("]\n");
//				Py_DECREF(li);
            }
//			Py_DECREF(l);
            //			Py_DECREF(s1);
//			Py_DECREF(s2);
//			Py_DECREF(s3);
//			Py_DECREF(a);

            if (pValue != NULL) {
                PyObject* v = PyObject_GetAttrString(pModule, "richTextOutput");
//				output.Format("Result of call: %ld", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            //Some error catching
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                return handlePyError();
            }
        }
        else {
            if (PyErr_Occurred()) {
                return handlePyError();
            }
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        return handlePyError();
    }
    return output;
}
예제 #7
0
CString CGenethonDoc::runTest4(PyObject* pModule, CString& function) {
    CString output = CString();
    //	CString fileName = "c:/users/karl/multiply.py";
    /*
    CString fileName;
    GetTempFileName(fileName);
    fileName.Replace(".tmp", ".py");

    CStdioFile wFile(fileName, CFile::modeWrite | CFile::typeText | CFile::modeCreate);
    wFile.WriteString("def multiply(a,b):\n");
    wFile.WriteString("  print(\"Will compute\", a, \"times\", b)\n");
    wFile.WriteString("  c = 0\n");
    wFile.WriteString("  for i in range(0, a):\n");
    wFile.WriteString("    c = c + b\n");
    wFile.WriteString("  return c\n");
    wFile.Close();
    */

    PyObject *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    PyObject *ptype, *pvalue, *ptraceback;
    int i;

    numargs = 4;
    someString = CString("Very well done sir.");
    PyImport_AppendInittab("emb", &PyInit_emb);

    // Error checking of pName left out
    wchar_t *program = Py_DecodeLocale("GeneDoc", NULL);
    Py_SetProgramName(program);
    Py_Initialize();


    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, function);
        // pFunc is a new reference

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(2);
            pValue = PyLong_FromLong(2);
            if (!pValue) {
                Py_DECREF(pArgs);
                Py_DECREF(pModule);
                TRACE("Cannot convert argument\n");
                return output;
            }
            PyTuple_SetItem(pArgs, 0, pValue);
            pValue = PyLong_FromLong(3);
            if (!pValue) {
                Py_DECREF(pArgs);
                Py_DECREF(pModule);
                TRACE("Cannot convert argument\n");
                return output;
            }
            PyTuple_SetItem(pArgs, 1, pValue);
            // pValue reference stolen here:
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                PyObject* v = PyObject_GetAttrString(pModule, "richTextOutput");
                output.Format("Result of call: %ld\n%s", PyLong_AsLong(pValue), PyUnicode_AsUTF8(v));
                Py_DECREF(pValue);
                TRACE(output);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                output = handlePyError();
                TRACE(output);
                return output;
            }
        }
        else {
            if (PyErr_Occurred()) {
                output = handlePyError();
                TRACE("Cannot find function \"%s\"\n", "multiply");
            }
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        TRACE("pModule is null: Failed to load \n");
    }

    return output;

    //	DeleteTempFile(fileName);
    /*
    CString FileName;
    GetTempFileName(FileName);
    CStdioFile wFile(FileName, CFile::modeWrite | CFile::typeText | CFile::modeCreate);
    wFile.WriteString("Test test test test test test\n");
    wFile.Close();

    m_pTextView->LoadFile(FileName);

    DeleteTempFile(FileName);
    */

}
예제 #8
0
void eListboxPythonMultiContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected)
{
	gRegion itemregion(eRect(offset, m_itemsize));
	eListboxStyle *local_style = 0;
	eRect sel_clip(m_selection_clip);
	bool cursorValid = this->cursorValid();
	gRGB border_color;
	int border_size = 0;

	if (sel_clip.valid())
		sel_clip.moveBy(offset);

		/* get local listbox style, if present */
	if (m_listbox)
	{
		local_style = m_listbox->getLocalStyle();
		border_size = local_style->m_border_size;
		border_color = local_style->m_border_color;
	}

	painter.clip(itemregion);
	clearRegion(painter, style, local_style, ePyObject(), ePyObject(), ePyObject(), ePyObject(), selected, itemregion, sel_clip, offset, cursorValid);

	ePyObject items, buildfunc_ret;

	if (m_list && cursorValid)
	{
			/* a multicontent list can be used in two ways:
				either each item is a list of (TYPE,...)-tuples,
				or there is a template defined, which is a list of (TYPE,...)-tuples,
				and the list is an unformatted tuple. The template then references items from the list.
			*/
		items = PyList_GET_ITEM(m_list, m_cursor); // borrowed reference!

		if (m_buildFunc)
		{
			if (PyCallable_Check(m_buildFunc))  // when we have a buildFunc then call it
			{
				if (PyTuple_Check(items))
					buildfunc_ret = items = PyObject_CallObject(m_buildFunc, items);
				else
					eDebug("[eListboxPythonMultiContent] items is no tuple");
			}
			else
				eDebug("[eListboxPythonMultiContent] buildfunc is not callable");
		}

		if (!items)
		{
			eDebug("[eListboxPythonMultiContent] error getting item %d", m_cursor);
			goto error_out;
		}

		if (!m_template)
		{
			if (!PyList_Check(items))
			{
				eDebug("[eListboxPythonMultiContent] list entry %d is not a list (non-templated)", m_cursor);
				goto error_out;
			}
		} else
		{
			if (!PyTuple_Check(items))
			{
				eDebug("[eListboxPythonMultiContent] list entry %d is not a tuple (templated)", m_cursor);
				goto error_out;
			}
		}

		ePyObject data;

			/* if we have a template, use the template for the actual formatting.
				we will later detect that "data" is present, and refer to that, instead
				of the immediate value. */
		int start = 1;
		if (m_template)
		{
			data = items;
			items = m_template;
			start = 0;
		}

		int size = PyList_Size(items);
		for (int i = start; i < size; ++i)
		{
			ePyObject item = PyList_GET_ITEM(items, i); // borrowed reference!

			if (!item)
			{
				eDebug("[eListboxPythonMultiContent] ?");
				goto error_out;
			}

			if (!PyTuple_Check(item))
			{
				eDebug("[eListboxPythonMultiContent] did not receive a tuple.");
				goto error_out;
			}

			int size = PyTuple_Size(item);

			if (!size)
			{
				eDebug("[eListboxPythonMultiContent] receive empty tuple.");
				goto error_out;
			}

			int type = PyInt_AsLong(PyTuple_GET_ITEM(item, 0));

			switch (type)
			{
			case TYPE_TEXT: // text
			{
			/*
				(0, x, y, width, height, fnt, flags, "bla" [, color, colorSelected, backColor, backColorSelected, borderWidth, borderColor] )
			*/
				ePyObject px = PyTuple_GET_ITEM(item, 1),
							py = PyTuple_GET_ITEM(item, 2),
							pwidth = PyTuple_GET_ITEM(item, 3),
							pheight = PyTuple_GET_ITEM(item, 4),
							pfnt = PyTuple_GET_ITEM(item, 5),
							pflags = PyTuple_GET_ITEM(item, 6),
							pstring = PyTuple_GET_ITEM(item, 7),
							pforeColor, pforeColorSelected, pbackColor, pbackColorSelected, pborderWidth, pborderColor;

				if (!(px && py && pwidth && pheight && pfnt && pflags && pstring))
				{
					eDebug("[eListboxPythonMultiContent] received too small tuple (must be (TYPE_TEXT, x, y, width, height, fnt, flags, string [, color, backColor, backColorSelected, borderWidth, borderColor])");
					goto error_out;
				}

				if (size > 8)
					pforeColor = lookupColor(PyTuple_GET_ITEM(item, 8), data);

				if (size > 9)
					pforeColorSelected = lookupColor(PyTuple_GET_ITEM(item, 9), data);

				if (size > 10)
					pbackColor = lookupColor(PyTuple_GET_ITEM(item, 10), data);

				if (size > 11)
					pbackColorSelected = lookupColor(PyTuple_GET_ITEM(item, 11), data);

				if (size > 12)
				{
					pborderWidth = PyTuple_GET_ITEM(item, 12);
					if (pborderWidth == Py_None)
						pborderWidth=ePyObject();
				}
				if (size > 13)
					pborderColor = lookupColor(PyTuple_GET_ITEM(item, 13), data);

				if (PyInt_Check(pstring) && data) /* if the string is in fact a number, it refers to the 'data' list. */
					pstring = PyTuple_GetItem(data, PyInt_AsLong(pstring));

							/* don't do anything if we have 'None' as string */
				if (pstring == Py_None)
					continue;

				const char *string = (PyString_Check(pstring)) ? PyString_AsString(pstring) : "<not-a-string>";
				int x = PyInt_AsLong(px) + offset.x();
				int y = PyInt_AsLong(py) + offset.y();
				int width = PyInt_AsLong(pwidth);
				int height = PyInt_AsLong(pheight);
				int flags = PyInt_AsLong(pflags);
				int fnt = PyInt_AsLong(pfnt);
				int bwidth = pborderWidth ? PyInt_AsLong(pborderWidth) : 0;

				if (m_font.find(fnt) == m_font.end())
				{
					eDebug("[eListboxPythonMultiContent] specified font %d was not found!", fnt);
					goto error_out;
				}

				eRect rect(x+bwidth, y+bwidth, width-bwidth*2, height-bwidth*2);
				painter.clip(rect);

				{
					gRegion rc(rect);
					bool mustClear = (selected && pbackColorSelected) || (!selected && pbackColor);
					clearRegion(painter, style, local_style, pforeColor, pforeColorSelected, pbackColor, pbackColorSelected, selected, rc, sel_clip, offset, cursorValid, mustClear);
				}

				painter.setFont(m_font[fnt]);
				painter.renderText(rect, string, flags,
				 border_color, border_size);
				painter.clippop();

				// draw border
				if (bwidth)
				{
					eRect rect(eRect(x, y, width, height));
					painter.clip(rect);
					if (pborderColor)
					{
						unsigned int color = PyInt_AsUnsignedLongMask(pborderColor);
						painter.setForegroundColor(gRGB(color));
					}

					rect.setRect(x, y, width, bwidth);
					painter.fill(rect);

					rect.setRect(x, y+bwidth, bwidth, height-bwidth);
					painter.fill(rect);

					rect.setRect(x+bwidth, y+height-bwidth, width-bwidth, bwidth);
					painter.fill(rect);

					rect.setRect(x+width-bwidth, y+bwidth, bwidth, height-bwidth);
					painter.fill(rect);

					painter.clippop();
				}
				break;
			}
			case TYPE_PROGRESS_PIXMAP: // Progress
			/*
				(1, x, y, width, height, filled_percent, pixmap [, borderWidth, foreColor, foreColorSelected, backColor, backColorSelected] )
			*/
			case TYPE_PROGRESS: // Progress
			{
			/*
				(1, x, y, width, height, filled_percent [, borderWidth, foreColor, foreColorSelected, backColor, backColorSelected] )
			*/
				ePyObject px = PyTuple_GET_ITEM(item, 1),
							py = PyTuple_GET_ITEM(item, 2),
							pwidth = PyTuple_GET_ITEM(item, 3),
							pheight = PyTuple_GET_ITEM(item, 4),
							pfilled_perc = PyTuple_GET_ITEM(item, 5),
							ppixmap, pborderWidth, pforeColor, pforeColorSelected, pbackColor, pbackColorSelected;
				int idx = 6;
				if (type == TYPE_PROGRESS)
				{
					if (!(px && py && pwidth && pheight && pfilled_perc))
					{
						eDebug("[eListboxPythonMultiContent] received too small tuple (must be (TYPE_PROGRESS, x, y, width, height, filled percent [,border width, foreColor, backColor, backColorSelected]))");
						goto error_out;
					}
				}
				else
				{
					ppixmap = PyTuple_GET_ITEM(item, idx++);
					if (ppixmap == Py_None)
						continue;
					if (!(px && py && pwidth && pheight && pfilled_perc, ppixmap))
					{
						eDebug("[eListboxPythonMultiContent] received too small tuple (must be (TYPE_PROGRESS_PIXMAP, x, y, width, height, filled percent, pixmap, [,border width, foreColor, backColor, backColorSelected]))");
						goto error_out;
					}
				}

				if (size > idx)
				{
					pborderWidth = PyTuple_GET_ITEM(item, idx++);
					if (pborderWidth == Py_None)
						pborderWidth = ePyObject();
				}
				if (size > idx)
				{
					pforeColor = PyTuple_GET_ITEM(item, idx++);
					if (pforeColor == Py_None)
						pforeColor = ePyObject();
				}
				if (size > idx)
				{
					pforeColorSelected = PyTuple_GET_ITEM(item, idx++);
					if (pforeColorSelected == Py_None)
						pforeColorSelected=ePyObject();
				}
				if (size > idx)
				{
					pbackColor = PyTuple_GET_ITEM(item, idx++);
					if (pbackColor == Py_None)
						pbackColor=ePyObject();
				}
				if (size > idx)
				{
					pbackColorSelected = PyTuple_GET_ITEM(item, idx++);
					if (pbackColorSelected == Py_None)
						pbackColorSelected=ePyObject();
				}

				int x = PyInt_AsLong(px) + offset.x();
				int y = PyInt_AsLong(py) + offset.y();
				int width = PyInt_AsLong(pwidth);
				int height = PyInt_AsLong(pheight);
				int filled = PyInt_AsLong(pfilled_perc);

				if ((filled < 0) && data) /* if the string is in a negative number, it refers to the 'data' list. */
					filled = PyInt_AsLong(PyTuple_GetItem(data, -filled));

							/* don't do anything if percent out of range */
				if ((filled < 0) || (filled > 100))
					continue;

				int bwidth = pborderWidth ? PyInt_AsLong(pborderWidth) : 2;

				eRect rect(x, y, width, height);
				painter.clip(rect);

				{
					gRegion rc(rect);
					bool mustClear = (selected && pbackColorSelected) || (!selected && pbackColor);
					clearRegion(painter, style, local_style, pforeColor, pforeColorSelected, pbackColor, pbackColorSelected, selected, rc, sel_clip, offset, cursorValid, mustClear);
				}

				// border
				if (bwidth) {
					rect.setRect(x, y, width, bwidth);
					painter.fill(rect);

					rect.setRect(x, y+bwidth, bwidth, height-bwidth);
					painter.fill(rect);

					rect.setRect(x+bwidth, y+height-bwidth, width-bwidth, bwidth);
					painter.fill(rect);

					rect.setRect(x+width-bwidth, y+bwidth, bwidth, height-bwidth);
					painter.fill(rect);
				}

				rect.setRect(x+bwidth, y+bwidth, (width-bwidth*2) * filled / 100, height-bwidth*2);

				// progress
				if (ppixmap)
				{
					ePtr<gPixmap> pixmap;
					if (PyInt_Check(ppixmap) && data) /* if the pixmap is in fact a number, it refers to the data list */
						ppixmap = PyTuple_GetItem(data, PyInt_AsLong(ppixmap));

					if (SwigFromPython(pixmap, ppixmap))
					{
						eDebug("[eListboxPythonMultiContent] (Pixmap) get pixmap failed");
						painter.clippop();
						continue;
					}
					painter.blit(pixmap, rect.topLeft(), rect, 0);
				}
				else
					painter.fill(rect);

				painter.clippop();
				break;
			}
			case TYPE_PIXMAP_ALPHABLEND:
			case TYPE_PIXMAP_ALPHATEST:
			case TYPE_PIXMAP: // pixmap
			{
			/*
				(2, x, y, width, height, pixmap [, backColor, backColorSelected] )
			*/

				ePyObject px = PyTuple_GET_ITEM(item, 1),
							py = PyTuple_GET_ITEM(item, 2),
							pwidth = PyTuple_GET_ITEM(item, 3),
							pheight = PyTuple_GET_ITEM(item, 4),
							ppixmap = PyTuple_GET_ITEM(item, 5),
							pbackColor, pbackColorSelected;

				if (!(px && py && pwidth && pheight && ppixmap))
				{
					eDebug("[eListboxPythonMultiContent] received too small tuple (must be (TYPE_PIXMAP, x, y, width, height, pixmap [, backColor, backColorSelected] ))");
					goto error_out;
				}

				if (PyInt_Check(ppixmap) && data) /* if the pixemap is in fact a number, it refers to the 'data' list. */
					ppixmap = PyTuple_GetItem(data, PyInt_AsLong(ppixmap));

							/* don't do anything if we have 'None' as pixmap */
				if (ppixmap == Py_None)
					continue;

				int x = PyInt_AsLong(px) + offset.x();
				int y = PyInt_AsLong(py) + offset.y();
				int width = PyInt_AsLong(pwidth);
				int height = PyInt_AsLong(pheight);
				int flags = 0;
				ePtr<gPixmap> pixmap;
				if (SwigFromPython(pixmap, ppixmap))
				{
					eDebug("[eListboxPythonMultiContent] (Pixmap) get pixmap failed");
					goto error_out;
				}

				if (size > 6)
					pbackColor = lookupColor(PyTuple_GET_ITEM(item, 6), data);

				if (size > 7)
					pbackColorSelected = lookupColor(PyTuple_GET_ITEM(item, 7), data);

				if (size > 8)
					flags = PyInt_AsLong(PyTuple_GET_ITEM(item, 8));

				eRect rect(x, y, width, height);
				painter.clip(rect);

				{
					gRegion rc(rect);
					bool mustClear = (selected && pbackColorSelected) || (!selected && pbackColor);
					clearRegion(painter, style, local_style, ePyObject(), ePyObject(), pbackColor, pbackColorSelected, selected, rc, sel_clip, offset, cursorValid, mustClear);
				}
				flags |= (type == TYPE_PIXMAP_ALPHATEST) ? gPainter::BT_ALPHATEST : (type == TYPE_PIXMAP_ALPHABLEND) ? gPainter::BT_ALPHABLEND : 0;
				if (flags & gPainter::BT_SCALE)
					painter.blitScale(pixmap, rect, rect, flags);
				else
					painter.blit(pixmap, rect.topLeft(), rect, flags);
				painter.clippop();
				break;
			}
			default:
				eWarning("[eListboxPythonMultiContent] received unknown type (%d)", type);
				goto error_out;
			}
		}
	}

	if (selected && !sel_clip.valid() && (!local_style || !local_style->m_selection))
		style.drawFrame(painter, eRect(offset, m_itemsize), eWindowStyle::frameListboxEntry);

error_out:
	if (buildfunc_ret)
		Py_DECREF(buildfunc_ret);

	painter.clippop();
}
예제 #9
0
파일: gpi_embed.c 프로젝트: FinnG/cocotb
void embed_sim_init(gpi_sim_info_t *info)
{
    FENTER

    int i;

    // Find the simulation root
    gpi_sim_hdl dut = gpi_get_root_handle(getenv("TOPLEVEL"));

    if (dut == NULL) {
        fprintf(stderr, "Unable to find root instance!\n");
        gpi_sim_end();
        return;
    }

    PyObject *cocotb_module, *cocotb_init, *cocotb_args, *cocotb_retval;
    PyObject *simlog_obj, *simlog_func;
    PyObject *argv_list, *argc, *arg_dict, *arg_value;

    cocotb_module = NULL;
    arg_dict = NULL;

    //Ensure that the current thread is ready to callthe Python C API
    PyGILState_STATE gstate = PyGILState_Ensure();

    if (get_module_ref(COCOTB_MODULE, &cocotb_module))
        goto cleanup;

    // Create a logger object
    simlog_obj = PyObject_GetAttrString(cocotb_module, "log");

    if (simlog_obj == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to to get simlog object\n");
    }

    simlog_func = PyObject_GetAttrString(simlog_obj, "_printRecord");
    if (simlog_func == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to get the _printRecord method");
        goto cleanup;
    }

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_printRecord is not callable");
        goto cleanup;
    }

    set_log_handler(simlog_func);

    Py_DECREF(simlog_func);

    simlog_func = PyObject_GetAttrString(simlog_obj, "_willLog");
    if (simlog_func == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to get the _willLog method");
        goto cleanup;
    }

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_willLog is not callable");
        goto cleanup;
    }

    set_log_filter(simlog_func);

    argv_list = PyList_New(0);
    for (i = 0; i < info->argc; i++) {
        arg_value = PyString_FromString(info->argv[i]);
        PyList_Append(argv_list, arg_value);
    }

    arg_dict = PyModule_GetDict(cocotb_module);
    PyDict_SetItemString(arg_dict, "argv", argv_list);

    argc = PyInt_FromLong(info->argc);
    PyDict_SetItemString(arg_dict, "argc", argc);

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_printRecord is not callable");
        goto cleanup;
    }

    LOG_INFO("Running on %s version %s", info->product, info->version);
    LOG_INFO("Python interpreter initialised and cocotb loaded!");

    // Now that logging has been set up ok we initialise the testbench
    if (-1 == PyObject_SetAttrString(cocotb_module, "SIM_NAME", PyString_FromString(info->product))) {
        PyErr_Print();
        fprintf(stderr, "Unable to set SIM_NAME");
        goto cleanup;
    }

    // Hold onto a reference to our _fail_test function
    pEventFn = PyObject_GetAttrString(cocotb_module, "_sim_event");

    if (!PyCallable_Check(pEventFn)) {
        PyErr_Print();
        fprintf(stderr, "cocotb._sim_event is not callable");
        goto cleanup;
    }
    Py_INCREF(pEventFn);

    cocotb_init = PyObject_GetAttrString(cocotb_module, "_initialise_testbench");         // New reference

    if (cocotb_init == NULL || !PyCallable_Check(cocotb_init)) {
        if (PyErr_Occurred())
            PyErr_Print();
        fprintf(stderr, "Cannot find function \"%s\"\n", "_initialise_testbench");
        Py_DECREF(cocotb_init);
        goto cleanup;
    }

    cocotb_args = PyTuple_New(1);
    PyTuple_SetItem(cocotb_args, 0, PyLong_FromLong((long)dut));        // Note: This function “steals” a reference to o.
    cocotb_retval = PyObject_CallObject(cocotb_init, cocotb_args);

    if (cocotb_retval != NULL) {
        LOG_DEBUG("_initialise_testbench successful");
        Py_DECREF(cocotb_retval);
    } else {
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
        gpi_sim_end();
        goto cleanup;
    }

    FEXIT

cleanup:
    if (cocotb_module) {
        Py_DECREF(cocotb_module);
    }
    if (arg_dict) {
        Py_DECREF(arg_dict);
    }
    PyGILState_Release(gstate);
}
예제 #10
0
PyObject *
session_connect(PyObject *self, PyObject *args)
{
    sp_session_config config;
    PyObject *client;
    sp_session *session;
    sp_error error;
    char *username, *password;
    char *cache_location, *settings_location, *user_agent;

    if (!PyArg_ParseTuple(args, "O", &client))
        return NULL;
    PyEval_InitThreads();

    memset(&config, 0, sizeof(config));
    config.api_version = SPOTIFY_API_VERSION;
    config.userdata = (void *)client;
    config.callbacks = &g_callbacks;

    cache_location = PySpotify_GetConfigString(client, "cache_location");
    if (!cache_location)
        return NULL;
    config.cache_location = cache_location;
#ifdef DEBUG
    fprintf(stderr, "[DEBUG]-session- Cache location is '%s'\n",
            cache_location);
#endif

    settings_location = PySpotify_GetConfigString(client, "settings_location");
    config.settings_location = settings_location;
#ifdef DEBUG
    fprintf(stderr, "[DEBUG]-session- Settings location is '%s'\n",
            settings_location);
#endif

    PyObject *application_key =
        PyObject_GetAttr(client, PyBytes_FromString("application_key"));
    if (!application_key) {
        PyErr_SetString(SpotifyError,
                        "application_key not set");
        return NULL;
    }
    else if (!PyBytes_Check(application_key)) {
        PyErr_SetString(SpotifyError,
                        "application_key must be a byte string");
        return NULL;
    }
    char *s_appkey;
    Py_ssize_t l_appkey;

    PyBytes_AsStringAndSize(application_key, &s_appkey, &l_appkey);
    config.application_key_size = l_appkey;
    config.application_key = PyMem_Malloc(l_appkey);
    memcpy((char *)config.application_key, s_appkey, l_appkey);

    user_agent = PySpotify_GetConfigString(client, "user_agent");
    if (!user_agent)
        return NULL;
    if (strlen(user_agent) > 255) {
        PyErr_SetString(SpotifyError, "user agent must be 255 characters max");
    }
    config.user_agent = user_agent;
#ifdef DEBUG
        fprintf(stderr, "[DEBUG]-session- User agent set to '%s'\n",
                            user_agent);
#endif
    username = PySpotify_GetConfigString(client, "username");
    if (!username)
        return NULL;

    password = PySpotify_GetConfigString(client, "password");
    if (!password)
        return NULL;

    Py_BEGIN_ALLOW_THREADS;
#ifdef DEBUG
    fprintf(stderr, "[DEBUG]-session- creating session...\n");
#endif
    error = sp_session_create(&config, &session);
    Py_END_ALLOW_THREADS;
    if (error != SP_ERROR_OK) {
        PyErr_SetString(SpotifyError, sp_error_message(error));
        return NULL;
    }
    session_constructed = 1;

#ifdef DEBUG
    fprintf(stderr, "[DEBUG]-session- login as %s in progress...\n",
            username);
#endif
    Py_BEGIN_ALLOW_THREADS;
    sp_session_login(session, username, password);
    Py_END_ALLOW_THREADS;
    g_session = session;
    Session *psession =
        (Session *) PyObject_CallObject((PyObject *)&SessionType, NULL);
    psession->_session = session;
    return (PyObject *)psession;
}
예제 #11
0
void eListboxPythonConfigContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected)
{
	ePtr<gFont> fnt;
	ePtr<gFont> fnt2;
	eRect itemrect(offset, m_itemsize);
	eListboxStyle *local_style = 0;
	bool cursorValid = this->cursorValid();
	gRGB border_color;
	int border_size = 0;

	painter.clip(itemrect);
	style.setStyle(painter, selected ? eWindowStyle::styleListboxSelected : eWindowStyle::styleListboxNormal);

		/* get local listbox style, if present */
	if (m_listbox)
		local_style = m_listbox->getLocalStyle();

	if (local_style)
	{
		border_size = local_style->m_border_size;
		border_color = local_style->m_border_color;
		fnt = local_style->m_font;
		if (selected)
		{
			/* if we have a local background color set, use that. */
			if (local_style->m_background_color_selected_set)
				painter.setBackgroundColor(local_style->m_background_color_selected);
			/* same for foreground */
			if (local_style->m_foreground_color_selected_set)
				painter.setForegroundColor(local_style->m_foreground_color_selected);
		}
		else
		{
			/* if we have a local background color set, use that. */
			if (local_style->m_background_color_set)
				painter.setBackgroundColor(local_style->m_background_color);
			/* same for foreground */
			if (local_style->m_foreground_color_set)
				painter.setForegroundColor(local_style->m_foreground_color);
		}
	}

	if (fnt)
	{
		fnt2 = new gFont(fnt->family, fnt->pointSize - fnt->pointSize/5);
	}
	else
	{
		fnt = new gFont("Regular", 20);
		fnt2 = new gFont("Regular", 16);
	}

	if (!local_style || !local_style->m_transparent_background)
		/* if we have no transparent background */
	{
		/* blit background picture, if available (otherwise, clear only) */
		if (local_style && local_style->m_background && cursorValid)
			painter.blit(local_style->m_background, offset, eRect(), 0);
		else
			painter.clear();
	} else
	{
		if (local_style->m_background && cursorValid)
			painter.blit(local_style->m_background, offset, eRect(), gPainter::BT_ALPHATEST);
		else if (selected && !local_style->m_selection)
			painter.clear();
	}

	if (m_list && cursorValid)
	{
			/* get current list item */
		ePyObject item = PyList_GET_ITEM(m_list, m_cursor); // borrowed reference!
		ePyObject text, value;
		painter.setFont(fnt);
		int valueWidth(0);

		if (selected && local_style && local_style->m_selection)
			painter.blit(local_style->m_selection, offset, eRect(), gPainter::BT_ALPHATEST);

			/* the first tuple element is a string for the left side.
			   the second one will be called, and the result shall be an tuple.

			   of this tuple,
			   the first one is the type (string).
			   the second one is the value. */
		if (PyTuple_Check(item))
		{
				/* handle left part. get item from tuple, convert to string, display. */
			text = PyTuple_GET_ITEM(item, 0);
			text = PyObject_Str(text); /* creates a new object - old object was borrowed! */
			const char *configitemstring = (text && PyString_Check(text)) ? PyString_AsString(text) : "<not-a-string>";
			Py_XDECREF(text);
			eSize itemsize = eSize(m_itemsize.width()-10, m_itemsize.height());
			ePoint textoffset = ePoint(offset.x()+5, offset.y());

				/* when we have no label, align value to the left. (FIXME:
				   don't we want to specifiy this individually?) */
			int value_alignment_left = !*configitemstring;

				/* now, handle the value. get 2nd part from tuple*/
			if (PyTuple_Size(item) >= 2) // when no 2nd entry is in tuple this is a non selectable entry without config part
				value = PyTuple_GET_ITEM(item, 1);

			if (value)
			{
				ePyObject args = PyTuple_New(1);
				PyTuple_SET_ITEM(args, 0, PyInt_FromLong(selected));

					/* CallObject will call __call__ which should return the value tuple */
				value = PyObject_CallObject(value, args);

				if (PyErr_Occurred())
					PyErr_Print();

				Py_DECREF(args);
					/* the PyInt was stolen. */
			}

				/*  check if this is really a tuple */
			if (value && PyTuple_Check(value))
			{
					/* convert type to string */
				ePyObject type = PyTuple_GET_ITEM(value, 0);
				const char *atype = (type && PyString_Check(type)) ? PyString_AsString(type) : 0;

				if (atype)
				{
					if (!strcmp(atype, "text"))
					{
						ePyObject pvalue = PyTuple_GET_ITEM(value, 1);
						const char *value = (pvalue && PyString_Check(pvalue)) ? PyString_AsString(pvalue) : "<not-a-string>";
						eRect tmp = eRect(textoffset, itemsize);
						eTextPara *para = new eTextPara(tmp);
						para->setFont(fnt2);
						para->renderString(value);
						valueWidth = para->getBoundBox().width();

						painter.setFont(fnt2);
						painter.renderText(eRect(textoffset, itemsize), value, (value_alignment_left ?
							gPainter::RT_HALIGN_LEFT : gPainter::RT_HALIGN_RIGHT) |
							gPainter::RT_VALIGN_CENTER, border_color, border_size);

							/* pvalue is borrowed */
					} else if (!strcmp(atype, "slider"))
					{
						ePyObject pvalue = PyTuple_GET_ITEM(value, 1);
						ePyObject psize = PyTuple_GET_ITEM(value, 2);

							/* convert value to Long. fallback to -1 on error. */
						int value = (pvalue && PyInt_Check(pvalue)) ? PyInt_AsLong(pvalue) : -1;
						int size = (pvalue && PyInt_Check(psize)) ? PyInt_AsLong(psize) : 100;

							/* calc. slider length */
						valueWidth = (itemsize.width() - m_seperation) * value / size;
						int height = itemsize.height();

							/* draw slider */
						//painter.fill(eRect(offset.x() + m_seperation, offset.y(), width, height));
						//hack - make it customizable
						painter.fill(eRect(textoffset.x() + m_seperation, offset.y() + height/6, valueWidth, height*2/3));

							/* pvalue is borrowed */
					} else if (!strcmp(atype, "mtext"))
					{
						ePyObject pvalue = PyTuple_GET_ITEM(value, 1);
						const char *text = (pvalue && PyString_Check(pvalue)) ? PyString_AsString(pvalue) : "<not-a-string>";
						ePtr<eTextPara> para = new eTextPara(eRect(textoffset, itemsize));
						para->setFont(fnt2);
						para->renderString(text, gPainter::RT_VALIGN_CENTER);
						para->realign(value_alignment_left ? eTextPara::dirLeft : eTextPara::dirRight);
						int glyphs = para->size();

						ePyObject plist;

						if (PyTuple_Size(value) >= 3)
							plist = PyTuple_GET_ITEM(value, 2);

						int entries = 0;

						if (plist && PyList_Check(plist))
							entries = PyList_Size(plist);

						int left=0, right=0, last=-1;
						eRect bbox;
						for (int i = 0; i < entries; ++i)
						{
							ePyObject entry = PyList_GET_ITEM(plist, i);
							int num = PyInt_Check(entry) ? PyInt_AsLong(entry) : -1;

							if ((num < 0) || (num >= glyphs))
								eWarning("[eListboxPythonMultiContent] glyph index %d in PythonConfigList out of bounds!", num);
							else
							{
								if (last+1 != num && last != -1) {
									bbox = eRect(left, textoffset.y(), right-left,
										itemsize.height());
									painter.fill(bbox);
								}
								para->setGlyphFlag(num, GS_INVERT);
								bbox = para->getGlyphBBox(num);
								if (last+1 != num || last == -1)
									left = bbox.left();
								right = bbox.left() + bbox.width();
								last = num;
							}
							/* entry is borrowed */
						}
						if (last != -1) {
							bbox = eRect(left, textoffset.y(), right-left, itemsize.height());
							painter.fill(bbox);
						}
						painter.renderPara(para, ePoint(0, 0));
						/* pvalue is borrowed */
						/* plist is 0 or borrowed */
					}
				}
				/* type is borrowed */
			} else if (value)
				eWarning("[eListboxPythonConfigContent] second value of tuple is not a tuple.");
			if (value)
				Py_DECREF(value);

			valueWidth = valueWidth + 10;
			if (valueWidth > itemsize.width()) { valueWidth = itemsize.width(); }
			painter.setFont(fnt);
			painter.renderText(eRect(textoffset, eSize (itemsize.width()-valueWidth,itemsize.height())),
				configitemstring, gPainter::RT_HALIGN_LEFT | gPainter::RT_VALIGN_CENTER, border_color, border_size);
		}

		if (selected && (!local_style || !local_style->m_selection))
			style.drawFrame(painter, eRect(offset, m_itemsize), eWindowStyle::frameListboxEntry);
	}

	painter.clippop();
}
예제 #12
0
PyMODINIT_FUNC
init_zope_security_checker(void)
{
  PyObject* m;

  CheckerType.tp_new = PyType_GenericNew;
  if (PyType_Ready(&CheckerType) < 0)
    return;

  _defaultChecker = PyObject_CallFunction((PyObject*)&CheckerType, "{}");
  if (_defaultChecker == NULL)
    return;

#define INIT_STRING(S) \
if((str_##S = PyString_InternFromString(#S)) == NULL) return

  INIT_STRING(checkPermission);
  INIT_STRING(__Security_checker__);
  INIT_STRING(interaction);

  if ((_checkers = PyDict_New()) == NULL)
    return;

  NoProxy = PyObject_CallObject((PyObject*)&PyBaseObject_Type, NULL);
  if (NoProxy == NULL)
    return;

  if ((m = PyImport_ImportModule("zope.security._proxy")) == NULL) return;
  if ((Proxy = PyObject_GetAttrString(m, "_Proxy")) == NULL) return;
  Py_DECREF(m);

  if ((m = PyImport_ImportModule("zope.security._definitions")) == NULL) return;
  thread_local = PyObject_GetAttrString(m, "thread_local");
  if (thread_local == NULL) return;
  Py_DECREF(m);

  if ((m = PyImport_ImportModule("zope.security.interfaces")) == NULL) return;
  ForbiddenAttribute = PyObject_GetAttrString(m, "ForbiddenAttribute");
  if (ForbiddenAttribute == NULL) return;
  Unauthorized = PyObject_GetAttrString(m, "Unauthorized");
  if (Unauthorized == NULL) return;
  Py_DECREF(m);

  if ((m = PyImport_ImportModule("zope.security.checker")) == NULL) return;
  CheckerPublic = PyObject_GetAttrString(m, "CheckerPublic");
  if (CheckerPublic == NULL) return;
  Py_DECREF(m);

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

  m = Py_InitModule3("_zope_security_checker", module_methods,
                     "C optimizations for zope.security.checker");

  if (m == NULL)
    return;

#define EXPORT(N) Py_INCREF(N); PyModule_AddObject(m, #N, N)

  EXPORT(_checkers);
  EXPORT(NoProxy);
  EXPORT(_defaultChecker);
  EXPORT(_available_by_default);

  Py_INCREF(&CheckerType);
  PyModule_AddObject(m, "Checker", (PyObject *)&CheckerType);
}
예제 #13
0
파일: pygtype.c 프로젝트: RIFTIO/pygobject
static void
pyg_signal_class_closure_marshal(GClosure *closure,
				 GValue *return_value,
				 guint n_param_values,
				 const GValue *param_values,
				 gpointer invocation_hint,
				 gpointer marshal_data)
{
    PyGILState_STATE state;
    GObject *object;
    PyObject *object_wrapper;
    GSignalInvocationHint *hint = (GSignalInvocationHint *)invocation_hint;
    gchar *method_name, *tmp;
    PyObject *method;
    PyObject *params, *ret;
    guint i, len;

    state = pyglib_gil_state_ensure();

    g_return_if_fail(invocation_hint != NULL);
    /* get the object passed as the first argument to the closure */
    object = g_value_get_object(&param_values[0]);
    g_return_if_fail(object != NULL && G_IS_OBJECT(object));

    /* get the wrapper for this object */
    object_wrapper = pygobject_new(object);
    g_return_if_fail(object_wrapper != NULL);

    /* construct method name for this class closure */
    method_name = g_strconcat("do_", g_signal_name(hint->signal_id), NULL);

    /* convert dashes to underscores.  For some reason, g_signal_name
     * seems to convert all the underscores in the signal name to
       dashes??? */
    for (tmp = method_name; *tmp != '\0'; tmp++)
	if (*tmp == '-') *tmp = '_';

    method = PyObject_GetAttrString(object_wrapper, method_name);
    g_free(method_name);

    if (!method) {
	PyErr_Clear();
	Py_DECREF(object_wrapper);
	pyglib_gil_state_release(state);
	return;
    }
    Py_DECREF(object_wrapper);

    /* construct Python tuple for the parameter values; don't copy boxed values
       initially because we'll check after the call to see if a copy is needed. */
    params = PyTuple_New(n_param_values - 1);
    for (i = 1; i < n_param_values; i++) {
	PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);

	/* error condition */
	if (!item) {
	    Py_DECREF(params);
	    pyglib_gil_state_release(state);
	    return;
	}
	PyTuple_SetItem(params, i - 1, item);
    }

    ret = PyObject_CallObject(method, params);

    /* Copy boxed values if others ref them, this needs to be done regardless of
       exception status. */
    len = PyTuple_Size(params);
    for (i = 0; i < len; i++) {
	PyObject *item = PyTuple_GetItem(params, i);
	if (item != NULL && PyObject_TypeCheck(item, &PyGBoxed_Type)
	    && item->ob_refcnt != 1) {
	    PyGBoxed* boxed_item = (PyGBoxed*)item;
	    if (!boxed_item->free_on_dealloc) {
		gpointer boxed_ptr = pyg_boxed_get_ptr (boxed_item);
		pyg_boxed_set_ptr (boxed_item, g_boxed_copy (boxed_item->gtype, boxed_ptr));
		boxed_item->free_on_dealloc = TRUE;
	    }
	}
    }

    if (ret == NULL) {
	PyErr_Print();
	Py_DECREF(method);
	Py_DECREF(params);
	pyglib_gil_state_release(state);
	return;
    }
    Py_DECREF(method);
    Py_DECREF(params);
    if (G_IS_VALUE(return_value))
	pyg_value_from_pyobject(return_value, ret);
    Py_DECREF(ret);
    pyglib_gil_state_release(state);
}
예제 #14
0
파일: pygtype.c 프로젝트: RIFTIO/pygobject
static void
pyg_closure_marshal(GClosure *closure,
		    GValue *return_value,
		    guint n_param_values,
		    const GValue *param_values,
		    gpointer invocation_hint,
		    gpointer marshal_data)
{
    PyGILState_STATE state;
    PyGClosure *pc = (PyGClosure *)closure;
    PyObject *params, *ret;
    guint i;

    state = pyglib_gil_state_ensure();

    /* construct Python tuple for the parameter values */
    params = PyTuple_New(n_param_values);
    for (i = 0; i < n_param_values; i++) {
	/* swap in a different initial data for connect_object() */
	if (i == 0 && G_CCLOSURE_SWAP_DATA(closure)) {
	    g_return_if_fail(pc->swap_data != NULL);
	    Py_INCREF(pc->swap_data);
	    PyTuple_SetItem(params, 0, pc->swap_data);
	} else {
	    PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);

	    /* error condition */
	    if (!item) {
            if (!PyErr_Occurred ())
                PyErr_SetString (PyExc_TypeError,
                                 "can't convert parameter to desired type");

            if (pc->exception_handler)
                pc->exception_handler (return_value, n_param_values, param_values);
            else
                PyErr_Print();

            goto out;
	    }
	    PyTuple_SetItem(params, i, item);
	}
    }
    /* params passed to function may have extra arguments */
    if (pc->extra_args) {
	PyObject *tuple = params;
	params = PySequence_Concat(tuple, pc->extra_args);
	Py_DECREF(tuple);
    }
    ret = PyObject_CallObject(pc->callback, params);
    if (ret == NULL) {
	if (pc->exception_handler)
	    pc->exception_handler(return_value, n_param_values, param_values);
	else
	    PyErr_Print();
	goto out;
    }

    if (G_IS_VALUE(return_value) && pyg_value_from_pyobject(return_value, ret) != 0) {
	/* If we already have an exception set, use that, otherwise set a
	 * generic one */
	if (!PyErr_Occurred())
	    PyErr_SetString(PyExc_TypeError,
                            "can't convert return value to desired type");

	if (pc->exception_handler)
	    pc->exception_handler(return_value, n_param_values, param_values);
	else
	    PyErr_Print();
    }
    Py_DECREF(ret);

 out:
    Py_DECREF(params);
    pyglib_gil_state_release(state);
}
예제 #15
0
static void pyt_exec_str(RESULT * result, const char *module, const char *function, int argc, const char *argv[])
{

    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    const char *rv = NULL;
    int i;

    pName = PyString_FromString(module);
    /* Error checking of pName left out */

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

    if (pModule != NULL) {
        pDict = PyModule_GetDict(pModule);
        /* pDict is a borrowed reference */

        pFunc = PyDict_GetItemString(pDict, function);
        /* pFun: Borrowed reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc);
            for (i = 0; i < argc; ++i) {
                pValue = PyString_FromString(argv[i]);
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    error("Cannot convert argument \"%s\" to python format", argv[i]);
                    SetResult(&result, R_STRING, "");
                    return;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                rv = PyString_AsString(pValue);
                SetResult(&result, R_STRING, rv);
                Py_DECREF(pValue);
                /* rv is now a 'dangling reference' */
                return;
            } else {
                Py_DECREF(pModule);
                error("Python call failed (\"%s.%s\")", module, function);
                /* print traceback on stderr */
                PyErr_PrintEx(0);
                SetResult(&result, R_STRING, "");
                return;
            }
            /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
        } else {
            error("Can not find python function \"%s.%s\"", module, function);
        }
        Py_DECREF(pModule);
    } else {
        error("Failed to load python module \"%s\"", module);
        /* print traceback on stderr */
        PyErr_PrintEx(0);
    }
    SetResult(&result, R_STRING, "");
    return;
}
예제 #16
0
PyObject *
ContentObject_obj_from_ccn(PyObject *py_content_object)
{
    struct ccn_charbuf *content_object;
    struct ccn_parsed_ContentObject *parsed_content_object;
    PyObject *py_obj_ContentObject, *py_o;
    int r;
    struct ccn_charbuf *signature;
    PyObject *py_signature;
    struct ccn_charbuf *signed_info;
    PyObject *py_signed_info;

    if (!CCNObject_ReqType(CONTENT_OBJECT, py_content_object))
        return NULL;

    content_object = CCNObject_Get(CONTENT_OBJECT, py_content_object);
    parsed_content_object = _pyccn_content_object_get_pco(py_content_object);
    if (!parsed_content_object)
        return NULL;

    debug("ContentObject_from_ccn_parsed content_object->length=%zd\n",
          content_object->length);

    py_obj_ContentObject = PyObject_CallObject(g_type_ContentObject, NULL);
    if (!py_obj_ContentObject)
        return NULL;

    /* Name */
    py_o = Name_obj_from_ccn_parsed(py_content_object);
    JUMP_IF_NULL(py_o, error);
    r = PyObject_SetAttrString(py_obj_ContentObject, "name", py_o);
    Py_DECREF(py_o);
    JUMP_IF_NEG(r, error);

    /* Content */
    py_o = Content_from_ccn_parsed(content_object, parsed_content_object);
    JUMP_IF_NULL(py_o, error);
    r = PyObject_SetAttrString(py_obj_ContentObject, "content", py_o);
    Py_DECREF(py_o);
    JUMP_IF_NEG(r, error);

    /* Signature */
    debug("ContentObject_from_ccn_parsed Signature\n");
    py_signature = CCNObject_New_charbuf(SIGNATURE, &signature);
    JUMP_IF_NULL(py_signature, error);
    r = ccn_charbuf_append(signature,
                           &content_object->buf[parsed_content_object->offset[CCN_PCO_B_Signature]],
                           (size_t) (parsed_content_object->offset[CCN_PCO_E_Signature]
                                     - parsed_content_object->offset[CCN_PCO_B_Signature]));
    if (r < 0) {
        PyErr_NoMemory();
        Py_DECREF(py_signature);
        goto error;
    }

    py_o = Signature_obj_from_ccn(py_signature);
    Py_DECREF(py_signature);
    JUMP_IF_NULL(py_o, error);
    r = PyObject_SetAttrString(py_obj_ContentObject, "signature", py_o);
    Py_DECREF(py_o);
    JUMP_IF_NEG(r, error);

    debug("ContentObject_from_ccn_parsed SignedInfo\n");

    py_signed_info = CCNObject_New_charbuf(SIGNED_INFO, &signed_info);
    JUMP_IF_NULL(py_signed_info, error);

    r = ccn_charbuf_append(signed_info,
                           &content_object->buf[parsed_content_object->offset[CCN_PCO_B_SignedInfo]],
                           (size_t) (parsed_content_object->offset[CCN_PCO_E_SignedInfo]
                                     - parsed_content_object->offset[CCN_PCO_B_SignedInfo]));
    if (r < 0) {
        PyErr_NoMemory();
        Py_DECREF(py_signed_info);
        goto error;
    }

    py_o = SignedInfo_obj_from_ccn(py_signed_info);
    Py_DECREF(py_signed_info);
    JUMP_IF_NULL(py_o, error);
    r = PyObject_SetAttrString(py_obj_ContentObject, "signedInfo", py_o);
    Py_DECREF(py_o);
    JUMP_IF_NEG(r, error);

    debug("ContentObject_from_ccn_parsed DigestAlgorithm\n");
    // TODO...  Note this seems to default to nothing in the library...?
    r = PyObject_SetAttrString(py_obj_ContentObject, "digestAlgorithm", Py_None);
    JUMP_IF_NEG(r, error);

    /* Original data  */
    debug("ContentObject_from_ccn_parsed ccn_data\n");
    r = PyObject_SetAttrString(py_obj_ContentObject, "ccn_data", py_content_object);
    JUMP_IF_NEG(r, error);

    r = PyObject_SetAttrString(py_obj_ContentObject, "ccn_data_dirty", Py_False);
    JUMP_IF_NEG(r, error);

    debug("ContentObject_from_ccn_parsed complete\n");

    return py_obj_ContentObject;

error:
    Py_XDECREF(py_obj_ContentObject);
    return NULL;
}
예제 #17
0
CString CGenethonDoc::runTest1(PyObject *pModule, CString& function) {

    CString output = CString();
    CString format = CString();
    PyObject *pDict, *pFunc;
    PyObject *pArgTuple, *pValue, *pXVec, *pYVec;
    PyObject *ptype, *pvalue, *ptraceback;

    int i;

    // Set the path to include the current directory in case the module is located there. Found from
    // http://stackoverflow.com/questions/7624529/python-c-api-doesnt-load-module
    // and http://stackoverflow.com/questions/7283964/embedding-python-into-c-importing-modules


    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, function);   //Get the function by its name
        // pFunc is a new reference

        if (pFunc && PyCallable_Check(pFunc)) {

            // create list
            PyObject *l = PyList_New(4);
            for (size_t i = 0; i<4; i++) {
                PyObject *li = PyList_New(12);
                for (size_t j = 0; j < 12; j++) {
//					PyObject* pCell = PyStructSequence_New()
                    pValue = PyLong_FromLong(j);
                    PyList_SetItem(li, j, pValue);
                }
                PyList_SetItem(l, i, li);
            }

            PyObject *arglist = Py_BuildValue("(O)", l);
            pValue = PyObject_CallObject(pFunc, arglist);
            //Set up a tuple that will contain the function arguments. In this case, the
            //function requires two tuples, so we set up a tuple of size 2.

            for (size_t i = 0; i<4; i++) {
                PyObject *li = PyList_GetItem(l, i);
                output.Append("[");
                for (size_t j = 0; j < 12; j++) {
                    PyObject *pListV = PyList_GetItem(li, j);
                    long lon = PyLong_AsLong(pListV);
                    format.Format("%ld,", lon);
                    output.Append(format.GetString());
                    Py_DECREF(pListV);
                }
                output.Append("]\n");
//				Py_DECREF(li);
            }
            Py_DECREF(l);
            /*
            			for (size_t i = 0; i<4; i++) {
            				PyObject *li = PyList_GetItem(l, i);
            				Py_DECREF(li);
            			}
            */
            //			Py_DECREF(pXVec);
            //			Py_DECREF(pYVec);

            if (pValue != NULL) {
                PyObject* v = PyObject_GetAttrString(pModule, "richTextOutput");
//				output.Format("Result of call: %ld", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }

            //Some error catching
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                return handlePyError();
            }
        }
        else {
            if (PyErr_Occurred()) {
                return handlePyError();
            }
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        return handlePyError();
    }
    return output;
}
예제 #18
0
void eListboxServiceContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected)
{
	painter.clip(eRect(offset, m_itemsize));

	int marked = 0;

	if (m_current_marked && selected)
		marked = 2;
	else if (cursorValid() && isMarked(*m_cursor))
	{
		if (selected)
			marked = 2;
		else
			marked = 1;
	}
	else
		style.setStyle(painter, selected ? eWindowStyle::styleListboxSelected : eWindowStyle::styleListboxNormal);

	eListboxStyle *local_style = 0;

		/* get local listbox style, if present */
	if (m_listbox)
		local_style = m_listbox->getLocalStyle();

	if (marked == 1)  // marked
	{
		style.setStyle(painter, eWindowStyle::styleListboxMarked);
		if (m_color_set[markedForeground])
			painter.setForegroundColor(m_color[markedForeground]);
		if (m_color_set[markedBackground])
			painter.setBackgroundColor(m_color[markedBackground]);
	}
	else if (marked == 2) // marked and selected
	{
		style.setStyle(painter, eWindowStyle::styleListboxMarkedAndSelected);
		if (m_color_set[markedForegroundSelected])
			painter.setForegroundColor(m_color[markedForegroundSelected]);
		if (m_color_set[markedBackgroundSelected])
			painter.setBackgroundColor(m_color[markedBackgroundSelected]);
	}
	else if (local_style)
	{
		if (selected)
		{
			/* if we have a local background color set, use that. */
			if (local_style->m_background_color_selected_set)
				painter.setBackgroundColor(local_style->m_background_color_selected);
			/* same for foreground */
			if (local_style->m_foreground_color_selected_set)
				painter.setForegroundColor(local_style->m_foreground_color_selected);
		}
		else
		{
			/* if we have a local background color set, use that. */
			if (local_style->m_background_color_set)
				painter.setBackgroundColor(local_style->m_background_color);
			/* same for foreground */
			if (local_style->m_foreground_color_set)
				painter.setForegroundColor(local_style->m_foreground_color);
		}
	}

	if (!local_style || !local_style->m_transparent_background)
		/* if we have no transparent background */
	{
		/* blit background picture, if available (otherwise, clear only) */
		if (local_style && local_style->m_background)
			painter.blit(local_style->m_background, offset, eRect(), 0);
		else
			painter.clear();
	} else
	{
		if (local_style->m_background)
			painter.blit(local_style->m_background, offset, eRect(), gPainter::BT_ALPHATEST);
		else if (selected && !local_style->m_selection)
			painter.clear();
	}

	if (cursorValid())
	{
		/* get service information */
		ePtr<iStaticServiceInformation> service_info;
		m_service_center->info(*m_cursor, service_info);
		eServiceReference ref = *m_cursor;
		bool isMarker = ref.flags & eServiceReference::isMarker;
		bool isPlayable = !(ref.flags & eServiceReference::isDirectory || isMarker);
		ePtr<eServiceEvent> evt;

		bool serviceAvail = true;
#ifndef FORCE_SERVICEAVAIL
		if (!marked && isPlayable && service_info && m_is_playable_ignore.valid() && !service_info->isPlayable(*m_cursor, m_is_playable_ignore))
		{
			if (m_color_set[serviceNotAvail])
				painter.setForegroundColor(m_color[serviceNotAvail]);
			else
				painter.setForegroundColor(gRGB(0xbbbbbb));
			serviceAvail = false;
		}
#endif
		if (selected && local_style && local_style->m_selection)
			painter.blit(local_style->m_selection, offset, eRect(), gPainter::BT_ALPHATEST);

		int xoffset=0;  // used as offset when painting the folder/marker symbol or the serviceevent progress
		time_t now = time(0);

		for (int e = 0; e != celServiceTypePixmap; ++e)
		{
			if (m_element_font[e])
			{
				int flags=gPainter::RT_VALIGN_CENTER;
				int yoffs = 0;
				eRect &area = m_element_position[e];
				std::string text = "<n/a>";
				switch (e)
				{
				case celServiceNumber:
				{
					if (area.width() <= 0)
						continue; // no point in going on if we won't paint anything

					if( m_cursor->getChannelNum() == 0 )
						continue;

					char buffer[15];
					snprintf(buffer, sizeof(buffer), "%d", m_cursor->getChannelNum() );
					text = buffer;
					flags|=gPainter::RT_HALIGN_RIGHT;
					break;
				}
				case celServiceName:
				{
					if (service_info)
						service_info->getName(*m_cursor, text);
					break;
				}
				case celServiceInfo:
				{
					if ( isPlayable && service_info && !service_info->getEvent(*m_cursor, evt) )
					{
						std::string name = evt->getEventName();
						if (name.empty())
							continue;
						text = evt->getEventName();
						if (serviceAvail)
						{
							if (!selected && m_color_set[eventForeground])
								painter.setForegroundColor(m_color[eventForeground]);
							else if (selected && m_color_set[eventForegroundSelected])
								painter.setForegroundColor(m_color[eventForegroundSelected]);
							else
								painter.setForegroundColor(gRGB(0xe7b53f));
						}
						break;
					}
					continue;
				}
				case celServiceEventProgressbar:
				{
					if (area.width() > 0 && isPlayable && service_info && !service_info->getEvent(*m_cursor, evt))
					{
						char buffer[15];
						snprintf(buffer, sizeof(buffer), "%d %%", (int)(100 * (now - evt->getBeginTime()) / evt->getDuration()));
						text = buffer;
						flags|=gPainter::RT_HALIGN_RIGHT;
						break;
					}
					continue;
				}
				}

				eRect tmp = area;
				int xoffs = 0;
				ePtr<gPixmap> piconPixmap;

				if (e == celServiceName)
				{
					//picon stuff
					if (isPlayable && PyCallable_Check(m_GetPiconNameFunc))
					{
						ePyObject pArgs = PyTuple_New(1);
						PyTuple_SET_ITEM(pArgs, 0, PyString_FromString(ref.toString().c_str()));
						ePyObject pRet = PyObject_CallObject(m_GetPiconNameFunc, pArgs);
						Py_DECREF(pArgs);
						if (pRet)
						{
							if (PyString_Check(pRet))
							{
								std::string piconFilename = PyString_AS_STRING(pRet);
								if (!piconFilename.empty())
									loadPNG(piconPixmap, piconFilename.c_str());
							}
							Py_DECREF(pRet);
						}
					}
					xoffs = xoffset;
					tmp.setWidth(((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? tmp.width() : m_column_width) - xoffs);
				}

				eTextPara *para = new eTextPara(tmp);
				para->setFont(m_element_font[e]);
				para->renderString(text.c_str());

				if (e == celServiceName)
				{
					eRect bbox = para->getBoundBox();

					int servicenameWidth = ((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? bbox.width() : m_column_width);
					m_element_position[celServiceInfo].setLeft(area.left() + servicenameWidth + 8 + xoffs);
					m_element_position[celServiceInfo].setTop(area.top());
					m_element_position[celServiceInfo].setWidth(area.width() - (servicenameWidth + 8 + xoffs));
					m_element_position[celServiceInfo].setHeight(area.height());

					if (isPlayable)
					{
						//picon stuff
						if (PyCallable_Check(m_GetPiconNameFunc) and (m_column_width || piconPixmap))
						{
							eRect area = m_element_position[celServiceInfo];
							/* PIcons are usually about 100:60. Make it a
							 * bit wider in case the icons are diffently
							 * shaped, and to add a bit of margin between
							 * icon and text. */
							const int iconWidth = area.height() * 9 / 5;
							m_element_position[celServiceInfo].setLeft(area.left() + iconWidth);
							m_element_position[celServiceInfo].setWidth(area.width() - iconWidth);
							area = m_element_position[celServiceName];
							xoffs += iconWidth;
							if (piconPixmap)
							{
								area.moveBy(offset);
								painter.clip(area);
								painter.blitScale(piconPixmap,
									eRect(area.left(), area.top(), iconWidth, area.height()),
									area,
									gPainter::BT_ALPHABLEND | gPainter::BT_KEEP_ASPECT_RATIO);
								painter.clippop();
							}
						}

						//service type marker stuff
						if (m_servicetype_icon_mode)
						{
							int orbpos = m_cursor->getUnsignedData(4) >> 16;
							const char *filename = ref.path.c_str();
							ePtr<gPixmap> &pixmap =
								(m_cursor->flags & eServiceReference::isGroup) ? m_pixmaps[picServiceGroup] :
								(strstr(filename, "://")) ? m_pixmaps[picStream] :
								(orbpos == 0xFFFF) ? m_pixmaps[picDVB_C] :
								(orbpos == 0xEEEE) ? m_pixmaps[picDVB_T] : m_pixmaps[picDVB_S];
							if (pixmap)
							{
								eSize pixmap_size = pixmap->size();
								eRect area = m_element_position[celServiceInfo];
								m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + 8);
								m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - 8);
								int offs = 0;
								if (m_servicetype_icon_mode == 1)
								{
									area = m_element_position[celServiceName];
									offs = xoffs;
									xoffs += pixmap_size.width() + 8;
								}
								else if (m_crypto_icon_mode == 1 && m_pixmaps[picCrypto])
									offs = offs + m_pixmaps[picCrypto]->size().width() + 8;
								int correction = (area.height() - pixmap_size.height()) / 2;
								area.moveBy(offset);
								painter.clip(area);
								painter.blit(pixmap, ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHATEST);
								painter.clippop();
							}
						}

						//crypto icon stuff
						if (m_crypto_icon_mode && m_pixmaps[picCrypto])
						{
							eSize pixmap_size = m_pixmaps[picCrypto]->size();
							eRect area = m_element_position[celServiceInfo];
							int offs = 0;
							if (m_crypto_icon_mode == 1)
							{
								m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + 8);
								m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - 8);
								area = m_element_position[celServiceName];
								offs = xoffs;
								xoffs += pixmap_size.width() + 8;
							}
							int correction = (area.height() - pixmap_size.height()) / 2;
							area.moveBy(offset);
							if (service_info->isCrypted(*m_cursor))
							{
								if (m_crypto_icon_mode == 2)
								{
									m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + 8);
									m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - 8);
								}
								painter.clip(area);
								painter.blit(m_pixmaps[picCrypto], ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHATEST);
								painter.clippop();
							}
						}
					}
				}

				if (flags & gPainter::RT_HALIGN_RIGHT)
					para->realign(eTextPara::dirRight);
				else if (flags & gPainter::RT_HALIGN_CENTER)
					para->realign(eTextPara::dirCenter);
				else if (flags & gPainter::RT_HALIGN_BLOCK)
					para->realign(eTextPara::dirBlock);

				if (flags & gPainter::RT_VALIGN_CENTER)
				{
					eRect bbox = para->getBoundBox();
					yoffs = (area.height() - bbox.height()) / 2 - bbox.top();
				}

				painter.renderPara(para, offset+ePoint(xoffs, yoffs));
			}
			else if ((e == celFolderPixmap && m_cursor->flags & eServiceReference::isDirectory) ||
				(e == celMarkerPixmap && m_cursor->flags & eServiceReference::isMarker &&
				!(m_cursor->flags & eServiceReference::isNumberedMarker)))
			{
				ePtr<gPixmap> &pixmap =
					(e == celFolderPixmap) ? m_pixmaps[picFolder] : m_pixmaps[picMarker];
				if (pixmap)
				{
					eSize pixmap_size = pixmap->size();
					eRect area = m_element_position[e == celFolderPixmap ? celServiceName: celServiceNumber];
					int correction = (area.height() - pixmap_size.height()) / 2;
					if (e == celFolderPixmap)
						xoffset = pixmap_size.width() + 8;
					area.moveBy(offset);
					painter.clip(area);
					painter.blit(pixmap, ePoint(area.left(), offset.y() + correction), area, gPainter::BT_ALPHATEST);
					painter.clippop();
				}
			}
		}
예제 #19
0
CString CGenethonDoc::runTest3(PyObject *pModule, CString& function) {

    CString output = CString();
    PyObject *pDict, *pFunc;
    PyObject *pArgTuple, *pValue, *pXVec, *pYVec;
    PyObject *ptype, *pvalue, *ptraceback;

    int i;

    // Set the path to include the current directory in case the module is located there. Found from
    // http://stackoverflow.com/questions/7624529/python-c-api-doesnt-load-module
    // and http://stackoverflow.com/questions/7283964/embedding-python-into-c-importing-modules


    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, function);   //Get the function by its name
        // pFunc is a new reference

        if (pFunc && PyCallable_Check(pFunc)) {

            //Set up a tuple that will contain the function arguments. In this case, the
            //function requires two tuples, so we set up a tuple of size 2.
            pArgTuple = PyTuple_New(2);

            //Make some vectors containing the data
            static const double xarr[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 };
            std::vector<double> xvec(xarr, xarr + sizeof(xarr) / sizeof(xarr[0]));
            static const double yarr[] = { 0,0,1,1,0,0,2,2,0,0,1,1,0,0 };
            std::vector<double> yvec(yarr, yarr + sizeof(yarr) / sizeof(yarr[0]));

            //Transfer the C++ vector to a python tuple
            pXVec = PyTuple_New(xvec.size());
            for (i = 0; i < xvec.size(); ++i) {
                pValue = PyFloat_FromDouble(xvec[i]);
                if (!pValue) {
                    Py_DECREF(pXVec);
                    Py_DECREF(pModule);
                    return "Cannot convert array value\n";
                }
                PyTuple_SetItem(pXVec, i, pValue);
            }

            //Transfer the other C++ vector to a python tuple
            pYVec = PyTuple_New(yvec.size());
            for (i = 0; i < yvec.size(); ++i) {
                pValue = PyFloat_FromDouble(yvec[i]);
                if (!pValue) {
                    Py_DECREF(pYVec);
                    Py_DECREF(pModule);
                    return "Cannot convert array value\n";
                }
                PyTuple_SetItem(pYVec, i, pValue); //
            }

            //Set the argument tuple to contain the two input tuples
            PyTuple_SetItem(pArgTuple, 0, pXVec);
            PyTuple_SetItem(pArgTuple, 1, pYVec);

            //Call the python function
            pValue = PyObject_CallObject(pFunc, pArgTuple);

            Py_DECREF(pArgTuple);
            //			Py_DECREF(pXVec);
            //			Py_DECREF(pYVec);

            if (pValue != NULL) {
                PyObject* v = PyObject_GetAttrString(pModule, "richTextOutput");
                output.Format("Result of call: %ld", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }

            //Some error catching
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                return handlePyError();
            }
        }
        else {
            if (PyErr_Occurred()) {
                return handlePyError();
            }
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        return handlePyError();
    }
    return output;
}
예제 #20
0
void DataSourceWrapper::GetRow(StringList& row, const String& table, int row_index, const StringList& columns)
{
	PyObject* callable = PyObject_GetAttrString(self, "GetRow");
	if (!callable)
	{
		Core::String error_message(128, "Function \"GetRow\" not found on python data source %s.", Utilities::GetPythonClassName(self).CString());
		Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
		PyErr_SetString(PyExc_RuntimeError, error_message.CString());
		python::throw_error_already_set();
		return;
	}

	python::tuple t = python::make_tuple(table.CString(), row_index, columns);
	PyObject* result = PyObject_CallObject(callable, t.ptr());
	Py_DECREF(callable);	

	// If it's a list, then just get the entries out of it
	if (result && PyList_Check(result))
	{
		int num_entries = PyList_Size(result);
		for (int i = 0; i < num_entries; i++)
		{
			Core::String entry;

			PyObject* entry_object = PyList_GetItem(result, i);
			if (PyString_Check(entry_object))
			{
				entry = PyString_AS_STRING(entry_object);
			}
			else if (PyInt_Check(entry_object))
			{
				int entry_int = (int)PyInt_AS_LONG(entry_object);
				Core::TypeConverter< int, Core::String >::Convert(entry_int, entry);
			}
			else if (PyFloat_Check(entry_object))
			{
				float entry_float = (float)PyFloat_AS_DOUBLE(entry_object);
				Core::TypeConverter< float, Core::String >::Convert(entry_float, entry);
			}
			else
			{
				Core::String error_message(128, "Failed to convert row %d entry %d on data source %s.", row_index, i, Utilities::GetPythonClassName(self).CString());
				Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
				PyErr_SetString(PyExc_RuntimeError, error_message.CString());
				python::throw_error_already_set();
			}

			row.push_back(entry);
		}
	}
	else
	{
		// Print the error and restore it to the caller
		PyObject *type, *value, *traceback;
		PyErr_Fetch(&type, &value, &traceback);
		Py_XINCREF(type);
		Py_XINCREF(value);
		Py_XINCREF(traceback);

		Core::String error_message(128, "Failed to get entries for table %s row %d from python data source %s.", table.CString(), row_index, Utilities::GetPythonClassName(self).CString());
		Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
		if (type == NULL)
			PyErr_SetString(PyExc_RuntimeError, error_message.CString());
		else
			PyErr_Restore(type, value, traceback);

		python::throw_error_already_set();
	}

	if (result)
		Py_DECREF(result);
}
예제 #21
0
static void
_sieve_action_printer (void *data, mu_stream_t stream,
		       size_t msgno, mu_message_t msg,
		       const char *action, const char *fmt, va_list ap)
{
  PyObject *py_args;
  PyObject *py_dict = PyDict_New ();
  PyStream *py_stm;

  if (!py_dict)
    return;
  py_stm = PyStream_NEW ();
  if (py_stm)
    {
      PyMessage *py_msg = PyMessage_NEW ();
      char *buf = NULL;
      size_t buflen = 0;

      if (py_msg)
	{
	  PyStream *py_stm = PyStream_NEW ();
	  if (py_stm)
	    {
	      py_stm->stm = stream;
	      mu_stream_ref (stream);
	  
	      py_msg->msg = msg;
	      Py_INCREF (py_msg);

	      PyDict_SetItemString (py_dict, "msgno",
				    PyInt_FromSize_t (msgno));
	      PyDict_SetItemString (py_dict, "msg", (PyObject *)py_msg);
	      PyDict_SetItemString (py_dict, "action",
				    PyString_FromString (action ? action : ""));

	      if (mu_vasnprintf (&buf, &buflen, fmt, ap))
		{
		  mu_stream_unref (stream);
		  return;
		}
	      PyDict_SetItemString (py_dict, "text",
				    PyString_FromString (buf ? buf : ""));
	      free (buf);

	      py_args = PyTuple_New (1);
	      if (py_args)
		{
		  struct _mu_py_sieve_logger *s = data;
		  PyObject *py_fnc = s->py_action_printer;

		  Py_INCREF (py_dict);
		  PyTuple_SetItem (py_args, 0, py_dict);
		  
		  if (py_fnc && PyCallable_Check (py_fnc))
		    PyObject_CallObject (py_fnc, py_args);

		  Py_DECREF (py_dict);
		  Py_DECREF (py_args);
		}
	    }
	}
    }
}
예제 #22
0
PyObject *
Signature_obj_from_ccn(PyObject *py_signature)
{
	struct ccn_charbuf *signature;
	PyObject *py_obj_signature, *py_o;
	struct ccn_buf_decoder decoder, *d;
	size_t start, stop, size;
	const unsigned char *ptr;
	int r;

	assert(CCNObject_IsValid(SIGNATURE, py_signature));
	signature = CCNObject_Get(SIGNATURE, py_signature);

	debug("Signature_from_ccn start, len=%zd\n", signature->length);

	// 1) Create python object
	py_obj_signature = PyObject_CallObject(g_type_Signature, NULL);
	if (!py_obj_signature)
		return NULL;

	// 2) Set ccn_data to a cobject pointing to the c struct
	//    and ensure proper destructor is set up for the c object.
	r = PyObject_SetAttrString(py_obj_signature, "ccn_data", py_signature);
	JUMP_IF_NEG(r, error);

	// 3) Parse c structure and fill python attributes

	// Neither DigestAlgorithm nor Witness are included in the packet
	// from ccnput, so they are apparently both optional
	d = ccn_buf_decoder_start(&decoder, signature->buf, signature->length);

	if (!ccn_buf_match_dtag(d, CCN_DTAG_Signature)) {
		PyErr_Format(g_PyExc_CCNSignatureError, "Error finding"
				" CCN_DTAG_Signature (decoder state: %d)", d->decoder.state);
		goto error;
	}

	debug("Is a signature\n");
	ccn_buf_advance(d);

	/* CCN_DTAG_DigestAlgorithm */
	start = d->decoder.token_index;
	ccn_parse_optional_tagged_BLOB(d, CCN_DTAG_DigestAlgorithm, 1, -1);
	stop = d->decoder.token_index;

	r = ccn_ref_tagged_BLOB(CCN_DTAG_DigestAlgorithm, d->buf, start, stop,
			&ptr, &size);
	if (r == 0) {
		debug("PyObject_SetAttrString digestAlgorithm\n");
		py_o = PyBytes_FromStringAndSize((const char*) ptr, size);
		JUMP_IF_NULL(py_o, error);
		r = PyObject_SetAttrString(py_obj_signature, "digestAlgorithm", py_o);
		Py_DECREF(py_o);
		JUMP_IF_NEG(r, error);
	}

	/* CCN_DTAG_Witness */
	start = d->decoder.token_index;
	ccn_parse_optional_tagged_BLOB(d, CCN_DTAG_Witness, 1, -1);
	stop = d->decoder.token_index;
	debug("witness start %zd stop %zd\n", start, stop);

	r = ccn_ref_tagged_BLOB(CCN_DTAG_Witness, d->buf, start, stop, &ptr, &size);
	if (r == 0) {
		// The Witness is represented as a DER-encoded PKCS#1 DigestInfo,
		// which contains an AlgorithmIdentifier (an OID, together with any necessary parameters)
		// and a byte array (OCTET STRING) containing the digest information to be interpreted according to that OID.
		// http://www.ccnx.org/releases/latest/doc/technical/SignatureGeneration.html
		debug("PyObject_SetAttrString witness\n");
		py_o = PyBytes_FromStringAndSize((const char*) ptr, size);
		JUMP_IF_NULL(py_o, error);
		r = PyObject_SetAttrString(py_obj_signature, "witness", py_o);
		Py_DECREF(py_o);
		JUMP_IF_NEG(r, error);
	}

	/* CCN_DTAG_SignatureBits */
	start = d->decoder.token_index;
	ccn_parse_required_tagged_BLOB(d, CCN_DTAG_SignatureBits, 1, -1);
	stop = d->decoder.token_index;

	r = ccn_ref_tagged_BLOB(CCN_DTAG_SignatureBits, d->buf, start, stop, &ptr,
			&size);
	if (r < 0) {
		PyErr_Format(g_PyExc_CCNSignatureError, "Error parsing"
				" CCN_DTAG_SignatureBits (decoder state %d)", d->decoder.state);
		goto error;
	}

	assert(r == 0);
	debug("PyObject_SetAttrString signatureBits\n");
	py_o = PyBytes_FromStringAndSize((const char*) ptr, size);
	JUMP_IF_NULL(py_o, error);
	r = PyObject_SetAttrString(py_obj_signature, "signatureBits", py_o);
	Py_DECREF(py_o);
	JUMP_IF_NEG(r, error);

	ccn_buf_check_close(d);
	if (d->decoder.state < 0) {
		PyErr_Format(g_PyExc_CCNSignatureError, "Signature decoding error"
				" (decoder state: %d, numval: %zd)", d->decoder.state,
				d->decoder.numval);
		goto error;
	}

	// 4) Return the created object
	debug("Signature_from_ccn ends\n");
	return py_obj_signature;

error:
	Py_DECREF(py_obj_signature);
	return NULL;
}
예제 #23
0
static PyObject * aqbanking_listacc(PyObject *self, PyObject *args)
{
	int rv;
	AB_ACCOUNT_LIST2 *accs;
	// List of accounts => to return.
	PyObject *accountList;
	aqbanking_Account *account;
	accountList = PyList_New(0);

	// Initialize aqbanking.
	rv = AB_create(NULL);
	if (rv > 0)
	{
		return NULL;
	}

	/* Get a list of accounts which are known to AqBanking.
	 * There are some pecularities about the list returned:
	 * The list itself is owned by the caller (who must call
	 * AB_Account_List2_free() as we do below), but the elements of that
	 * list (->the accounts) are still owned by AqBanking.
	 * Therefore you MUST NOT free any of the accounts within the list returned.
	 * This also rules out calling AB_Account_List2_freeAll() which not only
	 * frees the list itself but also frees all its elements.
	 *
	 * The rest of this tutorial shows how lists are generally used by
	 * AqBanking.
	 */
	accs = AB_Banking_GetAccounts(ab);
	if (accs) {
		AB_ACCOUNT_LIST2_ITERATOR *it;

		/* List2's are traversed using iterators. An iterator is an object
		 * which points to a single element of a list.
		 * If the list is empty NULL is returned.
		 */
		it=AB_Account_List2_First(accs);
		if (it) {
			AB_ACCOUNT *a;

			/* this function returns a pointer to the element of the list to
			 * which the iterator currently points to */
			a=AB_Account_List2Iterator_Data(it);
			while(a) {
				AB_PROVIDER *pro;
				account = (aqbanking_Account*) PyObject_CallObject((PyObject *) &aqbanking_AccountType, NULL);

				/* every account is assigned to a backend (sometimes called provider)
				 * which actually performs online banking tasks. We get a pointer
				 * to that provider/backend with this call to show its name in our
				 * example.*/
				pro = AB_Account_GetProvider(a);
				// Populate the object.
				account->no = PyUnicode_FromString(AB_Account_GetAccountNumber(a));
				account->name = PyUnicode_FromString(AB_Account_GetAccountName(a));
				account->description = PyUnicode_FromString(AB_Provider_GetName(pro));
				account->bank_code = PyUnicode_FromString(AB_Account_GetBankCode(a));
				account->bank_name = PyUnicode_FromString(AB_Account_GetBankName(a));
				PyList_Append(accountList, (PyObject *)account);
				Py_DECREF(account);

				/* this function lets the iterator advance to the next element in
				 * the list, so a following call to AB_Account_List2Iterator_Data()
				 * would return a pointer to the next element.
				 * This function also returns a pointer to the next element of the
				 * list. If there is no next element then NULL is returned. */
				a = AB_Account_List2Iterator_Next(it);
			}
			/* the iterator must be freed after using it */
			AB_Account_List2Iterator_free(it);
		}
		/* as discussed the list itself is only a container which has to be freed
		 * after use. This explicitly does not free any of the elements in that
		 * list, and it shouldn't because AqBanking still is the owner of the
		 * accounts */
		AB_Account_List2_free(accs);
	}

	// Exit aqbanking.
	rv = AB_free(NULL);
	if (rv > 0)
	{
		Py_DECREF(account);
		Py_DECREF(accountList);
		return NULL;
	}

	return accountList;
}
예제 #24
0
static gboolean
cedit_python_init (CeditPluginLoaderPython *loader)
{
	PyObject *mdict, *tuple;
	PyObject *cedit, *ceditutils, *ceditcommands, *ceditplugins;
	PyObject *gettext, *install, *gettext_args;
	//char *argv[] = { "cedit", NULL };
	char *argv[] = { CEDIT_PLUGINS_LIBS_DIR, NULL };
#ifdef HAVE_SIGACTION
	gint res;
	struct sigaction old_sigint;
#endif

	if (loader->priv->init_failed)
	{
		/* We already failed to initialized Python, don't need to
		 * retry again */
		return FALSE;
	}
	
	if (Py_IsInitialized ())
	{
		/* Python has already been successfully initialized */
		return TRUE;
	}

	/* We are trying to initialize Python for the first time,
	   set init_failed to FALSE only if the entire initialization process
	   ends with success */
	loader->priv->init_failed = TRUE;

	/* Hack to make python not overwrite SIGINT: this is needed to avoid
	 * the crash reported on bug #326191 */

	/* CHECK: can't we use Py_InitializeEx instead of Py_Initialize in order
          to avoid to manage signal handlers ? - Paolo (Dec. 31, 2006) */

#ifdef HAVE_SIGACTION
	/* Save old handler */
	res = sigaction (SIGINT, NULL, &old_sigint);  
	if (res != 0)
	{
		g_warning ("Error initializing Python interpreter: cannot get "
		           "handler to SIGINT signal (%s)",
		           g_strerror (errno));

		return FALSE;
	}
#endif

	/* Python initialization */
	Py_Initialize ();

#ifdef HAVE_SIGACTION
	/* Restore old handler */
	res = sigaction (SIGINT, &old_sigint, NULL);
	if (res != 0)
	{
		g_warning ("Error initializing Python interpreter: cannot restore "
		           "handler to SIGINT signal (%s).",
		           g_strerror (errno));

		goto python_init_error;
	}
#endif

	PySys_SetArgv (1, argv);

	if (!cedit_check_pygtk2 ())
	{
		/* Warning message already printed in check_pygtk2 */
		goto python_init_error;
	}

	/* import gobject */	
	cedit_init_pygobject ();
	if (PyErr_Occurred ())
	{
		g_warning ("Error initializing Python interpreter: could not import pygobject.");

		goto python_init_error;		
	}

	/* import gtk */
	cedit_init_pygtk ();
	if (PyErr_Occurred ())
	{
		g_warning ("Error initializing Python interpreter: could not import pygtk.");

		goto python_init_error;
	}
	
	/* import gtksourceview */
	cedit_init_pygtksourceview ();
	if (PyErr_Occurred ())
	{
		PyErr_Print ();

		g_warning ("Error initializing Python interpreter: could not import pygtksourceview.");

		goto python_init_error;
	}	
	
	/* import cedit */
	cedit = Py_InitModule ("cedit", pycedit_functions);
	mdict = PyModule_GetDict (cedit);

	pycedit_register_classes (mdict);
	pycedit_add_constants (cedit, "CEDIT_");

	/* cedit version */
	tuple = Py_BuildValue("(iii)", 
			      CEDIT_MAJOR_VERSION,
			      CEDIT_MINOR_VERSION,
			      CEDIT_MICRO_VERSION);
	PyDict_SetItemString(mdict, "version", tuple);
	Py_DECREF(tuple);
	
	/* Retrieve the Python type for cedit.Plugin */
	PyCeditPlugin_Type = (PyTypeObject *) PyDict_GetItemString (mdict, "Plugin"); 
	if (PyCeditPlugin_Type == NULL)
	{
		PyErr_Print ();

		goto python_init_error;
	}

	/* import cedit.utils */
	ceditutils = Py_InitModule ("cedit.utils", pyceditutils_functions);
	PyDict_SetItemString (mdict, "utils", ceditutils);

	/* import cedit.commands */
	ceditcommands = Py_InitModule ("cedit.commands", pyceditcommands_functions);
	PyDict_SetItemString (mdict, "commands", ceditcommands);

	/* initialize empty cedit.plugins module */
	ceditplugins = Py_InitModule ("cedit.plugins", NULL);
	PyDict_SetItemString (mdict, "plugins", ceditplugins);

	mdict = PyModule_GetDict (ceditutils);
	pyceditutils_register_classes (mdict);
	
	mdict = PyModule_GetDict (ceditcommands);
	pyceditcommands_register_classes (mdict);

	/* i18n support */
	gettext = PyImport_ImportModule ("gettext");
	if (gettext == NULL)
	{
		g_warning ("Error initializing Python interpreter: could not import gettext.");

		goto python_init_error;
	}

	mdict = PyModule_GetDict (gettext);
	install = PyDict_GetItemString (mdict, "install");
	gettext_args = Py_BuildValue ("ss", GETTEXT_PACKAGE, CEDIT_LOCALEDIR);
	PyObject_CallObject (install, gettext_args);
	Py_DECREF (gettext_args);
	
	/* Python has been successfully initialized */
	loader->priv->init_failed = FALSE;
	
	return TRUE;
	
python_init_error:

	g_warning ("Please check the installation of all the Python related packages required "
	           "by cedit and try again.");

	PyErr_Clear ();

	cedit_python_shutdown (loader);

	return FALSE;
}
예제 #25
0
파일: main.c 프로젝트: yampolskiy/sslscan
int init(int argc, char *argv[], struct sslCheckOptions *options)
{
	SSLeay_add_all_algorithms();
	ERR_load_crypto_strings();
	// Init...
	memset(options, 0, sizeof(struct sslCheckOptions));
	// ToDo:
	//xmlArg = 0;
	strcpy(options->host, "127.0.0.1");
	options->service[0] = '\0';
	options->bindLocalAddress = false;
	options->forceAddressFamily = FORCE_AF_UNSPEC;
	options->noFailed = false;
	options->reneg = false;
	options->starttls_ftp = false;
	options->starttls_imap = false;
	options->starttls_pop3 = false;
	options->starttls_smtp = false;
	options->starttls_xmpp = false;
	options->verbose = false;
	options->targets = NULL;
	options->connection_delay = 0;
	options->connection_time.tv_sec = 0;
	options->connection_time.tv_usec = 0;

	options->ssl_versions = ssl_all;
	options->pout = false;
	options->scan_mode = SSLSCAN_SCAN_MODE_FAST;
	SSL_library_init();

#ifdef IS_PY3K
	wchar_t progname[255 + 1];
	mbstowcs(progname, argv[0], strlen(argv[0]) + 1);
	Py_SetProgramName(progname);
#else /* IS_PY3K */
	Py_SetProgramName(argv[0]);
#endif /* IS_PY3K */

	Py_Initialize();
	PyObject *py_tmp = PySys_GetObject("path");
	//PyList_Append(py_tmp, PyUnicode_FromString("./python"));
	PyObject *py_module = PyImport_ImportModule("sslscan");
	if (py_module == NULL) {
		PyErr_Print();
		// ToDo:
		return 1;
	}

	PyObject *py_func = PyObject_GetAttrString(py_module, "load_handlers");
	if(py_func == NULL) {
		PyErr_Print();
		// ToDo:
		return 1;
	}
	PyObject *py_args = PyTuple_New(0);
	PyObject *py_result = PyObject_CallObject(py_func, py_args);

	if(py_result == NULL) {
		PyErr_Print();
		// ToDo:
		return 1;
	}
	options->py_config = PyObject_GetAttrString(py_module, "config");
	options->py_output_handler = PyObject_GetAttrString(py_module, "output");
	options->py_service_handler = PyObject_GetAttrString(py_module, "service");
	return 0;
}
예제 #26
0
void PythonTransform::transform(const QByteArray &input, QByteArray &output)
{
    if (input.isEmpty())
        return;

    PyGILState_STATE lgstate;
    lgstate = PyGILState_Ensure();
    if (loadModule()) {
        PyObject * pyInbound = Py_False; // needs reference count management

        if (twoWays)
            pyInbound = (wayValue == INBOUND ? Py_True : Py_False );
        Py_INCREF(pyInbound);

        if (PyModule_AddObject(pModule, PythonModules::INBOUND_ATTR_NAME, pyInbound) == -1) { // steal reference
            pythonmgm->checkPyError();
            logError(tr("T_T Could not set the direction value properly:\n%1").arg(pythonmgm->getLastError()),id);
            Py_XDECREF(pyInbound);
            PyGILState_Release(lgstate);
            return;
        }

        PyObject *paramsdict = PyDict_New(); // setting an empty dictionary
        // setting parameters in the python environment
        if (!parameters.isEmpty()) {
            if (!pythonmgm->checkPyError()) {
                logError(tr("T_T Error while creating the Python parameter dict:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(paramsdict);
                PyGILState_Release(lgstate);
                return;
            }
            // adding parameters to the python list
            QHashIterator<QByteArray, QByteArray> i(parameters);
            while (i.hasNext()) {
                i.next();
                PyObject* paramKey = PyUnicode_FromStringAndSize(i.key(),i.key().size());
                if (!pythonmgm->checkPyError()) {
                    logError(tr("T_T Error while creating Python parameter key:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    PyGILState_Release(lgstate);
                    return;
                }

                PyObject* paramValue = PyUnicode_FromStringAndSize(i.value(),i.value().size());
                if (!pythonmgm->checkPyError()) {
                    logError(tr("T_T Error while creating Python parameter value:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    Py_XDECREF(paramKey);
                    PyGILState_Release(lgstate);
                    return;
                }

                if (PyDict_SetItem(paramsdict,paramKey,paramValue) == -1) { // not stealing reference
                    pythonmgm->checkPyError(); // we already know there was an error
                    logError(tr("T_T Error while setting Python parameter pair:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    Py_XDECREF(paramKey);
                    Py_XDECREF(paramValue);
                    PyGILState_Release(lgstate);
                    return;
                }

                // Cleaning the values (references not stolen)

                Py_XDECREF(paramKey);
                Py_XDECREF(paramValue);
            }
        }

        // setting the dictionary in any case, even if it is empty
        if (PyModule_AddObject(pModule,PythonModules::PARAMS_ATTR_NAME , paramsdict) == -1) { // stolen paramsdict reference
            pythonmgm->checkPyError();
            logError(tr("T_T Could not set the Pip3line_params value properly:\n%1").arg(pythonmgm->getLastError()),id);
        }

        PyObject * pFunc = PyObject_GetAttrString(pModule, PythonModules::MAIN_FUNCTION_NAME);

        if (pythonmgm->checkPyError() && PyCallable_Check(pFunc)) {
            PyObject* pArgs = PyTuple_New(1);

            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Error while creating the Python argument tuple:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                PyGILState_Release(lgstate);
                return;
            }

            PyObject* inputPy = PyByteArray_FromStringAndSize(input.data(),input.size());
            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                Py_XDECREF(inputPy);
                PyGILState_Release(lgstate);
                return;
            }

            if (PyTuple_SetItem(pArgs, 0, inputPy) != 0) {// stealing the reference of inputPy
                pythonmgm->checkPyError();
                Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(inputPy);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                PyGILState_Release(lgstate);
                return;
            }
            PyObject* returnValue = PyObject_CallObject(pFunc, pArgs); // new ref or NULL

            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Python error while executing the function:\n %1").arg(pythonmgm->getLastError()), id);
            } else {
                if (PyByteArray_Check(returnValue)) {

                    Py_ssize_t templength = PyByteArray_Size(returnValue);
                    if (templength > BLOCK_MAX_SIZE) {
                        templength = BLOCK_MAX_SIZE;
                        Q_EMIT warning(tr("Data block returned is too large, truncating."),id);
                    }

                    char * buffer = PyByteArray_AsString(returnValue); // never to be deleted
                    output.append(QByteArray(buffer,static_cast<int>(templength))); // safe cast as value was checked earlier
                } else {
                    Q_EMIT error(tr("The Python object returned is not a bytearray"), id);
                }
            }

            Py_XDECREF(returnValue);
            Py_XDECREF(pArgs);
          //  Py_DECREF(inputPy); // stolen reference, don't touch that
            Py_XDECREF(pFunc);

        } else {
            Q_EMIT error(tr("Python error while calling the function %1():\n%2").arg(PythonModules::MAIN_FUNCTION_NAME).arg(pythonmgm->getLastError()), id);
        }
    } else {
        qDebug() << "[Python transform] could not load the module";
    }

    PyGILState_Release(lgstate);
}
예제 #27
0
파일: jcc.cpp 프로젝트: ahua/java
static void JNICALL _PythonException_getErrorInfo(JNIEnv *vm_env, jobject self)
{
    PythonGIL gil(vm_env);

    if (!PyErr_Occurred())
        return;

    PyObject *type, *value, *tb, *errorName;
    jclass jcls = vm_env->GetObjectClass(self);

    PyErr_Fetch(&type, &value, &tb);

    errorName = PyObject_GetAttrString(type, "__name__");
    if (errorName != NULL)
    {
        jfieldID fid =
            vm_env->GetFieldID(jcls, "errorName", "Ljava/lang/String;");
        jstring str = env->fromPyString(errorName);

        vm_env->SetObjectField(self, fid, str);
        vm_env->DeleteLocalRef(str);
        Py_DECREF(errorName);
    }

    if (value != NULL)
    {
        PyObject *message = PyObject_Str(value);

        if (message != NULL)
        {
            jfieldID fid =
                vm_env->GetFieldID(jcls, "message", "Ljava/lang/String;");
            jstring str = env->fromPyString(message);

            vm_env->SetObjectField(self, fid, str);
            vm_env->DeleteLocalRef(str);
            Py_DECREF(message);
        }
    }

    PyObject *module = NULL, *cls = NULL, *stringIO = NULL, *result = NULL;
    PyObject *_stderr = PySys_GetObject("stderr");
    if (!_stderr)
        goto err;

    module = PyImport_ImportModule("cStringIO");
    if (!module)
        goto err;

    cls = PyObject_GetAttrString(module, "StringIO");
    Py_DECREF(module);
    if (!cls)
        goto err;

    stringIO = PyObject_CallObject(cls, NULL);
    Py_DECREF(cls);
    if (!stringIO)
        goto err;

    Py_INCREF(_stderr);
    PySys_SetObject("stderr", stringIO);

    PyErr_Restore(type, value, tb);
    PyErr_Print();

    result = PyObject_CallMethod(stringIO, "getvalue", NULL);
    Py_DECREF(stringIO);

    if (result != NULL)
    {
        jfieldID fid =
            vm_env->GetFieldID(jcls, "traceback", "Ljava/lang/String;");
        jstring str = env->fromPyString(result);

        vm_env->SetObjectField(self, fid, str);
        vm_env->DeleteLocalRef(str);
        Py_DECREF(result);
    }

    PySys_SetObject("stderr", _stderr);
    Py_DECREF(_stderr);

    return;

  err:
    PyErr_Restore(type, value, tb);
}
예제 #28
0
/*
 * bitfields extension:
 * bitsize != 0: this is a bit field.
 * pbitofs points to the current bit offset, this will be updated.
 * prev_desc points to the type of the previous bitfield, if any.
 */
PyObject *
PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
                Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
                Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
                int pack, int big_endian)
{
    CFieldObject *self;
    PyObject *proto;
    Py_ssize_t size, align;
    SETFUNC setfunc = NULL;
    GETFUNC getfunc = NULL;
    StgDictObject *dict;
    int fieldtype;
#define NO_BITFIELD 0
#define NEW_BITFIELD 1
#define CONT_BITFIELD 2
#define EXPAND_BITFIELD 3

    self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type,
                                               NULL);
    if (self == NULL)
        return NULL;
    dict = PyType_stgdict(desc);
    if (!dict) {
        PyErr_SetString(PyExc_TypeError,
                        "has no _stginfo_");
        Py_DECREF(self);
        return NULL;
    }
    if (bitsize /* this is a bitfield request */
        && *pfield_size /* we have a bitfield open */
#ifdef MS_WIN32
        /* MSVC, GCC with -mms-bitfields */
        && dict->size * 8 == *pfield_size
#else
        /* GCC */
        && dict->size * 8 <= *pfield_size
#endif
        && (*pbitofs + bitsize) <= *pfield_size) {
        /* continue bit field */
        fieldtype = CONT_BITFIELD;
#ifndef MS_WIN32
    } else if (bitsize /* this is a bitfield request */
        && *pfield_size /* we have a bitfield open */
        && dict->size * 8 >= *pfield_size
        && (*pbitofs + bitsize) <= dict->size * 8) {
        /* expand bit field */
        fieldtype = EXPAND_BITFIELD;
#endif
    } else if (bitsize) {
        /* start new bitfield */
        fieldtype = NEW_BITFIELD;
        *pbitofs = 0;
        *pfield_size = dict->size * 8;
    } else {
        /* not a bit field */
        fieldtype = NO_BITFIELD;
        *pbitofs = 0;
        *pfield_size = 0;
    }

    size = dict->size;
    proto = desc;

    /*  Field descriptors for 'c_char * n' are be scpecial cased to
        return a Python string instead of an Array object instance...
    */
    if (PyCArrayTypeObject_Check(proto)) {
        StgDictObject *adict = PyType_stgdict(proto);
        StgDictObject *idict;
        if (adict && adict->proto) {
            idict = PyType_stgdict(adict->proto);
            if (!idict) {
                PyErr_SetString(PyExc_TypeError,
                                "has no _stginfo_");
                Py_DECREF(self);
                return NULL;
            }
            if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
                struct fielddesc *fd = _ctypes_get_fielddesc("s");
                getfunc = fd->getfunc;
                setfunc = fd->setfunc;
            }
#ifdef CTYPES_UNICODE
            if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
                struct fielddesc *fd = _ctypes_get_fielddesc("U");
                getfunc = fd->getfunc;
                setfunc = fd->setfunc;
            }
#endif
        }
    }

    self->setfunc = setfunc;
    self->getfunc = getfunc;
    self->index = index;

    Py_INCREF(proto);
    self->proto = proto;

    switch (fieldtype) {
    case NEW_BITFIELD:
        if (big_endian)
            self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
        else
            self->size = (bitsize << 16) + *pbitofs;
        *pbitofs = bitsize;
        /* fall through */
    case NO_BITFIELD:
        if (pack)
            align = min(pack, dict->align);
        else
            align = dict->align;
        if (align && *poffset % align) {
            Py_ssize_t delta = align - (*poffset % align);
            *psize += delta;
            *poffset += delta;
        }

        if (bitsize == 0)
            self->size = size;
        *psize += size;

        self->offset = *poffset;
        *poffset += size;

        *palign = align;
        break;

    case EXPAND_BITFIELD:
        *poffset += dict->size - *pfield_size/8;
        *psize += dict->size - *pfield_size/8;

        *pfield_size = dict->size * 8;

        if (big_endian)
            self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
        else
            self->size = (bitsize << 16) + *pbitofs;

        self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
        *pbitofs += bitsize;
        break;

    case CONT_BITFIELD:
        if (big_endian)
            self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
        else
            self->size = (bitsize << 16) + *pbitofs;

        self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
        *pbitofs += bitsize;
        break;
    }

    return (PyObject *)self;
}
예제 #29
0
파일: GenPy.cpp 프로젝트: kbochenina/Snap
int CallPyFunction(const char *moduleName, const char *funcName, const TStrV& args, const TStrV& argTypes,  PyObject** res, PyObject*** pyObjects = nullptr)
{
	PyObject *pName, *pModule, *pFunc, *pArgs;
	bool err = false;
	// get PyObject representation of moduleName
	pName = PyUnicode_FromString(moduleName);
	TExeTm execTime;
	// import module
	pModule = PyImport_Import(pName);
	cout << "Time of importing module " << moduleName << ": " << execTime.GetTmStr() << endl;
	// we don't need pName anymore
	Py_DECREF(pName);
	// if module was loaded 
	if (pModule != nullptr) {
		// get pointer to function
		pFunc = PyObject_GetAttrString(pModule, funcName);
		// check function for existence
		if (pFunc && PyCallable_Check(pFunc)) {
			// a number of arguments
			int argc = argTypes.Len();
			// tuple of arguments
			pArgs = PyTuple_New(argc);
			// index of current PyObject in array of PyObjects
			int argPyObjIndex = 0, argStrIndex = 0;
			// parsing arguments
			for (size_t i = 0; i < argc; i++)
			{
				PyObject **arg = new PyObject*[1];
				//printf("argtypes[%d] = %s\n", i, argTypes[i].CStr());
				if (argTypes[i] != "pyobject"){
					if (!ParseArgument(args[argStrIndex++], argTypes[i], arg))
						err = true;
				}
				else
				{
					// non-safe
					*arg = pyObjects[argPyObjIndex++][0];
				}
				PyTuple_SetItem(pArgs, i, *arg);
				Py_DECREF(arg);
			}
			//TExeTm execTime;
			*res = PyObject_CallObject(pFunc, pArgs);
			//cout << "Time of execution of function " << funcName << ": " << execTime.GetTmStr() << endl; 
			if (PyErr_Occurred()){
                PyErr_Print();
				err = true;
			}
			if (res == nullptr)
			{
				PyErr_Print();
                fprintf(stderr,"Call failed\n");
                err = true;
			}
			//Py_DECREF(pArgs);
		}
		else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\" in module \"%s\"\n", funcName, moduleName);
			err = true;
        }
	}
	else {
		PyErr_Print();
		fprintf(stderr, "Failed to load \"%s\"\n", moduleName);
		err = true;
    }
	if (err == true) return 0;
	//Py_DECREF(pArgs);
	Py_DECREF(pFunc);
	Py_DECREF(pModule);
	
	return 1;
}
예제 #30
0
void EM_cluster_p(int nbr_cluster, int size)
{	
	PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue, *pXVec;

    const char *scriptDirectoryName = "/home/alex/Documents/Project/src/python/";

 	Py_Initialize();

    PyObject *sysPath = PySys_GetObject((char *)"path");
    PyObject *path = PyString_FromString(scriptDirectoryName);
    int result = PyList_Insert(sysPath, 0, path);
    pModule = PyImport_ImportModule("rdm_pnt");

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, "rdm_pnt");
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {

            pArgs = PyTuple_New(1);

            pXVec = PyTuple_New(2);

                pValue = PyInt_FromLong((long)nbr_cluster);
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument x\n");
                    return;
                }
                PyTuple_SetItem(pXVec, 0, pValue);
                //set Y's value on other array.
                pValue = PyInt_FromLong((long)size);
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument y\n");
                    return;
                }
                PyTuple_SetItem(pXVec, 1, pValue);  

            PyTuple_SetItem(pArgs, 0, pXVec);
			
            pValue = PyObject_CallObject(pFunc, pArgs);
            //Py_INCREF(pArgs);
            Py_DECREF(pArgs);

            if (PyInt_AsLong(pValue) == 1) {
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function/file\n");
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load module\n");
        return;
    }
    //Py_Finalize();
}