text:
/* Wrappers around C++ functions so they can be called from python The
   C code starts one or more non-Python threads which work out which
   points to calculate, and call the dynamically-compiled pointfunc C
   code created by the compiler for each pixel.

   Results are reported back through a site object. There are 2 kinds,
   a synchronous site which calls back into python (used by
   command-line fractal.py script) and an async site which wraps a
   file descriptor into which we write simple messages. The GTK+ main
   loop then listens to the FD and performs operations in response to
   messages written to the file descriptor.
*/

#include "Python.h"

#include <dlfcn.h>
#include <pthread.h>

#include "assert.h"

#include <new>

#include "fract_stdlib.h"
#include "pf.h"
#include "cmap.h"
#include "fractFunc.h"
#include "image.h"

/* not sure why this isn't defined already */
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif

#define CMAP_NAME "/fract4d_stdlib.so"

#ifdef USE_GMP
#define MODULE_NAME "fract4dcgmp"
#include "gmp.h"
#else
#define MODULE_NAME "fract4dc"
#endif

/*
 * pointfuncs
 */

PyObject *pymod=NULL;
void *cmap_module_handle=NULL;

typedef enum {
    DELTA_X,
    DELTA_Y,
    TOPLEFT
} vec_type_t;

static void
pf_unload(void *p)
{
#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : SO : DEREF\n",p);
#endif
    #ifndef STATIC_CALC
    dlclose(p);
    #endif
}

static int
ensure_cmap_loaded()
{
    char cwd[PATH_MAX+1];
    // load the cmap module so fract funcs we compile later
    // can call its methods
    if(NULL != cmap_module_handle)
    {
	return 1; // already loaded
    }

    char *filename = PyModule_GetFilename(pymod);
    //fprintf(stderr,"base name: %s\n",filename);
    char *path_end = strrchr(filename,'/');
    if(path_end == NULL)
    {
	filename = getcwd(cwd,sizeof(cwd));
	path_end = filename + strlen(filename);
    }

    int path_len = strlen(filename) - strlen(path_end);
    int len = path_len + strlen(CMAP_NAME);

    char *new_filename = (char *)malloc(len+1);
    strncpy(new_filename, filename, path_len);
    new_filename[path_len] = '\0';
    strcat(new_filename, CMAP_NAME);
    //fprintf(stderr,"Filename: %s\n", new_filename);

    cmap_module_handle = dlopen(new_filename, RTLD_GLOBAL | RTLD_NOW);
    if(NULL == cmap_module_handle)
    {
	/* an error */
	PyErr_SetString(PyExc_ValueError, dlerror());
	return 0;
    }
    return 1;
}

static PyObject *
pf_load(PyObject *self, PyObject *args)
{
    #ifdef STATIC_CALC
    Py_INCREF(Py_None);
    return Py_None;
    #else
    if(!ensure_cmap_loaded())
    {
	return NULL;
    }

    char *so_filename;
    if(!PyArg_ParseTuple(args,"s",&so_filename))
    {
	return NULL;
    }

    void *dlHandle = dlopen(so_filename, RTLD_NOW);
#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : SO : REF\n",dlHandle);
#endif
    if(NULL == dlHandle)
    {
	/* an error */
	PyErr_SetString(PyExc_ValueError,dlerror());
	return NULL;
    }
    return PyCObject_FromVoidPtr(dlHandle,pf_unload);
    #endif
}

struct pfHandle
{
    PyObject *pyhandle;
    pf_obj *pfo;
} ;

static void
pf_delete(void *p)
{
    struct pfHandle *pfh = (struct pfHandle *)p;
#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : PF : DTOR\n",pfh);
#endif
    pfh->pfo->vtbl->kill(pfh->pfo);
    Py_DECREF(pfh->pyhandle);
    free(pfh);
}

static PyObject *
pf_create(PyObject *self, PyObject *args)
{
    struct pfHandle *pfh = (pfHandle *)malloc(sizeof(struct pfHandle));
    void *dlHandle;
    pf_obj *(*pfn)(void);

    PyObject *pyobj;
#ifdef STATIC_CALC
    pf_obj *p = pf_new();
    pyobj = Py_None;
#else

    if(!PyArg_ParseTuple(args,"O",&pyobj))
    {
	return NULL;
    }
    if(!PyCObject_Check(pyobj))
    {
	PyErr_SetString(PyExc_ValueError,"Not a valid handle");
	return NULL;
    }

    dlHandle = PyCObject_AsVoidPtr(pyobj);
    pfn = (pf_obj *(*)(void))dlsym(dlHandle,"pf_new");
    if(NULL == pfn)
    {
	PyErr_SetString(PyExc_ValueError,dlerror());
	return NULL;
    }
    pf_obj *p = pfn();
#endif
    pfh->pfo = p;
    pfh->pyhandle = pyobj;
#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : PF : CTOR (%p)\n",pfh,pfh->pfo);
#endif
    // refcount module so it can't be unloaded before all funcs are gone
    Py_INCREF(pyobj);
    return PyCObject_FromVoidPtr(pfh,pf_delete);
}

void *
get_double_field(PyObject *pyitem, const char *name, double *pVal)
{
    PyObject *pyfield = PyObject_GetAttrString(pyitem,name);
    if(pyfield == NULL)
    {
	PyErr_SetString(PyExc_ValueError, "Bad segment object");
	return NULL;
    }
    *pVal = PyFloat_AsDouble(pyfield);
    Py_DECREF(pyfield);

    return pVal;
}

/* member 'name' of pyitem is a N-element list of doubles */
void *
get_double_array(PyObject *pyitem, const char *name, double *pVal, int n)
{
    PyObject *pyfield = PyObject_GetAttrString(pyitem,name);
    if(pyfield == NULL)
    {
	PyErr_SetString(PyExc_ValueError, "Bad segment object");
	return NULL;
    }

    if(!PySequence_Check(pyfield))
    {
	PyErr_SetString(PyExc_ValueError, "Bad segment object");
	Py_DECREF(pyfield);
	return NULL;
    }

    if(!(PySequence_Size(pyfield) == n))
    {
	PyErr_SetString(PyExc_ValueError, "Bad segment object");
	Py_DECREF(pyfield);
	return NULL;
    }

    for(int i = 0; i < n; ++i)
    {
	PyObject *py_subitem = PySequence_GetItem(pyfield,i);
	if(!py_subitem)
	{
	    PyErr_SetString(PyExc_ValueError, "Bad segment object");
	    Py_DECREF(pyfield);
	    return NULL;
	}
	*(pVal+i)=PyFloat_AsDouble(py_subitem);

	Py_DECREF(py_subitem);
    }

    Py_DECREF(pyfield);

    return pVal;
}

void *
get_int_field(PyObject *pyitem, const char *name, int *pVal)
{
    PyObject *pyfield = PyObject_GetAttrString(pyitem,name);
    if(pyfield == NULL)
    {
	PyErr_SetString(PyExc_ValueError, "Bad segment object");
	return NULL;
    }
    *pVal = PyInt_AsLong(pyfield);
    Py_DECREF(pyfield);

    return pVal;
}

static ColorMap *
cmap_from_pyobject(PyObject *pyarray)
{
    int len, i;
    GradientColorMap *cmap;

    len = PySequence_Size(pyarray);
    if(len == 0)
    {
	PyErr_SetString(PyExc_ValueError,"Empty color array");
	return NULL;
    }

    cmap = new(std::nothrow)GradientColorMap();

    if(!cmap)
    {
	PyErr_SetString(PyExc_MemoryError,"Can't allocate colormap");
	return NULL;
    }
    if(! cmap->init(len))
    {
	PyErr_SetString(PyExc_MemoryError,"Can't allocate colormap array");
	delete cmap;
	return NULL;
    }

    for(i = 0; i < len; ++i)
    {
	double left, right, mid, left_col[4], right_col[4];
	int bmode, cmode;
	PyObject *pyitem = PySequence_GetItem(pyarray,i);
	if(!pyitem)
	{
	    delete cmap;
	    return NULL;
	}

	if(!get_double_field(pyitem, "left", &left) ||
	   !get_double_field(pyitem, "right", &right) ||
	   !get_double_field(pyitem, "mid", &mid) ||
	   !get_int_field(pyitem, "cmode", &cmode) ||
	   !get_int_field(pyitem, "bmode", &bmode) ||
	   !get_double_array(pyitem, "left_color", left_col, 4) ||
	   !get_double_array(pyitem, "right_color", right_col, 4))
	{
	    Py_DECREF(pyitem);
	    delete cmap;
	    return NULL;
	}

	cmap->set(i, left, right, mid,
		  left_col,right_col,
		  (e_blendType)bmode, (e_colorType)cmode);

	Py_DECREF(pyitem);
    }
    return cmap;
}

static PyObject *
cmap_create_gradient(PyObject *self, PyObject *args)
{
    /* args = a gradient object:
       an array of objects with:
       float: left,right,mid
       int: bmode, cmode
       [f,f,f,f] : left_color, right_color
    */
    PyObject *pyarray, *pyret;

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

    if(!PySequence_Check(pyarray))
    {
	return NULL;
    }

    ColorMap *cmap = cmap_from_pyobject(pyarray);

    if(NULL == cmap)
    {
	return NULL;
    }

    pyret = PyCObject_FromVoidPtr(cmap,(void (*)(void *))cmap_delete);

    return pyret;
}

static bool
parse_posparams(PyObject *py_posparams, double *pos_params)
{
    // check and parse pos_params
    if(!PySequence_Check(py_posparams))
    {
	PyErr_SetString(PyExc_TypeError,
			"Positional params should be an array of floats");
	return false;
    }

    int len = PySequence_Size(py_posparams);
    if(len != N_PARAMS)
    {
	PyErr_SetString(
	    PyExc_ValueError,
	    "Wrong number of positional params");
	return false;
    }

    for(int i = 0; i < N_PARAMS; ++i)
    {
	PyObject *pyitem = PySequence_GetItem(py_posparams,i);
	if(pyitem == NULL || !PyFloat_Check(pyitem))
	{
	    PyErr_SetString(
		PyExc_ValueError,
		"All positional params must be floats");
	    return false;
	}
	pos_params[i] = PyFloat_AsDouble(pyitem);
    }
    return true;
}

static s_param *
parse_params(PyObject *pyarray, int *plen)
{
    struct s_param *params;

    // check and parse fractal params
    if(!PySequence_Check(pyarray))
    {
	PyErr_SetString(PyExc_TypeError,
			"parameters argument should be an array");
	return NULL;
    }

    int len = PySequence_Size(pyarray);
    if(len == 0)
    {
	params = (struct s_param *)malloc(sizeof(struct s_param));
	params[0].t = FLOAT;
	params[0].doubleval = 0.0;
    }
    else if(len > PF_MAXPARAMS)
    {
	PyErr_SetString(PyExc_ValueError,"Too many parameters");
	return NULL;
    }
    else
    {
	int i = 0;
	params = (struct s_param *)malloc(len * sizeof(struct s_param));
	if(!params) return NULL;
	for(i = 0; i < len; ++i)
	{
	    PyObject *pyitem = PySequence_GetItem(pyarray,i);
	    if(NULL == pyitem)
	    {
		free(params);
		return NULL;
	    }
	    if(PyFloat_Check(pyitem))
	    {
		params[i].t = FLOAT;
		params[i].doubleval = PyFloat_AsDouble(pyitem);
		//fprintf(stderr,"%d = float(%g)\n",i,params[i].doubleval);
	    }
	    else if(PyInt_Check(pyitem))
	    {
		params[i].t = INT;
		params[i].intval = PyInt_AS_LONG(pyitem);
		//fprintf(stderr,"%d = int(%d)\n",i,params[i].intval);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"cobject") &&
		PyObject_HasAttrString(pyitem,"segments"))
	    {
		// looks like a colormap. Either we already have an object, which we can use now,
		// or we need to construct one from a list of segments
		PyObject *pycob = PyObject_GetAttrString(pyitem,"cobject");
		if(pycob == Py_None || pycob == NULL)
		{
		    Py_XDECREF(pycob);
		    PyObject *pysegs = PyObject_GetAttrString(
			pyitem,"segments");

		    ColorMap *cmap;
		    if (pysegs == Py_None || pysegs == NULL)
		    {
			cmap = NULL;
		    }
		    else
		    {
			cmap = cmap_from_pyobject(pysegs);
		    }

		    Py_XDECREF(pysegs);

		    if(NULL == cmap)
		    {
			PyErr_SetString(PyExc_ValueError, "Invalid colormap object");
			free(params);
			return NULL;
		    }

		    pycob = PyCObject_FromVoidPtr(
			cmap, (void (*)(void *))cmap_delete);

		    if(NULL != pycob)
		    {
			PyObject_SetAttrString(pyitem,"cobject",pycob);
			// not quite correct, we are leaking some
			// cmap objects
			Py_INCREF(pycob);
		    }
		}
		params[i].t = GRADIENT;
		params[i].gradient = PyCObject_AsVoidPtr(pycob);
		//fprintf(stderr,"%d = gradient(%p)\n",i,params[i].gradient);
		Py_XDECREF(pycob);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"_img"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"_img");
		params[i].t = PARAM_IMAGE;
		params[i].image = PyCObject_AsVoidPtr(pycob);
		Py_XDECREF(pycob);
	    }
	    else
	    {
		Py_XDECREF(pyitem);
		PyErr_SetString(
		    PyExc_ValueError,
		    "All params must be floats, ints, images or gradients");
		free(params);
		return NULL;
	    }
	    Py_XDECREF(pyitem);
	}
    }
    *plen = len;
    return params;
}

