Esempio n. 1
0
// * GCHMCIntegrator Constructor * //
GCHMCIntegrator::GCHMCIntegrator(PyObject *universe, std::string ligdir, std::string gaff_fn)
{
  std::cout<<"GCHMCIntegrator instance created 20160826"<<std::endl;
  import_array();

  temperature = 300.0;
  delta_t = 0.0015;
  trouble = 0;
 
  this->universe = universe;

  PyObject *pyo_universe_spec;

  pyo_universe_spec = PyObject_GetAttrString(universe, "_spec");
  universe_spec = (PyUniverseSpecObject *)pyo_universe_spec;

  PyObject *objectList;
  objectList = PyObject_CallMethod(universe, "objectList", NULL);
  PyObject *object0 = PyList_GetItem(objectList, 0);

  // * Get confarr * //
  PyObject *confobj;
  PyObject *confarr;
  confobj = PyObject_CallMethod(universe, "configuration", NULL);
  confarr = PyObject_GetAttrString(confobj, "array");
  configuration = (PyArrayObject *)confarr;

  vector3 *x;
  x = (vector3 *)configuration->data;

  p_energy_po = new energy_data;

  #if defined(NUMPY)
    gradarr = (PyArrayObject *)PyArray_Copy(configuration);
  #else
    gradarr = (PyArrayObject *)PyArray_FromDims(configuration->nd, configuration->dimensions, PyArray_DOUBLE);
  #endif

  vector3 *f;
  f = (vector3 *)gradarr->data;
  for(int i=0; i<configuration->dimensions[0]; i++){
    f[i][0] = f[i][1] = f[i][2] = .0;
  }

  p_energy_po->gradients = (PyObject *)gradarr;
  p_energy_po->gradient_fn = NULL;
  p_energy_po->force_constants = NULL;
  p_energy_po->fc_fn = NULL;

  int natoms = configuration->dimensions[0];
  int order[natoms+2];
  int acceptance;

  PyObject *prmtop_order_obj = PyObject_GetAttrString(object0, "prmtop_order");
  for(int i=0; i<PyList_Size(prmtop_order_obj); i++){
    order[i] = (int)PyInt_AS_LONG( PyObject_GetAttrString(PyList_GetItem((prmtop_order_obj), i), "number") );
  }
  PyArrayObject *prmtop_order = (PyArrayObject *)prmtop_order_obj;
  order[natoms] = 1;
  order[natoms+1] = 1945;

  acceptance = order[natoms];

  int argc = 6;
  ligdir += '/';
  //gaffdir += '/';
  //string gaff_fn = gaffdir + "gaff.dat";

  /* Options are:
    IC: Internal Coordinates: fully flexible
    TD: Torsional Dynamics: only torsions are flexible 
    RR: Rigid Rings: torsional dynamics with rigid rings
   */
  const char *argv[6] = {
  "-ligdir", ligdir.c_str(),
  "-gaff",  gaff_fn.c_str(),
  "-ictd", "TD"
  };

  //+++++++ Simbody PART ++++++++++++
  bArgParser parser(argc, argv);
  parser.Print();
 
  TARGET_TYPE **indexMap = NULL;
  TARGET_TYPE *PrmToAx_po = NULL;
  TARGET_TYPE *MMTkToPrm_po = NULL;

  std::cout<<"MMTK configuration->dimensions[0]"<<configuration->dimensions[0]<<std::endl<<std::flush;
  indexMap = new TARGET_TYPE*[(configuration->dimensions[0])];
  int _indexMap[natoms][3];
  PrmToAx_po = new TARGET_TYPE[configuration->dimensions[0]];
  MMTkToPrm_po = new TARGET_TYPE[configuration->dimensions[0]];

  int natoms3 = 3*(configuration->dimensions[0]);
  int arrays_cut = 2 + 4*natoms3;

  SHMSZ = (
    2*sizeof(TARGET_TYPE) +       // Counter and flag
    natoms3*sizeof(TARGET_TYPE) + // Positions
    natoms3*sizeof(TARGET_TYPE) + // Velocities
    natoms3*sizeof(TARGET_TYPE) + // indexMap
    natoms3*sizeof(TARGET_TYPE) + // Gradients
    5*sizeof(TARGET_TYPE) +       // ac + 0 -> 4  // step, nosteps, temperature, timestep, trouble
    1*sizeof(TARGET_TYPE) +       // ac + 5       // potential energy
    2*sizeof(TARGET_TYPE) +       // ac + 6->7    // DAE step done; Move accepted
    1*sizeof(TARGET_TYPE) +       // ac + 8       // KE
    1*sizeof(TARGET_TYPE) +       // ac + 9       // steps_per_trial
    1*sizeof(TARGET_TYPE) //+     // ac + 10      // trial
  );
  shm = new TARGET_TYPE[SHMSZ];

  std::cout<<"parser.mol2F "<<parser.mol2F<<std::endl<<std::flush;
  std::cout<<"parser.rbF "<<parser.rbF<<std::endl<<std::flush;
  std::cout<<"parser.gaffF "<<parser.gaffF<<std::endl<<std::flush;
  std::cout<<"parser.frcmodF "<<parser.frcmodF<<std::endl<<std::flush;
  std::cout<<"parser.ictdF "<<parser.ictdF<<std::endl<<std::flush;

  // LS EU
  //(((PyFFEnergyTermObject **)(evaluator)->terms->data)[5])->param[0] = 0.5;
  // LS EU

  sys = new SymSystem(
    parser.mol2F, parser.rbF, parser.gaffF, parser.frcmodF,
    parser.ictdF, 
    PrmToAx_po, MMTkToPrm_po,
    evaluator,
    p_energy_po,
    configuration,
    universe_spec,
    shm
  );
  for(int i=0; i<natoms; i++){
    _indexMap[i][2] = order[i];
  }

  // * Memory alloc for convinient arrays * //
  coords = new TARGET_TYPE*[sys->mr->natms];
  TARGET_TYPE **vels = new TARGET_TYPE*[sys->mr->natms];
  TARGET_TYPE **inivels = new TARGET_TYPE*[sys->mr->natms];
  TARGET_TYPE **grads = new TARGET_TYPE*[sys->mr->natms];

  // * Seed the random number generator * //
  srand (time(NULL));

  //+++++++ SERVER PART +++++++++
  float mysweep = 0;
  shm[0] = CNT_START;

  int cli;
  sweep = 0;
  bool system_initialized = false;
  int big_loop_i;

  shm[1] = CLIENT_FLAG;
        int a;
        int start, start_1, stop;
        int i = natoms*2*3 + 2;

        // * Assign convenient pointers for order * /
        start = 2 + natoms3 + natoms3; 
        for(a=0; a<natoms; a++){
          indexMap[a] = &(shm[a*3 + start]);
        }
        // * Assign order in shm[][2] * //
        start = 2 + natoms3 + natoms3;
        cli = start;
        for (a=0; a<natoms; a++){ // Order
          cli += 2;
          shm[cli++] = order[a];
        }

        cli = 2;
        for (a=0; a<natoms; a++){ // Positions
          shm[cli++] = x[a][0]; shm[cli++] = x[a][1]; shm[cli++] = x[a][2];
        }
        for (a=0; a<natoms; a++){ // Velocities
          shm[cli++] = .0; //vels[a][0];//shm[cli++] = v[a][0];
          shm[cli++] = .0; //vels[a][1];//shm[cli++] = v[a][1];
          shm[cli++] = .0; //vels[a][2];//shm[cli++] = v[a][2];
        }
        for (a=0; a<natoms; a++){ // Order
          cli += 2;
          shm[cli++] = order[a];
        }
        for (a=0; a<natoms; a++){ // Forces
          shm[cli++] = .0; shm[cli++] = .0; shm[cli++] = .0;
        }
        shm[cli++] = big_loop_i;          // Step
        shm[cli++] = 50.0; //(TARGET_TYPE)nosteps;    // Number of steps
        shm[cli++] = temperature; // Temeperature
        shm[cli++] = delta_t;
        shm[cli++] = trouble;
        shm[cli++] = p_energy_po->energy;
        cli++; // DAE set only by the server
        shm[cli] = acceptance + 0.0;

        //Set the client flag
        shm[1] = CLIENT_FLAG;

      shm[arrays_cut + 6] = 13.0; // set DAE to done

      // * Assign convenient pointers for coordinates * //
      int shm_coords_sup = (natoms3)+2;
      int j=-1, k=0;
      start = 2; 
      for(j=0; j<natoms; j++){
        coords[j] = &(shm[j*3 + start]);
      }

      mysweep = shm[0] - CNT_START;

      // * Assign convenient pointers for velocities * //
      start = 2 + natoms3;
      start_1 = start - 1;
      stop = 2 + natoms3 + natoms3;
      for(j=0; j<natoms; j++){
        vels[j]    = &(shm[j*3 + start]);
        inivels[j] = &(shm[j*3 + start]);
      }


      // * Assign convenient pointers for gradients * //
      start = 2 + natoms3 + natoms3 + natoms3;
      start_1 = start - 1;
      stop = 2 + natoms3 + natoms3 + natoms3 + natoms3;
      for(j=0; j<natoms; j++){
        grads[j] = &(shm[j*3 + start]);
      }

      // * Rewrite indexMap to memory * /
      start = 2 + natoms3 + natoms3;
      start_1 = start - 1;
      stop = 2 + natoms3 + natoms3 + natoms3;

      // ************************* /
      // * Initialize Simulation * /
      // ************************* /
      TARGET_TYPE timestep, mytimestep;
      mytimestep = shm[arrays_cut + 3];
      // * Build bMainResidue and fill indexMap * /
      sys->InitSimulation(coords, vels, inivels, indexMap, grads, mytimestep, true);
      system_initialized = true;
}
Esempio n. 2
0
static int
pcap_PcapObject_init(PyObject *p,
                     PyObject *args,
                     PyObject *kwds)
{
  pcap_PcapObject *self     = (pcap_PcapObject *)p;
  static char     *kwlist[] = {"src", "mode", "snaplen", "linktype", NULL};
  char            *mode     = NULL;
  _uint32_t        snaplen  = 65535;
  _uint32_t        linktype = 1;
  PyObject        *pTmp     = NULL;
  PyObject        *pFile;       /* Don't decref, it's borrowed! */

  attempt {
    int tmp;

    tmp = PyArg_ParseTupleAndKeywords(args, kwds, "O|sll", kwlist, &pFile, &mode, &snaplen, &linktype);
    if (! tmp) break;

    if (PyString_Check(pFile)) {
      char *fn;

      fn = PyString_AsString(pFile);
      if (! fn) break;

      if (NULL == mode) {
        mode = "rb";
      }

      pFile = PyFile_FromString(fn, mode);
      if (! pFile) break;

      self->pFile = pFile;
    } else {
      self->pFile = pFile;
      Py_INCREF(self->pFile);
    }

    if ((! mode) || ('r' == mode[0])) {
      /* Try to read in the header. */

      pTmp = PyObject_CallMethod(pFile, "read", "i", sizeof(self->header));
      if (0 == mode) {
        /* If we're in auto-detect mode... */
        if (pTmp) {
          /* And it worked, then we become read-only */
          self->mode = 'r';
        } else {
          /* And it didn't work, then we become write-only */
          PyErr_Clear();
          self->mode = 'w';
        }
      } else {
        self->mode = mode[0];
      }
    } else {
      self->mode = mode[0];
    }

    if ('r' == self->mode) {
      if (! pTmp) break;

      {
        int   tmp;
        char *buf;
        int   len;

        tmp = PyString_AsStringAndSize(pTmp, &buf, &len);
        if (-1 == tmp) {
          break;
        }

        if (len != sizeof(self->header)) {
          PyErr_Format(PyExc_IOError, "Reading header returned wrong number of bytes");
          break;
        }

        memcpy(&(self->header), buf, len);
      }

      if (0xa1b2c3d4 == self->header.magic) {
        self->swap = 0;
      } else if (0xd4c3b2a1 == self->header.magic) {
        self->swap = 1;
      } else {
        PyErr_Format(PyExc_IOError, "Not a pcap file");
        break;
      }
    } else if ('w' == self->mode) {
      /* Write out header */

      memset(&(self->header), 0, sizeof(self->header));
      self->header.magic         = 0xa1b2c3d4;
      self->header.version_major = 2;
      self->header.version_minor = 4;
      self->header.snaplen       = snaplen;
      self->header.linktype      = linktype;
      self->swap                 = 0;

      pTmp = PyObject_CallMethod(pFile, "write", "s#", &(self->header), sizeof(self->header));
      if (! pTmp) break;
    } else {
      PyErr_Format(PyExc_IOError, "mode must be 'r' or 'w'");
      break;
    }
  }

  recover {
    Py_CLEAR(self->pFile);
    Py_CLEAR(pTmp);

    return -1;
  }

  return 0;
}
Esempio n. 3
0
void
Py_InitializeEx(int install_sigs)
{
	PyInterpreterState *interp;
	PyThreadState *tstate;
	PyObject *bimod, *sysmod;
	char *p;
#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
	char *codeset;
	char *saved_locale;
	PyObject *sys_stream, *sys_isatty;
#endif
	extern void _Py_ReadyTypes(void);

	if (initialized)
		return;
	initialized = 1;

	if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
		Py_DebugFlag = add_flag(Py_DebugFlag, p);
	if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
		Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
	if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
		Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);

	interp = PyInterpreterState_New();
	if (interp == NULL)
		Py_FatalError("Py_Initialize: can't make first interpreter");

	tstate = PyThreadState_New(interp);
	if (tstate == NULL)
		Py_FatalError("Py_Initialize: can't make first thread");
	(void) PyThreadState_Swap(tstate);

