Example #1
0
PyObject *py_uwsgi_spit(PyObject * self, PyObject * args) {
    PyObject *headers, *head;
    PyObject *h_key, *h_value;
    int i, j;

    struct wsgi_request *wsgi_req = current_wsgi_req(&uwsgi);

#ifndef UNBIT
    int base = 0;
#else
    int base = 4;
#endif

    // use writev()

    head = PyTuple_GetItem(args, 0);
    if (!head) {
        goto clear;
    }

    if (!PyString_Check(head)) {
        fprintf(stderr, "http status must be a string !\n");
        goto clear;
    }


#ifndef UNBIT
    if (uwsgi.shared->options[UWSGI_OPTION_CGI_MODE] == 0) {
        base = 4;
#endif


        if (wsgi_req->protocol_len == 0) {
            wsgi_req->hvec[0].iov_base = (char *) http_protocol;
            wsgi_req->protocol_len = 8;
        }
        else {
            wsgi_req->hvec[0].iov_base = wsgi_req->protocol;
        }

        wsgi_req->hvec[0].iov_len = wsgi_req->protocol_len;
        wsgi_req->hvec[1].iov_base = " ";
        wsgi_req->hvec[1].iov_len = 1;
#ifdef PYTHREE
        wsgi_req->hvec[2].iov_base = PyBytes_AsString(PyUnicode_AsASCIIString(head));
        wsgi_req->hvec[2].iov_len = strlen(wsgi_req->hvec[2].iov_base);
#else
        wsgi_req->hvec[2].iov_base = PyString_AsString(head);
        wsgi_req->hvec[2].iov_len = PyString_Size(head);
#endif
        wsgi_req->status = atoi(wsgi_req->hvec[2].iov_base);
        wsgi_req->hvec[3].iov_base = nl;
        wsgi_req->hvec[3].iov_len = NL_SIZE;
#ifndef UNBIT
    }
    else {
        // drop http status on cgi mode
        base = 3;
        wsgi_req->hvec[0].iov_base = "Status: ";
        wsgi_req->hvec[0].iov_len = 8;
#ifdef PYTHREE
        wsgi_req->hvec[1].iov_base = PyBytes_AsString(PyUnicode_AsASCIIString(head));
        wsgi_req->hvec[1].iov_len = strlen(wsgi_req->hvec[1].iov_base);
#else
        wsgi_req->hvec[1].iov_base = PyString_AsString(head);
        wsgi_req->hvec[1].iov_len = PyString_Size(head);
#endif
        wsgi_req->status = atoi(wsgi_req->hvec[1].iov_base);
        wsgi_req->hvec[2].iov_base = nl;
        wsgi_req->hvec[2].iov_len = NL_SIZE;
    }
#endif


#ifdef UNBIT
    if (wsgi_req->unbit_flags & (unsigned long long) 1) {
        if (tmp_dir_fd >= 0 && tmp_filename[0] != 0 && wsgi_req->status == 200 && wsgi_req->method_len == 3 && wsgi_req->method[0] == 'G' && wsgi_req->method[1] == 'E' && wsgi_req->method[2] == 'T') {
            save_to_disk = openat(tmp_dir_fd, tmp_filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP);
        }
    }
#endif


    headers = PyTuple_GetItem(args, 1);
    if (!headers) {
        goto clear;
    }
    if (!PyList_Check(headers)) {
        fprintf(stderr, "http headers must be in a python list\n");
        goto clear;
    }
    wsgi_req->header_cnt = PyList_Size(headers);



    if (wsgi_req->header_cnt > uwsgi.max_vars) {
        wsgi_req->header_cnt = uwsgi.max_vars;
    }
    for (i = 0; i < wsgi_req->header_cnt; i++) {
        j = (i * 4) + base;
        head = PyList_GetItem(headers, i);
        if (!head) {
            goto clear;
        }
        if (!PyTuple_Check(head)) {
            fprintf(stderr, "http header must be defined in a tuple !\n");
            goto clear;
        }
        h_key = PyTuple_GetItem(head, 0);
        if (!h_key) {
            goto clear;
        }
        h_value = PyTuple_GetItem(head, 1);
        if (!h_value) {
            goto clear;
        }
#ifdef PYTHREE
        wsgi_req->hvec[j].iov_base = PyBytes_AsString(PyUnicode_AsASCIIString(h_key));
        wsgi_req->hvec[j].iov_len = strlen(wsgi_req->hvec[j].iov_base);
#else
        wsgi_req->hvec[j].iov_base = PyString_AsString(h_key);
        wsgi_req->hvec[j].iov_len = PyString_Size(h_key);
#endif
        wsgi_req->hvec[j + 1].iov_base = h_sep;
        wsgi_req->hvec[j + 1].iov_len = H_SEP_SIZE;
#ifdef PYTHREE
        wsgi_req->hvec[j + 2].iov_base = PyBytes_AsString(PyUnicode_AsASCIIString(h_value));
        wsgi_req->hvec[j + 2].iov_len = strlen(wsgi_req->hvec[j + 2].iov_base);
#else
        wsgi_req->hvec[j + 2].iov_base = PyString_AsString(h_value);
        wsgi_req->hvec[j + 2].iov_len = PyString_Size(h_value);
#endif
        wsgi_req->hvec[j + 3].iov_base = nl;
        wsgi_req->hvec[j + 3].iov_len = NL_SIZE;
        //fprintf(stderr, "%.*s: %.*s\n", wsgi_req->hvec[j].iov_len, (char *)wsgi_req->hvec[j].iov_base, wsgi_req->hvec[j+2].iov_len, (char *) wsgi_req->hvec[j+2].iov_base);
    }


    // \r\n
    j = (i * 4) + base;
    wsgi_req->hvec[j].iov_base = nl;
    wsgi_req->hvec[j].iov_len = NL_SIZE;

    wsgi_req->headers_size = writev(wsgi_req->poll.fd, wsgi_req->hvec, j + 1);
    if (wsgi_req->headers_size < 0) {
        uwsgi_error("writev()");
    }

    Py_INCREF(uwsgi.wsgi_writeout);


    return uwsgi.wsgi_writeout;

clear:

    Py_INCREF(Py_None);
    return Py_None;
}
Example #2
0
static PyObject *sendmsg_sendmsg(PyObject *self, PyObject *args, PyObject *keywds) {

    int fd;
    int flags = 0;
    Py_ssize_t sendmsg_result, iovec_length;
    struct msghdr message_header;
    struct iovec iov[1];
    PyObject *ancillary = NULL;
    PyObject *iterator = NULL;
    PyObject *item = NULL;
    PyObject *result_object = NULL;

    static char *kwlist[] = {"fd", "data", "flags", "ancillary", NULL};

    if (!PyArg_ParseTupleAndKeywords(
            args, keywds, "it#|iO:sendmsg", kwlist,
            &fd,
            &iov[0].iov_base,
            &iovec_length,
            &flags,
            &ancillary)) {
        return NULL;
    }

    iov[0].iov_len = iovec_length;

    message_header.msg_name = NULL;
    message_header.msg_namelen = 0;

    message_header.msg_iov = iov;
    message_header.msg_iovlen = 1;

    message_header.msg_control = NULL;
    message_header.msg_controllen = 0;

    message_header.msg_flags = 0;

    if (ancillary) {

        if (!PyList_Check(ancillary)) {
            PyErr_Format(PyExc_TypeError,
                         "send1msg argument 3 expected list, got %s",
                         ancillary->ob_type->tp_name);
            goto finished;
        }

        iterator = PyObject_GetIter(ancillary);

        if (iterator == NULL) {
            goto finished;
        }

        size_t all_data_len = 0;

        /* First we need to know how big the buffer needs to be in order to
           have enough space for all of the messages. */
        while ( (item = PyIter_Next(iterator)) ) {
            int type, level;
            Py_ssize_t data_len;
            size_t prev_all_data_len;
            char *data;

            if (!PyTuple_Check(item)) {
                PyErr_Format(PyExc_TypeError,
                             "send1msg argument 3 expected list of tuple, "
                             "got list containing %s",
                             item->ob_type->tp_name);
                goto finished;
            }

            if (!PyArg_ParseTuple(
                        item, "iit#:sendmsg ancillary data (level, type, data)",
                        &level, &type, &data, &data_len)) {
                goto finished;
            }

            prev_all_data_len = all_data_len;
            all_data_len += CMSG_SPACE(data_len);

            Py_DECREF(item);
            item = NULL;

            if (all_data_len < prev_all_data_len) {
                PyErr_Format(PyExc_OverflowError,
                             "Too much msg_control to fit in a size_t: %zu",
                             prev_all_data_len);
                goto finished;
            }
        }

        Py_DECREF(iterator);
        iterator = NULL;

        /* Allocate the buffer for all of the ancillary elements, if we have
         * any.  */
        if (all_data_len) {
            if (all_data_len > SOCKLEN_MAX) {
                PyErr_Format(PyExc_OverflowError,
                             "Too much msg_control to fit in a socklen_t: %zu",
                             all_data_len);
                goto finished;
            }
            message_header.msg_control = PyMem_Malloc(all_data_len);
            if (!message_header.msg_control) {
                PyErr_NoMemory();
                goto finished;
            }
        } else {
            message_header.msg_control = NULL;
        }
        message_header.msg_controllen = (socklen_t) all_data_len;

        iterator = PyObject_GetIter(ancillary); /* again */

        if (!iterator) {
            goto finished;
        }

        /* Unpack the tuples into the control message. */
        struct cmsghdr *control_message = CMSG_FIRSTHDR(&message_header);
        while ( (item = PyIter_Next(iterator)) ) {
            int type, level;
            Py_ssize_t data_len;
            size_t data_size;
            unsigned char *data, *cmsg_data;

            /* We explicitly allocated enough space for all ancillary data
               above; if there isn't enough room, all bets are off. */
            assert(control_message);

            if (!PyArg_ParseTuple(item,
                                  "iit#:sendmsg ancillary data (level, type, data)",
                                  &level,
                                  &type,
                                  &data,
                                  &data_len)) {
                goto finished;
            }

            control_message->cmsg_level = level;
            control_message->cmsg_type = type;
            data_size = CMSG_LEN(data_len);

            if (data_size > SOCKLEN_MAX) {
                PyErr_Format(PyExc_OverflowError,
                             "CMSG_LEN(%zd) > SOCKLEN_MAX", data_len);
                goto finished;
            }

            control_message->cmsg_len = (socklen_t) data_size;

            cmsg_data = CMSG_DATA(control_message);
            memcpy(cmsg_data, data, data_len);

            Py_DECREF(item);
            item = NULL;

            control_message = CMSG_NXTHDR(&message_header, control_message);
        }
        Py_DECREF(iterator);
        iterator = NULL;

        if (PyErr_Occurred()) {
            goto finished;
        }
    }

    sendmsg_result = sendmsg(fd, &message_header, flags);

    if (sendmsg_result < 0) {
        PyErr_SetFromErrno(sendmsg_socket_error);
        goto finished;
    }

    result_object = Py_BuildValue("n", sendmsg_result);

 finished:

    if (item) {
        Py_DECREF(item);
        item = NULL;
    }
    if (iterator) {
        Py_DECREF(iterator);
        iterator = NULL;
    }
    if (message_header.msg_control) {
        PyMem_Free(message_header.msg_control);
        message_header.msg_control = NULL;
    }
    return result_object;
}
Example #3
0
static PyObject *wrap_rtdb_put(PyObject *self, PyObject *args)
{
    int i, list, list_len;
    int ma_type = -1;
    char *name;
    Integer* int_array;
    double *dbl_array;
    char *char_array;
    char cbuf[8192], *ptr;
    void *array = 0;
    PyObject *obj;

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

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

      if (ma_type == -1) {
          PyErr_SetString(PyExc_TypeError, 
                          "Usage: rtdb_put - ma_type is confused");
          return NULL;
      }
      
     
      if (ma_type != MT_CHAR) {
        if (!(array = malloc(MA_sizeof(ma_type, list_len, MT_CHAR)))) {
          PyErr_SetString(PyExc_MemoryError,
                          "rtdb_put failed allocating work array");
          return NULL;
        }
      }
      
      switch (ma_type) {
      case MT_INT:
      case MT_F_INT:  
      case MT_BASE + 11:        /* Logical */
        int_array = array;
        for (i = 0; i < list_len; i++) {
          if (list) 
            int_array[i] = PyInt_AS_LONG(PyList_GetItem(obj, i));
          else 
            int_array[i] = PyInt_AS_LONG(obj);
        }
        break;
        
      case MT_DBL:  
      case MT_F_DBL:
        dbl_array = array;
        for (i = 0; i < list_len; i++) {
          if (list) 
            PyArg_ParseTuple(PyList_GetItem(obj, i), "d", dbl_array+i);
          else 
            PyArg_ParseTuple(obj, "d", dbl_array+i);
        }
        break;
        
      case MT_CHAR: 
        ptr = cbuf;
        *ptr = 0;
        for (i = 0; i < list_len; i++) {
          if (list) 
            PyArg_ParseTuple(PyList_GetItem(obj, i), "s", &char_array); 
          else 
            PyArg_ParseTuple(obj, "s", &char_array); 
          /*printf("PROCESSED '%s'\n", char_array);*/
          if ((ptr+strlen(char_array)) >= (cbuf+sizeof(cbuf))) {
             PyErr_SetString(PyExc_MemoryError,"rtdb_put too many strings");
             return NULL;
           }
          strcpy(ptr,char_array);
          ptr = ptr+strlen(char_array);
          strcpy(ptr,"\n");
          ptr = ptr + 1;
        }                
        list_len = strlen(cbuf) + 1;
        array = cbuf;
        break;
        
      default:
        PyErr_SetString(NwchemError, "rtdb_put: ma_type is incorrect");
        if (array) free(array);
        return NULL;
        break;
      }                
      
      if (!(rtdb_seq_put(rtdb_handle, name, ma_type, list_len, array))) {
        PyErr_SetString(NwchemError, "rtdb_seq_put failed");
        if ((ma_type != MT_CHAR) && array) free(array);
        return NULL;
      }
      
    } else {
      PyErr_SetString(PyExc_TypeError, 
                      "Usage: rtdb_put(value or values,[optional type])");
      if ((ma_type != MT_CHAR) && array) free(array);
      return NULL;
    }
    Py_INCREF(Py_None);
    if ((ma_type != MT_CHAR) && array) free(array);
    return Py_None;
   Py_RETURN_NONE;
}
Example #4
0
bool
wsgi_call_application(Request* request)
{
  StartResponse* start_response = PyObject_NEW(StartResponse, &StartResponse_Type);
  start_response->request = request;

  /* From now on, `headers` stores the _response_ headers
   * (passed by the WSGI app) rather than the _request_ headers */
  PyObject* request_headers = request->headers;
  request->headers = NULL;

  /* application(environ, start_response) call */
  PyObject* retval = PyObject_CallFunctionObjArgs(
    request->server_info->wsgi_app,
    request_headers,
    start_response,
    NULL /* sentinel */
  );

  Py_DECREF(request_headers);
  Py_DECREF(start_response);

  if(retval == NULL)
    return false;

  /* The following code is somewhat magic, so worth an explanation.
   *
   * If the application we called was a generator, we have to call .next() on
   * it before we do anything else because that may execute code that
   * invokes `start_response` (which might not have been invoked yet).
   * Think of the following scenario:
   *
   *   def app(environ, start_response):
   *     start_response('200 Ok', ...)
   *     yield 'Hello World'
   *
   * That would make `app` return an iterator (more precisely, a generator).
   * Unfortunately, `start_response` wouldn't be called until the first item
   * of that iterator is requested; `start_response` however has to be called
   * _before_ the wsgi body is sent, because it passes the HTTP headers.
   *
   * If the application returned a list this would not be required of course,
   * but special-handling is painful - especially in C - so here's one generic
   * way to solve the problem:
   *
   * Look into the returned iterator in any case. This allows us to do other
   * optimizations, for example if the returned value is a list with exactly
   * one string in it, we can pick the string and throw away the list so bjoern
   * does not have to come back again and look into the iterator a second time.
   */
  PyObject* first_chunk;

  if(PyList_Check(retval) && PyList_GET_SIZE(retval) == 1 &&
     PyString_Check(PyList_GET_ITEM(retval, 0)))
  {
    /* Optimize the most common case, a single string in a list: */
    PyObject* tmp = PyList_GET_ITEM(retval, 0);
    Py_INCREF(tmp);
    Py_DECREF(retval);
    retval = tmp;
    goto string; /* eeevil */
  } else if(PyString_Check(retval)) {
    /* According to PEP 333 strings should be handled like any other iterable,
     * i.e. sending the response item for item. "item for item" means
     * "char for char" if you have a string. -- I'm not that stupid. */
    string:
    if(PyString_GET_SIZE(retval)) {
      first_chunk = retval;
    } else {
      Py_DECREF(retval);
      first_chunk = NULL;
    }
  } else if(FileWrapper_CheckExact(retval)) {
    request->state.use_sendfile = true;
    request->iterable = ((FileWrapper*)retval)->file;
    Py_INCREF(request->iterable);
    Py_DECREF(retval);
    request->iterator = NULL;
    first_chunk = NULL;
  } else {
    /* Generic iterable (list of length != 1, generator, ...) */
    request->iterable = retval;
    request->iterator = PyObject_GetIter(retval);
    if(request->iterator == NULL)
      return false;
    first_chunk = wsgi_iterable_get_next_chunk(request);
    if(first_chunk == NULL && PyErr_Occurred())
      return false;
  }

  if(request->headers == NULL) {
    /* It is important that this check comes *after* the call to
     * wsgi_iterable_get_next_chunk(), because in case the WSGI application
     * was an iterator, there's no chance start_response could be called
     * before. See above if you don't understand what I say. */
    PyErr_SetString(
      PyExc_RuntimeError,
      "wsgi application returned before start_response was called"
    );
    Py_XDECREF(first_chunk);
    return false;
  }
  
  /* keep-alive cruft */
  if(http_should_keep_alive(&request->parser.parser)) { 
    if(request->state.response_length_unknown) {
      if(request->parser.parser.http_major > 0 && request->parser.parser.http_minor > 0) {
        /* On HTTP 1.1, we can use Transfer-Encoding: chunked. */
        request->state.chunked_response = true;
        request->state.keep_alive = true;
      } else {
        /* On HTTP 1.0, we can only resort to closing the connection.  */
        request->state.keep_alive = false;
      }
    } else {
      /* We know the content-length. Can always keep-alive. */
      request->state.keep_alive = true;
    }
  } else {
    /* Explicit "Connection: close" (HTTP 1.1) or missing "Connection: keep-alive" (HTTP 1.0) */
    request->state.keep_alive = false;
  }

  /* Get the headers and concatenate the first body chunk.
   * In the first place this makes the code more simple because afterwards
   * we can throw away the first chunk PyObject; but it also is an optimization:
   * At least for small responses, the complete response could be sent with
   * one send() call (in server.c:ev_io_on_write) which is a (tiny) performance
   * booster because less kernel calls means less kernel call overhead. */
  PyObject* buf = PyString_FromStringAndSize(NULL, 1024);
  Py_ssize_t length = wsgi_getheaders(request, buf);

  if(first_chunk == NULL) {
    _PyString_Resize(&buf, length);
    goto out;
  }

  if(request->state.chunked_response) {
    PyObject* new_chunk = wrap_http_chunk_cruft_around(first_chunk);
    Py_DECREF(first_chunk);
    assert(PyString_GET_SIZE(new_chunk) >= PyString_GET_SIZE(first_chunk) + 5);
    first_chunk = new_chunk;
  }

  assert(buf);
  _PyString_Resize(&buf, length + PyString_GET_SIZE(first_chunk));
  memcpy(PyString_AS_STRING(buf)+length, PyString_AS_STRING(first_chunk),
         PyString_GET_SIZE(first_chunk));

  Py_DECREF(first_chunk);

out:
  request->state.wsgi_call_done = true;
  request->current_chunk = buf;
  request->current_chunk_p = 0;
  return true;
}
Example #5
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj, *exc, *toDictFunc, *iter;
  TypeContext *pc;
  PRINTMARK();
  if (!_obj) {
    tc->type = JT_INVALID;
    return;
  }

  obj = (PyObject*) _obj;

  pc = (TypeContext *) tc->prv;
  if (!pc)
  {
    tc->type = JT_INVALID;
    PyErr_NoMemory();
    return;
  }
  pc->newObj = NULL;
  pc->dictObj = NULL;
  pc->itemValue = NULL;
  pc->itemName = NULL;
  pc->iterator = NULL;
  pc->attrList = NULL;
  pc->index = 0;
  pc->size = 0;
  pc->longValue = 0;

  if (PyIter_Check(obj))
  {
    PRINTMARK();
    goto ISITERABLE;
  }

  if (PyBool_Check(obj))
  {
    PRINTMARK();
    tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
    return;
  }
  else
  if (PyLong_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyLongToINT64;
    tc->type = JT_LONG;
    GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

    exc = PyErr_Occurred();

    if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
    {
      PRINTMARK();
      goto INVALID;
    }

    return;
  }
  else
  if (PyInt_Check(obj))
  {
    PRINTMARK();
#ifdef _LP64
    pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
    pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
    return;
  }
  else
  if (PyString_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyUnicode_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyFloat_Check(obj) || (type_decimal && PyObject_IsInstance(obj, type_decimal)))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
    return;
  }
  else
  if (PyDateTime_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (PyDate_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (obj == Py_None)
  {
    PRINTMARK();
    tc->type = JT_NULL;
    return;
  }

ISITERABLE:
  if (PyDict_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_OBJECT;
    SetupDictIter(obj, pc);
    Py_INCREF(obj);
    return;
  }
  else
  if (PyList_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterEnd = List_iterEnd;
    pc->iterNext = List_iterNext;
    pc->iterGetValue = List_iterGetValue;
    pc->iterGetName = List_iterGetName;
    GET_TC(tc)->index =  0;
    GET_TC(tc)->size = PyList_GET_SIZE( (PyObject *) obj);
    return;
  }
  else
  if (PyTuple_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterEnd = Tuple_iterEnd;
    pc->iterNext = Tuple_iterNext;
    pc->iterGetValue = Tuple_iterGetValue;
    pc->iterGetName = Tuple_iterGetName;
    GET_TC(tc)->index = 0;
    GET_TC(tc)->size = PyTuple_GET_SIZE( (PyObject *) obj);
    GET_TC(tc)->itemValue = NULL;

    return;
  }
  /*
  else
  if (PyAnySet_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = NULL;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }
  */

  toDictFunc = PyObject_GetAttrString(obj, "toDict");

  if (toDictFunc)
  {
    PyObject* tuple = PyTuple_New(0);
    PyObject* toDictResult = PyObject_Call(toDictFunc, tuple, NULL);
    Py_DECREF(tuple);
    Py_DECREF(toDictFunc);

    if (toDictResult == NULL)
    {
      PyErr_Clear();
      tc->type = JT_NULL;
      return;
    }

    if (!PyDict_Check(toDictResult))
    {
      Py_DECREF(toDictResult);
      tc->type = JT_NULL;
      return;
    }

    PRINTMARK();
    tc->type = JT_OBJECT;
    SetupDictIter(toDictResult, pc);
    return;
  }

  PRINTMARK();
  PyErr_Clear();

  iter = PyObject_GetIter(obj);

  if (iter != NULL)
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterator = iter;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }

  PRINTMARK();
  PyErr_Clear();

  PRINTMARK();
  tc->type = JT_OBJECT;
  GET_TC(tc)->attrList = PyObject_Dir(obj);
  
  if (GET_TC(tc)->attrList == NULL)
  {
    PyErr_Clear();
    goto INVALID;
  }

  GET_TC(tc)->index = 0;
  GET_TC(tc)->size = PyList_GET_SIZE(GET_TC(tc)->attrList);
  PRINTMARK();
  
  pc->iterEnd = Dir_iterEnd;
  pc->iterNext = Dir_iterNext;
  pc->iterGetValue = Dir_iterGetValue;
  pc->iterGetName = Dir_iterGetName;
  return;

INVALID:
  PRINTMARK();
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
/**
 *******************************************************************************************************
 * This function applies a registered udf module on a particular record.
 *
 * @param self                  AerospikeClient object
 * @param py_key                The key under which to store the record.
 * @param py_module             The module name.
 * @param py_function           The UDF function to be applied on a record.
 * @param py_arglist            The arguments to the UDF function
 * @param py_policy             The optional policy parameters
 *
 * Returns the result of UDF function.
 *******************************************************************************************************
 */
PyObject * AerospikeClient_Apply_Invoke(
    AerospikeClient * self,
    PyObject * py_key, PyObject * py_module, PyObject * py_function,
    PyObject * py_arglist, PyObject * py_policy)
{
    // Python Return Value
    PyObject * py_result = NULL;

    // Aerospike Client Arguments
    as_error err;
    as_policy_apply apply_policy;
    as_policy_apply * apply_policy_p = NULL;
    as_key key;
    char * module = NULL;
    char * function = NULL;
    as_list * arglist = NULL;
    as_val * result = NULL;

    PyObject * py_umodule   = NULL;
    PyObject * py_ufunction = NULL;

    // Initialisation flags
    bool key_initialised = false;

    // Initialize error
    as_error_init(&err);

    if( !PyList_Check(py_arglist) ) {
        PyErr_SetString(PyExc_TypeError, "expected UDF method arguments in a 'list'");
        return NULL;
    }

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

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

    // Convert python key object to as_key
    pyobject_to_key(&err, py_key, &key);
    if ( err.code != AEROSPIKE_OK ) {
        goto CLEANUP;
    }
    // Key is initialiased successfully
    key_initialised = true;

    // Convert python list to as_list
    pyobject_to_list(self, &err, py_arglist, &arglist, NULL, -1);
    if ( err.code != AEROSPIKE_OK ) {
        goto CLEANUP;
    }

    // Convert python policy object to as_policy_apply
    pyobject_to_policy_apply(&err, py_policy, &apply_policy, &apply_policy_p,
                             &self->as->config.policies.apply);
    if ( err.code != AEROSPIKE_OK ) {
        goto CLEANUP;
    }

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

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

    // Invoke operation
    aerospike_key_apply(self->as, &err, apply_policy_p, &key, module, function, arglist, &result);

    if ( err.code == AEROSPIKE_OK ) {
        val_to_pyobject(&err, result, &py_result);
    } else {
        as_error_update(&err, err.code, NULL);
    }

CLEANUP:

    if (py_umodule) {
        Py_DECREF(py_umodule);
    }

    if (py_ufunction) {
        Py_DECREF(py_ufunction);
    }

    if (key_initialised == true) {
        // Destroy the key if it is initialised successfully.
        as_key_destroy(&key);
    }
    as_list_destroy(arglist);
    as_val_destroy(result);

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

    return py_result;
}
Example #7
0
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;
	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 (!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 = 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);
		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;
}
PyObject * py_cps_get(PyObject *self, PyObject *args) {
    PyObject * param_list;

    cps_api_get_params_t gr;
    if (cps_api_get_request_init (&gr)==cps_api_ret_code_ERR) {
        py_set_error_string("Failed to initialize the get req");
        return nullptr;
    }

    cps_api_get_request_guard rg(&gr);

    PyObject *res_obj;

    if (! PyArg_ParseTuple( args, "O!O", &PyList_Type, &param_list,&res_obj)) {
        py_set_error_string("Failed to parse input args.");
        return nullptr;
    }

    PyObject * lst = NULL;

    if (PyDict_Check(res_obj)) {
        PyObject *l = PyList_New(0);
        PyRef _l(l);
        if (l==NULL) {
            py_set_error_string("Can not create a list.");
            return nullptr;
        }
        PyObject *_prev = PyDict_GetItemString(res_obj,"list");
        if (_prev!=NULL) {
            PyDict_DelItemString(res_obj,"list");
        }

        if (!py_cps_util_set_item_to_dict(res_obj,"list",l)) {
            py_set_error_string("Can not create a list.");
            return nullptr;
        }
        lst = l;
    }
    if (PyList_Check(res_obj)) {
        lst = res_obj;
    }
    if (lst==NULL) {
        py_set_error_string("The return args are invalid.");
        return nullptr;
    }
    Py_ssize_t str_keys = PyList_Size(param_list);
    {
        Py_ssize_t ix = 0;
        for ( ;ix < str_keys ; ++ix ) {
            PyObject *strObj = PyList_GetItem(param_list, ix);
            if (PyString_Check(strObj)) {
                //
                cps_api_object_t o = cps_api_object_list_create_obj_and_append(gr.filters);
                if (o==NULL) {
                    py_set_error_string("Memory allocation error.");
                    return nullptr;
                }
                if (!cps_api_key_from_string(cps_api_object_key(o),PyString_AsString(strObj))) {
                    py_set_error_string("Memory allocation error.");
                    return nullptr;
                }
            }
            if (PyDict_Check(strObj)) {
                cps_api_object_t o = dict_to_cps_obj(strObj);
                if (o==NULL) {
                    py_set_error_string("Can't convert from a python to internal object");
                    return nullptr;
                }
                if (!cps_api_object_list_append(gr.filters,o)) {
                    cps_api_object_delete(o);
                    py_set_error_string("Memory allocation error.");
                    return nullptr;
                }
            }
        }
    }
    gr.keys = NULL;
    gr.key_count = 0;

    cps_api_return_code_t rc;
    {
        NonBlockingPythonContext l;
        rc = cps_api_get(&gr);
    }

    if (rc!=cps_api_ret_code_OK) {
        Py_RETURN_FALSE;
    }

    size_t ix = 0;
    size_t mx = cps_api_object_list_size(gr.list);
    for ( ; ix < mx ; ++ix) {
        cps_api_object_t obj = cps_api_object_list_get(gr.list,ix);
        PyObject *d = cps_obj_to_dict(obj);
        PyRef r(d);
        if (d==NULL) {
            py_set_error_string("Memory allocation error.");
            return nullptr;
        }
        if (PyList_Append(lst,d)) {
            py_set_error_string("Memory allocation error.");
            return nullptr;
        }
    }

    Py_RETURN_TRUE;
}
Example #9
0
static PyObject *
immom_saImmOmClassCreate(PyObject *self, PyObject *args)
{
    char* className;
    char* categoryStr;
    SaImmClassCategoryT classCategory;
    PyObject* alist;
    unsigned int len, i;
    SaImmAttrDefinitionT_2** attrDefinitions;
    SaAisErrorT rc;

    if (!PyArg_ParseTuple(args, "ssO", &className, &categoryStr, &alist)) 
        return NULL;
    if (!PyList_Check(alist))
        return immom_aisException(SA_AIS_ERR_INVALID_PARAM);
    if (strcmp(categoryStr, "CONFIG") == 0) {
        classCategory = SA_IMM_CLASS_CONFIG;
    } else if (strcmp(categoryStr, "RUNTIME") == 0) {
        classCategory = SA_IMM_CLASS_RUNTIME;
    } else {
        return immom_aisException(SA_AIS_ERR_INVALID_PARAM);
    }

    len = PyList_Size(alist);
    attrDefinitions = (SaImmAttrDefinitionT_2**)
        memget(sizeof(SaImmAttrDefinitionT_2*) * (len+1));
    attrDefinitions[len] = NULL;

    for (i = 0; i < len; i++) {
        PyObject* item = PyList_GetItem(alist, i);
        char* attrName;
        char* attrType;
        unsigned PY_LONG_LONG flags;
	PyObject* def;
        SaImmAttrDefinitionT_2* ad;

        if (!PyTuple_Check(item))
            return immom_aisException(SA_AIS_ERR_INVALID_PARAM);
        if (!PyArg_ParseTuple(item, "ssKO", &attrName, &attrType, &flags,&def))
            return immom_return_null();
	if (!PyList_Check(def))
	    return immom_aisException(SA_AIS_ERR_INVALID_PARAM);
        ad = (SaImmAttrDefinitionT_2*)memget(sizeof(SaImmAttrDefinitionT_2));
        ad->attrName = attrName;
        ad->attrValueType = immom_parseTypeStr(attrType);
        if ((int)ad->attrValueType == 0)
            return immom_aisException(SA_AIS_ERR_INVALID_PARAM);
        ad->attrFlags = flags;
	ad->attrDefaultValue = NULL;
	if (PyList_Size(def) > 0) {
		SaImmAttrValuesT_2* attr = memget(sizeof(SaImmAttrValuesT_2));
		if (immom_parseAttrValue(attr, attrName, attrType, def)== NULL)
			immom_return_null();
		ad->attrDefaultValue = attr->attrValues[0];
	}
        attrDefinitions[i] = ad;
    }

    rc = saImmOmClassCreate_2(
        immOmHandle, className, classCategory, 
        (const SaImmAttrDefinitionT_2**)attrDefinitions);
    if (rc != SA_AIS_OK) return immom_aisException(rc);
    return immom_return_None();
}
Example #10
0
/**
 *  evalDistribution function evaluate a model function with input vector
 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
 *
 */ 
