text:
<?php

class PHPParser_Comment
{
    protected $text;
    protected $line;

    /**
     * Constructs a comment node.
     *
     * @param string $text Comment text (including comment delimiters like /*)
     * @param int    $line Line number the comment started on
     */
    public function __construct($text, $line = -1) {
        $this->text = $text;
        $this->line = $line;
    }

    /**
     * Gets the comment text.
     *
     * @return string The comment text (including comment delimiters like /*)
     */
    public function getText() {
        return $this->text;
    }

    /**
     * Sets the comment text.
     *
     * @param string $text The comment text (including comment delimiters like /*)
     */
    public function setText($text) {
        $this->text = $text;
    }

    /**
     * Gets the line number the comment started on.
     *
     * @return int Line number
     */
    public function getLine() {
        return $this->line;
    }

    /**
     * Sets the line number the comment started on.
     *
     * @param int $line Line number
     */
    public function setLine($line) {
        $this->line = $line;
    }

    /**
     * Gets the comment text.
     *
     * @return string The comment text (including comment delimiters like /*)
     */
    public function __toString() {
        return $this->text;
    }

    /**
     * Gets the reformatted comment text.
     *
     * "Reformatted" here means that we try to clean up the whitespace at the
     * starts of the lines. This is necessary because we receive the comments
     * without trailing whitespace on the first line, but with trailing whitespace
     * on all subsequent lines.
     *
     * @return mixed|string
     */
    public function getReformattedText() {
        $text = trim($this->text);
        if (false === strpos($text, "\n")) {
            // Single line comments don't need further processing
            return $text;
        } elseif (preg_match('((*BSR_ANYCRLF)(*ANYCRLF)^.*(?:\R\s+\*.*)+$)', $text)) {
            // Multi line comment of the type
            //
            //     /*
            //      * Some text.
            //      * Some more text.
            //      */
            //
            // is handled by replacing the whitespace sequences before the * by a single space
            return preg_replace('(^\s+\*)m', ' *', $this->text);
        } elseif (preg_match('(^/\*\*?\s*[\r\n])', $text) && preg_match('(\n(\s*)\*/$)', $text, $matches)) {
            // Multi line comment of the type
            //
            //    /*
            //        Some text.
            //        Some more text.
            //    */
            //
            // is handled by removing the whitespace sequence on the line before the closing
            // */ on all lines. So if the last line is "    */", then "    " is removed at the
            // start of all lines.
            return preg_replace('(^' . preg_quote($matches[1]) . ')m', '', $text);
        } elseif (preg_match('(^/\*\*?\s*(?!\s))', $text, $matches)) {
            // Multi line comment of the type
            //
            //     /* Some text.
            //        Some more text.
            //        Even more text. */
            //
            // is handled by taking the length of the "/* " segment and leaving only that
            // many space characters before the lines. Thus in the above example only three
            // space characters are left at the start of every line.
            return preg_replace('(^\s*(?= {' . strlen($matches[0]) . '}(?!\s)))m', '', $text);
        }

        // No idea how to format this comment, so simply return as is
        return $text;
    }
}


text:
package com.syncano.android.lib.modules.projects;

import com.google.gson.annotations.Expose;
import com.syncano.android.lib.modules.Params;
import com.syncano.android.lib.modules.Response;

/**
 * Create a new project.
 */

public class ParamsProjectNew extends Params {
	/** New project's name */
	@Expose
	private String name;
	/** New project's description */
	@Expose
	private String description;

	/**
	 * @param name
	 *            New project's name. Cannot be null.
	 */
	public ParamsProjectNew(String name) {
		this.name = name;
	}

	@Override
	public String getMethodName() {
		return "project.new";
	}

	public Response instantiateResponse() {
		return new ResponseProjectNew();
	}

	/**
	 * @return name
	 */
	public String getName() {
		return name;
	}

