Ejemplo n.º 1
0
static PyObject *
pytrap_init(PyObject *self, PyObject *args, PyObject *keywds)
{
    char **argv = NULL;
    char *arg;
    PyObject *argvlist;
    PyObject *strObj;
    int argc = 0, i, ifcin = 1, ifcout = 0;

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

    argc = PyList_Size(argvlist);
    argv = calloc(argc, sizeof(char *));
    for (i=0; i<argc; i++) {
        strObj = PyList_GetItem(argvlist, i);
#if PY_MAJOR_VERSION >= 3
        arg = PyUnicode_AsUTF8AndSize(strObj, NULL);
#else
        arg = PyString_AS_STRING(strObj);
#endif
        argv[i] = arg;
    }

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

    Py_RETURN_NONE;
}
Ejemplo n.º 2
0
static int
dbm_contains(PyObject *self, PyObject *arg)
{
    dbmobject *dp = (dbmobject *)self;
    datum key, val;
    Py_ssize_t size;

    if ((dp)->di_dbm == NULL) {
        PyErr_SetString(DbmError,
                        "DBM object has already been closed");
         return -1;
    }
    if (PyUnicode_Check(arg)) {
        key.dptr = (char *)PyUnicode_AsUTF8AndSize(arg, &size);
        key.dsize = size;
        if (key.dptr == NULL)
            return -1;
    }
    else if (!PyBytes_Check(arg)) {
        PyErr_Format(PyExc_TypeError,
                     "dbm key must be bytes or string, not %.100s",
                     arg->ob_type->tp_name);
        return -1;
    }
    else {
        key.dptr = PyBytes_AS_STRING(arg);
        key.dsize = PyBytes_GET_SIZE(arg);
    }
    val = dbm_fetch(dp->di_dbm, key);
    return val.dptr != NULL;
}
Ejemplo n.º 3
0
int py_convert(lua_State *L, PyObject *o, int withnone)
{
    int ret = 0;
    if (o == Py_None) {
        if (withnone) {
            lua_pushliteral(L, "Py_None");
            lua_rawget(L, LUA_REGISTRYINDEX);
            if (lua_isnil(L, -1)) {
                lua_pop(L, 1);
                luaL_error(L, "lost none from registry");
            }
        } else {
            /* Not really needed, but this way we may check
             * for errors with ret == 0. */
            lua_pushnil(L);
            ret = 1;
        }
    } else if (o == Py_True) {
        lua_pushboolean(L, 1);
        ret = 1;
    } else if (o == Py_False) {
        lua_pushboolean(L, 0);
        ret = 1;
#if PY_MAJOR_VERSION >= 3
    } else if (PyUnicode_Check(o)) {
        Py_ssize_t len;
        char *s = PyUnicode_AsUTF8AndSize(o, &len);
#else
    } else if (PyString_Check(o)) {
        Py_ssize_t len;
        char *s;
        PyString_AsStringAndSize(o, &s, &len);
#endif
        lua_pushlstring(L, s, len);
        ret = 1;
    } else if (PyLong_Check(o)) {
        lua_pushnumber(L, (lua_Number)PyLong_AsLong(o));
        ret = 1;
    } else if (PyFloat_Check(o)) {
        lua_pushnumber(L, (lua_Number)PyFloat_AsDouble(o));
        ret = 1;
    } else if (LuaObject_Check(o)) {
        lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)o)->ref);
        ret = 1;
    } else {
        int asindx = 0;
        if (PyDict_Check(o) || PyList_Check(o) || PyTuple_Check(o))
            asindx = 1;
        ret = py_convert_custom(L, o, asindx);
        if (ret && !asindx &&
            (PyFunction_Check(o) || PyCFunction_Check(o)))
            lua_pushcclosure(L, py_asfunc_call, 1);
    }
    return ret;
}
Ejemplo n.º 4
0
// from Python/bltinmodule.c
static const char *
source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
{
    const char *str;
    Py_ssize_t size;
    Py_buffer view;

    *cmd_copy = NULL;
    if (PyUnicode_Check(cmd)) {
        cf->cf_flags |= PyCF_IGNORE_COOKIE;
        str = PyUnicode_AsUTF8AndSize(cmd, &size);
        if (str == NULL)
            return NULL;
    }
    else if (PyBytes_Check(cmd)) {
        str = PyBytes_AS_STRING(cmd);
        size = PyBytes_GET_SIZE(cmd);
    }
    else if (PyByteArray_Check(cmd)) {
        str = PyByteArray_AS_STRING(cmd);
        size = PyByteArray_GET_SIZE(cmd);
    }
    else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
        /* Copy to NUL-terminated buffer. */
        *cmd_copy = PyBytes_FromStringAndSize(
            (const char *)view.buf, view.len);
        PyBuffer_Release(&view);
        if (*cmd_copy == NULL) {
            return NULL;
        }
        str = PyBytes_AS_STRING(*cmd_copy);
        size = PyBytes_GET_SIZE(*cmd_copy);
    }
    else {
        PyErr_Format(PyExc_TypeError,
          "%s() arg 1 must be a %s object",
          funcname, what);
        return NULL;
    }

    if (strlen(str) != (size_t)size) {
        PyErr_SetString(PyExc_ValueError,
                        "source code string cannot contain null bytes");
        Py_CLEAR(*cmd_copy);
        return NULL;
    }
    return str;
}
Ejemplo n.º 5
0
static PyObject *
stdprinter_write(PyStdPrinter_Object *self, PyObject *args)
{
    PyObject *unicode;
    PyObject *bytes = NULL;
    const char *str;
    Py_ssize_t n;
    int err;

    if (self->fd < 0) {
        /* fd might be invalid on Windows
         * I can't raise an exception here. It may lead to an
         * unlimited recursion in the case stderr is invalid.
         */
        Py_RETURN_NONE;
    }

    if (!PyArg_ParseTuple(args, "U", &unicode))
        return NULL;

    /* encode Unicode to UTF-8 */
    str = PyUnicode_AsUTF8AndSize(unicode, &n);
    if (str == NULL) {
        PyErr_Clear();
        bytes = _PyUnicode_AsUTF8String(unicode, "backslashreplace");
        if (bytes == NULL)
            return NULL;
        str = PyBytes_AS_STRING(bytes);
        n = PyBytes_GET_SIZE(bytes);
    }

    n = _Py_write(self->fd, str, n);
    /* save errno, it can be modified indirectly by Py_XDECREF() */
    err = errno;

    Py_XDECREF(bytes);

    if (n == -1) {
        if (err == EAGAIN) {
            PyErr_Clear();
            Py_RETURN_NONE;
        }
        return NULL;
    }

    return PyLong_FromSsize_t(n);
}
Ejemplo n.º 6
0
static int py_convert(lua_State *L, PyObject *o) {
    int ret = 0;
    if (o == Py_None || o == Py_False) {
        lua_pushnil(L);
        ret = 1;
    } else if (o == Py_True) {
        lua_pushnumber(L, 1);
        ret = 1;
#if PY_MAJOR_VERSION >= 3
    } else if (PyUnicode_Check(o)) {
        Py_ssize_t len;
        char *s = PyUnicode_AsUTF8AndSize(o, &len);
#else
    } else if (PyString_Check(o)) {
        lua_pushstring(L, get_pyobject_as_string(L, o));
        ret = 1;
    } else if (PyUnicode_Check(o)) {
        char *s = get_pyobject_as_utf8string(L, o);
#endif
        lua_pushstring(L, s);
        ret = 1;
#if PY_MAJOR_VERSION < 3
    } else if (PyInt_Check(o)) {
        lua_pushnumber(L, PyInt_AsLong(o));
        ret = 1;
#endif
    } else if (PyLong_Check(o)) {
        lua_pushnumber(L, PyLong_AsLong(o));
        ret = 1;
    } else if (PyFloat_Check(o)) {
        lua_pushnumber(L, PyFloat_AsDouble(o));
        ret = 1;
    } else {
        int asindx = 0;
        if (PyList_Check(o) || PyTuple_Check(o) || PyDict_Check(o))
            asindx = 1;
        ret = py_convert_custom(L, o, asindx);
    }
    return ret;
}
Ejemplo n.º 7
0
static void *PyUnicodeToUTF8(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
{
  PyObject *obj = (PyObject *) _obj;
  PyObject *newObj;
#if (PY_VERSION_HEX >= 0x03030000)
  if(PyUnicode_IS_COMPACT_ASCII(obj))
  {
    Py_ssize_t len;
    char *data = PyUnicode_AsUTF8AndSize(obj, &len);
    *_outLen = len;
    return data;
  }
#endif
  newObj = PyUnicode_AsUTF8String(obj);
  if(!newObj)
  {
    return NULL;
  }

  GET_TC(tc)->newObj = newObj;

  *_outLen = PyString_GET_SIZE(newObj);
  return PyString_AS_STRING(newObj);
}
Ejemplo n.º 8
0
static PyObject* GetDataDecimal(Cursor* cur, Py_ssize_t iCol)
{
    // The SQL_NUMERIC_STRUCT support is hopeless (SQL Server ignores scale on input parameters and output columns,
    // Oracle does something else weird, and many drivers don't support it at all), so we'll rely on the Decimal's
    // string parsing.  Unfortunately, the Decimal author does not pay attention to the locale, so we have to modify
    // the string ourselves.
    //
    // Oracle inserts group separators (commas in US, periods in some countries), so leave room for that too.
    //
    // Some databases support a 'money' type which also inserts currency symbols.  Since we don't want to keep track of
    // all these, we'll ignore all characters we don't recognize.  We will look for digits, negative sign (which I hope
    // is universal), and a decimal point ('.' or ',' usually).  We'll do everything as Unicode in case currencies,
    // etc. are too far out.

    const TextEnc& enc = cur->cnxn->sqlwchar_enc;
    // I'm going to request the data as Unicode in case there is a weird currency symbol.  If
    // this is a performance problems we may want a flag on this.

    bool isNull = false;
    byte* pbData = 0;
    Py_ssize_t cbData = 0;
    if (!ReadVarColumn(cur, iCol, enc.ctype, isNull, pbData, cbData))
        return 0;

    if (isNull)
    {
        I(pbData == 0 && cbData == 0);
        Py_RETURN_NONE;
    }

    Object result(TextBufferToObject(enc, pbData, cbData));

    pyodbc_free(pbData);

    if (!result)
        return 0;

    // Remove non-digits and convert the databases decimal to a '.' (required by decimal ctor).
    //
    // We are assuming that the decimal point and digits fit within the size of ODBCCHAR.

    // If Unicode, convert to UTF-8 and copy the digits and punctuation out.  Since these are
    // all ASCII characters, we can ignore any multiple-byte characters.  Fortunately, if a
    // character is multi-byte all bytes will have the high bit set.

    char* pch;
    Py_ssize_t cch;

#if PY_MAJOR_VERSION >= 3
    if (PyUnicode_Check(result))
    {
        pch = PyUnicode_AsUTF8AndSize(result, &cch);
    }
    else
    {
        int n = PyBytes_AsStringAndSize(result, &pch, &cch);
        if (n < 0)
            pch = 0;
    }
#else
    Object encoded;
    if (PyUnicode_Check(result))
    {
        encoded = PyUnicode_AsUTF8String(result);
        if (!encoded)
            return 0;
        result = encoded.Detach();
    }
    int n = PyString_AsStringAndSize(result, &pch, &cch);
    if (n < 0)
        pch = 0;
#endif

    if (!pch)
        return 0;

    // TODO: Why is this limited to 100?  Also, can we perform a check on the original and use
    // it as-is?
    char ascii[100];
    size_t asciilen = 0;

    const char* pchMax = pch + cch;
    while (pch < pchMax)
    {
        if ((*pch & 0x80) == 0)
        {
            if (*pch == chDecimal)
            {
                // Must force it to use '.' since the Decimal class doesn't pay attention to the locale.
                ascii[asciilen++] = '.';
            }
            else if ((*pch >= '0' && *pch <= '9') || *pch == '-')
            {
                ascii[asciilen++] = (char)(*pch);
            }
        }
        pch++;
    }

    ascii[asciilen] = 0;

    Object str(PyString_FromStringAndSize(ascii, (Py_ssize_t)asciilen));
    if (!str)
        return 0;
    PyObject* decimal_type = GetClassForThread("decimal", "Decimal");
    if (!decimal_type)
        return 0;
    PyObject* decimal = PyObject_CallFunction(decimal_type, "O", str.Get());
    Py_DECREF(decimal_type);
    return decimal;
}
Ejemplo n.º 9
0
static PyObject *
pytrap_init(PyObject *self, PyObject *args, PyObject *keywds)
{
    char **argv = NULL;
    char *arg;
    PyObject *argvlist;
    PyObject *strObj;
    int argc = 0, i, ifcin = 1, ifcout = 0;

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

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

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

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

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

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

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

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

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

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

    Py_RETURN_NONE;
}
Ejemplo n.º 10
0
Archivo: misc.c Proyecto: cvxopt/smcp
static PyObject* sdpa_readhead
(PyObject *self, PyObject *args)
{
  int i,j,t;
  int_t m=0,n=0,nblocks=0;
  matrix *bstruct = NULL;
  PyObject *f;

  char buf[2048];  // buffer
  char *info;

  if (!PyArg_ParseTuple(args,"O",&f)) return NULL;
#if PY_MAJOR_VERSION >= 3
    if (PyUnicode_Check(f)) {
      const char* fname = PyUnicode_AsUTF8AndSize(f,NULL);
#else
    if (PyString_Check(f)) {
      const char* fname = PyString_AsString(f);
#endif
      FILE *fp = fopen(fname,"r");
      if (!fp) {
        return NULL;
      }
      /* Skip comments and read m */
      while (1) {
        info = fgets(buf,1024,fp);
        if (buf[0] != '*' && buf[0] != '"') {
          sscanf(buf,"%d",&i);
          break;
        }
      }
      m = (int_t) i;

      /* read nblocks */
      j = fscanf(fp,"%d",&i);
      nblocks = (int_t) i;

      /* read blockstruct and compute block offsets*/
      bstruct = Matrix_New(nblocks,1,INT);
      if (!bstruct) return PyErr_NoMemory();
      n = 0;
      for (i=0; i<nblocks; i++) {
        j = fscanf(fp,"%*[^0-9+-]%d",&t);
        MAT_BUFI(bstruct)[i] = (int_t) t;
        n += (int_t) labs(MAT_BUFI(bstruct)[i]);
      }
      fclose(fp);
  }

  return Py_BuildValue("iiN",n,m,bstruct);
}


static char doc_sdpa_read[] =
  "Reads sparse SDPA data file (dat-s).\n"
  "\n"
  "A,b,bstruct = sdpa_read(f[,neg=False])\n"
  "\n"
  "PURPOSE\n"
  "Reads problem data from sparse SDPA data file for\n"
  "the semidefinite programs:\n"
  "\n"
  "  (P)  minimize    <A0,X>\n"
  "       subject to  <Ai,X> = bi,   i = 1,...,m\n"
  "                   X >= 0\n"
  "\n"
  "  (D)  maximize    b'*y\n"
  "       subject to  sum_i Ai*yi + S = A0\n"
  "                   S >= 0\n"
  "\n"
  "Here '>=' means that X and S must be positive semidefinite.\n"
  "The matrices A0,A1,...Am are symmetric and of order n.\n"
  "If the optional argument 'neg' is True, the negative of the\n"
  "problem data is returned.\n"
  "\n"
  "ARGUMENTS\n"
  "f         Python file object\n"
  "\n"
  "neg       Python boolean (optional)\n"
  "\n"
  "RETURNS\n"
  "A         CVXOPT sparse matrix of doubles with columns Ai[:]\n"
  "          (Only lower trianglular elements of Ai are stored.)\n"
  "\n"
  "b         CVXOPT matrix\n"
  "\n"
  "bstruct   CVXOPT integer matrix\n";

static PyObject* sdpa_read
(PyObject *self, PyObject *args, PyObject *kwrds)
{
  int i,j,mno,bno,ii,jj,t;
  int_t k,m,n,nblocks,nlines;
  double v;
  long fpos;
  PyObject *f;
  PyObject *neg = Py_False;
  char *info;
  const char* fname;
  int_t* boff;     // block offset
  char buf[2048];  // buffer
  char *kwlist[] = {"f","neg",NULL};

  if (!PyArg_ParseTupleAndKeywords(args,kwrds,"O|O",kwlist,&f,&neg)) return NULL;
  #if PY_MAJOR_VERSION >= 3
  if (PyUnicode_Check(f)) fname = PyUnicode_AsUTF8AndSize(f,NULL);
  #elif PY_MAJOR_VERSION == 2
  if (PyString_Check(f)) fname = PyString_AsString(f);
  #endif
  FILE *fp = fopen(fname,"r");
  if (!fp) {
    return NULL;
  }
  /* Skip comments and read m */
  while (1) {
    info = fgets(buf,1024,fp);
    if (buf[0] != '*' && buf[0] != '"') {
      sscanf(buf,"%d",&i);
      break;
    }
  }
  m = (int_t) i;

  /* read nblocks */
  j = fscanf(fp,"%d",&i);
  nblocks = (int_t) i;

  /* read blockstruct and compute block offsets*/
  matrix *bstruct = Matrix_New(nblocks,1,INT);
  if (!bstruct) return PyErr_NoMemory();
  boff = malloc(sizeof(int_t)*(nblocks+1));
  if(!boff) return PyErr_NoMemory();
  boff[0] = 0;  n = 0;
  for (i=0; i<nblocks; i++) {
    j = fscanf(fp,"%*[^0-9+-]%d",&t);
    MAT_BUFI(bstruct)[i] = (int_t) t;
    n += (int_t) labs(MAT_BUFI(bstruct)[i]);
    boff[i+1] = n;
  }

  /* read vector b */
  matrix *b = Matrix_New(m,1,DOUBLE);
  if (!b) return PyErr_NoMemory();
  for (i=0;i<m;i++) {
    j = fscanf(fp,"%*[^0-9+-]%lf",&MAT_BUFD(b)[i]);
    if (neg == Py_True)
      MAT_BUFD(b)[i] *= -1;
  }

  /* count remaining lines */
  fpos = ftell(fp);
  for (nlines = 0; fgets(buf, 1023, fp) != NULL; nlines++);
  //nlines--;
  fseek(fp,fpos,SEEK_SET);

  /* Create data matrix A */
  spmatrix *A = SpMatrix_New(n*n,m+1,nlines,DOUBLE);
  if (!A) return PyErr_NoMemory();

  // read data matrices
  fseek(fp,fpos,SEEK_SET);
  for (i=0,j=-1,k=0;k<nlines;k++){
    if (fscanf(fp,"%*[^0-9+-]%d",&mno) <=0 ) break;
    if (fscanf(fp,"%*[^0-9+-]%d",&bno) <=0 ) break;
    if (fscanf(fp,"%*[^0-9+-]%d",&ii) <=0 ) break;
    if (fscanf(fp,"%*[^0-9+-]%d",&jj) <=0 ) break;
    if (fscanf(fp,"%*[^0-9+-]%lf",&v) <=0 ) break;

    // check that value is nonzero
    if (v != 0) {
      // add block offset
      ii += boff[bno-1];
      jj += boff[bno-1];

      // insert index and value
      SP_ROW(A)[i] = (int_t)  ((ii-1)*n + (jj-1));
      if (neg == Py_True)
	SP_VALD(A)[i] = -v;
      else
	SP_VALD(A)[i] = v;

      // update col. ptr.
      while (mno > j)
	SP_COL(A)[++j] = i;

      i++;
    }
  }
  // update last element(s) of col. ptr.
  while (m+1 > j)
    SP_COL(A)[++j] = i;

  fclose(fp);

  // free temp. memory
  free(boff);

  return Py_BuildValue("NNN",A,b,bstruct);
}
Ejemplo n.º 11
0
Archivo: misc.c Proyecto: cvxopt/smcp
static PyObject* sdpa_write
(PyObject *self, PyObject *args, PyObject *kwrds)
{
  int i,Il,Jl,Bl,Ml;
  int_t n;
  spmatrix *A;
  matrix *b,*bstruct;
  PyObject *f;
  PyObject *neg = Py_False;
  char *kwlist[] = {"f","A","b","bstruct","neg",NULL};
  const char* fname;
  double v;

  if (!PyArg_ParseTupleAndKeywords(args,kwrds, "OOOO|O", kwlist, &f, &A, &b, &bstruct,&neg)) return NULL;
  #if PY_MAJOR_VERSION >= 3
  if (PyUnicode_Check(f)) fname = PyUnicode_AsUTF8AndSize(f,NULL);
  #elif PY_MAJOR_VERSION == 2
  if (PyString_Check(f)) fname = PyString_AsString(f);
  #endif
  FILE *fp = fopen(fname,"r");
  if (!fp) {
    Py_DECREF(f);
    return NULL;
  }

  fprintf(fp,"* sparse SDPA data file (created by SMCP)\n");
  fprintf(fp,"%i = m\n",(int) MAT_NROWS(b));
  fprintf(fp,"%i = nBlocks\n", (int) MAT_NROWS(bstruct));
  // compute n and write blockstruct
  n = 0;
  for (i=0;i<MAT_NROWS(bstruct);i++) {
    fprintf(fp,"%i ", (int) MAT_BUFI(bstruct)[i]);
    n += (int_t) labs(MAT_BUFI(bstruct)[i]);
  }
  fprintf(fp,"\n");

  // write vector b
  if (neg == Py_True) {
    for (i=0;i<MAT_NROWS(b);i++)
      fprintf(fp,"%.12g ",-MAT_BUFD(b)[i]);
  }
  else {
    for (i=0;i<MAT_NROWS(b);i++)
      fprintf(fp,"%.12g ",MAT_BUFD(b)[i]);
  }
  fprintf(fp,"\n");

  // Write data matrices A0,A1,A2,...,Am
  for (Ml=0;Ml<=MAT_NROWS(b);Ml++) {
    for (i=0;i<SP_COL(A)[Ml+1]-SP_COL(A)[Ml];i++){

      Jl = 1 + SP_ROW(A)[SP_COL(A)[Ml]+i] / n;
      Il = 1 + SP_ROW(A)[SP_COL(A)[Ml]+i] % n;

      // Skip if element is in strict upper triangle
      if (Jl > Il)
	PyErr_Warn(PyExc_Warning,"Ignored strictly upper triangular element.");

      Bl = 1;
      while ((Il > labs(MAT_BUFI(bstruct)[Bl-1])) && (Jl > labs(MAT_BUFI(bstruct)[Bl-1]))) {
	Il -= (int_t) labs(MAT_BUFI(bstruct)[Bl-1]);
	Jl -= (int_t) labs(MAT_BUFI(bstruct)[Bl-1]);
	Bl += 1;
      }
      /* Error check */
      if ((Il > labs(MAT_BUFI(bstruct)[Bl-1])) || (Jl > labs(MAT_BUFI(bstruct)[Bl-1])))
	printf("Error: Matrix contains elements outside blocks!\n");

      // print upper triangle entries:
      //   <matno> <blkno> <i> <j> <entry>
      v = SP_VALD(A)[SP_COL(A)[Ml]+i];
      if ( v != 0.0) {
	if (neg == Py_True)
	  fprintf(fp,"%i %i %i %i %.12g\n",
		  (int) Ml,(int) Bl,(int) Jl,(int) Il, -v);
	else
	  fprintf(fp,"%i %i %i %i %.12g\n",
		  (int) Ml,(int) Bl,(int) Jl,(int) Il, v);
      }
    }
  }

  fclose(fp);
  Py_DECREF(f);
  Py_RETURN_NONE;
}
Ejemplo n.º 12
0
    void MainExport initFreeCAD() {

        // Init phase ===========================================================
        App::Application::Config()["ExeName"] = "FreeCAD";
        App::Application::Config()["ExeVendor"] = "FreeCAD";
        App::Application::Config()["AppDataSkipVendor"] = "true";


        int    argc=1;
        char** argv;
        argv = (char**)malloc(sizeof(char*)* (argc+1));

#if defined(FC_OS_WIN32)
        argv[0] = (char*)malloc(MAX_PATH);
        strncpy(argv[0],App::Application::Config()["AppHomePath"].c_str(),MAX_PATH);
        argv[0][MAX_PATH-1] = '\0'; // ensure null termination
#elif defined(FC_OS_CYGWIN)
        HMODULE hModule = GetModuleHandle("FreeCAD.dll");
        char szFileName [MAX_PATH];
        GetModuleFileName(hModule, szFileName, MAX_PATH-1);
        argv[0] = (char*)malloc(MAX_PATH);
        strncpy(argv[0],szFileName,MAX_PATH);
        argv[0][MAX_PATH-1] = '\0'; // ensure null termination
#elif defined(FC_OS_LINUX) || defined(FC_OS_BSD)
        putenv("LANG=C");
        putenv("LC_ALL=C");
        // get whole path of the library
        Dl_info info;
        int ret = dladdr((void*)initFreeCAD, &info);
        if ((ret == 0) || (!info.dli_fname)) {
            free(argv);
            PyErr_SetString(PyExc_ImportError, "Cannot get path of the FreeCAD module!");
            return;
        }

        argv[0] = (char*)malloc(PATH_MAX);
        strncpy(argv[0], info.dli_fname,PATH_MAX);
        argv[0][PATH_MAX-1] = '\0'; // ensure null termination
        // this is a workaround to avoid a crash in libuuid.so
#elif defined(FC_OS_MACOSX)

        // The MacOS approach uses the Python sys.path list to find the path
        // to FreeCAD.so - this should be OS-agnostic, except these two
        // strings, and the call to access().
        const static char libName[] = "/FreeCAD.so";
        const static char upDir[] = "/../";

        char *buf = NULL;

        PyObject *pySysPath = PySys_GetObject("path");
        if ( PyList_Check(pySysPath) ) { 
            int i;
            // pySysPath should be a *PyList of strings - iterate through it
            // backwards since the FreeCAD path was likely appended just before
            // we were imported.
            for (i = PyList_Size(pySysPath) - 1; i >= 0 ; --i) {
                char *basePath;
                PyObject *pyPath = PyList_GetItem(pySysPath, i);
                long sz = 0;

#if PY_MAJOR_VERSION >= 3
                if ( PyUnicode_Check(pyPath) ) {
                    // Python 3 string
                    basePath = PyUnicode_AsUTF8AndSize(pyPath, &sz);

                }
#else
                if ( PyString_Check(pyPath) ) {
                    // Python 2 string type
                    PyString_AsStringAndSize(pyPath, &basePath, &sz);

                } else if ( PyUnicode_Check(pyPath) ) {
                    // Python 2 unicode type - explicitly use UTF-8 codec
                    PyObject *fromUnicode = PyUnicode_AsUTF8String(pyPath);
                    PyString_AsStringAndSize(fromUnicode, &basePath, &sz);
                    Py_XDECREF(fromUnicode);
                }
#endif // #if/else PY_MAJOR_VERSION >= 3
                  else {
                    continue;
                }

                if (sz + sizeof(libName) > PATH_MAX) {
                    continue;
                }

                // buf gets assigned to argv[0], which is free'd at the end
                buf = (char *)malloc(sz + sizeof(libName));
                if (buf == NULL) {
                    break;
                }

                strcpy(buf, basePath);

                // append libName to buf
                strcat(buf, libName);
                if (access(buf, R_OK | X_OK) == 0) {

                    // The FreeCAD "home" path is one level up from
                    // libName, so replace libName with upDir.
                    strcpy(buf + sz, upDir); 
                    buf[sz + sizeof(upDir)] = '\0';
                    break;
                }
            } // end for (i = PyList_Size(pySysPath) - 1; i >= 0 ; --i) {
        } // end if ( PyList_Check(pySysPath) ) { 

        if (buf == NULL) {
            PyErr_SetString(PyExc_ImportError, "Cannot get path of the FreeCAD module!");
            return;
        }

        argv[0] = buf;
#else
# error "Implement: Retrieve the path of the module for your platform."
#endif
        argv[argc] = 0;

        try {
            // Inits the Application
            App::Application::init(argc,argv);
        }
        catch (const Base::Exception& e) {
            std::string appName = App::Application::Config()["ExeName"];
            std::stringstream msg;
            msg << "While initializing " << appName << " the  following exception occurred: '"
                << e.what() << "'\n\n";
            msg << "\nPlease contact the application's support team for more information.\n\n";
            printf("Initialization of %s failed:\n%s", appName.c_str(), msg.str().c_str());
        }

        free(argv[0]);
        free(argv);

        return;
    } //InitFreeCAD....
Ejemplo n.º 13
0
static PyObject *
complex_subtype_from_string(PyTypeObject *type, PyObject *v)
{
    const char *s, *start;
    char *end;
    double x=0.0, y=0.0, z;
    int got_bracket=0;
    PyObject *s_buffer = NULL;
    Py_ssize_t len;
    Py_buffer view = {NULL, NULL};

    if (PyUnicode_Check(v)) {
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
        if (s_buffer == NULL)
            return NULL;
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
        if (s == NULL)
            goto error;
    }
    else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
        s = (const char *)view.buf;
        len = view.len;
    }
    else {
        PyErr_Format(PyExc_TypeError,
            "complex() argument must be a string or a number, not '%.200s'",
            Py_TYPE(v)->tp_name);
        return NULL;
    }

    /* position on first nonblank */
    start = s;
    while (Py_ISSPACE(*s))
        s++;
    if (*s == '(') {
        /* Skip over possible bracket from repr(). */
        got_bracket = 1;
        s++;
        while (Py_ISSPACE(*s))
            s++;
    }

    /* a valid complex string usually takes one of the three forms:

         <float>                  - real part only
         <float>j                 - imaginary part only
         <float><signed-float>j   - real and imaginary parts

       where <float> represents any numeric string that's accepted by the
       float constructor (including 'nan', 'inf', 'infinity', etc.), and
       <signed-float> is any string of the form <float> whose first
       character is '+' or '-'.

       For backwards compatibility, the extra forms

         <float><sign>j
         <sign>j
         j

       are also accepted, though support for these forms may be removed from
       a future version of Python.
    */

    /* first look for forms starting with <float> */
    z = PyOS_string_to_double(s, &end, NULL);
    if (z == -1.0 && PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_ValueError))
            PyErr_Clear();
        else
            goto error;
    }
    if (end != s) {
        /* all 4 forms starting with <float> land here */
        s = end;
        if (*s == '+' || *s == '-') {
            /* <float><signed-float>j | <float><sign>j */
            x = z;
            y = PyOS_string_to_double(s, &end, NULL);
            if (y == -1.0 && PyErr_Occurred()) {
                if (PyErr_ExceptionMatches(PyExc_ValueError))
                    PyErr_Clear();
                else
                    goto error;
            }
            if (end != s)
                /* <float><signed-float>j */
                s = end;
            else {
                /* <float><sign>j */
                y = *s == '+' ? 1.0 : -1.0;
                s++;
            }
            if (!(*s == 'j' || *s == 'J'))
                goto parse_error;
            s++;
        }
        else if (*s == 'j' || *s == 'J') {
            /* <float>j */
            s++;
            y = z;
        }
        else
            /* <float> */
            x = z;
    }
    else {
        /* not starting with <float>; must be <sign>j or j */
        if (*s == '+' || *s == '-') {
            /* <sign>j */
            y = *s == '+' ? 1.0 : -1.0;
            s++;
        }
        else
            /* j */
            y = 1.0;
        if (!(*s == 'j' || *s == 'J'))
            goto parse_error;
        s++;
    }

    /* trailing whitespace and closing bracket */
    while (Py_ISSPACE(*s))
        s++;
    if (got_bracket) {
        /* if there was an opening parenthesis, then the corresponding
           closing parenthesis should be right here */
        if (*s != ')')
            goto parse_error;
        s++;
        while (Py_ISSPACE(*s))
            s++;
    }

    /* we should now be at the end of the string */
    if (s-start != len)
        goto parse_error;

    PyBuffer_Release(&view);
    Py_XDECREF(s_buffer);
    return complex_subtype_from_doubles(type, x, y);

  parse_error:
    PyErr_SetString(PyExc_ValueError,
                    "complex() arg is a malformed string");
  error:
    PyBuffer_Release(&view);
    Py_XDECREF(s_buffer);
    return NULL;
}
Ejemplo n.º 14
0
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
    if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
            __Pyx_sys_getdefaultencoding_not_ascii && 