static PyObject * evalDistribution(CSCCrystalModel *self, PyObject *args){
	PyObject *qx, *qy;
	PyArrayObject * pars;
	int npars ,mpars;
	
	// Get parameters
	
	    // Reader parameter dictionary
    self->model->phi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "phi") );
    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
    self->model->dnn = PyFloat_AsDouble( PyDict_GetItemString(self->params, "dnn") );
    self->model->sldSph = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSph") );
    self->model->d_factor = PyFloat_AsDouble( PyDict_GetItemString(self->params, "d_factor") );
    self->model->psi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "psi") );
    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
    self->model->theta = PyFloat_AsDouble( PyDict_GetItemString(self->params, "theta") );
    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
    // Read in dispersion parameters
    PyObject* disp_dict;
    DispersionVisitor* visitor = new DispersionVisitor();
    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, "phi");
    self->model->phi.dispersion->accept_as_destination(visitor, self->model->phi.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "psi");
    self->model->psi.dispersion->accept_as_destination(visitor, self->model->psi.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "theta");
    self->model->theta.dispersion->accept_as_destination(visitor, self->model->theta.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(CSCCrystalModelError, 
	    	"CSCCrystalModel.evalDistribution expects a q value.");
		return NULL;
	}
    // Check params
	
    if(PyArray_Check(pars)==1) {
		
	    // Length of list should 1 or 2
	    npars = pars->nd; 
	    if(npars==1) {
	        // input is a numpy array
	        if (PyArray_Check(pars)) {
		        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
		    }
		}else{
		    PyErr_SetString(CSCCrystalModelError, 
                   "CSCCrystalModel.evalDistribution expect numpy array of one dimension.");
	        return NULL;
		}
    }else if( PyList_Check(pars)==1) {
    	// Length of list should be 2 for I(qx,qy)
	    mpars = PyList_GET_SIZE(pars); 
	    if(mpars!=2) {
	    	PyErr_SetString(CSCCrystalModelError, 
	    		"CSCCrystalModel.evalDistribution expects a list of dimension 2.");
	    	return NULL;
	    }
	     qx = PyList_GET_ITEM(pars,0);
	     qy = PyList_GET_ITEM(pars,1);
	     if (PyArray_Check(qx) && PyArray_Check(qy)) {
	         return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
		           (PyArrayObject*)qy);
		 }else{
		    PyErr_SetString(CSCCrystalModelError, 
                   "CSCCrystalModel.evalDistribution expect 2 numpy arrays in list.");
	        return NULL;
	     }
	}
	PyErr_SetString(CSCCrystalModelError, 
                   "CSCCrystalModel.evalDistribution couln't be run.");
	return NULL;
	
}
Example #11
0
/**
 * Function to call to evaluate model in cartesian coordinates
 * @param args: input q or [qx, qy]]
 * @return: function value
 */
