text:
<?php
require_once('inc/common.php');

role_needed(ROLE_AUTHOR);

$title = 'Create New Document';

$src_path = (isset($_POST['src_path']) ? $_POST['src_path'] : '');
$trans_path = (isset($_POST['trans_path']) ? $_POST['trans_path'] : '');
$doc_title = (isset($_POST['doc_title']) ? $_POST['doc_title'] : '');

if ($src_path and $trans_path and $doc_title) {
	if (trim($doc_title) and validate_path($src_path) and validate_path(str_replace('{LANG}', '', $trans_path, $count))
		and $count == 1) {

		if (isset($_POST['confirm_ok'])) {
			if (file_exists(REF_DIR . '/' . $src_path))
				error_box($title, 'This document already exists !');

			$time = time();

			if(!is_dir(dirname(REF_DIR . '/' . $src_path)))
				mkdir(dirname(REF_DIR . '/' . $src_path), 0770, true);

			file_put_contents(REF_DIR . '/' . $src_path,
				str_replace('{TITLE}', $doc_title, $base_document))
					or error_box($title, 'Unable to write to the destination directory!');

			// Insert entry in the database
			db_query('
				INSERT INTO ' . DB_DOCS . '
				(name, path_original, path_translations) ' . "
				VALUES (?, ?, ?)", array($doc_title, $src_path, $trans_path));

			$doc_id = db_insert_id();

			require_once('inc/git.php');
			git_pull(REF_DIR . '/');
			git_add(REF_DIR . '/' . $src_path);
			git_commit(REF_DIR . '/', 'New document: "' . $doc_title . '"');
			git_push(REF_DIR . '/');

			// Log
			db_query('
				INSERT INTO ' . DB_LOG . '
				(log_user, log_time, log_action, log_doc) ' . "
				VALUES (?, ?, ?, ?)", array($user_id, $time, 'creat', $doc_id));

			redirect('edit.php?doc_id=' . $doc_id);

		} else if(!isset($_POST['confirm_cancel'])) {
			$doc_title = htmlspecialchars($doc_title);
			confirm_box($title, 'Do you really want to add this document ?',
				'Cancel', 'Add', <<<EOD
<input type="hidden" name="src_path" value="$src_path" />
<input type="hidden" name="trans_path" value="$trans_path" />
<input type="hidden" name="doc_title" value="$doc_title" />
EOD
			);
		} else {
			include('inc/start_html.php');
		}
	} else {
		include('inc/start_html.php');
?>

Incorrect parameter(s).

Name field must not be blank

Special characters are not allowed in paths

The translations path must contain the {LANG} placeholder once.

<?php
	}
} else {
	include('inc/start_html.php');
}

?>
<form action="" method="post">

New document

Document name:
<input type="text" name="doc_title" id="doc_title" value="<?=htmlspecialchars($doc_title)?>" size="64" maxlength="256" />
Example: "WebPositive"

Source path:
<input type="text" name="src_path" id="src_path" value="<?=htmlspecialchars($src_path)?>" size="64" maxlength="256" />

Example: userguide/en/applications/webpositive.html

Translations path:
<input type="text" name="trans_path" id="trans_path" value="<?=htmlspecialchars($trans_path)?>" size="64" maxlength="256" />

Example: userguide/{LANG}/applications/webpositive.html

<input type="submit" name="add_docs" value="Add" />

</form>
<?php
include('inc/end_html.php');

function validate_path($path) {
	if (preg_match('/^[+.-9A-Za-z_-]*$/', $path))
		if (strpos($path, '..') === false)
			return true;
	return false;
}
?>


text:
namespace rx
{

class DisplayGLX;
class FunctionsGLX;

class WindowSurfaceGLX : public SurfaceGLX
{
  public:
    WindowSurfaceGLX(const egl::SurfaceState &state,
                     const FunctionsGLX &glx,
                     DisplayGLX *glxDisplay,
                     RendererGL *renderer,
                     Window window,
                     Display *display,
                     glx::FBConfig fbConfig);
    ~WindowSurfaceGLX() override;

    egl::Error initialize(const egl::Display *display) override;
    egl::Error makeCurrent() override;

    egl::Error swap(const gl::Context *context) override;
    egl::Error postSubBuffer(const gl::Context *context,
                             EGLint x,
                             EGLint y,
                             EGLint width,
                             EGLint height) override;
    egl::Error querySurfacePointerANGLE(EGLint attribute, void **value) override;
    egl::Error bindTexImage(gl::Texture *texture, EGLint buffer) override;
    egl::Error releaseTexImage(EGLint buffer) override;
    void setSwapInterval(EGLint interval) override;

    EGLint getWidth() const override;
    EGLint getHeight() const override;

    EGLint isPostSubBufferSupported() const override;
    EGLint getSwapBehavior() const override;

    egl::Error checkForResize() override;
    glx::Drawable getDrawable() const override;

  private:
    bool getWindowDimensions(Window window, unsigned int *width, unsigned int *height) const;

    Window mParent;
    unsigned int mParentWidth, mParentHeight;
    Window mWindow;
    Display *mDisplay;

    const FunctionsGLX &mGLX;
    DisplayGLX *mGLXDisplay;

    glx::FBConfig mFBConfig;
    glx::Window mGLXWindow;

    SwapControlData mSwapControl;
};

}  // namespace rx

#endif // LIBANGLE_RENDERER_GL_GLX_WINDOWSURFACEGLX_H_

redpajama_set_name: RedPajamaGithub


text:
create index ZSTG_INTERMS_MODIFICATI on ZSTG_INTERACTIONCOMPPTMTERMS(MODIFICATION) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_AA on ZSTG_INTERACTIONCOMPPTMTERMS(AA) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_POSITION on ZSTG_INTERACTIONCOMPPTMTERMS(POSITION) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_PROTEIN on ZSTG_INTERACTIONCOMPPTMTERMS(PROTEIN) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_ROLE_TYPE on ZSTG_INTERACTIONCOMPPTMTERMS(ROLE_TYPE) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_MOLECULE_I on ZSTG_INTERACTIONCOMPPTMTERMS(MOLECULE_ID) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_SOURCE_ID on ZSTG_INTERACTIONCOMPPTMTERMS(SOURCE_ID) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_INTERMS_INTERACTIO on ZSTG_INTERACTIONCOMPPTMTERMS(INTERACTION_ID) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;

--EXIT;


text:
var Home = function (app, express) {

    'use strict';

    this.displayName = 'Home';

    var setup;

    setup = function (app, express) {

        var path = require('path'),
            HomeConfig = require('./configs'),
            HomeRoutes = require('./routes'),
            homeConfig = new HomeConfig(app, express),
            homeRoutes = new HomeRoutes(app);
    };

    setup(app, express);
};

module.exports = Home;


text:
#include "../../SDL_internal.h"

#if SDL_VIDEO_DRIVER_DIRECTFB
#include "SDL_DirectFB_window.h"
#include "SDL_DirectFB_modes.h"

#include "SDL_syswm.h"
#include "SDL_DirectFB_shape.h"

#include "../SDL_sysvideo.h"
#include "../../render/SDL_sysrender.h"

#ifndef DFB_VERSION_ATLEAST

#define DFB_VERSIONNUM(X, Y, Z)                     \
    ((X)*1000 + (Y)*100 + (Z))

#define DFB_COMPILEDVERSION \
    DFB_VERSIONNUM(DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION)

#define DFB_VERSION_ATLEAST(X, Y, Z) \
    (DFB_COMPILEDVERSION >= DFB_VERSIONNUM(X, Y, Z))

#define SDL_DFB_CHECK(x)    x

#endif

/* the following is not yet tested ... */
#define USE_DISPLAY_PALETTE         (0)

#define SDL_DFB_RENDERERDATA(rend) DirectFB_RenderData *renddata = ((rend) ? (DirectFB_RenderData *) (rend)->driverdata : NULL)
#define SDL_DFB_WINDOWSURFACE(win)  IDirectFBSurface *destsurf = ((DFB_WindowData *) ((win)->driverdata))->surface;

typedef struct
{
    SDL_Window *window;
    DFBSurfaceFlipFlags flipflags;
    int size_changed;
    int lastBlendMode;
    DFBSurfaceBlittingFlags blitFlags;
    DFBSurfaceDrawingFlags drawFlags;
    IDirectFBSurface* target;
} DirectFB_RenderData;

typedef struct
{
    IDirectFBSurface *surface;
    Uint32 format;
    void *pixels;
    int pitch;
    IDirectFBPalette *palette;
    int isDirty;

    SDL_VideoDisplay *display;      /* only for yuv textures */

#if (DFB_VERSION_ATLEAST(1,2,0))
    DFBSurfaceRenderOptions render_options;
#endif
} DirectFB_TextureData;

static SDL_INLINE void
SDLtoDFBRect(const SDL_Rect * sr, DFBRectangle * dr)
{
    dr->x = sr->x;
    dr->y = sr->y;
    dr->h = sr->h;
    dr->w = sr->w;
}
static SDL_INLINE void
SDLtoDFBRect_Float(const SDL_FRect * sr, DFBRectangle * dr)
{
    dr->x = sr->x;
    dr->y = sr->y;
    dr->h = sr->h;
    dr->w = sr->w;
}

static int
TextureHasAlpha(DirectFB_TextureData * data)
{
    /* Drawing primitive ? */
    if (!data)
        return 0;

    return (DFB_PIXELFORMAT_HAS_ALPHA(DirectFB_SDLToDFBPixelFormat(data->format)) ? 1 : 0);
#if 0
    switch (data->format) {
    case SDL_PIXELFORMAT_INDEX4LSB:
    case SDL_PIXELFORMAT_INDEX4MSB:
    case SDL_PIXELFORMAT_ARGB4444:
    case SDL_PIXELFORMAT_ARGB1555:
    case SDL_PIXELFORMAT_ARGB8888:
    case SDL_PIXELFORMAT_RGBA8888:
    case SDL_PIXELFORMAT_ABGR8888:
    case SDL_PIXELFORMAT_BGRA8888:
    case SDL_PIXELFORMAT_ARGB2101010:
       return 1;
    default:
        return 0;
    }
#endif
}

static SDL_INLINE IDirectFBSurface *get_dfb_surface(SDL_Window *window)
{
    SDL_SysWMinfo wm_info;
    SDL_memset(&wm_info, 0, sizeof(SDL_SysWMinfo));

    SDL_VERSION(&wm_info.version);
    if (!SDL_GetWindowWMInfo(window, &wm_info)) {
        return NULL;
    }

    return wm_info.info.dfb.surface;
}

static SDL_INLINE IDirectFBWindow *get_dfb_window(SDL_Window *window)
{
    SDL_SysWMinfo wm_info;
    SDL_memset(&wm_info, 0, sizeof(SDL_SysWMinfo));

    SDL_VERSION(&wm_info.version);
    if (!SDL_GetWindowWMInfo(window, &wm_info)) {
        return NULL;
    }

    return wm_info.info.dfb.window;
}

static void
SetBlendMode(DirectFB_RenderData * data, int blendMode,
             DirectFB_TextureData * source)
{
    IDirectFBSurface *destsurf = data->target;

    /* FIXME: check for format change */
    if (1 || data->lastBlendMode != blendMode) {
        switch (blendMode) {
        case SDL_BLENDMODE_NONE:
                                           /**< No blending */
            data->blitFlags = DSBLIT_NOFX;
            data->drawFlags = DSDRAW_NOFX;
            SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_ONE));
            SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_ZERO));
            break;
#if 0
        case SDL_BLENDMODE_MASK:
            data->blitFlags =  DSBLIT_BLEND_ALPHACHANNEL;
            data->drawFlags = DSDRAW_BLEND;
            SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_SRCALPHA));
            SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_INVSRCALPHA));
            break;
