示例#1
0
static PyObject *
PLy_result_slice(PyObject *arg, Py_ssize_t lidx, Py_ssize_t hidx)
{
	PLyResultObject *ob = (PLyResultObject *) arg;

	return PyList_GetSlice(ob->rows, lidx, hidx);
}
示例#2
0
文件: _list.hpp 项目: LenxWei/py11
 /** slice, [i:j].
  * @throw type_err
  */
 obj sub(int i, int j = std::numeric_limits<int>::max())const
 {
     PyObject* p = PyList_GetSlice(_p, i, j);
     if(!p)
         throw type_err("sub failed");
     return p;
 }
示例#3
0
static PyObject*
validate_list( Member* member, PyObject* owner, PyObject* oldvalue, PyObject* newvalue )
{
    if( !PyList_Check( newvalue ) )
        return validate_type_fail( member, owner, newvalue, "list" );
    Py_ssize_t size = PyList_GET_SIZE( newvalue );
    PyObjectPtr listcopy( PyList_GetSlice( newvalue, 0, size ) );
    if( !listcopy )
        return 0;
    if( member->validate_context != Py_None )
    {
        if( !Member_Check( member->validate_context ) )
            return py_bad_internal_call( "validate_list() context is not a Member or None" );
        Member* item_member = reinterpret_cast<Member*>( member->validate_context );
        for( Py_ssize_t i = 0; i < size; ++i )
        {
            PyObject* item = PyList_GET_ITEM( listcopy.get(), i );
            PyObject* valid_item = member_validate( item_member, owner, _py_null, item );
            if( !valid_item )
                return 0;
            if( valid_item != item )
                PyList_SetItem( listcopy.get(), i, valid_item ); // this steals the owned ref gained by member_validate
        }
    }
    return listcopy.release();
}
示例#4
0
/*	Set the slice of LDAPValueList between `ilow` and `ihigh` to the contents of `itemlist`.
	The `itemlist` must be containing unique elements. New items are append to the added list,
	and removed items are append to the deleted list. The `itemlist` may be NULL, indicating
	the assignment of an empty list (slice deletion).
*/
int
LDAPValueList_SetSlice(LDAPValueList *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *itemlist) {
	PyObject *remove;

	/* Copying the removable items from LDAPValueList to deleted list.*/
	remove = PyList_GetSlice((PyObject *)self, ilow, ihigh);
	if (remove == NULL) return -1;
	if (balancing(remove, self->added) != 0) {
		Py_DECREF(remove);
		return -1;
	}
	if (UniqueList_Extend(self->deleted, remove) != 0) {
		Py_DECREF(remove);
		return -1;
	}
	Py_DECREF(remove);

	/* Copying new items to the added list.*/
	if (itemlist != NULL) {
		if (balancing(itemlist, self->deleted) != 0) return -1;
		if (UniqueList_Extend(self->added, itemlist) != 0) return -1;
	}

    return UniqueList_SetSlice((UniqueList *)self, ilow, ihigh, itemlist);
}
示例#5
0
static PyObject*
default_list( Member* member, PyObject* owner )
{
    if( member->default_context == Py_None )
        return PyList_New( 0 );
    if( !PyList_Check( member->default_context ) )
        return py_type_fail( "expect a list as default context" );
    Py_ssize_t size = PyList_GET_SIZE( member->default_context );
    return PyList_GetSlice( member->default_context, 0, size );
}
示例#6
0
文件: locks.c 项目: chenbk85/jega
static PyObject*
condition_notify(ConditionObject *self, int num)
{
    PyObject *res, *waiters;
    PyObject *iter, *item;
    
    DEBUG("self:%p", self);
    res = call_method((PyObject*)self, "_is_owned");
    if (res == NULL) {
        return NULL;
    }
    
    if (PyObject_Not(res)) {
        Py_DECREF(res);
        PyErr_SetString(PyExc_RuntimeError, "cannot release un-acquired lock");
        return NULL;
    }
    Py_DECREF(res);
    waiters = PyList_GetSlice(self->waiters, 0, num);
    if (waiters == NULL) {
        return NULL;
    }
    if (PyObject_Not(waiters)) {
        Py_RETURN_NONE;
    }

    iter = PyObject_GetIter(waiters);
    if (PyErr_Occurred()) {
        return NULL;
    }

    while ((item =  PyIter_Next(iter))) {
        res = semaphore_release((SemaphoreObject*)item);
        Py_XDECREF(res);
        if (res == NULL) {
            Py_DECREF(item);
            goto err;
        }
        if (remove_from_list((PyListObject*)self->waiters, item) == -1) {
            Py_DECREF(item);
            goto err;
        }
        Py_DECREF(item);
        /* DEBUG("self->waiters len:%d", PyList_Size(self->waiters)); */
    }
    Py_DECREF(waiters);
    Py_DECREF(iter);
    Py_RETURN_NONE;
err:
    Py_DECREF(waiters);
    Py_DECREF(iter);
    return NULL;

}
示例#7
0
文件: pepy.cpp 项目: Arbiv/pe-parse
static PyObject *pepy_parsed_get_bytes(PyObject *self, PyObject *args) {
	uint64_t start, idx;
	uint8_t b;
	Py_ssize_t len;
	PyObject *byte, *tmp, *ret, *newlist;

	if (!PyArg_ParseTuple(args, "KK:pepy_parsed_get_bytes", &start, &len))
		return NULL;

	/*
	 * XXX: I don't think this is the best way to do this. I want a
	 * ByteArray object to be returned so first put each byte in a
	 * list and then call PyByteArray_FromObject to get the byte array.
	 */
	tmp = PyList_New(len);
	if (!tmp) {
		PyErr_SetString(pepy_error, "Unable to create initial list.");
		return NULL;
	}

	for (idx = 0; idx < len; idx++) {
		if (!ReadByteAtVA(((pepy_parsed *) self)->pe, start + idx, b))
			break;

		byte = PyInt_FromLong(b);
		if (!byte) {
			Py_DECREF(tmp);
			PyErr_SetString(pepy_error, "Unable to create integer object.");
			return NULL;
		}
		PyList_SET_ITEM(tmp, idx, byte);
		Py_DECREF(byte);
	}

	/* Didn't get all of it for some reason, so give back what we have. */
	if (idx < len) {
		newlist = PyList_GetSlice(tmp, 0, idx);
		if (!newlist) {
			PyErr_SetString(pepy_error, "Unable to create new list.");
			return NULL;
		}
		Py_DECREF(tmp);
		tmp = newlist;
	}

	ret = PyByteArray_FromObject(tmp);
	if (!ret) {
		PyErr_SetString(pepy_error, "Unable to create new list.");
		return NULL;
	}
	Py_DECREF(tmp);

	return ret;
}
static PyObject *
wrap_slice(PyObject *self, Py_ssize_t start, Py_ssize_t end)
{
    PyObject *obj = Proxy_GET_OBJECT(self);
    if (PyList_Check(obj)) {
        return PyList_GetSlice(obj, start, end);
    }
    else if (PyTuple_Check(obj)) {
        return PyTuple_GetSlice(obj, start, end);
    }
    else {
        return PySequence_GetSlice(obj, start, end);
    }
}
示例#9
0
PyObject *
PySequence_List(PyObject *v)
{
	PySequenceMethods *m;

	if (v == NULL)
		return null_error();

	if (PyList_Check(v))
		return PyList_GetSlice(v, 0, PyList_GET_SIZE(v));

	m = v->ob_type->tp_as_sequence;
	if (m && m->sq_item) {
		int i;
		PyObject *l;
		int n = PySequence_Size(v);
		if (n < 0)
			return NULL;
		l = PyList_New(n);
		if (l == NULL)
			return NULL;
		for (i = 0; ; i++) {
			PyObject *item = (*m->sq_item)(v, i);
			if (item == NULL) {
				if (PyErr_ExceptionMatches(PyExc_IndexError))
					PyErr_Clear();
				else {
					Py_DECREF(l);
					l = NULL;
				}
				break;
			}
			if (i < n)
				PyList_SET_ITEM(l, i, item);
			else if (PyList_Append(l, item) < 0) {
				Py_DECREF(l);
				l = NULL;
				break;
			}
		}
		if (i < n && l != NULL) {
			if (PyList_SetSlice(l, i, n, (PyObject *)NULL) != 0) {
				Py_DECREF(l);
				l = NULL;
			}
		}
		return l;
	}
	return type_error("list() argument must be a sequence");
}
示例#10
0
static PyObject *Scopeable_trim(PyObject *self, PyObject *args) {
  PyObject *dictList, *newList;
  int len;
  if (!PyArg_ParseTuple(args, "O", &self)) {
    return NULL;
  }
  dictList=GET_DICTLIST(self);
  len=PyList_Size(dictList);
  if (len>1) {
    newList=PyList_GetSlice(dictList, len-1, len);
    PyMapping_SetItemString(((PyInstanceObject *)self)->in_dict, DICTLIST, newList);
    Py_DECREF(newList);
    _resetMash(self);
    Py_DECREF(dictList);
    dictList=NULL;
  }
  Py_INCREF(Py_None);
  return Py_None;
}
示例#11
0
static PyObject *Scopeable_pop(PyObject *self, PyObject *args) {
  PyObject *dictList, *popped, *ndl;
  int len;
  if (!PyArg_ParseTuple(args, "O", &self)) {
    return NULL;
  }
  dictList=GET_DICTLIST(self);
  len=PyList_Size(dictList);
  if (len) {
    popped=PyList_GetItem(dictList, len-1);
    Py_INCREF(popped);
    ndl=PyList_GetSlice(dictList, 0, len-1);
    Py_DECREF(ndl);
    PyMapping_SetItemString(((PyInstanceObject *)self)->in_dict, DICTLIST, ndl);

    _resetMash(self);
    return popped;
  }
  PyErr_SetString(PyExc_IndexError, "pop from empty list");
  Py_DECREF(dictList); 
  dictList=NULL;
  return NULL;
  
}  
示例#12
0
static PyObject *Scopeable_mash(PyObject *self, PyObject *args) {
  PyObject *nd, *dictList, *dlCopy;
  int i,len;
  if (!PyArg_ParseTuple(args, "O", &self)) {
    return NULL;
  }
  REFCNT("self", self);  
  nd=PyDict_New();
  dictList=PyObject_GetAttrString(self, DICTLIST);

  len=PyList_Size(dictList);
  dlCopy=PyList_GetSlice(dictList, 0, len);

  for (i=len-1;i>=0;i--) {
    PyObject *d, *key, *value;
    int pos=0;
    d=PyList_GetItem(dlCopy, i);
    if (!PyDict_Check(d)) {
      PyErr_SetString(PyExc_TypeError, "dictionary expected inside dictList");
      Py_DECREF(dictList);
      Py_DECREF(nd);
      return NULL;
    }
    while (PyDict_Next(d, &pos, &key, &value)) {
/*       Py_INCREF(key); */
/*       Py_INCREF(value); */
      PyDict_SetItem(nd, key, value);
    }
  }
  Py_DECREF(dictList);
  Py_DECREF(dlCopy);

  REFCNT("dictList", dictList);
  REFCNT("nd", nd);
  return nd;
}
 List List::getSlice(int start, int stop) const
 {
     return List(BorrowedReference(PyList_GetSlice(mPtr, start, stop)));
 }