static PyObject * runXY(CSCCrystalModel *self, PyObject *args) {
	double qx_value, qy_value;
	PyObject* pars;
	int npars;
	
	// Get parameters
	
	    // Reader parameter dictionary
    self->model->phi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "phi") );
    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
    self->model->dnn = PyFloat_AsDouble( PyDict_GetItemString(self->params, "dnn") );
    self->model->sldSph = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSph") );
    self->model->d_factor = PyFloat_AsDouble( PyDict_GetItemString(self->params, "d_factor") );
    self->model->psi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "psi") );
    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
    self->model->theta = PyFloat_AsDouble( PyDict_GetItemString(self->params, "theta") );
    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
    // Read in dispersion parameters
    PyObject* disp_dict;
    DispersionVisitor* visitor = new DispersionVisitor();
    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, "phi");
    self->model->phi.dispersion->accept_as_destination(visitor, self->model->phi.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "psi");
    self->model->psi.dispersion->accept_as_destination(visitor, self->model->psi.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "theta");
    self->model->theta.dispersion->accept_as_destination(visitor, self->model->theta.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(CSCCrystalModelError, 
	    	"CSCCrystalModel.run expects a q value.");
		return NULL;
	}
	  
	// Check params
	if( PyList_Check(pars)==1) {
		
		// Length of list should be 2 for I(qx, qy))
	    npars = PyList_GET_SIZE(pars); 
	    if(npars!=2) {
	    	PyErr_SetString(CSCCrystalModelError, 
	    		"CSCCrystalModel.run expects a double or a list of dimension 2.");
	    	return NULL;
	    }
	    // We have a vector q, get the qx and qy values at which
	    // to evaluate I(qx,qy)
	    qx_value = CSCCrystalModel_readDouble(PyList_GET_ITEM(pars,0));
	    qy_value = CSCCrystalModel_readDouble(PyList_GET_ITEM(pars,1));
	    return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));

	} else {

		// We have a scalar q, we will evaluate I(q)
		qx_value = CSCCrystalModel_readDouble(pars);		
		
		return Py_BuildValue("d",(*(self->model))(qx_value));
	}	
}
/**
 *********************************************************************
 * This function will invoke aerospike_batch_get_bins to get filtered
 * bins from all the records in a batches.
 *
 * @param self                    AerospikeClient object
 * @param py_keys                 List of keys passed on by user
 * @param py_bins                 List of filter bins passed on by user
 * @param py_policy               User specified Policy dictionary
 *
 *********************************************************************
 **/
