text:
#ifndef _COCOS2D_CCLABEL_H_
#define _COCOS2D_CCLABEL_H_

#include "2d/CCSpriteBatchNode.h"
#include "base/ccTypes.h"
#include "renderer/CCCustomCommand.h"
#include "2d/CCFontAtlas.h"

NS_CC_BEGIN

enum class GlyphCollection {

    DYNAMIC,
    NEHE,
    ASCII,
    CUSTOM
};

enum class LabelEffect {

    NORMAL,
    OUTLINE,
    SHADOW,
    GLOW
};

typedef struct _ttfConfig
{
    std::string fontFilePath;
    int fontSize;
    GlyphCollection glyphs;
    const char *customGlyphs;
    bool distanceFieldEnabled;
    int outlineSize;

    _ttfConfig(const char* filePath = "",int size = 12, const GlyphCollection& glyphCollection = GlyphCollection::DYNAMIC,
        const char *customGlyphCollection = nullptr,bool useDistanceField = false,int outline = 0)
        :fontFilePath(filePath)
        ,fontSize(size)
        ,glyphs(glyphCollection)
        ,customGlyphs(customGlyphCollection)
        ,distanceFieldEnabled(useDistanceField)
        ,outlineSize(outline)
    {
        if(outline > 0)
        {
            distanceFieldEnabled = false;
        }
    }
}TTFConfig;

class CC_DLL Label : public SpriteBatchNode, public LabelProtocol
{
public:
    static const int DistanceFieldFontSize;

    static Label* create();

    /** Creates a label with an initial string,font[font name or font file],font size, dimension in points, horizontal alignment and vertical alignment.
     * @warning It will generate texture by the platform-dependent code
     */
    static Label* createWithSystemFont(const std::string& text, const std::string& font, float fontSize,
        const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
        TextVAlignment vAlignment = TextVAlignment::TOP);

    /** Creates a label with an initial string,font file,font size, dimension in points, horizontal alignment and vertical alignment.
     * @warning Not support font name.
     * @warning Cache textures for each different font size or font file.
     */
    static Label * createWithTTF(const std::string& text, const std::string& fontFile, float fontSize,
        const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
        TextVAlignment vAlignment = TextVAlignment::TOP);

    /** Create a label with TTF configuration
     * @warning Not support font name.
     * @warning Cache textures for each different font file when enable distance field.
     * @warning Cache textures for each different font size or font file when disable distance field.
     */
    static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::LEFT, int maxLineWidth = 0);

    /* Creates a label with an FNT file,an initial string,horizontal alignment,max line width and the offset of image*/
    static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,
        const TextHAlignment& alignment = TextHAlignment::LEFT, int maxLineWidth = 0,
        const Vec2& imageOffset = Vec2::ZERO);

    static Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
    static Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
    static Label * createWithCharMap(const std::string& plistFile);

    /** set TTF configuration for Label */
    virtual bool setTTFConfig(const TTFConfig& ttfConfig);
    virtual const TTFConfig& getTTFConfig() const { return _fontConfig;}

    virtual bool setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset = Vec2::ZERO);
    const std::string& getBMFontFilePath() const { return _bmFontPath;}

    virtual bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
    virtual bool setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
    virtual bool setCharMap(const std::string& plistFile);

    /* Sets the system font[font name or font file] of label*/
    virtual void setSystemFontName(const std::string& systemFont);
    virtual const std::string& getSystemFontName() const { return _systemFont;}

    /* Sets the system font size of label.*/
    virtual void setSystemFontSize(float fontSize);
    virtual float getSystemFontSize() const { return _systemFontSize;}

    /** changes the string to render
    * @warning It is as expensive as changing the string if you haven't set up TTF/BMFont/CharMap for the label.
    */
    virtual void setString(const std::string& text) override;

    virtual const std::string& getString() const override {  return _originalUTF8String; }

    /** Sets the text color of the label
     * Only support for TTF and system font
     * @warning Different from the color of Node.
     */
    virtual void setTextColor(const Color4B &color);
    /** Returns the text color of this label
     * Only support for TTF and system font
     * @warning Different from the color of Node.
     */
    const Color4B& getTextColor() const { return _textColor;}

    /**
     * Enable shadow for the label
     *
     * @todo support blur for shadow effect
     */
    virtual void enableShadow(const Color4B& shadowColor = Color4B::BLACK,const Size &offset = Size(2,-2), int blurRadius = 0);

    /** only support for TTF */
    virtual void enableOutline(const Color4B& outlineColor,int outlineSize = -1);

    /** only support for TTF */
    virtual void enableGlow(const Color4B& glowColor);

    /** disable shadow/outline/glow rendering */
    virtual void disableEffect();

    void setAlignment(TextHAlignment hAlignment) { setAlignment(hAlignment,_vAlignment);}
    TextHAlignment getTextAlignment() const { return _hAlignment;}

    void setAlignment(TextHAlignment hAlignment,TextVAlignment vAlignment);

    void setHorizontalAlignment(TextHAlignment hAlignment) { setAlignment(hAlignment,_vAlignment); }
    TextHAlignment getHorizontalAlignment() const { return _hAlignment; }

    void setVerticalAlignment(TextVAlignment vAlignment) { setAlignment(_hAlignment,vAlignment); }
    TextVAlignment getVerticalAlignment() const { return _vAlignment; }

    void setLineBreakWithoutSpace(bool breakWithoutSpace);

    /** Sets the max line width of the label.
     * The label's max line width be used for force line breaks if the set value not equal zero.
     * The label's width and max line width has not always to be equal.
     */
    void setMaxLineWidth(unsigned int maxLineWidth);
    unsigned int getMaxLineWidth() { return _maxLineWidth;}

    /** Sets the untransformed size of the label.
     * The label's width be used for text align if the set value not equal zero.
     * The label's max line width will be equal to the same value.
     */
    void setWidth(unsigned int width) { setDimensions(width,_labelHeight);}
    unsigned int getWidth() const { return _labelWidth; }

    /** Sets the untransformed size of the label.
     * The label's height be used for text align if the set value not equal zero.
     * The text will display of incomplete when the size of label not enough to support display all text.
     */
    void setHeight(unsigned int height){ setDimensions(_labelWidth,height);}
    unsigned int getHeight() const { return _labelHeight;}

    /** Sets the untransformed size of the label in a more efficient way. */
    void setDimensions(unsigned int width,unsigned int height);
    const Size& getDimensions() const{ return _labelDimensions;}

    /** update content immediately.*/
    virtual void updateContent();

    virtual Sprite * getLetter(int lettetIndex);

    /** clip upper and lower margin for reduce height of label.
     */
    void setClipMarginEnabled(bool clipEnabled) { _clipEnabled = clipEnabled; }
    bool isClipMarginEnabled() const { return _clipEnabled; }

    /** Sets the line height of the label
      @warning Not support system font
      @since v3.2.0
     */
    void setLineHeight(float height);
    /** Returns the line height of this label
      @warning Not support system font
     */
    float getLineHeight() const;

    /** Sets the additional kerning of the label
      @warning Not support system font
      @since v3.2.0
     */
    void setAdditionalKerning(float space);
    /** Returns the additional kerning of this label
      @warning Not support system font
      @since v3.2.0
     */
    float getAdditionalKerning() const;

    // string related stuff
    int getStringNumLines() const { return _currNumLines;}
    int getStringLength() const;

    FontAtlas* getFontAtlas() { return _fontAtlas; }

    virtual void setBlendFunc(const BlendFunc &blendFunc) override;

    virtual bool isOpacityModifyRGB() const override;
    virtual void setOpacityModifyRGB(bool isOpacityModifyRGB) override;
    virtual void updateDisplayedColor(const Color3B& parentColor) override;
    virtual void updateDisplayedOpacity(GLubyte parentOpacity) override;

    virtual void setScale(float scale) override;
    virtual void setScaleX(float scaleX) override;
    virtual void setScaleY(float scaleY) override;
    virtual float getScaleX() const override;
    virtual float getScaleY() const override;

    virtual void addChild(Node * child, int zOrder=0, int tag=0) override;
    virtual void sortAllChildren() override;

    virtual std::string getDescription() const override;

    virtual const Size& getContentSize() const override;

    virtual Rect getBoundingBox() const override;

    virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
    virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;

    CC_DEPRECATED_ATTRIBUTE static Label* create(const std::string& text, const std::string& font, float fontSize,
        const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
        TextVAlignment vAlignment = TextVAlignment::TOP);

    CC_DEPRECATED_ATTRIBUTE virtual void setFontDefinition(const FontDefinition& textDefinition);
    CC_DEPRECATED_ATTRIBUTE const FontDefinition& getFontDefinition() const { return _fontDefinition; }

    CC_DEPRECATED_ATTRIBUTE int getCommonLineHeight() const { return static_cast<int>(getLineHeight());}

protected:
    void onDraw(const Mat4& transform, bool transformUpdated);

    struct LetterInfo
    {
        FontLetterDefinition def;

        Vec2 position;
        Size  contentSize;
        int   atlasIndex;
    };
    enum class LabelType {

        TTF,
        BMFONT,
        CHARMAP,
        STRING_TEXTURE
    };

    /**
    * @js NA
    */
    Label(FontAtlas *atlas = nullptr, TextHAlignment hAlignment = TextHAlignment::LEFT,
        TextVAlignment vAlignment = TextVAlignment::TOP,bool useDistanceField = false,bool useA8Shader = false);
    /**
    * @js NA
    * @lua NA
    */
    virtual ~Label();

    virtual void setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false);

    bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex);
    bool recordPlaceholderInfo(int spriteIndex);

    void setFontScale(float fontScale);

    virtual void alignText();

    bool computeHorizontalKernings(const std::u16string& stringToRender);

    void computeStringNumLines();

    void updateQuads();

    virtual void updateColor() override;

    virtual void updateShaderProgram();

    void drawShadowWithoutBlur();

    void drawTextSprite(Renderer *renderer, uint32_t parentFlags);

    void createSpriteWithFontDefinition();

    void updateFont();
    void reset();

    std::string _bmFontPath;

    bool _isOpacityModifyRGB;
    bool _contentDirty;

    bool _systemFontDirty;
    std::string _systemFont;
    float         _systemFontSize;
    LabelType _currentLabelType;

    std::vector<SpriteBatchNode*> _batchNodes;
    FontAtlas *                   _fontAtlas;
    std::vector<LetterInfo>       _lettersInfo;

    TTFConfig _fontConfig;

    //compatibility with older LabelTTF
    Sprite* _textSprite;
    FontDefinition _fontDefinition;
    bool  _compatibleMode;

    //! used for optimization
    Sprite *_reusedLetter;
    Rect _reusedRect;
    int _limitShowCount;

    float _additionalKerning;
    float _commonLineHeight;
    bool  _lineBreakWithoutSpaces;
    int * _horizontalKernings;

    unsigned int _maxLineWidth;
    Size         _labelDimensions;
    unsigned int _labelWidth;
    unsigned int _labelHeight;
    TextHAlignment _hAlignment;
    TextVAlignment _vAlignment;

    int           _currNumLines;
    std::u16string _currentUTF16String;
    std::string          _originalUTF8String;

    float _fontScale;

    bool _useDistanceField;
    bool _useA8Shader;

    LabelEffect _currLabelEffect;
    Color4B _effectColor;
    Color4F _effectColorF;

    GLuint _uniformEffectColor;
    GLuint _uniformTextColor;
    CustomCommand _customCommand;

    bool    _shadowDirty;
    bool    _shadowEnabled;
    Size    _shadowOffset;
    int     _shadowBlurRadius;
    Mat4  _shadowTransform;
    Color3B _shadowColor;
    float   _shadowOpacity;
    Sprite*   _shadowNode;

    int     _outlineSize;

    Color4B _textColor;
    Color4F _textColorF;

    bool _clipEnabled;
    bool _blendFuncDirty;
    bool _insideBounds;                     /// whether or not the sprite was inside bounds the previous frame