#ifdef STACKLESS
	if (!_PyStackless_InitTypes()) {
		PyErr_Print();
		Py_FatalError("Py_Initialize: can't init stackless types");
	}
#endif

	_Py_ReadyTypes();

	if (!_PyFrame_Init())
		Py_FatalError("Py_Initialize: can't init frames");

	if (!_PyInt_Init())
		Py_FatalError("Py_Initialize: can't init ints");

	_PyFloat_Init();

	interp->modules = PyDict_New();
	if (interp->modules == NULL)
		Py_FatalError("Py_Initialize: can't make modules dictionary");
	interp->modules_reloading = PyDict_New();
	if (interp->modules_reloading == NULL)
		Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");

#ifdef Py_USING_UNICODE
	/* Init Unicode implementation; relies on the codec registry */
	_PyUnicode_Init();
#endif

	bimod = _PyBuiltin_Init();
	if (bimod == NULL)
		Py_FatalError("Py_Initialize: can't initialize __builtin__");
	interp->builtins = PyModule_GetDict(bimod);
	if (interp->builtins == NULL)
		Py_FatalError("Py_Initialize: can't initialize builtins dict");
	Py_INCREF(interp->builtins);

	sysmod = _PySys_Init();
	if (sysmod == NULL)
		Py_FatalError("Py_Initialize: can't initialize sys");
	interp->sysdict = PyModule_GetDict(sysmod);
	if (interp->sysdict == NULL)
		Py_FatalError("Py_Initialize: can't initialize sys dict");
	Py_INCREF(interp->sysdict);
	_PyImport_FixupExtension("sys", "sys");
	PySys_SetPath(Py_GetPath());
	PyDict_SetItemString(interp->sysdict, "modules",
			     interp->modules);

	_PyImport_Init();

	/* initialize builtin exceptions */
	_PyExc_Init();
	_PyImport_FixupExtension("exceptions", "exceptions");

	/* phase 2 of builtins */
	_PyImport_FixupExtension("__builtin__", "__builtin__");

	_PyImportHooks_Init();

	if (install_sigs)
		initsigs(); /* Signal handling stuff, including initintr() */

#ifdef STACKLESS
	_PyStackless_Init();
#endif
	initmain(); /* Module __main__ */
	if (!Py_NoSiteFlag)
		initsite(); /* Module site */

	/* auto-thread-state API, if available */
#ifdef WITH_THREAD
	_PyGILState_Init(interp, tstate);
#endif /* WITH_THREAD */

	warnings_module = PyImport_ImportModule("warnings");
	if (!warnings_module)
		PyErr_Clear();

#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
	/* On Unix, set the file system encoding according to the
	   user's preference, if the CODESET names a well-known
	   Python codec, and Py_FileSystemDefaultEncoding isn't
	   initialized by other means. Also set the encoding of
	   stdin and stdout if these are terminals.  */

	saved_locale = strdup(setlocale(LC_CTYPE, NULL));
	setlocale(LC_CTYPE, "");
	codeset = nl_langinfo(CODESET);
	if (codeset && *codeset) {
		PyObject *enc = PyCodec_Encoder(codeset);
		if (enc) {
			codeset = strdup(codeset);
			Py_DECREF(enc);
		} else {
			codeset = NULL;
			PyErr_Clear();
		}
	} else
		codeset = NULL;
	setlocale(LC_CTYPE, saved_locale);
	free(saved_locale);

	if (codeset) {
		sys_stream = PySys_GetObject("stdin");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
		   PyFile_Check(sys_stream)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stdin");
		}
		Py_XDECREF(sys_isatty);

		sys_stream = PySys_GetObject("stdout");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
		   PyFile_Check(sys_stream)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stdout");
		}
		Py_XDECREF(sys_isatty);

		sys_stream = PySys_GetObject("stderr");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
		   PyFile_Check(sys_stream)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stderr");
		}
		Py_XDECREF(sys_isatty);

		if (!Py_FileSystemDefaultEncoding)
			Py_FileSystemDefaultEncoding = codeset;
		else
			free(codeset);
	}