static
PyObject * AerospikeClient_Select_Many_Invoke(
		AerospikeClient * self,
		PyObject * py_keys, PyObject * py_bins, PyObject * py_policy)
{
	// Python Return Value
	PyObject * py_recs = NULL;

	// Aerospike Client Arguments
	as_error err;
	as_policy_batch policy;
	as_policy_batch * batch_policy_p = NULL;
	Py_ssize_t bins_size = 0;
	char **filter_bins = NULL;
	bool has_batch_index = false;

	// Unicode object's pool
	UnicodePyObjects u_objs;
	u_objs.size = 0;
	int i = 0;

	// Initialize error
	as_error_init(&err);

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

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

	// Check the type of bins and get it's size
	// i.e. number of bins provided
	if (py_bins != NULL && PyList_Check(py_bins)){
		bins_size = PyList_Size(py_bins);
	}
	else if (py_bins != NULL && PyTuple_Check(py_bins)){
		bins_size = PyTuple_Size(py_bins);
	}
	else {
		as_error_update(&err, AEROSPIKE_ERR_PARAM, "Filter bins should be specified as a list or tuple.");
		goto CLEANUP;
	}

	filter_bins = (char **)malloc(sizeof(long int) * bins_size);

	for (i = 0; i < bins_size; i++){
		PyObject *py_bin = NULL;
		if(PyList_Check(py_bins)){
			py_bin = PyList_GetItem(py_bins, i);
		}
		if(PyTuple_Check(py_bins)){
			py_bin = PyTuple_GetItem(py_bins, i);
		}
		if (PyUnicode_Check(py_bin)){
			// Store the unicode object into a pool
			// It is DECREFed at later stages
			// So, no need of DECREF here.
			filter_bins[i] = PyBytes_AsString(
					store_unicode_bins(&u_objs, PyUnicode_AsUTF8String(py_bin)));
		}
		else if (PyString_Check(py_bin)){
			filter_bins[i] = PyString_AsString(py_bin);
		}
		else{
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Bin name should be a string or unicode string.");
			goto CLEANUP;
		}
}

	// Convert python policy object to as_policy_batch
	pyobject_to_policy_batch(&err, py_policy, &policy, &batch_policy_p,
			&self->as->config.policies.batch);
	if ( err.code != AEROSPIKE_OK ) {
		goto CLEANUP;
	}

	has_batch_index = aerospike_has_batch_index(self->as);
	if (has_batch_index && !(self->as->config.policies.batch.use_batch_direct)) {
		py_recs = batch_select_aerospike_batch_read(&err, self, py_keys, batch_policy_p, filter_bins, bins_size);
	} else {
		py_recs = batch_select_aerospike_batch_get(&err, self, py_keys, batch_policy_p, filter_bins, bins_size);
	}

CLEANUP:

	if (filter_bins != NULL){
		free(filter_bins);
	}

	// DECREFed all the unicode objects stored in Pool
	for ( i = 0; i< u_objs.size; i++){
		Py_DECREF(u_objs.ob[i]);
	}

	if ( err.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(&err, &py_err);
		PyObject *exception_type = raise_exception(&err);
		if(PyObject_HasAttrString(exception_type, "key")) {
			PyObject_SetAttrString(exception_type, "key", py_keys);
		} 
		if(PyObject_HasAttrString(exception_type, "bin")) {
			PyObject_SetAttrString(exception_type, "bin", Py_None);
		}
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return py_recs;
}
/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_select_aerospike_batch_get(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char **filter_bins, Py_ssize_t bins_size)
{
	PyObject * py_recs = NULL;

	as_batch batch;
	bool batch_initialised = false;

	LocalData data;
	data.client = self;
	// Convert python keys list to as_key ** and add it to as_batch.keys
	// keys can be specified in PyList or PyTuple
	if ( py_keys != NULL && PyList_Check(py_keys) ) {
		Py_ssize_t size = PyList_Size(py_keys);

		py_recs = PyList_New(size);
		data.py_recs = py_recs;
		as_batch_init(&batch, size);

		// Batch object initialised
		batch_initialised = true;

		for ( int i = 0; i < size; i++ ) {

			PyObject * py_key = PyList_GetItem(py_keys, i);

			if ( !PyTuple_Check(py_key) ){
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
				goto CLEANUP;
			}

			pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));

			if ( err->code != AEROSPIKE_OK ) {
				goto CLEANUP;
			}
		}
	}
	else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
		Py_ssize_t size = PyTuple_Size(py_keys);

		py_recs = PyList_New(size);
		data.py_recs = py_recs;
		as_batch_init(&batch, size);
		// Batch object initialised
		batch_initialised = true;

		for ( int i = 0; i < size; i++ ) {
			PyObject * py_key = PyTuple_GetItem(py_keys, i);

			if ( !PyTuple_Check(py_key) ){
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
				goto CLEANUP;
			}

			pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));

			if ( err->code != AEROSPIKE_OK ) {
				goto CLEANUP;
			}
		}
	}
	else {
		as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
		goto CLEANUP;
	}

	// Invoke C-client API
	Py_BEGIN_ALLOW_THREADS
	aerospike_batch_get_bins(self->as, err, batch_policy_p,
		&batch, (const char **) filter_bins, bins_size,
		(aerospike_batch_read_callback) batch_select_cb,
		&data);
	Py_END_ALLOW_THREADS

