• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PyList_GET_SIZE函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中PyList_GET_SIZE函数的典型用法代码示例。如果您正苦于以下问题:C++ PyList_GET_SIZE函数的具体用法?C++ PyList_GET_SIZE怎么用?C++ PyList_GET_SIZE使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了PyList_GET_SIZE函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: SpiDev_xfer

static PyObject *
SpiDev_xfer(SpiDevObject *self, PyObject *args)
{
	uint16_t ii, len;
	int status;
	uint16_t delay_usecs = 0;
	uint32_t speed_hz = 0;
	uint8_t bits_per_word = 0;
	PyObject *list;
#ifdef SPIDEV_SINGLE
	struct spi_ioc_transfer *xferptr;
	memset(&xferptr, 0, sizeof(xferptr));
#else
	struct spi_ioc_transfer xfer;
	memset(&xfer, 0, sizeof(xfer));
#endif
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O|IHB:xfer", &list, &speed_hz, &delay_usecs, &bits_per_word))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > SPIDEV_MAXPATH) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

#ifdef SPIDEV_SINGLE
	xferptr = (struct spi_ioc_transfer*) malloc(sizeof(struct spi_ioc_transfer) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyLong_Check(val)) {
			PyErr_SetString(PyExc_TypeError, wrmsg);
			free(xferptr);
			free(txbuf);
			free(rxbuf);
			return NULL;
		}
		txbuf[ii] = (__u8)PyLong_AS_LONG(val);
		xferptr[ii].tx_buf = (unsigned long)&txbuf[ii];
		xferptr[ii].rx_buf = (unsigned long)&rxbuf[ii];
		xferptr[ii].len = 1;
		xferptr[ii].delay_usecs = delay;
		xferptr[ii].speed_hz = speed_hz ? speed_hz : self->max_speed_hz;
		xferptr[ii].bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;
#ifdef SPI_IOC_WR_MODE32
		xferptr[ii].tx_nbits = 0;
#endif
#ifdef SPI_IOC_RD_MODE32
		xferptr[ii].rx_nbits = 0;
#endif
	}

	status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		free(xferptr);
		free(txbuf);
		free(rxbuf);
		return NULL;
	}
#else
	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyLong_Check(val)) {
			PyErr_SetString(PyExc_TypeError, wrmsg);
			free(txbuf);
			free(rxbuf);
			return NULL;
		}
		txbuf[ii] = (__u8)PyLong_AS_LONG(val);
	}

	xfer.tx_buf = (unsigned long)txbuf;
	xfer.rx_buf = (unsigned long)rxbuf;
	xfer.len = len;
	xfer.delay_usecs = delay_usecs;
	xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz;
	xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;
#ifdef SPI_IOC_WR_MODE32
        xfer.tx_nbits = 0;
#endif
#ifdef SPI_IOC_RD_MODE32
        xfer.rx_nbits = 0;
#endif

	status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		free(txbuf);
		free(rxbuf);
		return NULL;
//.........这里部分代码省略.........
开发者ID:MiyamonY,项目名称:py-spidev,代码行数:101,代码来源:spidev_module.c


示例2: pickle___getstate__

static PyObject *
pickle___getstate__(PyObject *self)
{
  PyObject *slotnames=NULL, *slots=NULL, *state=NULL;
  PyObject **dictp;
  int n=0;

  slotnames = pickle_slotnames(self->ob_type);
  if (slotnames == NULL)
    return NULL;

  dictp = _PyObject_GetDictPtr(self);
  if (dictp)
    state = pickle_copy_dict(*dictp);
  else 
    {
      state = Py_None;
      Py_INCREF(state);
    }

  if (slotnames != Py_None)
    {
      int i;

      slots = PyDict_New();
      if (slots == NULL)
        goto end;

      for (i = 0; i < PyList_GET_SIZE(slotnames); i++) 
        {
          PyObject *name, *value;
          char *cname;

          name = PyList_GET_ITEM(slotnames, i);
          if (PyString_Check(name))
            {
              cname = PyString_AS_STRING(name);
              if (*cname == '_' &&
                  (cname[1] == 'v' || cname[1] == 'p') &&
                  cname[2] == '_')
                /* skip volatile and persistent */
                continue;
            }

          value = PyObject_GetAttr(self, name);
          if (value == NULL)
            PyErr_Clear();
          else 
            {
              int err = PyDict_SetItem(slots, name, value);
              Py_DECREF(value);
              if (err)
                goto end;
              n++;
            }
        }
    }

  if (n) 
    state = Py_BuildValue("(NO)", state, slots);

 end:
  Py_XDECREF(slotnames);
  Py_XDECREF(slots);
  
  return state;
}
开发者ID:goschtl,项目名称:zope,代码行数:67,代码来源:pickle.c


示例3: eval_frame