static PyObject *
pf_init(PyObject *self, PyObject *args)
{
    PyObject *pyobj, *pyarray, *py_posparams;
    struct s_param *params;
    struct pfHandle *pfh;
    double pos_params[N_PARAMS];

    if(!PyArg_ParseTuple(
	   args,"OOO",&pyobj,&py_posparams, &pyarray))
    {
	return NULL;
    }
    if(!PyCObject_Check(pyobj))
    {
	PyErr_SetString(PyExc_ValueError,"Not a valid handle");
	return NULL;
    }

    pfh = (struct pfHandle *)PyCObject_AsVoidPtr(pyobj);

    if(!parse_posparams(py_posparams, pos_params))
    {
	return NULL;
    }

    int len=0;
    params = parse_params(pyarray,&len);
    if(!params)
    {
	return NULL;
    }

    /*finally all args are assembled */
    pfh->pfo->vtbl->init(pfh->pfo,pos_params,params,len);
    free(params);

    Py_INCREF(Py_None);
    return Py_None;
}

/* convert an array of params from the s_param representation
   to a Python list */

static PyObject *
params_to_python(struct s_param *params, int len)
{
    PyObject *pyret = PyList_New(len);
    if(!pyret)
    {
	PyErr_SetString(PyExc_MemoryError, "Can't allocate defaults list");
	return NULL;
    }
    for(int i = 0; i < len; ++i)
    {
	switch(params[i].t)
	{
	case FLOAT:
	    PyList_SET_ITEM(pyret,i,PyFloat_FromDouble(params[i].doubleval));
	    break;
	case INT:
	    PyList_SET_ITEM(pyret,i,PyInt_FromLong(params[i].intval));
	    break;
	case GRADIENT:
	    Py_INCREF(Py_None);
	    PyList_SET_ITEM(pyret,i,Py_None);
	    break;
	default:
	    assert(0 && "Unexpected type for parameter");
	    Py_INCREF(Py_None);
	    PyList_SET_ITEM(pyret,i,Py_None);
	}
    }
    return pyret;
}

static PyObject *
pf_defaults(PyObject *self, PyObject *args)
{
    PyObject *pyobj, *pyarray, *py_posparams;
    struct s_param *params;
    struct pfHandle *pfh;
    double pos_params[N_PARAMS];

    if(!PyArg_ParseTuple(
	   args,"OOO",&pyobj,&py_posparams, &pyarray))
    {
	return NULL;
    }
    if(!PyCObject_Check(pyobj))
    {
	PyErr_SetString(PyExc_ValueError,"Not a valid handle");
	return NULL;
    }

    pfh = (struct pfHandle *)PyCObject_AsVoidPtr(pyobj);

    if(!parse_posparams(py_posparams, pos_params))
    {
	return NULL;
    }

    int len=0;
    params = parse_params(pyarray,&len);
    if(!params)
    {
	return NULL;
    }

    /*finally all args are assembled */
    pfh->pfo->vtbl->get_defaults(
	pfh->pfo,
	pos_params,
	params,
	len);

    PyObject *pyret = params_to_python(params,len);
    free(params);

    return pyret;
}

static PyObject *
pf_calc(PyObject *self, PyObject *args)
{
    PyObject *pyobj, *pyret;
    double params[4];
    struct pfHandle *pfh;
    int nIters, x=0,y=0,aa=0;
    int repeats = 1;
    int outIters=0, outFate=-777;
    double outDist=0.0;
    int outSolid=0;
    int fDirectColorFlag=0;
    double colors[4] = {0.0, 0.0, 0.0, 0.0};

    if(!PyArg_ParseTuple(args,"O(dddd)i|iiii",
			 &pyobj,
			 &params[0],&params[1],&params[2],&params[3],
			 &nIters,&x,&y,&aa,&repeats))
    {
	return NULL;
    }
    if(!PyCObject_Check(pyobj))
    {
	PyErr_SetString(PyExc_ValueError,"Not a valid handle");
	return NULL;
    }

    pfh = (struct pfHandle *)PyCObject_AsVoidPtr(pyobj);
#ifdef DEBUG_THREADS
    fprintf(stderr,"%p : PF : CALC\n",pfh);
#endif
    for(int i = 0; i < repeats; ++i)
    {
	pfh->pfo->vtbl->calc(
	    pfh->pfo,params,
	    nIters, -1,
	    nIters, 1.0E-9,
	    x,y,aa,
	    &outIters,&outFate,&outDist,&outSolid,
	    &fDirectColorFlag, &colors[0]);
    }
    assert(outFate != -777);
    pyret = Py_BuildValue("iidi",outIters,outFate,outDist,outSolid);
    return pyret; // Python can handle errors if this is NULL
}

/*
 * cmaps
 */
static PyObject *
cmap_create(PyObject *self, PyObject *args)
{
    /* args = an array of (index,r,g,b,a) tuples */
    PyObject *pyarray, *pyret;
    int len, i;
    ListColorMap *cmap;

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

    if(!PySequence_Check(pyarray))
    {
	return NULL;
    }

    len = PySequence_Size(pyarray);
    if(len == 0)
    {
	PyErr_SetString(PyExc_ValueError,"Empty color array");
	return NULL;
    }

    cmap = new(std::nothrow)ListColorMap();

    if(!cmap)
    {
	PyErr_SetString(PyExc_MemoryError,"Can't allocate colormap");
	return NULL;
    }
    if(! cmap->init(len))
    {
	PyErr_SetString(PyExc_MemoryError,"Can't allocate colormap array");
	delete cmap;
	return NULL;
    }
    for(i = 0; i < len; ++i)
    {
	double d;
	int r, g, b, a;
	PyObject *pyitem = PySequence_GetItem(pyarray,i);
	if(!pyitem)
	{
	    delete cmap;
	    return NULL;
	}
	if(!PyArg_ParseTuple(pyitem,"diiii",&d,&r,&g,&b,&a))
	{
	    Py_DECREF(pyitem);
	    delete cmap;
	    return NULL;
	}
	cmap->set(i,d,r,g,b,a);
	Py_DECREF(pyitem);
    }
    pyret = PyCObject_FromVoidPtr(cmap,(void (*)(void *))cmap_delete);

    return pyret;
}

static PyObject *
pycmap_set_solid(PyObject *self, PyObject *args)
{
    PyObject *pycmap;
    int which,r,g,b,a;
    ColorMap *cmap;

    if(!PyArg_ParseTuple(args,"Oiiiii",&pycmap,&which,&r,&g,&b,&a))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pycmap);
    if(!cmap)
    {
	return NULL;
    }

    cmap->set_solid(which,r,g,b,a);

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
pycmap_set_transfer(PyObject *self, PyObject *args)
{
    PyObject *pycmap;
    int which;
    e_transferType transfer;
    ColorMap *cmap;

    if(!PyArg_ParseTuple(args,"Oii",&pycmap,&which,&transfer))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pycmap);
    if(!cmap)
    {
	return NULL;
    }

    cmap->set_transfer(which,transfer);

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
cmap_pylookup(PyObject *self, PyObject *args)
{
    PyObject *pyobj, *pyret;
    double d;
    rgba_t color;
    ColorMap *cmap;

    if(!PyArg_ParseTuple(args,"Od", &pyobj, &d))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pyobj);
    if(!cmap)
    {
	return NULL;
    }

    color = cmap->lookup(d);

    pyret = Py_BuildValue("iiii",color.r,color.g,color.b,color.a);

    return pyret;
}

static PyObject *
cmap_pylookup_with_flags(PyObject *self, PyObject *args)
{
    PyObject *pyobj, *pyret;
    double d;
    rgba_t color;
    ColorMap *cmap;
    int inside;
    int solid;

    if(!PyArg_ParseTuple(args,"Odii", &pyobj, &d, &solid, &inside))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pyobj);
    if(!cmap)
    {
	return NULL;
    }

    color = cmap->lookup_with_transfer(d,solid,inside);

    pyret = Py_BuildValue("iiii",color.r,color.g,color.b,color.a);

    return pyret;
}

#ifdef THREADS
#define GET_LOCK PyGILState_STATE gstate; gstate = PyGILState_Ensure()
#define RELEASE_LOCK PyGILState_Release(gstate)
#else
#define GET_LOCK
#define RELEASE_LOCK
#endif

class PySite :public IFractalSite
{
public:
    PySite(PyObject *site_)
	{
	    site = site_;

	    has_pixel_changed_method =
		PyObject_HasAttrString(site,"pixel_changed");

#ifdef DEBUG_CREATION
	    fprintf(stderr,"%p : SITE : CTOR\n",this);
#endif

	    // Don't incref, that causes a loop with parent fractal
	    //Py_INCREF(site);
	}

    virtual void iters_changed(int numiters)
	{
	    GET_LOCK;
	    PyObject *ret = PyObject_CallMethod(
		site,
		const_cast<char *>("iters_changed"),
		const_cast<char *>("i"),
		numiters);
	    Py_XDECREF(ret);
	    RELEASE_LOCK;
	}

    virtual void tolerance_changed(double tolerance)
	{
	    GET_LOCK;
	    PyObject *ret = PyObject_CallMethod(
		site,
		const_cast<char *>("tolerance_changed"),
		const_cast<char *>("d"),
		tolerance);
	    Py_XDECREF(ret);
	    RELEASE_LOCK;
	}
    // we've drawn a rectangle of image
    virtual void image_changed(int x1, int y1, int x2, int y2)
	{
	    GET_LOCK;
	    PyObject *ret = PyObject_CallMethod(
		site,
		const_cast<char *>("image_changed"),
		const_cast<char *>("iiii"),
		x1,y1,x2,y2);
	    Py_XDECREF(ret);
	    RELEASE_LOCK;
	}
    // estimate of how far through current pass we are
    virtual void progress_changed(float progress)
	{
	    double d = (double)progress;

	    GET_LOCK;
	    PyObject *ret = PyObject_CallMethod(
		site,
		const_cast<char *>("progress_changed"),
		const_cast<char *>("d"),
		d);
	    Py_XDECREF(ret);
	    RELEASE_LOCK;
	}

    virtual void stats_changed(pixel_stat_t& stats)
	{
	    GET_LOCK;
	    PyObject *ret = PyObject_CallMethod(
		site,
		const_cast<char *>("stats_changed"),
		const_cast<char *>("[kkkkkkkkkk]"),
		stats.s[0], stats.s[1], stats.s[2],stats.s[3],stats.s[4],
		stats.s[5], stats.s[6], stats.s[7],stats.s[8],stats.s[9]);
	    Py_XDECREF(ret);
	    RELEASE_LOCK;
	}

    // one of the status values above
    virtual void status_changed(int status_val)
	{
	    assert(this != NULL && site != NULL);
	    //fprintf(stderr,"sc: %p %p\n",this,this->status_changed_cb);

	    GET_LOCK;
	    PyObject *ret = PyObject_CallMethod(
		site,
		const_cast<char *>("status_changed"),
		const_cast<char *>("i"),
		status_val);

	    if(PyErr_Occurred())
	    {
		fprintf(stderr,"bad status 2\n");
		PyErr_Print();
	    }
	    Py_XDECREF(ret);
	    RELEASE_LOCK;
	}

    // return true if we've been interrupted and are supposed to stop
    virtual bool is_interrupted()
	{
	    GET_LOCK;
	    PyObject *pyret = PyObject_CallMethod(
		site,
		const_cast<char *>("is_interrupted"),NULL);

	    bool ret = false;
	    if(pyret != NULL && PyInt_Check(pyret))
	    {
		long i = PyInt_AsLong(pyret);
		//fprintf(stderr,"ret: %ld\n",i);
		ret = (i != 0);
	    }

	    Py_XDECREF(pyret);
	    RELEASE_LOCK;
	    return ret;
	}

    // pixel changed
    virtual void pixel_changed(
	const double *params, int maxIters, int nNoPeriodIters,
	int x, int y, int aa,
	double dist, int fate, int nIters,
	int r, int g, int b, int a)
	{
	    if(has_pixel_changed_method)
	    {
		GET_LOCK;
		PyObject *pyret = PyObject_CallMethod(
		    site,
		    const_cast<char *>("pixel_changed"),
		    const_cast<char *>("(dddd)iiiiidiiiiii"),
		    params[0],params[1],params[2],params[3],
		    x,y,aa,
		    maxIters,nNoPeriodIters,
		    dist,fate,nIters,
		    r,g,b,a);

		Py_XDECREF(pyret);
		RELEASE_LOCK;
	    }
	};
    virtual void interrupt()
	{
	    // FIXME? interrupted = true;
	}

    virtual void start(pthread_t tid_)
	{
	    tid = tid_;
	}

    virtual void wait()
	{
	    pthread_join(tid,NULL);
	}

    ~PySite()
	{
#ifdef DEBUG_CREATION
	    fprintf(stderr,"%p : SITE : DTOR\n",this);
#endif
	    //Py_DECREF(site);
	}

    //PyThreadState *state;
private:
    PyObject *site;
    bool has_pixel_changed_method;
    pthread_t tid;
};

typedef enum
{
    ITERS,
    IMAGE,
    PROGRESS,
    STATUS,
    PIXEL,
    TOLERANCE,
    STATS,
} msg_type_t;