CLEANUP:
	if (batch_initialised == true){
		// We should destroy batch object as we are using 'as_batch_init' for initialisation
		// Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
		// is necessary.
		as_batch_destroy(&batch);
	}

	return py_recs;
}
/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_select_aerospike_batch_read(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char** filter_bins, Py_ssize_t bins_size)
{
	PyObject * py_recs = NULL;

	as_batch_read_records records;

	as_batch_read_record* record = NULL;
	bool batch_initialised = false;

	// Convert python keys list to as_key ** and add it to as_batch.keys
	// keys can be specified in PyList or PyTuple
	if ( py_keys != NULL && PyList_Check(py_keys) ) {
		Py_ssize_t size = PyList_Size(py_keys);

		py_recs = PyList_New(size);
		as_batch_read_inita(&records, size);

		// Batch object initialised
		batch_initialised = true;

		for ( int i = 0; i < size; i++ ) {

			PyObject * py_key = PyList_GetItem(py_keys, i);

			if ( !PyTuple_Check(py_key) ){
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
				goto CLEANUP;
			}

			record = as_batch_read_reserve(&records);

			pyobject_to_key(err, py_key, &record->key);
			if (bins_size) {
				record->bin_names = filter_bins;
				record->n_bin_names = bins_size;
			} else {
				record->read_all_bins = true;
			}

			if ( err->code != AEROSPIKE_OK ) {
				goto CLEANUP;
			}
		}
	}
	else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
		Py_ssize_t size = PyTuple_Size(py_keys);

		py_recs = PyList_New(size);
		as_batch_read_inita(&records, size);
		// Batch object initialised
		batch_initialised = true;

		for ( int i = 0; i < size; i++ ) {
			PyObject * py_key = PyTuple_GetItem(py_keys, i);

			if ( !PyTuple_Check(py_key) ){
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
				goto CLEANUP;
			}

			record = as_batch_read_reserve(&records);

			pyobject_to_key(err, py_key, &record->key);
			if (bins_size) {
				record->bin_names = filter_bins;
				record->n_bin_names = bins_size;
			} else {
				record->read_all_bins = true;
			}

			if ( err->code != AEROSPIKE_OK ) {
				goto CLEANUP;
			}
		}
	}
	else {
		as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
		goto CLEANUP;
	}

	// Invoke C-client API
	Py_BEGIN_ALLOW_THREADS
	aerospike_batch_read(self->as, err, batch_policy_p, &records);
	Py_END_ALLOW_THREADS
	if (err->code != AEROSPIKE_OK)
	{
		goto CLEANUP;
	}
	batch_select_recs(self, err, &records, &py_recs);