#endif
            PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
        char* defenc_c;
        // borrowed, cached reference
        PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
        if (!defenc) return NULL;
        defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        {
            char* end = defenc_c + PyBytes_GET_SIZE(defenc);
            char* c;
            for (c = defenc_c; c < end; c++) {
                if ((unsigned char) (*c) >= 128) {
                    // raise the error
                    PyUnicode_AsASCIIString(o);
                    return NULL;
                }
            }
        }
#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/
        *length = PyBytes_GET_SIZE(defenc);
        return defenc_c;
#else /* PY_VERSION_HEX < 0x03030000 */
        if (PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        if (PyUnicode_IS_ASCII(o)) {
            // cached for the lifetime of the object
            *length = PyUnicode_GET_DATA_SIZE(o);
            return PyUnicode_AsUTF8(o);
        } else {
            // raise the error
            PyUnicode_AsASCIIString(o);
            return NULL;
        }
#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
        return PyUnicode_AsUTF8AndSize(o, length);
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
#endif /* PY_VERSION_HEX < 0x03030000 */
    } else
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII  || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */

#if PY_VERSION_HEX >= 0x02060000
    if (PyByteArray_Check(o)) {
        *length = PyByteArray_GET_SIZE(o);
        return PyByteArray_AS_STRING(o);
    } else