//.........这里部分代码省略.........
                        if ((opcode-STORE_SLICE) & 1)
                                v = POP();
                        else
                                v = NULL;
                        u = POP();
                        t = POP();
                        err = assign_slice(u, v, w, t); /* u[v:w] = t */
                        Py_DECREF(t);
                        Py_DECREF(u);
                        Py_XDECREF(v);
                        Py_XDECREF(w);
                        if (err == 0) continue;
                        break;

                case STORE_SUBSCR:
                        w = POP();
                        v = POP();
                        u = POP();
                        /* v[w] = u */
                        err = PyObject_SetItem(v, w, u);
                        Py_DECREF(u);
                        Py_DECREF(v);
                        Py_DECREF(w);
                        if (err == 0) continue;
                        break;

                case BINARY_SUBSCR:
                        w = POP();
                        v = TOP();
                        if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
                                /* INLINE: list[int] */
                                long i = PyInt_AsLong(w);
                                if (i < 0)
                                        i += PyList_GET_SIZE(v);
                                if (i < 0 ||
                                    i >= PyList_GET_SIZE(v)) {
                                        /* ERROR */
                                        printf("list index out of range\n");
                                        x = NULL;
                                }
                                else {
                                        x = PyList_GET_ITEM(v, i);
                                        Py_INCREF(x);
                                }
                        }
                        else
                                x = PyObject_GetItem(v, w);
                        Py_DECREF(v);
                        Py_DECREF(w);
                        SET_TOP(x);
                        if (x != NULL) continue;
                        break;

		case BINARY_AND:
			w = POP();
			v = TOP();
			x = PyNumber_And(v, w);
			Py_DECREF(v);
			Py_DECREF(w);
			SET_TOP(x);
			if (x != NULL) continue;
			break;

		case PRINT_ITEM:
			v = POP();
开发者ID:brosner,项目名称:cleese,代码行数:66,代码来源:ceval.c


示例4: PyErr_SetString