CLEANUP:
	if (batch_initialised == true){
		// We should destroy batch object as we are using 'as_batch_init' for initialisation
		// Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
		// is necessary.
		as_batch_read_destroy(&records);
	}

	return py_recs;
}
Example #15
0
void eListboxPythonConfigContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected)
{
	ePtr<gFont> fnt = new gFont("Regular", 20);
	ePtr<gFont> fnt2 = new gFont("Regular", 16);
	eRect itemrect(offset, m_itemsize);
	eListboxStyle *local_style = 0;
	bool cursorValid = this->cursorValid();

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

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

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

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

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

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

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

			   of this tuple,
			   the first one is the type (string).
			   the second one is the value. */
		if (PyTuple_Check(item))
		{
				/* handle left part. get item from tuple, convert to string, display. */
			text = PyTuple_GET_ITEM(item, 0);
			text = PyObject_Str(text); /* creates a new object - old object was borrowed! */
			const char *string = (text && PyString_Check(text)) ? PyString_AsString(text) : "<not-a-string>";
			eSize item_left = eSize(m_seperation, m_itemsize.height());
			eSize item_right = eSize(m_itemsize.width() - m_seperation, m_itemsize.height());
			painter.renderText(eRect(offset, item_left), string, gPainter::RT_HALIGN_LEFT);
			Py_XDECREF(text);

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

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

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

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

				if (PyErr_Occurred())
					PyErr_Print();

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

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

				if (atype)
				{
					if (!strcmp(atype, "text"))
					{
						ePyObject pvalue = PyTuple_GET_ITEM(value, 1);
						const char *value = (pvalue && PyString_Check(pvalue)) ? PyString_AsString(pvalue) : "<not-a-string>";
						painter.setFont(fnt2);
						if (value_alignment_left)
							painter.renderText(eRect(offset, item_right), value, gPainter::RT_HALIGN_LEFT);
						else
							painter.renderText(eRect(offset + eSize(m_seperation, 0), item_right), value, gPainter::RT_HALIGN_RIGHT);

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

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

							/* calc. slider length */
						int width = item_right.width() * value / size;
						int height = item_right.height();


							/* draw slider */
						//painter.fill(eRect(offset.x() + m_seperation, offset.y(), width, height));
						//hack - make it customizable
						painter.fill(eRect(offset.x() + m_seperation, offset.y() + 5, width, height-10));

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

						ePyObject plist;

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

						int entries = 0;

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

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

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

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

	painter.clippop();
}
Example #16
0
static PyObject*
immom_saImmOmAdminOperationInvoke(PyObject *self, PyObject *args)
{
    SaAisErrorT rc, oprc;
    PyObject* attrList;
    unsigned int len, i;
    char* dn;
    unsigned long long op;
    SaNameT objectName;
    SaImmAdminOperationParamsT_2** params;

    if (!haveAdminOwner) 
        return immom_aisException(SA_AIS_ERR_BAD_OPERATION);
    if (!PyArg_ParseTuple(args, "sLO", &dn, &op, &attrList))
        return NULL;
    if (immom_saName(dn, &objectName) == NULL)
        return NULL;
    if (!PyList_Check(attrList))
        return immom_aisException(SA_AIS_ERR_INVALID_PARAM);

    len = PyList_Size(attrList);
    params = (SaImmAdminOperationParamsT_2**)memget(
        sizeof(SaImmAdminOperationParamsT_2*) * (len+1));
    params[len] = NULL;

    for (i = 0; i < len; i++) {
        PyObject* item = PyList_GetItem(attrList, i);
        char* attrName;
        char* attrType;
        PyObject* valueList;
        SaImmAttrValuesT_2 av;
        SaImmAdminOperationParamsT_2* p;

        if (!PyTuple_Check(item))
            return immom_aisException(SA_AIS_ERR_INVALID_PARAM);
        if (!PyArg_ParseTuple(item, "ssO", &attrName, &attrType, &valueList)) 
            return immom_return_null();
        if (!PyList_Check(valueList))
            return immom_aisException(SA_AIS_ERR_INVALID_PARAM);

        if (immom_parseAttrValue(
                &av, attrName, attrType, valueList) == NULL)
            return immom_return_null();
        if (av.attrValuesNumber != 1)
            return immom_aisException(SA_AIS_ERR_INVALID_PARAM);

        p = (SaImmAdminOperationParamsT_2*)
            memget(sizeof(SaImmAdminOperationParamsT_2));
        p->paramName = av.attrName;
        p->paramType = av.attrValueType;
        p->paramBuffer = av.attrValues[0];
        params[i] = p;
    }

    rc = saImmOmAdminOperationInvoke_2(
        adminOwnerHandle, &objectName, 0ULL, op, 
        (SaImmAdminOperationParamsT_2 const**)params, &oprc, 
        SA_TIME_ONE_MINUTE);
    if (rc != SA_AIS_OK)
        return immom_aisException(rc);
    if (oprc != SA_AIS_OK)
        return immom_aisException(oprc);

    return immom_return_None();
}
Example #17
0
void eListboxPythonMultiContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected)
{
	gRegion itemregion(eRect(offset, m_itemsize));
	eListboxStyle *local_style = 0;
	eRect sel_clip(m_selection_clip);
	bool cursorValid = this->cursorValid();
	if (sel_clip.valid())
		sel_clip.moveBy(offset);

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

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

	ePyObject items, buildfunc_ret;

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

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

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

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

		ePyObject data;

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

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

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

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

			int size = PyTuple_Size(item);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				if ((filled < 0) && data) /* if the string is in a negative number, it refers to the 'data' list. */
					filled = PyInt_AsLong(PyTuple_GetItem(data, -filled));
					
							/* don't do anything if percent out of range */
				if ((filled < 0) || (filled > 100))
					continue;

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

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

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

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

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

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

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

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

				// progress
				if (ppixmap)
				{
					ePtr<gPixmap> pixmap;
					if (SwigFromPython(pixmap, ppixmap))
					{
						eDebug("eListboxPythonMultiContent (Pixmap) get pixmap failed");
						painter.clippop();
						continue;
					}
					painter.blit(pixmap, rect.topLeft(), rect, 0);
				}
				else
					painter.fill(rect);

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

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

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

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

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

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

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

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

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

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

				painter.blit(pixmap, rect.topLeft(), rect, (type == TYPE_PIXMAP_ALPHATEST) ? gPainter::BT_ALPHATEST : (type == TYPE_PIXMAP_ALPHABLEND) ? gPainter::BT_ALPHABLEND : 0);
				painter.clippop();
				break;
			}
			default:
				eWarning("eListboxPythonMultiContent received unknown type (%d)", type);
				goto error_out;
			}
		}
	}

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

error_out:
	if (buildfunc_ret)
		Py_DECREF(buildfunc_ret);

	painter.clippop();
}
Example #18
0
PyObject *scribus_bezierline(PyObject* /* self */, PyObject* args)
{
	char *Name = const_cast<char*>("");
	PyObject *il;
	// FIXME: PyList_Check failing will cause the function to return NULL w/o an exception. Separarate out the check.
	if ((!PyArg_ParseTuple(args, "O|es", &il, "utf-8", &Name)) || (!PyList_Check(il)))
		return NULL;
	if(!checkHaveDocument())
		return NULL;
	int len = PyList_Size(il);
	if (len < 8)
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("Point list must contain at least four points (eight values).","python error").toLocal8Bit().constData());
		return NULL;
	}
	if ((len % 6) != 0)
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("Point list must have a multiple of six values.","python error").toLocal8Bit().constData());
		return NULL;
	}
//	if (ItemExists(QString::fromUtf8(Name)))
//	{
//		PyErr_SetString(NameExistsError, QObject::tr("An object with the requested name already exists.","python error").toLocal8Bit().constData());
//		return NULL;
//	}
	double x, y, w, h, kx, ky, kx2, ky2;
	int i = 0;
	x = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
	i++;
	y = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
	i++;
	kx = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
	i++;
	ky = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
	i++;
	kx2 = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
	i++;
	ky2 = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
	i++;
	//int ic = ScCore->primaryMainWindow()->view->PaintPolyLine(x, y, 1, 1,	ScCore->primaryMainWindow()->doc->toolSettings.dWidth, ScCore->primaryMainWindow()->doc->toolSettings.dBrush, ScCore->primaryMainWindow()->doc->toolSettings.dPen);
	int ic = ScCore->primaryMainWindow()->doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, x, y, 1, 1,	ScCore->primaryMainWindow()->doc->itemToolPrefs().shapeLineWidth, ScCore->primaryMainWindow()->doc->itemToolPrefs().shapeFillColor, ScCore->primaryMainWindow()->doc->itemToolPrefs().shapeLineColor, true);
	PageItem *it = ScCore->primaryMainWindow()->doc->Items->at(ic);
	it->PoLine.resize(2);
	it->PoLine.setPoint(0, 0, 0);
	it->PoLine.setPoint(1, kx-x, ky-y);
	int pp = 6;
	for (i = 6; i < len - 6; i += 6)
	{
		w = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i))));
		h = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i+1))));
		kx = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i+2))));
		ky = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i+3))));
		kx2 = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i+4))));
		ky2 = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, i+5))));
		it->PoLine.resize(pp);
		it->PoLine.setPoint(pp-4, w-x, h-y);
		it->PoLine.setPoint(pp-3, kx-x, ky-y);
		it->PoLine.setPoint(pp-2, it->PoLine.point(pp-4));
		it->PoLine.setPoint(pp-1, kx2-x, ky2-y);
		pp += 4;
	}
	pp -= 2;
	w = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, len-6))));
	h = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, len-5))));
	kx = pageUnitXToDocX(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, len-4))));
	ky = pageUnitYToDocY(static_cast<double>(PyFloat_AsDouble(PyList_GetItem(il, len-3))));
	it->PoLine.resize(pp);
	it->PoLine.setPoint(pp-2, w-x, h-y);
	it->PoLine.setPoint(pp-1, kx-x, ky-y);
	FPoint np2 = getMinClipF(&it->PoLine);
	if (np2.x() < 0)
	{
		it->PoLine.translate(-np2.x(), 0);
		ScCore->primaryMainWindow()->doc->MoveItem(np2.x(), 0, it);
	}
	if (np2.y() < 0)
	{
		it->PoLine.translate(0, -np2.y());
		ScCore->primaryMainWindow()->doc->MoveItem(0, np2.y(), it);
	}
	ScCore->primaryMainWindow()->doc->SizeItem(it->PoLine.WidthHeight().x(), it->PoLine.WidthHeight().y(), ic, false, false, false);
	ScCore->primaryMainWindow()->doc->AdjustItemSize(it);
	if (Name != EMPTY_STRING)
	{
		QString objName = QString::fromUtf8(Name);
		if (!ItemExists(objName))
			ScCore->primaryMainWindow()->doc->Items->at(ic)->setItemName(objName);
	}
	return PyString_FromString(it->itemName().toUtf8());
}
Example #19
0
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;
#else
	struct spi_ioc_transfer 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 (!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 = speed_hz ? speed_hz : self->max_speed_hz;
		xferptr[ii].bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;
	}

	status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}
#else
	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);
	}

	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);
		return NULL;
	}
