Exemple #1
0
static int pyth_metric_init (apr_pool_t *p)
{
    DIR *dp;
    struct dirent *entry;
    int i;
    char* modname;
    PyObject *pmod, *pinitfunc, *pobj, *pparamdict;
    py_metric_init_t minfo;
    Ganglia_25metric *gmi;
    mapped_info_t *mi;
    const char* path = python_module.module_params;
    cfg_t *module_cfg;

    /* Allocate a pool that will be used by this module */
    apr_pool_create(&pool, p);

    metric_info = apr_array_make(pool, 10, sizeof(Ganglia_25metric));
    metric_mapping_info = apr_array_make(pool, 10, sizeof(mapped_info_t));

    /* Verify path exists and can be read */

    if (!path) {
        err_msg("[PYTHON] Missing python module path.\n");
        return -1;
    }

    if (access(path, F_OK))
    {
        /* 'path' does not exist */
        err_msg("[PYTHON] Can't open the python module path %s.\n", path);
        return -1;
    }

    if (access(path, R_OK))
    {
        /* Don't have read access to 'path' */
        err_msg("[PYTHON] Can't read from the python module path %s.\n", path);
        return -1;
    }

    /* Init Python environment */

    /* Set up the python path to be able to load module from our module path */
    Py_Initialize();
    Py_InitModule("ganglia", GangliaMethods);

    PyObject *sys_path = PySys_GetObject("path");
    PyObject *addpath = PyString_FromString(path);
    PyList_Append(sys_path, addpath);

    PyEval_InitThreads();
    gtstate = PyEval_SaveThread();

    /* Initialize each python module */
    if ((dp = opendir(path)) == NULL) {
        /* Error: Cannot open the directory - Shouldn't happen */
        /* Log? */
        err_msg("[PYTHON] Can't open the python module path %s.\n", path);
        return -1;
    }

    i = 0;

    while ((entry = readdir(dp)) != NULL) {
        modname = is_python_module(entry->d_name);

        if (modname == NULL)
            continue;

        /* Find the specified module configuration in gmond.conf 
           If this return NULL then either the module config
           doesn't exist or the module is disabled. */
        module_cfg = find_module_config(modname);
        if (!module_cfg)
            continue;

        PyEval_RestoreThread(gtstate);

        pmod = PyImport_ImportModule(modname);
        if (!pmod) {
            /* Failed to import module. Log? */
            err_msg("[PYTHON] Can't import the metric module [%s].\n", modname);
            if (PyErr_Occurred()) {
                PyErr_Print();
            }
            gtstate = PyEval_SaveThread();
            continue;
        }

        pinitfunc = PyObject_GetAttrString(pmod, "metric_init");
        if (!pinitfunc || !PyCallable_Check(pinitfunc)) {
            /* No metric_init function. */
            err_msg("[PYTHON] Can't find the metric_init function in the python module [%s].\n", modname);
            Py_DECREF(pmod);
            gtstate = PyEval_SaveThread();
            continue;
        }

        /* Build a parameter dictionary to pass to the module */
        pparamdict = build_params_dict(module_cfg);
        if (!pparamdict || !PyDict_Check(pparamdict)) {
            /* No metric_init function. */
            err_msg("[PYTHON] Can't build the parameters dictionary for [%s].\n", modname);
            Py_DECREF(pmod);
            gtstate = PyEval_SaveThread();
            continue;
        }

        /* Now call the metric_init method of the python module */
        pobj = PyObject_CallFunction(pinitfunc, "(N)", pparamdict);

        if (!pobj) {
            /* failed calling metric_init */
            err_msg("[PYTHON] Can't call the metric_init function in the python module [%s].\n", modname);
            if (PyErr_Occurred()) {
                PyErr_Print();
            }
            Py_DECREF(pinitfunc);
            Py_DECREF(pmod);
            gtstate = PyEval_SaveThread();
            continue;
        }

        if (PyList_Check(pobj)) {
            int j;
            int size = PyList_Size(pobj);
            for (j = 0; j < size; j++) {
                PyObject* plobj = PyList_GetItem(pobj, j);
                if (PyMapping_Check(plobj)) {
                    fill_metric_info(plobj, &minfo, modname, pool);
                    gmi = (Ganglia_25metric*)apr_array_push(metric_info);
                    fill_gmi(gmi, &minfo);
                    mi = (mapped_info_t*)apr_array_push(metric_mapping_info);
                    mi->pmod = pmod;
                    mi->mod_name = apr_pstrdup(pool, modname);
                    mi->pcb = minfo.pcb;
                }
            }
        }
        else if (PyMapping_Check(pobj)) {
            fill_metric_info(pobj, &minfo, modname, pool);
            gmi = (Ganglia_25metric*)apr_array_push(metric_info);
            fill_gmi(gmi, &minfo);
            mi = (mapped_info_t*)apr_array_push(metric_mapping_info);
            mi->pmod = pmod;
            mi->mod_name = apr_pstrdup(pool, modname);
            mi->pcb = minfo.pcb;
        }
        Py_DECREF(pobj);
        Py_DECREF(pinitfunc);
        gtstate = PyEval_SaveThread();
    }
    closedir(dp);

    apr_pool_cleanup_register(pool, NULL,
                              pyth_metric_cleanup,
                              apr_pool_cleanup_null);

    /* Replace the empty static metric definition array with the
       dynamic array that we just created 
    */
    /*XXX Need to put this into a finalize MACRO. This is just pushing
      a NULL entry onto the array so that the looping logic can 
      determine the end if the array. We should probably give back
      a ready APR array rather than a pointer to a Ganglia_25metric
      array. */
    gmi = apr_array_push(metric_info);
    memset (gmi, 0, sizeof(*gmi));
    mi = apr_array_push(metric_mapping_info);
    memset (mi, 0, sizeof(*mi));

    python_module.metrics_info = (Ganglia_25metric *)metric_info->elts;
    return 0;
}
Exemple #2
0
static PyObject *PDFfile_save(PDFfile *self)
{
	if (!ScCore->primaryMainWindow()->HaveDoc) {
		PyErr_SetString(PyExc_SystemError, "Need to open document first");
		return NULL;
	};

// copied from file scribus.cpp
//void ScribusMainWindow::SaveAsPDF()
	int Components = 3;
	QString nam = "";
	if (ScCore->primaryMainWindow()->bookmarkPalette->BView->topLevelItemCount() == 0)
		ScCore->primaryMainWindow()->doc->PDF_Options.Bookmarks = false;

// apply fonts attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.EmbedList.clear();
	int n = PyList_Size(self->fonts);
	for ( int i=0; i<n; ++i){
		QString tmpFon;
		tmpFon = QString(PyString_AsString(PyList_GetItem(self->fonts, i)));
		ScCore->primaryMainWindow()->doc->PDF_Options.EmbedList.append(tmpFon);
	}
// apply file attribute
	QString fn;
	fn = QString(PyString_AsString(self->file));
	ScCore->primaryMainWindow()->doc->PDF_Options.fileName = fn;
// apply pages attribute
	std::vector<int> pageNs;
	int nn=PyList_Size(self->pages);
	for (int i = 0; i < nn; ++i) {
		pageNs.push_back((int)PyInt_AsLong(PyList_GetItem(self->pages, i)));
	}
// apply thumbnails attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.Thumbnails = self->thumbnails;
// apply compress attribute
	self->compressmtd = minmaxi(self->compressmtd, 0, 3);
	ScCore->primaryMainWindow()->doc->PDF_Options.Compress = self->compress;
	ScCore->primaryMainWindow()->doc->PDF_Options.CompressMethod = (PDFOptions::PDFCompression) self->compressmtd;
// apply quality attribute
	self->quality = minmaxi(self->quality, 0, 4);
	ScCore->primaryMainWindow()->doc->PDF_Options.Quality = self->quality;
// apply resolusion attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.Resolution = PyInt_AsLong(self->resolution);
// apply downsample attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.RecalcPic = PyInt_AsLong(self->downsample);
	if (ScCore->primaryMainWindow()->doc->PDF_Options.RecalcPic)
		ScCore->primaryMainWindow()->doc->PDF_Options.PicRes = PyInt_AsLong(self->downsample);
	else
		ScCore->primaryMainWindow()->doc->PDF_Options.PicRes = ScCore->primaryMainWindow()->doc->PDF_Options.Resolution;
// apply bookmarks attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.Bookmarks = self->bookmarks;
// apply binding attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.Binding = self->binding;
// apply presentation attribute
	ScCore->primaryMainWindow()->doc->PDF_Options.PresentMode = self->presentation;

	QList<PDFPresentationData> PresentVals;
	PresentVals.clear();
	int tmpnum;
	tmpnum=PyList_Size(self->effval);
	for (int i=0; i<tmpnum; ++i) {
		PDFPresentationData t;
// How do I make this commented piece of code to work?
// I always get an error here
		PyObject *ti = PyList_GetItem(self->effval, i);
//		 if (!PyArg_ParseTuple(ti , "[iiiiii]",
//				  &t.pageEffectDuration, &t.pageViewDuration, &t.effectType, &t.Dm,
//				  &t.M, &t.Di)) {
//			 PyErr_SetString(PyExc_SystemError, "while parsing 'effval'. WHY THIS HAPPENED????");
//			 return NULL;
//		 }
//		 PresentVals.append(t);
				// pv 10/03/2004 crashed when pt is null
				if (ti)
				{
					// Do I Need to check if every PyInt_AsLong and PyList_GetItem funtion succeed???
					t.pageEffectDuration = PyInt_AsLong(PyList_GetItem(ti, 0));
					t.pageViewDuration = PyInt_AsLong(PyList_GetItem(ti, 1));
					t.effectType = PyInt_AsLong(PyList_GetItem(ti, 2));
					t.Dm = PyInt_AsLong(PyList_GetItem(ti, 3));
					t.M = PyInt_AsLong(PyList_GetItem(ti, 4));
					t.Di = PyInt_AsLong(PyList_GetItem(ti, 5));
					PresentVals.append(t);
				} // if ti=NULL

	}

	ScCore->primaryMainWindow()->doc->PDF_Options.PresentVals = PresentVals;
// apply lpival
	int n2 = PyList_Size(self->lpival);
	for (int i=0; i<n2; ++i){
		LPIData lpi;
		PyObject *t = PyList_GetItem(self->lpival, i);
// This code always raise exception - WHY???
//		char *s;
//		 if (!PyArg_ParseTuple(t, "[siii]", &s, &lpi.Frequency,
//				  &lpi.Angle, &lpi.SpotFunc)) {
//			 PyErr_SetString(PyExc_SystemError, "while parsing 'lpival'. WHY THIS HAPPENED????");
//			 return NULL;
//		 }
//		 ScCore->primaryMainWindow()->doc->PDF_Options.LPISettings[QString(s)]=lpi;
		QString st;
		st = QString(PyString_AsString(PyList_GetItem(t,0)));
		lpi.Frequency = PyInt_AsLong(PyList_GetItem(t, 1));
		lpi.Angle = PyInt_AsLong(PyList_GetItem(t, 2));
		lpi.SpotFunc = PyInt_AsLong(PyList_GetItem(t, 3));
		ScCore->primaryMainWindow()->doc->PDF_Options.LPISettings[st]=lpi;
	}

	ScCore->primaryMainWindow()->doc->PDF_Options.Articles = self->article;
	ScCore->primaryMainWindow()->doc->PDF_Options.Encrypt = self->encrypt;
	ScCore->primaryMainWindow()->doc->PDF_Options.UseLPI = self->uselpi;
	ScCore->primaryMainWindow()->doc->PDF_Options.UseSpotColors = self->usespot;
	ScCore->primaryMainWindow()->doc->PDF_Options.doMultiFile = self->domulti;
	self->version = minmaxi(self->version, 12, 14);
	// FIXME: Sanity check version
	ScCore->primaryMainWindow()->doc->PDF_Options.Version = (PDFOptions::PDFVersion)self->version;
	if (self->encrypt)
	{
		int Perm = -64;
		if (ScCore->primaryMainWindow()->doc->PDF_Options.Version == PDFOptions::PDFVersion_14)
			Perm &= ~0x00240000;
		if (self->aprint)
			Perm += 4;
		if (self->achange)
			Perm += 8;
		if (self->acopy)
			Perm += 16;
		if (self->aanot)
			Perm += 32;
		ScCore->primaryMainWindow()->doc->PDF_Options.Permissions = Perm;
		ScCore->primaryMainWindow()->doc->PDF_Options.PassOwner = QString(PyString_AsString(self->owner));
		ScCore->primaryMainWindow()->doc->PDF_Options.PassUser = QString(PyString_AsString(self->user));
	}
	if (self->outdst == 0)
	{
		ScCore->primaryMainWindow()->doc->PDF_Options.UseRGB = true;
		ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles = false;
		ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles2 = false;
	}
	else
	{
		ScCore->primaryMainWindow()->doc->PDF_Options.UseRGB = false;
		if (ScCore->primaryMainWindow()->doc->HasCMS)
		{
			ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles = self->profiles;
			ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles2 = self->profilei;
			self->intents = minmaxi(self->intents, 0, 3);
			ScCore->primaryMainWindow()->doc->PDF_Options.Intent = self->intents;
			self->intenti = minmaxi(self->intenti, 0, 3);
			ScCore->primaryMainWindow()->doc->PDF_Options.Intent2 = self->intenti;
			ScCore->primaryMainWindow()->doc->PDF_Options.EmbeddedI = self->noembicc;
			ScCore->primaryMainWindow()->doc->PDF_Options.SolidProf = PyString_AsString(self->solidpr);
			ScCore->primaryMainWindow()->doc->PDF_Options.ImageProf = PyString_AsString(self->imagepr);
			ScCore->primaryMainWindow()->doc->PDF_Options.PrintProf = PyString_AsString(self->printprofc);
			if (ScCore->primaryMainWindow()->doc->PDF_Options.Version == PDFOptions::PDFVersion_X3)
			{
// Where does compiler find cms function when I have not included header for it
				ScColorProfile hIn;
				hIn = ScColorMgmtEngine::openProfileFromFile(ScCore->PrinterProfiles[ScCore->primaryMainWindow()->doc->PDF_Options.PrintProf]);
				nam = hIn.productDescription();
				if (hIn.colorSpace() == ColorSpace_Rgb)
					Components = 3;
				if (hIn.colorSpace() == ColorSpace_Cmyk)
					Components = 4;
				if (hIn.colorSpace() == ColorSpace_Gray)
					Components = 3;
				ScCore->primaryMainWindow()->doc->PDF_Options.Info = PyString_AsString(self->info);
				self->bleedt = minmaxd(self->bleedt, 0, ScCore->primaryMainWindow()->view->Doc->pageHeight*ScCore->primaryMainWindow()->view->Doc->unitRatio());
				ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Top = self->bleedt/ScCore->primaryMainWindow()->view->Doc->unitRatio();
				self->bleedl = minmaxd(self->bleedl, 0, ScCore->primaryMainWindow()->view->Doc->pageWidth*ScCore->primaryMainWindow()->view->Doc->unitRatio());
				ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Left = self->bleedl/ScCore->primaryMainWindow()->view->Doc->unitRatio();
				self->bleedr = minmaxd(self->bleedr, 0, ScCore->primaryMainWindow()->view->Doc->pageWidth*ScCore->primaryMainWindow()->view->Doc->unitRatio());
				ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Right = self->bleedr/ScCore->primaryMainWindow()->view->Doc->unitRatio();
				self->bleedb = minmaxd(self->bleedb, 0, ScCore->primaryMainWindow()->view->Doc->pageHeight*ScCore->primaryMainWindow()->view->Doc->unitRatio());
				ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Bottom = self->bleedb/ScCore->primaryMainWindow()->view->Doc->unitRatio();
				ScCore->primaryMainWindow()->doc->PDF_Options.Encrypt = false;
				ScCore->primaryMainWindow()->doc->PDF_Options.PresentMode = false;
			}
		}
		else
		{
			ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles = false;
			ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles2 = false;
		}

	}
	QMap<int,QPixmap> thumbs;
	for (uint ap = 0; ap < pageNs.size(); ++ap)
	{
		QPixmap pm(10,10);
		if (ScCore->primaryMainWindow()->doc->PDF_Options.Thumbnails)
			pm = QPixmap::fromImage(ScCore->primaryMainWindow()->view->PageToPixmap(pageNs[ap]-1, 100));
		thumbs.insert(pageNs[ap], pm);
	}
	ReOrderText(ScCore->primaryMainWindow()->doc, ScCore->primaryMainWindow()->view);
	QString errorMessage;
	if (!ScCore->primaryMainWindow()->getPDFDriver(fn, nam, Components, pageNs, thumbs, errorMessage)) {
		fn  = "Cannot write the File: " + fn;
		if (!errorMessage.isEmpty())
			fn += QString("\n%1").arg(errorMessage);
		PyErr_SetString(PyExc_SystemError, fn.toAscii());
		return NULL;
	}
//	Py_INCREF(Py_None);
//	return Py_None;
	Py_RETURN_NONE;
}
/**
 *******************************************************************************************************
 * This function invokes csdk's API's.
 *
 * @param self                  AerospikeClient object
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param key                   The C client's as_key that identifies the record.
 * @param py_list               The list containing op, bin and value.
 * @param py_meta               The metadata for the operation.
 * @param operate_policy_p      The value for operate policy.
 *******************************************************************************************************
 */