#endif
    {
        char* result;
        int r = PyBytes_AsStringAndSize(o, &result, length);
        if (unlikely(r < 0)) {
            return NULL;
        } else {
            return result;
        }
    }
}
Ejemplo n.º 15
0
Archivo: type.c Proyecto: zillow/ctds
static int SqlDecimal_init(PyObject* self, PyObject* args, PyObject* kwargs)
{
    struct SqlDecimal* decimal = (struct SqlDecimal*)self;

    DBINT size;
    PyObject* value;
    Py_ssize_t precision = DECIMAL_DEFAULT_PRECISION;
    Py_ssize_t scale = DECIMAL_DEFAULT_SCALE;
    static char* s_kwlist[] =
    {
        "value",
        "precision",
        "scale",
        NULL
    };
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|nn", s_kwlist, &value, &precision, &scale))
    {
        return -1;
    }
    if (!((1 <= precision) && (precision <= DECIMAL_MAX_PRECISION)))
    {
        PyErr_Format(PyExc_ValueError, "invalid precision: %ld", precision);
        return -1;
    }
    if (!((0 <= scale) && (scale <= precision)))
    {
        PyErr_Format(PyExc_ValueError, "invalid scale: %ld", scale);
        return -1;
    }

    if (Py_None != value)
    {
        PyObject* ostr = PyObject_Str(value);
        if (ostr)
        {
            DBTYPEINFO dbtypeinfo;
            Py_ssize_t nutf8;
#if PY_MAJOR_VERSION < 3
            const char* str = PyString_AS_STRING(ostr);
            nutf8 = PyString_GET_SIZE(ostr);
#else /* if PY_MAJOR_VERSION < 3 */
            const char* str = PyUnicode_AsUTF8AndSize(ostr, &nutf8);
#endif /* else if PY_MAJOR_VERSION < 3 */

            dbtypeinfo.precision = (DBINT)precision;
            dbtypeinfo.scale = (DBINT)scale;

            size = dbconvert_ps(NULL,
                                TDSCHAR,
                                (BYTE*)str,
                                (DBINT)nutf8,
                                TDSDECIMAL,
                                (BYTE*)&decimal->dbdecimal,
                                sizeof(decimal->dbdecimal),
                                &dbtypeinfo);
            if (-1 == size)
            {
                PyErr_Format(PyExc_RuntimeError, "failed to convert '%s'", str);
            }
            Py_DECREF(ostr);
        }

        if (PyErr_Occurred())
        {
            return -1;
        }
    }
    else
    {
        decimal->dbdecimal.precision = (BYTE)precision;
        decimal->dbdecimal.scale = (BYTE)scale;
    }

    SqlType_init_fixed(self,
                       value,
                       TDSDECIMAL,
                       decimal->dbdecimal);

    return 0;
}
Ejemplo n.º 16
0
Archivo: type.c Proyecto: zillow/ctds
PyObject* encode_for_dblib(PyObject* unicode, const char** utf8bytes, size_t* nutf8bytes, size_t* width)
{
    PyObject* encoded = NULL;

    do
    {
#if PY_MAJOR_VERSION >= 3
        Py_ssize_t size;
#endif /* if PY_MAJOR_VERSION >= 3 */

        PyObject* encodable;

#if defined(CTDS_USE_UTF16)
        size_t ix;

        /* FreeTDS supports encoding to UTF-16, so the whole string is encodable. */
        encodable = unicode;
        Py_INCREF(encodable);
#else /* if defined(CTDS_USE_UTF16) */
        /*
            FreeTDS will only convert strings to UCS-2, so translate all
            strings to UCS-2 prior to binding.
        */
        encodable = translate_to_ucs2(unicode);
        if (!encodable)
        {
            break;
        }
        /*
            If the string was translated to UCS-2, the SQL NCHAR width is simply
            the string length.
        */
#  if PY_VERSION_HEX >= 0x03030000
        *width = (size_t)PyUnicode_GET_LENGTH(encodable);
#  else
        *width = (size_t)PyUnicode_GET_SIZE(encodable);
#  endif
#endif /* else if defined(CTDS_USE_UTF16) */

#if PY_MAJOR_VERSION < 3
        encoded = PyUnicode_AsUTF8String(encodable);
        Py_DECREF(encodable);
        if (!encoded)
        {
            break;
        }

        *utf8bytes = PyString_AS_STRING(encoded);
        *nutf8bytes = (size_t)PyString_GET_SIZE(encoded);
#else /* if PY_MAJOR_VERSION < 3 */
        encoded = encodable; /* steal reference */

        *utf8bytes = PyUnicode_AsUTF8AndSize(encoded, &size);
        *nutf8bytes = (size_t)size;
#endif /* else if PY_MAJOR_VERSION < 3 */

#if defined(CTDS_USE_UTF16)
        /*
            Compute the SQL type width, which is really the number of UTF-16
            sequences.
        */
#define IS_UTF8_SINGLE_BYTE(b)       (((b) & 0x80) == 0)
#define IS_UTF8_CONTINUATION_BYTE(b) (((b) & 0xC0) == 0x80)
#define IS_UTF8_FIRST_BYTE_OF_2(b)   (((b) & 0xE0) == 0xC0)
#define IS_UTF8_FIRST_BYTE_OF_3(b)   (((b) & 0xF0) == 0xE0)
#define IS_UTF8_FIRST_BYTE_OF_4(b)   (((b) & 0xF8) == 0xF0)

        *width = 0;
        for (ix = 0; ix < *nutf8bytes;)
        {
            if (IS_UTF8_SINGLE_BYTE((*utf8bytes)[ix]))
            {
                ++(*width);
                ix += 1;
            }
            else if (IS_UTF8_FIRST_BYTE_OF_2((*utf8bytes)[ix]))
            {
                ++(*width);
                ix += 2;
            }
            else if (IS_UTF8_FIRST_BYTE_OF_3((*utf8bytes)[ix]))
            {
                ++(*width);
                ix += 3;
            }
            else
            {
                /* Two-byte UTF-16 sequences require double the width. */
                assert(IS_UTF8_FIRST_BYTE_OF_4((*utf8bytes)[ix]));
                (*width) += 2;
                ix += 4;
            }
        }
#endif /* if defined(CTDS_USE_UTF16) */

    }
    while (0);

    return encoded;
}