#endif

	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);

	Py_INCREF(list);
	return list;
}
Example #20
0
PyObject*
PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
{
    ImagingEncoderObject* encoder;

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

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

    Py_ssize_t d_size;
    PyObject *keys, *values;


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

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


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

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

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

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

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

    encoder->encode  = ImagingLibTiffEncode;

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

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

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

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

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

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

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

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

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

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

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

		arglist = as_arraylist_new(size, 0);

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


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

CLEANUP:

	if (py_ufunction) {
		Py_DECREF(py_ufunction);
	}

	if (py_umodule) {
		Py_DECREF(py_umodule);
	}

	if ( err.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(&err, &py_err);
		PyErr_SetObject(PyExc_Exception, py_err);
		Py_DECREF(py_err);
		return NULL;
	}

	Py_INCREF(self);
	return self;
}
Example #22
0
static PyObject* pybullet_renderImage(PyObject* self, PyObject* args)
{
	if (0==sm)
	{
		PyErr_SetString(SpamError, "Not connected to physics server.");
		return NULL;
	}
	
	///request an image from a simulated camera, using a software renderer.
	struct b3CameraImageData imageData;
	PyObject* objViewMat,* objProjMat;
	int width,  height;
	
	if (PyArg_ParseTuple(args, "iiOO", &width, &height, &objViewMat, &objProjMat))
	{
	
		PyObject* seq;
		int i, len;
		PyObject* item;
		float viewMatrix[16];
		float projectionMatrix[16];
		int valid = 1;
		{
    		seq = PySequence_Fast(objViewMat, "expected a sequence");
    		len = PySequence_Size(objViewMat);
		//printf("objViewMat size = %d\n", len);
			if (len==16)
			{
				
				if (PyList_Check(seq))
				{
					for (i = 0; i < len; i++) 
					{
            			item = PyList_GET_ITEM(seq, i);
						viewMatrix[i] = PyFloat_AsDouble(item);
						float v = viewMatrix[i]; 
	 			//printf("view %d to %f\n", i,v);
	
					}
				}
				else
				{
					for (i = 0; i < len; i++)
					{
        			item = PyTuple_GET_ITEM(seq,i);
						viewMatrix[i] = PyFloat_AsDouble(item);
					}
				}
			} else
			{
				valid = 0;
			}
		}
		
		
		{
			seq = PySequence_Fast(objProjMat, "expected a sequence");
			len = PySequence_Size(objProjMat);
	//printf("projMat len = %d\n", len);
			if (len==16)
			{
				if (PyList_Check(seq))
				{
					for (i = 0; i < len; i++)
					{
							item = PyList_GET_ITEM(seq, i);
							projectionMatrix[i] = PyFloat_AsDouble(item);
					}
				}
				else
				{
					for (i = 0; i < len; i++)
					{
							item = PyTuple_GET_ITEM(seq,i);
							projectionMatrix[i] = PyFloat_AsDouble(item);
					}
				}
			} else
			{
					valid = 0;
			}
		}

    		Py_DECREF(seq);	
		{
			b3SharedMemoryCommandHandle command;
			
			command = b3InitRequestCameraImage(sm);
			if (valid)
			{
			//printf("set b3RequestCameraImageSetCameraMatrices\n");
			b3RequestCameraImageSetCameraMatrices(command, viewMatrix, projectionMatrix);
			}

			b3RequestCameraImageSetPixelResolution(command,width,height);
		
			if (b3CanSubmitCommand(sm))
			{
				b3SharedMemoryStatusHandle statusHandle;
				int statusType;
				statusHandle = b3SubmitClientCommandAndWaitStatus(sm, command);
				statusType = b3GetStatusType(statusHandle);
				if (statusType==CMD_CAMERA_IMAGE_COMPLETED)
				{
					PyObject *item2;
					PyObject* pyResultList;//store 4 elements in this result: width, height, rgbData, depth

					b3GetCameraImageData(sm, &imageData);
					//todo: error handling if image size is 0
					pyResultList =  PyTuple_New(4);
					PyTuple_SetItem(pyResultList, 0, PyInt_FromLong(imageData.m_pixelWidth));
					PyTuple_SetItem(pyResultList, 1, PyInt_FromLong(imageData.m_pixelHeight));	
			
					PyObject *pylistPos;
					PyObject* pylistDep;
					int i,j,p;

						//printf("image width = %d, height = %d\n", imageData.m_pixelWidth, imageData.m_pixelHeight);
						{

							PyObject *item;
						int bytesPerPixel = 4;//Red, Green, Blue, each 8 bit values
							int num=bytesPerPixel*imageData.m_pixelWidth*imageData.m_pixelHeight;
							pylistPos = PyTuple_New(num);
						pylistDep = PyTuple_New(imageData.m_pixelWidth*imageData.m_pixelHeight);
			
						for (i=0;i<imageData.m_pixelWidth;i++)
						{
							for (j=0;j<imageData.m_pixelHeight;j++)
							{
								int depIndex = i+j*imageData.m_pixelWidth;
								item = PyFloat_FromDouble(imageData.m_depthValues[depIndex]);
								PyTuple_SetItem(pylistDep, depIndex, item);
								for (p=0;p<bytesPerPixel;p++)
								{
									int pixelIndex = bytesPerPixel*(i+j*imageData.m_pixelWidth)+p;
									item = PyInt_FromLong(imageData.m_rgbColorData[pixelIndex]);
											PyTuple_SetItem(pylistPos, pixelIndex, item);
								}
							}
						}	
					}

					PyTuple_SetItem(pyResultList, 2,pylistPos);
					PyTuple_SetItem(pyResultList, 3,pylistDep);
					return pyResultList;	
				}	
			}
			
		}

	}

	Py_INCREF(Py_None);
	return Py_None;
}
Example #23
0
static PyObject*
start_response(PyObject* self, PyObject* args, PyObject* kwargs)
{
  Request* request = ((StartResponse*)self)->request;

  if(request->state.start_response_called) {
    /* not the first call of start_response --
     * throw away any previous status and headers. */
    Py_CLEAR(request->status);
    Py_CLEAR(request->headers);
    request->state.response_length_unknown = false;
  }

  PyObject* status = NULL;
  PyObject* headers = NULL;
  PyObject* exc_info = NULL;
  if(!PyArg_UnpackTuple(args, "start_response", 2, 3, &status, &headers, &exc_info))
    return NULL;

  if(exc_info && exc_info != Py_None) {
    if(!PyTuple_Check(exc_info) || PyTuple_GET_SIZE(exc_info) != 3) {
      TYPE_ERROR("start_response argument 3", "a 3-tuple", exc_info);
      return NULL;
    }

    restore_exception_tuple(exc_info, /* incref items? */ true);

    if(request->state.wsgi_call_done) {
      /* Too late to change headers. According to PEP 333, we should let
       * the exception propagate in this case. */
      return NULL;
    }

    /* Headers not yet sent; handle this start_response call as if 'exc_info'
     * would not have been passed, but print and clear the exception. */
    PyErr_Print();
  }
  else if(request->state.start_response_called) {
    PyErr_SetString(PyExc_TypeError, "'start_response' called twice without "
                     "passing 'exc_info' the second time");
    return NULL;
  }

  if(!PyString_Check(status)) {
    TYPE_ERROR("start_response argument 1", "a 'status reason' string", status);
    return NULL;
  }
  if(!PyList_Check(headers)) {
    TYPE_ERROR("start response argument 2", "a list of 2-tuples", headers);
    return NULL;
  }

  request->headers = headers;

  if(!inspect_headers(request)) {
    request->headers = NULL;
    return NULL;
  }

  request->status = status;

  Py_INCREF(request->status);
  Py_INCREF(request->headers);

  request->state.start_response_called = true;

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

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

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

    /* Verify path exists and can be read */

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

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

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

    /* Init Python environment */

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

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

    PyEval_InitThreads();
    gtstate = PyEval_SaveThread();

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

    i = 0;

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

        if (modname == NULL)
            continue;

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

        PyEval_RestoreThread(gtstate);

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

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

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

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

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

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

    apr_pool_cleanup_register(pool, NULL,
                              pyth_metric_cleanup,
                              apr_pool_cleanup_null);

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

    python_module.metrics_info = (Ganglia_25metric *)metric_info->elts;
    return 0;
}
static int         MaterialDefInit    (MaterialDefObject  *self,
                                       PyObject           *args,
                                       PyObject           *kwds)
 {
  float                                R,G,B;
  PyObject                            *TempTexNames;
  int                                  TempDoubleSided;
  int                                  TempTransparent;
  int                                  TempBillboard;
  int                                  TempBillboardMode;
  int                                  AlphaCtrlEnabled;
  float                                AlphaFadeIn;
  float                                AlphaFadeOut;

  if (!PyArg_ParseTuple
        (args,
         "(fff)Oiiiii(ff)",
         &R,&G,&B,
         &TempTexNames,
         &TempDoubleSided,
         &TempTransparent,
         &TempBillboard,
         &TempBillboardMode,
         &AlphaCtrlEnabled,
         &AlphaFadeIn,
         &AlphaFadeOut))
   {
    return(-1);
   }

  if      (PyList_Check(TempTexNames))
   {
   }
  else
   {
    PyErr_SetString(PyExc_RuntimeError,"texture names argument must be a list");

    return(-1);
   }

  Py_XDECREF(self->Color);
  self->Color = Py_BuildValue("(fff)",R,G,B);
  Py_XDECREF(self->TexNames);
  Py_INCREF(TempTexNames);
  self->TexNames = TempTexNames;

  Py_XDECREF(self->DoubleSided);
  self->DoubleSided = Py_BuildValue("i",TempDoubleSided);
  Py_XDECREF(self->Transparent);
  self->Transparent = Py_BuildValue("i",TempTransparent);
  Py_XDECREF(self->Billboard);
  self->Billboard = Py_BuildValue("i",TempBillboard);
  Py_XDECREF(self->BillboardMode);
  self->BillboardMode = Py_BuildValue("i",TempBillboardMode);
  Py_XDECREF(self->AlphaCtrlEnabled);
  self->AlphaCtrlEnabled = Py_BuildValue("i",AlphaCtrlEnabled);
  Py_XDECREF(self->AlphaFadeRange);
  self->AlphaFadeRange = Py_BuildValue("(ff)",AlphaFadeIn,AlphaFadeOut);

  return(0);
 }