#endif
        case SDL_BLENDMODE_BLEND:
            data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL;
            data->drawFlags = DSDRAW_BLEND;
            SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_SRCALPHA));
            SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_INVSRCALPHA));
            break;
        case SDL_BLENDMODE_ADD:
            data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL;
            data->drawFlags = DSDRAW_BLEND;
            /* FIXME: SRCALPHA kills performance on radeon ...
             * It will be cheaper to copy the surface to a temporary surface and premultiply
             */
            if (source && TextureHasAlpha(source))
                SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_SRCALPHA));
            else
                SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_ONE));
            SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_ONE));
            break;
        case SDL_BLENDMODE_MOD:
            data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL;
            data->drawFlags = DSDRAW_BLEND;
            SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_ZERO));
            SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_SRCCOLOR));

            break;
        case SDL_BLENDMODE_MUL:
            data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL;
            data->drawFlags = DSDRAW_BLEND;
            SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_DESTCOLOR));
            SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_INVSRCALPHA));

            break;
        }
        data->lastBlendMode = blendMode;
    }
}

static int
PrepareDraw(SDL_Renderer * renderer, const SDL_RenderCommand *cmd)
{
    DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
    IDirectFBSurface *destsurf = data->target;
    Uint8 r = cmd->data.draw.r;
    Uint8 g = cmd->data.draw.g;
    Uint8 b = cmd->data.draw.b;
    Uint8 a = cmd->data.draw.a;

    SetBlendMode(data, cmd->data.draw.blend, NULL);
    SDL_DFB_CHECKERR(destsurf->SetDrawingFlags(destsurf, data->drawFlags));

    switch (renderer->blendMode) {
    case SDL_BLENDMODE_NONE:
    /* case SDL_BLENDMODE_MASK: */
    case SDL_BLENDMODE_BLEND:
        break;
    case SDL_BLENDMODE_ADD:
    case SDL_BLENDMODE_MOD:
    case SDL_BLENDMODE_MUL:
        r = ((int) r * (int) a) / 255;
        g = ((int) g * (int) a) / 255;
        b = ((int) b * (int) a) / 255;
        a = 255;
        break;
    case SDL_BLENDMODE_INVALID: break;
    }

    SDL_DFB_CHECKERR(destsurf->SetColor(destsurf, r, g, b, a));
    return 0;
  error:
    return -1;
}

static void
DirectFB_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
{
    SDL_DFB_RENDERERDATA(renderer);

    if (event->event == SDL_WINDOWEVENT_SIZE_CHANGED) {
        /* Rebind the context to the window area and update matrices */
        /* SDL_CurrentContext = NULL; */
        /* data->updateSize = SDL_TRUE; */
        renddata->size_changed = SDL_TRUE;
   }
}

static void
DirectFB_ActivateRenderer(SDL_Renderer * renderer)
{
    SDL_DFB_RENDERERDATA(renderer);

    if (renddata->size_changed /* || windata->wm_needs_redraw */) {
        renddata->size_changed = SDL_FALSE;
    }
}

static int
DirectFB_AcquireVidLayer(SDL_Renderer * renderer, SDL_Texture * texture)
{
    SDL_Window *window = renderer->window;
    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
    SDL_DFB_DEVICEDATA(display->device);
    DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata;
    DirectFB_TextureData *data = texture->driverdata;
    DFBDisplayLayerConfig layconf;
    DFBResult ret;

    if (devdata->use_yuv_direct && (dispdata->vidID >= 0)
        && (!dispdata->vidIDinuse)
        && SDL_ISPIXELFORMAT_FOURCC(data->format)) {
        layconf.flags =
            DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT |
            DLCONF_SURFACE_CAPS;
        layconf.width = texture->w;
        layconf.height = texture->h;
        layconf.pixelformat = DirectFB_SDLToDFBPixelFormat(data->format);
        layconf.surface_caps = DSCAPS_VIDEOONLY | DSCAPS_DOUBLE;

        SDL_DFB_CHECKERR(devdata->dfb->GetDisplayLayer(devdata->dfb,
                                                       dispdata->vidID,
                                                       &dispdata->vidlayer));
        SDL_DFB_CHECKERR(dispdata->
                         vidlayer->SetCooperativeLevel(dispdata->vidlayer,
                                                       DLSCL_EXCLUSIVE));

        if (devdata->use_yuv_underlays) {
            ret = dispdata->vidlayer->SetLevel(dispdata->vidlayer, -1);
            if (ret != DFB_OK)
                SDL_DFB_DEBUG("Underlay Setlevel not supported\n");
        }
        SDL_DFB_CHECKERR(dispdata->
                         vidlayer->SetConfiguration(dispdata->vidlayer,
                                                    &layconf));
        SDL_DFB_CHECKERR(dispdata->
                         vidlayer->GetSurface(dispdata->vidlayer,
                                              &data->surface));
        dispdata->vidIDinuse = 1;
        data->display = display;
        return 0;
    }
    return 1;
  error:
    if (dispdata->vidlayer) {
        SDL_DFB_RELEASE(data->surface);
        SDL_DFB_CHECKERR(dispdata->
                         vidlayer->SetCooperativeLevel(dispdata->vidlayer,
                                                       DLSCL_ADMINISTRATIVE));
        SDL_DFB_RELEASE(dispdata->vidlayer);
    }
    return 1;
}

/* Copy the SDL_Surface palette to the DirectFB texture palette */
void DirectFB_SetTexturePalette(SDL_Renderer *renderer, SDL_Texture *texture, SDL_Palette *pal)
{
    int i;
    DFBColor dfbpal[256];
    DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata;
    for (i = 0; i < pal->ncolors; i++) {
            dfbpal[i].a = pal->colors[i].a;
            dfbpal[i].r = pal->colors[i].r;
            dfbpal[i].g = pal->colors[i].g;
            dfbpal[i].b = pal->colors[i].b;
    }
    data->palette->SetEntries(data->palette, dfbpal, pal->ncolors, 0);
}

static int
DirectFB_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    SDL_Window *window = renderer->window;
    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
    SDL_DFB_DEVICEDATA(display->device);
    DirectFB_TextureData *data;
    DFBSurfaceDescription dsc;
    DFBSurfacePixelFormat pixelformat;

    DirectFB_ActivateRenderer(renderer);

    SDL_DFB_ALLOC_CLEAR(data, sizeof(*data));
    texture->driverdata = data;

    /* find the right pixelformat */
    pixelformat = DirectFB_SDLToDFBPixelFormat(texture->format);
    if (pixelformat == DSPF_UNKNOWN) {
        SDL_SetError("Unknown pixel format %d", data->format);
        goto error;
    }

    data->format = texture->format;
    data->pitch = texture->w * DFB_BYTES_PER_PIXEL(pixelformat);

    if (DirectFB_AcquireVidLayer(renderer, texture) != 0) {
        /* fill surface description */
        dsc.flags =
            DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS;
        dsc.width = texture->w;
        dsc.height = texture->h;
        if(texture->format == SDL_PIXELFORMAT_YV12 ||
           texture->format == SDL_PIXELFORMAT_IYUV) {
           /* dfb has problems with odd sizes -make them even internally */
           dsc.width += (dsc.width % 2);
           dsc.height += (dsc.height % 2);
        }
        /* <1.2 Never use DSCAPS_VIDEOONLY here. It kills performance
         * No DSCAPS_SYSTEMONLY either - let dfb decide
         * 1.2: DSCAPS_SYSTEMONLY boosts performance by factor ~8
         * Depends on other settings as well. Let dfb decide.
         */
        dsc.caps = DSCAPS_PREMULTIPLIED;
#if 0
        if (texture->access == SDL_TEXTUREACCESS_STREAMING)
            dsc.caps |= DSCAPS_SYSTEMONLY;
        else
            dsc.caps |= DSCAPS_VIDEOONLY;
#endif

        dsc.pixelformat = pixelformat;
        data->pixels = NULL;

        /* Create the surface */
        SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc,
                                                     &data->surface));
        if (SDL_ISPIXELFORMAT_INDEXED(data->format)
            && !SDL_ISPIXELFORMAT_FOURCC(data->format)) {
#if 1
            SDL_DFB_CHECKERR(data->surface->GetPalette(data->surface, &data->palette));
#else
            /* DFB has issues with blitting LUT8 surfaces.
             * Creating a new palette does not help.
             */
            DFBPaletteDescription pal_desc;
            pal_desc.flags = DPDESC_SIZE; /* | DPDESC_ENTRIES */
            pal_desc.size = 256;
            SDL_DFB_CHECKERR(devdata->dfb->CreatePalette(devdata->dfb, &pal_desc,&data->palette));
            SDL_DFB_CHECKERR(data->surface->SetPalette(data->surface, data->palette));
#endif
        }

    }