// This dMList function creates a list of the dM values giving the probabilities of mutations
static PyObject *dMList(PyObject *self, PyObject *args) {
    // Calling variables are (in order): uts, only_need, n_aa, length, grs, dmlist, residue_to_compute, iwt, brs
    PyObject *uts, *only_need, *grs, *r_grs_tuple, *gr_diag, *p, *p_inv, *dmlist, *brs, *brz;
    long n_aa, length, n_aa2, n_uts, residue_to_compute, i_ut, x, y, index, only_need_index, only_need_i, only_need_i_n_aa, index2, iwt, n_aa3, z;
    double *arr_dmlist, *cp_inv, *cp, *cgr_diag, *cexpd, *cbrz, *cvrz, *cvrz_p_inv;
    complex double *complex_cp_inv, *complex_cp, *complex_cgr_diag, *complex_cexpd, *complex_naa2_list, *complex_naa_list, *complex_cvrz, *complex_cvrz_p_inv, *complex_cbrz;
    double ut, exp_utdx, exp_utdy, dx, dy;
    complex double complex_exp_utdx, complex_exp_utdy, complex_dx, complex_dy;
    int array_type;
#ifdef USE_ACCELERATE_CBLAS
    complex double complex_one = 1, complex_zero = 0;
#else
    complex double complex_dmxy, complex_v_p_inv_xy;
    double dmxy, v_p_inv_xy;
    long yindex, irowcolumn;
#endif
    // Parse the arguments.  
    if (! PyArg_ParseTuple( args, "O!O!llO!O!llO!", &PyList_Type, &uts, &PyList_Type, &only_need, &n_aa, &length, &PyList_Type, &grs, &PyArray_Type, &dmlist, &residue_to_compute, &iwt, &PyList_Type, &brs)) {
        PyErr_SetString(PyExc_TypeError, "Invalid calling arguments to dMList.");
        return NULL;
    }
    // Error checking on arguments
    if (length < 1) { // length of the protein
        PyErr_SetString(PyExc_ValueError, "length is less than one.");
        return NULL;
    }
    if (n_aa < 1) { // number of amino acids.  Normally will be 20.
        PyErr_SetString(PyExc_ValueError, "n_aa is less than one.");
        return NULL;
    }
    if (PyList_GET_SIZE(grs) != length) { // make sure grs is of the same size as length
        PyErr_SetString(PyExc_ValueError, "grs is not of the same size as length.");
        return NULL;
    }
    n_uts = PyList_GET_SIZE(uts); // number of entries in uts
    if (n_uts < 1) { // make sure there are entries in uts 
        PyErr_SetString(PyExc_ValueError, "uts has no entries.");
        return NULL;
    }
    if (PyList_GET_SIZE(only_need) != n_uts * length) { // make sure only_need is of correct size
        PyErr_SetString(PyExc_ValueError, "only_need is of wrong size.");
        return NULL;
    }
    if (! ((residue_to_compute >= 0) && (residue_to_compute < length))) {
        PyErr_SetString(PyExc_ValueError, "Invalid value for residue_to_compute.");
        return NULL;
    }
    if (! ((iwt >= 0) && (iwt < n_aa))) {
        PyErr_SetString(PyExc_ValueError, "Invalid value for iwt.");
        return NULL;
    }
    if (PyList_GET_SIZE(brs) != n_aa) { // make sure brs has one entry for each amino acid
        PyErr_SetString(PyExc_ValueError, "brs is not of length equal to n_aa");
        return NULL;
    }
    n_aa2 = n_aa * n_aa; // square of the number of amino acids
    n_aa3 = n_aa2 * n_aa; // cube of the number of amino acids
    // The results will be returned in a numpy ndarray 'float_' (C type double) array called dmlist.
    // This array will be of size length * n_uts * n_aa3.
    arr_dmlist = (double *) PyArray_DATA(dmlist); // this is the data array of dmlist
    long const sizeof_cexpd = n_aa2 * sizeof(double);
    long const complex_sizeof_cexpd = n_aa2 * sizeof(complex double);
    // gr_diag, p, and p_inv are the eigenvalues, left, and right diagonalizing matrices of gr
    r_grs_tuple = PyList_GET_ITEM(grs, residue_to_compute);
    gr_diag = PyTuple_GET_ITEM(r_grs_tuple, 0); 
    p = PyTuple_GET_ITEM(r_grs_tuple, 1);
    p_inv = PyTuple_GET_ITEM(r_grs_tuple, 2);
    // Now begin filling arr_dmlist with the appropriate values
    index = 0;
    only_need_index = residue_to_compute * n_uts;
    // determine if these arrays are complex double or real doubles
    array_type = PyArray_TYPE(gr_diag);
    if (array_type == NPY_DOUBLE) { // array is of doubles, real not complex
        // Note that these next assignments assume that the arrays are C-style contiguous
        cp = PyArray_DATA(p);
        cp_inv = PyArray_DATA(p_inv);
        cgr_diag = PyArray_DATA(gr_diag);
        cexpd = (double *) malloc(sizeof_cexpd); // allocate memory
        cvrz = (double *) malloc(sizeof_cexpd); // allocate memory
        cvrz_p_inv = (double *) malloc(sizeof_cexpd); // allocate memory
        for (i_ut = 0; i_ut < n_uts; i_ut++) { // loop over ut values
            only_need_i = PyInt_AS_LONG(PyList_GET_ITEM(only_need, only_need_index)); // value of only_need
            only_need_index++;
            if (only_need_i == -1) { // we don't need to do anything for these entries in dmlist
                index += n_aa3;
            } else { // we need to compute at least some entries in dmlist
                ut = PyFloat_AS_DOUBLE(PyList_GET_ITEM(uts, i_ut));  // ut value
                // Entries of cexpd are defined by D_xy = (exp(ut d_x) - exp(ut d_y)) / (d_x - d_y)
                // for x != y, and D_yy = ut exp(d_x ut)
                index2 = 0;
                for (x = 0; x < n_aa; x++) {
                    dx = cgr_diag[x];
                    exp_utdx = exp(ut * dx);
                    for (y = 0; y < n_aa; y++) {
                        if (y == x) {
                            cexpd[index2] = ut * exp_utdx;
                        } else {
                            dy = cgr_diag[y];
                            exp_utdy = exp(ut * dy);
//.........这里部分代码省略.........
开发者ID:jbloomlab,项目名称:pips-1.0,代码行数:101,代码来源:cddg_inference.c


示例5: handle_starttag

static int
handle_starttag(tdi_soup_parser *self, tdi_parser_event *event,
                tdi_lexer_event *event_)
{
    PyObject *name, *normname, *tmp, *data;
    int res;

    if (self->inempty && close_empty(self) == -1) return -1;

    /* sanitize */
    if (PyString_GET_SIZE(event_->info.starttag.name) == 0
        && PyList_GET_SIZE(event_->info.starttag.attr) == 0) {
        name = (Py_INCREF(self->lastopen), self->lastopen);
    }
    else {
        name = event_->info.starttag.name;
        Py_INCREF(name);
        Py_CLEAR(self->lastopen);
        self->lastopen = (Py_INCREF(name), name);
    }

    if (!(normname = self->normalize(self->normalize_ctx, name)))
        goto error;

    /* close unnestables */
    while (self->tagstack) {
        res = self->nestable(self->nestable_ctx,
                             self->tagstack->normname, normname);
        if (res == -1)
            goto error_normname;
        if (res) break;

        event->type = TDI_PARSER_EVENT_ENDTAG;
        if (!(data = PyString_FromString("")))
            goto error_normname;
        tmp = self->tagstack->name;
        event->info.endtag.name = (Py_INCREF(tmp), tmp);
        event->info.endtag.data = data;
        tagstack_pop(&self->tagstack);
        res = !self->cb(event, self->cb_ctx) ? 0 : -1;
        Py_DECREF(tmp);
        Py_DECREF(data);
        if (res == -1)
            goto error_normname;
    }

    /* CDATA */
    if (!event_->info.starttag.closed) {
        if ((res = self->cdata(self->cdata_ctx, normname)) == -1)
            goto error_normname;
        if (res) {
            res = tdi_soup_lexer_state_cdata(self->lexer, self->normalize,
                                             self->normalize_ctx, normname);
            if (res == -1) {
                lexer_error(self);
                goto error_normname;
            }
        }
    }

    /* pass event */
    event->type = TDI_PARSER_EVENT_STARTTAG;
    event->info.starttag.name = name;
    event->info.starttag.attr = event_->info.starttag.attr;
    event->info.starttag.closed = event_->info.starttag.closed;
    event->info.starttag.data = event_->info.starttag.data;
    if (self->cb(event, self->cb_ctx))
        goto error_normname;

    /* Maintain stack */
    if (!event_->info.starttag.closed) {
        if (tagstack_push(&self->tagstack, normname, name) == -1)
            goto error_normname;
        if ((res = self->empty(self->empty_ctx, normname)) == -1)
            goto error_normname;
        if (res)
            self->inempty = 1;
    }

    /* cleanup & finish */
    Py_DECREF(normname);
    Py_DECREF(name);
    return 0;

error_normname:
    Py_DECREF(normname);
error:
    Py_DECREF(name);

    if (!self->last_error)
        self->last_error = TDI_PARSER_ERR_ENV;
    return -1;
}
开发者ID:AvdN,项目名称:tdi,代码行数:93,代码来源:soup_parser.c


示例6: dialect_init

static int
dialect_init(DialectObj * self, PyObject * args, PyObject * kwargs)
{
        PyObject *dialect = NULL, *name_obj, *value_obj;

	self->quotechar = '"';
	self->delimiter = ',';
	self->escapechar = '\0';
	self->skipinitialspace = 0;
        Py_XDECREF(self->lineterminator);
	self->lineterminator = PyString_FromString("\r\n");
        if (self->lineterminator == NULL)
                return -1;
	self->quoting = QUOTE_MINIMAL;
	self->doublequote = 1;
	self->strict = 0;

	if (!PyArg_UnpackTuple(args, "", 0, 1, &dialect))
                return -1;
        Py_XINCREF(dialect);
        if (kwargs != NULL) {
                PyObject * key = PyString_FromString("dialect");
                PyObject * d;

                d = PyDict_GetItem(kwargs, key);
                if (d) {
                        Py_INCREF(d);
                        Py_XDECREF(dialect);
                        PyDict_DelItem(kwargs, key);
                        dialect = d;
                }
                Py_DECREF(key);
        }
        if (dialect != NULL) {
                int i;
                PyObject * dir_list;

                /* If dialect is a string, look it up in our registry */
                if (PyString_Check(dialect)
#ifdef Py_USING_UNICODE
		    || PyUnicode_Check(dialect)
#endif
			) {
                        PyObject * new_dia;
                        new_dia = get_dialect_from_registry(dialect);
                        Py_DECREF(dialect);
                        if (new_dia == NULL)
                                return -1;
                        dialect = new_dia;
                }
                /* A class rather than an instance? Instantiate */
                if (PyObject_TypeCheck(dialect, &PyClass_Type)) {
                        PyObject * new_dia;
                        new_dia = PyObject_CallFunction(dialect, "");
                        Py_DECREF(dialect);
                        if (new_dia == NULL)
                                return -1;
                        dialect = new_dia;
                }
                /* Make sure we finally have an instance */
                if (!PyInstance_Check(dialect) ||
                    (dir_list = PyObject_Dir(dialect)) == NULL) {
                        PyErr_SetString(PyExc_TypeError,
                                        "dialect must be an instance");
                        Py_DECREF(dialect);
                        return -1;
                }
                /* And extract the attributes */
                for (i = 0; i < PyList_GET_SIZE(dir_list); ++i) {
			char *s;
                        name_obj = PyList_GET_ITEM(dir_list, i);
			s = PyString_AsString(name_obj);
			if (s == NULL)
				return -1;
                        if (s[0] == '_')
                                continue;
                        value_obj = PyObject_GetAttr(dialect, name_obj);
                        if (value_obj) {
                                if (PyObject_SetAttr((PyObject *)self, 
                                                     name_obj, value_obj)) {
					Py_DECREF(value_obj);
                                        Py_DECREF(dir_list);
					Py_DECREF(dialect);
                                        return -1;
                                }
                                Py_DECREF(value_obj);
                        }
                }
                Py_DECREF(dir_list);
                Py_DECREF(dialect);
        }
        if (kwargs != NULL) {
                int pos = 0;

                while (PyDict_Next(kwargs, &pos, &name_obj, &value_obj)) {
                        if (PyObject_SetAttr((PyObject *)self, 
                                             name_obj, value_obj))
                                return -1;
                }
        }
//.........这里部分代码省略.........
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:101,代码来源:_csv.c


示例7: run

/**
 * Function to call to evaluate model
 * @param args: input q or [q,phi]
 * @return: function value
 */
static PyObject * run(CFlexCylEllipXModel *self, PyObject *args) {
	double q_value, phi_value;
	PyObject* pars;
	int npars;
	
	// Get parameters
	
	    // Reader parameter dictionary
    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
    self->model->sldCyl = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldCyl") );
    self->model->axis_ratio = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_ratio") );
    self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") );
    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
    self->model->kuhn_length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "kuhn_length") );
    // Read in dispersion parameters
    PyObject* disp_dict;
    DispersionVisitor* visitor = new DispersionVisitor();
    disp_dict = PyDict_GetItemString(self->dispersion, "length");
    self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "kuhn_length");
    self->model->kuhn_length.dispersion->accept_as_destination(visitor, self->model->kuhn_length.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "axis_ratio");
    self->model->axis_ratio.dispersion->accept_as_destination(visitor, self->model->axis_ratio.dispersion, disp_dict);

	
	// Get input and determine whether we have to supply a 1D or 2D return value.
	if ( !PyArg_ParseTuple(args,"O",&pars) ) {
	    PyErr_SetString(CFlexCylEllipXModelError, 
	    	"CFlexCylEllipXModel.run expects a q value.");
		return NULL;
	}
	  
	// Check params
	if( PyList_Check(pars)==1) {
		
		// Length of list should be 2 for I(q,phi)
	    npars = PyList_GET_SIZE(pars); 
	    if(npars!=2) {
	    	PyErr_SetString(CFlexCylEllipXModelError, 
	    		"CFlexCylEllipXModel.run expects a double or a list of dimension 2.");
	    	return NULL;
	    }
	    // We have a vector q, get the q and phi values at which
	    // to evaluate I(q,phi)
	    q_value = CFlexCylEllipXModel_readDouble(PyList_GET_ITEM(pars,0));
	    phi_value = CFlexCylEllipXModel_readDouble(PyList_GET_ITEM(pars,1));
	    // Skip zero
	    if (q_value==0) {
	    	return Py_BuildValue("d",0.0);
	    }
		return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));

	} else {

		// We have a scalar q, we will evaluate I(q)
		q_value = CFlexCylEllipXModel_readDouble(pars);		
		
		return Py_BuildValue("d",(*(self->model))(q_value));
	}	
}
开发者ID:ricleal,项目名称:SasModeling,代码行数:69,代码来源:CFlexCylEllipXModel.cpp


示例8: SPI_xfer

static PyObject *
SPI_xfer(SPI *self, PyObject *args)
{
	uint8_t ii, len;
	int status;
	int delay = -1;
	//uint8_t ret = 0;
	PyObject *list;
	struct spi_ioc_transfer *xferptr;
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O|i:msg", &list, &delay))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > MAXMSGLEN) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	if (delay == -1) {
		delay = 0;
	}

	xferptr = (struct spi_ioc_transfer*) malloc(sizeof(struct spi_ioc_transfer) * len);
	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyInt_Check(val)) {
			PyErr_SetString(PyExc_TypeError, wrmsg);
			return NULL;
		}
		txbuf[ii] = (__u8)PyInt_AS_LONG(val);
		xferptr[ii].tx_buf = (unsigned long)&txbuf[ii];
		xferptr[ii].rx_buf = (unsigned long)&rxbuf[ii];
		xferptr[ii].len = 1;
		xferptr[ii].delay_usecs = delay;
		xferptr[ii].speed_hz = 0;      
		xferptr[ii].bits_per_word = 0;
	}

	status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}

	// WA:
	// in CS_HIGH mode CS isn't pulled to low after transfer, but after read
	// reading 0 bytes doesnt matter but brings cs down
	status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);
	free(xferptr);

	Py_INCREF(list);
	return list;
}
开发者ID:GeeksWine,项目名称:PyBBIO,代码行数:70,代码来源:spimodule.c