static
PyObject *  AerospikeClient_Operate_Invoke(
	AerospikeClient * self, as_error *err,
	as_key * key, PyObject * py_list, PyObject * py_meta,
	as_policy_operate * operate_policy_p)
{
	as_val* put_val = NULL;
	char* bin = NULL;
	char* val = NULL;
	long offset = 0;
    double double_offset = 0.0;
	uint32_t ttl = 0;
	long operation = 0;
	int i = 0;
	PyObject * py_rec = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_ustr1 = NULL;
	PyObject * py_bin = NULL;
	as_record * rec = NULL;

	as_static_pool static_pool;
	memset(&static_pool, 0, sizeof(static_pool));

	as_operations ops;
	Py_ssize_t size = PyList_Size(py_list);
	as_operations_inita(&ops, size);

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

	if(py_meta) {
		AerospikeClient_CheckForMeta(py_meta, &ops, err);
	}

	if (err->code != AEROSPIKE_OK) {
		goto CLEANUP;
	}

	for ( i = 0; i < size; i++) {
		PyObject * py_val = PyList_GetItem(py_list, i);
		operation = -1;
		offset = 0;
        double_offset = 0.0;
		if ( PyDict_Check(py_val) ) {
			PyObject *key_op = NULL, *value = NULL;
			PyObject * py_value = NULL;
			Py_ssize_t pos = 0;
			while (PyDict_Next(py_val, &pos, &key_op, &value)) {
				if ( ! PyString_Check(key_op) ) {
					as_error_update(err, AEROSPIKE_ERR_CLIENT, "A operation key must be a string.");
					goto CLEANUP;
				} else {
					char * name = PyString_AsString(key_op);
					if(!strcmp(name,"op") && (PyInt_Check(value) || PyLong_Check(value))) {
						operation = PyInt_AsLong(value);
					} else if (!strcmp(name, "bin")) {
						py_bin = value;
					} else if(!strcmp(name, "val")) {
						py_value = value;
					} else {
						as_error_update(err, AEROSPIKE_ERR_PARAM, "operation can contain only op, bin and val keys");
						goto CLEANUP;
					}
				}
			}

			if (py_bin) {
				if (PyUnicode_Check(py_bin)) {
					py_ustr = PyUnicode_AsUTF8String(py_bin);
					bin = PyString_AsString(py_ustr);
				} else if (PyString_Check(py_bin)) {
					bin = PyString_AsString(py_bin);
				} else {
					as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin name should be of type string");
					goto CLEANUP;
				}
			} else if (!py_bin && operation != AS_OPERATOR_TOUCH) {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin is not given");
				goto CLEANUP;
			}
			if (py_value) {
				if (check_type(self, py_value, operation, err)) {
                    goto CLEANUP;
				} else if (PyString_Check(py_value) && (operation == AS_OPERATOR_INCR)) {
                    char * incr_string = PyString_AsString(py_value);
                    int incr_value = 0, sign = 1;

                    if (strlen(incr_string) > 15) {
				        as_error_update(err, AEROSPIKE_ERR_PARAM, "Unsupported string length for increment operation");
                        goto CLEANUP;
                    }
                    if (*incr_string == '-') {
                        incr_string = incr_string + 1;
                        sign = -1;
                    } else if (*incr_string == '+') {
                        incr_string = incr_string + 1;
                        sign = 1;
                    }
                    while (*incr_string != '\0') {
                        if (*incr_string >= 48 && *incr_string <= 57) {
                            incr_value = (incr_value * 10) + (*incr_string ^ 0x30);
                        } else {
				            as_error_update(err, AEROSPIKE_ERR_PARAM, "Unsupported operand type(s) for +: 'int' and 'str'");
                            goto CLEANUP;
                        }
                        incr_string = incr_string + 1;
                    }
                    incr_value = incr_value * sign;
                    py_value = PyInt_FromLong(incr_value);
                }
			} else if ((!py_value) && (operation != AS_OPERATOR_READ)) {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Value should be given");
				goto CLEANUP;
			}

			switch(operation) {
				case AS_OPERATOR_APPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
					} else {
						val = PyString_AsString(py_value);
					}
					as_operations_add_append_str(&ops, bin, val);
					break;
				case AS_OPERATOR_PREPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
					} else {
						val = PyString_AsString(py_value);
					}
					as_operations_add_prepend_str(&ops, bin, val);
					break;
				case AS_OPERATOR_INCR:
					if (PyInt_Check(py_value)) {
                        offset = PyInt_AsLong(py_value);
                        as_operations_add_incr(&ops, bin, offset);
                    } else if ( PyLong_Check(py_value) ) {
                        offset = PyLong_AsLong(py_value);
                        if(-1 == offset) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        as_operations_add_incr(&ops, bin, offset);
                    } else if (PyFloat_Check(py_value)) {
                        double_offset = PyFloat_AsDouble(py_value);
                        as_operations_add_incr_double(&ops, bin, double_offset);
                    }
                    break;
				case AS_OPERATOR_TOUCH:
					if (PyInt_Check(py_value)) {
                        ops.ttl = PyInt_AsLong(py_value);
                    } else if ( PyLong_Check(py_value) ) {
                        ttl = PyLong_AsLong(py_value);
                        if((uint32_t)-1 == ttl) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for ttl exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        ops.ttl = ttl;
                    }
					as_operations_add_touch(&ops);
					break;
				case AS_OPERATOR_READ:
					as_operations_add_read(&ops, bin);
					break;
				case AS_OPERATOR_WRITE:
					pyobject_to_astype_write(self, err, bin, py_value, &put_val, &ops,
							&static_pool, SERIALIZER_PYTHON);
					if (err->code != AEROSPIKE_OK) {
						goto CLEANUP;
					}
					as_operations_add_write(&ops, bin, (as_bin_value *) put_val);
					break;
				default:
					as_error_update(err, AEROSPIKE_ERR_PARAM, "Invalid operation given");
			}
		}
	}

	// Initialize record
	as_record_init(rec, 0);

	aerospike_key_operate(self->as, err, operate_policy_p, key, &ops, &rec);
	if (err->code != AEROSPIKE_OK) {
		as_error_update(err, err->code, NULL);
		goto CLEANUP;
	}
	if(rec) {
		record_to_pyobject(err, rec, key, &py_rec);
	}