private:
    CC_DISALLOW_COPY_AND_ASSIGN(Label);

    friend class LabelTextFormatter;
};

NS_CC_END

#endif /*__COCOS2D_CCLABEL_H */


text:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { AbstractGroupComponent } from '../shared/abstract-groups-items/abstract-group.component';
import { MultipathSourceViewModel } from './multipath-source-view-model';
import { SiteLogService } from '../shared/site-log/site-log.service';

/**
 * This class represents a group of Pressure Sensors.
 */
@Component({
    moduleId: module.id,
    selector: 'multipath-source-group',
    templateUrl: 'multipath-source-group.component.html',
})
export class MultipathSourceGroupComponent extends AbstractGroupComponent<MultipathSourceViewModel> {

    constructor(protected siteLogService: SiteLogService, formBuilder: FormBuilder) {
        super(siteLogService, formBuilder);
    }

    getItemName(): string {
        return 'Multipath Source';
    }

    getControlName(): string {
        return 'multipathSources';
    }

    getNewItemViewModel(): MultipathSourceViewModel {
        return new MultipathSourceViewModel();
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: "Happy Father's Day!"
---

<embed src="http://player.youku.com/player.php/sid/XNDE0NjIxMDg0/v.swf" allowFullScreen="true" quality="high" width="480" height="400" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>

.

.

© 2012 QING Pei. All rights reserved.


text:
(function(Iconizer){
	Iconizer.icons=function(icons,target,options){
		return new Icons(icons,target,options);
	}
	function Icons(icons,target,options){
		if(icons!=undefined){
			this.update(icons,target,options);
		}
	}
	Icons.prototype.update=function(icons,newTarget,options){
		newTarget ? this.removeFromDom():wrapper=this.emptyWrapper();
		//create the new icons
		this.icons=[];
		if( Object.prototype.toString.call( icons ) === '[object Object]' ) {
			this.icons.push(new Icon(icons));
		}
		else{
			icons.forEach(function(element,index){
				this.icons[index]=new Icon(element);
			}.bind(this));
		}
		if(newTarget){
			this.addToTarget(newTarget,options);
		}
		else if(wrapper){
			this.insertIntoWrapper(wrapper);
		}
		return this;
	}

	Icons.prototype.replace=function(icons,target,options){
		//coming soon
	}
	Icons.prototype.move=function(target,options){
		this.removeFromDom().addToTarget(target,options);
	}
	Icons.prototype.addToTarget=function(target,options){
		options = options ? options:{};
		var wrapper=document.createElement("div");
		var wrapperClass="iconizer-wrapper";
		wrapper.setAttribute("class",(options.class ? options.class+" ":"")+wrapperClass)
		this.insertIntoWrapper(wrapper);
		switch(options.location){
			case "before":
				target.insertBefore(wrapper,target.firstChild);
				break;
			case "append":
			default:
				target.appendChild(wrapper,target.firstChild);
				break;
		}
		return this;
	}
	Icons.prototype.insertIntoWrapper=function(wrapper){
		this.icons.forEach(function(element){
			wrapper.appendChild(element.icon);
		});
	}
	Icons.prototype.removeFromDom=function(){
		var wrapper=this.emptyWrapper(wrapper);
		if(wrapper){
			var wrapperClass=wrapper.getAttribute("class");
			if(wrapperClass!=null && wrapperClass.indexOf("iconizer-wrapper")!==-1){
				wrapper.parentNode.removeChild(wrapper);
			}
		}
		return this;
	}
	Icons.prototype.emptyWrapper=function(){
		if(this.icons && this.icons[0].icon.parentNode!=null){
			var wrapper=this.icons[0].icon.parentNode;
			this.icons.forEach(function(element){
				wrapper.removeChild(element.icon);
			});
			return wrapper;
		}
		return false;
	}
	function Icon(info){
		var icon,wrapper;
		if(info.img){
			icon=document.createElement("img");
			icon.setAttribute("src",info.img);
		}
		else{
			icon=document.createElement("i");
			icon.setAttribute("class","icon-"+info.class);
		}
		if(info.wrapper){
			var wrapper=document.createElement(info.wrapper.type);
			if(info.wrapper.class){
				wrapper.setAttribute("class",info.wrapper.class);
			}
			wrapper.appendChild(icon);
			if(info.wrapper.text){
				wrapper.appendChild(document.createTextNode(info.wrapper.text));
			}
		}
		this.icon=wrapper ? wrapper:icon;
		this.defaultEvent="click";
		if(info.handler!=undefined){
			this.addHandler(info.handler,info.eventType);
		}
	}
	Icon.prototype.addHandler=function(handler,eventType){
		this.icon.addEventListener(eventType ? eventType:this.defaultEvent,handler,true);
	}
}( window.Iconizer = window.Iconizer || {}));


text:
package pl.edu.ug.introductiontojee.servlets.servlet.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(urlPatterns = "/")
public class CounterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = getServletContext();

        Counter counter = (Counter) servletContext.getAttribute("counter");
        counter.set(counter.get() + 1);
        servletContext.setAttribute("counter", counter);

        PrintWriter writer = response.getWriter();
        String body = "" +
                "" +
                "
Counter: " + counter + "
" +
                "
Context path: " + servletContext.getContextPath() + "
" +
                "
Server info: " + servletContext.getServerInfo() + "
" +
                "" +
                "";

        writer.println(body);
    }
}


text:
package com.stylelint.nodejs;

import com.google.common.base.Joiner;
import com.intellij.execution.configurations.PathEnvironmentVariableUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.EnvironmentUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class NodeFinder {
    private static final Pattern NVM_NODE_DIR_NAME_PATTERN = Pattern.compile("^v?(\\d+)\\.(\\d+)\\.(\\d+)$");
    private static final String NODE_MODULES = "node_modules";
    private static final String BIN = ".bin";
    private static final String NVM_DIR = "NVM_DIR";
    private static final String USR_LOCAL_CELLAR_NODE = "/usr/local/Cellar/node";

    private NodeFinder() {
    }

    public static String getBinName(String baseBinName) {
        return SystemInfo.isWindows ? baseBinName + ".cmd" : baseBinName;
    }

    @NotNull
    private static List<File> searchNodeModulesBin(String exeFileName) {
        Set<File> interpreters = ContainerUtil.newLinkedHashSet();
        List<File> fromPath = PathEnvironmentVariableUtil.findAllExeFilesInPath(exeFileName);
        List<File> nvmInterpreters = listNodeInterpretersFromNvm(exeFileName);
        List<File> brewInterpreters = listNodeInterpretersFromHomeBrew(exeFileName);
        interpreters.addAll(fromPath);
        interpreters.removeAll(nvmInterpreters);
        interpreters.removeAll(brewInterpreters);
        interpreters.addAll(nvmInterpreters);
        interpreters.addAll(brewInterpreters);
        return ContainerUtil.newArrayList(interpreters);
    }

    @NotNull
    public static List<File> searchAllScopesForBin(File projectRoot, String exeFileName) {
        List<File> globalJscsBin = searchNodeModulesBin(exeFileName);
        if (projectRoot != null) {
            File file = resolvePath(projectRoot, NODE_MODULES, BIN, exeFileName);
            if (file.exists()) {
                globalJscsBin.add(file);
            }
        }
        return globalJscsBin;
    }

    private static File resolvePath(File root, @Nullable String first, @Nullable String second, String... rest) {
        String path = buildPath(first, second, rest);
        return new File(root, path);
    }

    private static String buildPath(@Nullable String first, @Nullable String second, String... rest) {
        return Joiner.on(File.separatorChar).join(first, second, (Object[]) rest);
    }

    @NotNull
    private static List<File> listNodeInterpretersFromNvm(String exeFileName) {
        String nvmDirPath = EnvironmentUtil.getValue(NVM_DIR);
        if (StringUtil.isEmpty(nvmDirPath)) {
            return Collections.emptyList();
        }
        File nvmDir = new File(nvmDirPath);
        if (nvmDir.isDirectory() && nvmDir.isAbsolute()) {
            return listNodeInterpretersFromVersionDir(nvmDir, exeFileName);
        }
        return Collections.emptyList();
    }

    private static List<File> listNodeInterpretersFromHomeBrew(String exeFileName) {
        return listNodeInterpretersFromVersionDir(new File(USR_LOCAL_CELLAR_NODE), exeFileName);
    }

    private static List<File> listNodeInterpretersFromVersionDir(@NotNull File parentDir, String exeFileName) {
        if (!parentDir.isDirectory()) {
            return Collections.emptyList();
        }
        File[] dirs = parentDir.listFiles((dir, name) -> NodeFinder.structureNodeVersionStr(name) != null);
        if (dirs == null || dirs.length == 0) {
            return Collections.emptyList();
        }
        Arrays.sort(dirs, (dir1, dir2) -> {
            int[] v1 = NodeFinder.structureNodeVersionStr(dir1.getName());
            int[] v2 = NodeFinder.structureNodeVersionStr(dir2.getName());
            if (v1 != null && v2 != null) {
                for (int i = 0; i < v1.length; i++) {
                    if (i < v2.length) {
                        int cmp = v2[i] - v1[i];
                        if (cmp != 0) {
                            return cmp;
                        }
                    }
                }
            }
            return dir1.getName().compareTo(dir2.getName());
        });
        List<File> interpreters = ContainerUtil.newArrayListWithCapacity(dirs.length);
        for (File dir : dirs) {
            File interpreter = new File(dir, "bin" + File.separator + exeFileName);
            if (interpreter.isFile() && interpreter.canExecute()) {
                interpreters.add(interpreter);
            }
        }
        return interpreters;
    }

    @Nullable
    private static int[] structureNodeVersionStr(@NotNull String name) {
        Matcher matcher = NVM_NODE_DIR_NAME_PATTERN.matcher(name);
        if (matcher.matches() && matcher.groupCount() == 3) {
            try {
                return new int[]{Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))};
            } catch (Exception ignored) {
            }
        }
        return null;
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class News_model extends Base_model {

	protected $connection;

    public function __construct()
    {
        parent::__construct();
    }

    public function insert_news($data)
    {
        $this->db->trans_begin();

        // insert post
            $sql_post = "INSERT INTO post (`category_id`, `category_name`, `type`, `status`, `created_by`) VALUES (?, ?, ?, ?, ?)";
            $this->db->query($sql_post, array($data['category_id'], $data['category_name'], 'news', $data['status'], $data['by']));
            $post_id = $this->db->insert_id();
        // insert news
			$sql_news = "INSERT INTO news (`post_id`,`title`, `url`, `description`, `detail`, `order`) VALUES (?, ?, ?, ?, ?, ?)";
			$this->db->query($sql_news, array($post_id, $data['title'], $data['url'], $data['description'], $data['detail'], $data['order']));
        // insert url_route
            $sql_url = "INSERT INTO url_route (`url`, `category_id`, `post_id`, `type`, `created_by`) VALUES (?, ?, ?, ?, ?)";
            $this->db->query($sql_url, array($data['url'], $data['category_id'], $post_id, 'news', $data['by']));

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return FALSE;
        }
        else
        {
            $this->db->trans_commit();
            return TRUE;
        }
    }

    public function update_news($data)
    {
        $this->db->trans_begin();

        // update news
            $sql_news = "UPDATE news
                            SET `title`=?, `url`=?, `thumbnail`=?,
                                `description`=?, `order`=?, `detail`=?
                            WHERE `post_id` = ?
                            ";
            $this->db->query($sql_news, array($data['title'], $data['url'], $data['thumbnail'], $data['description'],$data['order'], $data['detail'], $data['id']));
        // update post
    		$sql_post = "UPDATE post
    					SET `category_id`=?, `status`=?, `modified_datetime`=?, `modified_by`=?
    					WHERE `id`= ?
    					";
    		$this->db->query($sql_post, array($data['category_id'], $data['status'], $data['datetime'], $data['by'], $data['id']));

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return FALSE;
        }
        else
        {
            $this->db->trans_commit();
            return TRUE;
        }
    }