示例9: SPI_xfer2

static PyObject *
SPI_xfer2(SPI *self, PyObject *args)
{
	static char *msg = "Argument must be a list of at least one, "
				"but not more than 1024 integers";
	int status;	
	uint8_t ii, len;
	PyObject *list;
	struct spi_ioc_transfer	xfer;
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O:xfer2", &list))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > MAXMSGLEN) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyInt_Check(val)) {
			PyErr_SetString(PyExc_TypeError, msg);
			return NULL;
		}
		txbuf[ii] = (__u8)PyInt_AS_LONG(val);
	}

	xfer.tx_buf = (unsigned long)txbuf;
	xfer.rx_buf = (unsigned long)rxbuf;
	xfer.len = len;
	xfer.delay_usecs = 0;
	xfer.speed_hz = 0;      
	xfer.bits_per_word = 0;
	
	status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}
	// WA:
	// in CS_HIGH mode CS isnt pulled to low after transfer
	// reading 0 bytes doesn't really matter but brings CS down
	status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);

	Py_INCREF(list);
	return list;
}
开发者ID:GeeksWine,项目名称:PyBBIO,代码行数:64,代码来源:spimodule.c


示例10: GMPy_Context_Fsum

static PyObject *
GMPy_Context_Fsum(PyObject *self, PyObject *other)
{
    MPFR_Object *temp, *result;
    mpfr_ptr *tab;
    int errcode;
    Py_ssize_t i, seq_length = 0;
    CTXT_Object *context = NULL;

    if (self && CTXT_Check(self)) {
        context = (CTXT_Object*)self;
    }
    else {
        CHECK_CONTEXT(context);
    }

    if (!(result = GMPy_MPFR_New(0, context))) {
        return NULL;
    }

    if (!(other = PySequence_List(other))) {
        Py_DECREF((PyObject*)result);
        TYPE_ERROR("argument must be an iterable");
        return NULL;
    }

    /* other contains a new list containing all the values from the
     * iterable. Now make sure each item in the list is an mpfr.
     */

    seq_length = PyList_GET_SIZE(other);
    for (i=0; i < seq_length; i++) {
        if (!(temp = GMPy_MPFR_From_Real(PyList_GET_ITEM(other, i), 1, context))) {
            Py_DECREF(other);
            Py_DECREF((PyObject*)result);
            TYPE_ERROR("all items in iterable must be real numbers");
            return NULL;
        }

        errcode = PyList_SetItem(other, i,(PyObject*)temp);
        if (errcode < 0) {
            Py_DECREF(other);
            Py_DECREF((PyObject*)result);
            TYPE_ERROR("all items in iterable must be real numbers");
            return NULL;
        }
    }

    /* create an array of pointers to the mpfr_t field of a Pympfr object */

    if (!(tab = (mpfr_ptr *)GMPY_MALLOC((sizeof(mpfr_srcptr) * seq_length)))) {
        Py_DECREF(other);
        Py_DECREF((PyObject*)result);
        return PyErr_NoMemory();
    }
    for (i=0; i < seq_length; i++) {
        temp = (MPFR_Object*)PyList_GET_ITEM(other, i);
        tab[i] = temp->f;
    }

    mpfr_clear_flags();
    result->rc = mpfr_sum(result->f, tab, seq_length, GET_MPFR_ROUND(context));
    Py_DECREF(other);
    GMPY_FREE(tab);

    _GMPy_MPFR_Cleanup(&result, context);
    return (PyObject*)result;
}
开发者ID:martingkelly,项目名称:gmpy,代码行数:68,代码来源:gmpy2_math.c