// query
static PyObject *echoprint_py_query_inverted_index(
  PyObject *self, PyObject *args)
{
  PyObject *arg_query, *arg_index, *arg_sim_fun;
  EchoprintInvertedIndex *index;
  uint32_t n;
  uint32_t query_length, n_results, N_MAX_RESULTS;
  uint32_t *query, *output_indices;
  float *output_scores;
  similarity_function sf;
  PyObject *results;

  if(!PyArg_ParseTuple(args, "OOS", &arg_query, &arg_index, &arg_sim_fun))
    return NULL;
  if(!PyList_Check(arg_query))
    return NULL;

  if(strcmp(PyString_AsString(arg_sim_fun), "jaccard") == 0)
    sf = JACCARD;
  else if(strcmp(PyString_AsString(arg_sim_fun), "set_int") == 0)
    sf = SET_INT;
  else if(strcmp(PyString_AsString(arg_sim_fun),
		 "set_int_norm_length_first") == 0)
    sf = SET_INT_NORM_LENGTH_FIRST;
  else
  {
    PyErr_SetString(PyExc_Exception, "similarity must be one of: \"jaccard\", \"set_int\", \"set_int_norm_length_first\"");
    return NULL;
  }

  index = (EchoprintInvertedIndex *) PyCapsule_GetPointer(arg_index, NULL);
  if(!index)
  {
    PyErr_SetString(PyExc_Exception, "the argument is not a valid index");
    return NULL;
  }

  query_length = PySequence_Length(arg_query);
  query = (uint32_t *) malloc(sizeof(uint32_t) * query_length);
  for(n = 0; n < query_length; n++)
  {
    PyObject *code_obj;
    long code;
    code_obj = PySequence_GetItem(arg_query, n);
    if(!PyInt_Check(code_obj))
    {
      PyErr_SetString(
	PyExc_TypeError, "all the codes in the query must be integers");
      Py_DECREF(code_obj);
      free(query);
      return NULL;
    }
    code = (uint32_t) PyInt_AsLong(code_obj);
    Py_DECREF(code_obj);
    query[n] = (int) code;
  }

  N_MAX_RESULTS = 10;
  output_indices = (uint32_t *) malloc(sizeof(uint32_t) * N_MAX_RESULTS);
  output_scores = (float *) malloc(sizeof(float) * N_MAX_RESULTS);
  n_results = echoprint_inverted_index_query(
    query_length, query, index,
    N_MAX_RESULTS, output_indices, output_scores, sf);

  results = PyList_New(n_results);
  for(n = 0; n < n_results; n++)
  {
    PyObject *r = PyDict_New();                                                                                                                                                                                                        
    PyStringObject* score_k = (PyStringObject*)PyString_FromString("score");
    PyFloatObject* score_v = (PyFloatObject*)PyFloat_FromDouble((float) output_scores[n]);
    PyDict_SetItem(r, (PyObject*)score_k, (PyObject*)score_v);
    Py_DECREF(score_k);
    Py_DECREF(score_v);
    PyStringObject* index_k = (PyStringObject*)PyString_FromString("index");
    PyIntObject* index_v = (PyIntObject*)PyInt_FromLong((long) output_indices[n]);
    PyDict_SetItem(r, (PyObject*)index_k, (PyObject*)index_v);
    Py_DECREF(index_k);
    Py_DECREF(index_v);
    PyList_SetItem(results, n, r); 
  }

  free(output_indices);
  free(output_scores);
  free(query);

  return results;
}
Example #27
0
static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
{
	Main *bmain = CTX_data_main(BPy_GetContext());
	Main *mainl = NULL;
	int err = 0;

	flag_all_listbases_ids(LIB_PRE_EXISTING, 1);

	/* here appending/linking starts */
	mainl = BLO_library_append_begin(bmain, &(self->blo_handle), self->relpath);

	{
		int i = 0, code;
		while ((code = BKE_idcode_iter_step(&i))) {
			if (BKE_idcode_is_linkable(code)) {
				const char *name_plural = BKE_idcode_to_name_plural(code);
				PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
				// printf("lib: %s\n", name_plural);
				if (ls && PyList_Check(ls)) {
					/* loop */
					Py_ssize_t size = PyList_GET_SIZE(ls);
					Py_ssize_t i;
					PyObject *item;
					const char *item_str;

					for (i = 0; i < size; i++) {
						item = PyList_GET_ITEM(ls, i);
						item_str = _PyUnicode_AsString(item);

						// printf("  %s\n", item_str);

						if (item_str) {
							ID *id = BLO_library_append_named_part(mainl, &(self->blo_handle), item_str, code);
							if (id) {
#ifdef USE_RNA_DATABLOCKS
								PointerRNA id_ptr;
								RNA_id_pointer_create(id, &id_ptr);
								Py_DECREF(item);
								item = pyrna_struct_CreatePyObject(&id_ptr);
#endif
							}
							else {
								bpy_lib_exit_warn_idname(self, name_plural, item_str);
								/* just warn for now */
								/* err = -1; */
#ifdef USE_RNA_DATABLOCKS
								item = Py_None;
								Py_INCREF(item);
#endif
							}

							/* ID or None */
						}
						else {
							/* XXX, could complain about this */
							bpy_lib_exit_warn_type(self, item);
							PyErr_Clear();

#ifdef USE_RNA_DATABLOCKS
							item = Py_None;
							Py_INCREF(item);
#endif
						}

#ifdef USE_RNA_DATABLOCKS
						PyList_SET_ITEM(ls, i, item);
#endif
					}
				}
			}
		}
	}

	if (err == -1) {
		/* exception raised above, XXX, this leaks some memory */
		BLO_blendhandle_close(self->blo_handle);
		self->blo_handle = NULL;
		flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
		return NULL;
	}
	else {
		Library *lib = mainl->curlib; /* newly added lib, assign before append end */
		BLO_library_append_end(NULL, mainl, &(self->blo_handle), 0, self->flag);
		BLO_blendhandle_close(self->blo_handle);
		self->blo_handle = NULL;

		{	/* copied from wm_operator.c */
			/* mark all library linked objects to be updated */
			recalc_all_library_objects(G.main);

			/* append, rather than linking */
			if ((self->flag & FILE_LINK) == 0) {
				BKE_library_make_local(bmain, lib, 1);
			}
		}

		flag_all_listbases_ids(LIB_PRE_EXISTING, 0);

		Py_RETURN_NONE;
	}
}
static PyObject *echoprint_py_inverted_index_create_block(
  PyObject *self, PyObject *args)
{
  // input is a list of lists, each item of the outer list being a
  // song (list of codes); second argument is the output path

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

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

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

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

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

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

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

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

  if(error_parsing_input || error_writing_blocks)
    return NULL;

  return Py_None;

}
Example #29
0
static PyObject *object_to_string(PyObject *object)
{
  PyObject *result = NULL;

  if (PyUnicode_Check(object)) {
    Py_INCREF(object);
    result = object;
  }
  
  else if (PyString_Check(object)) {
    /* Python DOM binding: string objects must be UTF-8 */
    result = PyUnicode_FromEncodedObject(object, "UTF-8", "strict");
  }

  else if (PyFloat_Check(object)) {
    double d = PyFloat_AS_DOUBLE(object);
    if (PyNumber_Finite(object)) {
      if (floor(d) == d) {
        /* Format as integer */
        PyObject *num = PyNumber_Long(object);
        if (!num)
          return NULL;
        result = PyObject_Unicode(num);
        Py_DECREF(num);
      } 
      else {
        /* worst case length calc to ensure no buffer overrun:
           fmt = %#.<prec>g
           buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp for 
                                                  any double rep.) 
           len = 1 + prec + 1 + 2 + 5 = 9 + prec
           If prec=0 the effective precision is 1 (the leading digit is
           always given), therefore increase by one to 10+prec. 
        */
        char buf[32]; /* only 10 + 12 + '\0' is needed, more than enough */
        int len;
        len = sprintf(buf, "%0.12g", d);
        result = PyUnicode_DecodeASCII(buf, len, "strict");
      }
    }
    else if (PyNumber_IsNaN(object)) {
      result = PyUnicode_DecodeASCII("NaN", 3, "strict");
    }
    else if (d < 0) {
      result = PyUnicode_DecodeASCII("-Infinity", 9, "strict");
    }
    else {
      result = PyUnicode_DecodeASCII("Infinity", 8, "strict");
    }
  }

  else if (PyBoolean_Check(object)) {
    if (PyObject_IsTrue(object))
      result = PyUnicode_DecodeASCII("true", 4, "strict");
    else
      result = PyUnicode_DecodeASCII("false", 5, "strict");
  }

  else if (PyInt_Check(object) || PyLong_Check(object)) {
    result = PyObject_Unicode(object);
  }

  else if (PyList_Check(object)) {
    if (PyList_GET_SIZE(object)) 
      result = object_to_string(PyList_GET_ITEM(object, 0));
    else
      result = PyUnicode_FromUnicode(NULL, 0);
  }

  else {
    /* check for pre-computed string value */
    result = PyObject_GetAttrString(object, "stringValue");
    if (result == NULL) {
      /* assume a DOM node, node_to_string() returns empty string if not */
      PyErr_Clear();
      result = node_to_string(object);
    }
  }
  return result;
}
Example #30
0
/**
 *  evalDistribution function evaluate a model function with input vector
 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
 *
 */ 
static PyObject * evalDistribution(CGaussian *self, PyObject *args){
	PyObject *qx, *qy;
	PyArrayObject * pars;
	int npars ,mpars;
	
	// Get parameters
	
	    // Reader parameter dictionary
    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
    self->model->sigma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sigma") );
    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
    // Read in dispersion parameters
    PyObject* disp_dict;
    DispersionVisitor* visitor = new DispersionVisitor();

	
	// Get input and determine whether we have to supply a 1D or 2D return value.
	if ( !PyArg_ParseTuple(args,"O",&pars) ) {
	    PyErr_SetString(CGaussianError, 
	    	"CGaussian.evalDistribution expects a q value.");
		return NULL;
	}
    // Check params
	
    if(PyArray_Check(pars)==1) {
		
	    // Length of list should 1 or 2
	    npars = pars->nd; 
	    if(npars==1) {
	        // input is a numpy array
	        if (PyArray_Check(pars)) {
		        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
		    }
		}else{
		    PyErr_SetString(CGaussianError, 
                   "CGaussian.evalDistribution expect numpy array of one dimension.");
	        return NULL;
		}
    }else if( PyList_Check(pars)==1) {
    	// Length of list should be 2 for I(qx,qy)
	    mpars = PyList_GET_SIZE(pars); 
	    if(mpars!=2) {
	    	PyErr_SetString(CGaussianError, 
	    		"CGaussian.evalDistribution expects a list of dimension 2.");
	    	return NULL;
	    }
	     qx = PyList_GET_ITEM(pars,0);
	     qy = PyList_GET_ITEM(pars,1);
	     if (PyArray_Check(qx) && PyArray_Check(qy)) {
	         return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
		           (PyArrayObject*)qy);
		 }else{
		    PyErr_SetString(CGaussianError, 
                   "CGaussian.evalDistribution expect 2 numpy arrays in list.");
	        return NULL;
	     }
	}
	PyErr_SetString(CGaussianError, 
                   "CGaussian.evalDistribution couln't be run.");
	return NULL;
	
}