//-----------------------------------------------------------------------------
// TimestampVar_SetValue()
//   Set the value of the variable.
//-----------------------------------------------------------------------------
static int TimestampVar_SetValue(
    udt_TimestampVar *var,              // variable to set value for
    unsigned pos,                       // array position to set
    PyObject *value)                    // value to set
{
    TIMESTAMP_STRUCT *sqlValue;

    sqlValue = &var->data[pos];
    sqlValue->fraction = 0;
    if (PyDateTime_Check(value)) {
        sqlValue->year = PyDateTime_GET_YEAR(value);
        sqlValue->month = PyDateTime_GET_MONTH(value);
        sqlValue->day = PyDateTime_GET_DAY(value);
        sqlValue->hour = PyDateTime_DATE_GET_HOUR(value);
        sqlValue->minute = PyDateTime_DATE_GET_MINUTE(value);
        sqlValue->second = PyDateTime_DATE_GET_SECOND(value);
    } else if (PyDate_Check(value)) {
        sqlValue->year = PyDateTime_GET_YEAR(value);
        sqlValue->month = PyDateTime_GET_MONTH(value);
        sqlValue->day = PyDateTime_GET_DAY(value);
        sqlValue->hour = 0;
        sqlValue->minute = 0;
        sqlValue->second = 0;
    } else {
        PyErr_SetString(PyExc_TypeError, "expecting date or datetime data");
        return -1;
    }

    return 0;
}
	static void construct(
	        PyObject *obj_ptr,
	        converter::rvalue_from_python_stage1_data *data )
	{
		assert( obj_ptr );
		assert( PyDateTime_Check( obj_ptr ) );

		PyDateTime_DateTime const* datetime = reinterpret_cast<PyDateTime_DateTime*>( obj_ptr );

		const posix_time::ptime t(
			gregorian::date(
				PyDateTime_GET_YEAR( datetime ),
				PyDateTime_GET_MONTH( datetime ),
				PyDateTime_GET_DAY( datetime )
			),
			posix_time::time_duration(
				PyDateTime_DATE_GET_HOUR( datetime ),
				PyDateTime_DATE_GET_MINUTE( datetime ),
				PyDateTime_DATE_GET_SECOND( datetime ),
				0
			) + posix_time::microseconds( PyDateTime_DATE_GET_MICROSECOND( datetime ) )
		);

		void* storage = (( converter::rvalue_from_python_storage<posix_time::ptime>* ) data )->storage.bytes;
		new( storage ) posix_time::ptime( t );
		data->convertible = storage;
	}
	static void *convertible( PyObject *obj_ptr )
	{
		if ( !PyDateTime_Check( obj_ptr ) )
		{
			return 0;
		}
		return obj_ptr;
	}