示例11: PyBobIpGaborGraph_init

static int PyBobIpGaborGraph_init(PyBobIpGaborGraphObject* self, PyObject* args, PyObject* kwargs) {
BOB_TRY
  char** kwlist1 = Graph_doc.kwlist(3);
  char** kwlist2 = Graph_doc.kwlist(2);
  char** kwlist3 = Graph_doc.kwlist(1);
  char** kwlist4 = Graph_doc.kwlist(0);

  // get the number of command line arguments
  Py_ssize_t nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);

  switch (nargs){
    case 1: {
      // two ways to call with one argument
      PyObject* k = Py_BuildValue("s", kwlist1[0]);
      auto k_ = make_safe(k);
      if (
        (kwargs && PyDict_Contains(kwargs, k)) ||
        (args && PyBobIoHDF5File_Check(PyTuple_GetItem(args, 0)))
      ){
        PyBobIoHDF5FileObject* hdf5;
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&", kwlist1, &PyBobIoHDF5File_Converter, &hdf5)) return -1;
        auto hdf5_ = make_safe(hdf5);

        self->cxx.reset(new bob::ip::gabor::Graph(*hdf5->f));
      } else {
        PyListObject* list;
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!", kwlist2, &PyList_Type, &list)) return -1;

        std::vector<blitz::TinyVector<int,2>> nodes(PyList_GET_SIZE(list));
        Py_ssize_t i = 0;
        for (auto nit = nodes.begin(); nit != nodes.end(); ++nit, ++i){
          // check that the object inside the list is a two-element int tuple
          if (!PyArg_ParseTuple(PyList_GET_ITEM(list, i), "ii", &((*nit)[0]), &((*nit)[1]))){
            PyErr_Format(PyExc_TypeError, "%s requires only tuples of two integral positions in the nodes list", Py_TYPE(self)->tp_name);
            return -1;
          }
        }
        self->cxx.reset(new bob::ip::gabor::Graph(nodes));
      }
      break;
    }

    case 3:{
      blitz::TinyVector<int,2> first, last, step;
      if (!PyArg_ParseTupleAndKeywords(args, kwargs, "(ii)(ii)(ii)", kwlist3, &first[0], &first[1], &last[0], &last[1], &step[0], &step[1])) return -1;
      self->cxx.reset(new bob::ip::gabor::Graph(first, last, step));

    }
    break;

    case 6:{
      blitz::TinyVector<int,2> right, left;
      int between, along, above, below;
      if (!PyArg_ParseTupleAndKeywords(args, kwargs, "(ii)(ii)iiii", kwlist4, &right[0], &right[1], &left[0], &left[1], &between, &along, &above, &below)) return -1;
      self->cxx.reset(new bob::ip::gabor::Graph(right, left,  between, along, above, below));
    }
    break;

    default:
      return -1;
  }

  return 0;