CLEANUP:
	if (py_ustr) {
		Py_DECREF(py_ustr);
	}
	if (py_ustr1) {
		Py_DECREF(py_ustr1);
	}
	if (rec) {
		as_record_destroy(rec);
	}
	if (key->valuep) {
		as_key_destroy(key);
	}
	if (put_val) {
		as_val_destroy(put_val);
	}

	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}

	if (py_rec) {
		return py_rec;
	} else {
		return PyLong_FromLong(0);
	}
}
Exemple #4
0
QList<PythonVariable> PythonEngine::variableList()
{
    QStringList filter_name;
    filter_name << "__builtins__" << "StdoutCatcher" << "python_engine_stdout" << "chdir"
                << "python_engine_get_completion_file" << "python_engine_get_completion_string"
                << "python_engine_get_completion_string_dot" << "PythonLabRopeProject"
                << "pythonlab_rope_project"
                << "python_engine_pyflakes_check";

    QStringList filter_type;
    filter_type << "builtin_function_or_method";

    QList<PythonVariable> list;

    PyObject *keys = PyDict_Keys(m_dict);
    for (int i = 0; i < PyList_Size(keys); ++i)
    {
        PyObject *key = PyList_GetItem(keys, i);
        PyObject *value = PyDict_GetItem(m_dict, key);

        // variable
        PythonVariable var;

        // variable name
        var.name = PyString_AsString(key);

        // variable type
        var.type = value->ob_type->tp_name;

        // variable value
        if (var.type == "bool")
        {
            var.value = PyInt_AsLong(value) ? "True" : "False";
        }
        else if (var.type == "int")
        {
            var.value = (int) PyInt_AsLong(value);
        }
        else if (var.type == "float")
        {
            var.value = PyFloat_AsDouble(value);
        }
        else if (var.type == "str")
        {
            var.value = PyString_AsString(value);
        }
        else if (var.type == "list")
        {
            var.value = QString("%1 items").arg(PyList_Size(value));
        }
        else if (var.type == "tuple")
        {
            var.value = QString("%1 items").arg(PyTuple_Size(value));
        }
        else if (var.type == "dict")
        {
            var.value = QString("%1 items").arg(PyDict_Size(value));
        }
        else if (var.type == "numpy.ndarray")
        {
            var.value = ""; //TODO count
        }
        else if (var.type == "module")
        {
            var.value = PyString_AsString(PyObject_GetAttrString(value, "__name__"));
        }
        else if (var.type == "function"
                 || var.type == "instance"
                 || var.type == "classobj")
        {
            // qDebug() << value->ob_type->tp_name;
        }

        // append
        if (!filter_name.contains(var.name) && !filter_type.contains(var.type))
        {
            list.append(var);
        }
    }
    Py_DECREF(keys);

    return list;
}
Exemple #5
0
static PyObject
*turnstile_period_search (PyObject *self, PyObject *args)
{
    int i, j;

    int nperiods;
    double min_period, max_period,  amp, var;
    PyObject *datasets;

    // Parse the input arguments.
    if (!PyArg_ParseTuple(args, "Oddidd", &datasets, &min_period,
                          &max_period, &nperiods, &amp, &var))
        return NULL;

    // Parse and extract the necessary information from the datasets.
    if (!PyList_Check(datasets)) {
        PyErr_SetString(PyExc_TypeError, "Expected a list.");
        return NULL;
    }
    int max_sets, nsets = (int)PyList_Size(datasets),
        *ndata = malloc(nsets * sizeof(int));
    double **time = malloc(nsets * sizeof(double*)),
           **flux = malloc(nsets * sizeof(double*)),
           **ferr = malloc(nsets * sizeof(double*));
    PyObject *timeobj = NULL, *fluxobj = NULL, *ferrobj = NULL;
    PyArrayObject *timearray = NULL, *fluxarray = NULL, *ferrarray = NULL;

    for (max_sets = 0; max_sets < nsets; ++max_sets) {
        // Get the dataset.
        PyObject *ds = PyList_GetItem(datasets, max_sets);
        if (ds == NULL) goto fail;

        // Access the attributes that we need.
        timeobj = PyObject_GetAttrString(ds, "time");
        fluxobj = PyObject_GetAttrString(ds, "flux");
        ferrobj = PyObject_GetAttrString(ds, "ferr");

        // Clean up properly if anything went wrong.
        if (timeobj == NULL || fluxobj == NULL || ferrobj == NULL)
            goto ds_fail;

        // Parse the objects as numpy arrays.
        timearray = PARSE_ARRAY(timeobj),
        fluxarray = PARSE_ARRAY(fluxobj),
        ferrarray = PARSE_ARRAY(ferrobj);

        // Clean up properly if anything went wrong.
        if (timearray == NULL || fluxarray == NULL || ferrarray == NULL)
            goto ds_fail;

        // Figure out the size of the dataset and allocate the needed memory.
        ndata[max_sets] = (int)PyArray_DIM(timearray, 0);
        if (PyArray_DIM(fluxarray, 0) != ndata[max_sets] ||
            PyArray_DIM(ferrarray, 0) != ndata[max_sets]) {
            PyErr_SetString(PyExc_ValueError, "Dimension mismatch.");
            goto ds_fail;
        }
        time[max_sets] = malloc(ndata[max_sets] * sizeof(double));
        flux[max_sets] = malloc(ndata[max_sets] * sizeof(double));
        ferr[max_sets] = malloc(ndata[max_sets] * sizeof(double));

        // Copy the data over.
        double *t =  PyArray_DATA(timearray),
               *f =  PyArray_DATA(fluxarray),
               *fe =  PyArray_DATA(ferrarray);
        for (i = 0; i < ndata[max_sets]; ++i) {
            time[max_sets][i] = t[i];
            flux[max_sets][i] = f[i];
            ferr[max_sets][i] = fe[i];
        }

        // Reference counting.
        Py_DECREF(timeobj);
        Py_DECREF(fluxobj);
        Py_DECREF(ferrobj);
        Py_DECREF(timearray);
        Py_DECREF(fluxarray);
        Py_DECREF(ferrarray);
    }

    int *nepochs = NULL;
    double *periods = NULL, **epochs = NULL, **depths = NULL, **dvar = NULL;
    turnstile (nsets, ndata, time, flux, ferr, amp, var,
               min_period, max_period, nperiods,
               &nepochs, &periods, &epochs, &depths, &dvar);

    // Construct the output period array.
    npy_intp d1[1] = {nperiods};
    PyObject *periodarray = PyArray_SimpleNewFromData(1, d1, NPY_DOUBLE,
                                                      periods);
    if (periodarray == NULL) {
        Py_XDECREF(periodarray);
        goto fail;
    }

    // Construct the lists of epoch, depth and depth uncertainty arrays.
    PyObject *epochlist = PyList_New(nperiods),
             *depthlist = PyList_New(nperiods),
             *dvarlist = PyList_New(nperiods);
    if (epochlist == NULL || depthlist == NULL || dvarlist == NULL) {
        Py_DECREF(periodarray);
        Py_XDECREF(epochlist);
        Py_XDECREF(depthlist);
        Py_XDECREF(dvarlist);
        goto fail;
    }
    for (i = 0; i < nperiods; ++i) {
        npy_intp dim[1] = {nepochs[i]};
        PyObject *ea = PyArray_SimpleNewFromData(1, dim, NPY_DOUBLE, epochs[i]),
                 *da = PyArray_SimpleNewFromData(1, dim, NPY_DOUBLE, depths[i]),
                 *va = PyArray_SimpleNewFromData(1, dim, NPY_DOUBLE, dvar[i]);
        if (ea == NULL || da == NULL || va == NULL) {
            Py_DECREF(periodarray);
            Py_DECREF(epochlist);
            Py_DECREF(depthlist);
            Py_DECREF(dvarlist);
            Py_XDECREF(ea);
            Py_XDECREF(da);
            Py_XDECREF(va);
            goto fail;
        }
        int info = PyList_SetItem(epochlist, i, ea)
                 + PyList_SetItem(depthlist, i, da)
                 + PyList_SetItem(dvarlist, i, va);
        if (info != 0) {
            Py_DECREF(periodarray);
            Py_DECREF(epochlist);
            Py_DECREF(depthlist);
            Py_DECREF(dvarlist);
            Py_XDECREF(ea);
            Py_XDECREF(da);
            Py_XDECREF(va);
            goto fail;
        }
    }

    return Py_BuildValue("OOOO", periodarray, epochlist, depthlist, dvarlist);

ds_fail:

    Py_XDECREF(timeobj);
    Py_XDECREF(fluxobj);
    Py_XDECREF(ferrobj);
    Py_XDECREF(timearray);
    Py_XDECREF(fluxarray);
    Py_XDECREF(ferrarray);

fail:

    for (j = 0; j < max_sets; ++j) {
        free(time[j]);
        free(flux[j]);
        free(ferr[j]);
    }
    free(time);
    free(flux);
    free(ferr);
    return NULL;
}
Exemple #6
0
int launch_py_user_action(PyVCScanvas_Object *self, 
#ifdef X11WM
			  Window window, XEvent event, 
#elif defined (QTWM)
			  QEvent event,
#endif
			  struct data_point info, 
			  int ipoint[2])
{
#ifdef X11WM
  Window parent;
#endif
  int x,y,w,h,bw,dpth;
  int line;
  PyObject *canvas, *funcs, *func, *args, *kargs, *kval;
#ifdef X11WM
  XGetGeometry(self->connect_id.display,window,&parent,&x,&y,&w,&h,&bw,&dpth) ;
#elif defined (QTWM)
  vcs_legacy_Qt_get_window_dimensions_by_id(self->connect_id.wkst_id,&x,&y,&w,&h);
#else
  fprintf(stderr,"insert here your WM getgeometry function\n");
#endif
  

  if ((x<BUTTON_X) && (BUTTON_X<x+w) && (y<BUTTON_Y) && (BUTTON_Y<y+h))
    {
      PY_ENTER_THREADS;
      PY_GRAB_THREAD;
      canvas = getPyCanvas( self->canvas_id );
      kargs = PyDict_New();
      if (info.x!=-999.)
	{
	  kval = Py_BuildValue("d",info.x);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"datawc_x",kval);
      Py_DECREF(kval);

      if (info.y!=-999.)
	{
	  kval = Py_BuildValue("d",info.y);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"datawc_y",kval);
      Py_DECREF(kval);

      if (info.value!=-999.)
	{
	  kval = Py_BuildValue("d",info.value);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"value",kval);
      Py_DECREF(kval);
      if (info.value2!=-999.)
	{
	  kval = Py_BuildValue("d",info.value2);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"value2",kval);
      Py_DECREF(kval);
      if (info.x_index!=-999)
	{
	  kval = Py_BuildValue("i",info.x_index);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"index_x",kval);
      Py_DECREF(kval);
      if (info.y_index!=-999)
	{
	  kval = Py_BuildValue("i",info.y_index);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"index_y",kval);
      Py_DECREF(kval);
      if (info.color!=-999.)
	{
	  kval = Py_BuildValue("i",info.color);
	}
      else
	{
	  Py_INCREF(Py_None);
	  kval = Py_None;
	}
      PyDict_SetItemString(kargs,"color",kval);
      Py_DECREF(kval);
      
      kval = Py_BuildValue("i",ipoint[0]);
      PyDict_SetItemString(kargs,"XW_x",kval);
      Py_DECREF(kval);

      kval = Py_BuildValue("i",ipoint[1]);
      PyDict_SetItemString(kargs,"XW_y",kval);
      Py_DECREF(kval);

      PyDict_SetItemString(kargs,"canvas",canvas);
      
      funcs = PyObject_GetAttrString(canvas,"user_actions_names");
      if (PyList_Check(funcs)) 
	{
	  line = (BUTTON_Y-y)*PyList_Size(funcs)/h;
	}
      else line=1;
      Py_DECREF(funcs);      
      /* Set the line number as argument */
      args = Py_BuildValue("()",line);

      /* following is for direct call of func */
      funcs = PyObject_GetAttrString(canvas,"user_actions"); /* decref ? */
      if (PyList_Check(funcs))
	{
	  func = PyList_GetItem(funcs,line);
	  if (PyCallable_Check(func))
	    {
	      PY_RELEASE_THREAD;
	      PY_LEAVE_THREADS;
	      PY_ENTER_THREADS;
	      PY_GRAB_THREAD;
	      kval = PyEval_CallObjectWithKeywords(func,args,kargs);
	      Py_DECREF(kargs);
	      Py_DECREF(args);
	      Py_XDECREF(kval);
	      PY_RELEASE_THREAD;
	      PY_LEAVE_THREADS;
	    }
	  else
	    {
	      PY_RELEASE_THREAD
		PY_LEAVE_THREADS
	      return 1;
	    }
	}
      else {
static PyObject* selNSGA2(PyObject *self, PyObject *args){
    /* Args[0] : Individual list
     * Args[1] : Number of individuals wanted in output
     * Return : k selected individuals from input individual list
     */
    PyObject *lListIndv = PyTuple_GetItem(args, 0);
#ifdef PY3K
    unsigned long k = (unsigned long)PyLong_AS_LONG(PyTuple_GetItem(args, 1));
#else
    unsigned int k = (unsigned int)PyInt_AS_LONG(PyTuple_GetItem(args, 1));
#endif
    
    PyObject *lListSelect = PyList_New(0);
    
    unsigned int lLenListIndv = (unsigned int)PyList_Size(lListIndv);
    unsigned int lNbrObjectives = (unsigned int)PyTuple_Size(PyObject_GetAttrString(PyObject_GetAttrString(PyList_GetItem(lListIndv,0), "fitness"), "values"));
    
    if(k == 0)
        return lListSelect;
    
    // First : copy fitness values into an std::vector<std::vector<double> >
    // First vector index is used to identify individuals
    // Second vector index represents an objective
    std::vector<std::vector<double> > lPopFit(lLenListIndv, std::vector<double>(lNbrObjectives,0.));
    for(unsigned int i = 0; i < lLenListIndv; i++){
        for(unsigned int j = 0; j < lNbrObjectives; j++)
            lPopFit[i][j] = PyFloat_AS_DOUBLE(PyTuple_GetItem(PyObject_GetAttrString(PyObject_GetAttrString(PyList_GetItem(lListIndv,i), "fitness"), "wvalues"), j));
    }
    
    
    unsigned int lParetoSorted = 0;
    unsigned int lFrontIndex = 0;
    std::vector<std::vector<unsigned int> > lParetoFront(1, std::vector<unsigned int>(0));
    std::vector<unsigned int> lDominating(lLenListIndv, 0);
    std::vector<std::vector<unsigned int> > lDominatedInds(lLenListIndv, std::vector<unsigned int>(0));
    
    // Rank first pareto front
    for(unsigned int i = 0; i < lLenListIndv; i++){
        for(unsigned int j = i+1; j < lLenListIndv; j++){
            
            if(isDominated(lPopFit[j], lPopFit[i])){
                lDominating[j]++;
                lDominatedInds[i].push_back(j);
            }
            else if(isDominated(lPopFit[i], lPopFit[j])){
                lDominating[i]++;
                lDominatedInds[j].push_back(i);
            }
        }
        if(lDominating[i] == 0){
            lParetoFront[lFrontIndex].push_back(i);
            lParetoSorted++;
        }
    }

    // Rank other pareto fronts, until we reach the *k* limit
    while(lParetoSorted < k && lParetoSorted < lLenListIndv){
        lFrontIndex++;
        lParetoFront.push_back(std::vector<unsigned int>(0));
        for(unsigned int i = 0; i < lParetoFront[lFrontIndex-1].size(); i++){
            unsigned int lIndiceP = lParetoFront[lFrontIndex-1][i];
            for(unsigned int j = 0; j < lDominatedInds[lIndiceP].size(); j++){
                unsigned int lIndiceD = lDominatedInds[lIndiceP][j];
                if(--lDominating[lIndiceD] == 0){
                    lParetoFront[lFrontIndex].push_back(lIndiceD);
                    lParetoSorted++;
                }
            }
        }
    }
    
    // Append individuals from pareto ranking until we reach the limit
    for(unsigned int i = 0; i < lParetoFront.size(); i++){
        if(PyList_Size(lListSelect)+lParetoFront[i].size() <= k){
            for(unsigned int j = 0; j < lParetoFront[i].size(); j++)
                PyList_Append(lListSelect, PyList_GetItem(lListIndv,lParetoFront[i][j]));
        }
        else{
            break;
        }
    }

    // Crowding distance on the last front
    if(PyList_Size(lListSelect) == k)
        return lListSelect;
    
    FitComp lCmpIndvObj;
    std::vector<unsigned int> lLastParetoFront = lParetoFront.back();
    std::vector<std::pair<double, unsigned int> > lDistances(0);
    std::vector<std::pair<std::vector<double>, unsigned int> > lCrowdingList(0);
    double lInfinity = std::numeric_limits<double>::infinity();
    
    // Reserve sufficient memory for the subsequent push_back
    lDistances.reserve(lLastParetoFront.size());
    lCrowdingList.reserve(lLastParetoFront.size());
    
    for(unsigned int i = 0; i < lLastParetoFront.size(); i++){
        // Push initial distance (0.0) and individual index in lPopFit and lListIndv for each individual
        lDistances.push_back(std::pair<double, unsigned int>(0., lLastParetoFront[i]));
        
        // Push fitness and individual index in lDistances for each individual
        lCrowdingList.push_back(std::pair<std::vector<double>, unsigned int>(lPopFit[lLastParetoFront[i]],i));
    }
    
    for(unsigned int i = 0; i < lNbrObjectives; i++){
        // For each objective
        // Set the current objective in the comparison class
        lCmpIndvObj.mCompIndex = i;
        // Sort (stable, in order to keep the same order for equal fitness values)
        stable_sort(lCrowdingList.begin(), lCrowdingList.end(), lCmpIndvObj);
        
        // Set an infinite distance to the extremums
        lDistances[lCrowdingList[0].second].first = lInfinity;
        lDistances[lCrowdingList.back().second].first = lInfinity;

        for(unsigned int j = 1; j < lCrowdingList.size()-1; j++){
            if(lDistances[lCrowdingList[j].second].first < lInfinity)
                lDistances[lCrowdingList[j].second].first += lCrowdingList[j+1].first[i]-lCrowdingList[j-1].first[i];
        }
    }
    
    // Final sorting (again, must be stable)
    stable_sort(lDistances.begin(), lDistances.end(), crowdDistComp);
   
    // Pick the last individuals (with the higher crowding distance) first
    for(unsigned int i = lDistances.size()-1; i >= 0; i--){
        if(PyList_Size(lListSelect) >= k)
            break;
        // While the size of the return list is lesser than *k*, append the next individual
        PyList_Append(lListSelect, PyList_GetItem(lListIndv,lDistances[i].second));  
    }
    
    return lListSelect;
}
Exemple #8
0
/*
 * HTML starttag builder
 */
PyObject *
tdi_soup_encode_starttag(tdi_node_t *node)
{
    PyObject *result, *attr;
    tdi_attr_t *item;
    char *cresult;
    Py_ssize_t j, length, size;

    /* 1st pass: count result bytes */
    size = PyString_GET_SIZE(node->tagname) + 2;  /* <> */
    if (node->flags & NODE_CLOSED)
        size += 2;  /* ' /' */

    if (!(attr = PyDict_Values(node->attr)))
        return NULL;
    length = PyList_GET_SIZE(attr);
    for (j = 0; j < length; ++j) {
        if (!(item = (tdi_attr_t *)PyList_GetItem(attr, j))) {
            Py_DECREF(attr);
            return NULL;
        }
        if (item->value == Py_None)
            size += PyString_GET_SIZE(item->key) + 1;  /* ' ' */
        else
            size += PyString_GET_SIZE(item->key)
                + PyString_GET_SIZE(item->value) + 2;  /* ' =' */
    }

    /* 2nd pass: assemble result */
    if (!(result = PyString_FromStringAndSize(NULL, size))) {
        Py_DECREF(attr);
        return NULL;
    }
    cresult = PyString_AS_STRING(result);
    *cresult++ = '<';

    size = PyString_GET_SIZE(node->tagname);
    (void)memcpy(cresult, PyString_AS_STRING(node->tagname), (size_t)size);
    cresult += size;

    for (j = 0; j < length; ++j) {
        if (!(item = (tdi_attr_t *)PyList_GetItem(attr, j))) {
            Py_DECREF(result);
            Py_DECREF(attr);
            return NULL;
        }

        *cresult++ = ' ';

        size = PyString_GET_SIZE(item->key);
        (void)memcpy(cresult, PyString_AS_STRING(item->key), (size_t)size);
        cresult += size;

        if (item->value != Py_None) {
            *cresult++ = '=';
            size = PyString_GET_SIZE(item->value);
            (void)memcpy(cresult, PyString_AS_STRING(item->value),
                         (size_t)size);
            cresult += size;
        }
    }
    Py_DECREF(attr);

    if (node->flags & NODE_CLOSED) {
        *cresult++ = ' ';
        *cresult++ = '/';
    }
    *cresult = '>';

    return result;
}
/**
 * need not gain GIL
 */
int network_mysqld_python_initialize(chassis_plugin_config *config){
    PyObject *path = PySys_GetObject("path");

    if(!config->python_script){
		g_message("No avalible python script.");
		return 0;
	}

	if(init_python_types()){
		PyErr_Print();
		PyErr_Clear();
		return -1;
	}

    PyObject *script = PyString_FromString(config->python_script);
    PyObject *split_path = PyObject_CallMethod(script, "rsplit", "si", "/", 1);
    Py_DECREF(script);

    Py_ssize_t length = PyList_GET_SIZE(split_path);
    assert(length == 2);
    PyList_Append(path, PyList_GetItem(split_path, 0));

	// Add current dir to sys.path.
	char path_buf[MAX_PATH_LENGTH];
	char* result = getcwd(path_buf, MAX_PATH_LENGTH);
	if(result){
		PyObject *curr_path = PyString_FromString(path_buf);
		PyList_Append(path, curr_path);
		Py_DECREF(curr_path);
	}
	else{
		Py_DECREF(split_path);
		g_critical("Script file path is too long! Max length is %d\n",
					MAX_PATH_LENGTH);
		return -1;
	}

	//Now load the script
	PyObject *file_name = PyList_GetItem(split_path, length - 1);
	PyObject *split_file_name= PyObject_CallMethod(file_name, "split",
				"si", ".", 1);
	PyObject *mod_name = PyList_GetItem(split_file_name, 0);
	PyObject *script_mod = PyImport_Import(mod_name);

	if(!script_mod){
		PyObject *exc_type = PyErr_Occurred();
		if(exc_type){
			PyErr_Print();
			PyErr_Clear();
		}
		else
			g_critical("Unknown error occurred while importing script %s\n",
						PyString_AsString(mod_name));
		Py_DECREF(split_file_name);
		Py_DECREF(split_path);
		return -1;
	}
	config->proxy_funcs = g_new0(pyproxy_functions, 1);
	if(!config->proxy_funcs){
		g_critical("No memory avaible for alloc proxy functions!\n");
		Py_DECREF(script_mod);
		Py_DECREF(split_file_name);
		Py_DECREF(split_path);
		return -1;
	}

	//Load the script hook function to config->proxy_methods.
#define LOAD_FUNC(func) \
	config->proxy_funcs->func = NULL;\
	if(PyObject_HasAttrString(script_mod, #func)){\
		PyObject *fun = PyObject_GetAttrString(script_mod, #func);\
		if(PyCallable_Check(fun)){\
			config->proxy_funcs->func = fun;\
		}\
		else{\
			PyObject *func_name = PyObject_Str(mod_name);\
			g_message("Load %s.%s failed: object %s is not callable!\n", \
				PyString_AsString(func_name), #func, #func);\
			Py_DECREF(func_name);\
		}\
	}

	LOAD_FUNC(init)
	LOAD_FUNC(connect_server)
	LOAD_FUNC(read_handshake)
	LOAD_FUNC(read_auth)
	LOAD_FUNC(read_auth_result)
	LOAD_FUNC(read_query)
	LOAD_FUNC(read_query_result)
	LOAD_FUNC(disconnect_client)

	Py_DECREF(script_mod);
	Py_DECREF(split_file_name);

    Py_DECREF(split_path);
	return 0;
}
Exemple #10
0
static int
my_action(void *new_ps, void **children, int n_children, int pn_offset,
	  struct D_Parser *parser, int speculative) {
  D_ParseNode *dd = D_PN(new_ps, pn_offset);
  PyObject *result = NULL;
  PyObject *children_list, *string_list = NULL;
  PNode *pn = (PNode *)new_ps;
  int action_index = pn->reduction->action_index;
  PyObject *tuple = NULL;
  PyObject *arg_types = NULL;
  D_ParserPyInterface *ppi = d_interface(parser);
  int takes_speculative = 0;
  PyObject *action = 0;

  if (PyErr_Occurred()) {
    /* just keep returning until finished parsing.  Need a way to tell dparser to quit */
    return 0;
  }

  if (action_index != -1) {
    tuple = PyList_GetItem(ppi->actions, action_index);
    PyArg_ParseTuple(tuple, "OOi", &action, &arg_types, &takes_speculative);
  }
  
  if (ppi->takes_globals) {
    inc_global_state(parser, dd);
  }

  if (ppi->print_debug_info && tuple) {
    print_debug_info(dd, tuple, speculative, ppi->print_debug_info);
  }

  if (takes_speculative == -1 && !speculative) {
    /* user.t and user.s were already set when this was called speculatively */
    return 0;
  }

  if (ppi->takes_strings) {
    string_list = pylist_children(parser, dd, 1);
    if (string_list == NULL) {
      return -1;
    }
  }
  /* this function owns string_list */

  if (takes_speculative == 0 && speculative) {
    Py_INCREF(Py_None);
    Py_XDECREF(dd->user.t);
    /*    if (dd->user.s)
	  printf("freeing2:%d\n", dd->user.s);*/
    Py_XDECREF(dd->user.s);
    dd->user.t = Py_None;
    //    printf("dd1:%d\n", dd);
    dd->user.s = NULL;
    Py_XDECREF(string_list);
    /*    printf("setting:%d\n", string_list);*/
    //dd->user.s = string_list;

    return 0;
  }

  children_list = pylist_children(parser, dd, 0);
  if (children_list == NULL) {
    /*    if (string_list)
	  printf("freeing3:%d\n", string_list);*/

      Py_XDECREF(string_list);
      return -1;
  }
  /* this function owns children_list */

  if (action_index != -1) {
    result = take_action(arg_types, children_list, speculative, dd, string_list, 
			 n_children, parser, children, pn_offset, action);
    Py_DECREF(children_list);
  } else {
    result = children_list;
  }
  /* function now owns result, string_list */

  if (result == ppi->reject || result == NULL) {
    /*    if (string_list)
	  printf("freeing4:%d\n", string_list);*/

    Py_XDECREF(result);
    Py_XDECREF(string_list);
    return -1;  /* user rejected */
  }

  Py_XDECREF(dd->user.t); /* these may have been set in a speculative pass */
  /*  if(dd->user.s)
      printf("freeing5:%d\n", dd->user.s);*/
  Py_XDECREF(dd->user.s);
  /*  if(dd->user.s)
      printf("setting2:%d\n", string_list);*/
  //  printf("dd2:%d\n", dd);
  dd->user.t = result;
  dd->user.s = string_list;  

  return 0;
}
Exemple #11
0
static
PyObject* ccmapninfo(PyObject *xyz_data,PyObject *ninfo_data)
{
  int i,j;
  PyObject *xyz_item1,*xyz_item2,*ninfo_item,*out_list,*out_list2;
  long ninfo_max=PyList_Size(ninfo_data);
    
  long icon,jcon;
  double nlength;
  double nowcontact=0.0,nowlength=0.0;
  long max=PyList_Size(xyz_data);
  out_list=PyList_New(max);
  long d2_list[max][max];
    
  for(i=0;i<max;i++){
    for(j=0;j<max;j++){
      d2_list[j][i]=0;
    }
  }
  for(i=0;i<ninfo_max;i++){
    ninfo_item=PyList_GetItem(ninfo_data,i);
    icon=PyInt_AsLong(PyList_GetItem(ninfo_item,0));
    jcon=PyInt_AsLong(PyList_GetItem(ninfo_item,1));
    nlength=PyFloat_AsDouble(PyList_GetItem(ninfo_item,2));
    xyz_item1=PyList_GetItem(xyz_data,icon-1);
    xyz_item2=PyList_GetItem(xyz_data,jcon-1);
    nowlength=clength(PyFloat_AsDouble(PyList_GetItem(xyz_item1,0)),
                      PyFloat_AsDouble(PyList_GetItem(xyz_item1,1)),
                      PyFloat_AsDouble(PyList_GetItem(xyz_item1,2)),
                      PyFloat_AsDouble(PyList_GetItem(xyz_item2,0)),
                      PyFloat_AsDouble(PyList_GetItem(xyz_item2,1)),
                      PyFloat_AsDouble(PyList_GetItem(xyz_item2,2)));
    if(nowlength<nlength*1.2){
      d2_list[icon-1][jcon-1]=1;
      d2_list[jcon-1][icon-1]=1;
    }
  }
  for(i=0;i<max;i++){
    out_list2=PyList_New(max);
    for(j=0;j<max;j++){
      PyList_SetItem(out_list2,j,PyInt_FromLong(d2_list[i][j]));
    }
    PyList_SetItem(out_list,i,out_list2);
  }

  return out_list;
}
Exemple #12
0
static PyObject*
take_action(PyObject *arg_types, PyObject *children_list, int speculative, 
	    D_ParseNode *dd, PyObject *string_list, int n_children, 
	    struct D_Parser *parser, void **children, int pn_offset,
	    PyObject *action) {
  int i;
  int arg_count = PyList_Size(arg_types);
  D_ParserPyInterface *ppi = d_interface(parser);
  PyObject *arglist = PyTuple_New(arg_count);
  PyObject *globals_holder = NULL;
  PyObject *result = NULL;

  Py_INCREF(children_list);
  PyTuple_SetItem(arglist, 0, children_list);
  for (i=1; i<arg_count; i++) {
    PyObject *item = PyList_GetItem(arg_types, i);
    int type = PyInt_AsLong(item);
    if (type == 1) {
      PyTuple_SetItem(arglist, i, Py_BuildValue("i", speculative));
    }
    else if (type == 2) {
      if (!dd->user.inced_global_state) {
	dd->user.inced_global_state = 1;
      }
      globals_holder = PyList_New(1);
      Py_INCREF(dd->globals);
      PyList_SetItem(globals_holder, 0, dd->globals);
      PyTuple_SetItem(arglist, i, globals_holder);
    }
    else if (type == 3) {
      Py_INCREF(string_list);
      PyTuple_SetItem(arglist, i, string_list);
    }
    else if (type == 4) {
      PyObject* nodes = PyList_New(n_children);
      int j;
      for (j=0; j<n_children; j++) {
	PyList_SetItem(nodes, j, make_py_node(parser, D_PN(children[j], pn_offset)));
      }
      PyTuple_SetItem(arglist, i, nodes);
    }
    else if (type == 5) {
      PyTuple_SetItem(arglist, i, make_py_node(parser, dd));
    }
    else if (type == 6) {
      Py_INCREF(Py_None);
      PyTuple_SetItem(arglist, i, Py_None);
    }
    else if (type == 7) {
      Py_INCREF(ppi->self);
      PyTuple_SetItem(arglist, i, ppi->self);
    }
  }
  result = PyEval_CallObject(action, arglist);
  if (globals_holder) {
    Py_DECREF(dd->globals);
    dd->globals = PyList_GetItem(globals_holder, 0);
    Py_INCREF(dd->globals);
  }
  Py_DECREF(arglist);
  return result;
}
Exemple #13
0
PyObject * convert_datablock( DATABLOCK * datablock )
{
    PyObject * current_datablock = PyDict_New();
    PyDict_PutString( current_datablock, "name",
                      datablock_name( datablock ) );

    size_t length = datablock_length( datablock );
    char **tags   = datablock_tags( datablock );
    ssize_t * value_lengths = datablock_value_lengths( datablock );
    char ***values = datablock_values( datablock );
    int *inloop   = datablock_in_loop( datablock );
    int  loop_count = datablock_loop_count( datablock );
    datablock_value_type_t **types = datablock_types( datablock );

    PyObject * taglist    = PyList_New(0);
    PyObject * valuehash  = PyDict_New();
    PyObject * loopid     = PyDict_New();
    PyObject * loops      = PyList_New(0);
    PyObject * typehash   = PyDict_New();
    PyObject * saveframes = PyList_New(0);

    size_t i;
    ssize_t j;
    for( i = 0; i < loop_count; i++ ) {
        PyObject * loop = PyList_New(0);
        PyList_Append( loops, loop );
    }

    for( i = 0; i < length; i++ ) {
        PyList_Append( taglist, PyString_FromString( tags[i] ) );

        PyObject * tagvalues  = PyList_New(0);
        PyObject * typevalues = PyList_New(0);
        PyObject * type;
        for( j = 0; j < value_lengths[i]; j++ ) {
            PyList_Append( tagvalues, PyString_FromString( values[i][j] ) );
            switch ( types[i][j] ) {
                case DBLK_INT :
                    type = PyString_FromString( "INT" ); break;
                case DBLK_FLOAT :
                    type = PyString_FromString( "FLOAT" ); break;
                case DBLK_SQSTRING :
                    type = PyString_FromString( "SQSTRING" ); break;
                case DBLK_DQSTRING :
                    type = PyString_FromString( "DQSTRING" ); break;
                case DBLK_UQSTRING :
                    type = PyString_FromString( "UQSTRING" ); break;
                case DBLK_TEXT :
                    type = PyString_FromString( "TEXTFIELD" ); break;
                default :
                    type = PyString_FromString( "UNKNOWN" );
            }
            PyList_Append( typevalues, type );
        }
        PyDict_SetItemString( valuehash, tags[i], tagvalues );
        PyDict_SetItemString( typehash, tags[i], typevalues );

        if( inloop[i] != -1 ) {
            PyDict_SetItemString( loopid, tags[i], PyInt_FromLong( inloop[i] ) );
            PyObject * current_loop = PyList_GetItem( loops, inloop[i] );
            PyList_Append( current_loop, PyString_FromString( tags[i] ) );
        }
    }

    DATABLOCK * saveframe;
    foreach_datablock( saveframe,
                       datablock_save_frame_list( datablock ) ) {
        PyList_Append( saveframes,
                       convert_datablock( saveframe ) );
    }
static PyObject *echoprint_py_inverted_index_create_block(
  PyObject *self, PyObject *args)
{
  // input is a list of lists, each item of the outer list being a
  // song (list of codes); second argument is the output path

  PyObject *arg_songs, *arg_output_path;
  int n, m, n_songs, error_parsing_input, error_writing_blocks;
  char *path_out;
  uint32_t **block_songs_codes;
  uint32_t *block_song_lengths;

  if(!PyArg_ParseTuple(args, "OS", &arg_songs, &arg_output_path))
    return NULL;

  error_parsing_input = 0;
  if(!PyList_Check(arg_songs))
  {
    PyErr_SetString(
      PyExc_TypeError, "first argument must be a list (of lists of codes)");
    return NULL;
  }

  path_out = PyString_AsString(arg_output_path);
  n_songs = PyList_Size(arg_songs);

  block_song_lengths = (uint32_t*) malloc(sizeof(uint32_t) * n_songs);
  block_songs_codes = (uint32_t **) malloc(sizeof(uint32_t *) * n_songs);

  for(n = 0; n < n_songs; n++)
    block_songs_codes[n] = 0;
  for(n = 0; n < n_songs; n++)
  {
    if(error_parsing_input)
      break;
    else
    {
      PyObject * py_song_seq = PySequence_GetItem(arg_songs, n);
      uint32_t song_length = PyList_Size(py_song_seq);
      block_songs_codes[n] = (uint32_t *) malloc(
	sizeof(uint32_t) * song_length);
      for(m = 0; m < song_length; m++)
      {
	PyObject *code = PyList_GetItem(py_song_seq, m);
	if(!PyInt_Check(code))
	{
	  PyErr_SetString(
	    PyExc_TypeError, "all codes in input songs must be integers");
	  error_parsing_input = 1;
	  break;
	}
	else
	  block_songs_codes[n][m] = (uint32_t) PyInt_AsLong(code);
      }
      block_song_lengths[n] = song_length;
      Py_DECREF(py_song_seq);
    }
  }

  error_writing_blocks = 0;
  if(!error_parsing_input)
  {
    if(echoprint_inverted_index_build_write_block(
	 block_songs_codes, block_song_lengths, n_songs, path_out, 0))
    {
      error_writing_blocks = 1;
      PyErr_SetString(PyExc_TypeError, "could not write the index block");
    }
  }

  for(n = 0; n < n_songs; n++)
    if(block_songs_codes[n] != 0)
      free(block_songs_codes[n]);
  free(block_songs_codes);
  free(block_song_lengths);

  if(error_parsing_input || error_writing_blocks)
    return NULL;

  return Py_None;

}
Exemple #15
0
static PyObject *
_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
{
    Py_ssize_t i;
    PyObject *binary;
    PyObject *v;
    Py_ssize_t npath;
    size_t taillen;
    PyObject *syspath;
    PyObject *path;
    const char* tail;
    PyObject *filebytes;
    const char* filepath;
    Py_ssize_t len;
    PyObject* result;

    filebytes = PyUnicode_EncodeFSDefault(filename);
    if (filebytes == NULL) {
        PyErr_Clear();
        return NULL;
    }
    filepath = PyBytes_AS_STRING(filebytes);

    /* Search tail of filename in sys.path before giving up */
    tail = strrchr(filepath, SEP);
    if (tail == NULL)
        tail = filepath;
    else
        tail++;
    taillen = strlen(tail);

    syspath = _PySys_GetObjectId(&PyId_path);
    if (syspath == NULL || !PyList_Check(syspath))
        goto error;
    npath = PyList_Size(syspath);

    for (i = 0; i < npath; i++) {
        v = PyList_GetItem(syspath, i);
        if (v == NULL) {
            PyErr_Clear();
            break;
        }
        if (!PyUnicode_Check(v))
            continue;
        path = PyUnicode_EncodeFSDefault(v);
        if (path == NULL) {
            PyErr_Clear();
            continue;
        }
        len = PyBytes_GET_SIZE(path);
        if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) {
            Py_DECREF(path);
            continue; /* Too long */
        }
        strcpy(namebuf, PyBytes_AS_STRING(path));
        Py_DECREF(path);
        if (strlen(namebuf) != (size_t)len)
            continue; /* v contains '\0' */
        if (len > 0 && namebuf[len-1] != SEP)
            namebuf[len++] = SEP;
        strcpy(namebuf+len, tail);

        binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb");
        if (binary != NULL) {
            result = binary;
            goto finally;
        }
        PyErr_Clear();
    }
    goto error;

error:
    result = NULL;
finally:
    Py_DECREF(filebytes);
    return result;
}
Exemple #16
0
static PyObject *wrap_rtdb_put(PyObject *self, PyObject *args)
{
    int i, list, list_len;
    int ma_type = -1;
    char *name;
    Integer* int_array;
    double *dbl_array;
    char *char_array;
    char cbuf[8192], *ptr;
    void *array = 0;
    PyObject *obj;

     if ((PyTuple_Size(args) == 2) ) {
      PyArg_ParseTuple(args, "sO", &name,&obj);
      

      if (PyList_Check(obj)) 
        list = 1; 
      else 
        list = 0;
      
      if (list) {
        list_len = PyList_Size(obj);
        if (   PyInt_Check(PyList_GetItem(obj, 0)))  
          ma_type = MT_F_INT;
        else if ( PyFloat_Check(PyList_GetItem(obj, 0)))  
          ma_type = MT_F_DBL;
        else if (PyString_Check(PyList_GetItem(obj, 0))) 
          ma_type = MT_CHAR;
        else {
          printf("ERROR A\n");
          ma_type = -1;
        }
      } else {
        list_len = 1;
        if (   PyInt_Check(obj))  
          ma_type = MT_F_INT;
        else if ( PyFloat_Check(obj))  
          ma_type = MT_F_DBL;
        else if (PyString_Check(obj))  
          ma_type = MT_CHAR; 
        else {
          printf("ERROR B\n");
          ma_type = -1;
        }
      } 

      if (ma_type == -1) {
          PyErr_SetString(PyExc_TypeError, 
                          "Usage: rtdb_put - ma_type is confused");
          return NULL;
      }
      
     
      if (ma_type != MT_CHAR) {
        if (!(array = malloc(MA_sizeof(ma_type, list_len, MT_CHAR)))) {
          PyErr_SetString(PyExc_MemoryError,
                          "rtdb_put failed allocating work array");
          return NULL;
        }
      }
      
      switch (ma_type) {
      case MT_INT:
      case MT_F_INT:  
      case MT_BASE + 11:        /* Logical */
        int_array = array;
        for (i = 0; i < list_len; i++) {
          if (list) 
            int_array[i] = PyInt_AS_LONG(PyList_GetItem(obj, i));
          else 
            int_array[i] = PyInt_AS_LONG(obj);
        }
        break;
        
      case MT_DBL:  
      case MT_F_DBL:
        dbl_array = array;
        for (i = 0; i < list_len; i++) {
          if (list) 
            PyArg_ParseTuple(PyList_GetItem(obj, i), "d", dbl_array+i);
          else 
            PyArg_ParseTuple(obj, "d", dbl_array+i);
        }
        break;
        
      case MT_CHAR: 
        ptr = cbuf;
        *ptr = 0;
        for (i = 0; i < list_len; i++) {
          if (list) 
            PyArg_ParseTuple(PyList_GetItem(obj, i), "s", &char_array); 
          else 
            PyArg_ParseTuple(obj, "s", &char_array); 
          /*printf("PROCESSED '%s'\n", char_array);*/
          if ((ptr+strlen(char_array)) >= (cbuf+sizeof(cbuf))) {
             PyErr_SetString(PyExc_MemoryError,"rtdb_put too many strings");
             return NULL;
           }
          strcpy(ptr,char_array);
          ptr = ptr+strlen(char_array);
          strcpy(ptr,"\n");
          ptr = ptr + 1;
        }                
        list_len = strlen(cbuf) + 1;
        array = cbuf;
        break;
        
      default:
        PyErr_SetString(NwchemError, "rtdb_put: ma_type is incorrect");
        if (array) free(array);
        return NULL;
        break;
      }                
      
      if (!(rtdb_seq_put(rtdb_handle, name, ma_type, list_len, array))) {
        PyErr_SetString(NwchemError, "rtdb_seq_put failed");
        if ((ma_type != MT_CHAR) && array) free(array);
        return NULL;
      }
      
    } else {
      PyErr_SetString(PyExc_TypeError, 
                      "Usage: rtdb_put(value or values,[optional type])");
      if ((ma_type != MT_CHAR) && array) free(array);
      return NULL;
    }
    Py_INCREF(Py_None);
    if ((ma_type != MT_CHAR) && array) free(array);
    return Py_None;
   Py_RETURN_NONE;
}
Exemple #17
0
static long _adbobj_trace_skip(AdbObject *self, PyFrameObject *frame)
{
    unsigned long ignoreSize;
    int result;
    unsigned int i;
    PyObject *__obj;

#ifdef DEBUG_PRINT
    fprintf(stderr, "_adbobj_trace_skip...\n");
#endif
    // super debugger.  If we need to debug the debugger, then this var
    // gets set, and we never skip a frame
    if (PyInt_AsLong(__adb_debugAll) != 0) {
        return 0;
    }

    // if no frame or line number we skip the frame
    if (frame == NULL || frame->f_lineno == 0) {
        return 1;
    }

    // if this frame is explicitly hidden, skip it
    if (PyDict_GetItemString(frame->f_globals,"DBGPHide") != NULL) {
        return 1;
    }
    
    // if the module this frame is in is in our ignore list, the skip it
    /*
      if self._ignoreModules and \
        frame.f_globals.has_key('__name__') and \
        frame.f_globals['__name__'] in self._ignoreModules:
        return 1;
    */
    ignoreSize = PyList_Size(__adb_ignoreModules);
    if (ignoreSize > 0) {
        __obj = PyDict_GetItemString(frame->f_globals,"__name__");
        if (__obj != NULL) {
            for (i=0; i < ignoreSize; i++) {
                PyObject *item = PyList_GetItem(__adb_ignoreModules, i);
                if (item != NULL && PyString_Check(item) &&
                    PyObject_Cmp(__obj, item, &result) != -1 &&
                    result == 0) {
                        return 1;
                }
            }
        }
    }

    /*
        if frame and frame.f_back and frame.f_back.f_globals.has_key('DBGPHideChildren'):
            frame.f_globals['DBGPHideChildren'] = frame.f_back.f_globals['DBGPHideChildren']
    */
    if (frame->f_back) {
        __obj = PyDict_GetItemString(frame->f_back->f_globals,"DBGPHideChildren");
        if (__obj != NULL && PyInt_Check(__obj)) {
            PyDict_SetItemString(frame->f_globals,"DBGPHideChildren", __obj);
            return PyInt_AsLong(__obj);
        }
    }
    
    // now we have to look through the frame stack, and see if this is
    // a frame we need to ignore, because it is a child of a frame that .
    // we want to bypass (eg. stdout redirection in the dbgp module).
    // this is a bit of a perf hit, but that is prevented somewhat by the
    // block above.  see _pyclient.py trace_skip for some comments or refer
    // to bugs 35933 and 44620
    while (frame != NULL) {
        __obj = PyDict_GetItemString(frame->f_globals,"DBGPHideChildren");
        if (__obj != NULL && PyInt_Check(__obj) && PyInt_AsLong(__obj) != 0) {
            return PyInt_AsLong(__obj);
        }
        frame = frame->f_back;
    }
    return 0;
}
static
struct bt_plugin *bt_plugin_from_python_plugin_info(PyObject *plugin_info)
{
	struct bt_plugin *plugin = NULL;
	PyObject *py_name = NULL;
	PyObject *py_author = NULL;
	PyObject *py_description = NULL;
	PyObject *py_license = NULL;
	PyObject *py_version = NULL;
	PyObject *py_comp_class_addrs = NULL;
	const char *name = NULL;
	const char *author = NULL;
	const char *description = NULL;
	const char *license = NULL;
	unsigned int major = 0, minor = 0, patch = 0;
	const char *version_extra = NULL;
	int ret;

	assert(plugin_info);
	assert(python_state == PYTHON_STATE_FULLY_INITIALIZED);
	py_name = PyObject_GetAttrString(plugin_info, "name");
	if (!py_name) {
		BT_LOGW("Cannot find `name` attribute in Python plugin info object: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	py_author = PyObject_GetAttrString(plugin_info, "author");
	if (!py_author) {
		BT_LOGW("Cannot find `author` attribute in Python plugin info object: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	py_description = PyObject_GetAttrString(plugin_info, "description");
	if (!py_description) {
		BT_LOGW("Cannot find `desciption` attribute in Python plugin info object: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	py_license = PyObject_GetAttrString(plugin_info, "license");
	if (!py_license) {
		BT_LOGW("Cannot find `license` attribute in Python plugin info object: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	py_version = PyObject_GetAttrString(plugin_info, "version");
	if (!py_version) {
		BT_LOGW("Cannot find `version` attribute in Python plugin info object: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	py_comp_class_addrs = PyObject_GetAttrString(plugin_info,
		"comp_class_addrs");
	if (!py_comp_class_addrs) {
		BT_LOGW("Cannot find `comp_class_addrs` attribute in Python plugin info object: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	if (PyUnicode_Check(py_name)) {
		name = PyUnicode_AsUTF8(py_name);
		if (!name) {
			BT_LOGW("Cannot decode Python plugin name string: "
				"py-plugin-info-addr=%p", plugin_info);
			goto error;
		}
	} else {
		/* Plugin name is mandatory */
		BT_LOGW("Plugin name is not a string: "
			"py-plugin-info-addr=%p", plugin_info);
		goto error;
	}

	if (PyUnicode_Check(py_author)) {
		author = PyUnicode_AsUTF8(py_author);
		if (!author) {
			BT_LOGW("Cannot decode Python plugin author string: "
				"py-plugin-info-addr=%p", plugin_info);
			goto error;
		}
	}

	if (PyUnicode_Check(py_description)) {
		description = PyUnicode_AsUTF8(py_description);
		if (!description) {
			BT_LOGW("Cannot decode Python plugin description string: "
				"py-plugin-info-addr=%p", plugin_info);
			goto error;
		}
	}

	if (PyUnicode_Check(py_license)) {
		license = PyUnicode_AsUTF8(py_license);
		if (!license) {
			BT_LOGW("Cannot decode Python plugin license string: "
				"py-plugin-info-addr=%p", plugin_info);
			goto error;
		}
	}

	if (PyTuple_Check(py_version)) {
		if (PyTuple_Size(py_version) >= 3) {
			PyObject *py_major = PyTuple_GetItem(py_version, 0);
			PyObject *py_minor = PyTuple_GetItem(py_version, 1);
			PyObject *py_patch = PyTuple_GetItem(py_version, 2);

			assert(py_major);
			assert(py_minor);
			assert(py_patch);

			if (PyLong_Check(py_major)) {
				major = PyLong_AsUnsignedLong(py_major);
			}

			if (PyLong_Check(py_minor)) {
				minor = PyLong_AsUnsignedLong(py_minor);
			}

			if (PyLong_Check(py_patch)) {
				patch = PyLong_AsUnsignedLong(py_patch);
			}

			if (PyErr_Occurred()) {
				/* Overflow error, most probably */
				BT_LOGW("Invalid Python plugin version format: "
					"py-plugin-info-addr=%p", plugin_info);
				goto error;
			}
		}

		if (PyTuple_Size(py_version) >= 4) {
			PyObject *py_extra = PyTuple_GetItem(py_version, 3);

			assert(py_extra);

			if (PyUnicode_Check(py_extra)) {
				version_extra = PyUnicode_AsUTF8(py_extra);
				if (!version_extra) {
				BT_LOGW("Cannot decode Python plugin version's extra string: "
					"py-plugin-info-addr=%p", plugin_info);
					goto error;
				}
			}
		}
	}

	plugin = bt_plugin_create_empty(BT_PLUGIN_TYPE_PYTHON);
	if (!plugin) {
		BT_LOGE_STR("Cannot create empty plugin object.");
		goto error;
	}

	bt_plugin_set_name(plugin, name);

	if (description) {
		bt_plugin_set_description(plugin, description);
	}

	if (author) {
		bt_plugin_set_author(plugin, author);
	}

	if (license) {
		bt_plugin_set_license(plugin, license);
	}

	bt_plugin_set_version(plugin, major, minor, patch, version_extra);

	if (PyList_Check(py_comp_class_addrs)) {
		size_t i;

		for (i = 0; i < PyList_Size(py_comp_class_addrs); i++) {
			struct bt_component_class *comp_class;
			PyObject *py_comp_class_addr;

			py_comp_class_addr =
				PyList_GetItem(py_comp_class_addrs, i);
			assert(py_comp_class_addr);
			if (PyLong_Check(py_comp_class_addr)) {
				comp_class = (struct bt_component_class *)
					PyLong_AsUnsignedLongLong(py_comp_class_addr);
			} else {
				BT_LOGW("Component class address is not an integer in Python plugin info object: "
					"py-plugin-info-addr=%p, index=%zu",
					plugin_info, i);
				continue;
			}

			ret = bt_plugin_add_component_class(plugin, comp_class);
			if (ret < 0) {
				BT_LOGE("Cannot add component class to plugin: "
					"py-plugin-info-addr=%p, "
					"plugin-addr=%p, plugin-name=\"%s\", "
					"comp-class-addr=%p, "
					"comp-class-name=\"%s\", "
					"comp-class-type=%s",
					plugin_info,
					plugin, bt_plugin_get_name(plugin),
					comp_class,
					bt_component_class_get_name(comp_class),
					bt_component_class_type_string(
						bt_component_class_get_type(comp_class)));
				continue;
			}
		}
	}

	bt_plugin_freeze(plugin);

	goto end;

error:
	print_python_traceback_warn();
	pyerr_clear();
	BT_PUT(plugin);

end:
	Py_XDECREF(py_name);
	Py_XDECREF(py_author);
	Py_XDECREF(py_description);
	Py_XDECREF(py_license);
	Py_XDECREF(py_version);
	Py_XDECREF(py_comp_class_addrs);
	return plugin;
}
Exemple #19
0
PyObject *_PyCodec_Lookup(const char *encoding)
{
    PyInterpreterState *interp;
    PyObject *result, *args = NULL, *v;
    Py_ssize_t i, len;

    if (encoding == NULL) {
	PyErr_BadArgument();
	goto onError;
    }

    interp = PyThreadState_GET()->interp;
    if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
	goto onError;

    /* Convert the encoding to a normalized Python string: all
       characters are converted to lower case, spaces and hyphens are
       replaced with underscores. */
    v = normalizestring(encoding);
    if (v == NULL)
	goto onError;
    PyString_InternInPlace(&v);

    /* First, try to lookup the name in the registry dictionary */
    result = PyDict_GetItem(interp->codec_search_cache, v);
    if (result != NULL) {
	Py_INCREF(result);
	Py_DECREF(v);
	return result;
    }
    
    /* Next, scan the search functions in order of registration */
    args = PyTuple_New(1);
    if (args == NULL)
	goto onError;
    PyTuple_SET_ITEM(args,0,v);

    len = PyList_Size(interp->codec_search_path);
    if (len < 0)
	goto onError;
    if (len == 0) {
	PyErr_SetString(PyExc_LookupError,
			"no codec search functions registered: "
			"can't find encoding");
	goto onError;
    }

    for (i = 0; i < len; i++) {
	PyObject *func;
	
	func = PyList_GetItem(interp->codec_search_path, i);
	if (func == NULL)
	    goto onError;
	result = PyEval_CallObject(func, args);
	if (result == NULL)
	    goto onError;
	if (result == Py_None) {
	    Py_DECREF(result);
	    continue;
	}
	if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
	    PyErr_SetString(PyExc_TypeError,
			    "codec search functions must return 4-tuples");
	    Py_DECREF(result);
	    goto onError;
	}
	break;
    }
    if (i == len) {
	/* XXX Perhaps we should cache misses too ? */
	PyErr_Format(PyExc_LookupError,
                     "unknown encoding: %s", encoding);
	goto onError;
    }

    /* Cache and return the result */
    PyDict_SetItem(interp->codec_search_cache, v, result);
    Py_DECREF(args);
    return result;

 onError:
    Py_XDECREF(args);
    return NULL;
}
Exemple #20
0
static PyObject *cboodle_init(PyObject *self, PyObject *args)
{
  char *devname = NULL;
  int ratewanted = 0;
  int verbose = 0;
  int ix, res;
  PyObject *extras = NULL;
  extraopt_t *opts = NULL;
  extraopt_t dummyopt = {NULL, NULL};

  if (!PyArg_ParseTuple(args, "|ziiO:init", &devname, &ratewanted, &verbose, &extras))
    return NULL;

  res = noteq_init();
  if (!res) {
    PyErr_SetString(PyExc_IOError, "unable to initialize note queue");
    return NULL;
  }

  if (extras && PyList_Check(extras)) {
    int count = PyList_Size(extras);

    opts = (extraopt_t *)malloc(sizeof(extraopt_t) * (count+1));
    if (!opts) {
      PyErr_SetString(PyExc_IOError, "unable to initialize extra options");
      return NULL;
    }

    for (ix=0; ix<count; ix++) {
      PyObject *tup = PyList_GetItem(extras, ix);
      PyObject *tkey, *tval;
      if (!tup)
	return NULL;
      if (!PyTuple_Check(tup) || PyTuple_Size(tup) != 2) {
	PyErr_SetString(PyExc_TypeError, "extraopts must be a list of 2-tuples");
	return NULL;
      }

      tkey = PyTuple_GetItem(tup, 0);
      if (!tkey)
	return NULL;
      tval = PyTuple_GetItem(tup, 1);
      if (!tval)
	return NULL;
      if (!PyString_Check(tkey) 
	|| !(tval == Py_None || PyString_Check(tval))) {
	PyErr_SetString(PyExc_TypeError, "extraopts must be (string, string) or (string, None)");
	return NULL;
      }

      opts[ix].key = PyString_AsString(tkey);
      if (tval == Py_None)
	opts[ix].val = NULL;
      else
	opts[ix].val = PyString_AsString(tval);
    }

    opts[count].key = NULL;
    opts[count].val = NULL;
  }

  res = audev_init_device(devname, ratewanted, (verbose!=0),
    (opts?opts:(&dummyopt)));
  if (!res) {
    PyErr_SetString(PyExc_IOError, "unable to initialize audio device");
    if (opts) {
      free(opts);
    }
    return NULL;
  }

  if (opts) {
    free(opts);
  }

  Py_INCREF(Py_None);
  return Py_None;
}
Exemple #21
0
QStringList PythonEngine::codeCompletion(const QString& code, int offset, const QString& fileName)
{
    runPythonHeader();

    QStringList out;

    QString exp;
    if (QFile::exists(fileName))
    {
        exp = QString("result_rope_pythonlab = python_engine_get_completion_file(\"%1\", %2)").
                arg(fileName).
                arg(offset);
    }
    else
    {
        QString str = code;
        // if (str.lastIndexOf("=") != -1)
        //    str = str.right(str.length() - str.lastIndexOf("=") - 1);

        for (int i = 33; i <= 126; i++)
        {
            // skip numbers and alphabet and dot
            if ((i >= 48 && i <= 57) || (i >= 65 && i <= 90) || (i >= 97 && i <= 122) || (i == 46))
                continue;

            QChar c(i);
            // qDebug() << c << ", " << str.lastIndexOf(c) << ", " << str.length();

            if (str.lastIndexOf(c) != -1)
            {
                str = str.right(str.length() - str.lastIndexOf(c) - 1);
                break;
            }
        }

        if (str.contains("."))
        {
            QString search = str.left(str.lastIndexOf("."));
            exp = QString("result_rope_pythonlab = python_engine_get_completion_string_dot(\"%1\")").
                    arg(search);
        }
        else
            exp = QString("result_rope_pythonlab = python_engine_get_completion_string(\"%1\", %2)").
                    arg(str.trimmed()).
                    arg(str.trimmed().length());
    }

    // QTime time;
    // time.start();
    PyObject *output = PyRun_String(exp.toLatin1().data(), Py_single_input, m_dict, m_dict);
    // qDebug() << time.elapsed();

    // parse result
    if (output)
    {
        PyObject *result = PyDict_GetItemString(m_dict, "result_rope_pythonlab");
        if (result)
        {
            Py_INCREF(result);
            PyObject *list;
            if (PyArg_Parse(result, "O", &list))
            {
                int count = PyList_Size(list);
                for (int i = 0; i < count; i++)
                {
                    PyObject *item = PyList_GetItem(list, i);

                    QString str = PyString_AsString(item);

                    // remove builtin methods
                    if (!str.startsWith("__"))
                        out.append(str);
                }
            }
            Py_DECREF(result);
        }

        PyRun_String("del result_rope_pythonlab", Py_single_input, m_dict, m_dict);
    }
    else
    {
        PyErr_Clear();
    }

    return out;
}
Exemple #22
0
static PyObject* Set_List(PyObject *self, PyObject *args)
{
	int i;
	PyObject *bn, *bne, *sn, *sne, *gn, *gne;
	PyObject *tmp;
	char *p;
	Py_ssize_t len = NAME_LEN;
	
	//bone_count, name, name_eng, skin_count, name, name_eng, bone_group_count, name, name_eng
	if(!PyArg_ParseTuple(args, "iOOiOOiOO",
							&list.bone_count, &bn, &bne,
							&list.skin_count, &sn, &sne,
							&list.disp_count, &gn, &gne))return NULL;
	
	list.bone = MALLOC(list.bone_count * sizeof(char)*NAME_LEN);
	list.bone_eng = MALLOC(list.bone_count * sizeof(char)*NAME_LEN);
	list.skin = MALLOC(list.skin_count * sizeof(char)*NAME_LEN);
	list.skin_eng = MALLOC(list.skin_count * sizeof(char)*NAME_LEN);
	list.disp = MALLOC(list.disp_count * sizeof(char)*NAME_LEN);
	list.disp_eng = MALLOC(list.disp_count * sizeof(char)*NAME_LEN);
	
	p = NULL;
	
	/*ボーン*/
	for(i=0; i<list.bone_count; i++){
		tmp = PyList_GetItem(bn, i);
		PyBytes_AsStringAndSize(tmp, &p, &len);
		strncpy(list.bone[i], p, NAME_LEN);
		
		tmp = PyList_GetItem(bne, i);
		PyBytes_AsStringAndSize(tmp, &p, &len);
		strncpy(list.bone_eng[i], p, NAME_LEN);
		//printf("%d %s\n", i, list.bone[i]);
	}
	
	/*表情*/
	for(i=0; i<list.skin_count; i++){
		tmp = PyList_GetItem(sn, i);
		//strncpy(list.skin[i], PyBytes_AsString(tmp), NAME_LEN);
		PyBytes_AsStringAndSize(tmp, &p, &len);
		strncpy(list.skin[i], p, NAME_LEN);
		
		tmp = PyList_GetItem(sne, i);
		//strncpy(list.skin_eng[i], PyBytes_AsString(tmp), NAME_LEN);
		PyBytes_AsStringAndSize(tmp, &p, &len);
		strncpy(list.skin_eng[i], p, NAME_LEN);
	}
	
	/*ボーングループ*/
	for(i=0; i<list.disp_count; i++){
		tmp = PyList_GetItem(gn, i);
		//strncpy(list.disp[i], PyBytes_AsString(tmp), NAME_LEN);
		PyBytes_AsStringAndSize(tmp, &p, &len);
		strncpy(list.disp[i], p, NAME_LEN);
		
		tmp = PyList_GetItem(gne, i);
		//strncpy(list.disp_eng[i], PyBytes_AsString(tmp), NAME_LEN);
		PyBytes_AsStringAndSize(tmp, &p, &len);
		strncpy(list.disp_eng[i], p, NAME_LEN);
	}
	
	return Py_BuildValue("i", 0);
}
/**
 ******************************************************************************************************
 * Removes a bin from a record.
 *
 * @param self                  AerospikeClient object
 * @prama py_key                The key for the record.
 * @pram py_binList             The name of the bins to be removed from the record.
 * @param py_policy             The optional policies.
 * @param err                   The C client's as_error to be set to the encountered error.
 *
 * Returns an integer status. 0(Zero) is success value.
 * In case of error,appropriate exceptions will be raised.
 *******************************************************************************************************
 */
static
PyObject * AerospikeClient_RemoveBin_Invoke(
		AerospikeClient * self,
		PyObject * py_key,PyObject* py_binList ,PyObject * py_policy, PyObject * py_meta, as_error *err)
{

	// Aerospike Client Arguments
	as_policy_write write_policy;
	as_policy_write * write_policy_p = NULL;
	as_key key;
	as_record rec;
	char* binName = NULL;
	int count = 0;
	PyObject * py_ustr = NULL;

	// Get the bin list size;
	Py_ssize_t size = PyList_Size(py_binList);
	// Initialize record
	as_record_inita(&rec, size);

	// Convert python key object to as_key
	pyobject_to_key(err, py_key, &key);
	if ( err->code != AEROSPIKE_OK ) {
		goto CLEANUP;
	}

	// Convert python policy object to as_policy_write
	pyobject_to_policy_write(err, py_policy, &write_policy, &write_policy_p,
			&self->as->config.policies.write);
	if ( err->code != AEROSPIKE_OK ) {
		as_error_update(err, AEROSPIKE_ERR_CLIENT, "Incorrect policy");
		goto CLEANUP;
	}

	// Invoke operation

	for ( count = 0; count < size; count++ ) {
		PyObject * py_val = PyList_GetItem(py_binList, count);
		if( PyUnicode_Check(py_val) ){
			py_ustr = PyUnicode_AsUTF8String(py_val);
			binName = PyStr_AsString(py_ustr);
		}
		else if( PyStr_Check(py_val) ) {
			binName = PyStr_AsString(py_val);
		}
		else
		{
			as_error_update(err, AEROSPIKE_ERR_CLIENT, "Invalid bin name, bin name should be a string or unicode string")
			goto CLEANUP;
		}
		if (!as_record_set_nil(&rec, binName)){
			goto CLEANUP;
		}
		if (py_ustr) {
			Py_DECREF(py_ustr);
			py_ustr = NULL;
		}
	}

	if ( py_meta && PyDict_Check(py_meta) ) {
		PyObject * py_gen = PyDict_GetItemString(py_meta, "gen");
		PyObject * py_ttl = PyDict_GetItemString(py_meta, "ttl");

		if( py_ttl != NULL ){
			if ( PyInt_Check(py_ttl) ) {
				rec.ttl = (uint32_t) PyInt_AsLong(py_ttl);
			}
			else if ( PyLong_Check(py_ttl) ) {
				rec.ttl = (uint32_t) PyLong_AsLongLong(py_ttl);
                if((uint32_t)-1 == rec.ttl) {
				    as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for ttl exceeds sys.maxsize");
			        goto CLEANUP;
                }
			}
			else
			{
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Ttl should be an int or long");
			    goto CLEANUP;
			}
		}

		if( py_gen != NULL ){
			if ( PyInt_Check(py_gen) ) {
				rec.gen = (uint16_t) PyInt_AsLong(py_gen);
			}
			else if ( PyLong_Check(py_gen) ) {
				rec.gen = (uint16_t) PyLong_AsLongLong(py_gen);
                if((uint16_t)-1 == rec.gen) {
                    as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for gen exceeds sys.maxsize");
			        goto CLEANUP;
                }
			}
			else
			{
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Generation should be an int or long");
			    goto CLEANUP;
			}
		}
	}

    Py_BEGIN_ALLOW_THREADS
	aerospike_key_put(self->as, err, write_policy_p, &key, &rec);
    Py_END_ALLOW_THREADS
    if (err->code != AEROSPIKE_OK)
	{
		as_error_update(err, err->code, NULL);
		goto CLEANUP;
	}

CLEANUP:

	as_record_destroy(&rec);

	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		if(PyObject_HasAttrString(exception_type, "key")) {
			PyObject_SetAttrString(exception_type, "key", py_key);
		} 
		if(PyObject_HasAttrString(exception_type, "bin")) {
			PyObject_SetAttrString(exception_type, "bin", Py_None);
		}
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return PyLong_FromLong(0);
}
Exemple #24
0
/*
 * This function must be called with a range of samples, and a desired
 * width and height.
 * It will average samples if needed.
 */
static PyObject *
py_fill_surface (PyObject * self, PyObject * args)
{
    PyObject *samples;
    PyObject *sampleObj;
    int length, i;
    double sample;
    cairo_surface_t *surface;
    cairo_t *ctx;
    int width, height;
    float pixelsPerSample;
    float currentPixel;
    int samplesInAccum;
    float x = 0.;
    float lastX = 0.;
    double accum;
    double lastAccum = 0.;

    if (!PyArg_ParseTuple (args, "O!ii", &PyList_Type, &samples, &width, &height))
        return NULL;

    length = PyList_Size (samples);

    surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);

    ctx = cairo_create (surface);

    cairo_set_source_rgb (ctx, 0.2, 0.6, 0.0);
    cairo_set_line_width (ctx, 0.5);
    cairo_move_to (ctx, 0, height);

    pixelsPerSample = width / (float) length;
    currentPixel = 0.;
    samplesInAccum = 0;
    accum = 0.;

    for (i = 0; i < length; i++) {
        /* Guaranteed to return something */
        sampleObj = PyList_GetItem (samples, i);
        sample = PyFloat_AsDouble (sampleObj);

        /* If the object was not a float or convertible to float */
        if (PyErr_Occurred ()) {
            cairo_surface_finish (surface);
            Py_DECREF (samples);
            return NULL;
        }

        currentPixel += pixelsPerSample;
        samplesInAccum += 1;
        accum += sample;
        if (currentPixel > 1.0) {
            accum /= samplesInAccum;
            cairo_line_to (ctx, x, height - accum);
            lastAccum = accum;
            accum = 0;
            currentPixel -= 1.0;
            samplesInAccum = 0;
            lastX = x;
        }
        x += pixelsPerSample;
    }

    Py_DECREF (samples);
    cairo_line_to (ctx, width, height);
    cairo_close_path (ctx);
    cairo_fill_preserve (ctx);

    return PycairoSurface_FromSurface (surface, NULL);
}
Exemple #25
0
static PyObject *
pytrap_init(PyObject *self, PyObject *args, PyObject *keywds)
{
    char **argv = NULL;
    char *arg;
    PyObject *argvlist;
    PyObject *strObj;
    int argc = 0, i, ifcin = 1, ifcout = 0;

    static char *kwlist[] = {"argv", "ifcin", "ifcout", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!|ii", kwlist, &PyList_Type, &argvlist, &ifcin, &ifcout)) {
        return NULL;
    }

    argc = PyList_Size(argvlist);
    if (argc ==0) {
        PyErr_SetString(TrapError, "argv list must not be empty.");
        return NULL;
    }
    argv = calloc(argc, sizeof(char *));
    for (i=0; i<argc; i++) {
        strObj = PyList_GetItem(argvlist, i);
#if PY_MAJOR_VERSION >= 3
        if (!PyUnicode_Check(strObj)) {
#else
        if (!PyString_Check(strObj)) {
#endif
            PyErr_SetString(TrapError, "argv must contain string.");
            goto failure;
        }
#if PY_MAJOR_VERSION >= 3
        arg = PyUnicode_AsUTF8AndSize(strObj, NULL);
#else
        arg = PyString_AS_STRING(strObj);
#endif
        argv[i] = arg;
    }

    int ret = local_trap_init(argc, argv, module_info, ifcin, ifcout);
    if (ret != 0) {
        PyErr_SetString(TrapError, "Initialization failed");
        return NULL;
    }

    Py_RETURN_NONE;
failure:
    free(argv);
    return NULL;
}

static PyObject *
pytrap_send(PyObject *self, PyObject *args, PyObject *keywds)
{
    uint32_t ifcidx = 0;
    PyObject *dataObj;
    char *data;
    Py_ssize_t data_size;

    static char *kwlist[] = {"data", "ifcidx", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|I", kwlist, &dataObj, &ifcidx)) {
        return NULL;
    }

    if (PyByteArray_Check(dataObj)) {
        data_size = PyByteArray_Size(dataObj);
        data = PyByteArray_AsString(dataObj);
    } else if (PyBytes_Check(dataObj)) {
        PyBytes_AsStringAndSize(dataObj, &data, &data_size);
    } else {
        PyErr_SetString(PyExc_TypeError, "Argument data must be of bytes or bytearray type.");
        return NULL;
    }

    if (data_size > 0xFFFF) {
        PyErr_SetString(TrapError, "Data length is out of range (0-65535)");
        return NULL;
    }

    int ret;
    Py_BEGIN_ALLOW_THREADS
    ret = trap_send(ifcidx, data, (uint16_t) data_size);
    Py_END_ALLOW_THREADS

    if (ret == TRAP_E_TIMEOUT) {
        PyErr_SetString(TimeoutError, "Timeout");
        return NULL;
    } else if (ret == TRAP_E_BAD_IFC_INDEX) {
        PyErr_SetString(TrapError, "Bad index of IFC.");
        return NULL;
    } else if (ret == TRAP_E_TERMINATED) {
        PyErr_SetString(TrapTerminated, "IFC was terminated.");
        return NULL;
    }

    Py_RETURN_NONE;
}
AerospikeQuery * AerospikeQuery_Apply(AerospikeQuery * self, PyObject * args, PyObject * kwds)
{

	// Python function arguments
	PyObject * py_module = NULL;
	PyObject * py_function = NULL;
	PyObject * py_args = NULL;
	PyObject * py_policy = NULL;

	PyObject * py_umodule   = NULL;
	PyObject * py_ufunction = NULL;
	// Python function keyword arguments
	static char * kwlist[] = {"module", "function", "arguments", "policy", NULL};

	if ( PyArg_ParseTupleAndKeywords(args, kwds, "OO|OO:apply", kwlist, &py_module, &py_function, &py_args, &py_policy) == false ){
		return NULL;
	}

	// Aerospike error object
	as_error err;
	// Initialize error object
	as_error_init(&err);

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

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

	// Aerospike API Arguments
	char * module = NULL;
	char * function = NULL;
	as_arraylist * arglist = NULL;

	if ( PyUnicode_Check(py_module) ){
		py_umodule = PyUnicode_AsUTF8String(py_module);
		module = PyStr_AsString(py_umodule);
	}
	else if ( PyStr_Check(py_module) ) {
		module = PyStr_AsString(py_module);
	}
	else {
		as_error_update(&err, AEROSPIKE_ERR_CLIENT, "udf module argument must be a string or unicode string");
		goto CLEANUP;
	}

	if ( PyUnicode_Check(py_function) ){
		py_ufunction = PyUnicode_AsUTF8String(py_function);
		function = PyStr_AsString(py_ufunction);
	}
	else if ( PyStr_Check(py_function) ) {
		function = PyStr_AsString(py_function);
	}
	else {
		as_error_update(&err, AEROSPIKE_ERR_CLIENT, "udf function argument must be a string or unicode string");
		goto CLEANUP;
	}

	if ( py_args && PyList_Check(py_args) ){
		Py_ssize_t size = PyList_Size(py_args);

		arglist = as_arraylist_new(size, 0);

		for ( int i = 0; i < size; i++ ) {
			PyObject * py_val = PyList_GetItem(py_args, (Py_ssize_t)i);
			as_val * val = NULL;
			pyobject_to_val(self->client, &err, py_val, &val, &self->static_pool, SERIALIZER_PYTHON);
			if ( err.code != AEROSPIKE_OK ) {
				as_error_update(&err, err.code, NULL);
				goto CLEANUP;
			}
			else {
				as_arraylist_append(arglist, val);
			}
		}
	}


	as_query_apply(&self->query, module, function, (as_list *) arglist);

CLEANUP:

	if (py_ufunction) {
		Py_DECREF(py_ufunction);
	}

	if (py_umodule) {
		Py_DECREF(py_umodule);
	}

	if ( err.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(&err, &py_err);
		PyObject *exception_type = raise_exception(&err);
		if(PyObject_HasAttrString(exception_type, "module")) {
			PyObject_SetAttrString(exception_type, "module", py_module);
		} 
		if(PyObject_HasAttrString(exception_type, "func")) {
			PyObject_SetAttrString(exception_type, "func", py_function);
		}
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}

	Py_INCREF(self);
	return self;
}
Exemple #27
0
static PyObject *writeData(PyObject *self, PyObject *args, PyObject *kwargs) {

    char *filename=NULL, SymData[80], *tempchar;
    PyArrayObject *data;
    PyObject *header;
    MRCHeader m_header;
    FILE *m_fp=NULL;
    gzFile gzfp=NULL;
    int i,j,k,bytesize=4,compress=0;
    void *matrix;

    static char *kwlist[] = {"header", "data", "filename", "compress", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOsi", kwlist,
                                     &header, &data, &filename, &compress))
        return Py_BuildValue("Os", Py_None,"Couldn't parse variable from C function.");

    data = PyArray_GETCONTIGUOUS(data);
    matrix = (void *) PyArray_DATA(data);
    if (compress){
        gzfp = gzopen(filename,"wb");
        if(gzfp==NULL)
            return Py_BuildValue("Os", Py_None,"Couldn't write file.");
    }
    else{
        m_fp=fopen(filename,"w");
        if(m_fp==NULL)
            return Py_BuildValue("Os", Py_None,"Couldn't write file.");
    }

    m_header.nx=PyInt_AsLong(PyObject_GetAttrString(header, "nx"));
    m_header.ny=PyInt_AsLong(PyObject_GetAttrString(header, "ny"));
    m_header.nz=PyInt_AsLong(PyObject_GetAttrString(header, "nz"));
    m_header.mode=PyInt_AsLong(PyObject_GetAttrString(header, "mode"));
    m_header.nxstart=PyInt_AsLong(PyObject_GetAttrString(header, "nxstart"));
    m_header.nystart=PyInt_AsLong(PyObject_GetAttrString(header, "nystart"));
    m_header.nzstart=PyInt_AsLong(PyObject_GetAttrString(header, "nzstart"));
    m_header.mx=PyInt_AsLong(PyObject_GetAttrString(header, "mx"));
    m_header.my=PyInt_AsLong(PyObject_GetAttrString(header, "my"));
    m_header.mz=PyInt_AsLong(PyObject_GetAttrString(header, "mz"));
    m_header.mapc=PyInt_AsLong(PyObject_GetAttrString(header, "mapc"));
    m_header.mapr=PyInt_AsLong(PyObject_GetAttrString(header, "mapr"));
    m_header.maps=PyInt_AsLong(PyObject_GetAttrString(header, "maps"));
    m_header.ispg=PyInt_AsLong(PyObject_GetAttrString(header, "ispg"));
    m_header.nsymbt=PyInt_AsLong(PyObject_GetAttrString(header, "nsymbt"));
    m_header.machst=PyInt_AsLong(PyObject_GetAttrString(header, "machst"));
    m_header.nlabels=PyInt_AsLong(PyObject_GetAttrString(header, "nlabels"));

    m_header.dmin=(float)PyFloat_AsDouble(PyObject_GetAttrString(header, "dmin"));
    m_header.dmax=(float)PyFloat_AsDouble(PyObject_GetAttrString(header, "dmax"));
    m_header.dmean=(float)PyFloat_AsDouble(PyObject_GetAttrString(header, "dmean"));
    m_header.rms=(float)PyFloat_AsDouble(PyObject_GetAttrString(header, "rms"));

    tempchar=PyString_AsString(PyObject_GetAttrString(header, "map"));
    strncpy(m_header.map,tempchar,4);
    for(i=0;i<4;i++)
        if (m_header.map[i]=='\0'){
            for(j=i+1;j<4;j++)
                m_header.map[j]='\0';
            break;
        }

    tempchar=PyString_AsString(PyObject_GetAttrString(header, "extra"));
    strncpy(m_header.extra,tempchar,100);
    for(i=0;i<100;i++)
        if (m_header.extra[i]=='\0'){
            for(j=i+1;j<100;j++)
                m_header.extra[j]='\0';
            break;
        }

    for (i=0;i<3;i++){
      m_header.cella[i]=(float)PyFloat_AsDouble(PyList_GetItem(PyObject_GetAttrString(header,"cella"), i));
      m_header.cellb[i]=(float)PyFloat_AsDouble(PyList_GetItem(PyObject_GetAttrString(header,"cellb"), i));
      m_header.origin[i]=(float)PyFloat_AsDouble(PyList_GetItem(PyObject_GetAttrString(header,"origin"), i));
    }

    for (i=0;i<10;i++){
      tempchar=PyString_AsString(PyList_GetItem(PyObject_GetAttrString(header,"label"), i));
      strncpy(m_header.label[i],tempchar,80);
        for(j=0;j<80;j++)
            if (m_header.label[i][j]=='\0'){
                for(k=j+1;k<80;k++)
                    m_header.label[i][k]='\0';
                break;
            }
    }

    if (m_header.nsymbt==80){
        tempchar=PyString_AsString(PyObject_GetAttrString(header, "symdata"));
        strncpy(SymData,tempchar,80);
        for(i=0;i<80;i++)
            if (SymData[i]=='\0'){
                for(j=i+1;j<80;j++)
                    SymData[j]='\0';
                break;
            }
    }
    else
        m_header.nsymbt=0;

    switch(m_header.mode)
    {
        case 0:
            bytesize=1;break;
        case 1:
            bytesize=2;break;
        case 2:
            bytesize=4;break;
        case 5:
            bytesize=1;break;
        case 6:
            bytesize=2;break;
    }

    // Write file.
    if (compress){
        if (gzwrite(gzfp,&m_header,1024)!=1024){
            gzclose(gzfp);
            return Py_BuildValue("Os", Py_None,"Couldn't write the header.");
        }
        if (m_header.nsymbt==80){
            if (gzwrite(gzfp, SymData, 80)!=80){
                gzclose(gzfp);
                return Py_BuildValue("Os", Py_None,"Couldn't write Symmetry Data.");
            }
        }
        if (gzwrite(gzfp, matrix, bytesize*m_header.nz*m_header.ny*m_header.nx)!=bytesize*m_header.nz*m_header.ny*m_header.nx){
            gzclose(gzfp);
            return Py_BuildValue("Os", Py_None,"Couldn't write Matrix.");
        }
        gzclose(gzfp);
    }
    else{
        if (fwrite(&m_header,1,1024,m_fp)!=1024){
            fclose(m_fp);
            return Py_BuildValue("Os", Py_None,"Couldn't write the header.");
        }
        if (m_header.nsymbt==80){
            if (fwrite(SymData, 1, (size_t)80, m_fp)!=80){
                fclose(m_fp);
                return Py_BuildValue("Os", Py_None,"Couldn't write Symmetry Data.");
            }
        }
        if (fwrite(matrix, bytesize, m_header.nz*m_header.ny*m_header.nx, m_fp)!=m_header.nz*m_header.ny*m_header.nx){
            fclose(m_fp);
            return Py_BuildValue("Os", Py_None,"Couldn't write Matrix.");
        }
        fclose(m_fp);
    }
    Py_XDECREF(data);
    return Py_BuildValue("i", 0);
}
static PyObject *
RdkHandle_configure(RdkHandle *self, PyObject *args, PyObject *kwds)
{
    char *keywords[] = {"conf", "topic_conf", NULL};
    PyObject *conf = NULL;
    PyObject *topic_conf = NULL;
    if (! PyArg_ParseTupleAndKeywords(args,
                                      kwds,
                                      "|OO",
                                      keywords,
                                      &conf,
                                      &topic_conf)) {
        return NULL;
    }

    if (RdkHandle_safe_lock(self, /* check_running= */ 0)) return NULL;
    if ((conf && topic_conf) || (!conf && !topic_conf)) {
        return set_pykafka_error(
            "RdKafkaException",
            "You need to specify *either* `conf` *or* `topic_conf`.");
    }
    if (self->rdk_handle) {
        return set_pykafka_error(
            "RdKafkaException",
            "Cannot configure: seems instance was started already?");
    }

    Py_BEGIN_ALLOW_THREADS  /* avoid callbacks deadlocking */
        if (! self->rdk_conf) {
            self->rdk_conf = rd_kafka_conf_new();
            rd_kafka_conf_set_log_cb(self->rdk_conf, logging_callback);
        }
        if (! self->rdk_topic_conf) {
            self->rdk_topic_conf = rd_kafka_topic_conf_new();
        }
    Py_END_ALLOW_THREADS

    PyObject *retval = Py_None;
    PyObject *conf_or_topic_conf = topic_conf ? topic_conf : conf;
    Py_ssize_t i, len = PyList_Size(conf_or_topic_conf);
    for (i = 0; i != len; ++i) {
        PyObject *conf_pair = PyList_GetItem(conf_or_topic_conf, i);
        const char *name = NULL;
        const char *value =  NULL;
        if (! PyArg_ParseTuple(conf_pair, "ss", &name, &value)) {
            retval = NULL;
            break;
        }
        char errstr[512];
        rd_kafka_conf_res_t res;
        Py_BEGIN_ALLOW_THREADS  /* avoid callbacks deadlocking */
            if (topic_conf) {
                res = rd_kafka_topic_conf_set(
                    self->rdk_topic_conf, name, value, errstr, sizeof(errstr));
            } else {
                res = rd_kafka_conf_set(
                    self->rdk_conf, name, value, errstr, sizeof(errstr));
            }
        Py_END_ALLOW_THREADS
        if (res != RD_KAFKA_CONF_OK) {
            retval = set_pykafka_error("RdKafkaException", errstr);
            break;
        }
    }

    if (RdkHandle_unlock(self)) return NULL;
    Py_XINCREF(retval);
    return retval;
}
Exemple #29
0
static LIST*
call_python_function(RULE* r, FRAME* frame)
{
    LIST * result = 0;
    PyObject * arguments = 0;
    PyObject * kw = NULL;
    int i ;
    PyObject * py_result;

    if (r->arguments)
    {
        SETTINGS * args;

        arguments = PyTuple_New(0);
        kw = PyDict_New();

        for (args = collect_arguments(r, frame); args; args = args->next)
        {
            PyObject *key = PyString_FromString(args->symbol);
            PyObject *value = 0;
            if (args->multiple)
                value = list_to_python(args->value);
            else {
                if (args->value)
                    value = PyString_FromString(args->value->string);
            }

            if (value)
                PyDict_SetItem(kw, key, value);
            Py_DECREF(key);
            Py_XDECREF(value);
        }
    }
    else
    {
        arguments = PyTuple_New( frame->args->count );
        for ( i = 0; i < frame->args->count; ++i )
        {
            PyObject * arg = PyList_New(0);
            LIST* l = lol_get( frame->args, i);
            
            for ( ; l; l = l->next )
            {
                PyObject * v = PyString_FromString(l->string);
                PyList_Append( arg, v );
                Py_DECREF(v);
            }
            /* Steals reference to 'arg' */
            PyTuple_SetItem( arguments, i, arg );
        }
    }

    frame_before_python_call = frame;
    py_result = PyObject_Call( r->python_function, arguments, kw );
    Py_DECREF(arguments);
    Py_XDECREF(kw);
    if ( py_result != NULL )
    {
        if ( PyList_Check( py_result ) )
        {
            int size = PyList_Size( py_result );
            int i;
            for ( i = 0; i < size; ++i )
            {
                PyObject * item = PyList_GetItem( py_result, i );
                char *s = python_to_string (item);
                if (!s) {
                    fprintf( stderr, "Non-string object returned by Python call.\n" );
                } else {
                    result = list_new (result, s);
                }
            }
        }
        else if ( py_result == Py_None )
        {
            result = L0;
        }
        else 
        {
            char *s = python_to_string(py_result);
            if (s)
                result = list_new(0, s);
            else 
                /* We have tried all we could.  Return empty list. There are
                   cases, e.g.  feature.feature function that should return
                   value for the benefit of Python code and which also can be
                   called by Jam code, where no sensible value can be
                   returned. We cannot even emit a warning, since there will
                   be a pile of them.  */                
                result = L0;                    
        }

        Py_DECREF( py_result );
    }
    else
    {
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
    }

    return result;
}
Exemple #30
0
PyObject*
PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
{
    ImagingEncoderObject* encoder;

    char* mode;
    char* rawmode;
    char* compname;
    char* filename;
    int fp;

    PyObject *dir;
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    int status;

    Py_ssize_t d_size;
    PyObject *keys, *values;


    if (! PyArg_ParseTuple(args, "sssisO", &mode, &rawmode, &compname, &fp, &filename, &dir)) {
        return NULL;
    }

    if (!PyDict_Check(dir)) {
        PyErr_SetString(PyExc_ValueError, "Invalid Dictionary");
        return NULL;
    } else {
        d_size = PyDict_Size(dir);
        TRACE(("dict size: %d\n", (int)d_size));
        keys = PyDict_Keys(dir);
        values = PyDict_Values(dir);
        for (pos=0;pos<d_size;pos++){
            TRACE(("  key: %d\n", (int)PyInt_AsLong(PyList_GetItem(keys,pos))));
        }
        pos = 0;
    }


    TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));

    encoder = PyImaging_EncoderNew(sizeof(TIFFSTATE));
    if (encoder == NULL)
        return NULL;

    if (get_packer(encoder, mode, rawmode) < 0)
        return NULL;

    if (! ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) {
        Py_DECREF(encoder);
        PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed");
        return NULL;
    }

        // While failes on 64 bit machines, complains that pos is an int instead of a Py_ssize_t
        //    while (PyDict_Next(dir, &pos, &key, &value)) {
        for (pos=0;pos<d_size;pos++){
                key = PyList_GetItem(keys,pos);
                value = PyList_GetItem(values,pos);
        status = 0;
        TRACE(("Attempting to set key: %d\n", (int)PyInt_AsLong(key)));
        if (PyInt_Check(value)) {
            TRACE(("Setting from Int: %d %ld \n", (int)PyInt_AsLong(key),PyInt_AsLong(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyInt_AsLong(value));
        } else if(PyBytes_Check(value)) {
            TRACE(("Setting from Bytes: %d, %s \n", (int)PyInt_AsLong(key),PyBytes_AsString(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyBytes_AsString(value));
        } else if(PyList_Check(value)) {
            int len,i;
            float *floatav;
            int *intav;
            TRACE(("Setting from List: %d \n", (int)PyInt_AsLong(key)));
            len = (int)PyList_Size(value);
            if (len) {
                if (PyInt_Check(PyList_GetItem(value,0))) {
                    TRACE((" %d elements, setting as ints \n", len));
                    intav = malloc(sizeof(int)*len);
                    if (intav) {
                        for (i=0;i<len;i++) {
                            intav[i] = (int)PyInt_AsLong(PyList_GetItem(value,i));
                        }
                        status = ImagingLibTiffSetField(&encoder->state,
                                                        (ttag_t) PyInt_AsLong(key),
                                                        intav);
                        free(intav);
                    }
                } else {
                    TRACE((" %d elements, setting as floats \n", len));
                    floatav = malloc(sizeof(float)*len);
                    if (floatav) {
                        for (i=0;i<len;i++) {
                            floatav[i] = (float)PyFloat_AsDouble(PyList_GetItem(value,i));
                        }
                        status = ImagingLibTiffSetField(&encoder->state,
                                                        (ttag_t) PyInt_AsLong(key),
                                                        floatav);
                        free(floatav);
                    }
                }
            }
        } else if (PyFloat_Check(value)) {
            TRACE(("Setting from Float: %d, %f \n", (int)PyInt_AsLong(key),PyFloat_AsDouble(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            (float)PyFloat_AsDouble(value));
        } else {
            TRACE(("Unhandled type for key %d : %s \n",
                   (int)PyInt_AsLong(key),
                   PyBytes_AsString(PyObject_Str(value))));
        }
        if (!status) {
            TRACE(("Error setting Field\n"));
            Py_DECREF(encoder);
            PyErr_SetString(PyExc_RuntimeError, "Error setting from dictionary");
            return NULL;
        }
    }

    encoder->encode  = ImagingLibTiffEncode;

    return (PyObject*) encoder;
}