struct calc_args
{
    double params[N_PARAMS];
    int eaa, maxiter, nThreads;
    int auto_deepen, yflip, periodicity, dirty;
    int auto_tolerance;
    double tolerance;
    int async, warp_param;
    render_type_t render_type;
    pf_obj *pfo;
    ColorMap *cmap;
    IImage *im;
    IFractalSite *site;

    PyObject *pycmap, *pypfo, *pyim, *pysite;
    calc_args()
	{
#ifdef DEBUG_CREATION
	    fprintf(stderr,"%p : CA : CTOR\n",this);
#endif
	    pycmap = NULL;
	    pypfo = NULL;
	    pyim = NULL;
	    pysite = NULL;
	    dirty = 1;
	    periodicity = true;
	    yflip = false;
	    auto_deepen = false;
	    auto_tolerance = false;
	    tolerance = 1.0E-9;
	    eaa = AA_NONE;
	    maxiter = 1024;
	    nThreads = 1;
	    render_type = RENDER_TWO_D;
	    async = false;
	    warp_param = -1;
	}

    void set_cmap(PyObject *pycmap_)
	{
	    pycmap = pycmap_;
	    cmap = (ColorMap *)PyCObject_AsVoidPtr(pycmap);
	    Py_XINCREF(pycmap);
	}

    void set_pfo(PyObject *pypfo_)
	{
	    pypfo = pypfo_;

	    pfo = ((pfHandle *)PyCObject_AsVoidPtr(pypfo))->pfo;
	    Py_XINCREF(pypfo);
	}

    void set_im(PyObject *pyim_)
	{
	    pyim = pyim_;
	    im = (IImage *)PyCObject_AsVoidPtr(pyim);
	    Py_XINCREF(pyim);
	}
    void set_site(PyObject *pysite_)
	{
	    pysite = pysite_;
	    site = (IFractalSite *)PyCObject_AsVoidPtr(pysite);
	    Py_XINCREF(pysite);
	}

    ~calc_args()
	{
#ifdef DEBUG_CREATION
	    fprintf(stderr,"%p : CA : DTOR\n",this);
#endif
	    Py_XDECREF(pycmap);
	    Py_XDECREF(pypfo);
	    Py_XDECREF(pyim);
	    Py_XDECREF(pysite);
	}
};

// write the callbacks to a file descriptor
class FDSite :public IFractalSite
{
public:
    FDSite(int fd_) : fd(fd_), tid((pthread_t)0),
		      interrupted(false), params(NULL)
	{
#ifdef DEBUG_CREATION
	    fprintf(stderr,"%p : FD : CTOR\n",this);
#endif
	    pthread_mutex_init(&write_lock,NULL);
	}

    inline void send(msg_type_t type, int size, void *buf)
	{
	    pthread_mutex_lock(&write_lock);
	    if (write(fd,&type,sizeof(type))) {};
	    if (write(fd,&size,sizeof(size))) {};
	    if (write(fd,buf,size)) {};
	    pthread_mutex_unlock(&write_lock);
	}
    virtual void iters_changed(int numiters)
	{
	    send(ITERS, sizeof(int), &numiters);
	}
    virtual void tolerance_changed(double tolerance)
	{
	    send (TOLERANCE, sizeof(tolerance), &tolerance);
	}

    // we've drawn a rectangle of image
    virtual void image_changed(int x1, int y1, int x2, int y2)
	{
	    if(!interrupted)
	    {
		int buf[4] = { x1, y1, x2, y2 };
		send(IMAGE, sizeof(buf), &buf[0]);
	    }
	}
    // estimate of how far through current pass we are
    virtual void progress_changed(float progress)
	{
	    if(!interrupted)
	    {
		int percentdone = (int) (100.0 * progress);
		send(PROGRESS, sizeof(percentdone), &percentdone);
	    }
	}

    virtual void stats_changed(pixel_stat_t& stats)
	{
	    if(!interrupted)
	    {
		send(STATS,sizeof(stats),&stats);
	    }

	}

    // one of the status values above
    virtual void status_changed(int status_val)
	{
	    send(STATUS,sizeof(status_val),&status_val);
	}

    // return true if we've been interrupted and are supposed to stop
    virtual bool is_interrupted()
	{
	    //fprintf(stderr,"int: %d\n",interrupted);
	    return interrupted;
	}

    // pixel changed
    virtual void pixel_changed(
	const double *params, int maxIters, int nNoPeriodIters,
	int x, int y, int aa,
	double dist, int fate, int nIters,
	int r, int g, int b, int a)
	{
	    /*
	    fprintf(stderr,"pixel: <%g,%g,%g,%g>(%d,%d,%d) = (%g,%d,%d)\n",
		   params[0],params[1],params[2],params[3],
		   x,y,aa,dist,fate,nIters);
	    */
	    return; // FIXME
	};

    virtual void interrupt()
	{
#ifdef DEBUG_THREADS
	    fprintf(stderr,"%p : CA : INT(%p)\n", this, tid);
#endif
	    interrupted = true;
	}

    virtual void start(calc_args *params_)
	{
#ifdef DEBUG_THREADS
	    fprintf(stderr,"clear interruption\n");
#endif
	    interrupted = false;
	    params = params_;
	}

    virtual void set_tid(pthread_t tid_)
	{
#ifdef DEBUG_THREADS
	    fprintf(stderr,"%p : CA : SET(%p)\n", this,tid_);
#endif
	    tid = tid_;
	}

    virtual void wait()
	{
	    if(tid != 0)
	    {
#ifdef DEBUG_THREADS
		fprintf(stderr,"%p : CA : WAIT(%p)\n", this,tid);
#endif
		pthread_join(tid,NULL);
	    }
	}
    ~FDSite()
	{
#ifdef DEBUG_CREATION
	    fprintf(stderr,"%p : FD : DTOR\n",this);
#endif
	    close(fd);
	}
private:
    int fd;
    pthread_t tid;
    volatile bool interrupted;
    calc_args *params;
    pthread_mutex_t write_lock;
};

static void
site_delete(IFractalSite *site)
{
    delete site;
}

static void
fw_delete(IFractWorker *worker)
{
    delete worker;
}

struct ffHandle
{
    PyObject *pyhandle;
    fractFunc *ff;
} ;

static void
ff_delete(struct ffHandle *ffh)
{
#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : FF : DTOR\n",ffh);
#endif
    delete ffh->ff;
    Py_DECREF(ffh->pyhandle);
    delete ffh;
}

static PyObject *
pysite_create(PyObject *self, PyObject *args)
{
    PyObject *pysite;
    if(!PyArg_ParseTuple(
	   args,
	   "O",
	   &pysite))
    {
	return NULL;
    }

    IFractalSite *site = new PySite(pysite);

    //fprintf(stderr,"pysite_create: %p\n",site);
    PyObject *pyret = PyCObject_FromVoidPtr(site,(void (*)(void *))site_delete);

    return pyret;
}

static PyObject *
pyfdsite_create(PyObject *self, PyObject *args)
{
    int fd;
    if(!PyArg_ParseTuple(args,"i", &fd))
    {
	return NULL;
    }

    IFractalSite *site = new FDSite(fd);

    PyObject *pyret = PyCObject_FromVoidPtr(site,(void (*)(void *))site_delete);

    return pyret;
}

static PyObject *
pystop_calc(PyObject *self, PyObject *args)
{
    PyObject *pysite;
    if(!PyArg_ParseTuple(
	   args,
	   "O",
	   &pysite))
    {
	return NULL;
    }

    IFractalSite *site = (IFractalSite *)PyCObject_AsVoidPtr(pysite);
    if(!site)
    {
	return NULL;
    }

    site->interrupt();

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
fw_create(PyObject *self, PyObject *args)
{
    int nThreads;
    pf_obj *pfo;
    ColorMap *cmap;
    IImage *im;
    IFractalSite *site;

    PyObject *pypfo, *pycmap, *pyim, *pysite;

    if(!PyArg_ParseTuple(args,"iOOOO",
			 &nThreads,
			 &pypfo,
			 &pycmap,
			 &pyim,
			 &pysite))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pycmap);
    pfo = ((pfHandle *)PyCObject_AsVoidPtr(pypfo))->pfo;
    im = (IImage *)PyCObject_AsVoidPtr(pyim);
    site = (IFractalSite *)PyCObject_AsVoidPtr(pysite);
    if(!cmap || !pfo || !im || !im->ok() || !site)
    {
	return NULL;
    }

    IFractWorker *worker = IFractWorker::create(nThreads,pfo,cmap,im,site);

    if(!worker->ok())
    {
	PyErr_SetString(PyExc_ValueError,"Error creating worker");
	delete worker;
	return NULL;
    }

    PyObject *pyret = PyCObject_FromVoidPtr(
	worker,(void (*)(void *))fw_delete);

    return pyret;
}