BOB_CATCH_MEMBER("Graph constructor", -1)
}
开发者ID:183amir,项目名称:bob.ip.gabor,代码行数:65,代码来源:graph.cpp


示例12: List_iterBegin

//=============================================================================
// List iteration functions 
// itemValue is borrowed from object (which is list). No refcounting
//=============================================================================
void List_iterBegin(JSOBJ obj, JSONTypeContext *tc)
{
	GET_TC(tc)->index =  0;
	GET_TC(tc)->size = PyList_GET_SIZE( (PyObject *) obj);
}
开发者ID:acdha,项目名称:ultrajson,代码行数:9,代码来源:objToJSON.c


示例13: find_method

// find and call a method on this object that matches the python args.
// typically called by way of pyjmethod when python invokes __call__.
//
// steals reference to self, methodname and args.
PyObject* find_method(JNIEnv *env,
                      PyObject *methodName,
                      Py_ssize_t methodCount,
                      PyObject *attr,
                      PyObject *args) {
    // all possible method candidates
    PyJmethod_Object **cand = NULL;
    Py_ssize_t         pos, i, listSize, argsSize;
    
    pos = i = listSize = argsSize = 0;

    // not really likely if we were called from pyjmethod, but hey...
    if(methodCount < 1) {
        PyErr_Format(PyExc_RuntimeError, "I have no methods.");
        return NULL;
    }

    if(!attr || !PyList_CheckExact(attr)) {
        PyErr_Format(PyExc_RuntimeError, "Invalid attr list.");
        return NULL;
    }
    
    cand = (PyJmethod_Object **)
        PyMem_Malloc(sizeof(PyJmethod_Object*) * methodCount);
    
    // just for safety
    for(i = 0; i < methodCount; i++)
        cand[i] = NULL;
    
    listSize = PyList_GET_SIZE(attr);
    for(i = 0; i < listSize; i++) {
        PyObject *tuple = PyList_GetItem(attr, i);               /* borrowed */

        if(PyErr_Occurred())
            break;
        
        if(!tuple || tuple == Py_None || !PyTuple_CheckExact(tuple))
            continue;

        if(PyTuple_Size(tuple) == 2) {
            PyObject *key = PyTuple_GetItem(tuple, 0);           /* borrowed */
            
            if(PyErr_Occurred())
                break;
            
            if(!key || !PyString_Check(key))
                continue;
            
            if(PyObject_Compare(key, methodName) == 0) {
                PyObject *method = PyTuple_GetItem(tuple, 1);    /* borrowed */
                if(pyjmethod_check(method))
                    cand[pos++] = (PyJmethod_Object *) method;
            }
        }
    }
    
    if(PyErr_Occurred())
        goto EXIT_ERROR;
    
    // makes more sense to work with...
    pos--;
    
    if(pos < 0) {
        // didn't find a method by that name....
        // that shouldn't happen unless the search above is broken.
        PyErr_Format(PyExc_NameError, "No such method.");
        goto EXIT_ERROR;
    }
    if(pos == 0) {
        // we're done, call that one
        PyObject *ret = pyjmethod_call_internal(cand[0], args);
        PyMem_Free(cand);
        return ret;
    }

    // first, find out if there's only one method that
    // has the correct number of args
    argsSize = PyTuple_Size(args);
    {
        PyJmethod_Object *matching = NULL;
        int               count    = 0;
        
        for(i = 0; i <= pos && cand[i]; i++) {
            // make sure method is fully initialized
            if(!cand[i]->parameters) {
                if(!pyjmethod_init(env, cand[i])) {
                    // init failed, that's not good.
                    cand[i] = NULL;
                    PyErr_Warn(PyExc_Warning, "pyjmethod init failed.");
                    continue;
                }
            }

            if(cand[i]->lenParameters == argsSize) {
                matching = cand[i];
                count++;
//.........这里部分代码省略.........
开发者ID:Kroisse,项目名称:jep,代码行数:101,代码来源:pyjobject.c


示例14: SpiDev_xfer2

static PyObject *
SpiDev_xfer2(SpiDevObject *self, PyObject *args)
{
	static char *msg = "Argument must be a list of at least one, "
				"but not more than 4096 integers";
	int status;
	uint16_t delay_usecs = 0;
	uint32_t speed_hz = 0;
	uint8_t bits_per_word = 0;
	uint16_t ii, len;
	PyObject *list;
	struct spi_ioc_transfer xfer;
	memset(&xfer, 0, sizeof(xfer));
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O|IHB:xfer2", &list, &speed_hz, &delay_usecs, &bits_per_word))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > SPIDEV_MAXPATH) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyLong_Check(val)) {
			PyErr_SetString(PyExc_TypeError, msg);
			free(txbuf);
			free(rxbuf);
			return NULL;
		}
		txbuf[ii] = (__u8)PyLong_AS_LONG(val);
	}

	xfer.tx_buf = (unsigned long)txbuf;
	xfer.rx_buf = (unsigned long)rxbuf;
	xfer.len = len;
	xfer.delay_usecs = delay_usecs;
	xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz;
	xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;

	status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		free(txbuf);
		free(rxbuf);
		return NULL;
	}

	list = PyList_New(len);
	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}
	// WA:
	// in CS_HIGH mode CS isnt pulled to low after transfer
	// reading 0 bytes doesn't really matter but brings CS down
	// tomdean:
	// Stop generating an extra CS except in mode CS_HOGH
	if (self->mode & SPI_CS_HIGH) status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);

	return list;
}
开发者ID:MiyamonY,项目名称:py-spidev,代码行数:74,代码来源:spidev_module.c