#endif
}
Esempio n. 4
0
static int
modena_model_t_init(modena_model_t *self, PyObject *args, PyObject *kwds)
{
    PyObject *pParameters=NULL, *pModel=NULL;
    char *modelId=NULL;

    static char *kwlist[] = {"model", "modelId", "parameters"};

    if
    (
        !PyArg_ParseTupleAndKeywords
        (
            args, kwds, "|OsO", kwlist, &pModel, &modelId, &pParameters
        )
    )
    {
        return -1;
    }

    if(!pModel)
    {
        PyObject *pName = PyString_FromString("modena.SurrogateModel");
        if(!pName){ Modena_PyErr_Print(); }

        PyObject *pModule = PyImport_Import(pName);
        Py_DECREF(pName);
        if(!pModule){ Modena_PyErr_Print(); }

        PyObject *pDict = PyModule_GetDict(pModule); // Borrowed ref
        if(!pDict){ Modena_PyErr_Print(); }

        pName = PyString_FromString("SurrogateModel");
        if(!pName){ Modena_PyErr_Print(); }

        PyObject *sModel = PyObject_GetItem(pDict, pName);
        Py_DECREF(pName);
        if(!sModel){ Modena_PyErr_Print(); }

        self->pModel = PyObject_CallMethod(sModel, "load", "(z)", modelId);
        Py_DECREF(sModel);
        if(!self->pModel){ Modena_PyErr_Print(); }

        modena_model_get_minMax(self);

        Py_DECREF(pModule);
    }
    else
    {
        Py_INCREF(pModel);
        self->pModel = pModel;

        // Set everything to zero
        self->inputs_minMax_size = 0;
        self->inputs_min = NULL;
        self->inputs_max = NULL;
    }

    //PyObject_Print(self->pModel, stdout, 0);
    //printf("\n");

    PyObject *pOutputs = PyObject_GetAttrString(self->pModel, "outputs");
    if(!pOutputs){ Modena_PyErr_Print(); }
    self->outputs_size = PyDict_Size(pOutputs);
    Py_DECREF(pOutputs);

    PyObject *pMaxArgPos = PyObject_CallMethod
    (
        self->pModel, "inputs_max_argPos", NULL
    );
    if(!pMaxArgPos){ Modena_PyErr_Print(); }
    self->inputs_size = 1 + PyInt_AsSsize_t(pMaxArgPos);
    Py_DECREF(pMaxArgPos);

    self->inherited_inputs_size = 0;

    // Avoiding double indirection in modena_model_call
    // Use modena_function_new to construct, then copy function pointer
    self->mf = modena_function_new(self);
    self->function = self->mf->function;

    self->argPos_used = malloc
    (
        (self->inputs_size + self->inherited_inputs_size)*sizeof(bool)
    );

    modena_model_read_substituteModels(self);

    if(!pParameters)
    {
        pParameters = PyObject_GetAttrString(self->pModel, "parameters");
        if(!pParameters){ Modena_PyErr_Print(); }
    }
    else
    {
        Py_INCREF(pParameters);
    }

    PyObject *pSeq = PySequence_Fast(pParameters, "expected a sequence");
    self->parameters_size = PySequence_Size(pParameters);
    self->parameters = malloc(self->parameters_size*sizeof(double));
    size_t i;
    for(i = 0; i < self->parameters_size; i++)
    {
        self->parameters[i] = PyFloat_AsDouble(PyList_GET_ITEM(pSeq, i));
    }
    Py_DECREF(pSeq);
    Py_DECREF(pParameters);
    if(PyErr_Occurred()){ Modena_PyErr_Print(); }

    return 0;
}
Esempio n. 5
0
extern "C" PyObject* generate_mipmap(PyObject*, PyObject* args)
{
    // Convert some of this Python nonsense to good old C
    PyObject* blTexImage = nullptr; // unchecked... better be right
    PyObject* pymm = nullptr;
    if (PyArg_ParseTuple(args, "OO", &blTexImage, &pymm) && blTexImage && pymm) {
        // Since we can't link with PyHSPlasma easily, let's do some roundabout type-checking
        korlib::pyref classindex = PyObject_CallMethod(pymm, "ClassIndex", "");
        static short mipmap_classindex = plFactory::ClassIndex("plMipmap");

        if (PyLong_AsLong(classindex) != mipmap_classindex) {
            PyErr_SetString(PyExc_TypeError, "generate_mipmap expects a Blender ImageTexture and a plMipmap");
            return nullptr;
        }
    } else {
        PyErr_SetString(PyExc_TypeError, "generate_mipmap expects a Blender ImageTexture and a plMipmap");
        return nullptr;
    }

    // Grab the important stuff
    plMipmap* mipmap = ((pyMipmap*)pymm)->fThis;
    korlib::pyref blImage = korlib::getattr<PyObject*>(blTexImage, "image");
    bool makeMipMap = korlib::getattr<bool>(blTexImage, "use_mipmap");
    bool useAlpha = korlib::getattr<bool>(blTexImage, "use_alpha");
    bool calcAlpha = korlib::getattr<bool>(blTexImage, "use_calculate_alpha");

    // Okay, so, here are the assumptions.
    // We assume that the Korman Python code as already created the mipmap's key and named it appropriately
    // So, if we're mipmapping nb01StoneSquareCobble.tga -> nb01StoneSquareCobble.dds as the key name
    // What we now need to do:
    //     1) Make sure this is a POT texture (if not, call scale on the Blender Image)
    //     2) Check calcAlpha and all that rubbish--det DXT1/DXT5/uncompressed
    //     3) "Create" the plMipmap--this allocates internal buffers and such
    //     4) Loop through the levels, going down through the POTs and fill in the pixel data
    // The reason we do this in C instead of python is because it's a lot of iterating over a lot of
    // floating point data (we have to convert to RGB8888, joy). Should be faster here!
    print("Exporting '%s'...", mipmap->getKey()->getName().cstr());

    // Step 1: Resize to POT (if needed) -- don't rely on GLU for this because it may not suppport
    //         NPOT if we're being run on some kind of dinosaur...
    imagesize_t dimensions = get_image_size(blImage);
    size_t width = pow(2., korlib::log2(static_cast<double>(std::get<0>(dimensions))));
    size_t height = pow(2., korlib::log2(static_cast<double>(std::get<1>(dimensions))));
    if (std::get<0>(dimensions) != width || std::get<1>(dimensions) != height) {
        print("\tImage is not a POT (%dx%d)... resizing to %dx%d", std::get<0>(dimensions),
              std::get<1>(dimensions), width, height);
        resize_image(blImage, width, height);
    }

    // Steps 2+3: Translate flags and pass to plMipmap::Create
    // TODO: PNG compression for lossless images
    uint8_t numLevels = (makeMipMap) ? 0 : 1; // 0 means "you figure it out"
    uint8_t compType = (makeMipMap) ? plBitmap::kDirectXCompression : plBitmap::kUncompressed;
    bool alphaChannel = useAlpha || calcAlpha;
    mipmap->Create(width, height, numLevels, compType, plBitmap::kRGB8888, alphaChannel ? plBitmap::kDXT5 : plBitmap::kDXT1);

    // Step 3.9: Load the image into OpenGL
    gl_loadimage guard(blImage);
    if (!guard.success()) {
        PyErr_SetString(PyExc_RuntimeError, "failed to load image into OpenGL");
        return nullptr;
    }

    // Step 4: Now it's a matter of looping through all the levels and exporting the image
    for (size_t i = 0; i < mipmap->getNumLevels(); ++i) {
        stuff_mip_level(mipmap, i, blImage, calcAlpha);
    }

    Py_RETURN_NONE;
}
Esempio n. 6
0
static PyObject* image_new( PyObject* self, PyObject* args )
{
    ImageObject* imageobj = NULL;
    PyObject* pilobj = NULL;
    PyObject* modestrobj = NULL;
    PyObject* sizeobj = NULL;
    PyObject* datastrobj = NULL;
    unsigned char* data;
    char* modestr;
    int i;
    int pixelsize;
    static PyObject* PILmodule = NULL;
    PyObject* oldpilobj;
    PyObject* nameobj;

    if ( !PyArg_ParseTuple( args, "O:new_image", &pilobj ) )
	return NULL;
    Py_INCREF( pilobj );

    if ( PyString_Check( pilobj ) )
    {
	// object is a string; assume it's a filename and attempt to create the PIL object ourselves;
#if 0
	printf( "fine, creating the PIL object myself\n" );
#endif

	if ( PILmodule == NULL )
	{
	    PyObject* name = PyString_FromString( "Image" );
	    PILmodule = PyImport_Import( name );
	    Py_DECREF( name );
	    if ( PILmodule == NULL )
	    {
		PyErr_SetString( ImageError, "failed to find PIL module" );
		goto error;
	    }
	}

	nameobj = pilobj;
	
	oldpilobj = pilobj;
	pilobj = PyObject_CallMethod( PILmodule, "open", "O", pilobj );
	Py_DECREF( oldpilobj );
	if ( pilobj == NULL )
	    goto error;
	Py_INCREF( pilobj );
    }
    else
	nameobj = Py_None;
    
    imageobj = PyObject_New( ImageObject, &ImageType );

    Py_INCREF( nameobj );
    imageobj->filename = nameobj;

    modestrobj = PyObject_GetAttrString( pilobj, "mode" );
    modestr = PyString_AsString( modestrobj );
    if ( strcmp( modestr, "RGBA" ) == 0 )
    {
	pixelsize = 4;
    }
    else if ( strcmp( modestr, "RGB" ) == 0 )
    {
	pixelsize = 3;
    }
    else
    {
#if 0
	printf( "attempting conversion to RGB\n" );
#endif
	
	// need to convert image to RGB
	oldpilobj = pilobj;
	pilobj = PyObject_CallMethod( pilobj, "convert", "s", "RGB" );
	Py_DECREF( oldpilobj );
	if ( pilobj == NULL )
	    goto error;
	Py_INCREF( pilobj );

	pixelsize = 3;
    }

    sizeobj = PyObject_GetAttrString( pilobj, "size" );
    if ( !PyTuple_Check( sizeobj ) || PyTuple_Size( sizeobj ) != 2 )
    {
	PyErr_SetString( ImageError, "size attribute is wrong wrong wrong" );
	Py_DECREF( sizeobj );
	Py_DECREF( pilobj );
	return NULL;
    }

    imageobj->w = PyInt_AsLong( PyTuple_GetItem( sizeobj, 0 ) );
    imageobj->h = PyInt_AsLong( PyTuple_GetItem( sizeobj, 1 ) );
    if ( imageobj->w < 1 || imageobj->h < 1 )
    {
	PyErr_Format( ImageError, "PIL says image size is %d x %d; that can't be right",
		      imageobj->w, imageobj->h );
	goto error;
    }
#if 0
    printf( "image is %d x %d\n", imageobj->w, imageobj->h );
#endif

    imageobj->tw = 1;
    while( imageobj->tw < imageobj->w )
    {
	imageobj->tw <<= 1;
	if ( imageobj->tw <= 0 )
	{
	    PyErr_SetString( ImageError, "image is too wide" );
	    goto error;
	}
    }
    imageobj->th = 1;
    while( imageobj->th < imageobj->h )
    {
	imageobj->th <<= 1;
	if ( imageobj->th <= 0 )
	{
	    PyErr_SetString( ImageError, "image is too tall" );
	    goto error;
	}
    }

#if 0
    printf( "texture must be %d x %d\n", imageobj->tw, imageobj->th );
#endif

    datastrobj = PyObject_CallMethod( pilobj, "tostring", NULL );
    if ( datastrobj == NULL )
	goto error;
    PyString_AsStringAndSize( datastrobj, (char**)&data, &i );
    if ( i != imageobj->w * imageobj->h * pixelsize )
    {
	PyErr_Format( ImageError, "got %d bytes of image data; expected %d", i,
		      imageobj->w * imageobj->h * pixelsize );
	goto error;
    }

    imageobj->data = malloc( imageobj->tw * imageobj->th * pixelsize );
    for ( i = 0; i < imageobj->h; ++i )
	memcpy( imageobj->data + i * (pixelsize * imageobj->tw),
		data + i * (pixelsize * imageobj->w),
		pixelsize*imageobj->w );
    if ( imageobj->w < imageobj->tw )
    {
	for ( i = 0; i < imageobj->h; ++i )
	    memcpy( imageobj->data + i * (pixelsize * imageobj->tw) + pixelsize * imageobj->w,
		    imageobj->data + i * (pixelsize * imageobj->tw) + pixelsize * (imageobj->w-1),
		    pixelsize );
    }
    if ( imageobj->h < imageobj->th )
    {
	memcpy( imageobj->data + imageobj->tw * pixelsize * imageobj->h,
		imageobj->data + imageobj->tw * pixelsize * (imageobj->h-1),
		imageobj->tw * pixelsize );
    }
		    
    
    imageobj->has_alpha = (pixelsize == 4);
    imageobj->has_texture = 0;
    imageobj->tright = ((double)imageobj->w) / imageobj->tw;
    imageobj->tbottom = ((double)imageobj->h) / imageobj->th;

    Py_DECREF( datastrobj );
    Py_DECREF( sizeobj );
    Py_DECREF( modestrobj );
    Py_DECREF( pilobj );
    
    return (PyObject*)imageobj;

 error:
    if ( imageobj )
	PyObject_Del( imageobj );
    Py_XDECREF( modestrobj );
    Py_XDECREF( sizeobj );
    Py_XDECREF( datastrobj );
    Py_XDECREF( pilobj );
    return NULL;
}
Esempio n. 7
0
static PyObject *
subprocess_fork_exec(PyObject* self, PyObject *args)
{
    PyObject *gc_module = NULL;
    PyObject *executable_list, *py_close_fds, *py_fds_to_keep;
    PyObject *env_list, *preexec_fn;
    PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
    PyObject *preexec_fn_args_tuple = NULL;
    int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
    int errpipe_read, errpipe_write, close_fds, restore_signals;
    int call_setsid;
    PyObject *cwd_obj, *cwd_obj2;
    const char *cwd;
    pid_t pid;
    int need_to_reenable_gc = 0;
    char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
    Py_ssize_t arg_num, num_fds_to_keep;

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

    close_fds = PyObject_IsTrue(py_close_fds);
    if (close_fds && errpipe_write < 3) {  /* precondition */
        PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
        return NULL;
    }
    num_fds_to_keep = PySequence_Length(py_fds_to_keep);
    if (num_fds_to_keep < 0) {
        PyErr_SetString(PyExc_ValueError, "bad fds_to_keep");
        return NULL;
    }

    /* We need to call gc.disable() when we'll be calling preexec_fn */
    if (preexec_fn != Py_None) {
        PyObject *result;
        gc_module = PyImport_ImportModule("gc");
        if (gc_module == NULL)
            return NULL;
        result = PyObject_CallMethod(gc_module, "isenabled", NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        need_to_reenable_gc = PyObject_IsTrue(result);
        Py_DECREF(result);
        if (need_to_reenable_gc == -1) {
            Py_DECREF(gc_module);
            return NULL;
        }
        result = PyObject_CallMethod(gc_module, "disable", NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        Py_DECREF(result);
    }

    exec_array = _PySequence_BytesToCharpArray(executable_list);
    if (!exec_array)
        return NULL;

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

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

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

    if (preexec_fn != Py_None) {
        preexec_fn_args_tuple = PyTuple_New(0);
        if (!preexec_fn_args_tuple)
            goto cleanup;
        _PyImport_AcquireLock();
    }

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

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

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

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

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

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

    /* Reenable gc in the parent process (or if fork failed). */
    if (need_to_reenable_gc && _enable_gc(gc_module)) {
        Py_XDECREF(gc_module);
        return NULL;
    }
    Py_XDECREF(preexec_fn_args_tuple);
    Py_XDECREF(gc_module);

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

    return PyLong_FromPid(pid);

cleanup:
    if (envp)
        _Py_FreeCharPArray(envp);
    if (argv)
        _Py_FreeCharPArray(argv);
    _Py_FreeCharPArray(exec_array);
    Py_XDECREF(converted_args);
    Py_XDECREF(fast_args);
    Py_XDECREF(preexec_fn_args_tuple);

    /* Reenable gc if it was disabled. */
    if (need_to_reenable_gc)
        _enable_gc(gc_module);
    Py_XDECREF(gc_module);
    return NULL;
}
Esempio n. 8
0
void start_watcher(int i, struct uwsgi_socket* uwsgi_sock) {
        PyObject_CallMethod(ugevent.watchers[i], "start", "Oli", uwsgi_gevent_main,(long)uwsgi_sock, i);
}
Esempio n. 9
0
/*@C
  PetscPythonInitialize - Initialize Python and import petsc4py.

   Input Parameter:
+  pyexe - path to the Python interpreter executable, or NULL.
-  pylib - full path to the Python dynamic library, or NULL.

  Level: intermediate

.keywords: Python

@*/
PetscErrorCode  PetscPythonInitialize(const char pyexe[],const char pylib[])
{
  PyObject       *module = 0;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  if (PetscBeganPython) PetscFunctionReturn(0);
  /* Python executable */
  if (pyexe && pyexe[0] != 0) {
    ierr = PetscStrncpy(PetscPythonExe,pyexe,sizeof(PetscPythonExe));CHKERRQ(ierr);
  } else {
    ierr = PetscPythonFindExecutable(PetscPythonExe);CHKERRQ(ierr);
  }
  /* Python dynamic library */
  if (pylib && pylib[0] != 0) {
    ierr = PetscStrncpy(PetscPythonLib,pylib,sizeof(PetscPythonLib));CHKERRQ(ierr);
  } else {
    ierr = PetscPythonFindLibrary(PetscPythonExe,PetscPythonLib);CHKERRQ(ierr);
  }
  /* dynamically load Python library */
  ierr = PetscPythonLoadLibrary(PetscPythonLib);CHKERRQ(ierr);
  /* initialize Python */
  PetscBeganPython = PETSC_FALSE;
  if (!Py_IsInitialized()) {
    static PetscBool registered = PETSC_FALSE;
    const char       *py_version;
    PyObject         *sys_path;
    char             path[PETSC_MAX_PATH_LEN] = { 0 };

    /* initialize Python */
    Py_InitializeEx(0); /* 0: do not install signal handlers */
    /*  build 'sys.argv' list */
    py_version = Py_GetVersion();
    if (py_version[0] == '2') {
      int argc = 0; char **argv = 0;
      ierr = PetscGetArgs(&argc,&argv);CHKERRQ(ierr);
      PySys_SetArgv(argc,argv);
    }
    if (py_version[0] == '3') {
      /* XXX 'argv' is type 'wchar_t**' */
      PySys_SetArgv(0,NULL);
    }
    /* add PETSC_LIB_DIR in front of 'sys.path' */
    sys_path = PySys_GetObject("path");
    if (sys_path) {
      ierr = PetscStrreplace(PETSC_COMM_SELF,"${PETSC_LIB_DIR}",path,sizeof(path));CHKERRQ(ierr);
      Py_DecRef(PyObject_CallMethod(sys_path,"insert","is",(int)0,(char*)path));
    }
    /* register finalizer */
    if (!registered) {
      ierr = PetscRegisterFinalize(PetscPythonFinalize);CHKERRQ(ierr);

      registered = PETSC_TRUE;
    }
    PetscBeganPython = PETSC_TRUE;
  }
  /* import 'petsc4py.PETSc' module */
  module = PyImport_ImportModule("petsc4py.PETSc");
  if (module) {
    ierr = PetscInfo(0,"Python: successfully imported  module 'petsc4py.PETSc'\n");CHKERRQ(ierr);

    Py_DecRef(module); module = 0;
  } else {
    PetscPythonPrintError();
    SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it\n");
  }
  PetscFunctionReturn(0);
}
Esempio n. 10
0
PyObject *
Reference_get_object(Reference *self)
{
    return PyObject_CallMethod((PyObject *) self, "peel", NULL);
}
Esempio n. 11
0
void SlowScan::playFile(PyObject* file_path)
{
	
	// Call the function "PrintText" in PythonLand.
    pValue = PyObject_CallMethod(pInstance, "playFile", "(O)", file_path);
}
Esempio n. 12
0
File: buffer.c Progetto: Benj1/numpy
NPY_NO_EXPORT PyArray_Descr*
_descriptor_from_pep3118_format(char *s)
{
    char *buf, *p;
    int in_name = 0;
    int obtained;
    PyObject *descr;
    PyObject *str;
    PyObject *_numpy_internal;

    if (s == NULL) {
        return PyArray_DescrNewFromType(NPY_BYTE);
    }

    /* Fast path */
    obtained = _descriptor_from_pep3118_format_fast(s, &descr);
    if (obtained) {
        return (PyArray_Descr*)descr;
    }

    /* Strip whitespace, except from field names */
    buf = malloc(strlen(s) + 1);
    if (buf == NULL) {
        return NULL;
    }
    p = buf;
    while (*s != '\0') {
        if (*s == ':') {
            in_name = !in_name;
            *p = *s;
            p++;
        }
        else if (in_name || !NumPyOS_ascii_isspace(*s)) {
            *p = *s;
            p++;
        }
        s++;
    }
    *p = '\0';

    str = PyUString_FromStringAndSize(buf, strlen(buf));
    if (str == NULL) {
        free(buf);
        return NULL;
    }

    /* Convert */
    _numpy_internal = PyImport_ImportModule("numpy.core._internal");
    if (_numpy_internal == NULL) {
        Py_DECREF(str);
        free(buf);
        return NULL;
    }
    descr = PyObject_CallMethod(
        _numpy_internal, "_dtype_from_pep3118", "O", str);
    Py_DECREF(str);
    Py_DECREF(_numpy_internal);
    if (descr == NULL) {
        PyErr_Format(PyExc_ValueError,
                     "'%s' is not a valid PEP 3118 buffer format string", buf);
        free(buf);
        return NULL;
    }
    if (!PyArray_DescrCheck(descr)) {
        PyErr_Format(PyExc_RuntimeError,
                     "internal error: numpy.core._internal._dtype_from_pep3118 "
                     "did not return a valid dtype, got %s", buf);
        Py_DECREF(descr);
        free(buf);
        return NULL;
    }
    free(buf);
    return (PyArray_Descr*)descr;
}
Esempio n. 13
0
static PyObject *_YIELD_FROM( struct Nuitka_GeneratorObject *generator, PyObject *value )
{
    // This is the value, propagated back and forth the sub-generator and the
    // yield from consumer.
    PyObject *send_value = Py_None;

    while( 1 )
    {
        // Send iteration value to the sub-generator, which may be a CPython
        // generator object, something with an iterator next, or a send method,
        // where the later is only required if values other than "None" need to
        // be passed in.
        PyObject *retval;

        // Exception, was thrown into us, need to send that to sub-generator.
        if ( generator->m_exception_type )
        {
            // The yielding generator is being closed, but we also are tasked to
            // immediately close the currently running sub-generator.
            if ( EXCEPTION_MATCH_BOOL_SINGLE( generator->m_exception_type, PyExc_GeneratorExit ) )
            {
                PyObject *close_method = PyObject_GetAttr( value, const_str_plain_close );

                if ( close_method )
                {
                    PyObject *close_value = PyObject_Call( close_method, const_tuple_empty, NULL );
                    Py_DECREF( close_method );

                    if (unlikely( close_value == NULL ))
                    {
                        return NULL;
                    }

                    Py_DECREF( close_value );
                }
                else
                {
                    PyObject *error = GET_ERROR_OCCURRED();

                    if ( error != NULL && !EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_AttributeError ) )
                    {
                        PyErr_WriteUnraisable( (PyObject *)value );
                    }
                }

                RAISE_GENERATOR_EXCEPTION( generator );

                return NULL;
            }

            PyObject *throw_method = PyObject_GetAttr( value, const_str_plain_throw );

            if ( throw_method )
            {
                retval = PyObject_CallFunctionObjArgs( throw_method, generator->m_exception_type, generator->m_exception_value, generator->m_exception_tb, NULL );
                Py_DECREF( throw_method );

                if (unlikely( send_value == NULL ))
                {
                    if ( EXCEPTION_MATCH_BOOL_SINGLE( GET_ERROR_OCCURRED(), PyExc_StopIteration ) )
                    {
                        return ERROR_GET_STOP_ITERATION_VALUE();
                    }

                    return NULL;
                }

                generator->m_exception_type = NULL;
                generator->m_exception_value = NULL;
                generator->m_exception_tb = NULL;
            }
            else if ( EXCEPTION_MATCH_BOOL_SINGLE( GET_ERROR_OCCURRED(), PyExc_AttributeError ) )
            {
                CLEAR_ERROR_OCCURRED();

                RAISE_GENERATOR_EXCEPTION( generator );

                return NULL;
            }
            else
            {
                assert( ERROR_OCCURRED() );

                Py_CLEAR( generator->m_exception_type );
                Py_CLEAR( generator->m_exception_value );
                Py_CLEAR( generator->m_exception_tb );

                return NULL;
            }

        }
        else if ( PyGen_CheckExact( value ) )
        {
            retval = PyGen_Send( (PyGenObject *)value, Py_None );
        }
        else if ( send_value == Py_None && Py_TYPE( value )->tp_iternext != NULL )
        {
            retval = Py_TYPE( value )->tp_iternext( value );
        }
        else
        {
            // Bug compatibility here, before 3.3 tuples were unrolled in calls, which is what
            // PyObject_CallMethod does.
#if PYTHON_VERSION >= 340
            retval = PyObject_CallMethodObjArgs( value, const_str_plain_send, send_value, NULL );
#else
            retval = PyObject_CallMethod( value, (char *)"send", (char *)"O", send_value );
#endif
        }

        // Check the sub-generator result
        if ( retval == NULL )
        {
            PyObject *error = GET_ERROR_OCCURRED();
            if ( error == NULL )
            {
                return INCREASE_REFCOUNT( Py_None ) ;
            }

            // The sub-generator has given an exception. In case of
            // StopIteration, we need to check the value, as it is going to be
            // the expression value of this "yield from", and we are done. All
            // other errors, we need to raise.
            if (likely( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration ) ))
            {
                return ERROR_GET_STOP_ITERATION_VALUE();
            }

            return NULL;
        }
        else
        {
            generator->m_yielded = retval;

#if PYTHON_VERSION >= 350
            generator->m_yieldfrom = value;
#endif
            // Return to the calling context.
            swapFiber( &generator->m_yielder_context, &generator->m_caller_context );

#if PYTHON_VERSION >= 350
            generator->m_yieldfrom = NULL;
#endif

            send_value = generator->m_yielded;

            CHECK_OBJECT( send_value );
        }
    }
}
Esempio n. 14
0
		PyObject *ret = PyObject_CallMethod(watcher, "start", "OO", current, watcher);
        	if (!ret) {
                	stop_the_watchers_and_clear
                	return -1;
        	}
        	Py_DECREF(ret);

        	ret = PyObject_CallMethod(timer, "start", "OO", current, timer);
        	if (!ret) {
                	stop_the_watchers_and_clear
                	return -1;
        	}
        	Py_DECREF(ret);

        	ret = PyObject_CallMethod(ugevent.hub, "switch", NULL);
		wsgi_req->switches++;
        	if (!ret) {
                	stop_the_watchers_and_clear
                	return -1;
        	}
        	Py_DECREF(ret);

        	if (ret == timer) {
                	stop_the_watchers_and_clear
                	return 0;
        	}

		UWSGI_RELEASE_GIL;	
                ssize_t rlen = read(wsgi_req->poll.fd, tmp_buf+*tmp_pos, remains);
                if (rlen <= 0) {
Esempio n. 15
0
//-------------------------------------------------------------------------------------
PyObject* Map::__py_get(PyObject* self, PyObject* args)
{
	return PyObject_CallMethod(static_cast<Map*>(self)->pyDict_, 
		const_cast<char*>("get"), const_cast<char*>("O"), args);
}
Esempio n. 16
0
PyObject *
xid_recover(PyObject *conn)
{
    PyObject *rv = NULL;
    PyObject *curs = NULL;
    PyObject *xids = NULL;
    xidObject *xid = NULL;
    PyObject *recs = NULL;
    PyObject *rec = NULL;
    PyObject *item = NULL;
    PyObject *tmp;
    Py_ssize_t len, i;

    /* curs = conn.cursor()
     * (sort of. Use the real cursor in case the connection returns
     * somenthing non-dbapi -- see ticket #114) */
    if (!(curs = PyObject_CallFunctionObjArgs(
        (PyObject *)&cursorType, conn, NULL))) { goto exit; }

    /* curs.execute(...) */
    if (!(tmp = PyObject_CallMethod(curs, "execute", "s",
        "SELECT gid, prepared, owner, database FROM pg_prepared_xacts")))
    {
        goto exit;
    }
    Py_DECREF(tmp);

    /* recs = curs.fetchall() */
    if (!(recs = PyObject_CallMethod(curs, "fetchall", NULL))) { goto exit; }

    /* curs.close() */
    if (!(tmp = PyObject_CallMethod(curs, "close", NULL))) { goto exit; }
    Py_DECREF(tmp);

    /* Build the list with return values. */
    if (0 > (len = PySequence_Size(recs))) { goto exit; }
    if (!(xids = PyList_New(len))) { goto exit; }

    /* populate the xids list */
    for (i = 0; i < len; ++i) {
        if (!(rec = PySequence_GetItem(recs, i))) { goto exit; }

        /* Get the xid with the XA triple set */
        if (!(item = PySequence_GetItem(rec, 0))) { goto exit; }
        if (!(xid = xid_from_string(item))) { goto exit; }
        Py_CLEAR(item);

        /* set xid.prepared */
        Py_CLEAR(xid->prepared);
        if (!(xid->prepared = PySequence_GetItem(rec, 1))) { goto exit; }

        /* set xid.owner */
        Py_CLEAR(xid->owner);
        if (!(xid->owner = PySequence_GetItem(rec, 2))) { goto exit; }

        /* set xid.database */
        Py_CLEAR(xid->database);
        if (!(xid->database = PySequence_GetItem(rec, 3))) { goto exit; }

        /* xid finished: add it to the returned list */
        PyList_SET_ITEM(xids, i, (PyObject *)xid);
        xid = NULL;  /* ref stolen */

        Py_CLEAR(rec);
    }

    /* set the return value. */
    rv = xids;
    xids = NULL;

exit:
    Py_XDECREF(xids);
    Py_XDECREF(xid);
    Py_XDECREF(curs);
    Py_XDECREF(recs);
    Py_XDECREF(rec);
    Py_XDECREF(item);

    return rv;
}
Esempio n. 17
0
/*
 *
 * Tests for and converts a Python datetime.datetime or datetime.date
 * object into a NumPy pandas_datetimestruct.  Uses tzinfo (if present)
 * to convert to UTC time.
 *
 * While the C API has PyDate_* and PyDateTime_* functions, the following
 * implementation just asks for attributes, and thus supports
 * datetime duck typing. The tzinfo time zone conversion would require
 * this style of access anyway.
 *
 * Returns -1 on error, 0 on success, and 1 (with no error set)
 * if obj doesn't have the needed date or datetime attributes.
 */
int convert_pydatetime_to_datetimestruct(PyObject *obj,
                                         pandas_datetimestruct *out) {
    PyObject *tmp;
    int isleap;

    /* Initialize the output to all zeros */
    memset(out, 0, sizeof(pandas_datetimestruct));
    out->month = 1;
    out->day = 1;

    /* Need at least year/month/day attributes */
    if (!PyObject_HasAttrString(obj, "year") ||
        !PyObject_HasAttrString(obj, "month") ||
        !PyObject_HasAttrString(obj, "day")) {
        return 1;
    }

    /* Get the year */
    tmp = PyObject_GetAttrString(obj, "year");
    if (tmp == NULL) {
        return -1;
    }
    out->year = PyInt_AsLong(tmp);
    if (out->year == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the month */
    tmp = PyObject_GetAttrString(obj, "month");
    if (tmp == NULL) {
        return -1;
    }
    out->month = PyInt_AsLong(tmp);
    if (out->month == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the day */
    tmp = PyObject_GetAttrString(obj, "day");
    if (tmp == NULL) {
        return -1;
    }
    out->day = PyInt_AsLong(tmp);
    if (out->day == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Validate that the month and day are valid for the year */
    if (out->month < 1 || out->month > 12) {
        goto invalid_date;
    }
    isleap = is_leapyear(out->year);
    if (out->day < 1 ||
        out->day > days_per_month_table[isleap][out->month - 1]) {
        goto invalid_date;
    }

    /* Check for time attributes (if not there, return success as a date) */
    if (!PyObject_HasAttrString(obj, "hour") ||
        !PyObject_HasAttrString(obj, "minute") ||
        !PyObject_HasAttrString(obj, "second") ||
        !PyObject_HasAttrString(obj, "microsecond")) {
        return 0;
    }

    /* Get the hour */
    tmp = PyObject_GetAttrString(obj, "hour");
    if (tmp == NULL) {
        return -1;
    }
    out->hour = PyInt_AsLong(tmp);
    if (out->hour == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the minute */
    tmp = PyObject_GetAttrString(obj, "minute");
    if (tmp == NULL) {
        return -1;
    }
    out->min = PyInt_AsLong(tmp);
    if (out->min == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the second */
    tmp = PyObject_GetAttrString(obj, "second");
    if (tmp == NULL) {
        return -1;
    }
    out->sec = PyInt_AsLong(tmp);
    if (out->sec == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the microsecond */
    tmp = PyObject_GetAttrString(obj, "microsecond");
    if (tmp == NULL) {
        return -1;
    }
    out->us = PyInt_AsLong(tmp);
    if (out->us == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    if (out->hour < 0 || out->hour >= 24 || out->min < 0 || out->min >= 60 ||
        out->sec < 0 || out->sec >= 60 || out->us < 0 || out->us >= 1000000) {
        goto invalid_time;
    }

    /* Apply the time zone offset if it exists */
    if (PyObject_HasAttrString(obj, "tzinfo")) {
        tmp = PyObject_GetAttrString(obj, "tzinfo");
        if (tmp == NULL) {
            return -1;
        }
        if (tmp == Py_None) {
            Py_DECREF(tmp);
        } else {
            PyObject *offset;
            int seconds_offset, minutes_offset;

            /* The utcoffset function should return a timedelta */
            offset = PyObject_CallMethod(tmp, "utcoffset", "O", obj);
            if (offset == NULL) {
                Py_DECREF(tmp);
                return -1;
            }
            Py_DECREF(tmp);

            /*
             * The timedelta should have a function "total_seconds"
             * which contains the value we want.
             */
            tmp = PyObject_CallMethod(offset, "total_seconds", "");
            if (tmp == NULL) {
                return -1;
            }
            seconds_offset = PyInt_AsLong(tmp);
            if (seconds_offset == -1 && PyErr_Occurred()) {
                Py_DECREF(tmp);
                return -1;
            }
            Py_DECREF(tmp);

            /* Convert to a minutes offset and apply it */
            minutes_offset = seconds_offset / 60;

            add_minutes_to_datetimestruct(out, -minutes_offset);
        }
    }

    return 0;

invalid_date:
    PyErr_Format(PyExc_ValueError,
                 "Invalid date (%d,%d,%d) when converting to NumPy datetime",
                 (int)out->year, (int)out->month, (int)out->day);
    return -1;

invalid_time:
    PyErr_Format(PyExc_ValueError,
                 "Invalid time (%d,%d,%d,%d) when converting "
                 "to NumPy datetime",
                 (int)out->hour, (int)out->min, (int)out->sec, (int)out->us);
    return -1;
}
Esempio n. 18
0
int main(void)
{
	Py_Initialize();
	if(!Py_IsInitialized())
		return -1;
	
	PyRun_SimpleString("import sys");
	//where you put your py file
	PyRun_SimpleString("sys.path.append('../')");
	//Import 
	PyObject* pModule = PyImport_ImportModule("pc");//no *.py
	if(!pModule)
	{
		printf("can't open python file!\n");
		return -1;
	}
	//Dict module
	PyObject* pDict = PyModule_GetDict(pModule);
	if(!pDict)
	{
		printf("can't find dictionary.\n");
		return -1;
	}
	printDict(pDict);

	PyObject *pFunHi = PyDict_GetItemString(pDict, "sayHi");
	PyObject_CallFunction(pFunHi, "s", "yourname");// @para1: obj, @para2: name
	//release
	Py_DECREF(pFunHi);
	
	//Contruct a obj , call it's function
	//Second Class
	PyObject *pClassSecond = PyDict_GetItemString(pDict , "Second");
	if(!pClassSecond)
	{
		printf("can't find second class.\n");
		return -1;
	}
	//Person Class
	PyObject *pClassPerson = PyDict_GetItemString(pDict, "Person");
	if(!pClassPerson)
	{
		printf("can't find Person class.\n");
		return -1;
	}
	//Construct Second Instance
	PyObject* pInstanceSecond = PyInstance_New(pClassSecond, NULL, NULL);
	if(!pInstanceSecond)
	{
		printf("can't create second instance.\n");
		return -1;
	}
	//Construct Person Instance
	PyObject *pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);
	if(!pInstancePerson)
	{
		printf("can't create Person instance.\n");
		return -1;
	}

	//pass Person Instance to Second Instance 
	PyObject_CallMethod(pInstanceSecond, "invoke", "O", pInstancePerson);
	PyObject_CallMethod(pInstanceSecond, "method2", "O", pInstancePerson);

	//call execute a py file
	PyRun_SimpleString("exec(compile(open('./1.py').read(),'1.py', 'exec'),locals(), globals())");
	//release
	Py_DECREF(pInstanceSecond);
	Py_DECREF(pInstancePerson);
	Py_DECREF(pClassSecond);
	Py_DECREF(pClassPerson);
	Py_DECREF(pModule);
	Py_Finalize();

	return 0;
}
Esempio n. 19
0
NPY_NO_EXPORT int
PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
                              PyArray_Descr **out_dtype, int string_type)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
    Py_buffer buffer_view;

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* See if it's a python None */
    if (obj == Py_None) {
        dtype = PyArray_DescrFromType(NPY_OBJECT);
        if (dtype == NULL) {
            goto fail;
        }
        Py_INCREF(dtype);
        goto promote_types;
    }
    /* Check if it's a NumPy scalar */
    else if (PyArray_IsScalar(obj, Generic)) {
        if (!string_type) {
            dtype = PyArray_DescrFromScalar(obj);
            if (dtype == NULL) {
                goto fail;
            }
        }
        else {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        if (string_type) {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* PEP 3118 buffer interface */
    if (PyObject_CheckBuffer(obj) == 1) {
        memset(&buffer_view, 0, sizeof(Py_buffer));
        if (PyObject_GetBuffer(obj, &buffer_view,
                               PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
            PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

            PyErr_Clear();
            dtype = _descriptor_from_pep3118_format(buffer_view.format);
            PyBuffer_Release(&buffer_view);
            if (dtype) {
                goto promote_types;
            }
        }
        else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
                 PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

            PyErr_Clear();
            dtype = PyArray_DescrNewFromType(NPY_VOID);
            dtype->elsize = buffer_view.itemsize;
            PyBuffer_Release(&buffer_view);
            goto promote_types;
        }
        else {
            PyErr_Clear();
        }
    }

    /* The array interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
#if defined(NPY_PY3K)
            PyObject *tmp = NULL;
#endif
            typestr = PyDict_GetItemString(ip, "typestr");
#if defined(NPY_PY3K)
            /* Allow unicode type strings */
            if (PyUnicode_Check(typestr)) {
                tmp = PyUnicode_AsASCIIString(typestr);
                typestr = tmp;
            }
#endif
            if (typestr && PyBytes_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr));
#if defined(NPY_PY3K)
                if (tmp == typestr) {
                    Py_DECREF(tmp);
                }
#endif
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The array struct interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array__");
    if (ip != NULL) {
        Py_DECREF(ip);
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
     */
    if (maxdims == 0 || !PySequence_Check(obj)) {
        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /* Recursive case */
    size = PySequence_Size(obj);
    if (size < 0) {
        goto fail;
    }
    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        int res;
        ip = PySequence_GetItem(obj, i);
        if (ip == NULL) {
            goto fail;
        }
        res = PyArray_DTypeFromObjectHelper(ip, maxdims - 1,
                                            out_dtype, string_type);
        if (res < 0) {
            Py_DECREF(ip);
            goto fail;
        }
        else if (res > 0) {
            Py_DECREF(ip);
            return res;
        }
        Py_DECREF(ip);
    }

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        if (!string_type && dtype->type_num == NPY_STRING) {
            Py_DECREF(dtype);
            return RETRY_WITH_STRING;
        }
        if (!string_type && dtype->type_num == NPY_UNICODE) {
            Py_DECREF(dtype);
            return RETRY_WITH_UNICODE;
        }
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_UNICODE &&
                (*out_dtype)->type_num != NPY_UNICODE) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_UNICODE;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_STRING &&
                (*out_dtype)->type_num != NPY_STRING) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_STRING;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}

#undef RETRY_WITH_STRING
#undef RETRY_WITH_UNICODE

/* new reference */
NPY_NO_EXPORT PyArray_Descr *
_array_typedescr_fromstr(char *c_str)
{
    PyArray_Descr *descr = NULL;
    PyObject *stringobj = PyString_FromString(c_str);

    if (stringobj == NULL) {
        return NULL;
    }
    if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) {
        Py_DECREF(stringobj);
        return NULL;
    }
    Py_DECREF(stringobj);
    return descr;
}


NPY_NO_EXPORT char *
index2ptr(PyArrayObject *mp, npy_intp i)
{
    npy_intp dim0;

    if (PyArray_NDIM(mp) == 0) {
        PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed");
        return NULL;
    }
    dim0 = PyArray_DIMS(mp)[0];
    if (check_and_adjust_index(&i, dim0, 0) < 0)
        return NULL;
    if (i == 0) {
        return PyArray_DATA(mp);
    }
    return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0];
}
Esempio n. 20
0
ofxPythonObject ofxPythonObject::method(const string &method_name)
{
	return make_object_owned(
		PyObject_CallMethod(get()->obj,noconststring(method_name),NULL));
}
Esempio n. 21
0
static PyObject *
LDAPEntry_rename(LDAPEntry *self, PyObject *args, PyObject *kwds) {
	int rc;
	char *newparent_str, *newrdn_str, *olddn_str;
	PyObject *newdn, *newparent, *newrdn;
	PyObject *tmp;
	char *kwlist[] = {"newdn", NULL};

	/* Client must be set. */
	if (self->client == NULL) {
		PyErr_SetString(PyExc_AttributeError, "LDAPClient is not set.");
		return NULL;
	}
	/* Client must be connected. */
	if (!self->client->connected) {
		PyObject *ldaperror = get_error("NotConnected");
		PyErr_SetString(ldaperror, "Client has to connect to the server first.");
		Py_DECREF(ldaperror);
		return NULL;
	}

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &newdn)) {
		PyErr_SetString(PyExc_AttributeError, "Wrong parameter.");
		return NULL;
	}

	/* Save old dn string. */
	tmp = PyObject_Str(self->dn);
	olddn_str = PyObject2char(tmp);
	Py_DECREF(tmp);
	if (olddn_str == NULL) return NULL;

	/* Validate and set new LDAP DN. */
	if (LDAPEntry_setDN(self, newdn, NULL) != 0) return NULL;

	/* Get rdn and parent strings. */
	newrdn = PyObject_CallMethod(self->dn, "get_rdn", "(i)", 0);
	newparent = PyObject_CallMethod(self->dn, "get_ancestors", NULL);
	if (newrdn == NULL || newparent == NULL) return NULL;

	newrdn_str = PyObject2char(newrdn);
	newparent_str = PyObject2char(newparent);
	Py_DECREF(newrdn);
	Py_DECREF(newparent);

	rc = ldap_rename_s(self->client->ld, olddn_str, newrdn_str, newparent_str, 1, NULL, NULL);
	if (rc != LDAP_SUCCESS) {
		//TODO Proper errors
		PyObject *ldaperror = get_error("LDAPError");
		PyErr_SetString(ldaperror, ldap_err2string(rc));
		Py_DECREF(ldaperror);
		free(olddn_str);
		free(newrdn_str);
		free(newparent_str);
		return NULL;
	}
	free(olddn_str);
	free(newrdn_str);
	free(newparent_str);
	return Py_None;
}
Esempio n. 22
0
// Returns a new string
MCHAR * pythonExceptionTraceback( bool clearException )
{
    /*
    	import traceback
    	return '\n'.join(traceback.format_exc()).encode('ascii','replace')
    */
    MCHAR * ret = 0;
    bool success = false;

    PyObject * type, * value, * traceback;
    /* Save the current exception */
    PyErr_Fetch(&type, &value, &traceback);
    if( type ) {

        PyObject * traceback_module = PyImport_ImportModule("traceback");
        if (traceback_module) {

            /* Call the traceback module's format_exception function, which returns a list */
            PyObject * traceback_list = PyObject_CallMethod(traceback_module, "format_exception", "OOO", type, value ? value : Py_None, traceback ? traceback : Py_None);
            if( traceback_list ) {

                PyObject * separator = PyString_FromString("");
                if( separator ) {

                    PyObject * retUni = PyUnicode_Join(separator, traceback_list);
                    if( retUni ) {
#ifdef UNICODE
                        ret = _tcsdup( PyUnicode_AsUnicode(retUni) );
#else
                        PyObject * retAscii = PyUnicode_AsEncodedString(retUni, "ascii", "replace");
                        if( retAscii ) {
                            Py_ssize_t len = 0;
                            char * tmp;
                            if( PyString_AsStringAndSize( retAscii, &tmp, &len ) != -1 ) {
                                ret = strdup( tmp );//, len );
                                success = true;
                            } else {
                                ret = _tcsdup( _T("Uhoh, failed to get pointer to ascii representation of the exception") );
                                success = false;
                            }
                            Py_DECREF( retAscii );
                        } else {
                            ret = _tcsdup( _T("Uhoh, encoding exception to ascii failed") );
                            success = false;
                        }
#endif
                        Py_DECREF(retUni);

                    } else
                        ret = _tcsdup(_T("PyUnicode_Join failed"));

                    Py_DECREF(separator);
                } else
                    ret = _tcsdup(_T("PyUnicode_FromString failed"));

                Py_DECREF(traceback_list);
            } else
                ret = _tcsdup(_T("Failure calling traceback.format_exception"));

            Py_DECREF(traceback_module);
        } else
            ret = _tcsdup(_T("Unable to load the traceback module, can't get exception text"));
    } else
        ret = _tcsdup(_T("pythonExceptionTraceback called, but no exception set"));

    if( clearException ) {
        Py_DECREF(type);
        Py_XDECREF(value);
        Py_XDECREF(traceback);
    } else
        PyErr_Restore(type,value,traceback);

    return ret;
}
Esempio n. 23
0
/*
modena_model_call returns:

201: requesting exit for new DOE without Restart
200: requesting exit for new DOE with Restart
100: updated model parameters, requesting to continue this run
1: failure
0: okay

If exit is requested, do what's necessary and exit with the same error code!

*/
int modena_model_call
(
    modena_model_t *m,
    modena_inputs_t *inputs,
    modena_outputs_t *outputs
)
{
    size_t j;
    for(j = 0; j < m->substituteModels_size; j++)
    {
        modena_substitute_model_call(&m->substituteModels[j], m, inputs);
    }

    for(j = 0; j < m->inputs_minMax_size; j++)
    {
        /*
        printf
        (
            "j = %zu %g < %g || %g > %g\n",
            j,
            inputs->inputs[j],
            m->inputs_min[j],
            inputs->inputs[j],
            m->inputs_max[j]
        );
        */

        if
        (
            inputs->inputs[j] < m->inputs_min[j]
         || inputs->inputs[j] > m->inputs_max[j]
        )
        {
            PyObject* pOutside = PyList_New(m->inputs_minMax_size);

            for(j = 0; j < m->inputs_minMax_size; j++)
            {
                PyList_SET_ITEM
                (
                    pOutside, j, PyFloat_FromDouble(inputs->inputs[j])
                );
            }

            PyObject *pRet = PyObject_CallMethod
            (
                m->pModel, "outOfBounds", "(O)", pOutside
            );
            Py_DECREF(pOutside);
            if(!pRet){ Modena_PyErr_Print(); }
            int ret = PyInt_AsLong(pRet);
            Py_DECREF(pRet);

            return ret;
        }
    }

    m->function
    (
        m->parameters,
        inputs->inherited_inputs,
        inputs->inputs,
        outputs->outputs
    );

    return 0;
}
  FIATQuadratureAdapter::FIATQuadratureAdapter( PyObject *py_quad_factory ,
						int order ) :
    QuadratureFamilyBase( order ) , pts_(3) , wts_(3)
  {
    
    for (i=0;i<3;i++) {
      stack<PyObject *> to_decref;
      // call the factory function with shape and order
      // to get the FIAT quadrature rule for that shape
      
      PyObject *py_quad_rule = 
	PyObject_CallFunction( py_quad_factory , "(ii)" , i+1 , order );
      TEUCHOS_TEST_FOR_EXCEPTION( !py_quad_rule , std::runtime_error , 
			  "Unable to construct quadrature rule" );
      to_decref.push( py_quad_rule );
      
      PyObject *py_quad_points =
	PyObject_CallMethod( py_quad_rule , "get_points" , NULL );
      
      TEUCHOS_TEST_FOR_EXCEPTION( !py_quad_points , std::runtime_error ,
			  "Unable to extract quadrature points" );
      
      to_decref.push( py_quad_points );
      
      PyObject *py_quad_weights =
	PyObject_CallMethod( py_quad_rule , "get_weights" , NULL );
      
      
      TEUCHOS_TEST_FOR_EXCEPTION( !py_quad_weights , std::runtime_error , 
			  "Unable to extract quadrature weights" );
      
      int num_points = PyObject_Length( py_quad_points );
      
      TEUCHOS_TEST_FOR_EXCEPTION( (num_points < 1) , std::runtime_error ,
			  "Not enough points" );
      
      TEUCHOS_TEST_FOR_EXCEPTION( (num_points != PyObject_Length( py_quad_weights ) ) ,
			  std::runtime_error ,
			  "Number of points and weights don't match" );
      
      to_decref.push( py_quad_weights );
      
      
      // get ready to copy data
      pts_[i].resize( num_points );
      wts_[i].resize( num_points );
      
      for (int j=0;j<num_points;j++) {
	pts_[i][j].resize(i+1);				
      }
      
      // copy data for the points
      // lookup functions into list and tuple are borrowed reference
      // and hence don't need to be decrefed
      for (int j=0;j<num_points;j++) {
	// Get a tuple that is the current point
	PyObject *py_pt_cur = PyList_GetItem( py_quad_points , j );
	for (k=0;k<i+1;k++) {
	  PyObject *py_pt_cur_k = PyTuple_GetItem( py_pt_cur , k );
	  pts_[i][j][k] = PyFloat_AsDouble( py_pt_cur_k );
	}
      }
      
      // copy data for weights
      // since they are a Numeric array, I go through the
      // object protocol and have to decref.
      for (int j=0;j<num_points;j++) {
	PyObject *py_j = PyInt_FromLong( (long) j );
	PyObject *py_wt_cur = PyObject_GetItem( py_quad_weights , py_j );
	wts_[i][j] = PyFloat_AsDouble( py_wt_cur );
	to_decref.push( py_j );
	to_decref.push( py_wt_cur );
      }
      
      while( !to_decref.empty() ) {
	PyObject *foo = to_decref.top();
	Py_DECREF( foo );
	to_decref.pop();
      }
    }
  }
Esempio n. 25
0
/* This is the main function.  Read this to understand how the
 * collection process works. */
static Py_ssize_t
collect(int generation)
{
	int i;
	Py_ssize_t m = 0; /* # objects collected */
	Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
	PyGC_Head *young; /* the generation we are examining */
	PyGC_Head *old; /* next older generation */
	PyGC_Head unreachable; /* non-problematic unreachable trash */
	PyGC_Head finalizers;  /* objects with, & reachable from, __del__ */
	PyGC_Head *gc;
	double t1 = 0.0;

	if (delstr == NULL) {
		delstr = PyString_InternFromString("__del__");
		if (delstr == NULL)
			Py_FatalError("gc couldn't allocate \"__del__\"");
	}

	if (debug & DEBUG_STATS) {
		if (tmod != NULL) {
			PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
			if (f == NULL) {
				PyErr_Clear();
			}
			else {
				t1 = PyFloat_AsDouble(f);
				Py_DECREF(f);
			}
		}
		PySys_WriteStderr("gc: collecting generation %d...\n",
				  generation);
		PySys_WriteStderr("gc: objects in each generation:");
		for (i = 0; i < NUM_GENERATIONS; i++)
			PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
					  gc_list_size(GEN_HEAD(i)));
		PySys_WriteStderr("\n");
	}

	/* update collection and allocation counters */
	if (generation+1 < NUM_GENERATIONS)
		generations[generation+1].count += 1;
	for (i = 0; i <= generation; i++)
		generations[i].count = 0;

	/* merge younger generations with one we are currently collecting */
	for (i = 0; i < generation; i++) {
		gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
	}

	/* handy references */
	young = GEN_HEAD(generation);
	if (generation < NUM_GENERATIONS-1)
		old = GEN_HEAD(generation+1);
	else
		old = young;

	/* Using ob_refcnt and gc_refs, calculate which objects in the
	 * container set are reachable from outside the set (i.e., have a
	 * refcount greater than 0 when all the references within the
	 * set are taken into account).
	 */
	update_refs(young);
	subtract_refs(young);

	/* Leave everything reachable from outside young in young, and move
	 * everything else (in young) to unreachable.
	 * NOTE:  This used to move the reachable objects into a reachable
	 * set instead.  But most things usually turn out to be reachable,
	 * so it's more efficient to move the unreachable things.
	 */
	gc_list_init(&unreachable);
	move_unreachable(young, &unreachable);

	/* Move reachable objects to next generation. */
	if (young != old)
		gc_list_merge(young, old);

	/* All objects in unreachable are trash, but objects reachable from
	 * finalizers can't safely be deleted.  Python programmers should take
	 * care not to create such things.  For Python, finalizers means
	 * instance objects with __del__ methods.  Weakrefs with callbacks
	 * can also call arbitrary Python code but they will be dealt with by
	 * handle_weakrefs().
 	 */
	gc_list_init(&finalizers);
	move_finalizers(&unreachable, &finalizers);
	/* finalizers contains the unreachable objects with a finalizer;
	 * unreachable objects reachable *from* those are also uncollectable,
	 * and we move those into the finalizers list too.
	 */
	move_finalizer_reachable(&finalizers);

	/* Collect statistics on collectable objects found and print
	 * debugging information.
	 */
	for (gc = unreachable.gc.gc_next; gc != &unreachable;
			gc = gc->gc.gc_next) {
		m++;
		if (debug & DEBUG_COLLECTABLE) {
			debug_cycle("collectable", FROM_GC(gc));
		}
		if (tmod != NULL && (debug & DEBUG_STATS)) {
			PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
			if (f == NULL) {
				PyErr_Clear();
			}
			else {
				t1 = PyFloat_AsDouble(f)-t1;
				Py_DECREF(f);
				PySys_WriteStderr("gc: %.4fs elapsed.\n", t1);
			}
		}
	}

	/* Clear weakrefs and invoke callbacks as necessary. */
	m += handle_weakrefs(&unreachable, old);

	/* Call tp_clear on objects in the unreachable set.  This will cause
	 * the reference cycles to be broken.  It may also cause some objects
	 * in finalizers to be freed.
	 */
	delete_garbage(&unreachable, old);

	/* Collect statistics on uncollectable objects found and print
	 * debugging information. */
	for (gc = finalizers.gc.gc_next;
	     gc != &finalizers;
	     gc = gc->gc.gc_next) {
		n++;
		if (debug & DEBUG_UNCOLLECTABLE)
			debug_cycle("uncollectable", FROM_GC(gc));
	}
	if (debug & DEBUG_STATS) {
		if (m == 0 && n == 0)
			PySys_WriteStderr("gc: done.\n");
		else
			PySys_WriteStderr(
			    "gc: done, "
			    "%" PY_FORMAT_SIZE_T "d unreachable, "
			    "%" PY_FORMAT_SIZE_T "d uncollectable.\n",
			    n+m, n);
	}

	/* Append instances in the uncollectable set to a Python
	 * reachable list of garbage.  The programmer has to deal with
	 * this if they insist on creating this type of structure.
	 */
	(void)handle_finalizers(&finalizers, old);

	if (PyErr_Occurred()) {
		if (gc_str == NULL)
			gc_str = PyString_FromString("garbage collection");
		PyErr_WriteUnraisable(gc_str);
		Py_FatalError("unexpected exception during garbage collection");
	}
	return n+m;
}
Esempio n. 26
0
static void gevent_loop() {

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

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

    // get the GIL
    UWSGI_GET_GIL

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

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

    struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;

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

    uwsgi.current_wsgi_req = uwsgi_gevent_current_wsgi_req;

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

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

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

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

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

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

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


    PyObject *gevent_get_hub = PyDict_GetItemString(gevent_dict, "get_hub");

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

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

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


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

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

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

    // pre-fill the greenlet args
    ugevent.greenlet_args = PyTuple_New(2);
    PyTuple_SetItem(ugevent.greenlet_args, 0, uwsgi_request_greenlet);

    if (uwsgi.signal_socket > -1) {
        // and these are the watcher for signal sockets

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

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

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

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

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

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

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

    }

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

        // start the main greenlet
        PyObject_CallMethod(ugevent.watchers[i], "start", "Ol", uwsgi_gevent_main,(long)uwsgi_sock);
        uwsgi_sock = uwsgi_sock->next;
        i++;
    }

    // patch goodbye_cruel_world
    uwsgi.gbcw_hook = uwsgi_gevent_gbcw;

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

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

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

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

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

}
Esempio n. 27
0
static PyObject *
pcap_PcapObject_read(PyObject *p)
{
  pcap_PcapObject    *self = (pcap_PcapObject *)p;
  struct pcap_pkthdr *hdr;
  PyObject           *pTmp = NULL;
  PyObject           *pBuf = NULL;
  PyObject           *pRet = NULL;

  attempt {
    if ('r' != self->mode) {
      PyErr_Format(PyExc_IOError, "can not read from writable stream");
      break;
    }

    pTmp = PyObject_CallMethod(self->pFile, "read", "i", sizeof(*hdr));
    if (! pTmp) break;

    {
      char *buf;
      int   len;
      int   tmp;

      tmp = PyString_AsStringAndSize(pTmp, &buf, &len);
      if (-1 == tmp) {
        break;
      }

      /* 0 bytes means end of file */
      if (0 == len) {
        pRet = Py_None;
        Py_INCREF(pRet);
        succeed;
      }

      if (len != sizeof(*hdr)) {
        PyErr_Format(PyExc_IOError, "Read returned wrong number of bytes (%d)", len);
        break;
      }

      /* Since buf points to something Python owns, we can just make hdr
         point there and let buf fall off the stack. */

      hdr = (struct pcap_pkthdr *)buf;
    }

    pBuf = PyObject_CallMethod(self->pFile, "read", "i", sl(hdr->caplen));
    if (! pBuf) break;

    pRet = Py_BuildValue("(lll)O",
                         sl(hdr->ts.tv_sec),
                         sl(hdr->ts.tv_usec),
                         sl(hdr->len),
                         pBuf);
    if (! pRet) break;
  }

  Py_CLEAR(pTmp);
  Py_CLEAR(pBuf);

  recover {
    Py_CLEAR(pRet);

    return NULL;
  }

  return pRet;
}
Esempio n. 28
0
int pcmreader_read(struct pcmreader_s* reader,
                    unsigned pcm_frames,
                    aa_int* channels)
{
    PyObject* framelist_obj;
    pcm_FrameList* framelist;
    unsigned frame;
    unsigned channel;
    a_int* channel_a;

    struct pcmreader_callback* callback;
    PyObject* string_obj;
    unsigned char* string;
    Py_ssize_t string_length;

    /*make a call to "pcmreader.read(pcm_frames)"
      where "pcm_frames" is set to the proper PCM frame count*/
    if (((framelist_obj =
          PyObject_CallMethod(reader->pcmreader_obj, "read", "i",
                              (int)pcm_frames))) == NULL) {
        /*ensure result isn't an exception*/
        return 1;
    }

    /*ensure result is a pcm.FrameList object*/
    if (framelist_obj->ob_type != (PyTypeObject*)reader->framelist_type) {
        Py_DECREF(framelist_obj);
        PyErr_SetString(PyExc_TypeError,
                        "results from pcmreader.read() must be FrameLists");
        return 1;
    } else {
        framelist = (pcm_FrameList*)framelist_obj;
    }

    /*split framelist's packed ints into a set of channels*/
    channels->reset(channels);
    for (channel = 0; channel < framelist->channels; channel++) {
        channel_a = channels->append(channels);
        channel_a->resize(channel_a, framelist->frames);
        for (frame = 0; frame < framelist->frames; frame++) {
            a_append(channel_a,
                     framelist->samples[(frame * framelist->channels) +
                                        channel]);
        }
    }

    /*apply all callbacks to pcm.FrameList object*/
    for (callback = reader->callbacks;
         callback != NULL;
         callback = callback->next) {
        string_obj = PyObject_CallMethod(framelist_obj,
                                         "to_bytes", "(ii)",
                                         !callback->little_endian,
                                         callback->is_signed);
        if (string_obj == NULL) {
            Py_DECREF(framelist_obj);
            return 1;
        }

        if (PyString_AsStringAndSize(string_obj,
                                     (char**)(&string),
                                     &string_length) == -1) {
            Py_DECREF(framelist_obj);
            Py_DECREF(string_obj);
            return 1;
        }

        callback->callback(callback->user_data,
                           string,
                           (unsigned long)string_length);

        Py_DECREF(string_obj);
    }

    /*free any allocated buffers and Python objects*/
    Py_DECREF(framelist_obj);

    return 0;
}
Esempio n. 29
0
static PyObject *PyPCAP_next(PyPCAP *self) {
  PyObject *result;
  int len;
  int packet_offset;

  // Make sure our buffer is full enough:
  if(self->buffer->size - self->buffer->readptr < MAX_PACKET_SIZE) {
    len = PyPCAP_fill_buffer(self, self->fd);
    
    if(len<0) return NULL;
  };

  packet_offset = self->buffer->readptr;

  /** This is an interesting side effect of the talloc reference model:
      
  talloc_reference(context, ptr) adds a new context to ptr so ptr is
  now effectively parented by two parents. The two parents are not
  equal however because a talloc free(ptr) will remove the reference
  first and then the original parent.

  This causes problems here because we create the packet_header with
  self->buffer as a context. However other code takes references to it
  - pinning it to other parents. If we did a
  talloc_free(self->packet_header) here we would be removing those
  references _instead_ of freeing the ptr from our own self->buffer
  reference. This will cause both memory leaks (because we will not be
  freeing packet_header at all, and later crashes because important
  references will be removed.

  When references begin to be used extensively I think we need to
  start using talloc_unlink instead of talloc_free everywhere.
  */
  // Free old packets:
  if(self->packet_header) 
    talloc_unlink(self->buffer, self->packet_header);

  // Make a new packet:
  self->packet_header = (PcapPacketHeader)CONSTRUCT(PcapPacketHeader, Packet,
						    super.Con, self->buffer, NULL);

  if(self->file_header->little_endian) {
    self->packet_header->super.format = self->packet_header->le_format;
  };

  // Read the packet in:
  len = self->packet_header->super.Read((Packet)self->packet_header, self->buffer);

  // Did we finish?
  if(len<=0) {
    return PyErr_Format(PyExc_StopIteration, "Done");
  };

  // Make sure the new packet knows its offset and where it came from:
  self->packet_header->header.offset = self->pcap_offset;
  self->packet_header->header.pcap_file_id = self->pcap_file_id;

  // Keep track of our own file offset:
  self->pcap_offset += self->buffer->readptr - packet_offset;
  // CALL(self->buffer, skip, self->buffer->readptr);

  // Adjust the output endianess if needed
  switch(self->output_format) {
  case FORCE_BIG_ENDIAN:
    // FIXME - Leaks!!!
    self->packet_header->super.format = PCAP_PKTHEADER_STRUCT;
    break;

  case FORCE_LITTLE_ENDIAN:
    self->packet_header->super.format = PCAP_PKTHEADER_STRUCT_LE;
    break;

  default:
    // Do nothing
    break;
  };

  // create a new pypacket object:
  result = PyObject_CallMethod(g_pypacket_module, "PyPacket", "N",
			       PyCObject_FromVoidPtr(self->packet_header,NULL), "PcapPacketHeader");

  return result;
};
Esempio n. 30
0
boost::python::object GCHMCIntegrator::Call(
  int nosteps_arg,
  int steps_per_trial_arg,
  TARGET_TYPE temp_arg,
  TARGET_TYPE ts,
  int pyseed,
  int _massMatNumOpt, // EU
  int _metroFixmanOpt, // EU
  double _lj14sf //--
){
  #ifdef DEBUG_TIME
  //boost::timer boost_timer;
  #endif

  int ntrials_arg = 0;
  if(nosteps_arg%steps_per_trial_arg){
    fprintf(stderr, 
      "GCHMCIntegrator::Call(): Incorrect nosteps/steps_per_trial combination: %d/%d\n",
       nosteps_arg, steps_per_trial_arg);
    exit(1);
  }
  ntrials_arg = nosteps_arg/steps_per_trial_arg;

  int tx, tshm;
  boost::python::list booConfList;
  int i, j;
  double **retConfsPois = new double* [ntrials_arg];
  double *retPotEsPoi = new double[ntrials_arg];
  double *accs = new double;
  *accs = 0.0;
  vector3 *xCall;

  PyObject *SrcConfObj = PyObject_CallMethod(this->universe, "copyConfiguration", NULL);
  // START GET CURR CONF
  PyObject *CallConfArr = PyObject_GetAttrString(SrcConfObj, "array");
  PyArrayObject *CallConfiguration = (PyArrayObject *)CallConfArr;
  xCall = (vector3 *)CallConfiguration->data;
  // STOP  GET CURR CONF
  PyObject *ConfObjs[ntrials_arg];
  PyObject *ConfArrs[ntrials_arg];
  PyArrayObject *Confs[ntrials_arg];
  boost::python::object booConfObjs[ntrials_arg];
  boost::python::list booPotEs;
  
  for(i=0; i<ntrials_arg; i++){
    ConfObjs[i] = PyObject_CallMethod(this->universe, "copyConfiguration", NULL);
    ConfArrs[i] = PyObject_GetAttrString(ConfObjs[i], "array");
    Confs[i] = (PyArrayObject *)(ConfArrs[i]);
    retConfsPois[i] = (double *)(Confs[i])->data;
  }

  // Put curr conf from universe into shm
  for(int a=0; a<sys->mr->natms; a++){
    tx = (int)(sys->indexMap[ a ][2]);
    tshm = ((int)(sys->indexMap[ a ][1]) * 3) + 2;
    shm[ tshm +0] = xCall[tx][0];
    shm[ tshm +1] = xCall[tx][1];
    shm[ tshm +2] = xCall[tx][2];
  }

  *sys->pyseed = pyseed;
  sys->massMatNumOpt = _massMatNumOpt; // EU
  sys->metroFixmanOpt = _metroFixmanOpt; // EU
  sys->lj14sf = _lj14sf; //--
  sys->sysRetConfsPois = retConfsPois;
  sys->sysRetPotEsPoi = retPotEsPoi;
  sys->sysAccs = accs;

  if(nosteps_arg % ntrials_arg){
    fprintf(stderr, "nosteps_arg % ntrials_arg not 0\n");
    exit(1);
  }
  this->nosteps = nosteps_arg;
  this->ntrials = ntrials_arg;
  this->temperature = temp_arg;
  this->delta_t = ts;
  ++(this->sweep);

  int arrays_cut = 2 + 4*3*(sys->mr->natms);
  shm[arrays_cut + 0] = 0.0; // step (will be incremented in MidVV
  shm[arrays_cut + 1] = (TARGET_TYPE)(this->nosteps);
  shm[arrays_cut + 2] = this->temperature;
  shm[arrays_cut + 3] = delta_t; // picosec
  shm[arrays_cut + 7] = 1.0;     // acceptance always 1 !!
  shm[arrays_cut + 9] = nosteps/ntrials; // steps_per_trial
  shm[arrays_cut + 10] = 0.0;    // initialize trial

  // * Get <Universe>'s pyo_evaluator //
  PyObject *pyo_evaluator;
  PyObject *cpyo_evaluator;
  pyo_evaluator = PyObject_CallMethod(this->universe, "energyEvaluator", NULL);
  cpyo_evaluator = PyObject_CallMethod(pyo_evaluator, "CEvaluator", NULL);

  this->evaluator = (PyFFEvaluatorObject *)cpyo_evaluator;
  sys->evaluator = this->evaluator;

  #ifdef DEBUG_TIME
  //std::cout<<"Time simmain nosteps"<<this->nosteps<<" time "<<boost_timer.elapsed()<<std::endl;
  #endif
  sys->Advance(this->nosteps); 
  #ifdef DEBUG_TIME
  //std::cout<<"Time simmain nosteps"<<this->nosteps<<" time "<<boost_timer.elapsed()<<std::endl;
  #endif

  xCall = (vector3 *)configuration->data;

  for(int a=0; a<sys->mr->natms; a++){
    tx = (int)(sys->indexMap[ a ][2]);
    tshm = ((int)(sys->indexMap[ a ][1]) * 3) + 2;
    xCall[tx][0] = shm[ tshm +0];
    xCall[tx][1] = shm[ tshm +1];
    xCall[tx][2] = shm[ tshm +2];
  }

  for(i=0; i<ntrials_arg; i++){
    booConfObjs[i] = boost::python::object(boost::python::handle<>( boost::python::borrowed((PyObject *)(ConfObjs[i])) ));
    booConfList.append(booConfObjs[i]);

    booPotEs.append(retPotEsPoi[i]);  // potential energies
  }

  double ntrials = (shm[arrays_cut + 1]) / (shm[arrays_cut + 9]);
  double booAccPerTrials = *accs / ntrials;  //float(acc)/float(ntrials)
  boost::python::list booRetList;
  booRetList.append(booConfList);
  booRetList.append(booPotEs);
  //booRetList.append(booAccPerTrials); // RESTORE
  booRetList.append(int(*accs));
  booRetList.append(int(ntrials));
  booRetList.append(ts); // delta_t

  delete accs;

  return booRetList; // (xs, energies, acc, ntrials, delta_t)
}