/*
 * get product
 * */
    public function get_one($url)
    {
        $sql = "SELECT
                    post.id
                    ,post.category_id
                    ,post.category_name
                    ,post.status
                    ,news.title
                    ,news.url
                    ,news.description
                    ,news.thumbnail
                    ,news.order
                    ,news.detail
                FROM post
                INNER JOIN news ON news.post_id = post.id
            ";
        $where = " WHERE post.type='news' AND post.del_flg=0 AND news.url='".$url."'";
        $sql .= $where;
        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

    public function get_related($post_id, $category_id)
    {
        $sql = "SELECT
                    post.id
                    ,post.category_id
                    ,post.category_name
                    ,post.status
                    ,news.title
                    ,news.url
                    ,news.description
                    ,news.thumbnail
                    ,news.order
                    ,news.detail
                FROM post
                INNER JOIN news ON news.post_id = post.id
            ";
        $where = " WHERE post.type = 'news' AND post.del_flg=0 AND post.category_id='".$category_id."' AND post.id<>'".$post_id."'";
        $sql .= $where;
        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

}


text:
export CONFIG="$1"
export VERSION="$2"
export TASK="$3"
export GPACK="$4"

# make sure we are locked and loaded
[ -d "./bin" ] || ( tar fzx default.tgz; rm default.tgz )        # make sure to cleanup right away
export SEED=`echo $GPACK | sed -e 's@.*_seed-@@' -e 's@_.*@@'`
echo SEED: $SEED
export BASEDIR=`pwd`
source ./bin/helpers.sh

# tell us the initial state
initialState $*

# load all parameters relevant to this task
echo " Initialize package"
source $BASEDIR/$VERSION/${TASK}.env

# make sure to contain file mess
mkdir -p ./work
cd    ./work
export WORKDIR=`pwd`

# this might be an issue with root
export HOME=$WORKDIR

# make a working area
echo " Start to work now"
pwd
ls -lhrt

# make sure site is configured, if not, configure it (for DB access, not needed for lhe/gen)
configureSite

# initialize LHE step
setupCmssw $GEN_CMSSW_VERSION $GEN_PY

# start clean by removing copies of existing generator
executeCmd rm -rf $GENERATOR

# get our fresh generator tar ball
executeCmd tar fzx $BASEDIR/generators/$GENERATOR.tgz

####################################################################################################
# C H O O S E   T H E   G E N E R A T O R  [and run it]
####################################################################################################
echo " INFO -- using generator type: $GENERATOR_TYPE"
if   [ "$GENERATOR_TYPE" == "powheg" ]
then
  executeCmd $TIME $BASEDIR/bin/runPowheg.sh $TASK $GPACK
elif [ "$GENERATOR_TYPE" == "madgraph" ]
then
  executeCmd $TIME $BASEDIR/bin/runMadgraph.sh $TASK $GPACK
elif [ "$GENERATOR_TYPE" == "jhu" ]
then
  executeCmd $TIME $BASEDIR/bin/runJHU.sh $TASK $GPACK
else
  echo " ERROR -- generator type is not known (\$GENERATOR_TYPE=$GENERATOR_TYPE)"
  echo "          EXIT now because there is no LHE file."
  exit 1
fi

showDiskSpace

####################################################################################################
# hadronize step
####################################################################################################

# initialize GEN step
setupCmssw $GEN_CMSSW_VERSION $GEN_PY
executeCmd $TIME cmsRun ${GEN_PY}.py
if ! [ -e "${TASK}_${GPACK}_gen.root" ]
then
  echo " ERROR -- generation failed. No output file: ${TASK}_${GPACK}_gen.root"
  echo "          EXIT now because there is no GEN file."
  exit 1
fi

showDiskSpace

####################################################################################################
# Making the AODSIM step
####################################################################################################

if [ "$CONFIG" == "fastsm" ]
then

  # using fastsim
  ###############

  # initialize
  setupCmssw $FSM_CMSSW_VERSION $FSM_PY
  executeCmd $TIME cmsRun ${FSM_PY}.py
  if ! [ -e "${TASK}_${GPACK}_aodsim.root" ]
  then
    echo " ERROR -- fast simulation failed. No output file: ${TASK}_${GPACK}_aodsim.root"
    echo "          EXIT now because there is no AODSIM file."
    exit 1
  fi

  showDiskSpace

  # now aodsim is available, $TIME to cleanup LHE and gen

  exeCmd rm $WORKDIR/${TASK}_${GPACK}.lhe $WORKDIR/${TASK}_${GPACK}_gen.root

elif [ "$CONFIG" == "fullsm" ]
then

  # using fullsim
  ###############

  # gen->sim

  # initialize
  setupCmssw $SIM_CMSSW_VERSION $SIM_PY
  executeCmd $TIME cmsRun ${SIM_PY}.py
  if ! [ -e "${TASK}_${GPACK}_gensim.root" ]
  then
    echo " ERROR -- simulation step failed. No output file: ${TASK}_${GPACK}_gensim.root"
    echo "          EXIT now because there is no SIM file."
    exit 1
  fi

  # sim->simraw

  # initialize
  setupCmssw $SMR_CMSSW_VERSION $SMR_PY
  executeCmd $TIME cmsRun ${SMR_PY}.py
  if ! [ -e "${TASK}_${GPACK}_simraw.root" ]
  then
    echo " ERROR -- simraw step failed. No output file: ${TASK}_${GPACK}_simraw.root"
    echo "          EXIT now because there is no SIMRAW file."
    exit 1
  fi

  # simraw->aodsim

  # initialize
  setupCmssw $DGR_CMSSW_VERSION $DGR_PY
  executeCmd $TIME cmsRun ${DGR_PY}.py
  if ! [ -e "${TASK}_${GPACK}_aodsim.root" ]
  then
    echo " ERROR -- digireco failed. No output file: ${TASK}_${GPACK}_aodsim.root"
    echo "          EXIT now because there is no AODSIM file."
    exit 1
  fi

  showDiskSpace

  # now aodsim is available, $TIME to cleanup LHE and gen
  exeCmd rm $WORKDIR/${TASK}_${GPACK}.lhe $WORKDIR/${TASK}_${GPACK}_gen.root \
            $WORKDIR/${TASK}_${GPACK}_gensim.root $WORKDIR/${TASK}_${GPACK}_simraw.root

else

  # unknown config
  ################

  echo " ERROR -- config: $CONFIG not known."
  exit 1

fi

####################################################################################################
# miniaodsim step
####################################################################################################
# initialize MINIAOD step

setupCmssw $MIN_CMSSW_VERSION $MIN_PY
executeCmd $TIME cmsRun ${MIN_PY}.py
if ! [ -e "${TASK}_${GPACK}_miniaodsim.root" ]
then
  echo " ERROR -- miniaodsim failed. No output file: ${TASK}_${GPACK}_miniaodsim.root"
  echo "          EXIT now because there is no MINIAODSIM file."
  exit 1
fi

showDiskSpace

###########################################################################################
# initialize BAMBU
####################################################################################################
# bambu step

setupCmssw $BAM_CMSSW_VERSION $BAM_PY

# unpack the additional tarball
cd CMSSW_$BAM_CMSSW_VERSION
executeCmd tar fzx $BASEDIR/$VERSION/tgz/bambu_${BAM_CMSSW_VERSION}.tgz
cd $WORKDIR

executeCmd $TIME cmsRun ${BAM_PY}.py
# this is a little naming issue that has to be fixed
mv ${TASK}_${GPACK}_bambu*  ${TASK}_${GPACK}_bambu.root
if ! [ -e "${TASK}_${GPACK}_bambu.root" ]
then
  echo " ERROR -- bambu production failed. No output file: ${TASK}_${GPACK}_bambu.root"
  echo "          EXIT now because there is no BAMBU file."
  exit 1
fi

showDiskSpace

####################################################################################################
# push our files out to the Tier-2 / Dropbox
####################################################################################################
cd $WORKDIR
pwd
ls -lhrt

# define base output location
REMOTE_SERVER="se01.cmsaf.mit.edu"
REMOTE_BASE="srm/v2/server?SFN=/mnt/hadoop/cms/store"
REMOTE_USER_DIR="/user/paus/$CONFIG/$VERSION"

sample=`echo $GPACK | sed 's/\(.*\)_nev.*/\1/'`

# this is somewhat overkill but works very reliably, I suppose
setupCmssw 7_6_3 cmscp.py
tar fzx $BASEDIR/tgz/copy.tgz
pwd=`pwd`
# always first show the proxy
voms-proxy-info -all
for file in `echo ${TASK}_${GPACK}_bambu* ${TASK}_${GPACK}_miniaodsim*`
do
  # now do the copy
  executeCmd $TIME ./cmscp.py \
    --middleware OSG --PNN $REMOTE_SERVER --se_name $REMOTE_SERVER \
    --inputFileList $pwd/${file} \
    --destination srm://$REMOTE_SERVER:8443/${REMOTE_BASE}${REMOTE_USER_DIR}/${TASK}_${sample} \
    --for_lfn ${REMOTE_USER_DIR}/${TASK}_${sample}
done

tar fzx $BASEDIR/tgz/PyCox.tgz
cd PyCox
./install.sh
cat setup.sh
source setup.sh
# put config in the default spot
mv $BASEDIR/.pycox.cfg pycox.cfg
cd -
pwd=`pwd`

# make sure directory exists
executeCmd python ./PyCox/pycox.py --action mkdir \
           --source /cms/store${REMOTE_USER_DIR}/${TASK}_${sample}
for file in `echo ${TASK}_${GPACK}_bambu* ${TASK}_${GPACK}_miniaodsim*`
do
  # now do the copy
  executeCmd python ./PyCox/pycox.py --action up --source $file \
                        --target /cms/store${REMOTE_USER_DIR}/${TASK}_${sample}/${file}
done

# make condor happy because it also might want some of the files
executeCmd mv $WORKDIR/*.root $BASEDIR/

# leave the worker super clean

testBatch
if [ "$?" == "1" ]
then
  cd $BASEDIR
  executeCmd rm -rf $WORKDIR *.root bin/ generators/ html/ LICENSE  $VERSION/ README root/ tgz/
fi

# create the pickup output file for condor

echo " ---- D O N E ----" > $BASEDIR/${TASK}_${GPACK}.empty

pwd
ls -lhrt
echo " ---- D O N E ----"

exit 0


text:
"""
DRAC vendor-passthru interface
"""

from ironic_lib import metrics_utils

from ironic.common.i18n import _
from ironic.conductor import task_manager
from ironic.drivers import base
from ironic.drivers.modules.drac import bios as drac_bios
from ironic.drivers.modules.drac import common as drac_common
from ironic.drivers.modules.drac import job as drac_job

METRICS = metrics_utils.get_metrics_logger(__name__)

class DracVendorPassthru(base.VendorInterface):
    """Interface for DRAC specific methods."""

    def get_properties(self):
        """Return the properties of the interface."""
        return drac_common.COMMON_PROPERTIES

    @METRICS.timer('DracVendorPassthru.validate')
    def validate(self, task, **kwargs):
        """Validate the driver-specific info supplied.

        This method validates whether the 'driver_info' property of the
        supplied node contains the required information for this driver to
        manage the power state of the node.

        :param task: a TaskManager instance containing the node to act on.
        :param kwargs: not used.
        :raises: InvalidParameterValue if required driver_info attribute
                 is missing or invalid on the node.
        """
        return drac_common.parse_driver_info(task.node)

    @METRICS.timer('DracVendorPassthru.get_bios_config')
    @base.passthru(['GET'], async=False,
                   description=_("Returns a dictionary containing the BIOS "
                                 "settings from a node."))
    def get_bios_config(self, task, **kwargs):
        """Get the BIOS configuration.

        This method is used to retrieve the BIOS settings from a node.

        :param task: a TaskManager instance containing the node to act on.
        :param kwargs: not used.
        :raises: DracOperationError on an error from python-dracclient.
        :returns: a dictionary containing BIOS settings.
        """
        bios_attrs = {}
        for name, bios_attr in drac_bios.get_config(task.node).items():
            bios_attrs[name] = bios_attr.__dict__

        return bios_attrs

    @METRICS.timer('DracVendorPassthru.set_bios_config')
    @base.passthru(['POST'], async=False,
                   description=_("Change the BIOS configuration on a node. "
                                 "Required argument : a dictionary of "
                                 "{'AttributeName': 'NewValue'}. Returns "
                                 "a dictionary containing the "
                                 "'commit_required' key with a Boolean value "
                                 "indicating whether commit_bios_config() "
                                 "needs to be called to make the changes."))
    @task_manager.require_exclusive_lock
    def set_bios_config(self, task, **kwargs):
        """Change BIOS settings.

        This method is used to change the BIOS settings on a node.

        :param task: a TaskManager instance containing the node to act on.
        :param kwargs: a dictionary of {'AttributeName': 'NewValue'}
        :raises: DracOperationError on an error from python-dracclient.
        :returns: A dictionary containing the ``commit_required`` key with a
                  Boolean value indicating whether commit_bios_config() needs
                  to be called to make the changes.
        """
        return drac_bios.set_config(task, **kwargs)

    @METRICS.timer('DracVendorPassthru.commit_bios_config')
    @base.passthru(['POST'], async=False,
                   description=_("Commit a BIOS configuration job submitted "
                                 "through set_bios_config(). Required "
                                 "argument: 'reboot' - indicates whether a "
                                 "reboot job should be automatically created "
                                 "with the config job. Returns a dictionary "
                                 "containing the 'job_id' key with the ID of "
                                 "the newly created config job, and the "
                                 "'reboot_required' key indicating whether "
                                 "the node needs to be rebooted to start the "
                                 "config job."))
    @task_manager.require_exclusive_lock
    def commit_bios_config(self, task, reboot=False, **kwargs):
        """Commit a BIOS configuration job.

        This method is used to commit a BIOS configuration job.
        submitted through set_bios_config().

        :param task: a TaskManager instance containing the node to act on.
        :param reboot: indicates whether a reboot job should be automatically
                       created with the config job.
        :param kwargs: not used.
        :raises: DracOperationError on an error from python-dracclient.
        :returns: A dictionary containing the ``job_id`` key with the id of the
                  newly created config job, and the ``reboot_required`` key
                  indicating whether the node needs to be rebooted to start the
                  config job.
        """
        job_id = drac_bios.commit_config(task, reboot=reboot)
        return {'job_id': job_id, 'reboot_required': not reboot}

    @METRICS.timer('DracVendorPassthru.abandon_bios_config')
    @base.passthru(['DELETE'], async=False,
                   description=_("Abandon a BIOS configuration job previously "
                                 "submitted through set_bios_config()."))
    @task_manager.require_exclusive_lock
    def abandon_bios_config(self, task, **kwargs):
        """Abandon a BIOS configuration job.

        This method is used to abandon a BIOS configuration previously
        submitted through set_bios_config().

        :param task: a TaskManager instance containing the node to act on.
        :param kwargs: not used.
        :raises: DracOperationError on an error from python-dracclient.
        """
        drac_bios.abandon_config(task)

    @base.passthru(['GET'], async=False,
                   description=_('Returns a dictionary containing the key '
                                 '"unfinished_jobs"; its value is a list of '
                                 'dictionaries. Each dictionary represents '
                                 'an unfinished config Job object.'))
    def list_unfinished_jobs(self, task, **kwargs):
        """List unfinished config jobs of the node.

        :param task: a TaskManager instance containing the node to act on.
        :param kwargs: not used.
        :returns: a dictionary containing the ``unfinished_jobs`` key; this key
                  points to a list of dicts, with each dict representing a Job
                  object.
        :raises: DracOperationError on an error from python-dracclient.
        """
        jobs = drac_job.list_unfinished_jobs(task.node)
        # FIXME(mgould) Do this without calling private methods.
        return {'unfinished_jobs': [job._asdict() for job in jobs]}


text:
package org.ovirt.engine.core.bll.storage.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.bll.validator.storage.StoragePoolValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.ForceSelectSPMParameters;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.BusinessEntitiesDefinitions;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsSpmStatus;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.vdsbroker.irsbroker.SpmStopOnIrsVDSCommandParameters;

@NonTransactiveCommandAttribute
public class ForceSelectSPMCommand<T extends ForceSelectSPMParameters> extends CommandBase<T> {

    private StoragePool storagePoolForVds;

    public ForceSelectSPMCommand(T parameters) {
        super(parameters);
        setVdsId(getParameters().getPreferredSPMId());
    }

    @Override
    protected boolean validate() {
        if (getVds() == null) {
            return failValidation(EngineMessage.VDS_NOT_EXIST);
        }

        if (getVds().getStatus() != VDSStatus.Up) {
            return failValidation(EngineMessage.CANNOT_FORCE_SELECT_SPM_VDS_NOT_UP);
        }

        if (getStoragePoolForVds() == null) {
            return failValidation(EngineMessage.CANNOT_FORCE_SELECT_SPM_VDS_NOT_IN_POOL);
        }

        if (getVds().getSpmStatus() != VdsSpmStatus.None) {
            return failValidation(EngineMessage.CANNOT_FORCE_SELECT_SPM_VDS_ALREADY_SPM);
        }

        if (getVds().getVdsSpmPriority() == BusinessEntitiesDefinitions.HOST_MIN_SPM_PRIORITY) {
            return failValidation(EngineMessage.CANNOT_FORCE_SELECT_SPM_VDS_MARKED_AS_NEVER_SPM);
        }

        if (!validate(new StoragePoolValidator(getStoragePoolForVds()).isUp())) {
            return false;
        }

        if (isAsyncTasksRunningOnPool(getStoragePoolForVds().getId())) {
            return failValidation(EngineMessage.CANNOT_FORCE_SELECT_SPM_STORAGE_POOL_HAS_RUNNING_TASKS);
        }

        return true;
    }

    @Override
    protected void executeCommand() {
        SpmStopOnIrsVDSCommandParameters params =
                new SpmStopOnIrsVDSCommandParameters(getStoragePoolForVds().getId(),
                        getParameters().getPreferredSPMId());

        if (runVdsCommand(VDSCommandType.SpmStopOnIrs, params).getSucceeded()) {
            auditLogDirector.log(this, AuditLogType.USER_FORCE_SELECTED_SPM);
        } else {
            auditLogDirector.log(this, AuditLogType.USER_FORCE_SELECTED_SPM_STOP_FAILED);
        }

        setSucceeded(true);
    }

    @Override
    protected void setActionMessageParameters() {
        addValidationMessage(EngineMessage.VAR__ACTION__FORCE_SELECT);
        addValidationMessage(EngineMessage.VAR__TYPE__SPM);
        addValidationMessageVariable("VdsName", getVds().getName());
    }

    private boolean isAsyncTasksRunningOnPool(Guid storagePoolId) {
        List<Guid> tasks = getAsyncTaskDao().getAsyncTaskIdsByStoragePoolId(storagePoolId);
        return !tasks.isEmpty();
    }

    private StoragePool getStoragePoolForVds() {
        if (storagePoolForVds == null) {
            storagePoolForVds = getStoragePoolDao().getForVds(getVds().getId());
        }
        return storagePoolForVds;
    }

    @Override
    public Map<String, String> getJobMessageProperties() {
        if (jobProperties == null) {
            jobProperties = super.getJobMessageProperties();
            if (getVds() != null) {
                jobProperties.put(VdcObjectType.StoragePool.name().toLowerCase(), getVds().getStoragePoolName());
            }
        }
        return jobProperties;
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        List<PermissionSubject> permissions = new ArrayList<>();
        permissions.add(new PermissionSubject(getParameters().getPreferredSPMId(),
                VdcObjectType.VDS,
                ActionGroup.MANIPULATE_HOST));
        return permissions;
    }
}


text:
struct Gps {
  Gps();
  void Reset();
  std::string ToStringZZZ() const;
  void ToProto(GPSProto* gps_proto) const;
  void FromProto(const GPSProto& gps_proto);

  // GPS-Data
  double longitude_deg;
  double latitude_deg;
  // COG velocity
  double speed_m_s;  // boat forward speed over ground, in m/s
  // Possible additional compass input (but this is COG, not phi_z)
  // and at standstill both are very different. So we could use
  // cog_rad at higher speeds only, but how reliable is that speed
  // information?
  double cog_rad;
  bool valid;
};

#endif  // HELMSMAN_GPS_H


text:
/*
 * node of binary search tree
 * created by lisovskey
 */

#ifndef MAP_NODE_HPP
#define MAP_NODE_HPP

#include "map.hpp"

namespace rzd {

template <
  typename Key,
  typename T,
  typename Compare
> struct map<Key, T, Compare>::node {

  map& map_ref;

  using value_type = typename map::value_type;
  using pointer = typename map::pointer;

  value_type data;
  pointer left;
  pointer parent;
  pointer right;

  node(map& map_ref, const pointer& parent, const value_type& data)
      : map_ref{ map_ref }
      , data{ data }
      , left{ nullptr }
      , parent{ parent }
      , right{ nullptr } {
    map_ref.size_count++;
  }

  ~node() {
    map_ref.size_count--;
  }

};

}

#endif


text:
<?php

namespace DwslaTest\Unit\Service\Mpx;

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;

/**
 * An abstract base for MPX Service classes
 *
 * @author David Weinraub <david.weinraub@dws.la>
 */
abstract class AbstractServiceTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Create a service with a mocked client
     *
     * @param  int    $code
     * @param  array  $headers
     * @param  array  $bodyData
     * @return Client
     */
    protected function createMockClient($code, array $headers = array(), array $bodyData = array())
    {
        // Create a mock and queue a response.
        $mock = new MockHandler([
            new Response($code, $headers, \GuzzleHttp\json_encode($bodyData)),
        ]);

        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);

        return $client;
    }

}