static PyObject *
fw_pixel(PyObject *self, PyObject *args)
{
    PyObject *pyworker;
    int x,y,w,h;

    if(!PyArg_ParseTuple(args, "Oiiii",
			 &pyworker,
			 &x,&y,&w,&h))
    {
	return NULL;
    }

    IFractWorker *worker = (IFractWorker *)PyCObject_AsVoidPtr(pyworker);
    worker->pixel(x,y,w,h);

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
fw_pixel_aa(PyObject *self, PyObject *args)
{
    PyObject *pyworker;
    int x,y;

    if(!PyArg_ParseTuple(args, "Oii",
			 &pyworker,
			 &x,&y))
    {
	return NULL;
    }

    IFractWorker *worker = (IFractWorker *)PyCObject_AsVoidPtr(pyworker);
    worker->pixel_aa(x,y);

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
fw_find_root(PyObject *self, PyObject *args)
{
    PyObject *pyworker;
    dvec4 eye, look;

    if(!PyArg_ParseTuple(args, "O(dddd)(dddd)",
			 &pyworker,
			 &eye[VX],&eye[VY], &eye[VZ], &eye[VW],
			 &look[VX],&look[VY], &look[VZ], &look[VW]))
    {
	return NULL;
    }

    IFractWorker *worker = (IFractWorker *)PyCObject_AsVoidPtr(pyworker);
    dvec4 root;
    int ok = worker->find_root(eye,look,root);

    return Py_BuildValue(
	"i(dddd)",
	ok,root[0], root[1], root[2], root[3]);
}

static PyObject *
ff_create(PyObject *self, PyObject *args)
{
    PyObject *pypfo, *pycmap, *pyim, *pysite, *pyworker;
    double params[N_PARAMS];
    int eaa=-7, maxiter=-8, nThreads=-9;
    int auto_deepen, periodicity;
    int yflip;
    render_type_t render_type;
    pf_obj *pfo;
    ColorMap *cmap;
    IImage *im;
    IFractalSite *site;
    IFractWorker *worker;
    int auto_tolerance;
    double tolerance;

    if(!PyArg_ParseTuple(
	   args,
	   "(ddddddddddd)iiiiOOiiiOOOid",
	   &params[0],&params[1],&params[2],&params[3],
	   &params[4],&params[5],&params[6],&params[7],
	   &params[8],&params[9],&params[10],
	   &eaa,&maxiter,&yflip,&nThreads,
	   &pypfo,&pycmap,
	   &auto_deepen,
	   &periodicity,
	   &render_type,
	   &pyim, &pysite,
	   &pyworker,
	   &auto_tolerance, &tolerance
	   ))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pycmap);
    pfo = ((pfHandle *)PyCObject_AsVoidPtr(pypfo))->pfo;
    im = (IImage *)PyCObject_AsVoidPtr(pyim);
    site = (IFractalSite *)PyCObject_AsVoidPtr(pysite);
    worker = (IFractWorker *)PyCObject_AsVoidPtr(pyworker);

    if(!cmap || !pfo || !im || !site || !worker)
    {
	return NULL;
    }

    fractFunc *ff = new fractFunc(
	params,
	eaa,
	maxiter,
	nThreads,
	auto_deepen,
	auto_tolerance,
	tolerance,
	yflip,
	periodicity,
	render_type,
	-1, // warp_param
	worker,
	im,
	site);

    if(!ff)
    {
	return NULL;
    }

    ffHandle *ffh = new struct ffHandle;
    ffh->ff = ff;
    ffh->pyhandle = pyworker;

#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : FF : CTOR\n",ffh);
#endif

    PyObject *pyret = PyCObject_FromVoidPtr(
	ffh,(void (*)(void *))ff_delete);

    Py_INCREF(pyworker);

    return pyret;
}

static void *
calculation_thread(void *vdata)
{
    calc_args *args = (calc_args *)vdata;

#ifdef DEBUG_THREADS
    fprintf(stderr,"%p : CA : CALC(%d)\n",args,pthread_self());
#endif

    calc(args->params,args->eaa,args->maxiter,
	 args->nThreads,args->pfo,args->cmap,
	 args->auto_deepen,
	 args->auto_tolerance,
	 args->tolerance,
	 args->yflip, args->periodicity, args->dirty,
	 0, // debug_flags
	 args->render_type,
	 args->warp_param,
	 args->im,args->site);

#ifdef DEBUG_THREADS
    fprintf(stderr,"%p : CA : ENDCALC(%d)\n",args,pthread_self());
#endif

    delete args;
    return NULL;
}

static calc_args *
parse_calc_args(PyObject *args, PyObject *kwds)
{
    PyObject *pyparams, *pypfo, *pycmap, *pyim, *pysite;
    calc_args *cargs = new calc_args();
    double *p = NULL;

    static const char *kwlist[] = {
	"image",
	"site",
	"pfo",
	"cmap",
	"params",
	"antialias",
	"maxiter",
	"yflip",
	"nthreads",
	"auto_deepen",
	"periodicity",
	"render_type",
	"dirty",
	"async",
	"warp_param",
	"tolerance",
	"auto_tolerance",
	NULL};

    if(!PyArg_ParseTupleAndKeywords(
	   args,
	   kwds,
	   "OOOOO|iiiiiiiiiidi",
	   const_cast<char **>(kwlist),

	   &pyim, &pysite,
	   &pypfo,&pycmap,
	   &pyparams,
	   &cargs->eaa,
	   &cargs->maxiter,
	   &cargs->yflip,
	   &cargs->nThreads,
	   &cargs->auto_deepen,
	   &cargs->periodicity,
	   &cargs->render_type,
	   &cargs->dirty,
	   &cargs->async,
	   &cargs->warp_param,
	   &cargs->tolerance,
	   &cargs->auto_tolerance
	   ))
    {
	goto error;
    }

    p = cargs->params;
    if(!PyList_Check(pyparams) || PyList_Size(pyparams) != N_PARAMS)
    {
	PyErr_SetString(PyExc_ValueError, "bad parameter list");
	goto error;
    }

    for(int i = 0; i < N_PARAMS; ++i)
    {
	PyObject *elt = PyList_GetItem(pyparams, i);
	if(!PyFloat_Check(elt))
	{
	    PyErr_SetString(PyExc_ValueError, "a param is not a float");
	    goto error;
	}

	p[i] = PyFloat_AsDouble(elt);
    }

    cargs->set_cmap(pycmap);
    cargs->set_pfo(pypfo);
    cargs->set_im(pyim);
    cargs->set_site(pysite);
    if(!cargs->cmap || !cargs->pfo ||
       !cargs->im   || !cargs->site)
    {
	PyErr_SetString(PyExc_ValueError, "bad argument passed to calc");
	goto error;
    }

    if(!cargs->im->ok())
    {
	PyErr_SetString(PyExc_MemoryError, "image not allocated");
	goto error;
    }

    return cargs;

error:
    delete cargs;
    return NULL;
}

static PyObject *
pycalc(PyObject *self, PyObject *args, PyObject *kwds)
{
    calc_args *cargs = parse_calc_args(args, kwds);
    if(NULL == cargs)
    {
	return NULL;
    }

    if(cargs->async)
    {
	cargs->site->interrupt();
	cargs->site->wait();

	cargs->site->start(cargs);

	pthread_t tid;

	/* create low-priority attribute block */
	pthread_attr_t lowprio_attr;
	//struct sched_param lowprio_param;
	pthread_attr_init(&lowprio_attr);
	//lowprio_param.sched_priority = sched_get_priority_min(SCHED_OTHER);
	//pthread_attr_setschedparam(&lowprio_attr, &lowprio_param);

	/* start the calculation thread */
	pthread_create(&tid,&lowprio_attr,calculation_thread,(void *)cargs);
	assert(tid != 0);

	cargs->site->set_tid(tid);
    }
    else
    {
	Py_BEGIN_ALLOW_THREADS
	// synchronous
	calc(cargs->params,
	     cargs->eaa,
	     cargs->maxiter,
	     cargs->nThreads,
	     cargs->pfo,
	     cargs->cmap,
	     cargs->auto_deepen,
	     cargs->auto_tolerance,
	     cargs->tolerance,
	     cargs->yflip,
	     cargs->periodicity,
	     cargs->dirty,
	     0, // debug_flags
	     cargs->render_type,
	     cargs->warp_param,
	     cargs->im,
	     cargs->site);

	delete cargs;
	Py_END_ALLOW_THREADS
    }

    Py_INCREF(Py_None);

    return Py_None;
}

static void
image_delete(IImage *image)
{
#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : IM : DTOR\n",image);
#endif
    delete image;
}

static PyObject *
image_create(PyObject *self, PyObject *args)
{
    int x, y;
    int totalx = -1, totaly = -1;
    if(!PyArg_ParseTuple(args,"ii|ii",&x,&y,&totalx, &totaly))
    {
	return NULL;
    }

    IImage *i = new image();

    i->set_resolution(x,y,totalx, totaly);

    if(! i->ok())
    {
	PyErr_SetString(PyExc_MemoryError, "Image too large");
	delete i;
	return NULL;
    }

#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : IM : CTOR\n",i);
#endif

    PyObject *pyret = PyCObject_FromVoidPtr(i,(void (*)(void *))image_delete);

    return pyret;
}

static PyObject *
image_resize(PyObject *self, PyObject *args)
{
    int x, y;
    int totalx=-1, totaly=-1;
    PyObject *pyim;

    if(!PyArg_ParseTuple(args,"Oiiii",&pyim,&x,&y,&totalx,&totaly))
    {
	return NULL;
    }

    IImage *i = (IImage *)PyCObject_AsVoidPtr(pyim);
    if(NULL == i)
    {
	return NULL;
    }

    i->set_resolution(x,y,totalx,totaly);

    if(! i->ok())
    {
	PyErr_SetString(PyExc_MemoryError, "Image too large");
	return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
image_dims(PyObject *self, PyObject *args)
{
    PyObject *pyim;

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

    IImage *i = (IImage *)PyCObject_AsVoidPtr(pyim);
    if(NULL == i)
    {
	return NULL;
    }

    int xsize, ysize, xoffset, yoffset, xtotalsize, ytotalsize;
    xsize = i->Xres();
    ysize = i->Yres();
    xoffset = i->Xoffset();
    yoffset = i->Yoffset();
    xtotalsize = i->totalXres();
    ytotalsize = i->totalYres();

    PyObject *pyret = Py_BuildValue(
	"(iiiiii)", xsize,ysize,xtotalsize, ytotalsize, xoffset, yoffset);

    return pyret;
}

static PyObject *
image_set_offset(PyObject *self, PyObject *args)
{
    int x, y;
    PyObject *pyim;

    if(!PyArg_ParseTuple(args,"Oii",&pyim,&x,&y))
    {
	return NULL;
    }

    IImage *i = (IImage *)PyCObject_AsVoidPtr(pyim);
    if(NULL == i)
    {
	return NULL;
    }

    bool ok = i->set_offset(x,y);
    if(!ok)
    {
	PyErr_SetString(PyExc_ValueError, "Offset out of bounds");
	return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
image_clear(PyObject *self, PyObject *args)
{
    PyObject *pyim;

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

    IImage *i = (IImage *)PyCObject_AsVoidPtr(pyim);
    if(NULL == i)
    {
	return NULL;
    }

    i->clear();

    Py_INCREF(Py_None);
    return Py_None;
}

static void
image_writer_delete(ImageWriter *im)
{
    delete im;
}

static PyObject *
image_writer_create(PyObject *self,PyObject *args)
{
    PyObject *pyim;
    PyObject *pyFP;
    int file_type;
    if(!PyArg_ParseTuple(args,"OOi",&pyim,&pyFP,&file_type))
    {
	return NULL;
    }

    if(!PyFile_Check(pyFP))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

    FILE *fp = PyFile_AsFile(pyFP);

    if(!fp || !i)
    {
	PyErr_SetString(PyExc_ValueError, "Bad arguments");
	return NULL;
    }

    ImageWriter *writer = ImageWriter::create((image_file_t)file_type, fp, i);
    if(NULL == writer)
    {
	PyErr_SetString(PyExc_ValueError, "Unsupported file type");
	return NULL;
    }

    return PyCObject_FromVoidPtr(
	writer, (void (*)(void *))image_writer_delete);
}

static PyObject *
image_read(PyObject *self,PyObject *args)
{
    PyObject *pyim;
    PyObject *pyFP;
    int file_type;
    if(!PyArg_ParseTuple(args,"OOi",&pyim,&pyFP,&file_type))
    {
	return NULL;
    }

    if(!PyFile_Check(pyFP))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

    FILE *fp = PyFile_AsFile(pyFP);

    if(!fp || !i)
    {
	PyErr_SetString(PyExc_ValueError, "Bad arguments");
	return NULL;
    }

    ImageReader *reader = ImageReader::create((image_file_t)file_type, fp, i);
    //if(!reader->ok())
    //{
    //	PyErr_SetString(PyExc_IOError, "Couldn't create image reader");
    //	delete reader;
    //	return NULL;
    //}

    if(!reader->read())
    {
	PyErr_SetString(PyExc_IOError, "Couldn't read image contents");
	delete reader;
	return NULL;
    }
    delete reader;

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
image_save_header(PyObject *self,PyObject *args)
{
    PyObject *pyimwriter;
    if(!PyArg_ParseTuple(args,"O",&pyimwriter))
    {
	return NULL;
    }

    ImageWriter *i = (ImageWriter *)PyCObject_AsVoidPtr(pyimwriter);

    if(!i || !i->save_header())
    {
	PyErr_SetString(PyExc_IOError, "Couldn't save file header");
	return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
image_save_tile(PyObject *self,PyObject *args)
{
    PyObject *pyimwriter;
    if(!PyArg_ParseTuple(args,"O",&pyimwriter))
    {
	return NULL;
    }

    ImageWriter *i = (ImageWriter *)PyCObject_AsVoidPtr(pyimwriter);

    if(!i || !i->save_tile())
    {
	PyErr_SetString(PyExc_IOError, "Couldn't save image tile");
	return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
image_save_footer(PyObject *self,PyObject *args)
{
    PyObject *pyimwriter;
    if(!PyArg_ParseTuple(args,"O",&pyimwriter))
    {
	return NULL;
    }

    ImageWriter *i = (ImageWriter *)PyCObject_AsVoidPtr(pyimwriter);

    if(!i || !i->save_footer())
    {
	PyErr_SetString(PyExc_IOError, "Couldn't save image footer");
	return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
image_buffer(PyObject *self, PyObject *args)
{
    PyObject *pyim;
    PyObject *pybuf;

    int x=0,y=0;
    if(!PyArg_ParseTuple(args,"O|ii",&pyim,&x,&y))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : IM : BUF\n",i);
#endif

    if(!i || ! i->ok())
    {
	PyErr_SetString(PyExc_MemoryError, "image not allocated");
	return NULL;
    }

    if(x < 0 || x >= i->Xres() || y < 0 || y >= i->Yres())
    {
	PyErr_SetString(PyExc_ValueError,"request for buffer outside image bounds");
	return NULL;
    }
    int offset = 3 * (y * i->Xres() + x);
    assert(offset > -1 && offset < i->bytes());
    pybuf = PyBuffer_FromReadWriteMemory(i->getBuffer()+offset,i->bytes()-offset);
    Py_XINCREF(pybuf);
    //Py_XINCREF(pyim);

    return pybuf;
}

static PyObject *
image_fate_buffer(PyObject *self, PyObject *args)
{
    PyObject *pyim;
    PyObject *pybuf;

    int x=0,y=0;
    if(!PyArg_ParseTuple(args,"O|ii",&pyim,&x,&y))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

#ifdef DEBUG_CREATION
    fprintf(stderr,"%p : IM : BUF\n",i);
#endif

    if(NULL == i)
    {
	PyErr_SetString(PyExc_ValueError,
			"Bad image object");
	return NULL;
    }

    if(x < 0 || x >= i->Xres() || y < 0 || y >= i->Yres())
    {
	PyErr_SetString(PyExc_ValueError,"request for buffer outside image bounds");
	return NULL;
    }
    int index = i->index_of_subpixel(x,y,0);
    int last_index = i->index_of_sentinel_subpixel();
    assert(index > -1 && index < last_index);

    pybuf = PyBuffer_FromReadWriteMemory(
	i->getFateBuffer()+index,
	(last_index - index)  * sizeof(fate_t));

    Py_XINCREF(pybuf);

    return pybuf;
}

static PyObject *
image_get_color_index(PyObject *self, PyObject *args)
{
    PyObject *pyim;

    int x=0,y=0,sub=0;
    if(!PyArg_ParseTuple(args,"Oii|i",&pyim,&x,&y,&sub))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

    if(NULL == i)
    {
	PyErr_SetString(PyExc_ValueError,
			"Bad image object");
	return NULL;
    }

    if(x < 0 || x >= i->Xres() ||
       y < 0 || y >= i->Yres() ||
       sub < 0 || sub >= image::N_SUBPIXELS)
    {
	PyErr_SetString(PyExc_ValueError,
			"request for data outside image bounds");
	return NULL;
    }

    float dist = i->getIndex(x,y,sub);
    return Py_BuildValue("d", (double)dist);
}

static PyObject *
image_get_fate(PyObject *self, PyObject *args)
{
    PyObject *pyim;

    int x=0,y=0,sub=0;
    if(!PyArg_ParseTuple(args,"Oii|i",&pyim,&x,&y,&sub))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

    if(NULL == i)
    {
	PyErr_SetString(PyExc_ValueError,
			"Bad image object");
	return NULL;
    }

    if(x < 0 || x >= i->Xres() ||
       y < 0 || y >= i->Yres() ||
       sub < 0 || sub >= image::N_SUBPIXELS)
    {
	PyErr_SetString(PyExc_ValueError,
			"request for data outside image bounds");
	return NULL;
    }

    fate_t fate = i->getFate(x,y,sub);
    if(fate == FATE_UNKNOWN)
    {
	Py_INCREF(Py_None);
	return Py_None;
    }
    int is_solid = fate & FATE_SOLID ? 1 : 0;
    return Py_BuildValue("(ii)", is_solid, fate & ~FATE_SOLID);
}

static PyObject *
rot_matrix(PyObject *self, PyObject *args)
{
    double params[N_PARAMS];

    if(!PyArg_ParseTuple(
	   args,
	   "(ddddddddddd)",
	   &params[0],&params[1],&params[2],&params[3],
	   &params[4],&params[5],&params[6],&params[7],
	   &params[8],&params[9],&params[10]))
    {
	return NULL;
    }

    dmat4 rot = rotated_matrix(params);

    return Py_BuildValue(
	"((dddd)(dddd)(dddd)(dddd))",
	rot[0][0], rot[0][1], rot[0][2], rot[0][3],
	rot[1][0], rot[1][1], rot[1][2], rot[1][3],
	rot[2][0], rot[2][1], rot[2][2], rot[2][3],
	rot[3][0], rot[3][1], rot[3][2], rot[3][3]);
}

static PyObject *
eye_vector(PyObject *self, PyObject *args)
{
    double params[N_PARAMS], dist;

    if(!PyArg_ParseTuple(
	   args,
	   "(ddddddddddd)d",
	   &params[0],&params[1],&params[2],&params[3],
	   &params[4],&params[5],&params[6],&params[7],
	   &params[8],&params[9],&params[10],&dist))
    {
	return NULL;
    }

    dvec4 eyevec = test_eye_vector(params, dist);

    return Py_BuildValue(
	"(dddd)",
	eyevec[0], eyevec[1], eyevec[2], eyevec[3]);
}

static PyObject *
ff_get_vector(PyObject *self, PyObject *args)
{
    int vec_type;
    PyObject *pyFF;

    if(!PyArg_ParseTuple(
	   args,
	   "Oi",
	   &pyFF, &vec_type))
    {
	return NULL;
    }

    struct ffHandle *ffh = (struct ffHandle *)PyCObject_AsVoidPtr(pyFF);
    if(ffh == NULL)
    {
	return NULL;
    }

    fractFunc *ff = ffh->ff;
    if(ff == NULL)
    {
	return NULL;
    }

    dvec4 vec;
    switch(vec_type)
    {
    case DELTA_X:
	vec = ff->deltax;
	break;
    case DELTA_Y:
	vec = ff->deltay;
	break;
    case TOPLEFT:
	vec = ff->topleft;
	break;
    default:
	PyErr_SetString(PyExc_ValueError, "Unknown vector requested");
	return NULL;
    }

    return Py_BuildValue(
	"(dddd)",
	vec[0], vec[1], vec[2], vec[3]);

    return NULL;
}

static PyObject *
ff_look_vector(PyObject *self, PyObject *args)
{
    PyObject *pyFF;
    double x, y;
    if(!PyArg_ParseTuple(
	   args,
	   "Odd",
	   &pyFF, &x, &y))
    {
	return NULL;
    }

    struct ffHandle *ffh = (struct ffHandle *)PyCObject_AsVoidPtr(pyFF);
    if(ffh == NULL)
    {
	return NULL;
    }

    fractFunc *ff = ffh->ff;
    if(ff == NULL)
    {
	return NULL;
    }

    dvec4 lookvec = ff->vec_for_point(x,y);

    return Py_BuildValue(
	"(dddd)",
	lookvec[0], lookvec[1], lookvec[2], lookvec[3]);

}

static PyObject *
pyimage_lookup(PyObject *self, PyObject *args)
{
    PyObject *pyimage=NULL;
    double x,y;
    double r,g,b;

    if(!PyArg_ParseTuple(
	   args,
	   "Odd",
	   &pyimage, &x, &y))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyimage);

    image_lookup(i,x,y,&r,&g,&b);

    return Py_BuildValue(
	"(dddd)",
	r,g,b,1.0);
}

static PyObject *
pyrgb_to_hsv(PyObject *self, PyObject *args)
{
    double r,g,b,a=1.0,h,s,v;
    if(!PyArg_ParseTuple(
	   args,
	   "ddd|d",
	   &r,&g,&b,&a))
    {
	return NULL;
    }

    rgb_to_hsv(r,g,b,&h,&s,&v);

    return Py_BuildValue(
	"(dddd)",
	h,s,v,a);
}

static PyObject *
pyrgb_to_hsl(PyObject *self, PyObject *args)
{
    double r,g,b,a=1.0,h,l,s;
    if(!PyArg_ParseTuple(
	   args,
	   "ddd|d",
	   &r,&g,&b,&a))
    {
	return NULL;
    }

    rgb_to_hsl(r,g,b,&h,&s,&l);

    return Py_BuildValue(
	"(dddd)",
	h,s,l,a);
}

static PyObject *
pyhsl_to_rgb(PyObject *self, PyObject *args)
{
    double r,g,b,a=1.0,h,l,s;
    if(!PyArg_ParseTuple(
	   args,
	   "ddd|d",
	   &h,&s,&l,&a))
    {
	return NULL;
    }

    hsl_to_rgb(h,s,l,&r,&g,&b);

    return Py_BuildValue(
	"(dddd)",
	r,g,b,a);
}

static PyObject *
pyarena_create(PyObject *self, PyObject *args)
{
    int page_size, max_pages;
    if(!PyArg_ParseTuple(
	   args,
	   "ii",
	   &page_size,&max_pages))
    {
	return NULL;
    }

    arena_t arena = arena_create(page_size,max_pages);

    if(NULL == arena)
    {
	PyErr_SetString(PyExc_MemoryError,"Cannot allocate arena");
	return NULL;
    }

    PyObject *pyarena = PyCObject_FromVoidPtr(
	arena,(void (*)(void *))arena_delete);

    return pyarena;
}

static PyObject *
pyarena_alloc(PyObject *self, PyObject *args)
{
    PyObject *pyArena;
    int element_size;
    int n_dimensions;
    int n_elements[4];

    if(!PyArg_ParseTuple(
	   args,
	   "Oiii|iii",
	   &pyArena, &element_size,
	   &n_dimensions,
	   &n_elements[0],
	   &n_elements[1],
	   &n_elements[2],
	   &n_elements[3]
	   ))
    {
	return NULL;
    }

    arena_t arena = (arena_t)PyCObject_AsVoidPtr(pyArena);
    if(arena == NULL)
    {
	return NULL;
    }

    void *allocation = arena_alloc(
	arena, element_size,
	n_dimensions,
	n_elements);
    if(allocation == NULL)
    {
	PyErr_SetString(PyExc_MemoryError, "Can't allocate array");
	return NULL;
    }

    PyObject *pyAlloc = PyCObject_FromVoidPtr(allocation, NULL);

    return pyAlloc;
}

static PyObject *
pyarray_get(PyObject *self, PyObject *args)
{
    PyObject *pyAllocation;
    int indexes[4];
    int n_indexes;

    if(!PyArg_ParseTuple(
	   args,
	   "Oii|iii",
	   &pyAllocation, &n_indexes,
	   &indexes[0], &indexes[1], &indexes[2], &indexes[3]))
    {
	return NULL;
    }

    void *allocation = PyCObject_AsVoidPtr(pyAllocation);
    if(allocation == NULL)
    {
	return NULL;
    }

    int retval, inbounds;
    array_get_int(allocation, n_indexes, indexes, &retval, &inbounds);

    PyObject *pyRet = Py_BuildValue(
	"(ii)",
	retval,inbounds);

    return pyRet;
}

static PyObject *
pyarray_set(PyObject *self, PyObject *args)
{
    PyObject *pyAllocation;
    int val;
    int n_indexes;
    int indexes[4];
    if(!PyArg_ParseTuple(
	   args,
	   "Oiii|iii",
	   &pyAllocation,
	   &n_indexes,
	   &val,
	   &indexes[0], &indexes[1], &indexes[2], &indexes[3]))
    {
	return NULL;
    }

    void *allocation = PyCObject_AsVoidPtr(pyAllocation);
    if(allocation == NULL)
    {
	return NULL;
    }

    int retval = array_set_int(allocation, n_indexes, indexes, val);

    PyObject *pyRet = Py_BuildValue("i",retval);

    return pyRet;
}

static PyMethodDef PfMethods[] = {
    {"pf_load",  pf_load, METH_VARARGS,
     "Load a new point function shared library"},
    {"pf_create", pf_create, METH_VARARGS,
     "Create a new point function"},
    {"pf_init", pf_init, METH_VARARGS,
     "Init a point function"},
    {"pf_calc", pf_calc, METH_VARARGS,
     "Calculate one point"},
    {"pf_defaults", pf_defaults, METH_VARARGS,
     "Get defaults for this formula"},

    { "cmap_create", cmap_create, METH_VARARGS,
      "Create a new colormap"},
    { "cmap_create_gradient", cmap_create_gradient, METH_VARARGS,
      "Create a new gradient-based colormap"},
    { "cmap_lookup", cmap_pylookup, METH_VARARGS,
      "Get a color tuple from a distance value"},
    { "cmap_lookup_flags", cmap_pylookup_with_flags, METH_VARARGS,
      "Get a color tuple from a distance value and solid/inside flags"},
    { "cmap_set_solid", pycmap_set_solid, METH_VARARGS,
      "Set the inner or outer solid color"},
    { "cmap_set_transfer", pycmap_set_transfer, METH_VARARGS,
      "Set the inner or outer transfer function"},

    { "rgb_to_hsv", pyrgb_to_hsv, METH_VARARGS,
      "Convert a rgb(a) list into an hsv(a) one"},
    { "rgb_to_hsl", pyrgb_to_hsl, METH_VARARGS,
      "Convert a rgb(a) list into an hls(a) one"},
    { "hsl_to_rgb", pyhsl_to_rgb, METH_VARARGS,
      "Convert an hls(a) list into an rgb(a) one"},

    { "image_create", image_create, METH_VARARGS,
      "Create a new image buffer"},
    { "image_resize", image_resize, METH_VARARGS,
      "Change image dimensions - data is deleted" },
    { "image_set_offset", image_set_offset, METH_VARARGS,
      "set the image tile's offset" },
    { "image_dims", image_dims, METH_VARARGS,
      "get a tuple containing image's dimensions"},
    { "image_clear", image_clear, METH_VARARGS,
      "Clear all iteration and color data from image" },

    { "image_writer_create", image_writer_create, METH_VARARGS,
      "create an object used to write image to disk" },

    { "image_save_header", image_save_header, METH_VARARGS,
      "save an image header - useful for render-to-disk"},
    { "image_save_tile", image_save_tile, METH_VARARGS,
      "save an image fragment ('tile') - useful for render-to-disk"},
    { "image_save_footer", image_save_footer, METH_VARARGS,
      "save the final footer info for an image - useful for render-to-disk"},

    { "image_read", image_read, METH_VARARGS,
      "read an image in from disk"},

    { "image_buffer", image_buffer, METH_VARARGS,
      "get the rgb data from the image"},
    { "image_fate_buffer", image_fate_buffer, METH_VARARGS,
      "get the fate data from the image"},

    { "image_get_color_index", image_get_color_index, METH_VARARGS,
      "Get the color index data from a point on the image"},
    { "image_get_fate", image_get_fate, METH_VARARGS,
      "Get the (solid, fate) info for a point on the image"},

    { "image_lookup", pyimage_lookup, METH_VARARGS,
      "Get the color of a point on an image"},

    { "site_create", pysite_create, METH_VARARGS,
      "Create a new site"},
    { "fdsite_create", pyfdsite_create, METH_VARARGS,
      "Create a new file-descriptor site"},

    { "ff_create", ff_create, METH_VARARGS,
      "Create a fractFunc." },
    { "ff_look_vector", ff_look_vector, METH_VARARGS,
      "Get a vector from the eye to a point on the screen" },
    { "ff_get_vector", ff_get_vector, METH_VARARGS,
      "Get a vector inside the ff" },

    { "fw_create", fw_create, METH_VARARGS,
      "Create a fractWorker." },
    { "fw_pixel", fw_pixel, METH_VARARGS,
      "Draw a single pixel." },
    { "fw_pixel_aa", fw_pixel_aa, METH_VARARGS,
      "Draw a single pixel." },
    { "fw_find_root", fw_find_root, METH_VARARGS,
      "Find closest root considering fractal function along a vector"},

    { "calc", (PyCFunction) pycalc, METH_VARARGS | METH_KEYWORDS,
      "Calculate a fractal image"},

    { "interrupt", pystop_calc, METH_VARARGS,
      "Stop an async calculation" },

    { "rot_matrix", rot_matrix, METH_VARARGS,
      "Return a rotated and scaled identity matrix based on params"},

    { "eye_vector", eye_vector, METH_VARARGS,
      "Return the line between the user's eye and the center of the screen"},

    { "arena_create", pyarena_create, METH_VARARGS,
      "Create a new arena allocator" },
    { "arena_alloc", pyarena_alloc, METH_VARARGS,
      "Allocate a chunk of memory from the arena" },

    { "array_get_int", pyarray_get, METH_VARARGS,
      "Get an element from an array allocated in an arena" },

    { "array_set_int", pyarray_set, METH_VARARGS,
      "Set an element in an array allocated in an arena" },

    {NULL, NULL, 0, NULL}        /* Sentinel */
};

extern "C" PyMODINIT_FUNC
#ifdef USE_GMP
initfract4dcgmp(void)
#else
initfract4dc(void)
#endif
{
    pymod = Py_InitModule(MODULE_NAME, PfMethods);

#ifdef THREADS
    PyEval_InitThreads();
#endif

#ifdef USE_GMP
    mpf_t x;
    mpf_init(x);
#endif
    /* expose some constants */
    PyModule_AddIntConstant(pymod, "CALC_DONE", GF4D_FRACTAL_DONE);
    PyModule_AddIntConstant(pymod, "CALC_CALCULATING", GF4D_FRACTAL_CALCULATING);
    PyModule_AddIntConstant(pymod, "CALC_DEEPENING", GF4D_FRACTAL_DEEPENING);
    PyModule_AddIntConstant(pymod, "CALC_ANTIALIASING", GF4D_FRACTAL_ANTIALIASING);
    PyModule_AddIntConstant(pymod, "CALC_PAUSED", GF4D_FRACTAL_PAUSED);

    PyModule_AddIntConstant(pymod, "AA_NONE", AA_NONE);
    PyModule_AddIntConstant(pymod, "AA_FAST", AA_FAST);
    PyModule_AddIntConstant(pymod, "AA_BEST", AA_BEST);

    PyModule_AddIntConstant(pymod, "RENDER_TWO_D", RENDER_TWO_D);
    PyModule_AddIntConstant(pymod, "RENDER_LANDSCAPE", RENDER_LANDSCAPE);
    PyModule_AddIntConstant(pymod, "RENDER_THREE_D", RENDER_THREE_D);

    PyModule_AddIntConstant(pymod, "DRAW_GUESSING", DRAW_GUESSING);
    PyModule_AddIntConstant(pymod, "DRAW_TO_DISK", DRAW_TO_DISK);

    PyModule_AddIntConstant(pymod, "DELTA_X", DELTA_X);
    PyModule_AddIntConstant(pymod, "DELTA_Y", DELTA_Y);
    PyModule_AddIntConstant(pymod, "TOPLEFT", TOPLEFT);

    /* cf image_dims */
    PyModule_AddIntConstant(pymod, "IMAGE_WIDTH", 0);
    PyModule_AddIntConstant(pymod, "IMAGE_HEIGHT", 1);
    PyModule_AddIntConstant(pymod, "IMAGE_TOTAL_WIDTH", 2);
    PyModule_AddIntConstant(pymod, "IMAGE_TOTAL_HEIGHT", 3);
    PyModule_AddIntConstant(pymod, "IMAGE_XOFFSET", 4);
    PyModule_AddIntConstant(pymod, "IMAGE_YOFFSET", 5);

    /* image type consts */
    PyModule_AddIntConstant(pymod, "FILE_TYPE_TGA", FILE_TYPE_TGA);
    PyModule_AddIntConstant(pymod, "FILE_TYPE_PNG", FILE_TYPE_PNG);
    PyModule_AddIntConstant(pymod, "FILE_TYPE_JPG", FILE_TYPE_JPG);

    /* message type consts */
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_ITERS", ITERS);
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_IMAGE", IMAGE);
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_PROGRESS", PROGRESS);
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_STATUS", STATUS);
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_PIXEL", PIXEL);
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_TOLERANCE", TOLERANCE);
    PyModule_AddIntConstant(pymod, "MESSAGE_TYPE_STATS", STATS);
}


text:
using vm.Aspects.Diagnostics;

namespace vm.Aspects.Wcf.FaultContracts.Metadata
{
    abstract class XmlFaultMetadata
    {
        [Dump(0)]
        public object SourceUri { get; set; }

        [Dump(1)]
        public object LineNumber { get; set; }

        [Dump(2)]
        public object LinePosition { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<form class="form form-discount order-comment-form" data-bind="mageInit: { 'validation':[]}">

                <textarea class="input-text order-comment order-comment-input" name="comment-code" rows="4" data-bind="value: comment,valueUpdate: 'afterkeydown',attr:{placeholder: $t('Enter your comment...')} " ></textarea>

</form>


text:
import * as React from "react";
import RichTextEditor, { EditorValue } from "react-rte";

interface Props {
    onChange?: ((val: string) => void) | undefined;
}

class MyStatefulEditor extends React.Component<Props, any> {
  state = {
    value: RichTextEditor.createEmptyValue()
  };

  onChange = (value: EditorValue) => {
    this.setState({value});
    if (this.props.onChange) {
      // Send the changes up to the parent component as an HTML string.
      // This is here to demonstrate using `.toString()` but in a real app it
      // would be better to avoid generating a string on each change.
      this.props.onChange(
        value.toString('html')
      );
    }
  }

  render() {
    return (
      <RichTextEditor
        value={this.state.value}
        onChange={this.onChange}
      />
    );
  }
}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE)
{
    require_once(APPPATH."helpers/dompdf/dompdf_config.inc.php");
	// need to enable magic quotes for the
	$magic_quotes_enabled = get_magic_quotes_runtime();
    if(!$magic_quotes_enabled)
    {
    	ini_set("magic_quotes_runtime", true);
    }

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    ini_set("magic_quotes_runtime", $magic_quotes_enabled);

    if ($stream) {
        $dompdf->stream($filename.".pdf");
    } else {
        return $dompdf->output();
    }
}
?>


text:
using System.IO;
using System.Threading.Tasks;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using UnitTestHelpers;

namespace DynamicRestProxy.PortableHttpClient.UnitTests
{
    [TestClass]
    [DeploymentItem(@"MockResponses\")]
    public class FlickrTests
    {
        [TestMethod]
        [TestCategory("portable-client")]
        [TestCategory("flickr")]
        [TestCategory("integration")]
        public async Task FindUserByName()
        {
            var key = CredentialStore.RetrieveObject("flickr.key.json");
            var defaults = new DynamicRestClientDefaults();
            defaults.DefaultParameters.Add("format", "json");
            defaults.DefaultParameters.Add("api_key", key.Key);
            defaults.DefaultParameters.Add("nojsoncallback", "1");

            using (dynamic client = new DynamicRestClient("https://api.flickr.com/services/rest/", MockInitialization.Handler, false, defaults))
            {
                dynamic result = await client.get(method: "flickr.people.findByUsername", username: "dkackman");
                Assert.IsNotNull(result);
                Assert.AreEqual("9039518@N03", result.user.id);
            }
        }

        [TestMethod]
        [TestCategory("portable-client")]
        [TestCategory("integration")]
        [TestCategory("flickr")]
        [Ignore]
        public async Task UploadPhoto()
        {
            var key = CredentialStore.RetrieveObject("flickr.key.json");
            var defaults = new DynamicRestClientDefaults();
            defaults.DefaultParameters.Add("format", "json");
            defaults.DefaultParameters.Add("api_key", key.Key);
            defaults.DefaultParameters.Add("nojsoncallback", "1");

            using (dynamic client = new DynamicRestClient("https://up.flickr.com/services/", MockInitialization.Handler, false, defaults))
            {
                dynamic result = await client.upload.post(photo: File.OpenRead(@"D:\temp\test.png"));

                Assert.IsNotNull(result);
            }
        }
    }
}


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.WindowsAzure;

namespace Microsoft.Azure.Management.DataFactories.Models
{
    /// <summary>
    /// The Get data factory gateway operation response.
    /// </summary>
    public partial class GatewayGetResponse : OperationResponse
    {
        private Gateway _gateway;

        /// <summary>
        /// Optional. The data factory gateway information.
        /// </summary>
        public Gateway Gateway
        {
            get { return this._gateway; }
            set { this._gateway = value; }
        }

        /// <summary>
        /// Initializes a new instance of the GatewayGetResponse class.
        /// </summary>
        public GatewayGetResponse()
        {
        }
    }
}


text:
/**
 * @fileoverview Generating JavaScript for text blocks.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.JavaScript.sensors');

goog.require('Blockly.JavaScript');

Blockly.JavaScript['sensor_ultrasonic'] = function(block) {
  // Text value.
  var port = block.getFieldValue('PORT');
  var code = "getSensorValue('ultrasonic',"+port.split('PORT')[1]+")";
  return [code, Blockly.JavaScript.ORDER_ATOMIC];
};

Blockly.JavaScript['sensor_light'] = function(block) {
  // Text value.
  var port = block.getFieldValue('PORT');
  var code = "getSensorValue('light',"+port.split('PORT')[1]+")";
  return [code, Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['sensor_linefollower'] = function(block) {
  // Text value.
  var port = block.getFieldValue('PORT');
  var code = "getSensorValue('linefollower',"+port.split('PORT')[1]+")";
  return [code, Blockly.JavaScript.ORDER_ATOMIC];
};


text:
var mercury = require('mercury');
var insertCss = require('insert-css');

var h = mercury.h;

var css = require('./index.css');

var BUG_REPORT_URL = 'https://github.com/vanadium/browser/issues/new';

var BUG_REPORT_ICON = 'bug-report';

module.exports = create;
module.exports.render = render;
module.exports.BUG_REPORT_URL = BUG_REPORT_URL;
module.exports.BUG_REPORT_ICON = BUG_REPORT_ICON;

function create() {}

function render() {
  insertCss(css);

  var reportBugAction = h('core-tooltip', {
      'label': 'Report a bug or suggest features',
      'position': 'right'
    },
    h('a', {
      'href': BUG_REPORT_URL,
      'target': '_blank'
    }, h('paper-icon-button.icon', {
      attributes: {
        'icon': BUG_REPORT_ICON
      }
    }))
  );
  return h('div.bug-reporter', reportBugAction);
}


text:
namespace mos::gl {

struct Bloom_program : public Program {
  friend class Renderer;
private:
  Bloom_program();
public:
  GLint color_sampler;
};
}


text:
package by.vorokhobko.servletwithuser.servlets;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * AuthFilter.
 *
 * Class AuthFilter is the part of the work with web-service with control user entered part 004, lesson 6.
 * @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
 * @since 27.02.2018.
 * @version 1.
 */
public class AuthFilter implements Filter {
    /**
     * The method starts working with the database.
     * @param filterConfig - filterConfig.
     */
    @Override
    public void init(FilterConfig filterConfig) {
    }
    /**
     * The method handle a doFilter request.
     * @param servletRequest - servletRequest.
     * @param servletResponse - servletResponse.
     * @param filterChain - filterChain.
     * @throws IOException tag.
     * @throws ServletException tag.
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (request.getRequestURI().contains("/control")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpSession session = request.getSession();
            if (session.getAttribute("login") == null) {
                ((HttpServletResponse) servletResponse).sendRedirect(String.format("%s/control", request.getContextPath()));
                return;
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    /**
     * The method closes working with the database.
     */
    @Override
    public void destroy() {
    }
}


text:
/* Button Boxes
 *
 * The Button Box widgets are used to arrange buttons with padding.
 */

#include <gtk/gtk.h>

static GtkWidget *
create_bbox (gint  horizontal,
	     char *title,
	     gint  spacing,
	     gint  layout)
{
  GtkWidget *frame;
  GtkWidget *bbox;
  GtkWidget *button;

  frame = gtk_frame_new (title);

  if (horizontal)
    bbox = gtk_hbutton_box_new ();
  else
    bbox = gtk_vbutton_box_new ();

  gtk_container_set_border_width (GTK_CONTAINER (bbox), 5);
  gtk_container_add (GTK_CONTAINER (frame), bbox);

  gtk_button_box_set_layout (GTK_BUTTON_BOX (bbox), layout);
  gtk_box_set_spacing (GTK_BOX (bbox), spacing);

  button = gtk_button_new_from_stock (GTK_STOCK_OK);
  gtk_container_add (GTK_CONTAINER (bbox), button);

  button = gtk_button_new_from_stock (GTK_STOCK_CANCEL);
  gtk_container_add (GTK_CONTAINER (bbox), button);

  button = gtk_button_new_from_stock (GTK_STOCK_HELP);
  gtk_container_add (GTK_CONTAINER (bbox), button);

  return frame;
}

GtkWidget *
do_button_box (GtkWidget *do_widget)
{
  static GtkWidget *window = NULL;
  GtkWidget *main_vbox;
  GtkWidget *vbox;
  GtkWidget *hbox;
  GtkWidget *frame_horz;
  GtkWidget *frame_vert;

  if (!window)
  {
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_screen (GTK_WINDOW (window),
			   gtk_widget_get_screen (do_widget));
    gtk_window_set_title (GTK_WINDOW (window), "Button Boxes");

    g_signal_connect (window, "destroy",
		      G_CALLBACK (gtk_widget_destroyed),
		      &window);

    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    main_vbox = gtk_vbox_new (FALSE, 0);
    gtk_container_add (GTK_CONTAINER (window), main_vbox);

    frame_horz = gtk_frame_new ("Horizontal Button Boxes");
    gtk_box_pack_start (GTK_BOX (main_vbox), frame_horz, TRUE, TRUE, 10);

    vbox = gtk_vbox_new (FALSE, 0);
    gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
    gtk_container_add (GTK_CONTAINER (frame_horz), vbox);

    gtk_box_pack_start (GTK_BOX (vbox),
			create_bbox (TRUE, "Spread", 40, GTK_BUTTONBOX_SPREAD),
			TRUE, TRUE, 0);

    gtk_box_pack_start (GTK_BOX (vbox),
			create_bbox (TRUE, "Edge", 40, GTK_BUTTONBOX_EDGE),
			TRUE, TRUE, 5);

    gtk_box_pack_start (GTK_BOX (vbox),
			create_bbox (TRUE, "Start", 40, GTK_BUTTONBOX_START),
			TRUE, TRUE, 5);

    gtk_box_pack_start (GTK_BOX (vbox),
			create_bbox (TRUE, "End", 40, GTK_BUTTONBOX_END),
			TRUE, TRUE, 5);

    frame_vert = gtk_frame_new ("Vertical Button Boxes");
    gtk_box_pack_start (GTK_BOX (main_vbox), frame_vert, TRUE, TRUE, 10);

    hbox = gtk_hbox_new (FALSE, 0);
    gtk_container_set_border_width (GTK_CONTAINER (hbox), 10);
    gtk_container_add (GTK_CONTAINER (frame_vert), hbox);

    gtk_box_pack_start (GTK_BOX (hbox),
			create_bbox (FALSE, "Spread", 30, GTK_BUTTONBOX_SPREAD),
			TRUE, TRUE, 0);

    gtk_box_pack_start (GTK_BOX (hbox),
			create_bbox (FALSE, "Edge", 30, GTK_BUTTONBOX_EDGE),
			TRUE, TRUE, 5);

    gtk_box_pack_start (GTK_BOX (hbox),
			create_bbox (FALSE, "Start", 30, GTK_BUTTONBOX_START),
			TRUE, TRUE, 5);

    gtk_box_pack_start (GTK_BOX (hbox),
			create_bbox (FALSE, "End", 30, GTK_BUTTONBOX_END),
			TRUE, TRUE, 5);
  }

  if (!gtk_widget_get_visible (window))
    {
      gtk_widget_show_all (window);
    }
  else
    {
      gtk_widget_destroy (window);
      window = NULL;
    }

  return window;
}


text:
{% extends "tool_base.html" %}

{% block title %}{{ _('Run the Activity') }}{% endblock %}

{% block custom_css %}
  <link href="{{ url_for('static', filename='css/wordcounter.scss.css') }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block nav %}
  {% include 'tool_header.html' %}
{% endblock %}

{% block body %}

{{ _('Sketch a Story') }}

{{ _('Welcome to the WordCounter Sketch a Story activity! These videos will help you run the activity.')}}

{{ _('We\'re ready to start') }}

{{ _('Done with our stories! Time to share-back!') }}

{{ _('All done. What next?') }}

{% endblock %}


text:
package template

import (
	"fmt"
	"regexp"
	"strings"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/meta"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util/fielderrors"

	"github.com/openshift/origin/pkg/template/api"
	. "github.com/openshift/origin/pkg/template/generator"
	"github.com/openshift/origin/pkg/util"
	"github.com/openshift/origin/pkg/util/stringreplace"
)

var parameterExp = regexp.MustCompile(`\$\{([a-zA-Z0-9\_]+)\}`)

// Processor process the Template into the List with substituted parameters
type Processor struct {
	Generators map[string]Generator
}

// NewProcessor creates new Processor and initializes its set of generators.
func NewProcessor(generators map[string]Generator) *Processor {
	return &Processor{Generators: generators}
}

// Process transforms Template object into List object. It generates
// Parameter values using the defined set of generators first, and then it
// substitutes all Parameter expression occurrences with their corresponding
// values (currently in the containers' Environment variables only).
func (p *Processor) Process(template *api.Template) fielderrors.ValidationErrorList {
	templateErrors := fielderrors.ValidationErrorList{}

	if err := p.GenerateParameterValues(template); err != nil {
		return append(templateErrors.Prefix("Template"), fielderrors.NewFieldInvalid("parameters", err, "failure to generate parameter value"))
	}

	for i, item := range template.Objects {
		if obj, ok := item.(*runtime.Unknown); ok {
			// TODO: use runtime.DecodeList when it returns ValidationErrorList
			obj, err := runtime.UnstructuredJSONScheme.Decode(obj.RawJSON)
			if err != nil {
				util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("objects", err, "unable to handle object"))
				continue
			}
			item = obj
		}

		newItem, err := p.SubstituteParameters(template.Parameters, item)
		if err != nil {
			util.ReportError(&templateErrors, i, *fielderrors.NewFieldNotSupported("parameters", err))
		}
		stripNamespace(newItem)
		if err := addLabels(newItem, template.ObjectLabels); err != nil {
			util.ReportError(&templateErrors, i, *fielderrors.NewFieldInvalid("labels", err, "label could not be applied"))
		}
		template.Objects[i] = newItem
	}

	return templateErrors
}

func stripNamespace(obj runtime.Object) {
	// Remove namespace from the item
	if itemMeta, err := meta.Accessor(obj); err == nil {
		itemMeta.SetNamespace("")
		return
	}
	// TODO: allow meta.Accessor to handle runtime.Unstructured
	if unstruct, ok := obj.(*runtime.Unstructured); ok && unstruct.Object != nil {
		if obj, ok := unstruct.Object["metadata"]; ok {
			if m, ok := obj.(map[string]interface{}); ok {
				if _, ok := m["namespace"]; ok {
					m["namespace"] = ""
				}
			}
			return
		}
		if _, ok := unstruct.Object["namespace"]; ok {
			unstruct.Object["namespace"] = ""
			return
		}
	}
}

func addLabels(obj runtime.Object, labels map[string]string) error {
	if labels == nil {
		return nil
	}

	// Remove namespace from the item
	if meta, err := meta.Accessor(obj); err == nil {
		existing := meta.Labels()
		if existing == nil {
			existing = make(map[string]string)
		}
		if err := util.MergeInto(existing, labels, util.OverwriteExistingDstKey); err != nil {
			return err
		}
		meta.SetLabels(existing)
		return nil
	}
	// TODO: allow meta.Accessor to handle runtime.Unstructured
	if unstruct, ok := obj.(*runtime.Unstructured); ok && unstruct.Object != nil {
		// the presence of "metadata" is sufficient for us to apply the rules for Kube-like
		// objects.
		// TODO: add swagger detection to allow this to happen more effectively
		if obj, ok := unstruct.Object["metadata"]; ok {
			if m, ok := obj.(map[string]interface{}); ok {

				existing := make(map[string]string)
				if l, ok := m["labels"]; ok {
					if found, ok := extractLabels(l); ok {
						existing = found
					}
				}
				if err := util.MergeInto(existing, labels, util.OverwriteExistingDstKey); err != nil {
					return err
				}
				m["labels"] = mapToGeneric(existing)
			}
			return nil
		}

		// only attempt to set root labels if a root object called labels exists
		// TODO: add swagger detection to allow this to happen more effectively
		if obj, ok := unstruct.Object["labels"]; ok {
			existing := make(map[string]string)
			if found, ok := extractLabels(obj); ok {
				existing = found
			}
			if err := util.MergeInto(existing, labels, util.OverwriteExistingDstKey); err != nil {
				return err
			}
			unstruct.Object["labels"] = mapToGeneric(existing)
			return nil
		}
	}
	return nil
}

// extractLabels extracts a map[string]string from a map[string]interface{}
func extractLabels(obj interface{}) (map[string]string, bool) {
	lm, ok := obj.(map[string]interface{})
	if !ok {
		return nil, false
	}
	existing := make(map[string]string)
	for k, v := range lm {
		switch t := v.(type) {
		case string:
			existing[k] = t
		}
	}
	return existing, true
}

// mapToGeneric converts a map[string]string into a map[string]interface{}
func mapToGeneric(obj map[string]string) map[string]interface{} {
	if obj == nil {
		return nil
	}
	res := make(map[string]interface{})
	for k, v := range obj {
		res[k] = v
	}
	return res
}

// AddParameter adds new custom parameter to the Template. It overrides
// the existing parameter, if already defined.
func AddParameter(t *api.Template, param api.Parameter) {
	if existing := GetParameterByName(t, param.Name); existing != nil {
		*existing = param
	} else {
		t.Parameters = append(t.Parameters, param)
	}
}

// GetParameterByName searches for a Parameter in the Template
// based on its name.
func GetParameterByName(t *api.Template, name string) *api.Parameter {
	for i, param := range t.Parameters {
		if param.Name == name {
			return &(t.Parameters[i])
		}
	}
	return nil
}

// SubstituteParameters loops over all values defined in structured
// and unstructured types that are children of item.
//
// Example of Parameter expression:
//   - ${PARAMETER_NAME}
//
func (p *Processor) SubstituteParameters(params []api.Parameter, item runtime.Object) (runtime.Object, error) {
	// Make searching for given parameter name/value more effective
	paramMap := make(map[string]string, len(params))
	for _, param := range params {
		paramMap[param.Name] = param.Value
	}

	stringreplace.VisitObjectStrings(item, func(in string) string {
		for _, match := range parameterExp.FindAllStringSubmatch(in, -1) {
			if len(match) > 1 {
				if paramValue, found := paramMap[match[1]]; found {
					in = strings.Replace(in, match[0], paramValue, 1)
				}
			}
		}
		return in
	})

	return item, nil
}

// GenerateParameterValues generates Value for each Parameter of the given
// Template that has Generate field specified where Value is not already
// supplied.
//
// Examples:
//
// from             | value
// -----------------------------
// "test[0-9]{1}x"  | "test7x"
// "[0-1]{8}"       | "01001100"
// "0x[A-F0-9]{4}"  | "0xB3AF"
// "[a-zA-Z0-9]{8}" | "hW4yQU5i"
func (p *Processor) GenerateParameterValues(t *api.Template) error {
	for i := range t.Parameters {
		param := &t.Parameters[i]
		if len(param.Value) > 0 {
			continue
		}
		if param.Generate != "" {
			generator, ok := p.Generators[param.Generate]
			if !ok {
				return fmt.Errorf("template.parameters[%v]: Unable to find the '%v' generator", i, param.Generate)
			}
			if generator == nil {
				return fmt.Errorf("template.parameters[%v]: Invalid '%v' generator", i, param.Generate)
			}
			value, err := generator.GenerateValue(param.From)
			if err != nil {
				return err
			}
			param.Value, ok = value.(string)
			if !ok {
				return fmt.Errorf("template.parameters[%v]: Unable to convert the generated value '%#v' to string", i, value)
			}
		}
	}
	return nil
}


text:
/**
 * \file
 * \brief Rudimentary ELF32 loader and handling routines.
 */

/*
 * Copyright (c) 2007, 2008, 2009, 2010, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

#include "elf.h"

/**
 * \brief Return pointer to relocation section ELF header.
 *
 * This function finds and returns a pointer to the first ELF section
 * header of type 'type'.
 *
 * \param shdr          Pointer to head of ELF section header table.
 * \param entries       Number of entries in the ELF section header table.
 * \param type          ELF section header type to look for.
 *
 * \return Pointer to first ELF section header of type 'type', or NULL.
 */
struct Elf32_Shdr *
elf32_find_section_header_type(struct Elf32_Shdr *shdr,
                               uint32_t entries, uint32_t type)
{
    int i;

    for(i = 0; i < entries; i++) {
        struct Elf32_Shdr *s = &shdr[i];

        if(s->sh_type == type) {
            return s;
        }
    }

    return NULL;
}

/**
 * \brief Return pointer to relocation section ELF header.
 *
 * This function finds and returns a pointer to the first ELF section
 * header at virtual address 'addr'.
 *
 * \param shdr          Pointer to head of ELF section header table.
 * \param entries       Number of entries in the ELF section header table.
 * \param addr          Virtual address to look for
 *
 * \return Pointer to first ELF section header loaded at 'addr', or NULL.
 */
static struct Elf32_Shdr *
elf32_find_section_header_vaddr(struct Elf32_Shdr *shdr,
                                uint32_t entries, genvaddr_t addr)
{
    int i;

    for(i = 0; i < entries; i++) {
        struct Elf32_Shdr *s = &shdr[i];

        if(s->sh_addr == addr) {
            return s;
        }
    }

    return NULL;
}

/**
 * \brief Relocates the ELF image from src to dst.
 *
 * This function processes the ELF relocation section 'rela' of size 'size' of
 * the ELF image, formerly located at 'src', to the new location 'dst'.
 * Relocation is necessary for certain variables that cannot be coded as
 * position-independent code.
 *
 * \param dst           Address to relocate to.
 * \param src           Former base address of the ELF image.
 * \param rela          Pointer to relocation section of the ELF image.
 * \param size          Size in bytes of the ELF relocation section.
 * \param symtab        Pointer to ELF symbol table.
 * \param symsize       Size in bytes of the ELF symbol table.
 * \param start         Original base address of the ELF image.
 * \param vbase         Pointer to ELF image in virtual memory.
 */
void elf32_relocate(genvaddr_t dst, genvaddr_t src,
                    struct Elf32_Rel *rel, size_t size,
                    struct Elf32_Sym *symtab, size_t symsize,
                    genvaddr_t start, void *vbase)
{
    genvaddr_t base = dst - src, abase = dst - start;

    for(int i = 0; i < size / sizeof(struct Elf32_Rel); i++) {
        struct Elf32_Rel *r = &rel[i];
        uint32_t type = ELF32_R_TYPE(r->r_info);
        uint32_t *addr = vbase + r->r_offset - start;

        switch(type) {
        case R_386_32:
            {
                uint32_t sym = ELF32_R_SYM(r->r_info);
                assert(sym < symsize / sizeof(struct Elf32_Sym));
                /* assert(symtab[sym].st_value != 0); */
                *addr = abase + symtab[sym].st_value;
            }
            break;

        case R_386_RELATIVE:
            *addr += base;
            break;

        default:
            printf("elf_relocate: relocation %d type %d\n", i, type);
            assert(!"Unimplemented: Cannot handle relocation type");
            break;
        }
    }
}

/**
 * \brief Load ELF64 binary image into memory
 *
 * This function loads an ELF64 binary image, based at 'base' and of size
 * 'size' into the memory provided by 'allocate'
 *
 * \param allocate      Memory allocation function.
 * \param state         Pointer to state for allocation function.
 * \param base          Base address of ELF64 binary image in memory.
 * \param size          Size of ELF64 binary image in bytes.
 * \param retentry      Used to return entry point address
 */
errval_t elf32_load(elf_allocator_fn allocate_func, void *state, lvaddr_t base,
                    size_t size, genvaddr_t *retentry)
{
    struct Elf32_Ehdr *head = (struct Elf32_Ehdr *)base;
    errval_t err;
    int i;

    // Check for valid file size
    if (size < sizeof(struct Elf32_Ehdr)) {
        return -1;
    }

    // Check for compatible ELF32 header
    if (!IS_ELF(*head)
        || head->e_ident[EI_CLASS] != ELFCLASS32
        || head->e_ident[EI_DATA] != ELFDATA2LSB
        || head->e_ident[EI_VERSION] != EV_CURRENT
        || head->e_ident[EI_OSABI] != ELFOSABI_SYSV
        || head->e_ident[EI_ABIVERSION] != 0
        || (head->e_type != ET_EXEC && head->e_type != ET_DYN)
        || head->e_machine != EM_386
        || head->e_version != EV_CURRENT) {
        return -2;
    }

    // More sanity checks
    if (head->e_phoff + head->e_phentsize * head->e_phnum > size
        || head->e_phentsize != sizeof(struct Elf32_Phdr)) {
        return -3;
    }

    struct Elf32_Shdr *shead =
        (struct Elf32_Shdr *)(base + (uintptr_t)head->e_shoff);
    struct Elf32_Shdr *rela =
        elf32_find_section_header_type(shead, head->e_shnum, SHT_REL);
    struct Elf32_Shdr *symtab =
        elf32_find_section_header_type(shead, head->e_shnum, SHT_SYMTAB);

    size_t rela_size = rela ? rela->sh_size : 0, new_rela_size = 0;
    struct Elf32_Shdr *new_rela = NULL;

    // Find dynamic program header, if any
    struct Elf32_Phdr *phead =
        (struct Elf32_Phdr *)(base + (uintptr_t)head->e_phoff);
    for (i = 0; i < head->e_phnum; i++) {
        struct Elf32_Phdr *p = &phead[i];

        if (p->p_type == PT_DYNAMIC) {
            struct Elf32_Dyn *dynamic = (void *)(base + (uintptr_t)p->p_offset);
            int n_dynamic = p->p_filesz / sizeof(struct Elf32_Dyn);
            for (int j = 0; j < n_dynamic; j++) {
                switch (dynamic[j].d_tag) {
                case DT_RELA:
                    // virtual address of relocations, look for matching section
                    new_rela =
                        elf32_find_section_header_vaddr(shead, head->e_shnum,
                                                        dynamic[j].d_un.d_val);
                    break;

                case DT_RELASZ:
                    // store size of relocations, as they may cover more than
                    // one section
                    new_rela_size = dynamic[j].d_un.d_val;
                    break;

                case DT_SYMTAB:
                    // virtual address of symtab, look for matching section
                    symtab =
                        elf32_find_section_header_vaddr(shead, head->e_shnum,
                                                        dynamic[j].d_un.d_val);
                    break;

                case DT_SYMENT:
                    assert(dynamic[j].d_un.d_val == sizeof(struct Elf32_Sym));
                    break;
                }
            }

            if (new_rela != NULL) {
                assert(new_rela_size != 0);
                rela = new_rela;
                rela_size = new_rela_size;
            }
            break;
        }
    }

    // Process program headers to load file
    for (i = 0; i < head->e_phnum; i++) {
        struct Elf32_Phdr *p = &phead[i];

        if (p->p_type == PT_LOAD) {
            //printf("Loading segment: start=0x%lx, size=%lu, flags=%d\n",
            //       p->p_vaddr, p->p_memsz, p->p_flags);

            // Map segment in user-space memory
            void *dest = NULL;
            err = allocate_func(state, (genvaddr_t)p->p_vaddr,
                                p->p_memsz, p->p_flags, &dest);
            if (err != 0) {
                return -4;
            }
            assert(dest != NULL);

            // Copy file segment into memory
            memcpy(dest, (void *)(base + (uintptr_t)p->p_offset), p->p_filesz);

            // Initialize rest of memory segment (ie. BSS) with all zeroes
            memset(dest + p->p_filesz, 0, p->p_memsz - p->p_filesz);

            // Apply relocations
            if (rela != NULL && symtab != NULL) {
                elf32_relocate(p->p_vaddr, p->p_vaddr,
                               (struct Elf32_Rel *)
                               (base + (uintptr_t)rela->sh_offset),
                               rela_size,
                               (struct Elf32_Sym *)
                               (base + (uintptr_t)symtab->sh_offset),
                               symtab->sh_size, p->p_vaddr, dest);
            }
        }
    }

    if (retentry != NULL) {
        *retentry = head->e_entry;
    }

    return 0;
}


text:
package org.apache.harmony.nio.internal;

import java.io.FileDescriptor;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketImpl;
import java.net.SocketTimeoutException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.NotYetBoundException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;

import org.apache.harmony.luni.net.NetUtil;
import org.apache.harmony.luni.net.SocketImplProvider;
import org.apache.harmony.luni.platform.FileDescriptorHandler;
import org.apache.harmony.luni.platform.Platform;

/*
 * The default implementation class of java.nio.channels.ServerSocketChannel.
 */
public class ServerSocketChannelImpl extends ServerSocketChannel implements
        FileDescriptorHandler {

    // ----------------------------------------------------
    // Class variables
    // ----------------------------------------------------

    // status un-init, not initialized.
    private static final int SERVER_STATUS_UNINIT = -1;

    // status after open and before closed.
    private static final int SERVER_STATUS_OPEN = 0;

    // status closed.
    private static final int SERVER_STATUS_CLOSED = 1;

    // -------------------------------------------------------------------
    // Instance variables
    // -------------------------------------------------------------------

    // The fd to interact with native code
    private final FileDescriptor fd;

    // The internal ServerSocket
    private final ServerSocket socket;

    private final SocketImpl impl;

    int status = SERVER_STATUS_UNINIT;

    // whether the socket is bound
    boolean isBound = false;

    // lock for accept
    private class AcceptLock {}
    private final Object acceptLock = new AcceptLock();

    // ----------------------------------------------------
    // Constructor
    // ----------------------------------------------------

    /*
     * Constructor
     */
    public ServerSocketChannelImpl(SelectorProvider sp) throws IOException {
        super(sp);
        status = SERVER_STATUS_OPEN;
        fd = new FileDescriptor();
        Platform.getNetworkSystem().createServerStreamSocket(fd,
                NetUtil.preferIPv4Stack());
        impl = SocketImplProvider.getServerSocketImpl(fd);
        socket = new ServerSocketAdapter(impl, this);
    }

    // for native call
    private ServerSocketChannelImpl() throws IOException {
        super(SelectorProvider.provider());
        status = SERVER_STATUS_OPEN;
        fd = new FileDescriptor();
        impl = SocketImplProvider.getServerSocketImpl(fd);
        socket = new ServerSocketAdapter(impl, this);
        isBound = false;
    }

    // ----------------------------------------------------
    // Methods
    // ----------------------------------------------------

    /*
     * Getting the internal Socket If we have not the socket, we create a new
     * one.
     */
    public ServerSocket socket() {
        return socket;
    }

    /*
     *
     * @see java.nio.channels.ServerSocketChannel#accept()
     */
    public SocketChannel accept() throws IOException {
        if (!isOpen()) {
            throw new ClosedChannelException();
        }
        if (!isBound) {
            throw new NotYetBoundException();
        }

        SocketChannel sockChannel = SocketChannel.open();
        Socket socketGot = sockChannel.socket();

        try {
            begin();

            synchronized (acceptLock) {
                synchronized (blockingLock()) {
                    boolean isBlocking = isBlocking();
                    if (!isBlocking) {
                        // for non blocking mode, use select to see whether
                        // there are any pending connections.
                        int[] tryResult = Platform.getNetworkSystem().select(
                                new FileDescriptor[] { this.fd },
                                new FileDescriptor[0], 0);
                        if (0 == tryResult.length || 0 == tryResult[0]) {
                            // no pending connections, returns immediately.
                            return null;
                        }
                    }
                    // do accept.
                    do {
                        try {
                            ((ServerSocketAdapter) socket).accept(socketGot,
                                    (SocketChannelImpl) sockChannel);
                            // select successfully, break out immediately.
                            break;
                        } catch (SocketTimeoutException e) {
                            // continue to accept if the channel is in blocking
                            // mode.
                        }
                    } while (isBlocking);
                }
            }
        } finally {
            end(socketGot.isConnected());
        }
        return sockChannel;
    }

    // -------------------------------------------------------------------
    // Protected inherited methods
    // -------------------------------------------------------------------

    /*
     * @see java.nio.channels.spi.AbstractSelectableChannel#implConfigureBlocking
     *
     * (boolean)
     */
    protected void implConfigureBlocking(boolean blockingMode)
            throws IOException {
        // Do nothing here. For real accept() operation in nonblocking mode,
        // it uses INetworkSystem.select. Whether a channel is blocking can be
        // decided by isBlocking() method.
    }

    /*
     *
     * @see java.nio.channels.spi.AbstractSelectableChannel#implCloseSelectableChannel()
     */
    synchronized protected void implCloseSelectableChannel() throws IOException {
        status = SERVER_STATUS_CLOSED;
        if (!socket.isClosed()) {
            socket.close();
        }
    }

    /*
     * Gets the FileDescriptor
     */
    public FileDescriptor getFD() {
        return fd;
    }

    // ----------------------------------------------------
    // Adapter classes.
    // ----------------------------------------------------

    /*
     * The adapter class of ServerSocket.
     */
    private class ServerSocketAdapter extends ServerSocket {
        /*
         * The related ServerSocketChannel.
         */
        ServerSocketChannelImpl channelImpl;

        /*
         * The Constructor.
         */
        ServerSocketAdapter(SocketImpl impl,
                ServerSocketChannelImpl aChannelImpl) {
            super(impl);
            this.channelImpl = aChannelImpl;
        }

        /*
         *
         * @see java.net.ServerSocket#bind(java.net.SocketAddress, int)
         */
        public void bind(SocketAddress localAddr, int backlog)
                throws IOException {
            super.bind(localAddr, backlog);
            channelImpl.isBound = true;
        }

        /*
         * @see java.net.ServerSocket#accept()
         *
         * If the channel is in non-blocking mode and there is no connection
         * ready to be accepted, invoking this method will cause an
         * IllegalBlockingModeException.
         */
        public Socket accept() throws IOException {
            if (!isBound) {
                throw new IllegalBlockingModeException();
            }
            SocketChannel sc = channelImpl.accept();
            if (null == sc) {
                throw new IllegalBlockingModeException();
            }
            return sc.socket();
        }

        /*
         * do the accept.
         */
        private Socket accept(Socket aSocket, SocketChannelImpl sockChannel)
                throws IOException {
            // a new socket is pass in so we do not need to "Socket aSocket =
            // new Socket();"
            boolean connectOK = false;
            try {
                synchronized (this) {
                    super.implAccept(aSocket);
                    sockChannel.setConnected();
                }
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    sm.checkAccept(aSocket.getInetAddress().getHostAddress(),
                            aSocket.getPort());
                }
                connectOK = true;
            } finally {
                if (!connectOK) {
                    aSocket.close();
                }
            }
            return aSocket;
        }

        /*
         * getting internal channel.
         */
        public ServerSocketChannel getChannel() {
            return channelImpl;
        }

        /*
         *
         * @see java.net.ServerSocket#isBound()
         */
        public boolean isBound() {
            return channelImpl.isBound;
        }

        /*
         *
         * @see java.net.ServerSocket#bind(java.net.SocketAddress)
         */
        public void bind(SocketAddress localAddr) throws IOException {
            super.bind(localAddr);
            channelImpl.isBound = true;
        }

        /*
         * @see java.net.ServerSocket#close()
         */
        public void close() throws IOException {
            synchronized (channelImpl) {
                if (channelImpl.isOpen()) {
                    channelImpl.close();
                } else {
                    super.close();
                }
                channelImpl.status = SERVER_STATUS_CLOSED;
            }
        }
    }
}


text:
FOUNDATION_EXPORT double ABReviewReminderVersionNumber;
FOUNDATION_EXPORT const unsigned char ABReviewReminderVersionString[];


text:
import unittest
from performance.web import Request, RequestTypeError, Response, RequestData

class RequestTestCase(unittest.TestCase):
    def setUp(self):
        self.host = 'http://www.google.com'

    def test_constants(self):
        self.assertEqual('get', Request.GET)
        self.assertEqual('post', Request.POST)

    def test_init(self):
        request = Request(url=self.host)
        self.assertEqual(Request.GET, request.type)
        self.assertEqual(self.host, request.url)
        request = Request(url=self.host, type=Request.POST)
        self.assertEqual(Request.POST, request.type)

    def test_do(self):
        request = Request(url='/', type=Request.GET)
        response = request.do(host=self.host)
        self.assertTrue(isinstance(response, Response))

        request = Request(url='/', type=Request.GET, data=RequestData(data=''))
        response = request.do(host=self.host)
        self.assertTrue(isinstance(response, Response))

    def test_invalid_type(self):
        type = 'foo_bar'
        request = Request(url=self.host, type=type)
        with self.assertRaises(RequestTypeError) as error:
            request.do(host=self.host)
        self.assertEqual('Invalid request type "%s"' % type, error.exception.__str__())