示例15: qpycore_qmetaobject_connectslotsbyname

void qpycore_qmetaobject_connectslotsbyname(QObject *qobj,
        PyObject *qobj_wrapper)
{
    // Get the class attributes.
    PyObject *dir = PyObject_Dir((PyObject *)Py_TYPE(qobj_wrapper));

    if (!dir)
        return;

    PyObject *slot_obj = 0;

    for (SIP_SSIZE_T li = 0; li < PyList_GET_SIZE(dir); ++li)
    {
        PyObject *name_obj = PyList_GET_ITEM(dir, li);

        // Get the slot object.
        Py_XDECREF(slot_obj);
        slot_obj = PyObject_GetAttr(qobj_wrapper, name_obj);

        if (!slot_obj)
            continue;

        // Ignore it if it is not a callable.
        if (!PyCallable_Check(slot_obj))
            continue;

        // Use the signature attribute instead of the name if there is one.
        PyObject *sigattr = PyObject_GetAttr(slot_obj,
                qpycore_signature_attr_name);

        if (sigattr)
        {
            for (SIP_SSIZE_T i = 0; i < PyList_GET_SIZE(sigattr); ++i)
            {
                PyObject *decoration = PyList_GET_ITEM(sigattr, i);
                Chimera::Signature *sig = Chimera::Signature::fromPyObject(decoration);
                QByteArray args = sig->arguments();

                if (!args.isEmpty())
                    connect(qobj, slot_obj, sig->name(), args);
            }

            Py_DECREF(sigattr);
        }
        else
        {
            const char *ascii_name = sipString_AsASCIIString(&name_obj);

            if (!ascii_name)
                continue;

            PyErr_Clear();

            connect(qobj, slot_obj, QByteArray(ascii_name), QByteArray());

            Py_DECREF(name_obj);
        }
    }

    Py_XDECREF(slot_obj);
    Py_DECREF(dir);
}
开发者ID:AlexDoul,项目名称:PyQt4,代码行数:62,代码来源:qpycore_qmetaobject_helpers.cpp