Exemple #4
0
static jsval to_javascript_object(JSContext *context, PyObject *value) {
    if (PyString_Check(value)) {
        JSString *obj = JS_NewStringCopyN(context, PyString_AsString(value), PyString_Size(value));
        return STRING_TO_JSVAL(obj);
    } else if (PyUnicode_Check(value)) {
        PyObject *encoded = PyUnicode_AsUTF8String(value);
        JSString *obj = JS_NewStringCopyN(context, PyString_AsString(encoded), PyString_Size(encoded));
        Py_DECREF(encoded);
        return STRING_TO_JSVAL(obj);
    } else if (PyFloat_Check(value)) {
        return DOUBLE_TO_JSVAL(PyFloat_AsDouble(value));
    } else if (PyInt_Check(value)) {
        return INT_TO_JSVAL(PyInt_AsLong(value));
    } else if (PyLong_Check(value)) {
        return INT_TO_JSVAL(PyLong_AsLong(value));
    } else if (PyList_Check(value)) {
        JSObject *obj = JS_NewArrayObject(context, 0, NULL);
        int i;
        for (i = 0; i < PyList_Size(value); i++) {
            jsval item = to_javascript_object(context, PyList_GetItem(value, i));
            JS_SetElement(context, obj, i, &item);
        }
        return OBJECT_TO_JSVAL(obj);
    } else if (PyTuple_Check(value)) {
        JSObject *obj = JS_NewArrayObject(context, 0, NULL);
        int i;
        for (i = 0; i < PyTuple_Size(value); i++) {
            jsval item = to_javascript_object(context, PyTuple_GetItem(value, i));
            JS_SetElement(context, obj, i, &item);
        }
        return OBJECT_TO_JSVAL(obj);
    } else if (PyDict_Check(value)) {
        JSObject *obj = JS_NewObject(context, NULL, NULL, NULL);
        populate_javascript_object(context, obj, value);
        return OBJECT_TO_JSVAL(obj);
    } else if (PyDateTime_Check(value)) {
        JSObject *obj = JS_NewDateObject(context,
            PyDateTime_GET_YEAR(value),
            PyDateTime_GET_MONTH(value) - 1,
            PyDateTime_GET_DAY(value),
            PyDateTime_DATE_GET_HOUR(value),
            PyDateTime_DATE_GET_MINUTE(value),
            PyDateTime_DATE_GET_SECOND(value));
        return OBJECT_TO_JSVAL(obj);
    } else {
        return JSVAL_NULL;
    }
}
Exemple #5
0
//-----------------------------------------------------------------------------
// Variable_TypeByValue()
//   Return a variable type given a Python object or NULL if the Python
// object does not have a corresponding variable type.
//-----------------------------------------------------------------------------
static udt_VariableType *Variable_TypeByValue(
    PyObject* value,                    // Python type
    SQLUINTEGER* size)                  // size to use (OUT)
{
    if (value == Py_None) {
        *size = 1;
        return &ceString_VariableType;
    }
    if (ceString_Check(value)) {
        *size = ceString_GetSize(value);
        return &ceString_VariableType;
    }
#if PY_MAJOR_VERSION < 3
    if (PyUnicode_Check(value)) {
        *size = PyUnicode_GET_SIZE(value);
        return &vt_Unicode;
    }
#endif
    if (ceBinary_Check(value)) {
        udt_StringBuffer temp;
        if (StringBuffer_FromBinary(&temp, value) < 0)
            return NULL;
        *size = temp.size;
        StringBuffer_Clear(&temp);
        return &vt_Binary;
    }
    if (PyBool_Check(value))
        return &vt_Bit;
    if (PyInt_Check(value))
        return &vt_Integer;
    if (PyLong_Check(value))
        return &vt_BigInteger;
    if (PyFloat_Check(value))
        return &vt_Double;
    if (Py_TYPE(value) == (PyTypeObject*) g_DecimalType)
        return &vt_Decimal;
    if (PyTime_Check(value))
        return &vt_Time;
    if (PyDateTime_Check(value))
        return &vt_Timestamp;
    if (PyDate_Check(value))
        return &vt_Timestamp;

    PyErr_Format(g_NotSupportedErrorException,
            "Variable_TypeByValue(): unhandled data type %s",
            Py_TYPE(value)->tp_name);
    return NULL;
}
Exemple #6
0
  bool Device::getTimevalFromDateTime(PyObject *py_time, struct timeval &tv_time) {
    if ((!py_time) || (!PyDateTime_Check(py_time))) {
      return false;
    }
    struct tm t;
    t.tm_year = PyDateTime_GET_YEAR(py_time) - 1900;
    t.tm_mon  = PyDateTime_GET_MONTH(py_time) - 1;
    t.tm_mday = PyDateTime_GET_DAY(py_time);
    t.tm_hour = PyDateTime_DATE_GET_HOUR(py_time);
    t.tm_min  = PyDateTime_DATE_GET_MINUTE(py_time);
    t.tm_sec  = PyDateTime_DATE_GET_SECOND(py_time);

    tv_time.tv_sec  = mktime(&t);
    tv_time.tv_usec = PyDateTime_DATE_GET_MICROSECOND(py_time);
    return true;
  }