#if (DFB_VERSION_ATLEAST(1,2,0))
    data->render_options = DSRO_NONE;
#endif
    if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
        /* 3 plane YUVs return 1 bpp, but we need more space for other planes */
        if(texture->format == SDL_PIXELFORMAT_YV12 ||
           texture->format == SDL_PIXELFORMAT_IYUV) {
            SDL_DFB_ALLOC_CLEAR(data->pixels, (texture->h * data->pitch  + ((texture->h + texture->h % 2) * (data->pitch + data->pitch % 2) * 2) / 4));
        } else {
            SDL_DFB_ALLOC_CLEAR(data->pixels, texture->h * data->pitch);
        }
    }

    return 0;

  error:
    SDL_DFB_RELEASE(data->palette);
    SDL_DFB_RELEASE(data->surface);
    SDL_DFB_FREE(texture->driverdata);
    return -1;
}

#if 0
static int
DirectFB_SetTextureScaleMode(SDL_Renderer * renderer, SDL_Texture * texture)
{
#if (DFB_VERSION_ATLEAST(1,2,0))

    DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata;

    switch (texture->scaleMode) {
    case SDL_SCALEMODE_NONE:
    case SDL_SCALEMODE_FAST:
        data->render_options = DSRO_NONE;
        break;
    case SDL_SCALEMODE_SLOW:
        data->render_options = DSRO_SMOOTH_UPSCALE | DSRO_SMOOTH_DOWNSCALE;
        break;
    case SDL_SCALEMODE_BEST:
        data->render_options =
            DSRO_SMOOTH_UPSCALE | DSRO_SMOOTH_DOWNSCALE | DSRO_ANTIALIAS;
        break;
    default:
        data->render_options = DSRO_NONE;
        texture->scaleMode = SDL_SCALEMODE_NONE;
        return SDL_Unsupported();
    }
#endif
    return 0;
}
#endif

static int
DirectFB_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                       const SDL_Rect * rect, const void *pixels, int pitch)
{
    DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata;
    Uint8 *dpixels;
    int dpitch;
    Uint8 *src, *dst;
    int row;
    size_t length;
    int bpp = DFB_BYTES_PER_PIXEL(DirectFB_SDLToDFBPixelFormat(texture->format));
    /* FIXME: SDL_BYTESPERPIXEL(texture->format) broken for yuv yv12 3 planes */

    DirectFB_ActivateRenderer(renderer);

    if ((texture->format == SDL_PIXELFORMAT_YV12) ||
        (texture->format == SDL_PIXELFORMAT_IYUV)) {
        bpp = 1;
    }

    SDL_DFB_CHECKERR(data->surface->Lock(data->surface,
                                         DSLF_WRITE | DSLF_READ,
                                         ((void **) &dpixels), &dpitch));
    src = (Uint8 *) pixels;
    dst = (Uint8 *) dpixels + rect->y * dpitch + rect->x * bpp;
    length = rect->w * bpp;
    for (row = 0; row < rect->h; ++row) {
        SDL_memcpy(dst, src, length);
        src += pitch;
        dst += dpitch;
    }
    /* copy other planes for 3 plane formats */
    if ((texture->format == SDL_PIXELFORMAT_YV12) ||
        (texture->format == SDL_PIXELFORMAT_IYUV)) {
        src = (Uint8 *) pixels + texture->h * pitch;
        dst = (Uint8 *) dpixels + texture->h * dpitch + rect->y * dpitch / 4 + rect->x * bpp / 2;
        for (row = 0; row < rect->h / 2 + (rect->h & 1); ++row) {
            SDL_memcpy(dst, src, length / 2);
            src += pitch / 2;
            dst += dpitch / 2;
        }
        src = (Uint8 *) pixels + texture->h * pitch + texture->h * pitch / 4;
        dst = (Uint8 *) dpixels + texture->h * dpitch + texture->h * dpitch / 4 + rect->y * dpitch / 4 + rect->x * bpp / 2;
        for (row = 0; row < rect->h / 2 + (rect->h & 1); ++row) {
            SDL_memcpy(dst, src, length / 2);
            src += pitch / 2;
            dst += dpitch / 2;
        }
    }
    SDL_DFB_CHECKERR(data->surface->Unlock(data->surface));
    data->isDirty = 0;
    return 0;
  error:
    return 1;

}

static int
DirectFB_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                     const SDL_Rect * rect, void **pixels, int *pitch)
{
    DirectFB_TextureData *texturedata =
        (DirectFB_TextureData *) texture->driverdata;

    DirectFB_ActivateRenderer(renderer);

#if 0
    if (markDirty) {
        SDL_AddDirtyRect(&texturedata->dirty, rect);
    }
#endif

    if (texturedata->display) {
        void *fdata;
        int fpitch;

        SDL_DFB_CHECKERR(texturedata->surface->Lock(texturedata->surface,
                                                    DSLF_WRITE | DSLF_READ,
                                                    &fdata, &fpitch));
        *pitch = fpitch;
        *pixels = fdata;
    } else {
        *pixels =
            (void *) ((Uint8 *) texturedata->pixels +
                      rect->y * texturedata->pitch +
                      rect->x * DFB_BYTES_PER_PIXEL(DirectFB_SDLToDFBPixelFormat(texture->format)));
        *pitch = texturedata->pitch;
        texturedata->isDirty = 1;
    }
    return 0;

  error:
    return -1;
}

static void
DirectFB_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    DirectFB_TextureData *texturedata =
        (DirectFB_TextureData *) texture->driverdata;

    DirectFB_ActivateRenderer(renderer);

    if (texturedata->display) {
        SDL_DFB_CHECK(texturedata->surface->Unlock(texturedata->surface));
        texturedata->pixels = NULL;
    }
}

static void
DirectFB_SetTextureScaleMode()
{
}

#if 0
static void
DirectFB_DirtyTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                      int numrects, const SDL_Rect * rects)
{
    DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata;
    int i;

    for (i = 0; i < numrects; ++i) {
        SDL_AddDirtyRect(&data->dirty, &rects[i]);
    }
}
#endif

static int DirectFB_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture)
{
    DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
    DirectFB_TextureData *tex_data = NULL;

    DirectFB_ActivateRenderer(renderer);
    if (texture) {
        tex_data = (DirectFB_TextureData *) texture->driverdata;
        data->target = tex_data->surface;
    } else {
        data->target = get_dfb_surface(data->window);
    }
    data->lastBlendMode = 0;
    return 0;
}

static int
DirectFB_QueueSetViewport(SDL_Renderer * renderer, SDL_RenderCommand *cmd)
{
    return 0;  /* nothing to do in this backend. */
}

static int
DirectFB_QueueDrawPoints(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count)
{
    const size_t len = count * sizeof (SDL_FPoint);
    SDL_FPoint *verts = (SDL_FPoint *) SDL_AllocateRenderVertices(renderer, len, 0, &cmd->data.draw.first);

    if (!verts) {
        return -1;
    }

    cmd->data.draw.count = count;
    SDL_memcpy(verts, points, len);
    return 0;
}

static int
DirectFB_QueueGeometry(SDL_Renderer *renderer, SDL_RenderCommand *cmd, SDL_Texture *texture,
        const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride,
        int num_vertices, const void *indices, int num_indices, int size_indices,
        float scale_x, float scale_y)
{
    int i;
    int count = indices ? num_indices : num_vertices;
    float *verts;
    int sz = 2 + 4 + (texture ? 2 : 0);

    verts = (float *) SDL_AllocateRenderVertices(renderer, count * sz * sizeof (float), 0, &cmd->data.draw.first);
    if (!verts) {
        return -1;
    }

    cmd->data.draw.count = count;
    size_indices = indices ? size_indices : 0;

    for (i = 0; i < count; i++) {
        int j;
        float *xy_;
        SDL_Color col_;
        if (size_indices == 4) {
            j = ((const Uint32 *)indices)[i];
        } else if (size_indices == 2) {
            j = ((const Uint16 *)indices)[i];
        } else if (size_indices == 1) {
            j = ((const Uint8 *)indices)[i];
        } else {
            j = i;
        }

        xy_ = (float *)((char*)xy + j * xy_stride);
        col_ = *(SDL_Color *)((char*)color + j * color_stride);

        *(verts++) = xy_[0] * scale_x;
        *(verts++) = xy_[1] * scale_y;

        *(verts++) = col_.r;
        *(verts++) = col_.g;
        *(verts++) = col_.b;
        *(verts++) = col_.a;

        if (texture) {
            float *uv_ = (float *)((char*)uv + j * uv_stride);
            *(verts++) = uv_[0];
            *(verts++) = uv_[1];
        }
    }
    return 0;
}