	/**
	 * Sets name
	 *
	 * @param name
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return description
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * Sets description
	 *
	 * @param description
	 */
	public void setDescription(String description) {
		this.description = description;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.colorcorrect.framework;

import java.util.List;

public interface Input {
	public static class KeyEvent
	{
		public static final int KEY_DOWN = 0;
		public static final int KEY_UP = 1;

		public int type;
		public int keyCode;
		public int keyChar;
	}

	public static class TouchEvent
	{
		public static final int TOUCH_DOWN = 0;
		public static final int TOUCH_UP = 1;
		public static final int TOUCH_DRAGGED = 2;

		public int type;
		public int x,y;
		public int pointer;
	}

	public boolean isKeyPressed(int keyCode);

	public boolean isTouchDown(int pointer);

	public int getTouchX(int pointer); // undefined if pointer isn't assigned

	public int getTouchY(int pointer); // undefined if pointer isn't assigned

	public float getAccelX();

	public float getAccelZ();

	public float getAccelY();

	public List<KeyEvent> getKeyEvents();

	public List<TouchEvent> getTouchEvents();
}


text:
package org.innovateuk.ifs.competition.transactional;

import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.resource.CompetitionExternalConfigResource;
import org.springframework.security.access.prepost.PreAuthorize;

public interface CompetitionExternalConfigService {

    @SecuredBySpring(value = "READ", description = "A system maintainer can see the competition")
    @PreAuthorize("hasAuthority('system_maintainer')")
    ServiceResult<CompetitionExternalConfigResource> findOneByCompetitionId(long competitionId);

    @SecuredBySpring(value = "UPDATE_EXTERNAL_COMP", description = "A system maintainer can update the external competition data.")
    @PreAuthorize("hasAuthority('system_maintainer')")
    ServiceResult<Void> update(long competitionId, CompetitionExternalConfigResource competitionExternalConfigResource);

}


text:
export interface IDataCategory {
  case_count?: number;
  data_category: TCategory;
  file_count?: number;
};

// waiting on $Values
export type TCategory =
  | 'Sequencing Reads'
  | 'Transcriptome Profiling'
  | 'Simple Nucleotide Variation'
  | 'Copy Number Variation'
  | 'Clinical'
  | 'DNA Methylation'
  | 'Biospecimen';

export type TCategoryAbbr =
  | 'Bio'
  | 'Clinical'
  | 'CNV'
  | 'Exp'
  | 'Meth'
  | 'Seq'
  | 'SNV';

export type TCategoryMap = { [k in TCategoryAbbr]: TCategory };

export type TFindDataCategory = (
  category: TCategoryAbbr,
  categories: IDataCategory[]
) => IDataCategory;
export type TSumDataCategories = (categories: IDataCategory[]) => number;


text:
namespace llvm {

class GlobalValue;
class MCContext;
class MCSymbol;
template <typename T> class SmallVectorImpl;
class TargetMachine;
class Twine;

class Mangler {
public:
  enum ManglerPrefixTy {
    Default,               ///< Emit default string before each symbol.
    Private,               ///< Emit "private" prefix before each symbol.
    LinkerPrivate          ///< Emit "linker private" prefix before each symbol.
  };

private:
  MCContext &Context;
  const TargetMachine *TM;

  /// AnonGlobalIDs - We need to give global values the same name every time
  /// they are mangled.  This keeps track of the number we give to anonymous
  /// ones.
  ///
  DenseMap<const GlobalValue*, unsigned> AnonGlobalIDs;

  /// NextAnonGlobalID - This simple counter is used to unique value names.
  ///
  unsigned NextAnonGlobalID;

public:
  Mangler(MCContext &Context, const TargetMachine *TM)
    : Context(Context), TM(TM), NextAnonGlobalID(1) {}

  /// getSymbol - Return the MCSymbol for the specified global value.  This
  /// symbol is the main label that is the address of the global.
  MCSymbol *getSymbol(const GlobalValue *GV);

  /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
  /// and the specified global variable's name.  If the global variable doesn't
  /// have a name, this fills in a unique name for the global.
  void getNameWithPrefix(SmallVectorImpl<char> &OutName, const GlobalValue *GV,
                         bool isImplicitlyPrivate, bool UseGlobalPrefix = true);

  /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
  /// and the specified name as the global variable name.  GVName must not be
  /// empty.
  void getNameWithPrefix(SmallVectorImpl<char> &OutName, const Twine &GVName,
                         ManglerPrefixTy PrefixTy = Mangler::Default,
                         bool UseGlobalPrefix = true);
};

} // End llvm namespace

#endif // LLVM_TARGET_MANGLER_H


text:
local map, section, net = ...

local peeraddr, ip6addr
local tunlink, defaultroute, metric, ttl, mtu

maptype = section:taboption("general", ListValue, "type", translate("Type"))
maptype:value("map-e", "MAP-E")
maptype:value("map-t", "MAP-T")
maptype:value("lw4o6", "LW4over6")

peeraddr = section:taboption("general", Value, "peeraddr",
	translate("BR / DMR / AFTR"))

peeraddr.rmempty  = false
peeraddr.datatype = "ip6addr"

ipaddr = section:taboption("general", Value, "ipaddr",
	translate("IPv4 prefix"))
ipaddr.datatype = "ip4addr"

ip4prefixlen = s:taboption("general", Value, "ip4prefixlen",
        translate("IPv4 prefix length"),
        translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses."))

ip4prefixlen.placeholder = "32"
ip4prefixlen.datatype    = "range(0,32)"

ip6addr = s:taboption("general", Value, "ip6prefix",
        translate("IPv6 prefix"),
        translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>"))

ip6addr.rmempty  = false
ip6addr.datatype = "ip6addr"

ip6prefixlen = s:taboption("general", Value, "ip6prefixlen",
        translate("IPv6 prefix length"),
        translate("The length of the IPv6 prefix in bits"))

ip6prefixlen.placeholder = "16"
ip6prefixlen.datatype    = "range(0,64)"

s:taboption("general", Value, "ealen",
	translate("EA-bits length")).datatype = "range(0,48)"

s:taboption("general", Value, "psidlen",
	translate("PSID-bits length")).datatype = "range(0,16)"

s:taboption("general", Value, "offset",
	translate("PSID offset")).datatype = "range(0,16)"

tunlink = section:taboption("advanced", DynamicList, "tunlink", translate("Tunnel Link"))
tunlink.template = "cbi/network_netlist"
tunlink.nocreate = true

defaultroute = section:taboption("advanced", Flag, "defaultroute",
	translate("Default gateway"),
	translate("If unchecked, no default route is configured"))

defaultroute.default = defaultroute.enabled

metric = section:taboption("advanced", Value, "metric",
	translate("Use gateway metric"))

metric.placeholder = "0"
metric.datatype    = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)

ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype    = "range(1,255)"

mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype    = "max(9200)"


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zinc.Expressions
{
    public class ModExpression : BinaryExpression
    {
        public ModExpression(Expression left, Expression right)
            : base(left, right)
        {

        }

        public override void Visit(IExpressionVisitor visitor)
        {
            visitor.Mod(Left, Right);
        }
    }
}


text:
using namespace rdo::gui::editor;
using namespace rdo::gui::style;

// --------------------------------------------------------------------------------
// -------------------- Edit::Group
// ---------------------------------------------------------------------------
Edit::Group::Group()
    : bMatchCase     (false)
    , bMatchWholeWord(false)
    , bSearchDown    (true )
{}

void Edit::Group::insert(Edit* pEdit)
{
    m_list.push_back(pEdit);
}

Edit::Group::List::const_iterator Edit::Group::begin() const
{
    return m_list.begin();
}

Edit::Group::List::const_iterator Edit::Group::end() const
{
    return m_list.end();
}

Edit::Group::List::const_iterator Edit::Group::next(const List::const_iterator& it) const
{
    Edit::Group::List::const_iterator result(it);
    ++result;
    if (result == m_list.end())
    {
        result = m_list.begin();
    }
    return result;
}

Edit::Group::List::const_iterator Edit::Group::prev(const List::const_iterator& it) const
{
    Edit::Group::List::const_iterator result(it);
    if (result == m_list.begin())
    {
        result = m_list.end();
    }
    --result;
    return result;
}

void Edit::Group::for_each(const this_method& fun) const
{
    boost::range::for_each(m_list, fun);
}

Edit::Group::List::const_iterator Edit::Group::find_if(const this_predicate& fun) const
{
    return boost::range::find_if(m_list, fun);
}

// --------------------------------------------------------------------------------
// -------------------- Edit
// ---------------------------------------------------------------------------

// ---------------
// RTF export

#define RTF_HEADEROPEN    "{\\rtf1\\ansi\\deff0\\deftab720"
#define RTF_FONTDEFOPEN   "{\\fonttbl"
#define RTF_FONTDEF       "{\\f%d\\fnil %s;}"
#define RTF_FONTDEFCLOSE  "}"
#define RTF_COLORDEFOPEN  "{\\colortbl"
#define RTF_COLORDEF      "\\red%d\\green%d\\blue%d;"
#define RTF_COLORDEFCLOSE "}"
#define RTF_HEADERCLOSE   "\n"
#define RTF_BODYOPEN      ""
#define RTF_BODYCLOSE     "}"

#define RTF_SETFONTFACE   "\\f"
#define RTF_SETFONTSIZE   "\\fs"
#define RTF_SETCOLOR      "\\cf"
#define RTF_SETBACKGROUND "\\highlight"
#define RTF_BOLD_ON       "\\b"
#define RTF_BOLD_OFF      "\\b0"
#define RTF_ITALIC_ON     "\\i"
#define RTF_ITALIC_OFF    "\\i0"
#define RTF_UNDERLINE_ON  "\\ul"
#define RTF_UNDERLINE_OFF "\\ulnone"
#define RTF_STRIKE_ON     "\\i"
#define RTF_STRIKE_OFF    "\\strike0"

#define RTF_EOLN "\\par\n"
#define RTF_TAB  "\\tab "

#define MAX_STYLEDEF   128
#define MAX_FONTDEF      1
#define MAX_COLORDEF    32

// ---------------

Edit::Edit(QWidget* pParent)
    : super               (pParent)
    , m_pStyle            (NULL )
    , m_pGroup            (NULL )
    , m_firstFoundPos     (-1   )
    , m_haveFound         (false)
    , m_markerCount       (0    )
    , m_pFindDialog       (NULL )
    , m_pFindReplaceDialog(NULL )
{
    QObject::connect(this, SIGNAL(needShown(int, int)), this, SLOT(catchNeedShown(int, int)));
    QObject::connect(this, SIGNAL(charAdded(int)),      this, SLOT(catchCharAdded(int)));
    QObject::connect(this, SIGNAL(updateUi()),          this, SLOT(onUpdateEditGUI()));
    QObject::connect(this, SIGNAL(modified(int, int, int, int, const QByteArray&, int, int, int)), this, SLOT(onUpdateModify()));
    QObject::connect(this, SIGNAL(aboutToCopy(QMimeData*)), this, SLOT(onCopyAsRTF(QMimeData*)));
    QObject::connect(this, SIGNAL(zoom(int)),this, SLOT(onViewZoomChanged(int)));

    m_sciMarkerBookmark = getNewMarker();

    sendEditor(SCI_SETLEXER, SCLEX_NULL);
    //    int lexLanguage = sendEditor(SCI_GETLEXER);
    sendEditor(SCI_SETMARGINWIDTHN, 1, 0);
    sendEditor(SCI_USEPOPUP, 0);
}

Edit::~Edit()
{}

void Edit::catchNeedShown(int position, int length)
{
    ensureRangeVisible(position, position + length, false);
}

void Edit::catchCharAdded(int ch)
{
    if (m_pStyle && m_pStyle->tab.autoIndent && (ch == '\r' || ch == '\n'))
    {
        autoIndent();
    }
}

long Edit::sendEditorString(std::size_t msg, const std::string& str) const
{
    return super::sends(msg, str.length(), str.c_str());
}

int Edit::getNewMarker()
{
    ++m_markerCount;
    return m_markerCount;
}

void Edit::defineMarker(int marker, int markerType, QColor fore, QColor back) const
{
    sendEditor(SCI_MARKERDEFINE,  marker, markerType);
    sendEditor(SCI_MARKERSETFORE, marker, convertColor(fore));
    sendEditor(SCI_MARKERSETBACK, marker, convertColor(back));
}

const EditStyle* Edit::getEditorStyle() const
{
    return m_pStyle;
}

void Edit::setEditorStyle(EditStyle* pStyle)
{
    m_pStyle = pStyle;
    if (!m_pStyle)
        return;

    // ----------
    // Colors
    EditStyle* style = static_cast<EditStyle*>(m_pStyle);
    sendEditor(SCI_STYLESETBACK, STYLE_DEFAULT, convertColor(style->defaultColor));
    sendEditor(SCI_STYLESETBACK, STYLE_DEFAULT, convertColor(style->backgroundColor));
    sendEditor(SCI_STYLESETFORE, SCE_TEXT_DEFAULT, convertColor(style->defaultColor));
    sendEditor(SCI_STYLESETBACK, SCE_TEXT_DEFAULT, convertColor(style->backgroundColor));

    // ----------
    // Styles
    sendEditor(SCI_STYLESETBOLD     , STYLE_DEFAULT, static_cast<int>(style->defaultStyle) & static_cast<int>(StyleFont::Style::BOLD)     );
    sendEditor(SCI_STYLESETITALIC   , STYLE_DEFAULT, static_cast<int>(style->defaultStyle) & static_cast<int>(StyleFont::Style::ITALIC)   );
    sendEditor(SCI_STYLESETUNDERLINE, STYLE_DEFAULT, static_cast<int>(style->defaultStyle) & static_cast<int>(StyleFont::Style::UNDERLINE));
    sendEditor(SCI_STYLESETBOLD     , SCE_TEXT_DEFAULT, static_cast<int>(style->defaultStyle) & static_cast<int>(StyleFont::Style::BOLD)     );
    sendEditor(SCI_STYLESETITALIC   , SCE_TEXT_DEFAULT, static_cast<int>(style->defaultStyle) & static_cast<int>(StyleFont::Style::ITALIC)   );
    sendEditor(SCI_STYLESETUNDERLINE, SCE_TEXT_DEFAULT, static_cast<int>(style->defaultStyle) & static_cast<int>(StyleFont::Style::UNDERLINE));

    // ----------
    // Font Name
    sendEditorString(SCI_STYLESETFONT, STYLE_DEFAULT, m_pStyle->font.name.c_str());

    // ----------
    // Font Size
    sendEditor(SCI_STYLESETSIZE, STYLE_DEFAULT, m_pStyle->font.size);

    // ----------
    // Codepage and Characterset
    sendEditor(SCI_SETCODEPAGE, SC_CP_UTF8);

    // ----------
    // Tabs
    sendEditor(SCI_SETTABWIDTH, m_pStyle->tab.tabSize);
    sendEditor(SCI_SETINDENT, m_pStyle->tab.indentSize);
    sendEditor(SCI_SETUSETABS, m_pStyle->tab.useTabs);
    sendEditor(SCI_SETTABINDENTS, m_pStyle->tab.tabIndents);
    sendEditor(SCI_SETBACKSPACEUNINDENTS, !m_pStyle->tab.backspaceUntabs);

    // ----------
    // Caret
    sendEditor(SCI_SETCARETFORE, convertColor(style->caretColor));
    sendEditor(SCI_SETSELBACK, true, convertColor(style->selectionBgColor));
    sendEditor(SCI_SETCARETWIDTH, 1);

    // ----------
    // Bookmark
    QColor bookmarkFgColor = style->bookmarkFgColor;
    QColor bookmarkBgColor = style->bookmarkBgColor;
    switch (style->bookmarkStyle)
    {
    case EditStyle::Bookmark::NONE     : defineMarker(m_sciMarkerBookmark, SC_MARK_EMPTY    , bookmarkFgColor, bookmarkBgColor); break;
    case EditStyle::Bookmark::CIRCLE   : defineMarker(m_sciMarkerBookmark, SC_MARK_CIRCLE   , bookmarkFgColor, bookmarkBgColor); break;
    case EditStyle::Bookmark::RECT     : defineMarker(m_sciMarkerBookmark, SC_MARK_SMALLRECT, bookmarkFgColor, bookmarkBgColor); break;
    case EditStyle::Bookmark::ROUNDRECT: defineMarker(m_sciMarkerBookmark, SC_MARK_ROUNDRECT, bookmarkFgColor, bookmarkBgColor); break;
    case EditStyle::Bookmark::ARROW    : defineMarker(m_sciMarkerBookmark, SC_MARK_ARROW    , bookmarkFgColor, bookmarkBgColor); break;
    }

    // ----------
    // Window
    sendEditor(SCI_SETWRAPMODE, m_pStyle->window.wordWrap ? SC_WRAP_WORD : SC_WRAP_NONE);
    sendEditor(SCI_SETHSCROLLBAR, m_pStyle->window.showHorzScrollBar);
}

void Edit::setGroup(Group* pGroup)
{
    m_pGroup = pGroup;
}

void Edit::onEditUndo()
{
    sendEditor(SCI_UNDO);
}

void Edit::onEditRedo()
{
    sendEditor(SCI_REDO);
}

void Edit::onEditCut()
{
    sendEditor(SCI_CUT);
}

void Edit::onEditCopy()
{
    sendEditor(SCI_COPY);
}

void Edit::onEditPaste()
{
    sendEditor(SCI_PASTE);
}

void Edit::onEditDel()
{
    sendEditor(SCI_CLEAR);
}

void Edit::onEditSelectAll()
{
    sendEditor(SCI_SELECTALL);
}

void Edit::onEditUpperCase()
{
    sendEditor(SCI_UPPERCASE);
}

void Edit::onEditLowerCase()
{
    sendEditor(SCI_LOWERCASE);
}

std::string Edit::getCurrentWord() const
{
    int pos_begin = sendEditor(SCI_WORDSTARTPOSITION, getCurrentPos(), true);
    int pos_end   = sendEditor(SCI_WORDENDPOSITION, getCurrentPos(), true);
    int len = pos_end - pos_begin + 2;
    char* word = new char[ len ];
    TextRange tr;
    tr.lpstrText  = word;
    tr.chrg.cpMin = pos_begin;
    tr.chrg.cpMax = pos_end;
    sendEditor(SCI_GETTEXTRANGE, 0, (long)&tr);
    std::string str(tr.lpstrText);
    delete[] word;
    return str;
}

std::string Edit::getSelection() const
{
    CharacterRange cr = getSelectionRange();
    char* selection = new char[ cr.cpMax - cr.cpMin + 1 ];
    sendEditor(SCI_GETSELTEXT, 0, (long)selection);
    std::string str = selection;
    delete[] selection;
    return str;
}

std::string Edit::getCurrentOrSelectedWord() const
{
    return isSelected()
        ? getSelection  ()
        : getCurrentWord();
}

QString Edit::getWordForFind() const
{
    return isSelected()
        ? QString::fromStdString(getSelection())
        : !getCurrentWord().empty()
            ? QString::fromStdString(getCurrentWord())
            : m_pGroup && !m_pGroup->findStr.isEmpty()
                ? m_pGroup->findStr
                : QString();

}

CharacterRange Edit::getSelectionRange() const
{
    CharacterRange crange;
    crange.cpMin = sendEditor(SCI_GETSELECTIONSTART);
    crange.cpMax = sendEditor(SCI_GETSELECTIONEND);
    return crange;
}

void Edit::gotoLineEnsureVisible(int line) const
{
    sendEditor(SCI_ENSUREVISIBLEENFORCEPOLICY, line);
    sendEditor(SCI_GOTOLINE, line);
}

void Edit::ensureRangeVisible(int posStart, int posEnd, bool enforcePolicy) const
{
    int lineStart = getLineFromPosition(posStart < posEnd ? posStart : posEnd);
    int lineEnd   = getLineFromPosition(posStart > posEnd ? posStart : posEnd);
    for (int line = lineStart; line <= lineEnd; ++line)
    {
        sendEditor(enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line);
    }
}

void Edit::onSearchFind()
{
    m_findSettings.what = QString::fromStdString(getCurrentOrSelectedWord());

    if (!m_pFindDialog)
    {
        m_pFindDialog = new FindDialog(
            this,
            boost::bind(&Edit::onFindDlgFind,  this, _1),
            boost::bind(&Edit::onFindDlgClose, this)
        );
    }

    if(m_pGroup)
    {
        m_findSettings.what.isEmpty()
            ? m_findSettings.what = m_pGroup->findStr
            : m_pGroup->findStr = m_findSettings.what;
        m_findReplaceSettings.searchDown = m_pGroup->bSearchDown;
        m_findReplaceSettings.matchCase = m_pGroup->bMatchCase;
        m_findReplaceSettings.matchWholeWord = m_pGroup->bMatchWholeWord;
    }

    m_pFindDialog->setSettings(m_findSettings);
    m_pFindDialog->show();
    m_pFindDialog->raise();
    m_pFindDialog->activateWindow();
}

void Edit::onFindDlgFind(const FindDialog::Settings& settings)
{
    m_findSettings = settings;
    if (m_pGroup)
    {
        m_pGroup->findStr = m_findSettings.what;
    }
    onSearchFindNext();
    updateActionFind(isActivated());
}

void Edit::onFindDlgClose()
{
    m_pFindDialog = NULL;
}

void Edit::onSearchFindNext()
{
    findNext(
        m_pGroup->findStr.isEmpty()
            ? m_findSettings.what
            : m_pGroup->findStr,
        m_findSettings.searchDown,
        m_findSettings.matchCase,
        m_findSettings.matchWholeWord
    );
}

void Edit::onSearchFindPrevious()
{
    findNext(
        m_pGroup->findStr.isEmpty()
            ? m_findSettings.what
            : m_pGroup->findStr,
        !m_findSettings.searchDown,
        m_findSettings.matchCase,
        m_findSettings.matchWholeWord
    );
}

void Edit::onSearchFindNextCurrent()
{
    if (m_pGroup)
    {
        m_pGroup->findStr     = QString::fromStdString(getCurrentWord());
        m_pGroup->bSearchDown = true;
        findNext(m_pGroup->findStr, m_pGroup->bSearchDown, m_pGroup->bMatchCase, m_pGroup->bMatchWholeWord);
    }
}

void Edit::onSearchFindPreviousCurrent()
{
    if (m_pGroup)
    {
        m_pGroup->findStr     = QString::fromStdString(getCurrentWord());
        m_pGroup->bSearchDown = true;
        findNext(m_pGroup->findStr, !m_pGroup->bSearchDown, m_pGroup->bMatchCase, m_pGroup->bMatchWholeWord);
    }
}

void Edit::findNext(const QString& findWhat, bool searchDown, bool matchCase, bool matchWholeWord)
{
    if (findWhat.isEmpty())
        return;

    CharacterRange cr;
    if (m_haveFound)
    {
        cr = getSelectionRange();
    }
    else
    {
        CharacterRange crTemp;
        if (!getSelection().empty())
        {
            crTemp = getSelectionRange();
        }
        else if (!getCurrentWord().empty())
        {
            crTemp.cpMin = sendEditor(SCI_WORDSTARTPOSITION, getCurrentPos(), true);
            crTemp.cpMax = sendEditor(SCI_WORDENDPOSITION,   getCurrentPos(), true);
        }
        else
        {
            crTemp.cpMin = getCurrentPos();
            crTemp.cpMax = getCurrentPos();
        }

        cr.cpMin = std::min(crTemp.cpMin, crTemp.cpMax);
        cr.cpMax = std::max(crTemp.cpMin, crTemp.cpMax);
    }

    int startPosition = cr.cpMax;
    int endPosition   = getLength();
    if (!searchDown)
    {
        startPosition = cr.cpMin;
        endPosition   = 0;
    }

    int flags = (matchCase ? SCFIND_MATCHCASE : 0) | (matchWholeWord ? SCFIND_WHOLEWORD : 0);

    sendEditor(SCI_SETTARGETSTART, startPosition);
    sendEditor(SCI_SETTARGETEND, endPosition);
    sendEditor(SCI_SETSEARCHFLAGS, flags);
    int posFind = sendEditorString(SCI_SEARCHINTARGET, findWhat.toStdString());
    if (posFind == -1)
    {
        if (!searchDown)
        {
            startPosition = getLength();
            endPosition   = 0;
        }
        else
        {
            startPosition = 0;
            endPosition   = getLength();
        }
        sendEditor(SCI_SETTARGETSTART, startPosition);
        sendEditor(SCI_SETTARGETEND, endPosition);
        posFind = sendEditorString(SCI_SEARCHINTARGET, findWhat.toStdString());
    }
    if (posFind == -1)
    {
        m_firstFoundPos = -1;
        m_haveFound     = false;
        showFindWarning(findWhat);
        // TODO возможно, надо убрать
        setFocus();
    }
    else
    {
        if (m_firstFoundPos == -1)
        {
            m_firstFoundPos = posFind;
        }
        else if (posFind == m_firstFoundPos)
        {
            m_firstFoundPos = -1;
            m_haveFound     = false;
            showFindWarning(findWhat);
            // TODO возможно, надо убрать
            setFocus();
            return;
        }
        m_haveFound = true;
        int start   = sendEditor(SCI_GETTARGETSTART);
        int end     = sendEditor(SCI_GETTARGETEND);
        ensureRangeVisible(start, end);
        setSelection(start, end);
    }
}

void Edit::onSearchReplace()
{
    m_findReplaceSettings.what = QString::fromStdString(getCurrentOrSelectedWord());

    if (!m_pFindReplaceDialog)
    {
        m_pFindReplaceDialog = new FindReplaceDialog(
            this,
            boost::bind(&Edit::onFindReplaceDlgFind,       this, _1),
            boost::bind(&Edit::onFindReplaceDlgReplace,    this, _1),
            boost::bind(&Edit::onFindReplaceDlgReplaceAll, this, _1),
            boost::bind(&Edit::onFindReplaceDlgClose,      this)
        );
    }

    if(m_pGroup)
    {
        m_findReplaceSettings.what.isEmpty()
            ? m_findReplaceSettings.what = m_pGroup->findStr
            : m_pGroup->findStr = m_findReplaceSettings.what;
        m_findReplaceSettings.searchDown = m_pGroup->bSearchDown;
        m_findReplaceSettings.matchCase = m_pGroup->bMatchCase;
        m_findReplaceSettings.matchWholeWord = m_pGroup->bMatchWholeWord;
    }

    m_pFindReplaceDialog->setSettings(m_findReplaceSettings);
    m_pFindReplaceDialog->show();
    m_pFindReplaceDialog->raise();
    m_pFindReplaceDialog->activateWindow();
}

void Edit::onFindReplaceDlgFind(const FindReplaceDialog::Settings& settings)
{
    m_findReplaceSettings = settings;
    if (m_pGroup)
    {
        m_pGroup->findStr = m_findReplaceSettings.what;
    }
    findNext(m_findReplaceSettings.what, m_findReplaceSettings.searchDown, m_findReplaceSettings.matchCase, m_findReplaceSettings.matchWholeWord);
    updateActionFind(isActivated());
}

void Edit::onFindReplaceDlgReplace(const FindReplaceDialog::Settings& settings)
{
    m_findReplaceSettings = settings;
    if (m_pGroup)
    {
        m_pGroup->findStr = m_findReplaceSettings.what;
        m_pGroup->replaceStr = m_findReplaceSettings.byWhat;
    }
    if ((!getSelection().empty() && !m_haveFound) || (!getCurrentWord().empty() && !m_haveFound))
    {
        findNext(m_findReplaceSettings.what, m_findReplaceSettings.searchDown, m_findReplaceSettings.matchCase, m_findReplaceSettings.matchWholeWord);
    }
    replace(m_findReplaceSettings.what, m_findReplaceSettings.byWhat, m_findReplaceSettings.searchDown, m_findReplaceSettings.matchCase, m_findReplaceSettings.matchWholeWord);
    updateActionFind(isActivated());
}

void Edit::onFindReplaceDlgReplaceAll(const FindReplaceDialog::Settings& settings)
{
    m_findReplaceSettings = settings;
    if (m_pGroup)
    {
        m_pGroup->findStr    = m_findReplaceSettings.what;
        m_pGroup->replaceStr = m_findReplaceSettings.byWhat;
    }
    replaceAll(m_findReplaceSettings.what, m_findReplaceSettings.byWhat, m_findReplaceSettings.matchCase, m_findReplaceSettings.matchWholeWord);
    updateActionFind(isActivated());
}

void Edit::onFindReplaceDlgClose()
{
    m_pFindReplaceDialog = NULL;
}

void Edit::showFindWarning(const QString& findWhat)
{
    QMessageBox::warning(this, "Результаты поиска", QString("Невозможно найти строчку '%1'.").arg(findWhat));
}

void Edit::replace(const QString& findWhat, const QString& replaceWhat, bool searchDown, bool matchCase, bool matchWholeWord)
{
    if (m_haveFound)
    {
        CharacterRange cr = getSelectionRange();
        if (cr.cpMin == cr.cpMax)
        {
            cr.cpMin = sendEditor(SCI_WORDSTARTPOSITION, getCurrentPos(), true);
            cr.cpMax = cr.cpMin + getCurrentWord().length();
        }
        std::string replaceStr = replaceWhat.toStdString();
        sendEditor(SCI_SETTARGETSTART, cr.cpMin);
        sendEditor(SCI_SETTARGETEND,   cr.cpMax);
        sendEditorString(SCI_REPLACETARGET, replaceStr);
        setSelection(cr.cpMin + replaceStr.length(), cr.cpMin);
        m_haveFound = false;
    }
    findNext(findWhat, searchDown, matchCase, matchWholeWord);
}

void Edit::replaceAll(const QString& findWhat, const QString& replaceWhat, bool matchCase, bool matchWholeWord)
{
    if (findWhat.isEmpty())
        return;

    int startPosition = 0;
    int endPosition   = getLength();

    std::string replaceStr = replaceWhat.toStdString();
    std::string::size_type replaceLen = replaceStr.length();
    int flags = (matchCase ? SCFIND_MATCHCASE : 0) | (matchWholeWord ? SCFIND_WHOLEWORD : 0);

    sendEditor(SCI_SETTARGETSTART, startPosition);
    sendEditor(SCI_SETTARGETEND, endPosition);
    sendEditor(SCI_SETSEARCHFLAGS, flags);
    int posFind = sendEditorString(SCI_SEARCHINTARGET, findWhat.toStdString());

    if ((posFind != -1) && (posFind <= endPosition))
    {
        int lastMatch = posFind;
        sendEditor(SCI_BEGINUNDOACTION);
        while (posFind != -1)
        {
            int lenTarget = sendEditor(SCI_GETTARGETEND) - sendEditor(SCI_GETTARGETSTART);
            sendEditorString(SCI_REPLACETARGET, replaceStr);
            endPosition += replaceLen - lenTarget;
            lastMatch    = posFind + replaceLen;
            if (lenTarget <= 0)
                ++lastMatch;
            sendEditor(SCI_SETTARGETSTART, lastMatch);
            sendEditor(SCI_SETTARGETEND, endPosition);
            posFind = sendEditorString(SCI_SEARCHINTARGET, findWhat.toStdString());
        }
        setSelection(lastMatch, lastMatch);
        sendEditor(SCI_ENDUNDOACTION);
    }
    else
    {
        showFindWarning(findWhat);
        // TODO возможно, надо убрать
        setFocus();
    }
}

void Edit::clearAll()
{
    bool readOnly = isReadOnly();
    setReadOnly(false);
    sendEditor(SCI_CLEARALL);
    setReadOnly(readOnly);
}

bool Edit::bookmarkToggle(int line) const
{
    if (line == -1)
    {
        line = getCurrentLineNumber();
    }
    int state = sendEditor(SCI_MARKERGET, line);
    if (state & (1 << m_sciMarkerBookmark))
    {
        sendEditor(SCI_MARKERDELETE, line, m_sciMarkerBookmark);
        return false;
    }
    else
    {
        sendEditor(SCI_MARKERADD, line, m_sciMarkerBookmark);
        return true;
    }
}

bool Edit::bookmarkNext(bool canLoop, bool fromCurrentLine) const
{
    bool wasFound = false;
    bool wasLoop  = false;

    int line = fromCurrentLine
        ? getCurrentLineNumber()
        : -1;

    int nextLine = sendEditor(SCI_MARKERNEXT, line + 1, 1 << m_sciMarkerBookmark);
    if (nextLine < 0)
    {
        wasLoop = true;
        if (canLoop)
        {
            nextLine = sendEditor(SCI_MARKERNEXT, 0, 1 << m_sciMarkerBookmark);
        }
    }
    if (((canLoop && wasLoop) || !wasLoop) && nextLine >= 0 && nextLine != line)
    {
        gotoLineEnsureVisible(nextLine);
        wasFound = true;
    }

    return wasFound;
}

bool Edit::bookmarkPrev(bool canLoop, bool fromCurrentLine) const
{
    bool wasFound = false;
    bool wasLoop  = false;

    int lineCount = getLineCount();
    int line = fromCurrentLine
        ? getCurrentLineNumber()
        : lineCount + 1;

    int prevLine  = sendEditor(SCI_MARKERPREVIOUS, line - 1, 1 << m_sciMarkerBookmark);
    if (prevLine < 0)
    {
        wasLoop = true;
        if (canLoop)
        {
            prevLine = sendEditor(SCI_MARKERPREVIOUS, lineCount, 1 << m_sciMarkerBookmark);
        }
    }
    if (((canLoop && wasLoop) || !wasLoop) && prevLine >= 0 && prevLine != line)
    {
        gotoLineEnsureVisible(prevLine);
        wasFound = true;
    }

    return wasFound;
}

void Edit::bookmarkClearAll() const
{
    sendEditor(SCI_MARKERDELETEALL, m_sciMarkerBookmark);
}

bool Edit::hasBookmarks() const
{
    int nextLine = sendEditor(SCI_MARKERNEXT, 0, 1 << m_sciMarkerBookmark);
    return nextLine >= 0;
}

void Edit::onCopyAsRTF(QMimeData* pMimeData)
{
    if (!isSelected())
        return;

    CharacterRange cr = getSelectionRange();
    std::string result = saveAsRTF(cr.cpMin, cr.cpMax);
    if (result.empty())
        return;

    QByteArray ba;
    ba.append(result.c_str());
    // TODO для линуха надо будет использовать "text/rtf" ?
    pMimeData->setData("Rich Text Format", ba);
}

// --------------------------------------------------------------------------------
// -------------------- some functions for RTF export ---------- BEGIN
// --------------------------------------------------------------------------------
int GetHexChar(char ch) // 'H'
{
    return ch > '9' ? (ch | 0x20) - 'a' + 10 : ch - '0';
}

int GetHexByte(const char *hexbyte) // "HH"
{
    return (GetHexChar(*hexbyte) << 4) | GetHexChar(hexbyte[1]);
}

#ifdef COMPILER_VISUAL_STUDIO
    #pragma warning(disable: 4996)
#endif

void GetRTFStyleChange(char *delta, char *last, const char *current) // \f0\fs20\cf0\highlight0\b0\i0
{
    int lastLen = strlen(last), offset = 2, lastOffset, currentOffset, len;
    *delta = '\0';
    // font face
    lastOffset = offset + 1;
    while (last[lastOffset] != '\\')
        lastOffset++;
    currentOffset = offset + 1;
    while (current[currentOffset] != '\\')
        currentOffset++;
    if (lastOffset != currentOffset ||        // change
            strncmp(last + offset, current + offset, lastOffset - offset)) {
        if (lastOffset != currentOffset) {
            memmove(last + currentOffset, last + lastOffset, lastLen - lastOffset + 1);
            lastLen += currentOffset - lastOffset;
        }
        len = currentOffset - offset;
        memcpy(last + offset, current + offset, len);
        strcat(delta, RTF_SETFONTFACE);
        lastOffset = strlen(delta);
        memcpy(delta + lastOffset, last + offset, len);
        delta[lastOffset + len] = '\0';
    }
    offset = currentOffset + 3;
    // size
    lastOffset = offset + 1;
    while (last[lastOffset] != '\\')
        lastOffset++;
    currentOffset = offset + 1;
    while (current[currentOffset] != '\\')
        currentOffset++;
    if (lastOffset != currentOffset ||        // change
            strncmp(last + offset, current + offset, lastOffset - offset)) {
        if (lastOffset != currentOffset) {
            memmove(last + currentOffset, last + lastOffset, lastLen - lastOffset + 1);
            lastLen += currentOffset - lastOffset;
        }
        len = currentOffset - offset;
        memcpy(last + offset, current + offset, len);
        strcat (delta, RTF_SETFONTSIZE);
        lastOffset = strlen(delta);
        memcpy(delta + lastOffset, last + offset, len);
        delta[lastOffset + len] = '\0';
    }
    offset = currentOffset + 3;
    // color
    lastOffset = offset + 1;
    while (last[lastOffset] != '\\')
        lastOffset++;
    currentOffset = offset + 1;
    while (current[currentOffset] != '\\')
        currentOffset++;
    if (lastOffset != currentOffset ||        // change
            strncmp(last + offset, current + offset, lastOffset - offset)) {
        if (lastOffset != currentOffset) {
            memmove(last + currentOffset, last + lastOffset, lastLen - lastOffset + 1);
            lastLen += currentOffset - lastOffset;
        }
        len = currentOffset - offset;
        memcpy(last + offset, current + offset, len);
        strcat (delta, RTF_SETCOLOR);
        lastOffset = strlen(delta);
        memcpy(delta + lastOffset, last + offset, len);
        delta[lastOffset + len] = '\0';
    }
    offset = currentOffset + 10;
    // background
    lastOffset = offset + 1;
    while (last[lastOffset] != '\\')
        lastOffset++;
    currentOffset = offset + 1;
    while (current[currentOffset] != '\\')
        currentOffset++;
    if (lastOffset != currentOffset ||        // change
            strncmp(last + offset, current + offset, lastOffset - offset)) {
        if (lastOffset != currentOffset) {
            memmove(last + currentOffset, last + lastOffset, lastLen - lastOffset + 1);
            lastLen += currentOffset - lastOffset;
        }
        len = currentOffset - offset;
        memcpy(last + offset, current + offset, len);
        strcat(delta, RTF_SETBACKGROUND);
        lastOffset = strlen(delta);
        memcpy(delta + lastOffset, last + offset, len);
        delta[lastOffset + len] = '\0';
    }
    offset = currentOffset + 2;
    // bold
    if (last[offset] != current[offset]) {
        if (current[offset] == '\\') { // turn on
            memmove(last + offset, last + offset + 1, lastLen-- - offset);
            strcat (delta, RTF_BOLD_ON);
            offset += 2;
        } else { // turn off
            memmove (last + offset + 1, last + offset, ++lastLen - offset);
            last[offset] = '0';
            strcat(delta, RTF_BOLD_OFF);
            offset += 3;
        }
    } else
        offset += current[offset] == '\\' ? 2 : 3;
    // italic
    if (last[offset] != current[offset]) {
        if (current[offset] == '\\') { // turn on
            memmove(last + offset, last + offset + 1, lastLen-- - offset);
            strcat (delta, RTF_ITALIC_ON);
        } else { // turn off
            memmove(last + offset + 1, last + offset, ++lastLen - offset);
            last[offset] = '0';
            strcat(delta, RTF_ITALIC_OFF);
        }
    }
    if (*delta) {
        lastOffset = strlen(delta);
        delta[lastOffset] = ' ';
        delta[lastOffset + 1] = '\0';
    }
}

// --------------------------------------------------------------------------------
// -------------------- some functions for RTF export ---------- END
// --------------------------------------------------------------------------------

std::string Edit::saveAsRTF(int start, int end) const
{
    std::string saveStr;

    if (!m_pStyle)
    {
        return saveStr;
    }

    int lengthDoc = getLength();
    if (end < 0) end = lengthDoc;
    sendEditor(SCI_COLOURISE, 0, -1);
    char styles[STYLE_DEFAULT + 1][MAX_STYLEDEF];
    char fonts[STYLE_DEFAULT + 1][MAX_FONTDEF];
    char colors[STYLE_DEFAULT + 1][MAX_COLORDEF];
    char lastStyle[MAX_STYLEDEF], deltaStyle[MAX_STYLEDEF];
    int fontCount  = 1;
    int colorCount = 1;
    int i;

    saveStr = "";
    saveStr += RTF_HEADEROPEN;
    saveStr += RTF_FONTDEFOPEN;

    strncpy(*fonts, m_pStyle->font.name.c_str(), MAX_FONTDEF);
    saveStr += rdo::format(RTF_FONTDEF, 0, m_pStyle->font.name.c_str());
    strncpy(*colors, "#000000", MAX_COLORDEF);

    EditStyle* style = static_cast<EditStyle*>(m_pStyle);

    for (int istyle = 0; istyle <= STYLE_DEFAULT; istyle++) {
        if (style->styleUsing(istyle)) {
            sprintf(lastStyle, RTF_SETFONTFACE "%d", fontCount-1);
            sprintf(lastStyle + strlen(lastStyle), RTF_SETFONTSIZE "%d", m_pStyle->font.size * 2);
            if (style->styleDefault(istyle)) {
                strncpy(colors[colorCount++], style->styleBGColorToHEX(istyle).c_str(), MAX_COLORDEF);
            }
            strncpy(colors[colorCount++], style->styleFGColorToHEX(istyle).c_str(), MAX_COLORDEF);
            bool bold   = style->styleBold(istyle);
            bool italic = style->styleItalic(istyle);
            sprintf(lastStyle + strlen(lastStyle), RTF_SETCOLOR "%d", colorCount-1);
            sprintf(lastStyle + strlen(lastStyle), RTF_SETBACKGROUND "%d", 1);
            strcat(lastStyle, bold ? RTF_BOLD_ON : RTF_BOLD_OFF);
            strcat(lastStyle, italic ? RTF_ITALIC_ON : RTF_ITALIC_OFF);
            strncpy(styles[istyle], lastStyle, MAX_STYLEDEF);
        }
    }
    saveStr += RTF_FONTDEFCLOSE;
    saveStr += RTF_COLORDEFOPEN;

    for (i = 0; i < colorCount; i++) {
        saveStr += rdo::format(RTF_COLORDEF, GetHexByte(colors[i] + 1), GetHexByte(colors[i] + 3), GetHexByte(colors[i] + 5));
    }

    saveStr += rdo::format(RTF_COLORDEFCLOSE RTF_HEADERCLOSE RTF_BODYOPEN RTF_SETFONTFACE "0" RTF_SETFONTSIZE "%d" RTF_SETCOLOR "0 ", m_pStyle->font.size * 2);

    sprintf(lastStyle, RTF_SETFONTFACE "0" RTF_SETFONTSIZE "%d" RTF_SETCOLOR "0" RTF_SETBACKGROUND "0" RTF_BOLD_OFF RTF_ITALIC_OFF, m_pStyle->font.size * 2);

    std::string::size_type prevLength = saveStr.length();
    bool prevCR = false;
    int styleCurrent = -1;

    // TODO убрать копипаст
    char* word = new char[end - start + 1];
    TextRange tr;
    tr.lpstrText  = word;
    tr.chrg.cpMin = start;
    tr.chrg.cpMax = end;
    sendEditor(SCI_GETTEXTRANGE, 0, (long)&tr);
    std::string str(tr.lpstrText);
    delete[] word;
    std::wstring wstr = rdo::locale::convertToWStr(str);

    i = start;
    for (std::size_t chIndex = 0; chIndex < wstr.length(); ++chIndex)
    {
        int styleID = sendEditor(SCI_GETSTYLEAT, i);
        if (!style->styleUsing(styleID))
        {
            continue;
        }

        if (styleID != styleCurrent)
        {
            GetRTFStyleChange(deltaStyle, lastStyle, styles[styleID]);
            if (*deltaStyle)
            {
                saveStr += deltaStyle;
            }
            styleCurrent = styleID;
        }

        wchar_t ch = wstr[chIndex];
        if (ch == L'\\')
        {
            saveStr += "\\\\";
        }
        else if (ch == L'\t')
        {
            saveStr += RTF_TAB;
        }
        else if (ch == L'\n')
        {
            if (!prevCR)
            {
                saveStr += RTF_EOLN;
            }
        }
        else if (ch == L'\r')
        {
            saveStr += RTF_EOLN;
        }
        else
        {
            saveStr += boost::str(boost::format("\\u%1%?") % + (std::size_t)ch);
        }

        prevCR = ch == L'\r';

        i += rdo::locale::convertFromWStr(wstr.substr(chIndex, 1)).size();
    }
    bool wasGenerated = prevLength != saveStr.length();
    if (wasGenerated)
    {
        saveStr += RTF_BODYCLOSE;
    }
    else
    {
        saveStr.clear();
    }

    return saveStr;
}
#ifdef COMPILER_VISUAL_STUDIO
    #pragma warning(default: 4996)
#endif

void Edit::setCurrentPos(const int value) const
{
    sendEditor(SCI_SETCURRENTPOS, value);
    sendEditor(SCI_SETSELECTIONSTART, value);
    sendEditor(SCI_SETSELECTIONEND, value);
}

void Edit::setCurrentPos(const int line, int pos_in_line, const bool convert_rdo_tab) const
{
    int pos = getPositionFromLine(line);
    int line_length = sendEditor(SCI_LINELENGTH, line);
    char currentLine[8000];
    bool canUseLine = false;
    if (line_length < 8000)
    {
        sendEditor(SCI_GETLINE, line, (long)currentLine);
        while (currentLine[line_length-1] == 0x0A || currentLine[line_length-1] == 0x0D)
        {
            --line_length;
        }
        canUseLine = true;
    }
    else
    {
        line_length -= 2;
    }

    int new_line_length = line_length;

    if (canUseLine && convert_rdo_tab)
    {
        int tab_size = m_pStyle ? m_pStyle->tab.tabSize : 8;
        int spaces = 0;
        for (int i = 0; i < line_length; i++)
        {
            if (currentLine[i] == ' ')
            {
                spaces++;
            }
            else if (currentLine[i] == '\t')
            {
                int delta = spaces % 8;
                pos_in_line     -= 7 - delta;
                new_line_length += tab_size + delta;
                spaces = 0;
            }
            else
            {
                spaces = 0;
            }
        }
    }

    pos += (std::min)(new_line_length, pos_in_line);

    int line_to_scroll = line > 0 ? line - 1 : 0;
    scrollToLine(line_to_scroll);
    sendEditor(SCI_GOTOPOS, pos);

    setCurrentPos(pos);
}

bool Edit::isLineVisible(const int line) const
{
    int first_line = sendEditor(SCI_GETFIRSTVISIBLELINE);
    int last_line = first_line + sendEditor(SCI_LINESONSCREEN);
    return line >= first_line && line <= last_line;
}

void Edit::appendText(const QString& str) const
{
    std::string text = str.toStdString();
    sendEditorString(SCI_ADDTEXT, text.length(), text.c_str());
}

void Edit::scrollToLine(const int line) const
{
    sendEditor(SCI_LINESCROLL, 0, line - sendEditor(SCI_GETFIRSTVISIBLELINE) - sendEditor(SCI_LINESONSCREEN)/3);
    setCurrentPos(getPositionFromLine(line));
}

void Edit::scrollToLine2(const int line) const
{
    sendEditor(SCI_LINESCROLL, 0, line);
}

void Edit::scrollToCarret() const
{
    sendEditor(SCI_SCROLLCARET);
}

void Edit::horzScrollToCurrentPos() const
{
    setCurrentPos(getCurrentPos());
    sendEditor(SCI_REPLACESEL, 0, 0);
}

void Edit::load(const std::stringstream& stream)
{
    bool readOnly = isReadOnly();
    setReadOnly(false);

    std::string text = stream.str();
    sendEditorString(SCI_ADDTEXT, text.length(), text.c_str());

    setReadOnly(readOnly);
}

void Edit::save(std::stringstream& stream) const
{
    int len = getLength();
    std::vector<char> str;
    str.resize(len + 1);
    sendEditorString(SCI_GETTEXT, len + 1, &str[0]);
    stream.str(&str[0]);
}

int Edit::indentOfBlock(int line) const
{
    if (line < 0)
        return 0;

    return sendEditor(SCI_GETLINEINDENTATION, line);
}

void Edit::setLineIndentation(int line, int indent) const
{
    if (indent < 0) return;
    CharacterRange crange = getSelectionRange();
    int posBefore = sendEditor(SCI_GETLINEINDENTPOSITION, line);
    sendEditor(SCI_SETLINEINDENTATION, line, indent);
    int posAfter = sendEditor(SCI_GETLINEINDENTPOSITION, line);
    int posDifference = posAfter - posBefore;
    if (posAfter > posBefore)
    {
        if (crange.cpMin >= posBefore)
        {
            crange.cpMin += posDifference;
        }
        if (crange.cpMax >= posBefore)
        {
            crange.cpMax += posDifference;
        }
    }
    else if (posAfter < posBefore)
    {
        if (crange.cpMin >= posAfter)
        {
            if (crange.cpMin >= posBefore)
            {
                crange.cpMin += posDifference;
            }
            else
            {
                crange.cpMin = posAfter;
            }
        }
        if (crange.cpMax >= posAfter)
        {
            if (crange.cpMax >= posBefore)
            {
                crange.cpMax += posDifference;
            }
            else
            {
                crange.cpMax = posAfter;
            }
        }
    }
    setSelection(crange.cpMin, crange.cpMax);
}

void Edit::autoIndent() const
{
    CharacterRange crange = getSelectionRange();
    int selStart      = crange.cpMin;
    int curLine       = getCurrentLineNumber();
    int thisLineStart = getPositionFromLine(curLine);
    int indentBlock   = indentOfBlock(curLine - 1);

    if (selStart == thisLineStart)
    {
        setLineIndentation(curLine, indentBlock);
    }
}

void Edit::onSearchBookmarkToggle()
{
    bookmarkToggle();
}

void Edit::onSearchBookmarkNext() const
{
    onSearchBookmarkNextPrev(
        boost::bind(&Edit::bookmarkNext, _1, _2, _3),
        boost::bind(&Edit::Group::next, m_pGroup, _1)
    );
}

void Edit::onSearchBookmarkPrev() const
{
    onSearchBookmarkNextPrev(
        boost::bind(&Edit::bookmarkPrev, _1, _2, _3),
        boost::bind(&Edit::Group::prev, m_pGroup, _1)
    );
}

void Edit::onSearchBookmarkNextPrev(
    const boost::function<bool (const Edit*, bool, bool)>& nextPrevFun,
    const boost::function<Group::List::const_iterator (const Group::List::const_iterator& it)>& nextPrevGroup
) const
{
    if (nextPrevFun(this, false, true))
    {
        return;
    }

    if (!m_pGroup)
    {
        nextPrevFun(this, true, true);
    }
    else
    {
        Group::List::const_iterator it = std::find(m_pGroup->begin(), m_pGroup->end(), this);
        ASSERT(it != m_pGroup->end());

        std::size_t thisBookmarkCount = 0;
        for (;;)
        {
            it = nextPrevGroup(it);

            if (*it == this)
            {
                ++thisBookmarkCount;
                if (thisBookmarkCount > 1)
                {
                    break;
                }
            }

            if (nextPrevFun(*it, false, false))
            {
                QWidget* pParent = (*it)->parentWidget()->parentWidget();
                ASSERT(pParent);
                QTabWidget* pTabWidget = dynamic_cast<QTabWidget*>(pParent);
                if (pTabWidget)
                {
                    pTabWidget->setCurrentWidget(*it);
                }
                break;
            }
        }
    }
}

void Edit::onSearchBookmarkClearAll()
{
    methodOfGroup(boost::bind(&Edit::bookmarkClearAll, _1));
}

void Edit::onUpdateEditGUI()
{
    onUpdateActions(isActivated());
}

void Edit::onViewShowWhiteSpace()
{
    methodOfGroup(boost::bind(&Edit::setViewWhiteSpace, _1, !isViewWhiteSpace()));
}

void Edit::onViewShowEndOfLine()
{
    methodOfGroup(boost::bind(&Edit::setViewEndOfLine, _1, !isViewEndOfLine()));
}

void Edit::onViewZoomChanged(int)
{
    onUpdateActions(isActivated());
}

void Edit::onViewZoomInc()
{
    methodOfGroup(boost::bind(&Edit::zoomIn, _1));
    onUpdateActions(isActivated());
}

void Edit::onViewZoomDec()
{
    methodOfGroup(boost::bind(&Edit::zoomOut, _1));
    onUpdateActions(isActivated());
}

void Edit::onViewZoomReset()
{
    methodOfGroup(boost::bind(&Edit::resetZoom, _1));
    onUpdateActions(isActivated());
}

int Edit::findPos(const QString& findWhat, const int startFromLine, const bool matchCase, const bool matchWholeWord) const
{
    if (findWhat.isEmpty())
        return -1;

    int startPosition = getPositionFromLine(startFromLine);
    int endPosition   = getLength();

    int flags = (matchCase ? SCFIND_MATCHCASE : 0) | (matchWholeWord ? SCFIND_WHOLEWORD : 0);

    sendEditor(SCI_SETTARGETSTART, startPosition);
    sendEditor(SCI_SETTARGETEND, endPosition);
    sendEditor(SCI_SETSEARCHFLAGS, flags);
    return sendEditorString(SCI_SEARCHINTARGET, findWhat.toStdString());
}

std::string Edit::getLine(const int line) const
{
    int length = sendEditor(SCI_LINELENGTH, line);
    std::string str;
    str.resize(length);
    sendEditor(SCI_GETLINE, line, (long)str.data());
    return str;
}

void Edit::onSearchGotoLine()
{
    GoToLineDialog dialog(this, getCurrentLineNumber() + 1, getLineCount());
    if (dialog.exec() == QDialog::Accepted)
    {
        setCurrentPos(dialog.getLine() - 1, 0);
    }
}

void Edit::focusInEvent(QFocusEvent* pEvent)
{
    super::focusInEvent(pEvent);
    activate(pEvent);
}

void Edit::focusOutEvent(QFocusEvent* pEvent)
{
    deactivate(pEvent);
    super::focusOutEvent(pEvent);
}

void Edit::onUpdateActions(bool activated)
{
    MainWindow* pMainWindow = g_pApp->getMainWndUI();
    ASSERT(pMainWindow);

    updateAction(
        pMainWindow->actEditUndo,
        activated && sendEditor(SCI_CANUNDO),
        this, &Edit::onEditUndo
    );
    updateAction(
        pMainWindow->actEditRedo,
        activated && sendEditor(SCI_CANREDO),
        this, &Edit::onEditRedo
    );
    updateAction(
        pMainWindow->actEditCut,
        activated && !isReadOnly() && isSelected(),
        this, &Edit::onEditCut
    );
    updateAction(
        pMainWindow->actEditCopy,
        activated && isSelected(),
        this, &Edit::onEditCopy
    );
    updateAction(
        pMainWindow->actEditPaste,
        activated && sendEditor(SCI_CANPASTE),
        this, &Edit::onEditPaste
    );
    updateAction(
        pMainWindow->actEditDel,
        activated && !isReadOnly() && (getCurrentPos() != getLength() || isSelected()),
        this, &Edit::onEditDel
    );
    updateAction(
        pMainWindow->actEditSelectAll,
        activated && !isEmpty(),
        this, &Edit::onEditSelectAll
    );
    updateAction(
        pMainWindow->actEditUpperCase,
        activated && !isReadOnly() && isSelected(),
        this, &Edit::onEditUpperCase
    );
    updateAction(
        pMainWindow->actEditLowerCase,
        activated && !isReadOnly() && isSelected(),
        this, &Edit::onEditLowerCase
    );
    updateAction(
        pMainWindow->actViewShowWhiteSpace,
        activated,
        this, &Edit::onViewShowWhiteSpace
    );
    pMainWindow->actViewShowWhiteSpace->setChecked(isViewWhiteSpace());

    updateAction(
        pMainWindow->actViewShowEndOfLine,
        activated,
        this, &Edit::onViewShowEndOfLine
    );
    pMainWindow->actViewShowEndOfLine->setChecked(isViewEndOfLine());

    updateAction(
        pMainWindow->actHelpContext,
        activated,
        this, &Edit::onHelpContext
    );
    updateAction(
        pMainWindow->actViewZoomInc,
        activated &&  getZoom() < 20,
        this, &Edit::onViewZoomInc
    );
    updateAction(
        pMainWindow->actViewZoomDec,
        activated && getZoom() > -10,
        this, &Edit::onViewZoomDec
    );
    updateAction(
        pMainWindow->actViewZoomReset,
        activated && getZoom(),
        this, &Edit::onViewZoomReset
    );

    bool hasBookmark = predicateOfGroup(boost::bind(&Edit::hasBookmarks, _1));

    updateAction(
        pMainWindow->actSearchBookmarkNext,
        activated && hasBookmark,
        this, &Edit::onSearchBookmarkNext
    );
    updateAction(
        pMainWindow->actSearchBookmarkPrev,
        activated && hasBookmark,
        this, &Edit::onSearchBookmarkPrev
    );
    updateAction(
        pMainWindow->actSearchBookmarksToggle,
        activated,
        this, &Edit::onSearchBookmarkToggle
    );
    updateAction(
        pMainWindow->actSearchBookmarksClearAll,
        activated && hasBookmark,
        this, &Edit::onSearchBookmarkClearAll
    );
    updateAction(
        pMainWindow->actSearchGotoLine,
        activated,
        this, &Edit::onSearchGotoLine
    );
    updateAction(
        pMainWindow->actSearchFind,
        activated,
        this, &Edit::onSearchFind
    );

    updateActionFind(activated);

    QString modify = activated
        ? isReadOnly()
            ? "Только чтение"
            : isModify()
                ? "Изменён"
                : QString()
        : QString();

    pMainWindow->statusBar()->update<StatusBar::SB_MODIFY>(modify);

    QString coord = activated
        ? QString("%1: %2").arg(getCurrentColumnNumber() + 1).arg(getCurrentLineNumber() + 1)
        : QString();

    pMainWindow->statusBar()->update<StatusBar::SB_COORD>(coord);

    QString overwrite = activated && sendEditor(SCI_GETOVERTYPE)
        ? "Замена"
        : QString();

    pMainWindow->statusBar()->update<StatusBar::SB_OVERWRITE>(overwrite);
}

void Edit::updateActionFind(bool activated)
{
    Ui::MainWindow* pMainWindow = g_pApp->getMainWndUI();
    ASSERT(pMainWindow);

    updateAction(
        pMainWindow->actSearchFind,
        activated && !isEmpty(),
        this, &Edit::onSearchFind
    );

    updateAction(
        pMainWindow->actSearchReplace,
        activated && !isEmpty() && !isReadOnly(),
        this, &Edit::onSearchReplace
    );

    bool findNextPrev = activated && (!m_findReplaceSettings.what.isEmpty() || !m_findSettings.what.isEmpty() || (m_pGroup && !m_pGroup->findStr.isEmpty()));
    updateAction(
        pMainWindow->actSearchFindNext,
        findNextPrev,
        this, &Edit::onSearchFindNext
    );

    updateAction(
        pMainWindow->actSearchFindPrevious,
        findNextPrev,
        this, &Edit::onSearchFindPrevious
    );

    updateAction(
        pMainWindow->actSearchFindNextCurrent,
        activated,
        this, &Edit::onSearchFindNextCurrent
    );

    updateAction(
        pMainWindow->actSearchFindPreviousCurrent,
        activated,
        this, &Edit::onSearchFindPreviousCurrent
    );
}

void Edit::onUpdateModify()
{
    emit modifyChanged(isModify());
}

bool Edit::isViewWhiteSpace() const
{
    return sendEditor(SCI_GETVIEWWS) != SCWS_INVISIBLE;
}

void Edit::setViewWhiteSpace(bool value)
{
    sendEditor(SCI_SETVIEWWS, value ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
}

bool Edit::isViewEndOfLine() const
{
    return sendEditor(SCI_GETVIEWEOL) ? true : false;
}

void Edit::setViewEndOfLine(bool value)
{
    sendEditor(SCI_SETVIEWEOL, value);
}

void Edit::methodOfGroup(const this_method& fun)
{
    m_pGroup
        ? m_pGroup->for_each(fun)
        : fun(this);
}

bool Edit::predicateOfGroup(const this_predicate& fun) const
{
    return m_pGroup
        ? m_pGroup->find_if(fun) != m_pGroup->end()
        : fun(this);
}

std::size_t Edit::convertColor(const QColor& color)
{
    return color.red() | color.green() << 8 | color.blue() << 16;
}


text:
rnmLog(RNM_TRACE, "rnm_timestamp.lua")
-- rnm_timestamp -> get timestamp for NodeMCU

http.get("http://www.convert-unix-time.com/api?timestamp=now", nil, function(rc, data)
  if (rc == 200) then
    RNM_TSDIFF = string.sub(data, string.find(data, "timestamp")+11, string.find(data, "timezone")-3)-tmr.time()
    rnmLog(RNM_INFO,"timestamp: "..RNM_TSDIFF+tmr.time())
  else
    rnmLog(RNM_ERROR,"timestamp not received")
  end
end)


text:
import mock
import six

from st2common.constants import action as action_constants
from st2common.models.api.action import RunnerTypeAPI, ActionAPI, LiveActionAPI
from st2common.models.api.trigger import TriggerTypeAPI, TriggerAPI, TriggerInstanceAPI
from st2common.models.api.rule import RuleAPI
from st2common.persistence.liveaction import LiveAction
from st2common.persistence.runner import RunnerType
from st2common.persistence.execution import ActionExecution
from st2common.transport.publishers import PoolPublisher
import st2common.services.executions as executions_util
import st2common.util.action_db as action_utils
import st2common.util.date as date_utils

from st2tests.base import CleanDbTestCase
from st2tests.fixturesloader import FixturesLoader

import st2tests.config as tests_config
tests_config.parse_args()

FIXTURES_PACK = 'generic'

TEST_FIXTURES = {
    'liveactions': ['liveaction1.yaml', 'parentliveaction.yaml', 'childliveaction.yaml',
                    'successful_liveaction.yaml'],
    'actions': ['local.yaml'],
    'executions': ['execution1.yaml'],
    'runners': ['run-local.yaml'],
    'triggertypes': ['triggertype2.yaml'],
    'rules': ['rule3.yaml'],
    'triggers': ['trigger2.yaml'],
    'triggerinstances': ['trigger_instance_1.yaml']
}

DYNAMIC_FIXTURES = {
    'liveactions': ['liveaction3.yaml']
}

class ExecutionsUtilTestCase(CleanDbTestCase):
    def __init__(self, *args, **kwargs):
        super(ExecutionsUtilTestCase, self).__init__(*args, **kwargs)
        self.MODELS = None

    def setUp(self):
        super(ExecutionsUtilTestCase, self).setUp()
        self.MODELS = FixturesLoader().save_fixtures_to_db(fixtures_pack=FIXTURES_PACK,
                                                           fixtures_dict=TEST_FIXTURES)
        self.FIXTURES = FixturesLoader().load_fixtures(fixtures_pack=FIXTURES_PACK,
                                                       fixtures_dict=DYNAMIC_FIXTURES)

    def test_execution_creation_manual_action_run(self):
        liveaction = self.MODELS['liveactions']['liveaction1.yaml']
        pre_creation_timestamp = date_utils.get_datetime_utc_now()
        executions_util.create_execution_object(liveaction)
        post_creation_timestamp = date_utils.get_datetime_utc_now()
        execution = self._get_action_execution(liveaction__id=str(liveaction.id),
                                               raise_exception=True)
        self.assertDictEqual(execution.trigger, {})
        self.assertDictEqual(execution.trigger_type, {})
        self.assertDictEqual(execution.trigger_instance, {})
        self.assertDictEqual(execution.rule, {})
        action = action_utils.get_action_by_ref('core.local')
        self.assertDictEqual(execution.action, vars(ActionAPI.from_model(action)))
        runner = RunnerType.get_by_name(action.runner_type['name'])
        self.assertDictEqual(execution.runner, vars(RunnerTypeAPI.from_model(runner)))
        liveaction = LiveAction.get_by_id(str(liveaction.id))
        self.assertEquals(execution.liveaction['id'], str(liveaction.id))
        self.assertEquals(len(execution.log), 1)
        self.assertEquals(execution.log[0]['status'], liveaction.status)
        self.assertGreater(execution.log[0]['timestamp'], pre_creation_timestamp)
        self.assertLess(execution.log[0]['timestamp'], post_creation_timestamp)

    def test_execution_creation_action_triggered_by_rule(self):
        # Wait for the action execution to complete and then confirm outcome.
        trigger_type = self.MODELS['triggertypes']['triggertype2.yaml']
        trigger = self.MODELS['triggers']['trigger2.yaml']
        trigger_instance = self.MODELS['triggerinstances']['trigger_instance_1.yaml']
        test_liveaction = self.FIXTURES['liveactions']['liveaction3.yaml']
        rule = self.MODELS['rules']['rule3.yaml']
        # Setup LiveAction to point to right rule and trigger_instance.
        # XXX: We need support for dynamic fixtures.
        test_liveaction['context']['rule']['id'] = str(rule.id)
        test_liveaction['context']['trigger_instance']['id'] = str(trigger_instance.id)
        test_liveaction_api = LiveActionAPI(**test_liveaction)
        test_liveaction = LiveAction.add_or_update(LiveActionAPI.to_model(test_liveaction_api))
        liveaction = LiveAction.get(context__trigger_instance__id=str(trigger_instance.id))
        self.assertIsNotNone(liveaction)
        self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_REQUESTED)
        executions_util.create_execution_object(liveaction)
        execution = self._get_action_execution(liveaction__id=str(liveaction.id),
                                               raise_exception=True)
        self.assertDictEqual(execution.trigger, vars(TriggerAPI.from_model(trigger)))
        self.assertDictEqual(execution.trigger_type, vars(TriggerTypeAPI.from_model(trigger_type)))
        self.assertDictEqual(execution.trigger_instance,
                             vars(TriggerInstanceAPI.from_model(trigger_instance)))
        self.assertDictEqual(execution.rule, vars(RuleAPI.from_model(rule)))
        action = action_utils.get_action_by_ref(liveaction.action)
        self.assertDictEqual(execution.action, vars(ActionAPI.from_model(action)))
        runner = RunnerType.get_by_name(action.runner_type['name'])
        self.assertDictEqual(execution.runner, vars(RunnerTypeAPI.from_model(runner)))
        liveaction = LiveAction.get_by_id(str(liveaction.id))
        self.assertEquals(execution.liveaction['id'], str(liveaction.id))

    def test_execution_creation_with_web_url(self):
        liveaction = self.MODELS['liveactions']['liveaction1.yaml']
        executions_util.create_execution_object(liveaction)
        execution = self._get_action_execution(liveaction__id=str(liveaction.id),
                                               raise_exception=True)
        self.assertTrue(execution.web_url is not None)
        execution_id = str(execution.id)
        self.assertTrue(('history/%s/general' % execution_id) in execution.web_url)

    def test_execution_creation_chains(self):
        childliveaction = self.MODELS['liveactions']['childliveaction.yaml']
        child_exec = executions_util.create_execution_object(childliveaction)
        parent_execution_id = childliveaction.context['parent']['execution_id']
        parent_execution = ActionExecution.get_by_id(parent_execution_id)
        child_execs = parent_execution.children
        self.assertTrue(str(child_exec.id) in child_execs)

    def test_execution_update(self):
        liveaction = self.MODELS['liveactions']['liveaction1.yaml']
        executions_util.create_execution_object(liveaction)
        liveaction.status = 'running'
        pre_update_timestamp = date_utils.get_datetime_utc_now()
        executions_util.update_execution(liveaction)
        post_update_timestamp = date_utils.get_datetime_utc_now()
        execution = self._get_action_execution(liveaction__id=str(liveaction.id),
                                               raise_exception=True)
        self.assertEquals(len(execution.log), 2)
        self.assertEquals(execution.log[1]['status'], liveaction.status)
        self.assertGreater(execution.log[1]['timestamp'], pre_update_timestamp)
        self.assertLess(execution.log[1]['timestamp'], post_update_timestamp)

    @mock.patch.object(PoolPublisher, 'publish', mock.MagicMock())
    def test_abandon_executions(self):
        liveaction_db = self.MODELS['liveactions']['liveaction1.yaml']
        executions_util.create_execution_object(liveaction_db)
        execution_db = executions_util.abandon_execution_if_incomplete(
            liveaction_id=str(liveaction_db.id))
        self.assertEquals(execution_db.status, 'abandoned')

    @mock.patch.object(PoolPublisher, 'publish', mock.MagicMock())
    def test_abandon_executions_on_complete(self):
        liveaction_db = self.MODELS['liveactions']['successful_liveaction.yaml']
        executions_util.create_execution_object(liveaction_db)
        expected_msg = 'LiveAction %s already in a completed state %s\.' % \
                       (str(liveaction_db.id), liveaction_db.status)
        self.assertRaisesRegexp(ValueError, expected_msg,
                                executions_util.abandon_execution_if_incomplete,
                                liveaction_id=str(liveaction_db.id))

    def _get_action_execution(self, **kwargs):
        return ActionExecution.get(**kwargs)

# descendants test section

DESCENDANTS_PACK = 'descendants'

DESCENDANTS_FIXTURES = {
    'executions': ['root_execution.yaml', 'child1_level1.yaml', 'child2_level1.yaml',
                   'child1_level2.yaml', 'child2_level2.yaml', 'child3_level2.yaml',
                   'child1_level3.yaml', 'child2_level3.yaml', 'child3_level3.yaml']
}

class ExecutionsUtilDescendantsTestCase(CleanDbTestCase):
    def __init__(self, *args, **kwargs):
        super(ExecutionsUtilDescendantsTestCase, self).__init__(*args, **kwargs)
        self.MODELS = None

    def setUp(self):
        super(ExecutionsUtilDescendantsTestCase, self).setUp()
        self.MODELS = FixturesLoader().save_fixtures_to_db(fixtures_pack=DESCENDANTS_PACK,
                                                           fixtures_dict=DESCENDANTS_FIXTURES)

    def test_get_all_descendants_sorted(self):
        root_execution = self.MODELS['executions']['root_execution.yaml']
        all_descendants = executions_util.get_descendants(str(root_execution.id),
                                                          result_fmt='sorted')

        all_descendants_ids = [str(descendant.id) for descendant in all_descendants]
        all_descendants_ids.sort()

        # everything except the root_execution
        expected_ids = [str(v.id) for _, v in six.iteritems(self.MODELS['executions'])
                        if v.id != root_execution.id]
        expected_ids.sort()

        self.assertListEqual(all_descendants_ids, expected_ids)

        # verify sort order
        for idx in range(len(all_descendants) - 1):
            self.assertLess(all_descendants[idx].start_timestamp,
                            all_descendants[idx + 1].start_timestamp)

    def test_get_all_descendants(self):
        root_execution = self.MODELS['executions']['root_execution.yaml']
        all_descendants = executions_util.get_descendants(str(root_execution.id))

        all_descendants_ids = [str(descendant.id) for descendant in all_descendants]
        all_descendants_ids.sort()

        # everything except the root_execution
        expected_ids = [str(v.id) for _, v in six.iteritems(self.MODELS['executions'])
                        if v.id != root_execution.id]
        expected_ids.sort()

        self.assertListEqual(all_descendants_ids, expected_ids)

    def test_get_1_level_descendants_sorted(self):
        root_execution = self.MODELS['executions']['root_execution.yaml']
        all_descendants = executions_util.get_descendants(str(root_execution.id),
                                                          descendant_depth=1,
                                                          result_fmt='sorted')

        all_descendants_ids = [str(descendant.id) for descendant in all_descendants]
        all_descendants_ids.sort()

        # All children of root_execution
        expected_ids = [str(v.id) for _, v in six.iteritems(self.MODELS['executions'])
                        if v.parent == str(root_execution.id)]
        expected_ids.sort()

        self.assertListEqual(all_descendants_ids, expected_ids)

        # verify sort order
        for idx in range(len(all_descendants) - 1):
            self.assertLess(all_descendants[idx].start_timestamp,
                            all_descendants[idx + 1].start_timestamp)

    def test_get_2_level_descendants_sorted(self):
        root_execution = self.MODELS['executions']['root_execution.yaml']
        all_descendants = executions_util.get_descendants(str(root_execution.id),
                                                          descendant_depth=2,
                                                          result_fmt='sorted')

        all_descendants_ids = [str(descendant.id) for descendant in all_descendants]
        all_descendants_ids.sort()

        # All children of root_execution
        root_execution = self.MODELS['executions']['root_execution.yaml']
        expected_ids = []
        traverse = [(child_id, 1) for child_id in root_execution.children]
        while traverse:
            node_id, level = traverse.pop(0)
            expected_ids.append(node_id)
            children = self._get_action_execution(node_id).children
            if children and level < 2:
                traverse.extend([(child_id, level + 1) for child_id in children])
        expected_ids.sort()

        self.assertListEqual(all_descendants_ids, expected_ids)

    def _get_action_execution(self, ae_id):
        for _, execution in six.iteritems(self.MODELS['executions']):
            if str(execution.id) == ae_id:
                return execution
        return None


text:
FOUNDATION_EXPORT double NTSwiftJsonVersionNumber;

//! Project version string for NTSwiftJson.
FOUNDATION_EXPORT const unsigned char NTSwiftJsonVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <NTSwiftJson/PublicHeader.h>


text:
package com.intellij.debugger.memory.filtering;

import com.sun.jdi.ObjectReference;
import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
@FunctionalInterface
public interface ConditionChecker {
  CheckingResult check(@NotNull ObjectReference ref);

  ConditionChecker ALL_MATCHED_CHECKER = ref -> CheckingResultImpl.SUCCESS;
}


text:
/*
* Mercado de TI
* @author Paulo R. Almeida Filho
* pauloalmeidaf@gmail.com
* */

package com.github.palmeidaprog.iccmercado.main.test;

import com.github.palmeidaprog.iccmercado.main.Main;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class TestResultController {
    @FXML private Label hard, lider, criati, ensino, relaci, pesq, matem,
            logic, resol, desig;
    private Parent root;
    private Stage resultWindow = new Stage();

    //--Singleton pattern--------------------------------------------------
    private static volatile TestResultController instance = null;

    // constructor
    private TestResultController() { }
    public synchronized static TestResultController getInstance() {
        if(instance == null) {
            instance = new TestResultController();
        }
        return instance;
    }

    // atualiza informações das Labels
    // update info from the labels
    public void update() {
        Choices ch = Choices.getInstance();
        hard.setText("- Hardware: " + Hardware.getInstance().getStars());
        ch.setHardware(Hardware.getInstance().getStars());
        lider.setText("- Liderança: " + Lideranca.getInstance().getStars());
        ch.setLideranca(Lideranca.getInstance().getStars());
        criati.setText("- Criatividade: " + Criatividade.getInstance().getStars());
        ch.setCriatividade(Criatividade.getInstance().getStars());
        ensino.setText("- Ensino: " + Ensino.getInstance().getStars());
        ch.setEnsino(Ensino.getInstance().getStars());
        relaci.setText("- Relacionamento Interpessoal: " + Relacionamento.getInstance().getStars());
        ch.setRelacionamento(Relacionamento.getInstance().getStars());
        pesq.setText("- Pesquisa: " + Pesquisa.getInstance().getStars());
        ch.setPesquisa(Pesquisa.getInstance().getStars());
        matem.setText("- Matemática: " + Matematica.getInstance().getStars());
        ch.setMatematica(Matematica.getInstance().getStars());
        logic.setText("- Lógica e Abstração: " + Logica.getInstance().getStars());
        ch.setLogica(Logica.getInstance().getStars());
        resol.setText("- Resolução de Problemas: " + Problemas.getInstance().getStars());
        ch.setProblemas(Problemas.getInstance().getStars());
        desig.setText("- Design e Artes: " + Design.getInstance().getStars());
        ch.setDesign(Design.getInstance().getStars());
        ch.calculateProfessions();
    }

    public void showResult() {
        Choices cc = Choices.getInstance();
        cc.orderingProfessions();

        FXMLLoader loaderResult = new FXMLLoader(getClass().getResource("result_window.fxml"));
        loaderResult.setController(ResultWindowController.getInstance());
        try {
            root = loaderResult.load();
        } catch(IOException e) {
            e.printStackTrace();
        }
        resultWindow.setScene(new Scene(root, 750, 750));

        try {
            Image f = new Image(Main.class.getResourceAsStream("favicon.png"));
            resultWindow.getIcons().add(f);
        } catch(Exception e) { }

        resultWindow.setTitle("Resultado do Teste de Aptidão");
        ResultWindowController.getInstance().update(); // update professions before calling Stage
        resultWindow.show();

    }
}


text:
'use strict';

import React, { Component } from 'react';
import {
  Text,
  View,
} from 'react-native';
import { connect } from 'react-redux';

import { styles } from '../styles';
import { words } from '../words';

import { clickWord } from '../actions';

const Word = ({ sentence, index, onWordClick })  => {
  var targetWord = sentence[index];
  var wordStyle = ([
    styles.word,
    { backgroundColor: words[targetWord.type]['color']}
  ]);

  if (targetWord.type == 'punctuation') { // add thin gray outline
    wordStyle = ([
      wordStyle,
      { borderColor: '#aaa', borderWidth: 1.0 }
    ]);
  }

  return (
    <View style={wordStyle}>
    <Text style={styles.wordText}>
      { targetWord.word }
    </Text>
    </View>
  )
};

// /* Container Component */

const mapDispatchToProps = (dispatch) => {
  return {
    onWordClick: (wordType, wordIndex) => {
      dispatch(clickWord(wordType, wordIndex))
    }
  }
}

const mapStateToProps = (state) => {
  return {
    sentence: state.sentences.activeSentence
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Word)


text:
package com.group6.babytime.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

/**
 * Created by Administrator on 2016/10/24.
 */
public class MyGridView extends GridView {
    public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}


text:
<?php

namespace Ecedi\Donate\CoreBundle\Exception;

interface CoreExceptionInterface
{
}


text:
<!DOCTYPE HTML>

  <meta charset="UTF-8">
  <title>Firefox OS, otra manera de hacer las cosas</title>
  <meta name="viewport" content="width=device-width, user-scalable=yes">
  <link rel="stylesheet" href="themes/mozilla/styles/style.css">

Firefox OS, otra manera de hacer las cosas

    Pablo Bernardo
      (@voylinux)

Esta presentación usa el sistema shower, puedes pasar por encima de cada diapositiva para ver las notas y hacer clic en cualquiera de ellas para ir al modo de presentación. Después puedes usar las teclas para navegar <button onclick="goFullScreen()">Pantalla completa</button>

      Resumen:
      Firefox OS representa una revolución en los sistemas operativos para smartphone en cuanto a planteamiento, objetivos y tecnología

Firefox OS, otra manera de hacer las cosas

        Pablo Bernardo, LibreCon, Bilbao, 11 y 12/11/2014

Pablo Bernardo (@voylinux)

Desarrollador web y apps

Miembro activo Mozilla Hispano

Orgulloso #Mozillian

Bloguero, finisher, padre, geek, speaker...

Open Web Evangelist

Comunicador apasionado

Una realidad en el mundo

        http://nickdesaulniers.github.io/where-is-firefox-os/

Firefox OS

Firefox OS es el único sistema operativo móvil completamente abierto basado en estándares web

Mozilla desbloquea la web como una plataforma real para crear app móviles con HTML, CSS y JS

Se enfoca especialmente (no únicamente) a mercados emergentes

Devuelve el control a los desarrolladores, no a intermediarios

Representa una opción realmente abierta

Mejorando el mundo móvil

Enfocado a mercados emergentes y nuevos

Hardware asequible

Sin una cuenta controlada por terceros

Tecnologías web, sin tecnologías propietarias

Presente en 24 paises, más de 15 dispositivos

        https://firefoxosdevices.org/en/

La plataforma móvil que HTML5 merece

Verdadero Open Source

        https://github.com/mozilla-b2g/gaia

Arquitectura del sistema

Gonk: Kernel y controladores

Gecko: Tiempo de ejecución y APIS (accesibles)

Gaia: Interfaz de usuario

Soporte del navegador predecible

Todo el sistema es Web y propuesta de estándar

Batería API

          var b = navigator.battery;
          if (b) {
            var level = Math.round(b.level * 100) + "%",
                charging = (b.charging) ? "" : "not ",
                chargeTime = parseInt(b.chargingTime / 60, 10),
                dischargeTime = parseInt(b.dischargingTime/60,10);
            b.addEventListener("levelchange", show);
            b.addEventListener("chargingchange", show);
            b.addEventListener("chargingtimechange", show);
            b.addEventListener("dischargingtimechange", show);
          }

Aplicaciones de la Web abierta

¿Aplicaciones Firefox OS?

Aplicaciones de HTML5 con un archivo manifiest

Define datos de la app, permisos solicitados y otra información.

Modelo de seguridad de tres capas. Alojada vs. Empaquetada

Apps accesibles desde la web o el marketplace

Archivo manifest

        {
          "name": "Mi Aplicación",
          "description": "La descripción del uso",
          "launch_path": "/",
          "icons": { "128": "/img/icon-128.png" },
          "developer": {
            "name": "Tu nombre u organización",
            "url": "http://your-homepage-here.org"
          }
        }

Manifiesto de la App

Tres niveles de acceso…

Aplicaciones alojadas - guardadas en tu servidor, fácil de actualizar, acceso limitado.

Aplicaciones privilegiadas - revisadas por el marketplace, empaquetadas y firmadas

Aplicaciones certificadas - parte del SO, solo de Mozilla y asociados

App permissions

WebAPIs

Web APIs

        Wiki de las WebAPI

Web APIs (aplicaciones alojadas)

API vibración

Orientación de la pantalla

Geolocalización API

Control del mouse API

WebApps abiertas

Información de la red API

Estado de la batería API

Alarma API

Envio de notificaciones API

WebFM API / FMRadio

Pagos por Web

IndexedDB

Sensor de luz ambiente

Sensor de proximidad

Notificaciones

        Usar WebAPIs para hacer ampliar la capacidad de la capa web

Web APIs (aplicaciones privilegiadas)

Memoria del dispositivo API

Navegador API

TCP Socket API

Contactos API

systemXHR

        Usar WebAPIs para hacer ampliar la capacidad de la capa web

Contactos API

          var contact = new mozContact();
          contact.init({name: "Christian"});
          var request = navigator.mozContacts.save(contact);
          request.onsuccess = function() {
            // contact generated
          };
          request.onerror = function() {
            // contact generation failed
          };

Web APIs (aplicaciones certificadas)

WebTelephony

WebSMS

Espera API

Opciones API

Adminstración de energía API

Conexión móvil API

Información WiFi API

WebBluetooth

Permisos API

Estadísticas de red API

Cámara API

Fecha/Reloj API

Atención de la pantalla

Correo de voz

        Usar WebAPIs para hacer ampliar la capacidad de la capa web

Web Activities

Web activities

configure

costcontrol

dial

open

pick

record

save-bookmark

share

view

new, p.e type: "websms/sms" o "webcontacts/contact"

Obtener una imagen del teléfono (1/2)

        var getphoto = new MozActivity({
          name: "pick",
          data: {
            type: ["image/png",
                   "image/jpg",
                   "image/jpeg"]
          }
        });

Obtener una imagen del teléfono (2/2)

        getphoto.onsuccess = function () {
          var img = document.createElement("img");
          if (this.result.blob.type.indexOf("image") != -1) {
            img.src = window.URL.createObjectURL(this.result.blob);
          }
        };
        getphoto.onerror = function () { // error
        };

Activities y aplicaciones alojadas en Android

Búsqueda dinámica de aplicaciones

Caso de uso a aplicación

Caso de uso a aplicación

       <video class="middle" height="450" controls>
        <source src="pictures/fxos/dynamicsearch.mp4"  type="video/mp4"></source>
        <source src="pictures/fxos/dynamicsearch.webm"  type="video/webm"></source>
      </video>

Herramientas

Sin IDE ni SDK. Usa el navegador

Simulador de Firefox OS

          Simulador de Firefox OS

Prototipos con JSFiddle

Escribe tu código como harías normalmente con JSFiddle

Agrega /webapp.manifest a la URL del Fiddle y pega el enlace en el simulador de Firefox OS para instalar la aplicación

También puedes agregar /fxos.html a la URL del Fiddle para obtener una página de instalación como tendrías con una típica aplicación alojada de Firefox OS

          Usar para prototipos de aplicaciones de Firefox OS

Componentes de la interfaz de Firefox

        Crear FirefoxOS

Bloques de Firefox OS

        FirefoxOS edit mode

Mozilla Brick

        Brick – Presentamos Brick

Modelo de Web Activities

        Modelo de aplicaciones para Firefox OS

Recursos

Firefox OS Marketplace

          https://marketplace.firefox.com/

Centro para desarrolladores

          https://marketplace.firefox.com/developers/

El blog de Hacks

          https://hacks.mozilla.org/category/firefox-os/

Serie de videos sobre Firefox OS

          https://hacks.mozilla.org/category/videoseries/

El Wiki de Firefox OS

          https://developer.mozilla.org/en/docs/Mozilla/Firefox_OS

Gracias. ¿Preguntas?

Pablo Bernardo

@voylinux

Slides:

voylinux.github.io/librecon_2014_firefoxos

        Photo by Yortw


text:
@class TFPGCodeProgram, TFPPrinter, TFPPrintParameters;

@interface TFPPrintingProgressViewController : NSViewController
@property TFPGCodeProgram *program;
@property TFPPrinter *printer;
@property TFPPrintParameters *printParameters;

- (void)start;
@property (copy) void(^endHandler)(BOOL didFinishPrint);

- (NSString*)elapsedTimeString;
@end


text:
package sink

import (
	"context"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"testing"

	. "github.com/smartystreets/goconvey/convey"
	. "go.chromium.org/luci/common/testing/assertions"
	pb "go.chromium.org/luci/resultdb/proto/v1"
	sinkpb "go.chromium.org/luci/resultdb/sink/proto/v1"
)

func TestArtifactChannel(t *testing.T) {
	t.Parallel()

	Convey("schedule", t, func() {
		cfg := testServerConfig("127.0.0.1:123", "secret")
		ctx := context.Background()

		streamCh := make(chan *http.Request, 10)
		cfg.ArtifactStreamClient.Transport = mockTransport(
			func(in *http.Request) (*http.Response, error) {
				streamCh <- in
				return &http.Response{StatusCode: http.StatusNoContent}, nil
			},
		)
		batchCh := make(chan *pb.BatchCreateArtifactsRequest, 10)
		cfg.Recorder.(*mockRecorder).batchCreateArtifacts = func(ctx context.Context, in *pb.BatchCreateArtifactsRequest) (*pb.BatchCreateArtifactsResponse, error) {
			batchCh <- in
			return nil, nil
		}
		createTask := func(name, content string) *uploadTask {
			art := testArtifactWithContents([]byte(content))
			task, err := newUploadTask(name, art)
			So(err, ShouldBeNil)
			return task
		}

		Convey("with a small artifact", func() {
			task := createTask("invocations/inv/artifacts/art1", "content")
			ac := newArtifactChannel(ctx, &cfg)
			ac.schedule(task)
			ac.closeAndDrain(ctx)

			// The artifact should have been sent to the batch channel.
			So(<-batchCh, ShouldResembleProto, &pb.BatchCreateArtifactsRequest{
				Requests: []*pb.CreateArtifactRequest{{
					Parent: "invocations/inv",
					Artifact: &pb.Artifact{
						ArtifactId:  "art1",
						ContentType: task.art.ContentType,
						SizeBytes:   int64(len("content")),
						Contents:    []byte("content"),
					},
				}},
			})
		})

		Convey("with multiple, small artifacts", func() {
			cfg.MaxBatchableArtifactSize = 10
			ac := newArtifactChannel(ctx, &cfg)

			t1 := createTask("invocations/inv/artifacts/art1", "1234")
			t2 := createTask("invocations/inv/artifacts/art2", "5678")
			t3 := createTask("invocations/inv/artifacts/art3", "9012")
			ac.schedule(t1)
			ac.schedule(t2)
			ac.schedule(t3)
			ac.closeAndDrain(ctx)

			// The 1st request should contain the first two artifacts.
			So(<-batchCh, ShouldResembleProto, &pb.BatchCreateArtifactsRequest{
				Requests: []*pb.CreateArtifactRequest{
					// art1
					{
						Parent: "invocations/inv",
						Artifact: &pb.Artifact{
							ArtifactId:  "art1",
							ContentType: t1.art.ContentType,
							SizeBytes:   int64(len("1234")),
							Contents:    []byte("1234"),
						},
					},
					// art2
					{
						Parent: "invocations/inv",
						Artifact: &pb.Artifact{
							ArtifactId:  "art2",
							ContentType: t2.art.ContentType,
							SizeBytes:   int64(len("5678")),
							Contents:    []byte("5678"),
						},
					},
				},
			})

			// The 2nd request should only contain the last one.
			So(<-batchCh, ShouldResembleProto, &pb.BatchCreateArtifactsRequest{
				Requests: []*pb.CreateArtifactRequest{
					// art3
					{
						Parent: "invocations/inv",
						Artifact: &pb.Artifact{
							ArtifactId:  "art3",
							ContentType: t3.art.ContentType,
							SizeBytes:   int64(len("9012")),
							Contents:    []byte("9012"),
						},
					},
				},
			})
		})

		Convey("with a large artifact", func() {
			cfg.MaxBatchableArtifactSize = 10
			ac := newArtifactChannel(ctx, &cfg)

			t1 := createTask("invocations/inv/artifacts/art1", "content-foo-bar")
			ac.schedule(t1)
			ac.closeAndDrain(ctx)

			// The artifact should have been sent to the stream channel.
			req := <-streamCh
			So(req, ShouldNotBeNil)
			So(req.URL.String(), ShouldEqual,
				"https://"+cfg.ArtifactStreamHost+"/invocations/inv/artifacts/art1")
			body, err := io.ReadAll(req.Body)
			So(err, ShouldBeNil)
			So(body, ShouldResemble, []byte("content-foo-bar"))
		})
	})

}

func TestUploadTask(t *testing.T) {
	t.Parallel()

	Convey("newUploadTask", t, func() {
		name := "invocations/inv/artifacts/art1"
		fArt := testArtifactWithFile(func(f *os.File) {
			_, err := f.Write([]byte("content"))
			So(err, ShouldBeNil)
		})
		fArt.ContentType = "plain/text"
		defer os.Remove(fArt.GetFilePath())

		Convey("works", func() {
			t, err := newUploadTask(name, fArt)
			So(err, ShouldBeNil)
			So(t, ShouldResemble, &uploadTask{art: fArt, artName: name, size: int64(len("content"))})
		})

		Convey("fails", func() {
			// stat error
			So(os.Remove(fArt.GetFilePath()), ShouldBeNil)
			_, err := newUploadTask(name, fArt)
			So(err, ShouldErrLike, "querying file info")

			// is a directory
			path, err := ioutil.TempDir("", "foo")
			So(err, ShouldBeNil)
			defer os.RemoveAll(path)
			fArt.Body.(*sinkpb.Artifact_FilePath).FilePath = path
			_, err = newUploadTask(name, fArt)
			So(err, ShouldErrLike, "is a directory")
		})
	})

	Convey("CreateRequest", t, func() {
		name := "invocations/inv/tests/t1/results/r1/artifacts/a1"
		fArt := testArtifactWithFile(func(f *os.File) {
			_, err := f.Write([]byte("content"))
			So(err, ShouldBeNil)
		})
		fArt.ContentType = "plain/text"
		defer os.Remove(fArt.GetFilePath())
		ut, err := newUploadTask(name, fArt)
		So(err, ShouldBeNil)

		Convey("works", func() {
			req, err := ut.CreateRequest()
			So(err, ShouldBeNil)
			So(req, ShouldResembleProto, &pb.CreateArtifactRequest{
				Parent: "invocations/inv/tests/t1/results/r1",
				Artifact: &pb.Artifact{
					ArtifactId:  "a1",
					ContentType: "plain/text",
					SizeBytes:   int64(len("content")),
					Contents:    []byte("content"),
				},
			})
		})

		Convey("fails", func() {
			// the artifact content changed.
			So(os.WriteFile(fArt.GetFilePath(), []byte("surprise!!"), 0), ShouldBeNil)
			_, err := ut.CreateRequest()
			So(err, ShouldErrLike, "the size of the artifact contents changed")

			// the file no longer exists.
			So(os.Remove(fArt.GetFilePath()), ShouldBeNil)
			_, err = ut.CreateRequest()
			So(err, ShouldErrLike, "open "+fArt.GetFilePath()) // no such file or directory
		})
	})
}


text:
using pc2x.Application.Repositories.EntityFramework.Entities;
using System.Data.Entity.ModelConfiguration;

namespace pc2x.Application.Repositories.EntityFramework.EntitiesConfiguration
{
    class EstadoConfiguration : EntityTypeConfiguration<EstadoEntity>
    {
        public EstadoConfiguration()
        {
            //table name
            Map(m => m.ToTable("Estados"));

            //add primary key
            HasKey(m => m.Id);

            //Required Field
            Property(m => m.Nombre)
                .HasColumnName("Nombre")
                .HasColumnType("nvarchar")
                .HasMaxLength(50)
                .IsRequired();

            Property(m => m.Codigo)
                .HasColumnName("Codigo")
                .HasColumnType("nvarchar")
                .HasMaxLength(5)
                .IsRequired();

            HasMany(m => m.Municipios)
                .WithRequired(m => m.Estado)
                .HasForeignKey(m => m.EstadoId)
                .WillCascadeOnDelete();

            //ignora un campo de mapear a la db
            //Ignore(m => m.Id);
        }
    }
}


text:
namespace cc {

base::SingleThreadTaskRunner* Proxy::MainThreadTaskRunner() const {
  return main_task_runner_.get();
}

bool Proxy::HasImplThread() const { return !!impl_task_runner_.get(); }

base::SingleThreadTaskRunner* Proxy::ImplThreadTaskRunner() const {
  return impl_task_runner_.get();
}

bool Proxy::IsMainThread() const {
#if DCHECK_IS_ON
  if (impl_thread_is_overridden_)
    return false;

  bool is_main_thread = base::PlatformThread::CurrentId() == main_thread_id_;
  if (is_main_thread && main_task_runner_.get()) {
    DCHECK(main_task_runner_->BelongsToCurrentThread());
  }
  return is_main_thread;
#else
  return true;
#endif
}

bool Proxy::IsImplThread() const {
#if DCHECK_IS_ON
  if (impl_thread_is_overridden_)
    return true;
  if (!impl_task_runner_.get())
    return false;
  return impl_task_runner_->BelongsToCurrentThread();
#else
  return true;
#endif
}

#if DCHECK_IS_ON
void Proxy::SetCurrentThreadIsImplThread(bool is_impl_thread) {
  impl_thread_is_overridden_ = is_impl_thread;
}
#endif

bool Proxy::IsMainThreadBlocked() const {
#if DCHECK_IS_ON
  return is_main_thread_blocked_;
#else
  return true;
#endif
}

#if DCHECK_IS_ON
void Proxy::SetMainThreadBlocked(bool is_main_thread_blocked) {
  is_main_thread_blocked_ = is_main_thread_blocked;
}
#endif

Proxy::Proxy(scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner)
    : main_task_runner_(base::MessageLoopProxy::current()),
#if !DCHECK_IS_ON
      impl_task_runner_(impl_task_runner) {
#else
      impl_task_runner_(impl_task_runner),
      main_thread_id_(base::PlatformThread::CurrentId()),
      impl_thread_is_overridden_(false),
      is_main_thread_blocked_(false) {
#endif
}

Proxy::~Proxy() {
  DCHECK(IsMainThread());
}

scoped_ptr<base::Value> Proxy::SchedulerAsValueForTesting() {
  return make_scoped_ptr(base::Value::CreateNullValue());
}

}  // namespace cc