//-----------------------------------------------------------------------------
// DateVar_SetValue()
//   Set the value of the variable.
//-----------------------------------------------------------------------------
static int DateVar_SetValue(
    udt_DateVar *var,                   // variable to set value for
    unsigned pos,                       // array position to set
    PyObject *value)                    // value to set
{
    DATE_STRUCT *sqlValue;

    sqlValue = &var->data[pos];
    if (PyDateTime_Check(value) || PyDate_Check(value)) {
        sqlValue->year = PyDateTime_GET_YEAR(value);
        sqlValue->month = PyDateTime_GET_MONTH(value);
        sqlValue->day = PyDateTime_GET_DAY(value);
    } else {
        PyErr_SetString(PyExc_TypeError, "expecting date or datetime data");
        return -1;
    }

    return 0;
}
Exemple #8
0
int fudgepyc_convertPythonToTime ( FudgeTime * target, PyObject * source )
{
    FudgeStatus status;
    int hour, minute, second, microsecond, offset = 0, result, hastz;
    PyObject * utcoffset;

    if ( ! ( PyTime_Check ( source ) || PyDateTime_Check ( source ) ) )
    {
        exception_raise_any ( PyExc_TypeError,
                              "Only datetime.time and datetime.datetime "
                              "types can be converted in to FudgeTime" );
        return -1;
    }

    if ( ! ( utcoffset = PyObject_CallMethod ( source, "utcoffset", "" ) ) )
        return -1;
    if ( ( hastz = ( utcoffset != Py_None ) ) )
        result = fudgepyc_convertUtcOffset ( &offset, utcoffset );
    else
        result = offset = 0;
    Py_DECREF( utcoffset );
    if ( result )
        return -1;

    if ( fudgepyc_convertAttrToInt ( &hour, source, "hour" ) ||
         fudgepyc_convertAttrToInt ( &minute, source, "minute" ) ||
         fudgepyc_convertAttrToInt ( &second, source, "second" ) ||
         fudgepyc_convertAttrToInt ( &microsecond, source, "microsecond" ) )
        return -1;

    if ( hastz )
        status = FudgeTime_initialiseWithTimezone ( target,
                                                    second + minute * 60 + hour * 3600,
                                                    microsecond * 1000,
                                                    FUDGE_DATETIME_PRECISION_MICROSECOND,
                                                    offset );
    else
        status = FudgeTime_initialise ( target,
                                        second + minute * 60 + hour * 3600,
                                        microsecond * 1000,
                                        FUDGE_DATETIME_PRECISION_MICROSECOND );
    return exception_raiseOnError ( status );
}
Exemple #9
0
int fudgepyc_convertPythonToDate ( FudgeDate * target, PyObject * source )
{
    FudgeStatus status;
    int year, month, day;

    if ( ! ( PyDate_Check ( source ) || PyDateTime_Check ( source ) ) )
    {
        exception_raise_any ( PyExc_TypeError,
                              "Only datetime.date and datetime.datetime "
                              "types can be converted in to FudgeDate" );
        return -1;
    }

    if ( fudgepyc_convertAttrToInt ( &year, source, "year" ) ||
         fudgepyc_convertAttrToInt ( &month, source, "month" ) ||
         fudgepyc_convertAttrToInt ( &day, source, "day" ) )
        return -1;

    status = FudgeDate_initialise ( target, year, month, day );
    return exception_raiseOnError ( status );
}
Exemple #10
0
//-----------------------------------------------------------------------------
// TimestampVar_SetValue()
//   Set the value of the variable.
//-----------------------------------------------------------------------------
static int TimestampVar_SetValue(
    udt_TimestampVar *var,              // variable to set value for
    unsigned pos,                       // array position to set
    PyObject *value)                    // value to set
{
    sword status;
    uword valid;

    // make sure a timestamp is being bound
    if (!PyDateTime_Check(value)) {
        PyErr_SetString(PyExc_TypeError, "expecting timestamp data");
        return -1;
    }

    // store a copy of the value
    status = OCIDateTimeConstruct(var->environment->handle,
            var->environment->errorHandle, var->data[pos],
            (sb2) PyDateTime_GET_YEAR(value),
            PyDateTime_GET_MONTH(value),
            PyDateTime_GET_DAY(value),
            PyDateTime_DATE_GET_HOUR(value),
            PyDateTime_DATE_GET_MINUTE(value),
            PyDateTime_DATE_GET_SECOND(value),
            PyDateTime_DATE_GET_MICROSECOND(value) * 1000, NULL, 0);
    if (Environment_CheckForError(var->environment, status,
            "TimestampVar_SetValue(): create structure") < 0)
        return -1;
    status = OCIDateTimeCheck(var->environment->handle,
            var->environment->errorHandle, var->data[pos], &valid);
    if (Environment_CheckForError(var->environment, status,
            "TimestampVar_SetValue()") < 0)
        return -1;
    if (valid != 0) {
        PyErr_SetString(g_DataErrorException, "invalid date");
        return -1;
    }

    return 0;
}
Exemple #11
0
//-----------------------------------------------------------------------------
// TimeVar_SetValue()
//   Set the value of the variable.
//-----------------------------------------------------------------------------
static int TimeVar_SetValue(
    udt_TimeVar *var,              // variable to set value for
    unsigned pos,                       // array position to set
    PyObject *value)                    // value to set
{
    TIME_STRUCT *sqlValue;

    sqlValue = &var->data[pos];
    if (PyDateTime_Check(value)) {
        sqlValue->hour = PyDateTime_DATE_GET_HOUR(value);
        sqlValue->minute = PyDateTime_DATE_GET_MINUTE(value);
        sqlValue->second = PyDateTime_DATE_GET_SECOND(value);
    } else if (PyTime_Check(value)) {
        sqlValue->hour = PyDateTime_TIME_GET_HOUR(value);
        sqlValue->minute = PyDateTime_TIME_GET_MINUTE(value);
        sqlValue->second = PyDateTime_TIME_GET_SECOND(value);
    } else {
        PyErr_SetString(PyExc_TypeError, "expecting datetime or time data");
        return -1;
    }

    return 0;
}
/**
  Convert a Python datetime.datetime to MySQL DATETIME.

  Convert the PyObject obj, which must be a datetime.datetime,
  to MySQL DATETIME value.

  Raises TypeError when obj is not a PyDateTime_Type.

  @param    obj     the PyObject to be converted

  @return   Converted datetime object.
    @retval PyBytes     Python v3
    @retval PyString    Python v2
    @retval NULL        Exception
*/
PyObject*
pytomy_datetime(PyObject *obj)
{
    char result[27]= "";
    PyDateTime_IMPORT;

    if (!obj || !PyDateTime_Check(obj))
    {
        PyErr_SetString(PyExc_ValueError,
                        "Object must be a datetime.datetime");
        return NULL;
    }

    if (PyDateTime_DATE_GET_MICROSECOND(obj))
    {
        PyOS_snprintf(result, 27, "%04d-%02d-%02d %02d:%02d:%02d.%06d",
                 PyDateTime_GET_YEAR(obj),
                 PyDateTime_GET_MONTH(obj),
                 PyDateTime_GET_DAY(obj),
                 PyDateTime_DATE_GET_HOUR(obj),
                 PyDateTime_DATE_GET_MINUTE(obj),
                 PyDateTime_DATE_GET_SECOND(obj),
                 PyDateTime_DATE_GET_MICROSECOND(obj));
    }
    else
    {
        PyOS_snprintf(result, 27, "%04d-%02d-%02d %02d:%02d:%02d",
                 PyDateTime_GET_YEAR(obj),
                 PyDateTime_GET_MONTH(obj),
                 PyDateTime_GET_DAY(obj),
                 PyDateTime_DATE_GET_HOUR(obj),
                 PyDateTime_DATE_GET_MINUTE(obj),
                 PyDateTime_DATE_GET_SECOND(obj));
    }

    return PyBytesFromString(result);
}
Exemple #13
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj, *exc, *toDictFunc;
  TypeContext *pc;
  PRINTMARK();
  if (!_obj) {
    tc->type = JT_INVALID;
    return;
  }

  obj = (PyObject*) _obj;

  tc->prv = PyObject_Malloc(sizeof(TypeContext));
  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->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))
    {
#if HAS_JSON_HANDLE_BIGINTS
      PyErr_Clear();
      pc->PyTypeToJSON = PyBigIntToSTR;
      tc->type = JT_BIGINT;
      GET_TC(tc)->longValue = 0;
      return;
#endif
      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;
    pc->iterBegin = Dict_iterBegin;
    pc->iterEnd = Dict_iterEnd;
    pc->iterNext = Dict_iterNext;
    pc->iterGetValue = Dict_iterGetValue;
    pc->iterGetName = Dict_iterGetName;
    pc->dictObj = obj;
    Py_INCREF(obj);
    return;
  }
  else
  if (PyList_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = List_iterBegin;
    pc->iterEnd = List_iterEnd;
    pc->iterNext = List_iterNext;
    pc->iterGetValue = List_iterGetValue;
    pc->iterGetName = List_iterGetName;
    return;
  }
  else
  if (PyTuple_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = Tuple_iterBegin;
    pc->iterEnd = Tuple_iterEnd;
    pc->iterNext = Tuple_iterNext;
    pc->iterGetValue = Tuple_iterGetValue;
    pc->iterGetName = Tuple_iterGetName;
    return;
  }
  else
  if (PyAnySet_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = Iter_iterBegin;
    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;
    pc->iterBegin = Dict_iterBegin;
    pc->iterEnd = Dict_iterEnd;
    pc->iterNext = Dict_iterNext;
    pc->iterGetValue = Dict_iterGetValue;
    pc->iterGetName = Dict_iterGetName;
    pc->dictObj = toDictResult;
    return;
  }

  PyErr_Clear();

  PRINTMARK();
  // Falling to INVALID case as this type of object(class instance, module,
  // class, function, etc..) can't be serialized.
  PyErr_Format (PyExc_TypeError, "%s", "Object is not JSON serializable");