text:
#include "IrrCompileConfig.h"
#include "CTRTextureGouraud.h"

#ifdef _IRR_COMPILE_WITH_SOFTWARE_

namespace irr
{
namespace video
{

class CTRTextureGouraudAdd : public CTRTextureGouraud
{
public:

	//! constructor
	CTRTextureGouraudAdd(IZBuffer* zbuffer);

	//! draws an indexed triangle list
	virtual void drawIndexedTriangleList(S2DVertex* vertices, s32 vertexCount, const u16* indexList, s32 triangleCount);

protected:

};

//! constructor
CTRTextureGouraudAdd::CTRTextureGouraudAdd(IZBuffer* zbuffer)
: CTRTextureGouraud(zbuffer)
{
	#ifdef _DEBUG
	setDebugName("CTRTextureGouraudAdd");
	#endif
}

//! draws an indexed triangle list
void CTRTextureGouraudAdd::drawIndexedTriangleList(S2DVertex* vertices, s32 vertexCount, const u16* indexList, s32 triangleCount)
{
	const S2DVertex *v1, *v2, *v3;

	u16 color;
	f32 tmpDiv; // temporary division factor
	f32 longest; // saves the longest span
	s32 height; // saves height of triangle
	u16* targetSurface; // target pointer where to plot pixels
	s32 spanEnd; // saves end of spans
	f32 leftdeltaxf; // amount of pixels to increase on left side of triangle
	f32 rightdeltaxf; // amount of pixels to increase on right side of triangle
	s32 leftx, rightx; // position where we are
	f32 leftxf, rightxf; // same as above, but as f32 values
	s32 span; // current span
	u16 *hSpanBegin, *hSpanEnd; // pointer used when plotting pixels
	s32 leftR, leftG, leftB, rightR, rightG, rightB; // color values
	s32 leftStepR, leftStepG, leftStepB,
		rightStepR, rightStepG, rightStepB; // color steps
	s32 spanR, spanG, spanB, spanStepR, spanStepG, spanStepB; // color interpolating values while drawing a span.
	s32 leftTx, rightTx, leftTy, rightTy; // texture interpolating values
	s32 leftTxStep, rightTxStep, leftTyStep, rightTyStep; // texture interpolating values
	s32 spanTx, spanTy, spanTxStep, spanTyStep; // values of Texturecoords when drawing a span
	core::rect<s32> TriangleRect;

	s32 leftZValue, rightZValue;
	s32 leftZStep, rightZStep;
	s32 spanZValue, spanZStep; // ZValues when drawing a span
	TZBufferType* zTarget, *spanZTarget; // target of ZBuffer;

	lockedSurface = (u16*)RenderTarget->lock();
	lockedZBuffer = ZBuffer->lock();
	lockedTexture = (u16*)Texture->lock();

	for (s32 i=0; i<triangleCount; ++i)
	{
		v1 = &vertices[*indexList];
		++indexList;
		v2 = &vertices[*indexList];
		++indexList;
		v3 = &vertices[*indexList];
		++indexList;

		// back face culling

		if (BackFaceCullingEnabled)
		{
			s32 z = ((v3->Pos.X - v1->Pos.X) * (v3->Pos.Y - v2->Pos.Y)) -
				((v3->Pos.Y - v1->Pos.Y) * (v3->Pos.X - v2->Pos.X));

			if (z < 0)
				continue;
		}

		//near plane clipping

		if (v1->ZValue<0 && v2->ZValue<0 && v3->ZValue<0)
			continue;

		// sort for width for inscreen clipping

		if (v1->Pos.X > v2->Pos.X)	swapVertices(&v1, &v2);
		if (v1->Pos.X > v3->Pos.X)	swapVertices(&v1, &v3);
		if (v2->Pos.X > v3->Pos.X)	swapVertices(&v2, &v3);

		if ((v1->Pos.X - v3->Pos.X) == 0)
			continue;

		TriangleRect.UpperLeftCorner.X = v1->Pos.X;
		TriangleRect.LowerRightCorner.X = v3->Pos.X;

		// sort for height for faster drawing.

		if (v1->Pos.Y > v2->Pos.Y)	swapVertices(&v1, &v2);
		if (v1->Pos.Y > v3->Pos.Y)	swapVertices(&v1, &v3);
		if (v2->Pos.Y > v3->Pos.Y)	swapVertices(&v2, &v3);

		TriangleRect.UpperLeftCorner.Y = v1->Pos.Y;
		TriangleRect.LowerRightCorner.Y = v3->Pos.Y;

		if (!TriangleRect.isRectCollided(ViewPortRect))
			continue;

		// calculate height of triangle
		height = v3->Pos.Y - v1->Pos.Y;
		if (!height)
			continue;

		// calculate longest span

		longest = (v2->Pos.Y - v1->Pos.Y) / (f32)height * (v3->Pos.X - v1->Pos.X) + (v1->Pos.X - v2->Pos.X);

		spanEnd = v2->Pos.Y;
		span = v1->Pos.Y;
		leftxf = (f32)v1->Pos.X;
		rightxf = (f32)v1->Pos.X;

		leftZValue = v1->ZValue;
		rightZValue = v1->ZValue;

		leftR = rightR = video::getRed(v1->Color)<<8;
		leftG = rightG = video::getGreen(v1->Color)<<8;
		leftB = rightB = video::getBlue(v1->Color)<<8;
		leftTx = rightTx = v1->TCoords.X;
		leftTy = rightTy = v1->TCoords.Y;

		targetSurface = lockedSurface + span * SurfaceWidth;
		zTarget = lockedZBuffer + span * SurfaceWidth;

		if (longest < 0.0f)
		{
			tmpDiv = 1.0f / (f32)(v2->Pos.Y - v1->Pos.Y);
			rightdeltaxf = (v2->Pos.X - v1->Pos.X) * tmpDiv;
			rightZStep = (s32)((v2->ZValue - v1->ZValue) * tmpDiv);
			rightStepR = (s32)(((s32)(video::getRed(v2->Color)<<8) - rightR) * tmpDiv);
			rightStepG = (s32)(((s32)(video::getGreen(v2->Color)<<8) - rightG) * tmpDiv);
			rightStepB = (s32)(((s32)(video::getBlue(v2->Color)<<8) - rightB) * tmpDiv);
			rightTxStep = (s32)((v2->TCoords.X - rightTx) * tmpDiv);
			rightTyStep = (s32)((v2->TCoords.Y - rightTy) * tmpDiv);

			tmpDiv = 1.0f / (f32)height;
			leftdeltaxf = (v3->Pos.X - v1->Pos.X) * tmpDiv;
			leftZStep = (s32)((v3->ZValue - v1->ZValue) * tmpDiv);
			leftStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - leftR) * tmpDiv);
			leftStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - leftG) * tmpDiv);
			leftStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - leftB) * tmpDiv);
			leftTxStep = (s32)((v3->TCoords.X - leftTx) * tmpDiv);
			leftTyStep = (s32)((v3->TCoords.Y - leftTy) * tmpDiv);
		}
		else
		{
			tmpDiv = 1.0f / (f32)height;
			rightdeltaxf = (v3->Pos.X - v1->Pos.X) * tmpDiv;
			rightZStep = (s32)((v3->ZValue - v1->ZValue) * tmpDiv);
			rightStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - rightR) * tmpDiv);
			rightStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - rightG) * tmpDiv);
			rightStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - rightB) * tmpDiv);
			rightTxStep = (s32)((v3->TCoords.X - rightTx) * tmpDiv);
			rightTyStep = (s32)((v3->TCoords.Y - rightTy) * tmpDiv);

			tmpDiv = 1.0f / (f32)(v2->Pos.Y - v1->Pos.Y);
			leftdeltaxf = (v2->Pos.X - v1->Pos.X) * tmpDiv;
			leftZStep = (s32)((v2->ZValue - v1->ZValue) * tmpDiv);
			leftStepR = (s32)(((s32)(video::getRed(v2->Color)<<8) - leftR) * tmpDiv);
			leftStepG = (s32)(((s32)(video::getGreen(v2->Color)<<8) - leftG) * tmpDiv);
			leftStepB = (s32)(((s32)(video::getBlue(v2->Color)<<8) - leftB) * tmpDiv);
			leftTxStep = (s32)((v2->TCoords.X - leftTx) * tmpDiv);
			leftTyStep = (s32)((v2->TCoords.Y - leftTy) * tmpDiv);
		}

		// do it twice, once for the first half of the triangle,
		// end then for the second half.

		for (s32 triangleHalf=0; triangleHalf<2; ++triangleHalf)
		{
			if (spanEnd > ViewPortRect.LowerRightCorner.Y)
				spanEnd = ViewPortRect.LowerRightCorner.Y;

			// if the span <0, than we can skip these spans,
			// and proceed to the next spans which are really on the screen.
			if (span < ViewPortRect.UpperLeftCorner.Y)
			{
				// we'll use leftx as temp variable
				if (spanEnd < ViewPortRect.UpperLeftCorner.Y)
				{
					leftx = spanEnd - span;
					span = spanEnd;
				}
				else
				{
					leftx = ViewPortRect.UpperLeftCorner.Y - span;
					span = ViewPortRect.UpperLeftCorner.Y;
				}

				leftxf += leftdeltaxf*leftx;
				rightxf += rightdeltaxf*leftx;
				targetSurface += SurfaceWidth*leftx;
				zTarget += SurfaceWidth*leftx;
				leftZValue += leftZStep*leftx;
				rightZValue += rightZStep*leftx;

				leftR += leftStepR*leftx;
				leftG += leftStepG*leftx;
				leftB += leftStepB*leftx;
				rightR += rightStepR*leftx;
				rightG += rightStepG*leftx;
				rightB += rightStepB*leftx;

				leftTx += leftTxStep*leftx;
				leftTy += leftTyStep*leftx;
				rightTx += rightTxStep*leftx;
				rightTy += rightTyStep*leftx;
			}

			// the main loop. Go through every span and draw it.

			while (span < spanEnd)
			{
				leftx = (s32)(leftxf);
				rightx = (s32)(rightxf + 0.5f);

				// perform some clipping
				// thanks to a correction by hybrid
				// calculations delayed to correctly propagate to textures etc.
				s32 tDiffLeft=0, tDiffRight=0;
				if (leftx<ViewPortRect.UpperLeftCorner.X)
					tDiffLeft=ViewPortRect.UpperLeftCorner.X-leftx;
				else
				if (leftx>ViewPortRect.LowerRightCorner.X)
					tDiffLeft=ViewPortRect.LowerRightCorner.X-leftx;

				if (rightx<ViewPortRect.UpperLeftCorner.X)
					tDiffRight=ViewPortRect.UpperLeftCorner.X-rightx;
				else
				if (rightx>ViewPortRect.LowerRightCorner.X)
					tDiffRight=ViewPortRect.LowerRightCorner.X-rightx;

				// draw the span
				if (rightx + tDiffRight - leftx - tDiffLeft)
				{
					tmpDiv = 1.0f / (f32)(rightx - leftx);
					spanZStep = (s32)((rightZValue - leftZValue) * tmpDiv);
					spanZValue = leftZValue+tDiffLeft*spanZStep;

					spanStepR = (s32)((rightR - leftR) * tmpDiv);
					spanR = leftR+tDiffLeft*spanStepR;
					spanStepG = (s32)((rightG - leftG) * tmpDiv);
					spanG = leftG+tDiffLeft*spanStepG;
					spanStepB = (s32)((rightB - leftB) * tmpDiv);
					spanB = leftB+tDiffLeft*spanStepB;

					spanTxStep = (s32)((rightTx - leftTx) * tmpDiv);
					spanTx = leftTx + tDiffLeft*spanTxStep;
					spanTyStep = (s32)((rightTy - leftTy) * tmpDiv);
					spanTy = leftTy+tDiffLeft*spanTyStep;

					hSpanBegin = targetSurface + leftx+tDiffLeft;
					spanZTarget = zTarget + leftx+tDiffLeft;
					hSpanEnd = targetSurface + rightx+tDiffRight;

					while (hSpanBegin < hSpanEnd)
					{
						if (spanZValue > *spanZTarget)
						{
							//*spanZTarget = spanZValue;
							color = lockedTexture[((spanTy>>8)&textureYMask) * lockedTextureWidth + ((spanTx>>8)&textureXMask)];

							s32 basis = *hSpanBegin;
							s32 r = (video::getRed(basis)<<3) + (video::getRed(color)<<3);
							if (r > 255) r = 255;
							s32 g = (video::getGreen(basis)<<3) + (video::getGreen(color)<<3);
							if (g > 255) g = 255;
							s32 b = (video::getBlue(basis)<<3) + (video::getBlue(color)<<3);
							if (b > 255) b = 255;

							*hSpanBegin = video::RGB16(r, g, b);
						}

						spanR += spanStepR;
						spanG += spanStepG;
						spanB += spanStepB;

						spanTx += spanTxStep;
						spanTy += spanTyStep;

						spanZValue += spanZStep;
						++hSpanBegin;
						++spanZTarget;
					}
				}

				leftxf += leftdeltaxf;
				rightxf += rightdeltaxf;
				++span;
				targetSurface += SurfaceWidth;
				zTarget += SurfaceWidth;
				leftZValue += leftZStep;
				rightZValue += rightZStep;

				leftR += leftStepR;
				leftG += leftStepG;
				leftB += leftStepB;
				rightR += rightStepR;
				rightG += rightStepG;
				rightB += rightStepB;

				leftTx += leftTxStep;
				leftTy += leftTyStep;
				rightTx += rightTxStep;
				rightTy += rightTyStep;
			}

			if (triangleHalf>0) // break, we've gout only two halves
				break;

			// setup variables for second half of the triangle.

			if (longest < 0.0f)
			{
				tmpDiv = 1.0f / (v3->Pos.Y - v2->Pos.Y);

				rightdeltaxf = (v3->Pos.X - v2->Pos.X) * tmpDiv;
				rightxf = (f32)v2->Pos.X;

				rightZValue = v2->ZValue;
				rightZStep = (s32)((v3->ZValue - v2->ZValue) * tmpDiv);

				rightR = video::getRed(v2->Color)<<8;
				rightG = video::getGreen(v2->Color)<<8;
				rightB = video::getBlue(v2->Color)<<8;
				rightStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - rightR) * tmpDiv);
				rightStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - rightG) * tmpDiv);
				rightStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - rightB) * tmpDiv);

				rightTx = v2->TCoords.X;
				rightTy = v2->TCoords.Y;
				rightTxStep = (s32)((v3->TCoords.X - rightTx) * tmpDiv);
				rightTyStep = (s32)((v3->TCoords.Y - rightTy) * tmpDiv);
			}
			else
			{
				tmpDiv = 1.0f / (v3->Pos.Y - v2->Pos.Y);

				leftdeltaxf = (v3->Pos.X - v2->Pos.X) * tmpDiv;
				leftxf = (f32)v2->Pos.X;

				leftZValue = v2->ZValue;
				leftZStep = (s32)((v3->ZValue - v2->ZValue) * tmpDiv);

				leftR = video::getRed(v2->Color)<<8;
				leftG = video::getGreen(v2->Color)<<8;
				leftB = video::getBlue(v2->Color)<<8;
				leftStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - leftR) * tmpDiv);
				leftStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - leftG) * tmpDiv);
				leftStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - leftB) * tmpDiv);

				leftTx = v2->TCoords.X;
				leftTy = v2->TCoords.Y;
				leftTxStep = (s32)((v3->TCoords.X - leftTx) * tmpDiv);
				leftTyStep = (s32)((v3->TCoords.Y - leftTy) * tmpDiv);
			}

			spanEnd = v3->Pos.Y;
		}

	}

	RenderTarget->unlock();
	ZBuffer->unlock();
	Texture->unlock();
}

} // end namespace video
} // end namespace irr