示例#14
0
/* This is a hacked version of Python's fileobject.c:file_writelines(). */
static PyObject *
fcgi_Stream_writelines(fcgi_Stream *self, PyObject *seq)
{
#define CHUNKSIZE 1000
    FCGX_Stream *s;
    PyObject *list, *line;
    PyObject *it;   /* iter(seq) */
    PyObject *result;
    int i, j, index, len, nwritten, islist;

    fcgi_Stream_Check();

    s = *(self->s);

    result = NULL;
    list = NULL;
    islist = PyList_Check(seq);
    if  (islist)
        it = NULL;
    else {
        it = PyObject_GetIter(seq);
        if (it == NULL) {
            PyErr_SetString(PyExc_TypeError,
                "writelines() requires an iterable argument");
            return NULL;
        }
        /* From here on, fail by going to error, to reclaim "it". */
        list = PyList_New(CHUNKSIZE);
        if (list == NULL)
            goto error;
    }

    /* Strategy: slurp CHUNKSIZE lines into a private list,
       checking that they are all strings, then write that list
       without holding the interpreter lock, then come back for more. */
    for (index = 0; ; index += CHUNKSIZE) {
        if (islist) {
            Py_XDECREF(list);
            list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
            if (list == NULL)
                goto error;
            j = PyList_GET_SIZE(list);
        }
        else {
            for (j = 0; j < CHUNKSIZE; j++) {
                line = PyIter_Next(it);
                if (line == NULL) {
                    if (PyErr_Occurred())
                        goto error;
                    break;
                }
                PyList_SetItem(list, j, line);
            }
        }
        if (j == 0)
            break;

        /* Check that all entries are indeed strings. If not,
           apply the same rules as for file.write() and
           convert the results to strings. This is slow, but
           seems to be the only way since all conversion APIs
           could potentially execute Python code. */
        for (i = 0; i < j; i++) {
            PyObject *v = PyList_GET_ITEM(list, i);
            if (!PyString_Check(v)) {
                    const char *buffer;
                    int len;
                if (PyObject_AsReadBuffer(v,
                          (const void**)&buffer,
                                &len) ||
                     PyObject_AsCharBuffer(v,
                               &buffer,
                               &len)) {
                    PyErr_SetString(PyExc_TypeError,
            "writelines() argument must be a sequence of strings");
                    goto error;
                }
                line = PyString_FromStringAndSize(buffer,
                                  len);
                if (line == NULL)
                    goto error;
                Py_DECREF(v);
                PyList_SET_ITEM(list, i, line);
            }
        }

        /* Since we are releasing the global lock, the
           following code may *not* execute Python code. */
        Py_BEGIN_ALLOW_THREADS
        errno = 0;
        for (i = 0; i < j; i++) {
                line = PyList_GET_ITEM(list, i);
            len = PyString_GET_SIZE(line);
            nwritten = FCGX_PutStr(PyString_AS_STRING(line), len, s);
            if (nwritten != len) {
                Py_BLOCK_THREADS
                if (nwritten < 0) {
                    PyErr_SetString(PyExc_IOError, "Write failed");
                } else {
                    char msgbuf[256];
                    PyOS_snprintf(msgbuf, sizeof(msgbuf),
                          "Write failed, wrote %d of %d bytes",
                          nwritten, len);
                    PyErr_SetString(PyExc_IOError, msgbuf);
                }
                goto error;
            }
        }
        Py_END_ALLOW_THREADS

        if (j < CHUNKSIZE)
            break;
    }
示例#15
0
            PyObject* initialize(PyObject* self, PyObject *originalTimeSeries, PyObject *calculatedTimesSeries)
            {
                if (0 < PySequence_Size(PyObject_GetAttrString(self, "_errorValues"))) {
                    PyErr_SetString(PyExc_StandardError, "An ErrorMeasure can only be initialized once.");
                    return NULL;
                }

                PyObject_CallMethodObjArgs(originalTimeSeries,    PyString_FromString("sort_timeseries"), NULL);
                PyObject_CallMethodObjArgs(calculatedTimesSeries, PyString_FromString("sort_timeseries"), NULL);

                int index = 0;
                PyObject* orgPair;
                PyObject* calcPair;
                PyObject* local_error;

                PyObject* _errorValues = PyList_New(PyObject_Length(originalTimeSeries));
                PyObject* _errorDates = PyList_New(PyObject_Length(originalTimeSeries));
                PyObject* iterator1 = PyObject_GetIter(originalTimeSeries);

                while ((orgPair = PyIter_Next(iterator1))) {

                    PyObject* iterator2 = PyObject_GetIter(calculatedTimesSeries);

                    while ((calcPair = PyIter_Next(iterator2))) {
                        if (PyFloat_AsDouble(PySequence_GetItem(orgPair, 0)) != PyFloat_AsDouble(PySequence_GetItem(calcPair, 0)))
                            continue;

                        local_error = PyObject_CallMethodObjArgs(self, PyString_FromString("local_error"),
                                                                       PyList_GetSlice(orgPair, 1, PyList_Size(orgPair)),
                                                                       PyList_GetSlice(calcPair, 1, PyList_Size(calcPair)),
                                                                       NULL
                                                                );

                        //NotImplemented Exception
                        if(!local_error || PyErr_Occurred()) {
                            PyErr_SetString(PyExc_NotImplementedError, "");
                            return NULL;
                        }

                        PyList_SetItem(_errorValues, index, local_error);
                        PyList_SetItem(_errorDates, index, PySequence_GetItem(orgPair, 0));
                        ++index;

                        Py_DECREF(calcPair);
                    }

                    Py_DECREF(iterator2);
                    Py_DECREF(orgPair);
                }

                Py_DECREF(iterator1);

                //Cut off trailing zeroes
                _errorValues = PyList_GetSlice(_errorValues, 0, index);
                _errorDates = PyList_GetSlice(_errorDates, 0, index);

                //return False, if the error cannot be calculated
                double _minimalErrorCalculationPercentage = PyFloat_AsDouble(PyObject_GetAttrString(self, "_minimalErrorCalculationPercentage"));

                if(PyList_Size(_errorValues) < (_minimalErrorCalculationPercentage * (float)PyObject_Length(originalTimeSeries)))
                    Py_RETURN_FALSE;

                PyObject_SetAttrString(self, "_errorValues", _errorValues);
                PyObject_SetAttrString(self, "_errorDates", _errorDates);
                Py_RETURN_TRUE;
            }
示例#16
0
文件: cdefer.c 项目: anrysev/twisted
static PyObject *cdefer_Deferred_get_callbacks(PyObject *o, void *context) {
    cdefer_Deferred *self = (cdefer_Deferred *)o;
    PyObject *cb = self->callbacks;
    return PyList_GetSlice(cb, self->callback_index, PyList_GET_SIZE(cb));
}
示例#17
0
PyObject* ctrlp_fuzzycomt_sorted_match_list(PyObject* self, PyObject* args) {
    PyObject *paths, *abbrev, *returnlist;
    Py_ssize_t limit;
    char *mmode;
    int i;
    int max;

    if (!PyArg_ParseTuple(args, "OOns", &paths, &abbrev, &limit, &mmode)) {
       return NULL;
    }
    returnlist = PyList_New(0);

    // Type checking
    if (PyList_Check(paths) != 1) {
        PyErr_SetString(PyExc_TypeError,"expected a list");
        return 0;
    }

    if (PyString_Check(abbrev) != 1) {
        PyErr_SetString(PyExc_TypeError,"expected a string");
        return 0;
    }

    matchobj_t matches[PyList_Size(paths)];

    if ( (limit > PyList_Size(paths)) || (limit == 0) ) {
        limit = PyList_Size(paths);
    }

    if ( PyString_Size(abbrev) == 0) {
        // if string is empty - just return first (:param limit) lines
        PyObject *initlist;

        initlist = PyList_GetSlice(paths,0,limit);
        return initlist;
    }
    else {
        // find matches and place them into matches array.
        ctrlp_get_line_matches(paths,abbrev, matches, mmode);

        // sort array of struct by struct.score key
        qsort(matches,
              PyList_Size(paths),
              sizeof(matchobj_t),
              ctrlp_comp_score_alpha);
    }

    for (i = 0, max = PyList_Size(paths); i < max; i++) {
       if (i == limit)
          break;
        if ( matches[i].score> 0 ) {
            // TODO it retuns non-encoded string. So cyrillic literals
            // arent properly showed.
            // There are PyString_AsDecodedObject, it works in interactive
            // session but it fails in Vim for some reason
            // (probably because we dont know what encoding vim returns)
            PyList_Append(returnlist,matches[i].str);
        }
    }

    return returnlist;
}
示例#18
0
/*	This function is based on list_ass_subscript from Python source listobject.c.
	But it uses LDAPValueList's setslice and setitem functions instead of memory opertation.
	It is probably a much more slower, but cleaner solution.
*/
static int
LVL_ass_subscript(LDAPValueList *self, PyObject *item, PyObject *value) {
    size_t cur;
	Py_ssize_t i;
	Py_ssize_t start, stop, step, slicelength;
    PyObject *seq;
    PyObject **seqitems;

	if (PyIndex_Check(item)) {
		i = PyNumber_AsSsize_t(item, PyExc_IndexError);
		if (i == -1 && PyErr_Occurred()) return -1;
		if (i < 0) i += PyList_GET_SIZE(self);
		return LVL_ass_item(self, i, value);
    } else if (PySlice_Check(item)) {
    	if (PySlice_GetIndicesEx(item, Py_SIZE(self), &start, &stop, &step, &slicelength) < 0) {
    		return -1;
    	}

    	if (step == 1) return LDAPValueList_SetSlice(self, start, stop, value);

        /* Make sure s[5:2] = [..] inserts at the right place:
           before 5, not before 2. */
    	if ((step < 0 && start < stop) || (step > 0 && start > stop)) {
    		stop = start;
    	}

    	if (value == NULL) {
    		/* delete slice */
            if (slicelength <= 0) return 0;

            if (step < 0) {
                stop = start + 1;
                start = stop + step*(slicelength - 1) - 1;
                step = -step;
            }

            for (cur = start, i = 0; cur < (size_t)stop; cur += step, i++) {
            	if (LDAPValueList_SetSlice(self, cur-i, cur+1-i, (PyObject *)NULL) != 0) {
            		return -1;
            	}
            }
            return 0;
        } else {
        	/* assign slice */
        	/* protect against a[::-1] = a */
        	if (self == (LDAPValueList*)value) {
        		seq = PyList_GetSlice(value, 0, PyList_GET_SIZE(value));
        	} else {
        		seq = PySequence_Fast(value, "must assign iterable to extended slice");
        	}
        	if (!seq) return -1;

        	if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
        		PyErr_Format(PyExc_ValueError, "attempt to assign sequence of size %zd to extended slice of "
        				"size %zd", PySequence_Fast_GET_SIZE(seq), slicelength);
        		Py_DECREF(seq);
        		return -1;
        	}

        	if (!slicelength) {
        		Py_DECREF(seq);
        		return 0;
        	}

        	seqitems = PySequence_Fast_ITEMS(seq);
        	for (cur = start, i = 0; i < slicelength; cur += (size_t)step, i++) {
        		if (LDAPValueList_SetItem(self, cur, seqitems[i]) != 0) {
        			return -1;
        		}
        	}
        	Py_DECREF(seq);
        	return 0;
        }
    } else {
    	PyErr_Format(PyExc_TypeError, "list indices must be integers, not %.200s", item->ob_type->tp_name);
    	return -1;
    }
}