INVALID:
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
Exemple #14
0
dbtype_t
from_python(pgctx_t *ctx, PyObject *ob)
{
    dbtype_t db;
    char *buf;
    Py_ssize_t length;
    PyObject *items;
    struct tm tm;
    long usec;
    //int i;
    
    if (PyObject_HasAttrString(ob, "__topongo__")) {
        ob = PyObject_CallMethod(ob, "__topongo__", NULL);
        if (PyErr_Occurred())
            return DBNULL;
    }
    if (ob == Py_None) {
        db = DBNULL;
    } else if (ob == pongo_id) {
        db = dbuuid_new(ctx, NULL);
    } else if (ob == pongo_utcnow) {
        db = dbtime_now(ctx);
    } else if (PyBool_Check(ob)) {
        db = dbboolean_new(ctx, ob == Py_True);
    } else if (PyInt_Check(ob)) {
        db = dbint_new(ctx, PyInt_AsLong(ob));
    } else if (PyLong_Check(ob)) {
        db = dbint_new(ctx, PyLong_AsLongLong(ob));
    } else if (PyFloat_Check(ob)) {
        db = dbfloat_new(ctx, PyFloat_AsDouble(ob));
    } else if (PyString_Check(ob)) {
        PyString_AsStringAndSize(ob, &buf, &length);
        // FIXME:
        //db = dbbuffer_new(ctx, buf, length);
        db = dbstring_new(ctx, buf, length);
    } else if (PyUnicode_Check(ob)) {
        ob = PyUnicode_AsUTF8String(ob);
        if (ob) {
            PyString_AsStringAndSize(ob, &buf, &length);
            db = dbstring_new(ctx, buf, length);
            Py_DECREF(ob);
        }
    } else if (PyDateTime_Check(ob)) {
        memset(&tm, 0, sizeof(tm));
        tm.tm_year = PyDateTime_GET_YEAR(ob);
        tm.tm_mon = PyDateTime_GET_MONTH(ob);
        tm.tm_mday = PyDateTime_GET_DAY(ob);
        tm.tm_hour = PyDateTime_DATE_GET_HOUR(ob);
        tm.tm_min = PyDateTime_DATE_GET_MINUTE(ob);
        tm.tm_sec = PyDateTime_DATE_GET_SECOND(ob);
        usec = PyDateTime_DATE_GET_MICROSECOND(ob);
        tm.tm_year -= 1900;
        db = dbtime_newtm(ctx, &tm, usec);
#ifdef WANT_UUID_TYPE
    } else if (PyObject_TypeCheck(ob, uuid_class)) {
        ob = PyObject_CallMethod(ob, "get_bytes", NULL);
        PyString_AsStringAndSize(ob, &buf, &length);
        db = dbuuid_new(ctx, (uint8_t*)buf);
#endif
    } else if (Py_TYPE(ob) == &PongoList_Type) {
        // Resolve proxy types back to their original dbtype
        PongoList *p = (PongoList*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoDict_Type) {
        // Resolve proxy types back to their original dbtype
        PongoDict *p = (PongoDict*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoCollection_Type) {
        // Resolve proxy types back to their original dbtype
        PongoCollection *p = (PongoCollection*)ob;
        db = p->dbptr;
    } else if (PyMapping_Check(ob)) {
        length = PyMapping_Length(ob);
        items = PyMapping_Items(ob);
        if (items) {
            // mapping object implements "items"
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_mapping_cb, items, NOSYNC);
            Py_XDECREF(items);
        } else {
            // mapping object implements iterator protocol
            // don't have to decref the iterator object cuz it self-decrefs
            // upon StopIteration
            PyErr_Clear();
            items = PyObject_GetIter(ob);
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_itermapping_cb, items, NOSYNC);
        }
    } else if (PySequence_Check(ob)) {
        length = PySequence_Length(ob);
        db = dblist_new(ctx);
        dblist_extend(ctx, db, length, _py_sequence_cb, ob, NOSYNC);
    } else {
        // FIXME: Unknown object type
        PyErr_SetObject(PyExc_TypeError, (PyObject*)Py_TYPE(ob));
        db = DBNULL;
    }
    return db;
}
Exemple #15
0
void Object_beginTypeContext (PyObject *obj, JSONTypeContext *tc)
{
	TypeContext *pc = (TypeContext *) tc->prv;
	PyObject *toDictFunc;

	tc->prv[0] = 0;
	tc->prv[1] = 0;
	tc->prv[2] = 0;
	tc->prv[3] = 0;
	tc->prv[4] = 0;
	tc->prv[5] = 0;
	tc->prv[6] = 0;
	tc->prv[7] = 0;
	tc->prv[8] = 0;
	tc->prv[9] = 0;
	tc->prv[10] = 0;
	tc->prv[11] = 0;
	tc->prv[12] = 0;
	tc->prv[13] = 0;
	tc->prv[14] = 0;
	
	if (PyIter_Check(obj))
	{
		goto ISITERABLE;
	}

	if (PyBool_Check(obj))
	{
		PRINTMARK();
		tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
		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 (PyLong_Check(obj))
	{
		PyObject *exc;

		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();
			tc->type = JT_INVALID;
			return;
		}

		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))
	{
		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;
		pc->iterBegin = Dict_iterBegin;
		pc->iterEnd = Dict_iterEnd;
		pc->iterNext = Dict_iterNext;
		pc->iterGetValue = Dict_iterGetValue;
		pc->iterGetName = Dict_iterGetName;
		pc->dictObj = obj;
		Py_INCREF(obj);

		return;
	}
	else
	if (PyList_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_ARRAY;
		pc->iterBegin = List_iterBegin;
		pc->iterEnd = List_iterEnd;
		pc->iterNext = List_iterNext;
		pc->iterGetValue = List_iterGetValue;
		pc->iterGetName = List_iterGetName;
		return;
	}
	else
	if (PyTuple_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_ARRAY;
		pc->iterBegin = Tuple_iterBegin;
		pc->iterEnd = Tuple_iterEnd;
		pc->iterNext = Tuple_iterNext;
		pc->iterGetValue = Tuple_iterGetValue;
		pc->iterGetName = Tuple_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;
		pc->iterBegin = Dict_iterBegin;
		pc->iterEnd = Dict_iterEnd;
		pc->iterNext = Dict_iterNext;
		pc->iterGetValue = Dict_iterGetValue;
		pc->iterGetName = Dict_iterGetName;
		pc->dictObj = toDictResult;
		return;
	}

	PyErr_Clear();

	tc->type = JT_OBJECT;
	pc->iterBegin = Dir_iterBegin;
	pc->iterEnd = Dir_iterEnd;
	pc->iterNext = Dir_iterNext;
	pc->iterGetValue = Dir_iterGetValue;
	pc->iterGetName = Dir_iterGetName;

	return;
}
static bool GetParameterInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
    // Determines the type of SQL parameter that will be used for this parameter based on the Python data type.
    //
    // Populates `info`.

    // TODO: if the param is a SQLParameter object, then bind to the wrapped value and use the input/output type from that

    // Hold a reference to param until info is freed, because info will often be holding data borrowed from param.
    if (PyObject_TypeCheck(param, (PyTypeObject*)SQLParameter_type))
    {
        info.pParam = ((SQLParameter*)param)->value;
        info.InputOutputType = ((SQLParameter*)param)->type;
    }
    else
    {
        info.pParam = param;
        info.InputOutputType = SQL_PARAM_INPUT;
    }

    if (info.pParam == Py_None)
        return GetNullInfo(cur, index, info);

    if (info.pParam == null_binary)
        return GetNullBinaryInfo(cur, index, info);

    if (PyBytes_Check(info.pParam))
        return GetBytesInfo(cur, index, info.pParam, info);

    if (PyUnicode_Check(info.pParam))
        return GetUnicodeInfo(cur, index, info.pParam, info);

    if (PyBool_Check(info.pParam))
        return GetBooleanInfo(cur, index, info.pParam, info);

    if (PyDateTime_Check(info.pParam))
        return GetDateTimeInfo(cur, index, info.pParam, info);

    if (PyDate_Check(info.pParam))
        return GetDateInfo(cur, index, info.pParam, info);

    if (PyTime_Check(info.pParam))
        return GetTimeInfo(cur, index, info.pParam, info);

    if (PyLong_Check(info.pParam))
        return GetLongInfo(cur, index, info.pParam, info);

    if (PyFloat_Check(info.pParam))
        return GetFloatInfo(cur, index, info.pParam, info);

    if (PyDecimal_Check(info.pParam))
        return GetDecimalInfo(cur, index, info.pParam, info);