static int
DirectFB_QueueFillRects(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FRect * rects, int count)
{
    const size_t len = count * sizeof (SDL_FRect);
    SDL_FRect *verts = (SDL_FRect *) SDL_AllocateRenderVertices(renderer, len, 0, &cmd->data.draw.first);

    if (!verts) {
        return -1;
    }

    cmd->data.draw.count = count;
    SDL_memcpy(verts, rects, len);
    return 0;
}

static int
DirectFB_QueueCopy(SDL_Renderer * renderer, SDL_RenderCommand *cmd, SDL_Texture * texture,
             const SDL_Rect * srcrect, const SDL_FRect * dstrect)
{
    DFBRectangle *verts = (DFBRectangle *) SDL_AllocateRenderVertices(renderer, 2 * sizeof (DFBRectangle), 0, &cmd->data.draw.first);

    if (!verts) {
        return -1;
    }

    cmd->data.draw.count = 1;

    SDLtoDFBRect(srcrect, verts++);
    SDLtoDFBRect_Float(dstrect, verts);

    return 0;
}

static int
DirectFB_RunCommandQueue(SDL_Renderer * renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize)
{
    /* !!! FIXME: there are probably some good optimization wins in here if someone wants to look it over. */
    DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
    IDirectFBSurface *destsurf = data->target;
    DFBRegion clip_region;
    size_t i;

    DirectFB_ActivateRenderer(renderer);

    SDL_zero(clip_region);  /* in theory, this always gets set before use. */

    while (cmd) {
        switch (cmd->command) {
            case SDL_RENDERCMD_SETDRAWCOLOR:
                break;  /* not used here */

            case SDL_RENDERCMD_SETVIEWPORT: {
                const SDL_Rect *viewport = &cmd->data.viewport.rect;
                clip_region.x1 = viewport->x;
                clip_region.y1 = viewport->y;
                clip_region.x2 = clip_region.x1 + viewport->w - 1;
                clip_region.y2 = clip_region.y1 + viewport->h - 1;
                destsurf->SetClip(destsurf, &clip_region);
                break;
            }

            case SDL_RENDERCMD_SETCLIPRECT: {
                /* !!! FIXME: how does this SetClip interact with the one in SETVIEWPORT? */
                if (cmd->data.cliprect.enabled) {
                    const SDL_Rect *rect = &cmd->data.cliprect.rect;
                    clip_region.x1 = rect->x;
                    clip_region.x2 = rect->x + rect->w;
                    clip_region.y1 = rect->y;
                    clip_region.y2 = rect->y + rect->h;
                    destsurf->SetClip(destsurf, &clip_region);
                }
                break;
            }

            case SDL_RENDERCMD_CLEAR: {
                const Uint8 r = cmd->data.color.r;
                const Uint8 g = cmd->data.color.g;
                const Uint8 b = cmd->data.color.b;
                const Uint8 a = cmd->data.color.a;
                destsurf->Clear(destsurf, r, g, b, a);
                break;
            }

            case SDL_RENDERCMD_DRAW_POINTS: {
                const size_t count = cmd->data.draw.count;
                const SDL_FPoint *points = (SDL_FPoint *) (((Uint8 *) vertices) + cmd->data.draw.first);
                PrepareDraw(renderer, cmd);
                for (i = 0; i < count; i++) {
                    const int x = points[i].x + clip_region.x1;
                    const int y = points[i].y + clip_region.y1;
                    destsurf->DrawLine(destsurf, x, y, x, y);
                }
                break;
            }

            case SDL_RENDERCMD_DRAW_LINES: {
                const SDL_FPoint *points = (SDL_FPoint *) (((Uint8 *) vertices) + cmd->data.draw.first);
                const size_t count = cmd->data.draw.count;

                PrepareDraw(renderer, cmd);

                #if (DFB_VERSION_ATLEAST(1,2,0))  /* !!! FIXME: should this be set once, somewhere else? */
                destsurf->SetRenderOptions(destsurf, DSRO_ANTIALIAS);
                #endif

                for (i = 0; i < count - 1; i++) {
                    const int x1 = points[i].x + clip_region.x1;
                    const int y1 = points[i].y + clip_region.y1;
                    const int x2 = points[i + 1].x + clip_region.x1;
                    const int y2 = points[i + 1].y + clip_region.y1;
                    destsurf->DrawLine(destsurf, x1, y1, x2, y2);
                }
                break;
            }

            case SDL_RENDERCMD_FILL_RECTS: {
                const SDL_FRect *rects = (SDL_FRect *) (((Uint8 *) vertices) + cmd->data.draw.first);
                const size_t count = cmd->data.draw.count;

                PrepareDraw(renderer, cmd);

                for (i = 0; i < count; i++, rects++) {
                    destsurf->FillRectangle(destsurf, rects->x + clip_region.x1, rects->y + clip_region.y1, rects->w, rects->h);
                }
                break;
            }

            case SDL_RENDERCMD_COPY: {
                SDL_Texture *texture = cmd->data.draw.texture;
                const Uint8 r = cmd->data.draw.r;
                const Uint8 g = cmd->data.draw.g;
                const Uint8 b = cmd->data.draw.b;
                const Uint8 a = cmd->data.draw.a;
                DFBRectangle *verts = (DFBRectangle *) (((Uint8 *) vertices) + cmd->data.draw.first);
                DirectFB_TextureData *texturedata = (DirectFB_TextureData *) texture->driverdata;
                DFBRectangle *sr = verts++;
                DFBRectangle *dr = verts;

                dr->x += clip_region.x1;
                dr->y += clip_region.y1;

                if (texturedata->display) {
                    int px, py;
                    SDL_Window *window = renderer->window;
                    IDirectFBWindow *dfbwin = get_dfb_window(window);
                    SDL_DFB_WINDOWDATA(window);
                    SDL_VideoDisplay *display = texturedata->display;
                    DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata;

                    dispdata->vidlayer->SetSourceRectangle(dispdata->vidlayer, sr->x, sr->y, sr->w, sr->h);
                    dfbwin->GetPosition(dfbwin, &px, &py);
                    px += windata->client.x;
                    py += windata->client.y;
                    dispdata->vidlayer->SetScreenRectangle(dispdata->vidlayer, px + dr->x, py + dr->y, dr->w, dr->h);
                } else {
                    DFBSurfaceBlittingFlags flags = 0;
                    if (texturedata->isDirty) {
                        const SDL_Rect rect = { 0, 0, texture->w, texture->h };
                        DirectFB_UpdateTexture(renderer, texture, &rect, texturedata->pixels, texturedata->pitch);
                    }

                    if (a != 0xFF) {
                        flags |= DSBLIT_BLEND_COLORALPHA;
                    }

                    if ((r & g & b) != 0xFF) {
                        flags |= DSBLIT_COLORIZE;
                    }

                    destsurf->SetColor(destsurf, r, g, b, a);

                    /* ???? flags |= DSBLIT_SRC_PREMULTCOLOR; */

                    SetBlendMode(data, texture->blendMode, texturedata);

                    destsurf->SetBlittingFlags(destsurf, data->blitFlags | flags);

#if (DFB_VERSION_ATLEAST(1,2,0))
                    destsurf->SetRenderOptions(destsurf, texturedata->render_options);
#endif

                    if (sr->w == dr->w && sr->h == dr->h) {
                        destsurf->Blit(destsurf, texturedata->surface, sr, dr->x, dr->y);
                    } else {
                        destsurf->StretchBlit(destsurf, texturedata->surface, sr, dr);
                    }
                }
                break;
            }

            case SDL_RENDERCMD_GEOMETRY: {
                const float *verts = (float *) (((Uint8 *) vertices) + cmd->data.draw.first);
                SDL_Texture *texture = cmd->data.draw.texture;
                const size_t count = cmd->data.draw.count;

                Uint8 save_r = cmd->data.draw.r;
                Uint8 save_g = cmd->data.draw.g;
                Uint8 save_b = cmd->data.draw.b;
                Uint8 save_a = cmd->data.draw.a;

                int j;
                for (j = 0; j < count; j += 3)
                {
                    float x1, y1, r1, g1, b1, a1, u1, v1;
                    float x2, y2, r2, g2, b2, a2, u2, v2;
                    float x3, y3, r3, g3, b3, a3, u3, v3;

                    x1 = *(verts++);
                    y1 = *(verts++);
                    r1 = *(verts++);
                    g1 = *(verts++);
                    b1 = *(verts++);
                    a1 = *(verts++);
                    if (texture) {
                        u1 = *(verts++);
                        v1 = *(verts++);
                    }
                    x2 = *(verts++);
                    y2 = *(verts++);
                    r2 = *(verts++);
                    g2 = *(verts++);
                    b2 = *(verts++);
                    a2 = *(verts++);
                    if (texture) {
                        u2 = *(verts++);
                        v2 = *(verts++);
                    }
                    x3 = *(verts++);
                    y3 = *(verts++);
                    r3 = *(verts++);
                    g3 = *(verts++);
                    b3 = *(verts++);
                    a3 = *(verts++);
                    if (texture) {
                        u3 = *(verts++);
                        v3 = *(verts++);
                    }

                    if (texture) {
                        DFBVertex vertices[3];

                        DirectFB_TextureData *texturedata = (DirectFB_TextureData *) texture->driverdata;

                        DFBSurfaceBlittingFlags flags = 0;

                        int r = (r1 + r2 + r3) / 3;
                        int g = (g1 + g2 + g3) / 3;
                        int b = (b1 + b2 + b3) / 3;
                        int a = (a1 + a2 + a3) / 3;

                        if (texturedata->isDirty) {
                            const SDL_Rect rect = { 0, 0, texture->w, texture->h };
                            DirectFB_UpdateTexture(renderer, texture, &rect, texturedata->pixels, texturedata->pitch);
                        }

                        if (a != 0xFF) {
                            flags |= DSBLIT_BLEND_COLORALPHA;
                        }

                        if ((r & g & b) != 0xFF) {
                            flags |= DSBLIT_COLORIZE;
                        }

                        destsurf->SetColor(destsurf, r, g, b, a);

                        /* ???? flags |= DSBLIT_SRC_PREMULTCOLOR; */

                        SetBlendMode(data, texture->blendMode, texturedata);

                        destsurf->SetBlittingFlags(destsurf, data->blitFlags | flags);

#if (DFB_VERSION_ATLEAST(1,2,0))
                        destsurf->SetRenderOptions(destsurf, texturedata->render_options);
#endif

                        vertices[0].x = x1;
                        vertices[0].y = y1;
                        vertices[0].z = 0;
                        vertices[0].w = 0;
                        vertices[0].s = u1;
                        vertices[0].t = v1;

                        vertices[1].x = x2;
                        vertices[1].y = y2;
                        vertices[1].z = 0;
                        vertices[1].w = 0;
                        vertices[1].s = u2;
                        vertices[1].t = v2;

                        vertices[2].x = x3;
                        vertices[2].y = y3;
                        vertices[2].z = 0;
                        vertices[2].w = 0;
                        vertices[2].s = u3;
                        vertices[2].t = v3;

                        destsurf->TextureTriangles(destsurf, texturedata->surface, vertices, NULL, 3, DTTF_LIST);
                    } else {
                        DFBTriangle tris;
                        tris.x1 = x1;
                        tris.y1 = y1;
                        tris.x2 = x2;
                        tris.y2 = y2;
                        tris.x3 = x3;
                        tris.y3 = y3;

                        cmd->data.draw.r = (r1 + r2 + r3) / 3;
                        cmd->data.draw.g = (g1 + g2 + g3) / 3;
                        cmd->data.draw.b = (b1 + b2 + b3) / 3;
                        cmd->data.draw.a = (a1 + a2 + a3) / 3;

                        PrepareDraw(renderer, cmd);

                        destsurf->FillTriangles(destsurf, &tris, 1);
                    }
                }

                cmd->data.draw.r = save_r;
                cmd->data.draw.g = save_g;
                cmd->data.draw.b = save_b;
                cmd->data.draw.a = save_a;
                break;
            }

            case SDL_RENDERCMD_COPY_EX: /* unused */
                break;

            case SDL_RENDERCMD_NO_OP:
                break;
        }

        cmd = cmd->next;
    }

    return 0;
}