#endif // _IRR_COMPILE_WITH_SOFTWARE_

namespace irr
{
namespace video
{

ITriangleRenderer* createTriangleRendererTextureGouraudAdd(IZBuffer* zbuffer)
{
	#ifdef _IRR_COMPILE_WITH_SOFTWARE_
	return new CTRTextureGouraudAdd(zbuffer);
	#else
	return 0;
	#endif // _IRR_COMPILE_WITH_SOFTWARE_
}

} // end namespace video
} // end namespace irr


text:
package net.betzel.lmdb.ra;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.jca.arquillian.embedded.Inject;
import org.jboss.jca.core.spi.mdr.MetadataRepository;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.annotation.Resource;
import javax.resource.ResourceException;
import javax.transaction.Status;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import java.util.UUID;
import java.util.logging.Logger;

import static org.junit.Assert.*;

/**
 * ConnectorTestCase
 *
 * @version $Revision: $
 */
@RunWith(Arquillian.class)
public class TransactionTestCase {

    private static Logger log = Logger.getLogger(TransactionTestCase.class.getName());

    private static String deploymentName = "TransactionTestCase";

    String databaseName = "testdb1";
    String databaseKey1 = "testKey1";
    String databaseVal1 = "testVal1";
    String databaseKey2 = "testKey2";
    String databaseVal2 = "testVal2";
    String databaseKey3 = "testKey3";
    String databaseVal3 = "testVal3";
    String databaseKey4 = "testKey4";
    String databaseVal4 = "testVal4";