#if PY_VERSION_HEX >= 0x02060000
    if (PyByteArray_Check(info.pParam))
        return GetByteArrayInfo(cur, index, info.pParam, info);
#endif

#if PY_MAJOR_VERSION < 3
    if (PyInt_Check(info.pParam))
        return GetIntInfo(cur, index, info.pParam, info);

    if (PyBuffer_Check(info.pParam))
        return GetBufferInfo(cur, index, info.pParam, info);
#endif

    RaiseErrorV("HY105", ProgrammingError, "Invalid parameter type.  param-index=%zd param-type=%s", index, Py_TYPE(info.pParam)->tp_name);
    return false;
}
Exemple #17
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;
}
Exemple #18
0
int AppendEscapedArg (Connection *self, char *start, char *end, PyObject *obj)
{
  int ret;
  PyObject *strobj;

  /*
  FIXME: Surround strings with '' could be performed in this function to avoid extra logic in AppendAndEscapeString */
  PRINTMARK();

  if (PyString_Check(obj))
  {
    PRINTMARK();
    return AppendAndEscapeString(start, end, PyString_AS_STRING(obj), PyString_AS_STRING(obj) + PyString_GET_SIZE(obj), TRUE);
  }
  else
    if (PyUnicode_Check(obj))
    {
      PRINTMARK();
      strobj = self->PFN_PyUnicode_Encode(PyUnicode_AS_UNICODE(obj), PyUnicode_GET_SIZE(obj), NULL);

      if (strobj == NULL)
      {
        if (PyErr_Occurred())
        {
          return -1;
        }

        PyErr_SetObject (PyExc_ValueError, obj);
        return -1;
      }


      ret = AppendAndEscapeString(start, end, PyString_AS_STRING(strobj), PyString_AS_STRING(strobj) + PyString_GET_SIZE(strobj), TRUE);
      Py_DECREF(strobj);

      return ret;
    }
    else
      if (obj == Py_None)
      {
        (*start++) = 'n';
        (*start++) = 'u';
        (*start++) = 'l';
        (*start++) = 'l';
        return  4;
      }
      else
        if (PyDateTime_Check(obj))
        {
          int len = sprintf (start, "'%04d-%02d-%02d %02d:%02d:%02d'", 
            PyDateTime_GET_YEAR(obj),
            PyDateTime_GET_MONTH(obj),
            PyDateTime_GET_DAY(obj),
            PyDateTime_DATE_GET_HOUR(obj),
            PyDateTime_DATE_GET_MINUTE(obj),
            PyDateTime_DATE_GET_SECOND(obj));

          return len;
        }
        else
          if (PyDate_Check(obj))
          {
            int len = sprintf (start, "'%04d:%02d:%02d'", 
              PyDateTime_GET_YEAR(obj),
              PyDateTime_GET_MONTH(obj),
              PyDateTime_GET_DAY(obj));

            return len;
          }

          //FIXME: Might possible to avoid this?
          PRINTMARK();
          strobj = PyObject_Str(obj);
          ret = AppendAndEscapeString(start, end, PyString_AS_STRING(strobj), PyString_AS_STRING(strobj) + PyString_GET_SIZE(strobj), FALSE);
          Py_DECREF(strobj);
          return ret;
}
static PyObject *
CalcVector(PyRPosObject *self, PyObject *args, PyObject *kwds)
{
  PyObject *location=NULL,*list=NULL, *timetuple=NULL;
  double lat=0,lon=0,mag, azm;
  double clat, clon;
  char *radarcode;
  int stid;
  struct RadarNetwork *network;
  struct Radar *radar;
  struct RadarSite *site;
  static char *kwlist[] = {"mag","azm","location","radarcode","radarid",NULL};
  char *envstr=NULL;
  FILE *fp;
  int yr,mo,dy,hr,mt;
  double sc;
  yr=2008;
  mo=7;
  dy=12;
  hr=12;
  mt=0;
  sc=0; 

  radarcode="kod";
  stid=-1;

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "dd|Osi", kwlist, 
                                      &mag,&azm,&location,&radarcode,&stid))
     return NULL; 

  if ( timetuple != NULL) {
    if (PyDateTime_Check(timetuple)) {	
      yr=PyDateTime_GET_YEAR(timetuple);   
      mo=PyDateTime_GET_MONTH(timetuple);  
      dy=PyDateTime_GET_DAY(timetuple);   
      hr=PyDateTime_DATE_GET_HOUR(timetuple);   
      mt=PyDateTime_DATE_GET_MINUTE(timetuple);   
      sc=PyDateTime_DATE_GET_SECOND(timetuple);   
    }
  } 

  if ( location != NULL) {
    if (PyTuple_Check(location) && PyTuple_Size(location)==2) {	
      lat=PyFloat_AS_DOUBLE(PyTuple_GetItem(location,0));
      lon=PyFloat_AS_DOUBLE(PyTuple_GetItem(location,1));
    }
  } else {
    envstr=getenv("SD_RADAR");
    if (envstr==NULL) {
      fprintf(stderr,"Environment variable 'SD_RADAR' must be defined.\n");
      exit(-1);
    }

    fp=fopen(envstr,"r");

    if (fp==NULL) {
      fprintf(stderr,"Could not locate radar information file.\n");
      exit(-1);
    }

    network=RadarLoad(fp);
    fclose(fp); 

    if (network==NULL) {
      fprintf(stderr,"Failed to read radar information.\n");
      exit(-1);
    }

    envstr=getenv("SD_HDWPATH");
    if (envstr==NULL) {
      fprintf(stderr,"Environment variable 'SD_HDWPATH' must be defined.\n");
      exit(-1);
    }

    RadarLoadHardware(envstr,network);

    if (stid==-1) {
      stid=RadarGetID(network,radarcode);
    } 
    radar=RadarGetRadar(network,stid);
    site=RadarYMDHMSGetSite(radar,yr,mo,dy,hr,mt,(int) sc);
    lat=site->geolat;
    lon=site->geolon;
  }
  RPosCalcVector(lat,lon,mag,azm,&clat,&clon);
  list = PyList_New(0);
  PyList_Append(list,Py_BuildValue("d",clat));
  PyList_Append(list,Py_BuildValue("d",clon));

  return list;  

}
Exemple #20
0
static PyObject *
cbson_dumps (PyObject *self,
             PyObject *args)
{
   const char *keystr;
   PyObject *doc;
   PyObject *key;
   PyObject *ret;
   PyObject *value;
   Py_ssize_t pos = 0;
   bson_t *b;
   size_t keylen;

   if (!PyArg_ParseTuple(args, "O", &doc)) {
      return NULL;
   }

   if (!PyDict_Check(doc)) {
      PyErr_SetString(PyExc_TypeError, "doc must be a dict.");
      return NULL;
   }

   b = bson_new();

   while (PyDict_Next(doc, &pos, &key, &value)) {
      /*
       * TODO: Key validation. Make sure no NULL is present. Ensure valid UTF-8.
       */

      if (PyString_Check(key)) {
         keystr = PyString_AS_STRING(key);
         keylen = PyString_GET_SIZE(key);
      } else if (PyUnicode_Check(key)) {
         /*
          * TODO: Convert to UTF-8.
          */
         keystr = (const char *)PyUnicode_AS_UNICODE(key);
         keylen = PyUnicode_GET_SIZE(key);
      } else {
         PyErr_SetString(PyExc_TypeError, "key must be a string.");
         bson_destroy(b);
         return NULL;
      }

      if (value == Py_None) {
         if (!bson_append_null(b, keystr, keylen)) {
            goto failure;
         }
      } else if (PyString_Check(value)) {
         /*
          * TODO: Validate UTF-8.
          */
         if (!bson_append_utf8(b, keystr, keylen,
                               PyString_AS_STRING(value),
                               PyString_GET_SIZE(value))) {
            goto failure;
         }
      } else if (PyUnicode_Check(value)) {
         /*
          * TODO: Convert and validate UTF-8.
          */
         if (!bson_append_utf8(b, keystr, keylen,
                               (const char *)PyUnicode_AS_UNICODE(value),
                               PyUnicode_GET_SIZE(value))) {
            goto failure;
         }
      } else if (PyDateTime_Check(value)) {
         /*
          * TODO: Convert to msec since epoch.
          */
      } else if (PyBool_Check(value)) {
         if (!bson_append_bool(b, keystr, keylen, (value == Py_True))) {
            goto failure;
         }
      } else if (PyLong_Check(value)) {
         if (!bson_append_int64(b, keystr, keylen, PyLong_AsLong(value))) {
            goto failure;
         }
      } else if (PyInt_Check(value)) {
         if (!bson_append_int32(b, keystr, keylen, PyInt_AsLong(value))) {
            goto failure;
         }
      } else if (PyFloat_Check(value)) {
         if (!bson_append_double(b, keystr, keylen, PyFloat_AsDouble(value))) {
            goto failure;
         }
      } else if (cbson_oid_check(value)) {
         if (!bson_append_oid(b, keystr, keylen, &((cbson_oid_t *)value)->oid)) {
            goto failure;
         }
      /* } else if (CHECK FOR REGEX) { */
      /* } else if (CHECK FOR BINARY) { */
      } else {
         goto failure;
      }
   }

   ret = PyString_FromStringAndSize((const char *)bson_get_data(b), b->len);
   bson_destroy(b);

   return ret;

failure:
   PyErr_SetString(PyExc_TypeError, "Cannot encode type.");
   bson_destroy(b);
   return NULL;
}
static PyObject *
PosMag(PyRPosObject *self, PyObject *args, PyObject *kwds)
{
  PyObject *list=NULL, *timetuple=NULL;
  char *radarcode;
  struct RadarNetwork *network;
  struct Radar *radar;
  struct RadarSite *site;
  int center, bcrd, rcrd;
  int frang,rsep,rxrise,height;
  int yr,mo,dy,hr,mt;
  double sc;
  int stid;
  double rho,lat,lng;
  char *envstr=NULL;
  FILE *fp;
  int r,c;
  static char *kwlist[] = {"center","bcrd","rcrd","frang","rsep","rxrise","height", "radarcode","radarid","time",NULL};
  PyDateTime_IMPORT;
  center=0;
  bcrd=1;
  rcrd=15;
  frang=1200;
  rxrise=0;
  rsep=100;
  height=300;
  radarcode="kod";
  stid=-1;
  yr=2008;
  mo=7;
  dy=12;
  hr=12;
  mt=0;
  sc=0; 

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "|iiiiiiisiO", kwlist, 
                                      &center,&bcrd,&rcrd,&frang,&rsep,&rxrise,&height,&radarcode,&stid,&timetuple))
     return NULL; 

  if ( timetuple != NULL) {
    if (PyDateTime_Check(timetuple)) {	
      yr=PyDateTime_GET_YEAR(timetuple);   
      mo=PyDateTime_GET_MONTH(timetuple);  
      dy=PyDateTime_GET_DAY(timetuple);   
      hr=PyDateTime_DATE_GET_HOUR(timetuple);   
      mt=PyDateTime_DATE_GET_MINUTE(timetuple);   
      sc=PyDateTime_DATE_GET_SECOND(timetuple);   
    }
  }
  envstr=getenv("SD_RADAR");
  if (envstr==NULL) {
    fprintf(stderr,"Environment variable 'SD_RADAR' must be defined.\n");
    exit(-1);
  }

  fp=fopen(envstr,"r");

  if (fp==NULL) {
    fprintf(stderr,"Could not locate radar information file.\n");
    exit(-1);
  }

  network=RadarLoad(fp);
  fclose(fp); 

  if (network==NULL) {
    fprintf(stderr,"Failed to read radar information.\n");
    exit(-1);
  }

  envstr=getenv("SD_HDWPATH");
  if (envstr==NULL) {
    fprintf(stderr,"Environment variable 'SD_HDWPATH' must be defined.\n");
    exit(-1);
  }

  RadarLoadHardware(envstr,network);


  if (stid==-1) {
    stid=RadarGetID(network,radarcode);
  }
  radar=RadarGetRadar(network,stid);
  site=RadarYMDHMSGetSite(radar,yr,mo,dy,hr,mt,(int) sc);
  RPosMag(center,bcrd,rcrd,site,frang,rsep,rxrise,height,&rho,&lat,&lng);
  radar=NULL;
  site=NULL;
  for (r=0;r<network->rnum;r++) {
    for (c=0;c<network->radar[r].cnum;c++) { 
      if (network->radar[r].code[c] !=NULL) free(network->radar[r].code[c]);
    } 
    if (network->radar[r].code !=NULL) free(network->radar[r].code);
    if (network->radar[r].name !=NULL) free(network->radar[r].name);
    if (network->radar[r].operator !=NULL) free(network->radar[r].operator);
    if (network->radar[r].hdwfname !=NULL) free(network->radar[r].hdwfname);
    if (network->radar[r].site !=NULL) free(network->radar[r].site);
  }
  free(network->radar);
  free(network);
  list = PyList_New(0);
  PyList_Append(list,Py_BuildValue("d",rho));
  PyList_Append(list,Py_BuildValue("d",lat));
  PyList_Append(list,Py_BuildValue("d",lng));
  return list;  
}