static void
DirectFB_RenderPresent(SDL_Renderer * renderer)
{
    DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
    SDL_Window *window = renderer->window;
    SDL_DFB_WINDOWDATA(window);
    SDL_ShapeData *shape_data = (window->shaper ? window->shaper->driverdata : NULL);

    DirectFB_ActivateRenderer(renderer);

    if (shape_data && shape_data->surface) {
        /* saturate the window surface alpha channel */
        SDL_DFB_CHECK(windata->window_surface->SetSrcBlendFunction(windata->window_surface, DSBF_ONE));
        SDL_DFB_CHECK(windata->window_surface->SetDstBlendFunction(windata->window_surface, DSBF_ONE));
        SDL_DFB_CHECK(windata->window_surface->SetDrawingFlags(windata->window_surface, DSDRAW_BLEND));
        SDL_DFB_CHECK(windata->window_surface->SetColor(windata->window_surface, 0, 0, 0, 0xff));
        SDL_DFB_CHECK(windata->window_surface->FillRectangle(windata->window_surface, 0,0, windata->size.w, windata->size.h));

        /* blit the mask */
        SDL_DFB_CHECK(windata->surface->SetSrcBlendFunction(windata->surface, DSBF_DESTCOLOR));
        SDL_DFB_CHECK(windata->surface->SetDstBlendFunction(windata->surface, DSBF_ZERO));
        SDL_DFB_CHECK(windata->surface->SetBlittingFlags(windata->surface, DSBLIT_BLEND_ALPHACHANNEL));
#if (DFB_VERSION_ATLEAST(1,2,0))
        SDL_DFB_CHECK(windata->surface->SetRenderOptions(windata->surface, DSRO_NONE));
#endif
        SDL_DFB_CHECK(windata->surface->Blit(windata->surface, shape_data->surface, NULL, 0, 0));
    }

    /* Send the data to the display */
    SDL_DFB_CHECK(windata->window_surface->Flip(windata->window_surface, NULL,
                                                data->flipflags));
}

static void
DirectFB_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata;

    DirectFB_ActivateRenderer(renderer);

    if (!data) {
        return;
    }
    SDL_DFB_RELEASE(data->palette);
    SDL_DFB_RELEASE(data->surface);
    if (data->display) {
        DFB_DisplayData *dispdata =
            (DFB_DisplayData *) data->display->driverdata;
        dispdata->vidIDinuse = 0;
        /* FIXME: Shouldn't we reset the cooperative level */
        SDL_DFB_CHECK(dispdata->vidlayer->SetCooperativeLevel(dispdata->vidlayer,
                                                DLSCL_ADMINISTRATIVE));
        SDL_DFB_RELEASE(dispdata->vidlayer);
    }
    SDL_DFB_FREE(data->pixels);
    SDL_free(data);
    texture->driverdata = NULL;
}

static void
DirectFB_DestroyRenderer(SDL_Renderer * renderer)
{
    DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
#if 0
    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(data->window);
    if (display->palette) {
        SDL_DelPaletteWatch(display->palette, DisplayPaletteChanged, data);
    }
#endif

    SDL_free(data);
    SDL_free(renderer);
}

static int
DirectFB_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                     Uint32 format, void * pixels, int pitch)
{
    Uint32 sdl_format;
    unsigned char* laypixels;
    int laypitch;
    DFBSurfacePixelFormat dfb_format;
    DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
    IDirectFBSurface *winsurf = data->target;

    DirectFB_ActivateRenderer(renderer);

    winsurf->GetPixelFormat(winsurf, &dfb_format);
    sdl_format = DirectFB_DFBToSDLPixelFormat(dfb_format);
    winsurf->Lock(winsurf, DSLF_READ, (void **) &laypixels, &laypitch);

    laypixels += (rect->y * laypitch + rect->x * SDL_BYTESPERPIXEL(sdl_format) );
    SDL_ConvertPixels(rect->w, rect->h,
                      sdl_format, laypixels, laypitch,
                      format, pixels, pitch);

    winsurf->Unlock(winsurf);

    return 0;
}

#if 0
static int
DirectFB_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                      Uint32 format, const void * pixels, int pitch)
{
    SDL_Window *window = renderer->window;
    SDL_DFB_WINDOWDATA(window);
    Uint32 sdl_format;
    unsigned char* laypixels;
    int laypitch;
    DFBSurfacePixelFormat dfb_format;

    SDL_DFB_CHECK(windata->surface->GetPixelFormat(windata->surface, &dfb_format));
    sdl_format = DirectFB_DFBToSDLPixelFormat(dfb_format);

    SDL_DFB_CHECK(windata->surface->Lock(windata->surface, DSLF_WRITE, (void **) &laypixels, &laypitch));

    laypixels += (rect->y * laypitch + rect->x * SDL_BYTESPERPIXEL(sdl_format) );
    SDL_ConvertPixels(rect->w, rect->h,
                      format, pixels, pitch,
                      sdl_format, laypixels, laypitch);

    SDL_DFB_CHECK(windata->surface->Unlock(windata->surface));

    return 0;
}
#endif

SDL_Renderer *
DirectFB_CreateRenderer(SDL_Window * window, Uint32 flags)
{
    IDirectFBSurface *winsurf = get_dfb_surface(window);
    /*SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);*/
    SDL_Renderer *renderer = NULL;
    DirectFB_RenderData *data = NULL;
    DFBSurfaceCapabilities scaps;

    if (!winsurf) {
        return NULL;
    }

    SDL_DFB_ALLOC_CLEAR(renderer, sizeof(*renderer));
    SDL_DFB_ALLOC_CLEAR(data, sizeof(*data));

    renderer->WindowEvent = DirectFB_WindowEvent;
    renderer->CreateTexture = DirectFB_CreateTexture;
    renderer->UpdateTexture = DirectFB_UpdateTexture;
    renderer->LockTexture = DirectFB_LockTexture;
    renderer->UnlockTexture = DirectFB_UnlockTexture;
    renderer->SetTextureScaleMode = DirectFB_SetTextureScaleMode;
    renderer->QueueSetViewport = DirectFB_QueueSetViewport;
    renderer->QueueSetDrawColor = DirectFB_QueueSetViewport;  /* SetViewport and SetDrawColor are (currently) no-ops. */
    renderer->QueueDrawPoints = DirectFB_QueueDrawPoints;
    renderer->QueueDrawLines = DirectFB_QueueDrawPoints;  /* lines and points queue vertices the same way. */
    renderer->QueueGeometry = DirectFB_QueueGeometry;
    renderer->QueueFillRects = DirectFB_QueueFillRects;
    renderer->QueueCopy = DirectFB_QueueCopy;
    renderer->RunCommandQueue = DirectFB_RunCommandQueue;
    renderer->RenderPresent = DirectFB_RenderPresent;

    /* FIXME: Yet to be tested */
    renderer->RenderReadPixels = DirectFB_RenderReadPixels;
    /* renderer->RenderWritePixels = DirectFB_RenderWritePixels; */

    renderer->DestroyTexture = DirectFB_DestroyTexture;
    renderer->DestroyRenderer = DirectFB_DestroyRenderer;
    renderer->SetRenderTarget = DirectFB_SetRenderTarget;

    renderer->info = DirectFB_RenderDriver.info;
    renderer->window = window;      /* SDL window */
    renderer->driverdata = data;

    renderer->info.flags =
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE;

    data->window = window;
    data->target = winsurf;

    data->flipflags = DSFLIP_PIPELINE | DSFLIP_BLIT;

    if (flags & SDL_RENDERER_PRESENTVSYNC) {
        data->flipflags |= DSFLIP_WAITFORSYNC | DSFLIP_ONSYNC;
        renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
    } else
        data->flipflags |= DSFLIP_ONSYNC;

    SDL_DFB_CHECKERR(winsurf->GetCapabilities(winsurf, &scaps));

#if 0
    if (scaps & DSCAPS_DOUBLE)
        renderer->info.flags |= SDL_RENDERER_PRESENTFLIP2;
    else if (scaps & DSCAPS_TRIPLE)
        renderer->info.flags |= SDL_RENDERER_PRESENTFLIP3;
    else
        renderer->info.flags |= SDL_RENDERER_SINGLEBUFFER;
#endif

    DirectFB_SetSupportedPixelFormats(&renderer->info);

#if 0
    /* Set up a palette watch on the display palette */
    if (display-> palette) {
        SDL_AddPaletteWatch(display->palette, DisplayPaletteChanged, data);
    }
#endif

    return renderer;

  error:
    SDL_DFB_FREE(renderer);
    SDL_DFB_FREE(data);
    return NULL;
}

SDL_RenderDriver DirectFB_RenderDriver = {
    DirectFB_CreateRenderer,
    {
     "directfb",
     (SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED),
     /* (SDL_TEXTUREMODULATE_NONE | SDL_TEXTUREMODULATE_COLOR |
      SDL_TEXTUREMODULATE_ALPHA),
      (SDL_BLENDMODE_NONE | SDL_BLENDMODE_MASK | SDL_BLENDMODE_BLEND |
      SDL_BLENDMODE_ADD | SDL_BLENDMODE_MOD),
     (SDL_SCALEMODE_NONE | SDL_SCALEMODE_FAST |
      SDL_SCALEMODE_SLOW | SDL_SCALEMODE_BEST), */
     0,
     {
             /* formats filled in later */
     },
     0,
     0}
};

#endif /* SDL_VIDEO_DRIVER_DIRECTFB */

/* vi: set ts=4 sw=4 expandtab: */


text:
const createReadyStateManager = require('./create-ready-state-manager');

module.exports = Object.assign({
  createReadyStateManager,
});


text:
package com.s3s3l.eve;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import org.simmetrics.StringMetric;
import org.simmetrics.builders.StringMetricBuilder;
import org.simmetrics.metrics.StringMetrics;
import org.simmetrics.simplifiers.Simplifiers;

import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.core.type.TypeReference;
import com.s3s3l.resource.JacksonHelper;
import com.s3s3l.resource.JacksonUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

/**
 *

 *

 * ClassName:Application

 * Date: May 11, 2017 3:41:23 PM

 *
 * @author kehw_zwei
 * @version 1.0.0
 * @since JDK 1.8
 */
public class EveHelper extends Application {
    private static final String api = "https://www.ceve-market.org/query/?search=";
    private static final JacksonHelper json = JacksonUtil.create();
    private static final DecimalFormat df = new DecimalFormat("#,###.00");
    private static double xOffset = 0;
    private static double yOffset = 0;
    private static double pinX = 0, pinY = 0;

    private static final AtomicBoolean control = new AtomicBoolean(false);
    private static final AtomicBoolean alt = new AtomicBoolean(false);
    private static final ITesseract tesseract = new Tesseract();

    @Override
    public void start(Stage primaryStage) throws Exception {
        // Scene scene = new Scene(new Group(
        // (Node) new FXMLLoader().load(new
        // FileInputStream(FileUtils.getFirstExistFile("MarketSearch.fxml")))));
        // scene.getStylesheets().add(FileUtils.getFirstExistFile("css/style.css").toURI().toURL().toExternalForm());
        // ((Group) scene.getRoot()).getStyleClass().add("scene");
        Rectangle cutedImg = new Rectangle(0, 0, 100, 100);
        Scene scene = new Scene(new Group(cutedImg));

        scene.setOnKeyPressed((event) -> {
            switch (event.getCode()) {
                case ALT:
                    alt.set(true);
                    break;
                case CONTROL:
                    control.set(true);
                    break;
                default:
                    break;
            }
        });
        scene.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                xOffset = primaryStage.getX() - event.getScreenX();
                yOffset = primaryStage.getY() - event.getScreenY();
            }
        });
        scene.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                primaryStage.setX(event.getScreenX() + xOffset);
                primaryStage.setY(event.getScreenY() + yOffset);
            }
        });

        primaryStage.initStyle(StageStyle.TRANSPARENT);
        primaryStage.setAlwaysOnTop(true);
        primaryStage.setScene(scene);
        // primaryStage.setOpacity(0.7);
        primaryStage.setResizable(true);
        primaryStage.show();

        Rectangle rect = new Rectangle(0, 0, 0, 0);
        rect.setFill(Color.WHITE);
        rect.setOpacity(0.8);

        Stage mask = new Stage(StageStyle.TRANSPARENT);
        mask.setResizable(false);
        // mask.setOpacity(0.3);
        mask.initModality(Modality.APPLICATION_MODAL);
        mask.setAlwaysOnTop(true);
        mask.initOwner(primaryStage);

        Dimension monitor = Toolkit.getDefaultToolkit().getScreenSize();

        Double screenWidth = Screen.getPrimary().getVisualBounds().getMaxX();
        Double screenHeight = Screen.getPrimary().getVisualBounds().getMaxY();

        System.out.println(screenWidth);
        System.out.println(screenHeight);
        System.out.println(monitor.getWidth());
        System.out.println(monitor.getHeight());

        Rectangle background = new Rectangle(screenWidth, screenHeight);
        BufferedImage screenShot = new Robot().createScreenCapture(new java.awt.Rectangle(monitor)).getSubimage(0, 0,
                screenWidth.intValue(), screenHeight.intValue());
        background.setFill(new ImagePattern(SwingFXUtils.toFXImage(screenShot, null)));

        Group root = new Group(background);
        root.getChildren().add(rect);

        Scene maskScene = new Scene(root, screenWidth, screenHeight);
        System.out.println(maskScene.getWidth());
        System.out.println(maskScene.getHeight());
        maskScene.addEventFilter(MouseEvent.MOUSE_PRESSED, (event) -> {
            pinX = event.getSceneX();
            pinY = event.getSceneY();
            rect.setWidth(0);
            rect.setHeight(0);
        });
        maskScene.addEventFilter(MouseEvent.MOUSE_DRAGGED, (event) -> {
            rect.setLayoutX(Math.min(event.getSceneX(), pinX));
            rect.setLayoutY(Math.min(event.getSceneY(), pinY));
            rect.setWidth(Math.abs(event.getSceneX() - pinX));
            rect.setHeight(Math.abs(event.getSceneY() - pinY));
        });
        maskScene.addEventFilter(MouseEvent.MOUSE_RELEASED, (event) -> {
            System.out.println(doOCR(cutImage(screenShot, rect)));
            BufferedImage img = cutImage(screenShot, rect);
            cutedImg.setWidth(img.getWidth());
            cutedImg.setHeight(img.getHeight());
            primaryStage.setWidth(img.getWidth());
            primaryStage.setHeight(img.getHeight());
            cutedImg.setFill(new ImagePattern(SwingFXUtils.toFXImage(img, null)));

        });
        mask.setScene(maskScene);
        mask.show();
    }

    public static void main(String[] args) throws InterruptedException, IOException, AWTException {
        tesseract.setDatapath(FileUtils.getFullFilePath("classpath:/"));
        tesseract.setLanguage("eng");

        StringMetric stringMetric = StringMetricBuilder.with(StringMetrics.cosineSimilarity()).simplify(Simplifiers.toLowerCase(Locale.ENGLISH))
                .simplify(Simplifiers.replaceNonWord()).build();
        launch(args);
    }

    private static BufferedImage cutImage(BufferedImage img, Rectangle rect) {
        System.out.println(rect.getLayoutX());
        System.out.println(rect.getLayoutY());
        System.out.println(rect.getWidth());
        System.out.println(rect.getHeight());
        BufferedImage cutedImg = img.getSubimage(new Double(Math.max(0, rect.getLayoutX())).intValue(),
                new Double(Math.max(0, rect.getLayoutY())).intValue(), new Double(rect.getWidth()).intValue(),
                new Double(rect.getHeight()).intValue());
        return cutedImg;
    }

    private static String doOCR(BufferedImage img) {
        try {
            return tesseract.doOCR(img);
        } catch (TesseractException e) {
            return "";
        }
    }

    private static void doSearch(String keyWord) throws IOException, AWTException {
        String url = api.concat(keyWord);
        System.out.println(url);
        List<Item> items = json.convert(doGet(url), new TypeReference<List<Item>>() {
        });
        System.out.println(json.prettyPrinter().toJsonString(items));
        for (Item item : items) {
        }
    }

    public static TreeNode doGet(String url) throws IOException {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder().url(url).addHeader("referer", "https://www.ceve-market.org/home/")
                .build();

        Response response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            System.out.println(String.format("查询失败, %s", response.message()));
        }

        return json.toTreeNode(response.body().byteStream());
    }
}


text:
using System;

namespace LibNETStandard10
{
    public class Class1
    {
        public const string Message = "Hello from netstandard1.0!";
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>31.4. runpy — Locating and executing Python modules — Python 3.5.2 documentation</title>

    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.5.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.5.2 documentation" href="../contents.html" />
    <link rel="up" title="31. Importing Modules" href="modules.html" />
    <link rel="next" title="31.5. importlib — The implementation of import" href="importlib.html" />
    <link rel="prev" title="31.3. modulefinder — Find modules used by a script" href="modulefinder.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.5.2
          Documentation  »

The Python Standard Library »

31. Importing Modules »

        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

         |

31.4. runpy — Locating and executing Python modules¶

Source code: Lib/runpy.py

The runpy module is used to locate and run Python modules without
importing them first. Its main use is to implement the -m command
line switch that allows scripts to be located using the Python module
namespace rather than the filesystem.

Note that this is not a sandbox module - all code is executed in the
current process, and any side effects (such as cached imports of other
modules) will remain in place after the functions have returned.

Furthermore, any functions and classes defined by the executed code are not
guaranteed to work correctly after a runpy function has returned.
If that limitation is not acceptable for a given use case, importlib
is likely to be a more suitable choice than this module.

The runpy module provides two functions:

runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)¶

Execute the code of the specified module and return the resulting module
globals dictionary. The module’s code is first located using the standard
import mechanism (refer to PEP 302 for details) and then executed in a
fresh module namespace.

The mod_name argument should be an absolute module name.
If the module name refers to a package rather than a normal
module, then that package is imported and the __main__ submodule within
that package is then executed and the resulting module globals dictionary
returned.

The optional dictionary argument init_globals may be used to pre-populate
the module’s globals dictionary before the code is executed. The supplied
dictionary will not be modified. If any of the special global variables
below are defined in the supplied dictionary, those definitions are
overridden by run_module().

The special global variables __name__, __spec__, __file__,
__cached__, __loader__ and __package__ are set in the globals
dictionary before the module code is executed (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail).

__name__ is set to run_name if this optional argument is not
None, to mod_name + '.__main__' if the named module is a
package and to the mod_name argument otherwise.

__spec__ will be set appropriately for the actually imported
module (that is, __spec__.name will always be mod_name or
mod_name + '.__main__, never run_name).

__file__, __cached__, __loader__ and __package__ are
set as normal based on the module spec.

If the argument alter_sys is supplied and evaluates to True,
then sys.argv[0] is updated with the value of __file__ and
sys.modules[__name__] is updated with a temporary module object for the
module being executed. Both sys.argv[0] and sys.modules[__name__]
are restored to their original values before the function returns.

Note that this manipulation of sys is not thread-safe. Other threads
may see the partially initialised module, as well as the altered list of
arguments. It is recommended that the sys module be left alone when
invoking this function from threaded code.

See also

The -m option offering equivalent functionality from the
command line.

Changed in version 3.1: Added ability to execute packages by looking for a __main__ submodule.

Changed in version 3.2: Added __cached__ global variable (see PEP 3147).

Changed in version 3.4: Updated to take advantage of the module spec feature added by
PEP 451. This allows __cached__ to be set correctly for modules
run this way, as well as ensuring the real module name is always
accessible as __spec__.name.

runpy.run_path(file_path, init_globals=None, run_name=None)¶

Execute the code at the named filesystem location and return the resulting
module globals dictionary. As with a script name supplied to the CPython
command line, the supplied path may refer to a Python source file, a
compiled bytecode file or a valid sys.path entry containing a __main__
module (e.g. a zipfile containing a top-level __main__.py file).

For a simple script, the specified code is simply executed in a fresh
module namespace. For a valid sys.path entry (typically a zipfile or
directory), the entry is first added to the beginning of sys.path. The
function then looks for and executes a __main__ module using the
updated path. Note that there is no special protection against invoking
an existing __main__ entry located elsewhere on sys.path if
there is no such module at the specified location.

The optional dictionary argument init_globals may be used to pre-populate
the module’s globals dictionary before the code is executed. The supplied
dictionary will not be modified. If any of the special global variables
below are defined in the supplied dictionary, those definitions are
overridden by run_path().

The special global variables __name__, __spec__, __file__,
__cached__, __loader__ and __package__ are set in the globals
dictionary before the module code is executed (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail).

__name__ is set to run_name if this optional argument is not
None and to '<run_path>' otherwise.

If the supplied path directly references a script file (whether as source
or as precompiled byte code), then __file__ will be set to the
supplied path, and __spec__, __cached__, __loader__ and
__package__ will all be set to None.

If the supplied path is a reference to a valid sys.path entry, then
__spec__ will be set appropriately for the imported __main__
module (that is, __spec__.name will always be __main__).
__file__, __cached__, __loader__ and __package__ will be
set as normal based on the module spec.

A number of alterations are also made to the sys module. Firstly,
sys.path may be altered as described above. sys.argv[0] is updated
with the value of file_path and sys.modules[__name__] is updated
with a temporary module object for the module being executed. All
modifications to items in sys are reverted before the function
returns.

Note that, unlike run_module(), the alterations made to sys
are not optional in this function as these adjustments are essential to
allowing the execution of sys.path entries. As the thread-safety
limitations still apply, use of this function in threaded code should be
either serialised with the import lock or delegated to a separate process.

See also

Interface options for equivalent functionality on the
command line (python path/to/script).

New in version 3.2.

Changed in version 3.4: Updated to take advantage of the module spec feature added by
PEP 451. This allows __cached__ to be set correctly in the
case where __main__ is imported from a valid sys.path entry rather
than being executed directly.

See also

PEP 338 – Executing modules as scripts

PEP written and implemented by Nick Coghlan.

PEP 366 – Main module explicit relative imports

PEP written and implemented by Nick Coghlan.

PEP 451 – A ModuleSpec Type for the Import System

PEP written and implemented by Eric Snow

Command line and environment - CPython command line details

The importlib.import_module() function

Previous topic

31.3. modulefinder — Find modules used by a script

Next topic

31.5. importlib — The implementation of import

This Page

Report a Bug

Show Source

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.5.2
          Documentation  »

The Python Standard Library »

31. Importing Modules »

        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

         |

    © Copyright 2001-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Dec 08, 2016.
    Found a bug?

    Created using Sphinx 1.3.3.


text:
r"""
A general Particle Swarm Optimization (general PSO) algorithm.

It takes a set of candidate solutions, and tries to find the best
solution using a position-velocity update method. Uses a user specified
topology.

The position update can be defined as:

.. math::

   x_{i}(t+1) = x_{i}(t) + v_{i}(t+1)

Where the position at the current timestep :math:`t` is updated using
the computed velocity at :math:`t+1`. Furthermore, the velocity update
is defined as:

.. math::

   v_{ij}(t + 1) = m * v_{ij}(t) + c_{1}r_{1j}(t)[y_{ij}(t) − x_{ij}(t)]
                   + c_{2}r_{2j}(t)[\hat{y}_{j}(t) − x_{ij}(t)]

Here, :math:`c1` and :math:`c2` are the cognitive and social parameters
respectively. They control the particle's behavior given two choices: (1) to
follow its *personal best* or (2) follow the swarm's *global best* position.
Overall, this dictates if the swarm is explorative or exploitative in nature.
In addition, a parameter :math:`w` controls the inertia of the swarm's
movement.

An example usage is as follows:

.. code-block:: python

    import pyswarms as ps
    from pyswarms.backend.topology import Pyramid
    from pyswarms.utils.functions import single_obj as fx

    # Set-up hyperparameters and topology
    options = {'c1': 0.5, 'c2': 0.3, 'w':0.9}
    my_topology = Pyramid(static=False)

    # Call instance of GlobalBestPSO
    optimizer = ps.single.GeneralOptimizerPSO(n_particles=10, dimensions=2,
                                        options=options, topology=my_topology)

    # Perform optimization
    stats = optimizer.optimize(fx.sphere, iters=100)

This algorithm was adapted from the earlier works of J. Kennedy and
R.C. Eberhart in Particle Swarm Optimization [IJCNN1995]_.

.. [IJCNN1995] J. Kennedy and R.C. Eberhart, "Particle Swarm Optimization,"
    Proceedings of the IEEE International Joint Conference on Neural
    Networks, 1995, pp. 1942-1948.
"""

# Import standard library
import logging

# Import modules
import numpy as np
import multiprocessing as mp

from collections import deque

from ..backend.operators import compute_pbest, compute_objective_function
from ..backend.topology import Topology
from ..backend.handlers import BoundaryHandler, VelocityHandler, OptionsHandler
from ..base import SwarmOptimizer
from ..utils.reporter import Reporter

class GeneralOptimizerPSO(SwarmOptimizer):
    def __init__(
        self,
        n_particles,
        dimensions,
        options,
        topology,
        bounds=None,
        oh_strategy=None,
        bh_strategy="periodic",
        velocity_clamp=None,
        vh_strategy="unmodified",
        center=1.00,
        ftol=-np.inf,
        ftol_iter=1,
        init_pos=None,
    ):
        """Initialize the swarm

        Attributes
        ----------
        n_particles : int
            number of particles in the swarm.
        dimensions : int
            number of dimensions in the space.
        options : dict with keys :code:`{'c1', 'c2', 'w'}` or :code:`{'c1',
                'c2', 'w', 'k', 'p'}`
            a dictionary containing the parameters for the specific
            optimization technique.
                * c1 : float
                    cognitive parameter
                * c2 : float
                    social parameter
                * w : float
                    inertia parameter
                if used with the :code:`Ring`, :code:`VonNeumann` or
                :code:`Random` topology the additional parameter k must be
                included
                * k : int
                    number of neighbors to be considered. Must be a positive
                    integer less than :code:`n_particles`
                if used with the :code:`Ring` topology the additional
                parameters k and p must be included
                * p: int {1,2}
                    the Minkowski p-norm to use. 1 is the sum-of-absolute
                    values (or L1 distance) while 2 is the Euclidean (or L2)
                    distance.
                if used with the :code:`VonNeumann` topology the additional
                parameters p and r must be included
                * r: int
                    the range of the VonNeumann topology.  This is used to
                    determine the number of neighbours in the topology.
        topology : pyswarms.backend.topology.Topology
            a :code:`Topology` object that defines the topology to use in the
            optimization process. The currently available topologies are:
                * Star
                    All particles are connected
                * Ring (static and dynamic)
                    Particles are connected to the k nearest neighbours
                * VonNeumann
                    Particles are connected in a VonNeumann topology
                * Pyramid (static and dynamic)
                    Particles are connected in N-dimensional simplices
                * Random (static and dynamic)
                    Particles are connected to k random particles
                Static variants of the topologies remain with the same
                neighbours over the course of the optimization. Dynamic
                variants calculate new neighbours every time step.
        bounds : tuple of numpy.ndarray, optional
            a tuple of size 2 where the first entry is the minimum bound while
            the second entry is the maximum bound. Each array must be of shape
            :code:`(dimensions,)`.
        oh_strategy : dict, optional, default=None(constant options)
            a dict of update strategies for each option.
        bh_strategy : str
            a strategy for the handling of out-of-bounds particles.
        velocity_clamp : tuple, optional
            a tuple of size 2 where the first entry is the minimum velocity and
            the second entry is the maximum velocity. It sets the limits for
            velocity clamping.
        vh_strategy : str
            a strategy for the handling of the velocity of out-of-bounds particles.
        center : list (default is :code:`None`)
            an array of size :code:`dimensions`
        ftol : float
            relative error in objective_func(best_pos) acceptable for
            convergence. Default is :code:`-np.inf`
        ftol_iter : int
            number of iterations over which the relative error in
            objective_func(best_pos) is acceptable for convergence.
            Default is :code:`1`
        init_pos : numpy.ndarray, optional
            option to explicitly set the particles' initial positions. Set to
            :code:`None` if you wish to generate the particles randomly.
        """
        super(GeneralOptimizerPSO, self).__init__(
            n_particles,
            dimensions=dimensions,
            options=options,
            bounds=bounds,
            velocity_clamp=velocity_clamp,
            center=center,
            ftol=ftol,
            ftol_iter=ftol_iter,
            init_pos=init_pos,
        )
        if oh_strategy is None:
            oh_strategy = {}
        # Initialize logger
        self.rep = Reporter(logger=logging.getLogger(__name__))
        # Initialize the resettable attributes
        self.reset()
        # Initialize the topology and check for type
        if not isinstance(topology, Topology):
            raise TypeError("Parameter `topology` must be a Topology object")
        else:
            self.top = topology
        self.bh = BoundaryHandler(strategy=bh_strategy)
        self.vh = VelocityHandler(strategy=vh_strategy)
        self.oh = OptionsHandler(strategy=oh_strategy)
        self.name = __name__

    def optimize(
        self, objective_func, iters, n_processes=None, verbose=True, **kwargs
    ):
        """Optimize the swarm for a number of iterations

        Performs the optimization to evaluate the objective
        function :code:`f` for a number of iterations :code:`iter.`

        Parameters
        ----------
        objective_func : callable
            objective function to be evaluated
        iters : int
            number of iterations
        n_processes : int
            number of processes to use for parallel particle evaluation (default: None = no parallelization)
        verbose : bool
            enable or disable the logs and progress bar (default: True = enable logs)
        kwargs : dict
            arguments for the objective function

        Returns
        -------
        tuple
            the global best cost and the global best position.
        """
        # Apply verbosity
        if verbose:
            log_level = logging.INFO
        else:
            log_level = logging.NOTSET

        self.rep.log("Obj. func. args: {}".format(kwargs), lvl=logging.DEBUG)
        self.rep.log(
            "Optimize for {} iters with {}".format(iters, self.options),
            lvl=log_level,
        )

        # Populate memory of the handlers
        self.bh.memory = self.swarm.position
        self.vh.memory = self.swarm.position

        # Setup Pool of processes for parallel evaluation
        pool = None if n_processes is None else mp.Pool(n_processes)

        self.swarm.pbest_cost = np.full(self.swarm_size[0], np.inf)
        ftol_history = deque(maxlen=self.ftol_iter)
        for i in self.rep.pbar(iters, self.name) if verbose else range(iters):
            # Compute cost for current position and personal best
            # fmt: off
            self.swarm.current_cost = compute_objective_function(self.swarm, objective_func, pool=pool, **kwargs)
            self.swarm.pbest_pos, self.swarm.pbest_cost = compute_pbest(self.swarm)
            best_cost_yet_found = self.swarm.best_cost
            # fmt: on
            # Update swarm
            self.swarm.best_pos, self.swarm.best_cost = self.top.compute_gbest(
                self.swarm, **self.options
            )
            # Print to console
            if verbose:
                self.rep.hook(best_cost=self.swarm.best_cost)
            hist = self.ToHistory(
                best_cost=self.swarm.best_cost,
                mean_pbest_cost=np.mean(self.swarm.pbest_cost),
                mean_neighbor_cost=self.swarm.best_cost,
                position=self.swarm.position,
                velocity=self.swarm.velocity,
            )
            self._populate_history(hist)
            # Verify stop criteria based on the relative acceptable cost ftol
            relative_measure = self.ftol * (1 + np.abs(best_cost_yet_found))
            delta = (
                np.abs(self.swarm.best_cost - best_cost_yet_found)
                < relative_measure
            )
            if i < self.ftol_iter:
                ftol_history.append(delta)
            else:
                ftol_history.append(delta)
                if all(ftol_history):
                    break
            # Perform options update
            self.swarm.options = self.oh(
                self.options, iternow=i, itermax=iters
            )
            # Perform velocity and position updates
            self.swarm.velocity = self.top.compute_velocity(
                self.swarm, self.velocity_clamp, self.vh, self.bounds
            )
            self.swarm.position = self.top.compute_position(
                self.swarm, self.bounds, self.bh
            )
        # Obtain the final best_cost and the final best_position
        final_best_cost = self.swarm.best_cost.copy()
        final_best_pos = self.swarm.pbest_pos[
            self.swarm.pbest_cost.argmin()
        ].copy()
        # Write report in log and return final cost and position
        self.rep.log(
            "Optimization finished | best cost: {}, best pos: {}".format(
                final_best_cost, final_best_pos
            ),
            lvl=log_level,
        )
        # Close Pool of Processes
        if n_processes is not None:
            pool.close()
        return (final_best_cost, final_best_pos)


text:
import os
import re
from jinja2 import Template, Environment, meta
import jinja2
from renderers import *
import logging

logger = logging.getLogger('hr.chatbot.server.template')

def render(string):
    render_result = ''
    variables = {}
    t = Template(string)
    env = Environment()
    ast = env.parse(string)
    for node in ast.body:
        if isinstance(node, jinja2.nodes.Assign):
            variables[node.target.name] = node.node.value
    func = get_render_func(ast)
    if func is not None:
        try:
            render_result = func(t) or t.render()
        except Exception as ex:
            logger.error("Rendering error, {}".format(ex))
            render_result = t.render()
    else:
        render_result = t.render()
    return {"render_result": render_result, "variables": variables}

def get_render_func(ast):
    func = None
    variables = meta.find_undeclared_variables(ast)
    if 'temperature' in variables:
        func = render_weather
    if 'location' in variables:
        func = render_location
    if 'faceemotion' in variables:
        func = render_face_emotion
    if 'objectdetected' in variables:
        func = render_object_detected
    if not func and variables:
        logger.error("Render is not found for template {}".format(string))
    return func

def render_template(answer):
    if answer and re.match('.*{.*}.*', answer):
        logger.info("Template answer {}".format(answer))
        render_result = render(answer)
        answer = render_result['render_result']
        if re.search('{.*}', answer):
            logger.error("answer contains illegal characters")
            answer = re.sub('{.*}', '', answer)
    return answer

if __name__ == '__main__':
    string = """aa {% set lineno = "file:123" %}{% set lineno2 = "file2:123" %}"""
    string  = render(string)
    print string

    string = """{% set location = "hong kong" %} {% if temperature is not defined %} I don't know {% elif temperature>30 %} it's really hot {% elif temperature<10 %} too cold here {% else %} Hmm, it\'s nice {% endif %}."""
    string  = render(string)
    print string

    string = """{% if temperature is not defined %} I don't know {% else %} The weather is {{ weather_desc }}, the temperature is {{ temperature }}. {% endif %}"""
    string  = render(string)
    print string

    string = """I think you are in {{ location }}. """
    string  = render(string)
    print string

    string = """{% if faceemotion is not defined %} I can't tell. How do you feel? {% else %} You look {{ faceemotion }}. {% endif %}"""
    string  = render(string)
    print string

    string = """{% if objectdetected is not defined %} Sorry, I don't know what's that. {% else %} Is that {{ objectdetected }}. {% endif %}"""
    string  = render(string)
    print string