    /**
     * Define the deployment
     *
     * @return The deployment archive
     */
    @Deployment
    public static ResourceAdapterArchive createDeployment() {
        ResourceAdapterArchive resourceAdapterArchive = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName + ".rar");
        JavaArchive javaArchive = ShrinkWrap.create(JavaArchive.class, UUID.randomUUID().toString() + ".jar");
        javaArchive.addPackages(true, Package.getPackage("net.betzel.lmdb.ra"));
        resourceAdapterArchive.addAsLibrary(javaArchive);
        resourceAdapterArchive.addAsManifestResource("ironjacamar.xml");
        return resourceAdapterArchive;
    }

    @Inject(name = "MDR")
    private MetadataRepository mdr;

    /**
     * Resource
     */
    @Resource(mappedName = "java:/eis/LMDbConnectionFactory")
    private LMDbConnectionFactory testConnectionFactory;

    @Resource(mappedName = "java:/UserTransaction")
    private UserTransaction userTransaction;

    @Resource(mappedName = "java:/TransactionManager")
    private TransactionManager transactionManager;

    /**
     * Test local transaction
     *
     * @throws Throwable Thrown if case of an error
     */

    @Test
    public void testTransaction() throws Throwable {
        log.finest("testTransaction()");
        assertNotNull(testConnectionFactory);
        assertNotNull(userTransaction);
        assertEquals(userTransaction.getStatus(), Status.STATUS_NO_TRANSACTION);

        userTransaction.begin();
        try (LMDbConnection connectionXA = testConnectionFactory.getConnection(databaseName)) {
            connectionXA.put(databaseKey1, LMDbUtil.toByteBuffer(databaseVal1));
            connectionXA.put(databaseKey2, LMDbUtil.toByteBuffer(databaseVal2));
        }
        userTransaction.commit();

        try (LMDbConnection connection = testConnectionFactory.getConnection(databaseName)) {
            String value1 = connection.get(LMDbUtil.toByteBuffer(databaseKey1), String.class);
            assertEquals(value1, databaseVal1);
            String value2 = connection.get(LMDbUtil.toByteBuffer(databaseKey2), String.class);
            assertEquals(value2, databaseVal2);
        }

        userTransaction.begin();
        try (LMDbConnection connectionXA = testConnectionFactory.getConnection(databaseName)) {
            connectionXA.delete(LMDbUtil.toByteBuffer(databaseKey1));
            connectionXA.delete(LMDbUtil.toByteBuffer(databaseKey2), LMDbUtil.toByteBuffer(databaseVal2));
        }
        userTransaction.commit();

        try (LMDbConnection connection = testConnectionFactory.getConnection(databaseName)) {
            String value1 = connection.get(LMDbUtil.toByteBuffer(databaseKey1), String.class);
            assertNull(value1);
            String value2 = connection.get(LMDbUtil.toByteBuffer(databaseKey2), String.class);
            assertNull(value2);
        }
    }

    @Test
    public void testTransactionSuspend() throws Throwable {
        log.finest("testTransactionSuspend()");
        assertNotNull(testConnectionFactory);
        assertNotNull(transactionManager);
        assertNotNull(userTransaction);

        assertEquals(Status.STATUS_NO_TRANSACTION, transactionManager.getStatus());

        userTransaction.begin();

        assertEquals(Status.STATUS_ACTIVE, transactionManager.getStatus());

        startNewTransaction();

        Transaction transaction = transactionManager.suspend(); // Suspend transaction from thread

        assertEquals(Status.STATUS_NO_TRANSACTION, transactionManager.getStatus());

        userTransaction.begin();

        assertEquals(Status.STATUS_ACTIVE, transactionManager.getStatus());

        startAnotherTransaction();

        userTransaction.commit();

        assertEquals(Status.STATUS_NO_TRANSACTION, transactionManager.getStatus());

        transactionManager.resume(transaction);

        assertEquals(Status.STATUS_ACTIVE, transactionManager.getStatus());

        userTransaction.commit();

        assertEquals(Status.STATUS_NO_TRANSACTION, transactionManager.getStatus());

        try (LMDbConnection connection = testConnectionFactory.getConnection(databaseName)) {
            String value1 = connection.get(LMDbUtil.toByteBuffer(databaseKey1), String.class);
            assertEquals(databaseVal1, value1);
            String value2 = connection.get(LMDbUtil.toByteBuffer(databaseKey2), String.class);
            assertEquals(databaseVal2, value2);
            String value3 = connection.get(LMDbUtil.toByteBuffer(databaseKey3), String.class);
            assertEquals(databaseVal3, value3);
            String value4 = connection.get(LMDbUtil.toByteBuffer(databaseKey4), String.class);
            assertEquals(databaseVal4, value4);
            connection.delete(LMDbUtil.toByteBuffer(databaseKey1));
            connection.delete(LMDbUtil.toByteBuffer(databaseKey2), LMDbUtil.toByteBuffer(databaseVal2));
            connection.delete(LMDbUtil.toByteBuffer(databaseKey3));
            connection.delete(LMDbUtil.toByteBuffer(databaseKey4), LMDbUtil.toByteBuffer(databaseVal4));
            assertNull(connection.get(LMDbUtil.toByteBuffer(databaseKey1), String.class));
            assertNull(connection.get(LMDbUtil.toByteBuffer(databaseKey2), String.class));
            assertNull(connection.get(LMDbUtil.toByteBuffer(databaseKey3), String.class));
            assertNull(connection.get(LMDbUtil.toByteBuffer(databaseKey4), String.class));
        }
    }

    private void startNewTransaction() throws ResourceException {
        try (LMDbConnection connectionXA = testConnectionFactory.getConnection(databaseName)) {
            connectionXA.put(databaseKey1, LMDbUtil.toByteBuffer(databaseVal1));
            connectionXA.put(databaseKey2, LMDbUtil.toByteBuffer(databaseVal2));
            assertNull(connectionXA.get(LMDbUtil.toByteBuffer(databaseKey1), String.class));
            assertNull(connectionXA.get(LMDbUtil.toByteBuffer(databaseKey2), String.class));
        }
    }

    private void startAnotherTransaction() throws ResourceException {
        try (LMDbConnection connectionXA = testConnectionFactory.getConnection(databaseName)) {
            connectionXA.put(databaseKey3, LMDbUtil.toByteBuffer(databaseVal3));
            connectionXA.put(databaseKey4, LMDbUtil.toByteBuffer(databaseVal4));
            assertNull(connectionXA.get(LMDbUtil.toByteBuffer(databaseKey3), String.class));
            assertNull(connectionXA.get(LMDbUtil.toByteBuffer(databaseKey4), String.class));
        }
    }

}


text:
require "dry/system/config/namespaces"
require "dry/system/config/namespace"

RSpec.describe Dry::System::Config::Namespaces do
  subject(:namespaces) { described_class.new }

  describe "#namespace" do
    it "returns the previously configured namespace for the given path" do
      added_namespace = namespaces.add "test/path", key: "key_ns", const: "const_ns"

      expect(namespaces.namespace("test/path")).to be added_namespace
    end

    it "returns nil when no namepace was previously configured for the given path" do
      expect(namespaces.namespace("test/path")).to be nil
    end
  end

  describe "#[]" do
    it "returns the previously configured namespace for the given path" do
      added_namespace = namespaces.add "test/path", key: "key_ns", const: "const_ns"

      expect(namespaces["test/path"]).to be added_namespace
    end

    it "returns nil when no namepace was previously configured for the given path" do
      expect(namespaces["test/path"]).to be nil
    end
  end

  describe "#root" do
    it "returns the previously configured root namespace" do
      added_root_namespace = namespaces.add_root

      expect(namespaces.root).to be added_root_namespace
    end

    it "returns nil when no root namespace was previously configured" do
      expect(namespaces.root).to be nil
    end
  end

  describe "#root with argumments (DEPRECATED for #add_root)" do
    before do
      # We don't care about the deprecation messages when we're not testing for them
      # specifically
      Dry::Core::Deprecations.set_logger!(StringIO.new)
    end

    it "adds a root namespace with the given configuration" do
      expect {
        namespaces.root key: "key_ns", const: "const_ns"
      }
        .to change { namespaces.length }
        .from(0).to(1)

      ns = namespaces.namespaces[nil]

      expect(ns).to be_root
      expect(ns.path).to be_nil
      expect(ns.key).to eq "key_ns"
      expect(ns.const).to eq "const_ns"
    end

    it "prints a deprecation warning" do
      logger = StringIO.new
      Dry::Core::Deprecations.set_logger! logger

      namespaces.root key: "key_ns", const: "const_ns"

      logger.rewind
      expect(logger.string).to match(/Namespaces#root \(with arguments\) is deprecated/)
    end
  end

  describe "#add" do
    it "adds the namespace with the given configuration" do
      expect {
        namespaces.add "test/path", key: "key_ns", const: "const_ns"
      }
        .to change { namespaces.length }
        .from(0).to(1)

      ns = namespaces.namespaces["test/path"]

      expect(ns.path).to eq "test/path"
      expect(ns.key).to eq "key_ns"
      expect(ns.const).to eq "const_ns"
    end

    it "raises an exception when a namespace is already added" do
      namespaces.add "test/path"

      expect { namespaces.add "test/path" }.to raise_error(Dry::System::NamespaceAlreadyAddedError, %r{test/path})
    end
  end

  describe "#add_root" do
    it "adds a root namespace with the given configuration" do
      expect {
        namespaces.add_root key: "key_ns", const: "const_ns"
      }
        .to change { namespaces.length }
        .from(0).to(1)

      ns = namespaces.namespaces[nil]

      expect(ns).to be_root
      expect(ns.path).to be_nil
      expect(ns.key).to eq "key_ns"
      expect(ns.const).to eq "const_ns"
    end

    it "raises an exception when a root namespace is already added" do
      namespaces.add_root

      expect { namespaces.add_root }.to raise_error(Dry::System::NamespaceAlreadyAddedError, /root path/)
    end
  end

  describe "#delete" do
    it "deletes and returns the configured namespace for the given path" do
      added_namespace = namespaces.add "test/path"

      deleted_namespace = nil
      expect {
        deleted_namespace = namespaces.delete("test/path")
      }
        .to change { namespaces.length }
        .from(1).to(0)

      expect(deleted_namespace).to be added_namespace
    end

    it "returns nil when no namespace has been configured for the given path" do
      expect(namespaces.delete("test/path")).to be nil
      expect(namespaces).to be_empty
    end
  end

  describe "#delete_root" do
    it "deletes and returns the configured root namespace" do
      added_namespace = namespaces.add_root

      deleted_namespace = nil
      expect {
        deleted_namespace = namespaces.delete_root
      }
        .to change { namespaces.length }
        .from(1).to(0)

      expect(deleted_namespace).to be added_namespace
    end

    it "returns nil when no root namespace has been configured" do
      expect(namespaces.delete_root).to be nil
      expect(namespaces).to be_empty
    end
  end

  describe "#length" do
    it "returns the count of configured namespaces" do
      namespaces.add "test/path_1"
      namespaces.add "test/path_2"
      expect(namespaces.length).to eq 2
    end

    it "returns 0 when there are no configured namespaces" do
      expect(namespaces.length).to eq 0
    end
  end

  describe "#empty?" do
    it "returns true if there are no configured namespaces" do
      expect(namespaces).to be_empty
    end

    it "returns false if a namespace has been added" do
      expect { namespaces.add "test/path" }
        .to change { namespaces.empty? }
        .from(true).to(false)
    end
  end

  describe "#to_a" do
    it "returns an array of the configured namespaces, in order of definition" do
      namespaces.add "test/path", key: "test_key_ns"
      namespaces.add_root key: "root_key_ns"

      arr = namespaces.to_a

      expect(arr.length).to eq 2

      expect(arr[0].path).to eq "test/path"
      expect(arr[0].key).to eq "test_key_ns"

      expect(arr[1].path).to eq nil
      expect(arr[1].key).to eq "root_key_ns"
    end

    it "appends a default root namespace if not explicitly configured" do
      namespaces.add "test/path", key: "test_key_ns"

      arr = namespaces.to_a

      expect(arr.length).to eq 2

      expect(arr[0].path).to eq "test/path"
      expect(arr[0].key).to eq "test_key_ns"

      expect(arr[1].path).to be nil
      expect(arr[1].key).to be nil
      expect(arr[1].const).to be nil
    end

    it "includes a default root namespace if no namespaces configured" do
      arr = namespaces.to_a

      expect(arr.length).to eq 1

      expect(arr[0].path).to be nil
      expect(arr[0].key).to be nil
      expect(arr[0].const).to be nil
    end
  end

  describe "#each" do
    it "yields each configured namespace" do
      namespaces.add "test/path", key: "test_key_ns"
      namespaces.add_root key: "root_key_ns"

      expect { |b|
        namespaces.each(&b)
      }.to yield_successive_args(
        an_object_satisfying { |ns| ns.path == "test/path" },
        an_object_satisfying(&:root?)
      )
    end
  end

  describe "#dup" do
    it "dups the registry of namespaces" do
      namespaces.add "test/path", key: "test_key_ns"

      new_namespaces = namespaces.dup

      expect(new_namespaces.to_a).to eq(namespaces.to_a)
      expect(new_namespaces.namespaces).not_to be(namespaces.namespaces)
    end
  end
end


text:
Multiple designers demo: https://www.webrtc-experiment.com/Canvas-Designer/multiple.html

### YouTube video:

* https://www.youtube.com/watch?v=pvAj5l_v3cM

[![npm](https://img.shields.io/npm/v/canvas-designer.svg)](https://npmjs.org/package/canvas-designer) [![downloads](https://img.shields.io/npm/dm/canvas-designer.svg)](https://npmjs.org/package/canvas-designer) [![Build Status: Linux](https://travis-ci.org/muaz-khan/Canvas-Designer.png?branch=master)](https://travis-ci.org/muaz-khan/Canvas-Designer)

> "Collaborative" [Canvas Designer](https://github.com/muaz-khan/Canvas-Designer) i.e. Canvas-Drawing tool allows you draw bezier/quadratic curves, rectangles, circles and lines. You can also set strokes, back/forth colors and much more. You can draw using pencils, erase drawing, type texts etc. You can [easily add your own tools](https://www.webrtc-experiment.com/Canvas-Designer/Help/#contribute).

**You can check all releases here:**

* https://github.com/muaz-khan/Canvas-Designer/releases

The specialty of this drawing-tool is that, it generates Canvas2D code for you; so simply draw and get the code! That code can be used in any javascript Canvas2D application.

**You can submit issues here:**

* https://github.com/muaz-khan/Canvas-Designer/issues

Also, you can collaborate your drawing with up to 15 users; and everything is synced from all users. So, if you draw a line and your friend-A draws quadratic curve and friend-B draws rectangle then everything will be synced among all users!

### Youtube Videos

* https://www.youtube.com/watch?v=oSSwMlBu8SY

Gif images:

* https://www.webrtc-experiment.com/images/Canvas-Designer.gif

# Built-in tools

You can use [`designer.setSelected`](https://github.com/muaz-khan/Canvas-Designer#setselected) or [`designer.setTools`](https://github.com/muaz-khan/Canvas-Designer#settools) for below tools.

1. `line` --- to draw straight lines
2. `pencil` --- to write/draw shapes
3. `dragSingle` --- to drag/ove and especially **resize** last selected shape
4. `dragMultiple` --- to drag/move all shapes
5. `eraser` --- to erase/clear specific portion of shapes
6. `rectangle` --- to draw rectangles
7. `arc` --- to draw circles
8. `bezier` --- to draw bezier curves
9. `quadratic` --- to draw quadratic curves
10. `text` --- to write texts on single or multiple lines, select font families/sizes and more
11. `image` --- add external images
12. `arrow` --- draw arrow lines
13. `marker` --- draw markers
14. `lineWidth` --- set line width
15. `colorsPicker` --- background and foreground colors picker
16. `extraOptions` --- extra options eg. lineCap, lineJoin, globalAlpha, globalCompositeOperation etc.
17. `pdf` --- to import PDF
18. `code` --- to enable/disable code view
19. `undo` --- undo recent shapes

The correct name for `dragSingle` should be: `drag-move-resize last-selected-shape`.

The correct name for `dragMultiple` should be: `drag-move all-shapes`.

### Upcoming tools

1. Allow users to add video-streams or screen-streams or existing-webm-mp4-videos
2. Resize all shapes at once (currently you can resize last selected shape only)

# Features

1. Draw single or multiple shapes of any kind (according to toolbox)
2. Drag/resize/adjust all the shapes in any possible direction
3. Rectangles and images can be resized in 4-directions

   Red transparent small circles helps you understand how to resize.

4. Undo drawings using `ctrl+z` keys (undo all shapes, undo last 10 or specific shapes, undo range of shapes or undo last shape)
5. Drag/move single or all the shapes without affecting any single coordinate

More importantly, you can use unlimited designers on a single page. Each will have its own surface and its own tools.

# Chinese, Arabic, other languages

You can install following chrome extension for multi-language input tools:

* https://chrome.google.com/webstore/detail/google-input-tools/mclkkofklkfljcocdinagocijmpgbhab?hl=en

Now type your own language text in any `<input>` box or anywhere, and simply copy that text.

Now click `T` tool icon from the tool-box and press `ctrl+v` to paste your own language's text.

**To repeat it:**

1. Type your own language texts anywhere and make sure to copy to clipboard using `ctrl+v`
2. Then click `T` icon, and then press `ctrl+v` to paste your copied text

You can paste any text: English, Arabic, Chinese etc.

# How to Use

1. Download/link `canvas-designer-widget.js` from [this github repository](https://github.com/muaz-khan/Canvas-Designer).
2. Set `designer.widgetHtmlURL` and `designer.widgetJsURL` in your HTML file.
3. Use this command to append widget in your HTML page:

   `var designer = new CanvasDesigner();`

   `designer.appendTo(document.body);`

```html
<!-- 1st step -->
<script src="https://www.webrtc-experiment.com/Canvas-Designer/canvas-designer-widget.js"></script>

<!-- 2nd step -->
<script>
var designer = new CanvasDesigner();

// both links are mandatory
// widget.html will internally use widget.js
designer.widgetHtmlURL = 'https://www.webrtc-experiment.com/Canvas-Designer/widget.html'; // you can place this file anywhere
designer.widgetJsURL = 'https://www.webrtc-experiment.com/Canvas-Designer/widget.js';     // you can place this file anywhere
</script>

<!-- 3rd i.e. last step -->
<script>
// <iframe> will be appended to "document.body"
designer.appendTo(document.body || document.documentElement);
</script>
```

# Complete Usage

```javascript
var designer = new CanvasDesigner();

websocket.onmessage = function(event) {
    designer.syncData( JSON.parse(event.data) );
};

designer.addSyncListener(function(data) {
    websocket.send(JSON.stringify(data));
});

designer.setSelected('pencil');

designer.setTools({
    pencil: true,
    text: true
});

designer.appendTo(document.documentElement);
```

It is having `designer.destroy()` method as well.

# Use [WebRTC](http://www.rtcmulticonnection.org/docs/)!

```javascript
webrtc.onmessage = function(event) {
    designer.syncData( event.data );
};

designer.addSyncListener(function(data) {
    webrtc.send(data);
});
```

# Use Socket.io

```javascript
socket.on('message', function(data) {
    designer.syncData( data );
});

designer.addSyncListener(function(data) {
    socket.emit('message', data);
});
```

# API Reference

## `widgetHtmlURL`

You can place `widget.html` file anywhere on your site.

```javascript
designer.widgetHtmlURL = '/html-files/widget.html';
```

By default `widget.html` is placed in the same directory of `index.html`.

```javascript
// here is default value
designer.widgetHtmlURL = 'widget.html';
```

Remember, `widget.html` is loaded using `<iframe>`.

## `widgetJsURL`

> **Note:** This file is **internally used** by `widget.html`.

You can place `widget.html` file anywhere on your site.

```javascript
designer.widgetJsURL = '/js-files/widget.min.js';
```

By default `widget.min.js` is placed in the same directory of `index.html`.

```javascript
// here is default value
designer.widgetJsURL = 'widget.min.js';
```

Remember, `widget.js` is loaded using `<iframe>`.

## `syncData`

Pass array-of-points that are shared by remote users using socket.io or websockets or XMPP or WebRTC.

```javascript
designer.syncData(arrayOfPoints);
```

An example to pass custom data on Canvas-Designer:

```javascript
var x = 0;
var y = 0;
var width = designer.iframe.clientWidth;
var height = designer.iframe.clientHeight;

var image = 'https://www.webrtc-experiment.com/images/RTCMultiConnection-STUN-TURN-usage.png';

var points = [
    ['image', [image, x, y, width, height, 1], ['2', '#6c96c8', 'rgba(0,0,0,0)', '1', 'source-over', 'round', 'round', '15px "Arial"']]
];

designer.syncData({
    startIndex: 0,
    points: points
});
```

## `clearCanvas`

Remove and clear all drawings from the canvas:

```javascript
designer.clearCanvas();
```

## `renderStream`

Call this method internally to fix video rendering issues.

```javascript
designer.renderStream();
```

## `addSyncListener`

This callback is invoked as soon as something new is drawn. An array-of-points is passed over this function. That array MUST be shared with remote users for collaboration.

```javascript
designer.addSyncListener(function(data) {
    designer.send(JSON.stringify(data));
});
```

## `setSelected`

This method allows you select specific tools.

* See list of [all tools](https://github.com/muaz-khan/Canvas-Designer#built-in-tools)

```javascript
designer.setSelected('rectangle');
```

## `setTools`

This method allows you choose between tools that **should be displayed** in the tools-panel.

* See list of [all tools](https://github.com/muaz-khan/Canvas-Designer#built-in-tools)

```javascript
designer.setTools({
    line: true,
    arrow: true,
    pencil: true,
    marker: true,
    dragSingle: true,
    dragMultiple: true,
    eraser: true,
    rectangle: true,
    arc: true,
    bezier: true,
    quadratic: true,
    text: true,
    image: true,
    pdf: true,
    zoom: true,
    lineWidth: true,
    colorsPicker: true,
    extraOptions: true,
    code: true,
    undo: true
});
```

## `icons`

You can force/set your own tool-icons:

```javascript
designer.icons = {
    line: '/icons/line.png',
    arrow: '/icons/arrow.png',
    pencil: '/icons/pencil.png',
    dragSingle: '/icons/dragSingle.png',
    dragMultiple: '/icons/dragMultiple.png',
    eraser: '/icons/eraser.png',
    rectangle: '/icons/rectangle.png',
    arc: '/icons/arc.png',
    bezier: '/icons/bezier.png',
    quadratic: '/icons/quadratic.png',
    text: '/icons/text.png',
    image: '/icons/image.png',
    pdf: '/icons/pdf.png',
    pdf_next: '/icons/pdf-next.png',
    pdf_prev: '/icons/pdf-prev.png',
    marker: '/icons/marker.png',
    zoom: '/icons/zoom.png',
    lineWidth: '/icons/lineWidth.png',
    colorsPicker: '/icons/colorsPicker.png',
    extraOptions: '/icons/extraOptions.png',
    code: '/icons/code.png'
};
```

You can set like this as well:

```javascript
designer.icons.line = '/icons/line.png';
```

Default values are `NULL` to force icons from `/dev/data-dris.js`.

## `appendTo`

CanvasDesigner is a widget; that widget should be appended to a DOM object. This method allows you pass `<body>` or any other HTMLDOMElement.

```javascript
designer.appendTo(document.body || document.documentElement);

// or
designer.appendTo(document.body || document.documentElement, function() {
    alert('iframe load callback');
});
```

The correct name for `appendTo` is: `append-iframe to target HTML-DOM-element`

## `destroy`

If you want to remove the widget from your HTMLDOMElement.

```javascript
designer.destroy();
```

## `iframe`

You can access designer iframe as following:

```javascript
designer.iframe.style.border = '5px solid red';

window.open(designer.iframe.src);
```

`designer.iframe` will be `null/undefined` until you call `appendTo`. So always use this code-block:

```javascript
if(!designer.iframe) {
    designer.appendTo(document.body);
}
designer.iframe.style.border = '5px solid red';
```

## `toDataURL`

Get data-URL of your drawings!

```javascript
designer.toDataURL('image/png', function(dataURL) {
    window.open(dataURL);
});
```

## `sync`

You can manually sync drawings by invoking `designer.sync` method:

```javascript
designer.sync();
```

Here is a real usecase:

```javascript
webrtcDataChannel.onopen = function() {
    if(designer.pointsLength > 0) {
        // you seems having data to be synced with new user!
        designer.sync();
    }
};
```

## `captureStream`

Get `MediaStream` object and share in realtime using `RTCPeerConnection.addStream` API.

```html
<script src="dev/webrtc-handler.js"></script>
<script>
designer.captureStream(function(stream) {
    var url = URL.createObjectURL(stream);
    videoPreview.src = url;

    rtcPeerConnection.addStream(stream);
    rtcPeerConnection.createOffer(success, failure, params);
});
</script>
```

## `pointsLength`

Each shape is considered as a `point`. This value allows you check number of shapes that are already drawn on the canvas-designer.

```javascript
(function looper() {
    document.getElementById('number-of-shapes').inenrHTML = designer.pointsLength;
    setTimeout(looper, 1000);
})();
```

Or a real usage:

```javascript
websocket.onopen = function() {
    if(designer.pointsLength > 0) {
        // you seems having data to be synced with existing users!
        designer.sync();
    }
};
```

## `undo`

You can either undo drawings by pressing `ctrl+z` on windows and `command+z` on Mac; however you can undo using `designer.undo` method as well:

```javascript
designer.undo();   // undo last shape
designer.undo(-1); // undo last shape

// undo shape from specific index
designer.undo(0);

// undo all shapes
designer.undo('all');

// undo last 10 shapes
designer.undo({
    numberOfLastShapes: 10
})

// to remove all occurrences of a specific shape
designer.undo('pencil');
designer.undo('arrow');
designer.undo('rect');
```

`designer.pointsLength` shows number of shapes; and `designer.undo` accepts shape-index as well.

Add New Tools

## First Step

Open [`widget.html`](https://github.com/muaz-khan/Canvas-Designer/blob/master/widget.html) and add your new tool-icon HTML.

```html
<div id="tool-box" class="tool-box"> <!-- search for this div; and include your HTML inside this div -->
    <canvas id="yourNewToolIcon" width="40" height="40"></canvas> <!-- here is your icon-HTML -->
</div>
```

## Second Step

Open [`decorator.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/decorator.js) and decorate your new HTML icon.

```javascript
var tools = {
    yourNewToolIcon: true // add this line to make sure index.html can use it
};
```

Search for `decorateLine` method, and append following snippet quickly after that method:

```javascript
function decorateYourNewToolIcon() {
    var context = getContext('yourNewToolIcon');

    context.fillStyle = 'Gray';
    context.font = '9px Verdana';
    context.fillText('New', 16, 12);

    bindEvent(context, 'YourNewToolIconSelected');
}

if (tools.yourNewToolIcon === true) {
    decorateYourNewToolIcon();
} else document.getElementById('yourNewToolIcon').style.display = 'none';
```

## Third Step

Open [`common.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js) and add selection-states for your new tool-icon (i.e. whether your new tool icon is selected or not):

```javascript
var is = {
    isYourNewToolIconSelected: false, // add this line

    set: function (shape) {
        var cache = this;

        cache.isYourNewToolIconSelected = false; // add this line as well.

        // ..... don't modify anything else
        cache['is' + shape] = true;
    }
};
```

You merely need to set `isYourNewToolIconSelected:true` also `cache.isYourNewToolIconSelected=false`.

## Fourth Step

Create new file in the [`dev`](https://github.com/muaz-khan/Canvas-Designer/tree/master/dev) directory. Name this file as `yourNewToolIcon-handler.js`.

This file MUST look like this:

```javascript
var yourNewToolIconHandler = {
    ismousedown: false,

    mousedown: function(e) {
        this.ismousedown = true;
    },

    mouseup: function(e) {
        this.ismousedown = false;
    },

    mousemove: function(e) {
        if(this.ismousedown) { ... }
    }
};
```

You can check other `*-handler.js` from [`dev`](https://github.com/muaz-khan/Canvas-Designer/tree/master/dev) directory to get the idea how exactly it works.

Now open [`Gruntfile.js#L43`](https://github.com/muaz-khan/Canvas-Designer/blob/master/Gruntfile.js#L43) and add link to your new file: `dev/events-handler.js`.

Now compile all your changes using `grunt`.

## Fifth Step

Open [`events-handler.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/events-handler.js) and make sure that your above `yourNewToolIconHandler` object is called for mouse up/down/move events.

```javascript
addEvent(canvas, isTouch ? 'touchstart' : 'mousedown', function (e) {

    // you merely need to add this line at the end of this method
    else if (is.isYourNewToolIconSelected) yourNewToolIconHandler.mousedown(e);
});

addEvent(document, isTouch ? 'touchend' : 'mouseup', function (e) {

    // you merely need to add this line at the end of this method
    else if (is.isYourNewToolIconSelected) yourNewToolIconHandler.mouseup(e);
});

addEvent(canvas, isTouch ? 'touchmove' : 'mousemove', function (e) {

    // you merely need to add this line at the end of this method
    else if (is.isYourNewToolIconSelected) yourNewToolIconHandler.mousemove(e);
});
```

First of all, we are checking whether your tool-icon is selected or not: `is.isYourNewToolIconSelected`

Then we are calling `yourNewToolIconHandler` dot `mousedown/mouseup/mousemove` events respectively.

## Sixth Step

Open [`draw-helper.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/draw-helper.js). Make sure that your new tool-icon can be drawn on the `<canvas>` surface.

```javascript
yourNewToolIcon: function(context, point, options) {
    context.beginPath();
    context.moveTo(point[0], point[1]);
    context.whateverYouWantToDoHere(point[2], point[3]);

    this.handleOptions(context, options);
}
```

Usually `point[0]` is `x` coordinates; `point[1]` is `y` coordinates; `point[2]` is `width` and `point[3]` is `height`.

Different shapes can handle these points differently.

There is NO-limit for `point[index]`. You can add as many points as you want.

Complex shapes can add 10 or 20 points.

## Seventh Step

Open [`drag-helper.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/drag-helper.js) and make sure that your new shape can be dragged/resized/move.

Search for `p[0] === 'line'` and add similar code-blocks for your shape (new-tool-icon) as well.

## Eighth Step

Open [`common.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js) and make sure that your new shape (tool-icon) is printed on the `<textarea>` as well.

This allows end-users to copy your shape's code and use anywhere on their own web-pages.

Open [`common.js`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js) file; there is a function [`updateTextArea`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js#L67) inside the "common" object – which is aimed to output into textarea element.

You don't have to change [`updateTextArea`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js#L67). For simplicity purpose, code is separated in different functions/properties that you've to edit:

1. [`forLoop`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js#L363)
2. [`absoluteNOTShortened`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js#L105)
3. [`relativeShortened`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js#L158)
4. [`relativeNOTShortened`](https://github.com/muaz-khan/Canvas-Designer/blob/master/dev/common.js#L281)

Search for `p[0] === 'line'` and add similar code-blocks for your shape (new-tool-icon) as well.

### For more information

* https://www.webrtc-experiment.com/Canvas-Designer/Help/#contribute

# Shortcut Keys

```
ctrl+t (to display text-fonts box)
ctrl+z (to undo last-single shape)
ctrl+a (to select all shapes)
ctrl+c (copy last-selected shape)
ctrl+v (paste last-copied shape)
```

`ctrl+mousedown` allows you quickly copy/paste all shapes. (i.e. ctrl button + mouse down)

# Signaling Server

* https://github.com/muaz-khan/RTCMultiConnection-Server

# Contributors

1. [Muaz Khan](https://github.com/muaz-khan)
2. [Oleg Aliullov](https://github.com/rashidovich2)

Please make pull-request to update this list.

# License

[Canvas Designer](https://github.com/muaz-khan/Canvas-Designer) is released under [MIT license](https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE) . Copyright (c) [Muaz Khan](https://MuazKhan.com).


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#000000" />

    <corners android:radius="8dp" />

    <padding
        android:bottom="1dp"
        android:left="2dp"
        android:right="2dp"
        android:top="1dp" />

</shape>