示例16: PyCode_Optimize


//.........这里部分代码省略.........
				tgt = GETJUMPTGT(codestr, (i+1));
				if (codestr[tgt] != POP_TOP)
					continue;
				j = GETARG(codestr, i+1) + 1;
				codestr[i] = JUMP_IF_TRUE;
				SETARG(codestr, i, j);
				codestr[i+3] = POP_TOP;
				codestr[i+4] = NOP;
				break;

				/* not a is b -->  a is not b
				   not a in b -->  a not in b
				   not a is not b -->  a is b
				   not a not in b -->  a in b
				*/
			case COMPARE_OP:
				j = GETARG(codestr, i);
				if (j < 6  ||  j > 9  ||
				    codestr[i+3] != UNARY_NOT  || 
				    !ISBASICBLOCK(blocks,i,4))
					continue;
				SETARG(codestr, i, (j^1));
				codestr[i+3] = NOP;
				break;

				/* Replace LOAD_GLOBAL/LOAD_NAME None
                                   with LOAD_CONST None */
			case LOAD_NAME:
			case LOAD_GLOBAL:
				j = GETARG(codestr, i);
				name = PyString_AsString(PyTuple_GET_ITEM(names, j));
				if (name == NULL  ||  strcmp(name, "None") != 0)
					continue;
				for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
					if (PyList_GET_ITEM(consts, j) == Py_None)
						break;
				}
				if (j == PyList_GET_SIZE(consts)) {
					if (PyList_Append(consts, Py_None) == -1)
					        goto exitError;
				}
				assert(PyList_GET_ITEM(consts, j) == Py_None);
				codestr[i] = LOAD_CONST;
				SETARG(codestr, i, j);
				cumlc = lastlc + 1;
				break;

				/* Skip over LOAD_CONST trueconst
                                   JUMP_IF_FALSE xx  POP_TOP */
			case LOAD_CONST:
				cumlc = lastlc + 1;
				j = GETARG(codestr, i);
				if (codestr[i+3] != JUMP_IF_FALSE  ||
				    codestr[i+6] != POP_TOP  ||
				    !ISBASICBLOCK(blocks,i,7)  ||
				    !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
					continue;
				memset(codestr+i, NOP, 7);
				cumlc = 0;
				break;

				/* Try to fold tuples of constants (includes a case for lists
				   which are only used for "in" and "not in" tests).
				   Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
				   Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
				   Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
开发者ID:Androtos,项目名称:toolchain_benchmark,代码行数:67,代码来源:peephole.c


示例17: fcicreate

static PyObject* fcicreate(PyObject* obj, PyObject* args)
{
    char *cabname, *p;
    PyObject *files;
    CCAB ccab;
    HFCI hfci;
    ERF erf;
    Py_ssize_t i;


    if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files))
        return NULL;

    if (!PyList_Check(files)) {
        PyErr_SetString(PyExc_TypeError, "FCICreate expects a list");
        return NULL;
    }

    ccab.cb = INT_MAX; /* no need to split CAB into multiple media */
    ccab.cbFolderThresh = 1000000; /* flush directory after this many bytes */
    ccab.cbReserveCFData = 0;
    ccab.cbReserveCFFolder = 0;
    ccab.cbReserveCFHeader = 0;

    ccab.iCab = 1;
    ccab.iDisk 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PyList_GetItem函数代码示例发布时间:2022-05-30
下一篇:
C++ PyList_Check函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap