text:
import os
from anima.ui.base import AnimaDialogBase
from anima.ui.lib import QtCore, QtGui, QtWidgets
from anima.ui.utils import create_button, create_separator

__here__ = os.path.abspath(__file__)

def UI(app_in=None, executor=None, **kwargs):
    """
    :param app_in: A Qt Application instance, which you can pass to let the UI
      be attached to the given applications event process.

    :param executor: Instead of calling app.exec_ the UI will call this given
      function. It also passes the created app instance to this executor.

    """
    from anima.ui.base import ui_caller

    return ui_caller(app_in, executor, ToolboxDialog, **kwargs)

class ToolboxDialog(QtWidgets.QDialog, AnimaDialogBase):
    """The toolbox dialog"""

    def __init__(self, environment=None, parent=None):
        super(ToolboxDialog, self).__init__(parent)
        self._setup_ui()

    def _setup_ui(self):
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setModal(True)
        self.resize(300, 300)
        size_policy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred
        )

        size_policy.setHorizontalStretch(1)
        size_policy.setVerticalStretch(1)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setSizeGripEnabled(True)

        self.horizontal_layout = QtWidgets.QHBoxLayout(self)
        self.toolbox_widget = QtWidgets.QWidget(self)
        self.horizontal_layout.addWidget(self.toolbox_widget)

        self.toolbox_layout = ToolboxLayout(self.toolbox_widget)
        self.toolbox_layout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        self.toolbox_layout.setContentsMargins(0, 0, 0, 0)

        # setup icon
        global __here__
        icon_path = os.path.abspath(
            os.path.join(__here__, "../../../ui/images/fusion.png")
        )
        icon = QtGui.QIcon(icon_path)

        self.setWindowIcon(icon)

class ToolboxLayout(QtWidgets.QVBoxLayout):
    """The toolbox"""

    def __init__(self, *args, **kwargs):
        super(ToolboxLayout, self).__init__(*args, **kwargs)
        self._setup_ui()

    def _setup_ui(self):
        """add tools"""
        # create the main tab layout
        main_tab_widget = QtWidgets.QTabWidget(self.widget())
        self.addWidget(main_tab_widget)

        # add the General Tab
        general_tab_widget = QtWidgets.QWidget(self.widget())
        general_tab_vertical_layout = QtWidgets.QVBoxLayout()
        general_tab_vertical_layout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        general_tab_widget.setLayout(general_tab_vertical_layout)

        main_tab_widget.addTab(general_tab_widget, "Generic")

        # Create tools for general tab

        # -------------------------------------------------------------------
        # Open Version
        create_button(
            "Open Version",
            general_tab_vertical_layout,
            GenericTools.version_dialog,
            callback_kwargs={"parent": self.parent(), "mode": 1},
        )

        # Save As Version
        create_button(
            "Save As Version",
            general_tab_vertical_layout,
            GenericTools.version_dialog,
            callback_kwargs={"parent": self.parent(), "mode": 0},
        )

        # Update Outputs
        create_button(
            "Update Savers", general_tab_vertical_layout, GenericTools.update_savers
        )

        # Loader Report
        create_button(
            "Loader Report", general_tab_vertical_layout, GenericTools.loader_report
        )

        # PassThrough All Saver nodes
        create_button(
            "PassThrough All Savers",
            general_tab_vertical_layout,
            GenericTools.pass_through_all_savers,
        )

        # Insert Pipe Router
        create_button(
            "Insert Pipe Router",
            general_tab_vertical_layout,
            GenericTools.insert_pipe_router_to_selected_node,
        )

        # Loader From Saver
        create_button(
            "Loader from Saver",
            general_tab_vertical_layout,
            GenericTools.loader_from_saver,
        )

        # Delete Recent Comps
        create_button(
            "Delete Recent Comps",
            general_tab_vertical_layout,
            GenericTools.delete_recent_comps,
        )

        # Set Frames At Once To 1, 5 and 10
        hbox_layout = QtWidgets.QHBoxLayout()
        general_tab_vertical_layout.addLayout(hbox_layout)
        set_frames_at_once_label = QtWidgets.QLabel()
        set_frames_at_once_label.setText("Set Frames At Once To")
        hbox_layout.addWidget(set_frames_at_once_label)

        for i in [1, 5, 10]:
            button = create_button(
                "%s" % i,
                hbox_layout,
                GenericTools.set_frames_at_once,
                callback_kwargs={"count": i},
            )
            button.setMinimumSize(QtCore.QSize(25, 0))

        general_tab_vertical_layout.addWidget(
            create_separator(general_tab_vertical_layout.parent())
        )

        # Range From Shot
        create_button(
            "Get Comp Range From Database",
            general_tab_vertical_layout,
            GenericTools.range_from_shot,
        )

        # Shot From Range
        create_button(
            "Set Comp Range To Database",
            general_tab_vertical_layout,
            GenericTools.shot_from_range,
        )

        general_tab_vertical_layout.addWidget(
            create_separator(general_tab_vertical_layout.parent())
        )

        # Render Merger
        create_button(
            "Render Merger",
            general_tab_vertical_layout,
            GenericTools.render_merger,
            tooltip="Creates comp setup to merge renders created with Render Slicer.",
        )

        # 3DE4 Lens Distort Node
        import functools

        create_button(
            "3DE4 Lens Distort",
            general_tab_vertical_layout,
            functools.partial(
                GenericTools.tde4_lens_distort_node_creator, self.parent()
            ),
            tooltip=GenericTools.tde4_lens_distort_node_creator.__doc__,
        )

        # 3DE4 Track Point Importer
        import functools

        create_button(
            "3DE4 Import Track Point",
            general_tab_vertical_layout,
            functools.partial(GenericTools.tde4_import_track_point, self.parent()),
            tooltip=GenericTools.tde4_import_track_point.__doc__,
        )

        # Create slate for Current Version
        import functools

        create_button(
            "Create Slate for Current version",
            general_tab_vertical_layout,
            functools.partial(GenericTools.create_slate_for_current_version),
            tooltip=GenericTools.create_slate_for_current_version.__doc__,
        )

        # Cache Node Setup
        create_button(
            "Cache Node Setup",
            general_tab_vertical_layout,
            functools.partial(GenericTools.cache_node_setup),
            tooltip=GenericTools.cache_node_setup.__doc__,
        )

        # -------------------------------------------------------------------
        # Add the stretcher
        general_tab_vertical_layout.addStretch()

class GenericTools(object):
    """Generic Tools"""

    @classmethod
    def version_dialog(cls, **args):
        """version dialog"""
        # from anima.ui.scripts import fusion
        # fusion.version_dialog(*args)
        from anima.utils import do_db_setup

        do_db_setup()
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        fusion_env.name = "Fusion"

        from anima.ui.dialogs import version_dialog

        ui_instance = version_dialog.MainDialog(environment=fusion_env, **args)
        ui_instance.show()
        ui_instance.center_window()

    @classmethod
    def update_savers(cls):
        """updates savers, creates missing ones"""
        from anima.utils import do_db_setup

        do_db_setup()
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        v = fusion_env.get_current_version()
        fusion_env.create_main_saver_node(version=v)

    @classmethod
    def loader_report(cls):
        """returns the loaders in this comp"""
        from anima.dcc import fusion

        fs = fusion.Fusion()
        comp = fs.comp

        paths = []

        all_loader_nodes = comp.GetToolList(False, "Loader").values()
        for loader_node in all_loader_nodes:
            node_input_list = loader_node.GetInputList()
            for input_entry_key in node_input_list.keys():
                input_entry = node_input_list[input_entry_key]
                input_id = input_entry.GetAttrs()["INPS_ID"]
                if input_id == "Clip":
                    # value = node_input_list[input_entry_key]
                    # input_entry[0] = value
                    # break
                    value = input_entry[0]
                    if value != "" or value is not None:
                        paths.append(value)

        for path in sorted(paths):
            print(path)

    @classmethod
    def pass_through_all_savers(cls):
        """disables all saver nodes in the current comp"""
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        comp = fusion_env.comp
        saver_nodes = comp.GetToolList(False, "Saver").values()
        for node in saver_nodes:
            node.SetAttrs({"TOOLB_PassThrough": True})

    @classmethod
    def insert_pipe_router_to_selected_node(cls):
        """inserts a Pipe Router node between the selected node and the nodes
        connected to its output
        """
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        comp = fusion_env.comp

        # get active node
        node = comp.ActiveTool

        # get all node outputs
        output = node.FindMainOutput(1)
        connected_inputs = output.GetConnectedInputs()

        # create pipe router
        pipe_router = comp.PipeRouter({"Input": node})

        # connect it to the other nodes
        for connected_input in connected_inputs.values():
            connected_input.ConnectTo(pipe_router)

    @classmethod
    def update_secondary_savers(cls):
        """Updates Savers which are not a Main Saver node"""
        # get all saver nodes
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        comp = fusion_env.comp

        all_saver_nodes = fusion_env.comp.GetToolList(False, "Saver").values()

        # filter all Main Saver nodes
        main_savers = fusion_env.get_main_saver_node()
        secondary_savers = [node for node in all_saver_nodes if node not in main_savers]

        # get the output path from one of the main savers

    @classmethod
    def loader_from_saver(cls):
        """creates a loader from the selected saver node"""
        from anima.dcc import fusion
        from anima.dcc.fusion.utils import NodeUtils

        fusion_env = fusion.Fusion()
        comp = fusion_env.comp

        node = comp.ActiveTool
        flow = comp.CurrentFrame.FlowView
        x, y = flow.GetPosTable(node).values()

        # instead of lock/unlock disable AutoClipBrowse temporarily
        auto_browse = NodeUtils.disable_auto_clip_browse()

        loader_node = comp.Loader()
        loader_node.Clip[0] = node.Clip[0]
        NodeUtils.set_auto_clip_browse(auto_browse)

        # set position near to the saver node
        flow.SetPos(loader_node, x + 1.0, y)
        flow.Select(node, False)
        flow.Select(loader_node, True)
        comp.SetActiveTool(loader_node)

    @classmethod
    def cache_node_setup(cls):
        """Create a Saver node for the selected node that renders the cache."""
        from anima.dcc import fusion
        from anima.dcc.fusion.utils import NodeUtils

        fusion_env = fusion.Fusion()
        comp = fusion_env.comp
        attributes = comp.GetAttrs()
        flow = comp.CurrentFrame.FlowView
        node = comp.ActiveTool
        node_name = node.GetAttrs("TOOLS_Name")
        first_frame = attributes["COMPN_RenderStartTime"]
        path = (
            "Project:/Comp/Outputs/cache/{node_name}/"
            "{node_name}.{first_frame:04d}.raw".format(
                node_name=node_name, first_frame=int(first_frame)
            )
        )

        auto_browse = NodeUtils.disable_auto_clip_browse()
        # create a loader with the path
        loader_node = comp.Loader()
        loader_node.SetAttrs({"TOOLS_Name": "{}_CacheLoader".format(node_name)})
        loader_node.Clip[0] = path

        # get all node outputs
        output = node.FindMainOutput(1)
        connected_inputs = output.GetConnectedInputs()

        # connect it to the other nodes
        for connected_input in connected_inputs.values():
            connected_input.ConnectTo(loader_node)

        saver_node = comp.Saver({"Input": node})
        saver_node.SetAttrs({"TOOLS_Name": "{}_CacheSaver".format(node_name)})
        saver_node.Clip[0] = path
        flow.Select(saver_node, False)
        comp.SetActiveTool(None)
        NodeUtils.set_auto_clip_browse(auto_browse)

        # place the nodes next to the current node
        x, y = flow.GetPosTable(node).values()
        flow.SetPos(saver_node, x, y + 1.0)
        flow.SetPos(loader_node, x, y + 2.0)
        flow.Select(node, False)
        flow.Select(loader_node, True)
        flow.Select(saver_node, True)
        comp.SetActiveTool(saver_node)

    @classmethod
    def delete_recent_comps(cls):
        """Deletes the Recent Comps value in the current preferences. This was
        created to remedy the low performance bug under Fusion 9 and Windows.
        It is not clear for now what happens under the other OSes.
        """
        import BlackmagicFusion as bmf

        fusion = bmf.scriptapp("Fusion")
        print("Erasing RecentComps value!")
        fusion.SetPrefs("Global.RecentComps", {})
        fusion.SavePrefs()

    @classmethod
    def set_frames_at_once(cls, count=1):
        """Sets the frames at once value to the given number
        :param count:
        :return:
        """
        import BlackmagicFusion as bmf

        fusion = bmf.scriptapp("Fusion")
        comp = fusion.GetCurrentComp()
        comp.SetPrefs("Comp.Memory.FramesAtOnce", count)

    @classmethod
    def afanasy_job_submitter(cls):
        """alpha feature"""
        # call the lua script from /opt/cgru/plugins/fusion/
        pass

    @classmethod
    def range_from_shot(cls):
        """sets the range from the shot"""
        from anima.utils import do_db_setup

        do_db_setup()
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        version = fusion_env.get_current_version()
        fusion_env.set_range_from_shot(version)

    @classmethod
    def shot_from_range(cls):
        """updates the Shot.cut_in and Shot.cut_out attributes from the current range"""
        from anima.utils import do_db_setup

        do_db_setup()
        from anima.dcc import fusion

        fusion_env = fusion.Fusion()
        version = fusion_env.get_current_version()
        try:
            fusion_env.set_shot_from_range(version)
        except BaseException as e:
            QtWidgets.QMessageBox.critical(None, "Error", "%s" % e)
        finally:
            QtWidgets.QMessageBox.information(
                None, "Success", "Shot Range has been updated successfully!"
            )

    @classmethod
    def render_merger(cls):
        """calls the render merger"""
        from anima.dcc.fusion import render_merger

        rm = render_merger.RenderMerger()
        rm.ui()

    @classmethod
    def tde4_lens_distort_node_creator(cls, parent):
        """creates lens distort nodes from the given 3de4 lens file"""
        # show a file browser
        dialog = QtWidgets.QFileDialog(parent, "Choose file")
        dialog.setNameFilter("3DE4 Lens Files (*.txt)")
        dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        if dialog.exec_():
            file_path = dialog.selectedFiles()[0]
            if not file_path:
                return
            from anima.dcc.fusion.utils import TDE4LensDistortionImporter

            lens_importer = TDE4LensDistortionImporter()
            lens_importer.import_(file_path)

    @classmethod
    def tde4_import_track_point(cls, parent):
        """imports 3DE4 track point as a Tracker"""
        # show a file browser
        dialog = QtWidgets.QFileDialog(parent, "Choose file")
        dialog.setNameFilter("3DE4 Track Point (*.txt)")
        dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        if dialog.exec_():
            file_path = dialog.selectedFiles()[0]
            if not file_path:
                return
            from anima.dcc.fusion.utils import TDE4PointImporter

            # use the project x and y resolution
            from anima.dcc import fusion

            f = fusion.Fusion()
            comp = f.comp
            width = comp.GetPrefs("Comp.FrameFormat.Width")
            height = comp.GetPrefs("Comp.FrameFormat.Height")

            lens_importer = TDE4PointImporter(xres=width, yres=height)
            lens_importer.load_points(file_path)

    @classmethod
    def create_slate_for_current_version(cls):
        """creates slate for the current version"""
        from anima.dcc import fusion

        f = fusion.Fusion()
        v = f.get_current_version()
        f.create_slate_node(v)


text:
<?php

namespace Orbas\Stage\Navigation;

class Renderer implements RenderContract
{
    /**
     * @param $item
     * @param $level
     *
     * @return Tag
     */
    public function render($item, $level)
    {
        $attributes = [
            'title' => $item['title']
        ];

        $url = $this->parseUrl($item);
        if ($url) {
            $attributes['url'] = $url;
        }

        return new Tag($this->getTagName($item, $level), null, $attributes);
    }

    /**
     * @param array   $item
     * @param integer $level
     *
     * @return string
     */
    protected function getTagName($item, $level)
    {
        if ($level == 1) {
            return 'classic-menu';
        } elseif ($level >= 2 && !empty($item['subItems'])) {
            return 'dropdown-submenu';
        }

        return 'submenu';
    }

    protected function parseUrl($item)
    {
        if (isset($item['url'])) {
            return $item['url'];
        }

        if (isset($item['route'])) {
            return route($item['route']);
        }

        if (isset($item['action'])) {
            return action($item['action']);
        }

        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
body{
  font-family: monospace;
  text-align: center;
  background: #282828;
  color: #FFF;
}
table{
  margin-left: auto;
  margin-right: auto;
}


text:
import { Expressions } from "../reflector/expressions";
import { Tracker } from "../tracker/tracker";
import { ExpressionEqualityComparer } from "../expression.equality-comparers/expression.equality-comparer";

/**
 * @hidden
 */
export class CallCounter {

    constructor(
        private readonly comparer: ExpressionEqualityComparer,
        private readonly tracker: Tracker) {

    }

    public count<T>(expected: Expressions<T>): number {
        let count = 0;
        for (const expression of this.tracker.interactions()) {
            if (this.comparer.equals(expression, expected) === true) {
                count += 1;
            }
        }

        return count;
    }
}


text:
<dmz>
<dmzLuaModuleBasic>
   <instance name="monster"/>
</dmzLuaModuleBasic>
</dmz>


text:
namespace Rbt.Svr
{
    partial class ProjectInstaller
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            //
            // serviceProcessInstaller1
            //
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            //
            // serviceInstaller1
            //
            this.serviceInstaller1.ServiceName = "微信机器人服务程序";
            //
            // ProjectInstaller
            //
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller1,
            this.serviceInstaller1});

        }

        #endregion

        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller1;
    }
}


text:
const _typeof = 'typeof';
const foo = 1;

var namespace = (Object.freeze || Object)({
	'typeof': _typeof,
	foo: foo
});

console.log( namespace );


text:
from os import path, getcwd
from sys import exit

from openpyxl import Workbook
from openpyxl.styles import colors, Font, Color, Alignment, Border, Side, PatternFill

from optparse import OptionParser
from datetime import datetime

from string import ascii_uppercase

_git_available = False
_hg_available = False
_svn_available = False

try:
    from pygit2 import Repository
    from pygit2 import GIT_SORT_TIME, GIT_DIFF_STATS_FULL
    _git_available = True
except ImportError:
    pass

try:
    import hglib
    _hg_available = True
except ImportError:
    pass

try:
    import svn.local
    _svn_available = True
except ImportError:
    pass

USAGE="""
This script allows to export version history from various Source Control Management
tools to excel spreadsheets (.xlsx). The main purpose is to allow a quick an easy
export for impact analysis."""

class LogEntry:
    def __init__(self):
        self.id = None
        self.msg = None
        self.author = None
        self.email = None
        self.time = None
        self.diff = None

class ScmAccessor:
    def __init__(self, repo_path, start_rev=None):
        self._repo_path = repo_path
        self._scm = None
        self._start_rev  = start_rev

    def get_log(self):
        raise RuntimeError("Not meant to be called in parent class")

class GitAccessor(ScmAccessor):
    def __init__(self, repo_path, start_rev=None):
        super().__init__(repo_path=repo_path, start_rev=start_rev)
        self._scm = Repository(path.join(repo_path))

    def get_log(self):
        data = []

        for c in self._scm.walk(self._scm.head.target, GIT_SORT_TIME):
            print("Processing commit %s" % c.id)

            diff = self._scm.diff(c, c.parents[0]).stats.format(GIT_DIFF_STATS_FULL, 1) if c.parents else ""

            diff = diff.splitlines()
            if len(diff) >= 1:
                diff = diff[:-1]

            stripped_diff = [ d.split("|")[0].strip() for d in diff ]

            e = LogEntry()
            e.id = c.id
            e.msg = c.message.strip("\n")
            e.author = c.committer.name
            e.email = c.committer.email
            e.time = datetime.fromtimestamp(c.commit_time)
            e.diff = stripped_diff
            data.append(e)

            if self._start_rev and c.id.hex == self._start_rev:
                break

        return data

class HgAccessor(ScmAccessor):
    def __init__(self, repo_path, start_rev=None):
        super().__init__(repo_path=repo_path, start_rev=start_rev)
        self._scm = hglib.open(path.join(repo_path))

    def get_log(self):
        data = []

        for c in self._scm.log():
            print("Processing commit %s" % str(c.rev, 'utf-8'))

            diff = self._scm.rawcommand([b'log', b'--stat', b'-r%s' % c.rev]).splitlines()

            commitid = str(diff[0], 'utf-8').lstrip("changeset:").lstrip(" ")
            tag = "" if not c.tags else " - " + str(c.tags, 'utf-8')

            if len(diff[5:-2][0]) == 0:
                diff = diff[1:]

            stripped_diff = [str(d, 'utf-8').split("|")[0].strip() for d in diff[5:-2]]

            e = LogEntry()
            e.id = commitid + tag
            e.msg = str(c.desc, 'utf-8')
            e.author = str(c.author, 'utf-8').split("<")[0]
            e.email = str(c.author, 'utf-8').split("<")[1].rstrip(">")
            e.time = c.date
            e.diff = stripped_diff
            data.append(e)

            if self._start_rev and (str(c.rev, 'utf-8') == self._start_rev or commitid == self._start_rev):
                break

        return data

class SvnAccessor(ScmAccessor):
    def __init__(self, repo_path, start_rev):
        super().__init__(repo_path=repo_path, start_rev=start_rev)
        self._scm = svn.local.LocalClient(path.join(repo_path))

    def get_log(self):
        data = []

        for c in self._scm.log_default():
            print("Processing commit %i" % c.revision)

            try:
                diff = [d['path'].lstrip(str(self._repo_path)) if d['kind'] == 'file' else "" for d in self._scm.diff_summary(c.revision-1, c.revision)]
            except:
                diff = ""

            e = LogEntry()
            e.id = c.revision
            e.msg = c.msg
            e.author = c.author
            e.time = c.date
            e.diff = diff
            data.append(e)

            if self._start_rev and str(c.revision) == self._start_rev:
                break

        return data

class Writer:
    def __init__(self, filename):
        self._filename = filename
        self._workbook = Workbook()
        self._columns = ["Date", "Commit-ID", "Message", "Author", "Changed files"]

        ws = self._workbook.active
        ws.column_dimensions["A"].width = 20
        ws.column_dimensions["B"].width = 20
        ws.column_dimensions["C"].width = 50
        ws.column_dimensions["D"].width = 20
        ws.column_dimensions["E"].width = 25
        ws.column_dimensions["F"].width = 20
        ws.column_dimensions["G"].width = 20
        ws.column_dimensions["H"].width = 20

    def write_header(self):
        ws = self._workbook.active

        ws.append([])
        ws.append(self._columns)

        for c in ascii_uppercase[:len(self._columns)]:
            ws[c+str(ws.max_row)].font = Font(bold=True)
            ws[c+str(ws.max_row)].fill = PatternFill("solid", fgColor="000099ff")
            ws[c+str(ws.max_row)].border = Border(top=Side(border_style="thin", color="00000000"),
                                                  left=Side(border_style="thin", color="00000000"),
                                                  right=Side(border_style="thin", color="00000000"),
                                                  bottom=Side(border_style="thin", color="00000000"))

    def write_data(self):
        raise RuntimeError("Not to be called in base class")

    def write_data(self, accessor):
        ws = self._workbook.active

        for d in accessor.get_log():
            ws.append([d.time.strftime("%Y-%m-%d %H:%M:%S"), str(d.id), str(d.msg), str(d.author), "\n".join(d.diff)])

            for c in ascii_uppercase[:len(self._columns)]:
                ws[c+str(ws.max_row)].alignment = Alignment(vertical="top")

            ws["B"+str(ws.max_row)].font = Font(name="Monospace", size=8)
            ws["C"+str(ws.max_row)].font = Font(size=10)
            ws["C"+str(ws.max_row)].alignment = Alignment(wrap_text=True, shrink_to_fit=True, vertical="top")
            #ws.row_dimensions[ws.max_row].height = d.msg.count("\n") * 15

            for c in ascii_uppercase[:len(self._columns)]:
                ws[c+str(ws.max_row)].border = Border(left=Side(border_style="thin", color="00000000"),
                                                      right=Side(border_style="thin", color="00000000"))

        for c in ascii_uppercase[:len(self._columns)]:
            ws[c+str(ws.max_row)].border = Border(left=Side(border_style="thin", color="00000000"),
                                                  right=Side(border_style="thin", color="00000000"),
                                                  bottom=Side(border_style="thin", color="00000000"))

    def save(self):
        self._workbook.save(self._filename)

class CommitHistoryWriter(Writer):
    def __init__(self, filename):
        super().__init__(filename)

    def write_header(self):
        ws = self._workbook.active
        ws['A1'] = "Commit history"
        ws['B1'] = "Generated on %s" % datetime.now().isoformat(" ")

        super().write_header()

class ImpactStatementWriter(Writer):
    def __init__(self, filename):
        super().__init__(filename=filename)

    def write_header(self):
        ws = self._workbook.active

        ws['A1'] = "Impact statement"
        ws['B1'] = "Generated on %s" % datetime.now().isoformat(" ")
        self._columns.extend(["Affected testcases", "Tested with version"])
        super().write_header()

def main():
    parser = OptionParser(usage=USAGE)

    parser.add_option("-o", "--outfile", dest="outfile",
                      help="Output file to write to.")
    parser.add_option("-s", "--scm", dest="scm",
                      help="SCM to use. Supported options: git, hg, svn",
                      default="git")
    parser.add_option("-I", "--impact", dest="impact",
                      help="If set, an impact statement is generated.",
                      action="store_true")
    parser.add_option("-H", "--history", dest="history",
                      help="If set, the commit history is exported.",
                      action="store_true")
    parser.add_option("-d", "--directory", dest="repo",
                      help="Path to the repository. If omitted, the location "
                            "the script is placed at is used.")
    parser.add_option("-r", "--rev", dest="rev",
                      help="Revision to start. If omitted, the complete history "
                           "is used. Dependent on the SCM used!", default=None)

    options, args = parser.parse_args()

    if not options.history and not options.impact:
        print("Not sure what to do. Impact analysis (-I) or commit history (-H)?")
        exit(-1)

    if not options.outfile:
        print("Output filename missing.")
        exit(-1)

    rpath = options.repo if options.repo else getcwd()
    rev = options.rev

    accessor = None

    if options.scm == "git":
        if not _git_available:
            print("Git support not available. Please install pygit2.")
            sys.exit(-1)
        accessor = GitAccessor(rpath, rev)
    elif options.scm == "hg":
        if not _hg_available:
            print("Mercurial support not available. Please install python-hglib.")
            sys.exit(-1)
        accessor = HgAccessor(rpath, rev)
    elif options.scm == "svn":
        if not _svn_available:
            print("SVN support not available. Please install svn.")
            sys.exit(-1)
        accessor = SvnAccessor(rpath, rev)

    outfile = options.outfile

    if not outfile.endswith(".xlsx"):
        outfile += ".xlsx"

    if options.history:
        print("Generating commit history...")
        writer = CommitHistoryWriter("History-" + outfile)
    elif options.impact:
        print("Generating impact statement...")
        writer = ImpactStatementWriter("Impacts-" + outfile)

    writer.write_header()
    writer.write_data(accessor=accessor)
    writer.save()

    print("...done.")

if __name__ == "__main__":
    main()


text:
using System;
using System.Collections.Generic;
using SystemInteract;
using IPTables.Net.Exceptions;

namespace IPTables.Net.IpUtils.Utils
{
    public class IpRouteController : IpController
    {
        public IpRouteController(ISystemFactory system) : base("route", system)
        {
        }

        protected override bool IsSingle(string key)
        {
            if (key == "onlink" || key == "linkdown" || key == "pervasive" || key == "broadcast" ||
                key == "unreachable" || key == "anycast") return true;
            return base.IsSingle(key);
        }

        public List<IpObject> GetAll(string table = null)
        {
            var r = new List<IpObject>();
            var args = table == null ? new string[0] : new string[] {"table", table};
            var ret = Command("show", args);
            var lines = ret[0].Trim().Split('\n');
            foreach (var line in lines)
            {
                var l = line.Trim();
                IpObject obj;
                try
                {
                    obj = ParseObject(l);
                }
                catch (Exception ex)
                {
                    throw new IpTablesNetException("An exception occured while parsing route: " + line, ex);
                }

                if (obj != null)
                {
                    if (table != "default" && table != "all") obj.Pairs.Add("table", table);
                    r.Add(obj);
                }
            }

            return r;
        }

        public IpObject ParseObject(string str)
        {
            return ParseObject(str, "to");
        }

        protected override IpObject ParseObject(string str, string firstKey, char[] firstTrimChars = null)
        {
            var strs = str.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
            if (strs.Length != 0 && (strs[0] == "local" || strs[0] == "multicast")) return base.ParseObject(str, null);
            return base.ParseObject(str, firstKey, firstTrimChars);
        }

        internal override string[] ExportObject(IpObject obj)
        {
            var ret = new List<string>();
            if (obj.Pairs.ContainsKey("to")) ret.Add(obj.Pairs["to"]);
            foreach (var kv in obj.Pairs)
            {
                if (kv.Key == "to") continue;
                ret.Add(kv.Key);
                ret.Add(kv.Value);
            }

            ret.AddRange(obj.Singles);
            return ret.ToArray();
        }
    }
}


text:
package org.devgateway.toolkit.forms.wicket.components.form;

import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkbox.bootstraptoggle.BootstrapToggle;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkbox.bootstraptoggle.BootstrapToggleConfig;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;

/**
 * @author mpostelnicu
 *
 */
public class CheckBoxToggleBootstrapFormComponent
        extends GenericEnablingBootstrapFormComponent<Boolean, BootstrapToggle> {
    private static final long serialVersionUID = -4032850928243673675L;

    private BootstrapToggleConfig config;

    private CheckBox wrappedCheckbox;

    public CheckBoxToggleBootstrapFormComponent(final String id, final IModel<String> labelModel,
            final IModel<Boolean> model) {
        super(id, labelModel, model);
    }

    /**
     * @param id
     * @param model
     */
    public CheckBoxToggleBootstrapFormComponent(final String id, final IModel<Boolean> model) {
        super(id, model);
    }

    public CheckBoxToggleBootstrapFormComponent(final String id) {
        super(id);
    }

    @Override
    protected FormComponent<Boolean> updatingBehaviorComponent() {
        return wrappedCheckbox;
    }

    @Override
    protected BootstrapToggle inputField(final String id, final IModel<Boolean> model) {

        config = new BootstrapToggleConfig();
        config.withOnStyle(BootstrapToggleConfig.Style.info).withOffStyle(BootstrapToggleConfig.Style.warning)
                .withStyle("customCssClass");

        final BootstrapToggle checkBoxToggle = new BootstrapToggle("field", initFieldModel(), config) {
            @Override
            protected CheckBox newCheckBox(final String id, final IModel<Boolean> model) {
                wrappedCheckbox = super.newCheckBox(id, model);
                wrappedCheckbox.add(new AjaxFormComponentUpdatingBehavior("change") {
                    @Override
                    protected void onUpdate(final AjaxRequestTarget target) {
                        CheckBoxToggleBootstrapFormComponent.this.onUpdate(target);
                    }
                });
                return wrappedCheckbox;
            }

            @Override
            protected IModel<String> getOnLabel() {
                return new StringResourceModel("onLabel", CheckBoxToggleBootstrapFormComponent.this);
            }

            @Override
            protected IModel<String> getOffLabel() {
                return new StringResourceModel("offLabel", CheckBoxToggleBootstrapFormComponent.this);
            }
        };

        return checkBoxToggle;
    }

    @Override
    public String getUpdateEvent() {
        return "change";
    }

    @Override
    protected boolean boundComponentsVisibilityAllowed(final Boolean selectedValue) {
        return selectedValue;
    }

    public BootstrapToggleConfig getConfig() {
        return config;
    }
}


text:
There are three main goals of the Image Manifest Specification.
The first goal is content-addressable images, by supporting an image model where the image's configuration can be hashed to generate a unique ID for the image and its components.
The second goal is to allow multi-architecture images, through a "fat manifest" which references image manifests for platform-specific versions of an image.
The third goal is to be translatable to the [OpenContainers/runtime-spec](https://github.com/opencontainers/runtime-spec)

# Manifest List

The manifest list is the "fat manifest" which points to specific image manifests for one or more platforms.
While the use of a manifest list is OPTIONAL for image providers, image consumers SHOULD be prepared to process them.
A client will distinguish a manifest list from an image manifest based on the Content-Type returned in the HTTP response.

## *Manifest List* Property Descriptions

- **`schemaVersion`** *int*

  This REQUIRED property specifies the image manifest schema version.
  For this version of the specification, this MUST be `2` to ensure backward compatibility with older versions of Docker. The value of this field will not change. This field MAY be removed in a future version of the specification.

- **`mediaType`** *string*

  This REQUIRED property contains the media type of the manifest list.
  For this version of the specification, this MUST be set to `application/vnd.oci.image.manifest.list.v1+json`.
  For the media type(s) that this is compatible with see the [matrix](media-types.md#compatibility-matrix).

- **`manifests`** *array*

  This REQUIRED property contains a list of manifests for specific platforms.
  While the property MUST be present, the size of the array MAY be zero.

  Each object in the manifest is a [descriptor](descriptor.md) with the following additional properties:

  - **`platform`** *object*

    This REQUIRED property describes the platform which the image in the manifest runs on.
    A full list of valid operating system and architecture values are listed in the [Go language documentation for `$GOOS` and `$GOARCH`](https://golang.org/doc/install/source#environment)

    - **`architecture`** *string*

        This REQUIRED property specified the CPU architecture, for example `amd64` or `ppc64le`.

    - **`os`** *string*

        This REQUIRED property specifies the operating system, for example `linux` or `windows`.

    - **`os.version`** *string*

        This OPTIONAL property specifies the operating system version, for example `10.0.10586`.

    - **`os.features`** *array*

        This OPTIONAL property specifies an array of strings, each specifying a mandatory OS feature (for example on Windows `win32k`).

    - **`variant`** *string*

        This OPTIONAL property specifies the variant of the CPU, for example `armv6l` to specify a particular CPU variant of the ARM CPU.

    - **`features`** *array*

        This OPTIONAL property specifies an array of strings, each specifying a mandatory CPU feature (for example `sse4` or `aes`).

- **`annotations`** *string-string hashmap*

    This OPTIONAL property contains arbitrary metadata for the manifest list.
    Annotations is a key-value, unordered hashmap.
    Keys are unique, and best practice is to namespace the keys.
    Common annotation keys include:
    * **created** date on which the image was built (string, timestamps type)
    * **authors** contact details of the people or organization responsible for the image (freeform string)
    * **homepage** URL to find more information on the image (string, must be a URL with scheme HTTP or HTTPS)
    * **documentation** URL to get documentation on the image (string, must be a URL with scheme HTTP or HTTPS)

## Example Manifest List

*Example showing a simple manifest list pointing to image manifests for two platforms:*
```json,title=Manifest%20List&mediatype=application/vnd.oci.image.manifest.list.v1%2Bjson
{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.manifest.list.v1+json",
  "manifests": [
    {
      "mediaType": "application/vnd.oci.image.manifest.v1+json",
      "size": 7143,
      "digest": "sha256:e692418e4cbaf90ca69d05a66403747baa33ee08806650b51fab815ad7fc331f",
      "platform": {
        "architecture": "ppc64le",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.oci.image.manifest.v1+json",
      "size": 7682,
      "digest": "sha256:5b0bcabd1ed22e9fb1310cf6c2dec7cdef19f0ad69efa1f392e94a4333501270",
      "platform": {
        "architecture": "amd64",
        "os": "linux",
        "features": [
          "sse4"
        ]
      }
    }
  ],
  "annotations": {
    "key1": "value1",
    "key2": "value2"
  }
}
```

# Image Manifest

Unlike the [Manifest List](#manifest-list), which contains information about a set of images that can span a variety of architectures and operating systems, an image manifest provides a configuration and set of layers for a single container image for a specific architecture and operating system.

## *Image Manifest* Property Descriptions

- **`schemaVersion`** *int*

  This REQUIRED property specifies the image manifest schema version.
  For this version of the specification, this MUST be `2` to ensure backward compatibility with older versions of Docker. The value of this field will not change. This field MAY be removed in a future version of the specification.

- **`mediaType`** *string*

    This REQUIRED property contains the media type of the image manifest.
    For this version of the specification, this MUST be set to `application/vnd.oci.image.manifest.v1+json`.
    For the media type(s) that this is compatible with see the [matrix](media-types.md#compatibility-matrix).

- **`config`** *[descriptor](descriptor.md)*

    This REQUIRED property references a configuration object for a container, by digest.
    The referenced configuration object is a JSON blob that the runtime uses to set up the container, see [Image JSON Description](serialization.md#image-json-description).

- **`layers`** *array*

    Each item in the array MUST be a [descriptor](descriptor.md).
    The array MUST have the base image at index 0.
    Subsequent layers MUST then follow in the order in which they are to be layered on top of each other.
    The algorithm to create the final unpacked filesystem layout MUST be to first unpack the layer at index 0, then index 1, and so on.

- **`annotations`** *hashmap*

    This OPTIONAL property contains arbitrary metadata for the manifest list.
    Annotations is a key-value, unordered hashmap.
    Keys MUST be unique within the hashmap, and best practice is to namespace the keys.
    Common annotation keys include:
    * **created** date on which the image was built (string, timestamps type)
    * **authors** contact details of the people or organization responsible for the image (freeform string)
    * **homepage** URL to find more information on the image (string, must be a URL with scheme HTTP or HTTPS)
    * **documentation** URL to get documentation on the image (string, must be a URL with scheme HTTP or HTTPS)
    * **source** URL to get the source code for the binary files in the image (string, must be a URL with scheme HTTP or HTTPS)

## Example Image Manifest

*Example showing an image manifest:*
```json,title=Manifest&mediatype=application/vnd.oci.image.manifest.v1%2Bjson
{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.manifest.v1+json",
  "config": {
    "mediaType": "application/vnd.oci.image.config.v1+json",
    "size": 7023,
    "digest": "sha256:b5b2b2c507a0944348e0303114d8d93aaaa081732b86451d9bce1f432a537bc7"
  },
  "layers": [
    {
      "mediaType": "application/vnd.oci.image.layer.tar+gzip",
      "size": 32654,
      "digest": "sha256:e692418e4cbaf90ca69d05a66403747baa33ee08806650b51fab815ad7fc331f"
    },
    {
      "mediaType": "application/vnd.oci.image.layer.tar+gzip",
      "size": 16724,
      "digest": "sha256:3c3a4604a545cdc127456d94e421cd355bca5b528f4a9c1905b15da2eb4a4c6b"
    },
    {
      "mediaType": "application/vnd.oci.image.layer.tar+gzip",
      "size": 73109,
      "digest": "sha256:ec4b8955958665577945c89419d1af06b5f7636b4ac3da7f12184802ad867736"
    }
  ],
  "annotations": {
    "key1": "value1",
    "key2": "value2"
  }
}
```


text:
layout: page
title: Andrews 40th Anniversary
date: 2016-05-24
author: Teresa Johnson
tags: weekly links, java
status: published
summary: Aenean dolor purus, eleifend vitae consequat ac, tempus.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 07/01/2016
  endDate: 07/04/2016
  ctyhocn: SLWHSHX
  groupCode: A4A
published: true
---
Ut lacus nulla, aliquam eget mauris nec, ultrices imperdiet libero. Nullam non lacus sit amet nulla dignissim porttitor eget quis arcu. Donec ut lacinia risus. Nunc sit amet orci arcu. Pellentesque at odio velit. Nullam laoreet tellus ac tincidunt sodales. Pellentesque eros risus, cursus in quam ac, porta auctor elit. In molestie vitae tortor a placerat. Proin fringilla id nisl nec accumsan. Nam ac maximus libero, non volutpat mi.

* Duis malesuada libero at augue tempor, a dictum arcu pharetra
* Sed imperdiet massa in tempus auctor.

Nunc condimentum augue vel facilisis ornare. Duis eget sapien non tellus placerat bibendum. Mauris lectus enim, iaculis eu placerat in, pretium sit amet nisi. Nulla id aliquet tellus. Proin et nunc dignissim, rhoncus ipsum quis, fringilla urna. Etiam at leo ante. Suspendisse velit quam, volutpat vel vestibulum eget, commodo imperdiet diam. Mauris sodales diam eu purus luctus fermentum. Sed eu est et erat tempor pulvinar. Integer lobortis bibendum accumsan. Maecenas sit amet eros sit amet erat malesuada fermentum eget semper orci. Maecenas sodales odio in auctor consectetur. Integer iaculis nisl vitae arcu tempor, eu bibendum lacus pellentesque. Aliquam blandit risus nibh, id efficitur turpis sagittis vitae. Sed lobortis magna vel ligula consectetur eleifend.


text:
cask 'superproductivity' do
  version '2.6.3'
  sha256 '0d0cbe40a8b2d93b64584aac6f07a7c3c34a1b82d60519ed24e17616f945f365'

  # github.com/johannesjo/super-productivity was verified as official when first introduced to the cask
  url "https://github.com/johannesjo/super-productivity/releases/download/v#{version}/superProductivity-#{version}-mac.zip"
  appcast 'https://github.com/johannesjo/super-productivity/releases.atom'
  name 'Super Productivity'
  homepage 'https://super-productivity.com/'

  app 'superProductivity.app'
end


text:
#pragma once
#include "Worker.h"
class SavePcdASCIIWorker : public Worker
{
	Q_OBJECT

private:
	QString _filename;

public:
	SavePcdASCIIWorker() : Worker()
	{
		_save_rgb = false;
	}
	void saveascii()
	{
		QMetaObject::invokeMethod(this, "doWork");
	}
	void setFileName(QString name)
	{
		_filename = name;
	}
	QString getFileName()
	{
		return _filename;
	}
	virtual bool is_para_satisfying(QString &message);
	virtual void prepare();

public slots:
	void doWork();

private:
	bool _save_rgb;
public:
	void setSaveRGBMode(bool mode)
	{
		_save_rgb = mode;
	}
	bool getSaveRGBMode()
	{
		return _save_rgb;
	}
};


text:
'use strict';

module.exports = new function() {

    var _ = require('lodash'),
        chalk = require('chalk'),
        args = require('yargs').argv,
        fs = require('fs'),
        path = require('path'),

        pattern = {};

    /**
     * Kick off loading and adding to gulp
     * both the tasks and workflows.
     * Add custom gulp task.
     */

    pattern.setup = function(gulp, args, appConfig, patternConfig) {
        var tasksAdded = pattern.addTasks(gulp, args, appConfig);
        var workflowsAdded = pattern.addWorkflows(gulp, args, appConfig);
        _addListTask(gulp, tasksAdded, workflowsAdded, patternConfig);
    };

    /**
     * Search for any tasks in the
     * recommended directory './gulp/tasks'
     * with the extensions '.tsk.js' and
     * run each one to add to gulp.
     */

    pattern.addTasks = function(gulp, args, appConfig) {
        var root = process.cwd();
        var tasks = fs.readdirSync(root + '/gulp/tasks/');
        _.each(tasks, function(task) {
            var taskBreakdown = task.split('.');
            if (taskBreakdown[1] === 'tsk') {
                var taskName = taskBreakdown[0] + '.' + taskBreakdown[1];
                require
                    (root + '/gulp/tasks/' + taskName)
                    (gulp, args, appConfig);
            }
        });
        return _.cloneDeep(gulp.tasks);
    };

    /**
     * Search for any workflows in the
     * recommended directory './gulp/workflows'
     * with the extensions '.wflow.js' and
     * run each one to add to gulp.
     */

    pattern.addWorkflows = function(gulp, args, appConfig) {
        var root = process.cwd();
        var workflows = fs.readdirSync(root + '/gulp/workflows/');
        _.each(workflows, function(workflow) {
            var workflowBreakdown = workflow.split('.');
            if (workflowBreakdown[1] === 'wflow') {
                var workflowName = workflowBreakdown[0] + '.' + workflowBreakdown[1];
                require
                    (root + '/gulp/workflows/' + workflowName)
                    (gulp, args, appConfig);
            }
        });
        return _.cloneDeep(gulp.tasks);
    };

    /**
     * Add the `list` gulp tasks, which
     * prints out a help menu, listing out
     * all the tasks and workflows, categorised.
     * The task also accepts flags to specify
     * either listing just tasks (-t) or just
     * the workflows (-w)
     *
     * @private
     */

    var _addListTask = function(gulp, tasks, workflows, patternConfig) {

        gulp.task('list', function() {

            var printTasks = true,
                printWorkflows = true;

            if (args.t) {
                printWorkflows = false;
            } else if (args.w) {
                printTasks = false;
            }

            if (printTasks) {

                console.log('');
                console.log('');
                console.log(chalk.blue.bold('list of tasks:'));
                console.log(chalk.blue.bold('--------------\n'));

                var allTasks = Object.keys(tasks).sort();

                if (patternConfig && patternConfig.tasks && patternConfig.tasks.ignore.length > 0) {
                    allTasks = allTasks.filter(function(task) {
                        return patternConfig.tasks.ignore.indexOf(task) === -1;
                    });
                }

                _.each(allTasks, function(name) {
                    console.log(chalk.yellow.bold(name));
                    if (tasks[name].help) {
                        console.log('  ' + chalk.gray(tasks[name].help.message));
                    }
                });
            }

            if (printWorkflows) {

                console.log('');
                console.log('');
                console.log(chalk.blue.bold('list of workflows:'));
                console.log(chalk.blue.bold('------------------\n'));

                var workflowNames = _.xor(Object.keys(workflows), Object.keys(tasks));
                _.each(workflowNames.sort(), function(name) {
                    console.log(chalk.yellow.bold(name));
                    console.log(chalk.gray(workflows[name].help.message));

                    if (workflows[name].dep.length > 0) {
                        var end,
                            deps = ' ';

                        _.each(workflows[name].dep, function(dep, i) {
                            end = (workflows[name].dep.length === (i + 1)) ? '.' : ', ';
                            deps = deps + dep + end;
                        });

                        console.log(chalk.white.bold('- tasks run:') + chalk.gray(deps));
                    }

                    console.log('\n');
                });
            }

            console.log('');
            console.log('');
            return gulp;
        });
    };

    return pattern;
};


text:
package org.ovirt.engine.core.utils.ovf.xml;

import org.w3c.dom.Node;

public class XmlAttribute extends XmlNode {

    public XmlAttribute(Node node) {
        super(node);
    }

    public String getValue() {
        return node.getTextContent();
    }
}


text:
namespace v8 {
namespace internal {

CompilationInfo::CompilationInfo(Handle<Script> script)
    : isolate_(script->GetIsolate()),
      flags_(LanguageModeField::encode(CLASSIC_MODE)),
      function_(NULL),
      scope_(NULL),
      global_scope_(NULL),
      script_(script),
      extension_(NULL),
      pre_parse_data_(NULL),
      osr_ast_id_(AstNode::kNoNumber) {
  Initialize(NONOPT);
}

CompilationInfo::CompilationInfo(Handle<SharedFunctionInfo> shared_info)
    : isolate_(shared_info->GetIsolate()),
      flags_(LanguageModeField::encode(CLASSIC_MODE) |
             IsLazy::encode(true)),
      function_(NULL),
      scope_(NULL),
      global_scope_(NULL),
      shared_info_(shared_info),
      script_(Handle<Script>(Script::cast(shared_info->script()))),
      extension_(NULL),
      pre_parse_data_(NULL),
      osr_ast_id_(AstNode::kNoNumber) {
  Initialize(BASE);
}

CompilationInfo::CompilationInfo(Handle<JSFunction> closure)
    : isolate_(closure->GetIsolate()),
      flags_(LanguageModeField::encode(CLASSIC_MODE) |
             IsLazy::encode(true)),
      function_(NULL),
      scope_(NULL),
      global_scope_(NULL),
      closure_(closure),
      shared_info_(Handle<SharedFunctionInfo>(closure->shared())),
      script_(Handle<Script>(Script::cast(shared_info_->script()))),
      extension_(NULL),
      pre_parse_data_(NULL),
      osr_ast_id_(AstNode::kNoNumber) {
  Initialize(BASE);
}

// Disable optimization for the rest of the compilation pipeline.
void CompilationInfo::DisableOptimization() {
  bool is_optimizable_closure =
    FLAG_optimize_closures &&
    closure_.is_null() &&
    !scope_->HasTrivialOuterContext() &&
    !scope_->outer_scope_calls_non_strict_eval() &&
    !scope_->inside_with();
  SetMode(is_optimizable_closure ? BASE : NONOPT);
}

void CompilationInfo::AbortOptimization() {
  Handle<Code> code(shared_info()->code());
  SetCode(code);
}

// Determine whether to use the full compiler for all code. If the flag
// --always-full-compiler is specified this is the case. For the virtual frame
// based compiler the full compiler is also used if a debugger is connected, as
// the code from the full compiler supports mode precise break points. For the
// crankshaft adaptive compiler debugging the optimized code is not possible at
// all. However crankshaft support recompilation of functions, so in this case
// the full compiler need not be be used if a debugger is attached, but only if
// break points has actually been set.
static bool is_debugging_active() {
#ifdef ENABLE_DEBUGGER_SUPPORT
  Isolate* isolate = Isolate::Current();
  return V8::UseCrankshaft() ?
    isolate->debug()->has_break_points() :
    isolate->debugger()->IsDebuggerActive();
#else
  return false;
#endif
}

static bool AlwaysFullCompiler() {
  return FLAG_always_full_compiler || is_debugging_active();
}

static void FinishOptimization(Handle<JSFunction> function, int64_t start) {
  int opt_count = function->shared()->opt_count();
  function->shared()->set_opt_count(opt_count + 1);
  double ms = static_cast<double>(OS::Ticks() - start) / 1000;
  if (FLAG_trace_opt) {
    PrintF("[optimizing: ");
    function->PrintName();
    PrintF(" / %" V8PRIxPTR, reinterpret_cast<intptr_t>(*function));
    PrintF(" - took %0.3f ms]\n", ms);
  }
  if (FLAG_trace_opt_stats) {
    static double compilation_time = 0.0;
    static int compiled_functions = 0;
    static int code_size = 0;

    compilation_time += ms;
    compiled_functions++;
    code_size += function->shared()->SourceSize();
    PrintF("Compiled: %d functions with %d byte source size in %fms.\n",
           compiled_functions,
           code_size,
           compilation_time);
  }
}

static bool MakeCrankshaftCode(CompilationInfo* info) {
  // Test if we can optimize this function when asked to. We can only
  // do this after the scopes are computed.
  if (!info->AllowOptimize()) {
    info->DisableOptimization();
  } else if (info->IsOptimizable()) {
    info->EnableDeoptimizationSupport();
  }

  // In case we are not optimizing simply return the code from
  // the full code generator.
  if (!info->IsOptimizing()) {
    return FullCodeGenerator::MakeCode(info);
  }

  // We should never arrive here if there is not code object on the
  // shared function object.
  Handle<Code> code(info->shared_info()->code());
  ASSERT(code->kind() == Code::FUNCTION);

  // We should never arrive here if optimization has been disabled on the
  // shared function info.
  ASSERT(!info->shared_info()->optimization_disabled());

  // Fall back to using the full code generator if it's not possible
  // to use the Hydrogen-based optimizing compiler. We already have
  // generated code for this from the shared function object.
  if (AlwaysFullCompiler() || !FLAG_use_hydrogen) {
    info->SetCode(code);
    return true;
  }

  // Limit the number of times we re-compile a functions with
  // the optimizing compiler.
  const int kMaxOptCount =
      FLAG_deopt_every_n_times == 0 ? Compiler::kDefaultMaxOptCount : 1000;
  if (info->shared_info()->opt_count() > kMaxOptCount) {
    info->AbortOptimization();
    Handle<JSFunction> closure = info->closure();
    info->shared_info()->DisableOptimization(*closure);
    // True indicates the compilation pipeline is still going, not
    // necessarily that we optimized the code.
    return true;
  }

  // Due to an encoding limit on LUnallocated operands in the Lithium
  // language, we cannot optimize functions with too many formal parameters
  // or perform on-stack replacement for function with too many
  // stack-allocated local variables.
  //
  // The encoding is as a signed value, with parameters and receiver using
  // the negative indices and locals the non-negative ones.
  const int parameter_limit = -LUnallocated::kMinFixedIndex;
  const int locals_limit = LUnallocated::kMaxFixedIndex;
  Scope* scope = info->scope();
  if ((scope->num_parameters() + 1) > parameter_limit ||
      (info->osr_ast_id() != AstNode::kNoNumber &&
       scope->num_parameters() + 1 + scope->num_stack_slots() > locals_limit)) {
    info->AbortOptimization();
    Handle<JSFunction> closure = info->closure();
    info->shared_info()->DisableOptimization(*closure);
    // True indicates the compilation pipeline is still going, not
    // necessarily that we optimized the code.
    return true;
  }

  // Take --hydrogen-filter into account.
  Vector<const char> filter = CStrVector(FLAG_hydrogen_filter);
  Handle<String> name = info->function()->debug_name();
  bool match = filter.is_empty() || name->IsEqualTo(filter);
  if (!match) {
    info->SetCode(code);
    return true;
  }

  // Recompile the unoptimized version of the code if the current version
  // doesn't have deoptimization support. Alternatively, we may decide to
  // run the full code generator to get a baseline for the compile-time
  // performance of the hydrogen-based compiler.
  int64_t start = OS::Ticks();
  bool should_recompile = !info->shared_info()->has_deoptimization_support();
  if (should_recompile || FLAG_hydrogen_stats) {
    HPhase phase(HPhase::kFullCodeGen);
    CompilationInfo unoptimized(info->shared_info());
    // Note that we use the same AST that we will use for generating the
    // optimized code.
    unoptimized.SetFunction(info->function());
    unoptimized.SetScope(info->scope());
    if (should_recompile) unoptimized.EnableDeoptimizationSupport();
    bool succeeded = FullCodeGenerator::MakeCode(&unoptimized);
    if (should_recompile) {
      if (!succeeded) return false;
      Handle<SharedFunctionInfo> shared = info->shared_info();
      shared->EnableDeoptimizationSupport(*unoptimized.code());
      // The existing unoptimized code was replaced with the new one.
      Compiler::RecordFunctionCompilation(
          Logger::LAZY_COMPILE_TAG, &unoptimized, shared);
    }
  }

  // Check that the unoptimized, shared code is ready for
  // optimizations.  When using the always_opt flag we disregard the
  // optimizable marker in the code object and optimize anyway. This
  // is safe as long as the unoptimized code has deoptimization
  // support.
  ASSERT(FLAG_always_opt || code->optimizable());
  ASSERT(info->shared_info()->has_deoptimization_support());

  if (FLAG_trace_hydrogen) {
    PrintF("-----------------------------------------------------------\n");
    PrintF("Compiling method %s using hydrogen\n", *name->ToCString());
    HTracer::Instance()->TraceCompilation(info->function());
  }

  Handle<Context> global_context(info->closure()->context()->global_context());
  TypeFeedbackOracle oracle(code, global_context, info->isolate());
  HGraphBuilder builder(info, &oracle);
  HPhase phase(HPhase::kTotal);
  HGraph* graph = builder.CreateGraph();
  if (info->isolate()->has_pending_exception()) {
    info->SetCode(Handle<Code>::null());
    return false;
  }

  if (graph != NULL && FLAG_build_lithium) {
    Handle<Code> optimized_code = graph->Compile(info);
    if (!optimized_code.is_null()) {
      info->SetCode(optimized_code);
      FinishOptimization(info->closure(), start);
      return true;
    }
  }

  // Keep using the shared code.
  info->AbortOptimization();
  if (!builder.inline_bailout()) {
    // Mark the shared code as unoptimizable unless it was an inlined
    // function that bailed out.
    Handle<JSFunction> closure = info->closure();
    info->shared_info()->DisableOptimization(*closure);
  }
  // True indicates the compilation pipeline is still going, not necessarily
  // that we optimized the code.
  return true;
}

static bool GenerateCode(CompilationInfo* info) {
  return info->IsCompilingForDebugging() || !V8::UseCrankshaft() ?
      FullCodeGenerator::MakeCode(info) :
      MakeCrankshaftCode(info);
}

static bool MakeCode(CompilationInfo* info) {
  // Precondition: code has been parsed.  Postcondition: the code field in
  // the compilation info is set if compilation succeeded.
  ASSERT(info->function() != NULL);
  return Rewriter::Rewrite(info) && Scope::Analyze(info) && GenerateCode(info);
}

#ifdef ENABLE_DEBUGGER_SUPPORT
bool Compiler::MakeCodeForLiveEdit(CompilationInfo* info) {
  // Precondition: code has been parsed.  Postcondition: the code field in
  // the compilation info is set if compilation succeeded.
  bool succeeded = MakeCode(info);
  if (!info->shared_info().is_null()) {
    Handle<ScopeInfo> scope_info = ScopeInfo::Create(info->scope());
    info->shared_info()->set_scope_info(*scope_info);
  }
  return succeeded;
}
#endif

static Handle<SharedFunctionInfo> MakeFunctionInfo(CompilationInfo* info) {
  Isolate* isolate = info->isolate();
  ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
  PostponeInterruptsScope postpone(isolate);

  ASSERT(!isolate->global_context().is_null());
  Handle<Script> script = info->script();
  script->set_context_data((*isolate->global_context())->data());

#ifdef ENABLE_DEBUGGER_SUPPORT
  if (info->is_eval()) {
    Script::CompilationType compilation_type = Script::COMPILATION_TYPE_EVAL;
    script->set_compilation_type(Smi::FromInt(compilation_type));
    // For eval scripts add information on the function from which eval was
    // called.
    if (info->is_eval()) {
      StackTraceFrameIterator it(isolate);
      if (!it.done()) {
        script->set_eval_from_shared(
            JSFunction::cast(it.frame()->function())->shared());
        Code* code = it.frame()->LookupCode();
        int offset = static_cast<int>(
            it.frame()->pc() - code->instruction_start());
        script->set_eval_from_instructions_offset(Smi::FromInt(offset));
      }
    }
  }

  // Notify debugger
  isolate->debugger()->OnBeforeCompile(script);
#endif

  // Only allow non-global compiles for eval.
  ASSERT(info->is_eval() || info->is_global());
  ParsingFlags flags = kNoParsingFlags;
  if (info->pre_parse_data() != NULL ||
      String::cast(script->source())->length() > FLAG_min_preparse_length) {
    flags = kAllowLazy;
  }
  if (!ParserApi::Parse(info, flags)) {
    return Handle<SharedFunctionInfo>::null();
  }

  // Measure how long it takes to do the compilation; only take the
  // rest of the function into account to avoid overlap with the
  // parsing statistics.
  HistogramTimer* rate = info->is_eval()
      ? info->isolate()->counters()->compile_eval()
      : info->isolate()->counters()->compile();
  HistogramTimerScope timer(rate);

  // Compile the code.
  FunctionLiteral* lit = info->function();
  LiveEditFunctionTracker live_edit_tracker(isolate, lit);
  if (!MakeCode(info)) {
    if (!isolate->has_pending_exception()) isolate->StackOverflow();
    return Handle<SharedFunctionInfo>::null();
  }

  // Allocate function.
  ASSERT(!info->code().is_null());
  Handle<SharedFunctionInfo> result =
      isolate->factory()->NewSharedFunctionInfo(
          lit->name(),
          lit->materialized_literal_count(),
          info->code(),
          ScopeInfo::Create(info->scope()));

  ASSERT_EQ(RelocInfo::kNoPosition, lit->function_token_position());
  Compiler::SetFunctionInfo(result, lit, true, script);

  if (script->name()->IsString()) {
    PROFILE(isolate, CodeCreateEvent(
        info->is_eval()
            ? Logger::EVAL_TAG
            : Logger::ToNativeByScript(Logger::SCRIPT_TAG, *script),
        *info->code(),
        *result,
        String::cast(script->name())));
    GDBJIT(AddCode(Handle<String>(String::cast(script->name())),
                   script,
                   info->code(),
                   info));
  } else {
    PROFILE(isolate, CodeCreateEvent(
        info->is_eval()
            ? Logger::EVAL_TAG
            : Logger::ToNativeByScript(Logger::SCRIPT_TAG, *script),
        *info->code(),
        *result,
        isolate->heap()->empty_string()));
    GDBJIT(AddCode(Handle<String>(), script, info->code(), info));
  }

  // Hint to the runtime system used when allocating space for initial
  // property space by setting the expected number of properties for
  // the instances of the function.
  SetExpectedNofPropertiesFromEstimate(result, lit->expected_property_count());

#ifdef ENABLE_DEBUGGER_SUPPORT
  // Notify debugger
  isolate->debugger()->OnAfterCompile(
      script, Debugger::NO_AFTER_COMPILE_FLAGS);
#endif

  live_edit_tracker.RecordFunctionInfo(result, lit);

  return result;
}

Handle<SharedFunctionInfo> Compiler::Compile(Handle<String> source,
                                             Handle<Object> script_name,
                                             int line_offset,
                                             int column_offset,
                                             v8::Extension* extension,
                                             ScriptDataImpl* pre_data,
                                             Handle<Object> script_data,
                                             NativesFlag natives) {
  Isolate* isolate = source->GetIsolate();
  int source_length = source->length();
  isolate->counters()->total_load_size()->Increment(source_length);
  isolate->counters()->total_compile_size()->Increment(source_length);

  // The VM is in the COMPILER state until exiting this function.
  VMState state(isolate, COMPILER);

  CompilationCache* compilation_cache = isolate->compilation_cache();

  // Do a lookup in the compilation cache but not for extensions.
  Handle<SharedFunctionInfo> result;
  if (extension == NULL) {
    result = compilation_cache->LookupScript(source,
                                             script_name,
                                             line_offset,
                                             column_offset);
  }

  if (result.is_null()) {
    // No cache entry found. Do pre-parsing, if it makes sense, and compile
    // the script.
    // Building preparse data that is only used immediately after is only a
    // saving if we might skip building the AST for lazily compiled functions.
    // I.e., preparse data isn't relevant when the lazy flag is off, and
    // for small sources, odds are that there aren't many functions
    // that would be compiled lazily anyway, so we skip the preparse step
    // in that case too.
    int flags = kNoParsingFlags;
    if ((natives == NATIVES_CODE) || FLAG_allow_natives_syntax) {
      flags |= kAllowNativesSyntax;
    }
    if (natives != NATIVES_CODE && FLAG_harmony_scoping) {
      flags |= EXTENDED_MODE;
    }

    // Create a script object describing the script to be compiled.
    Handle<Script> script = FACTORY->NewScript(source);
    if (natives == NATIVES_CODE) {
      script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
    }
    if (!script_name.is_null()) {
      script->set_name(*script_name);
      script->set_line_offset(Smi::FromInt(line_offset));
      script->set_column_offset(Smi::FromInt(column_offset));
    }

    script->set_data(script_data.is_null() ? HEAP->undefined_value()
                                           : *script_data);

    // Compile the function and add it to the cache.
    CompilationInfo info(script);
    info.MarkAsGlobal();
    info.SetExtension(extension);
    info.SetPreParseData(pre_data);
    result = MakeFunctionInfo(&info);
    if (extension == NULL && !result.is_null()) {
      compilation_cache->PutScript(source, result);
    }
  }

  if (result.is_null()) isolate->ReportPendingMessages();
  return result;
}

Handle<SharedFunctionInfo> Compiler::CompileEval(Handle<String> source,
                                                 Handle<Context> context,
                                                 bool is_global,
                                                 LanguageMode language_mode,
                                                 int scope_position) {
  Isolate* isolate = source->GetIsolate();
  int source_length = source->length();
  isolate->counters()->total_eval_size()->Increment(source_length);
  isolate->counters()->total_compile_size()->Increment(source_length);

  // The VM is in the COMPILER state until exiting this function.
  VMState state(isolate, COMPILER);

  // Do a lookup in the compilation cache; if the entry is not there, invoke
  // the compiler and add the result to the cache.
  Handle<SharedFunctionInfo> result;
  CompilationCache* compilation_cache = isolate->compilation_cache();
  result = compilation_cache->LookupEval(source,
                                         context,
                                         is_global,
                                         language_mode,
                                         scope_position);

  if (result.is_null()) {
    // Create a script object describing the script to be compiled.
    Handle<Script> script = isolate->factory()->NewScript(source);
    CompilationInfo info(script);
    info.MarkAsEval();
    if (is_global) info.MarkAsGlobal();
    info.SetLanguageMode(language_mode);
    info.SetCallingContext(context);
    result = MakeFunctionInfo(&info);
    if (!result.is_null()) {
      // If caller is strict mode, the result must be in strict mode or
      // extended mode as well, but not the other way around. Consider:
      // eval("'use strict'; ...");
      ASSERT(language_mode != STRICT_MODE || !result->is_classic_mode());
      // If caller is in extended mode, the result must also be in
      // extended mode.
      ASSERT(language_mode != EXTENDED_MODE ||
             result->is_extended_mode());
      compilation_cache->PutEval(
          source, context, is_global, result, scope_position);
    }
  }

  return result;
}

bool Compiler::CompileLazy(CompilationInfo* info) {
  Isolate* isolate = info->isolate();

  ZoneScope zone_scope(isolate, DELETE_ON_EXIT);

  // The VM is in the COMPILER state until exiting this function.
  VMState state(isolate, COMPILER);

  PostponeInterruptsScope postpone(isolate);

  Handle<SharedFunctionInfo> shared = info->shared_info();
  int compiled_size = shared->end_position() - shared->start_position();
  isolate->counters()->total_compile_size()->Increment(compiled_size);

  // Generate the AST for the lazily compiled function.
  if (ParserApi::Parse(info, kNoParsingFlags)) {
    // Measure how long it takes to do the lazy compilation; only take the
    // rest of the function into account to avoid overlap with the lazy
    // parsing statistics.
    HistogramTimerScope timer(isolate->counters()->compile_lazy());

    // After parsing we know the function's language mode. Remember it.
    LanguageMode language_mode = info->function()->language_mode();
    info->SetLanguageMode(language_mode);
    shared->set_language_mode(language_mode);

    // Compile the code.
    if (!MakeCode(info)) {
      if (!isolate->has_pending_exception()) {
        isolate->StackOverflow();
      }
    } else {
      ASSERT(!info->code().is_null());
      Handle<Code> code = info->code();
      // Set optimizable to false if this is disallowed by the shared
      // function info, e.g., we might have flushed the code and must
      // reset this bit when lazy compiling the code again.
      if (shared->optimization_disabled()) code->set_optimizable(false);

      Handle<JSFunction> function = info->closure();
      RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG, info, shared);

      if (info->IsOptimizing()) {
        ASSERT(shared->scope_info() != ScopeInfo::Empty());
        function->ReplaceCode(*code);
      } else {
        // Update the shared function info with the compiled code and the
        // scope info.  Please note, that the order of the shared function
        // info initialization is important since set_scope_info might
        // trigger a GC, causing the ASSERT below to be invalid if the code
        // was flushed. By setting the code object last we avoid this.
        Handle<ScopeInfo> scope_info = ScopeInfo::Create(info->scope());
        shared->set_scope_info(*scope_info);
        shared->set_code(*code);
        if (!function.is_null()) {
          function->ReplaceCode(*code);
          ASSERT(!function->IsOptimized());
        }

        // Set the expected number of properties for instances.
        FunctionLiteral* lit = info->function();
        int expected = lit->expected_property_count();
        SetExpectedNofPropertiesFromEstimate(shared, expected);

        // Set the optimization hints after performing lazy compilation, as
        // these are not set when the function is set up as a lazily
        // compiled function.
        shared->SetThisPropertyAssignmentsInfo(
            lit->has_only_simple_this_property_assignments(),
            *lit->this_property_assignments());

        // Check the function has compiled code.
        ASSERT(shared->is_compiled());
        shared->set_code_age(0);

        if (info->AllowOptimize() && !shared->optimization_disabled()) {
          // If we're asked to always optimize, we compile the optimized
          // version of the function right away - unless the debugger is
          // active as it makes no sense to compile optimized code then.
          if (FLAG_always_opt &&
              !Isolate::Current()->DebuggerHasBreakPoints()) {
            CompilationInfo optimized(function);
            optimized.SetOptimizing(AstNode::kNoNumber);
            return CompileLazy(&optimized);
          }
        }
      }

      return true;
    }
  }

  ASSERT(info->code().is_null());
  return false;
}

Handle<SharedFunctionInfo> Compiler::BuildFunctionInfo(FunctionLiteral* literal,
                                                       Handle<Script> script) {
  // Precondition: code has been parsed and scopes have been analyzed.
  CompilationInfo info(script);
  info.SetFunction(literal);
  info.SetScope(literal->scope());
  info.SetLanguageMode(literal->scope()->language_mode());

  LiveEditFunctionTracker live_edit_tracker(info.isolate(), literal);
  // Determine if the function can be lazily compiled. This is necessary to
  // allow some of our builtin JS files to be lazily compiled. These
  // builtins cannot be handled lazily by the parser, since we have to know
  // if a function uses the special natives syntax, which is something the
  // parser records.
  bool allow_lazy = literal->AllowsLazyCompilation() &&
      !LiveEditFunctionTracker::IsActive(info.isolate());

  Handle<ScopeInfo> scope_info(ScopeInfo::Empty());

  // Generate code
  if (FLAG_lazy && allow_lazy) {
    Handle<Code> code = info.isolate()->builtins()->LazyCompile();
    info.SetCode(code);
  } else if ((V8::UseCrankshaft() && MakeCrankshaftCode(&info)) ||
             (!V8::UseCrankshaft() && FullCodeGenerator::MakeCode(&info))) {
    ASSERT(!info.code().is_null());
    scope_info = ScopeInfo::Create(info.scope());
  } else {
    return Handle<SharedFunctionInfo>::null();
  }

  // Create a shared function info object.
  Handle<SharedFunctionInfo> result =
      FACTORY->NewSharedFunctionInfo(literal->name(),
                                     literal->materialized_literal_count(),
                                     info.code(),
                                     scope_info);
  SetFunctionInfo(result, literal, false, script);
  RecordFunctionCompilation(Logger::FUNCTION_TAG, &info, result);
  result->set_allows_lazy_compilation(allow_lazy);

  // Set the expected number of properties for instances and return
  // the resulting function.
  SetExpectedNofPropertiesFromEstimate(result,
                                       literal->expected_property_count());
  live_edit_tracker.RecordFunctionInfo(result, literal);
  return result;
}

// Sets the function info on a function.
// The start_position points to the first '(' character after the function name
// in the full script source. When counting characters in the script source the
// the first character is number 0 (not 1).
void Compiler::SetFunctionInfo(Handle<SharedFunctionInfo> function_info,
                               FunctionLiteral* lit,
                               bool is_toplevel,
                               Handle<Script> script) {
  function_info->set_length(lit->parameter_count());
  function_info->set_formal_parameter_count(lit->parameter_count());
  function_info->set_script(*script);
  function_info->set_function_token_position(lit->function_token_position());
  function_info->set_start_position(lit->start_position());
  function_info->set_end_position(lit->end_position());
  function_info->set_is_expression(lit->is_expression());
  function_info->set_is_anonymous(lit->is_anonymous());
  function_info->set_is_toplevel(is_toplevel);
  function_info->set_inferred_name(*lit->inferred_name());
  function_info->SetThisPropertyAssignmentsInfo(
      lit->has_only_simple_this_property_assignments(),
      *lit->this_property_assignments());
  function_info->set_allows_lazy_compilation(lit->AllowsLazyCompilation());
  function_info->set_language_mode(lit->language_mode());
  function_info->set_uses_arguments(lit->scope()->arguments() != NULL);
  function_info->set_has_duplicate_parameters(lit->has_duplicate_parameters());
}

void Compiler::RecordFunctionCompilation(Logger::LogEventsAndTags tag,
                                         CompilationInfo* info,
                                         Handle<SharedFunctionInfo> shared) {
  // SharedFunctionInfo is passed separately, because if CompilationInfo
  // was created using Script object, it will not have it.

  // Log the code generation. If source information is available include
  // script name and line number. Check explicitly whether logging is
  // enabled as finding the line number is not free.
  if (info->isolate()->logger()->is_logging() ||
      CpuProfiler::is_profiling(info->isolate())) {
    Handle<Script> script = info->script();
    Handle<Code> code = info->code();
    if (*code == info->isolate()->builtins()->builtin(Builtins::kLazyCompile))
      return;
    if (script->name()->IsString()) {
      int line_num = GetScriptLineNumber(script, shared->start_position()) + 1;
      USE(line_num);
      PROFILE(info->isolate(),
              CodeCreateEvent(Logger::ToNativeByScript(tag, *script),
                              *code,
                              *shared,
                              String::cast(script->name()),
                              line_num));
    } else {
      PROFILE(info->isolate(),
              CodeCreateEvent(Logger::ToNativeByScript(tag, *script),
                              *code,
                              *shared,
                              shared->DebugName()));
    }
  }

  GDBJIT(AddCode(Handle<String>(shared->DebugName()),
                 Handle<Script>(info->script()),
                 Handle<Code>(info->code()),
                 info));
}

} }  // namespace v8::internal


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

      <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"></meta>
      <title>dom4j 1.6.1 Reference Package org.dom4j</title>
      <link rel="stylesheet" href="../../stylesheet.css" type="text/css" title="style"></link>

        org.dom4j

Classes

            AbstractTestCase

            AddAttributeTest

            AddNodeTest

            AttributeDetachTest

            BackedListTest

            CloneTest

            ContentTest

            CopyTest

            DetachTest

            DocTypeTest

            ElementByIDTest

            EmbeddedHandlerTest

            GetQNamesTest

            GetXMLEncodingTest

            HTMLWriterTest

            IndexedElementTest

            IsTextOnlyTest

            IteratorTest

            LineFeedTest

            MakeElementTest

            MergeTextTest

            NamespaceTest

            NamespacesTest

            NodeTypeNameTest

            NormalizeTest

            NullAttributesTest

            ParentTest

            ParseTextTest

            ProcessingInstructionTest

            RoundTripTest

            SAXContentHandlerTest

            SerializeTest

            SetContentTest

            SetTextTest

            ThreadingTest

            UserDataTest

            ValidationTest

            XMLResultTest

            XMLSpaceAttributeTest

            XMLWriterTest

            XPathBugTest

            XPathExamplesTest

            XPathTest

            XSLTTest


text:
using System.Collections;
using UnityEngine;

namespace AngryChicken2D
{

/// <summary>
/// Spawn player.
/// </summary>
	public class SpawnPlayer : MonoBehaviour
	{
		public GameObject playerPrefab;
		bool canSpawn = false;
		SlingShot slingShot;
		GameObject catchObject;

		[Range(3, 30)]
		public int
			respawnTime = 5;

		void Start()
		{
			slingShot = GetComponent<SlingShot>();
			if (playerPrefab == null)
				enabled = false;
		}

		void Update()
		{
			if (canSpawn)
			{
				if (Input.GetKeyDown(KeyCode.Mouse0))
				{
					GameObject.Instantiate(playerPrefab, transform.position, Quaternion.identity);
					canSpawn = false;
				}
			} else
			{
				if (catchObject == null)
				{
					catchObject = slingShot.catchObject;
				}

				if (catchObject != null && Vector2.Distance(catchObject.transform.position, transform.position) > slingShot.maxPower * 1.3f)
				{
					StartCoroutine(Shooting(catchObject));
					catchObject = null;
				}
			}
		}

		IEnumerator Shooting(GameObject obj)
		{
			DestroyObject(obj, 20);
			yield return new WaitForSeconds(respawnTime);
			canSpawn = true;
		}

		void OnGUI()
		{
			if (canSpawn)
				GUILayout.Label("push to next shoot");
		}
	}
}


text:
package ecologylab.bigsemantics.generated.library.wikipediaPage;

import ecologylab.bigsemantics.generated.library.wikipediaPage.WikipediaPage;
import ecologylab.bigsemantics.metadata.Metadata;
import ecologylab.bigsemantics.metadata.builtins.MetadataBuiltinsTypesScope;
import ecologylab.bigsemantics.metadata.mm_name;
import ecologylab.bigsemantics.metadata.scalar.MetadataString;
import ecologylab.bigsemantics.metametadata.MetaMetadataCompositeField;
import ecologylab.bigsemantics.namesandnums.SemanticsNames;
import ecologylab.serialization.annotations.simpl_collection;
import ecologylab.serialization.annotations.simpl_inherit;
import ecologylab.serialization.annotations.simpl_scalar;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@simpl_inherit
public class Paragraph extends Metadata
{
	@simpl_scalar
	private MetadataString text;

	@simpl_collection("wikipedia_page")
	@mm_name("anchors")
	private List<WikipediaPage> anchors;

	public Paragraph()
	{ super(); }

	public Paragraph(MetaMetadataCompositeField mmd) {
		super(mmd);
	}

	public MetadataString	text()
	{
		MetadataString	result = this.text;
		if (result == null)
		{
			result = new MetadataString();
			this.text = result;
		}
		return result;
	}

	public String getText()
	{
		return this.text == null ? null : text().getValue();
	}

	public MetadataString getTextMetadata()
	{
		return text;
	}

	public void setText(String text)
	{
		if (text != null)
			this.text().setValue(text);
	}

	public void setTextMetadata(MetadataString text)
	{
		this.text = text;
	}

	public List<WikipediaPage> getAnchors()
	{
		return anchors;
	}

  // lazy evaluation:
  public List<WikipediaPage> anchors()
  {
    if (anchors == null)
      anchors = new ArrayList<WikipediaPage>();
    return anchors;
  }

  // addTo:
  public void addToAnchors(WikipediaPage element)
  {
    anchors().add(element);
  }

  // size:
  public int anchorsSize()
  {
    return anchors == null ? 0 : anchors.size();
  }

	public void setAnchors(List<WikipediaPage> anchors)
	{
		this.anchors = anchors;
	}
}


text:
package tmp;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *

 *     Given an array of integers, find the largest interval [a, b] (say a < b)
 *     such that if a and b are contained in the array, all the integers between a and b
 *     (i.e. a + 1, a + 2, ..., b - 2, b - 1) are also contained in the array.
 *

 *

 *     This is an interesting algorithm that uses an additional hash table (O(n) memory).
 *     Without additional memory, one would need to sort the array and then examine each
 *     subarray.
 *

 * Created by kedar on 10/25/16.
 */
public class LongestContainedInterval {

    /**
     * Given an array, finds a longest interval that is completely contained in it.
     * @param a the array of integers
     * @return a 2-element 1-dimensional array denoting the min and max of the interval. The
     * interval length then becomes (max - min).
     */
    static int[] find(int[] a) {
        if (a.length == 0)
            throw new IllegalArgumentException("empty array");
        if (a.length == 1)
            return new int[] {a[0], a[0]}; // cache?
        Set<Integer> set = Arrays.stream(a)
                .boxed()
                .collect(Collectors.toSet());
        int min = -1, max = -1;
        int iLen = 0;
        for (int x : a) {
            if (set.isEmpty())
                break;
            int minin = x - 1;
            while (! set.isEmpty() && set.contains(minin)) {
                set.remove(minin);
                minin -= 1;
            }
            minin += 1;
            int maxin = x + 1;
            while (! set.isEmpty() && set.contains(maxin)) {
                set.remove(maxin);
                maxin += 1;
            }
            maxin -= 1;
            set.remove(x);
            int diff = maxin - minin + 1;
            if (diff > iLen) {
                iLen = diff;
                max = maxin;
                min = minin;
            }
        }
        return new int[] {min, max};
    }
}


text:
package iot.jcypher.query.factories.clause;

import iot.jcypher.query.api.APIObjectAccess;
import iot.jcypher.query.api.collection.ICollectExpression;
import iot.jcypher.query.api.pattern.IElement;
import iot.jcypher.query.api.predicate.Concatenator;
import iot.jcypher.query.api.returns.AggregateDistinct;
import iot.jcypher.query.api.returns.RCount;
import iot.jcypher.query.api.returns.RDistinct;
import iot.jcypher.query.api.returns.RElement;
import iot.jcypher.query.api.returns.RFactory;
import iot.jcypher.query.api.returns.RSortable;
import iot.jcypher.query.api.returns.RTerminal;
import iot.jcypher.query.ast.ASTNode;
import iot.jcypher.query.ast.ClauseType;
import iot.jcypher.query.values.JcCollection;
import iot.jcypher.query.values.JcValue;

/**
 *
JCYPHER CLAUSE

 */
public class RETURN {

	/**
	 *
JCYPHER

	 *
return all nodes, relationships and paths found in a query,

	 *
e.g. RETURN.ALL()

	 *

	 */
	public static RTerminal ALL() {
		RTerminal ret = RFactory.ALL();
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
select a named (identified) value

	 *
e.g. RETURN.value(n)

	 *
or an expression like RETURN.value(n.property("age")) to be returned

	 *

	 */
	public static RSortable value(JcValue element) {
		RSortable ret = RFactory.value(element);
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
return the result of evaluating a Predicate Expression (true or false)

	 *
Use Factory Class P to create a Predicate Expressions

	 *
e.g. RETURN.evalPredicate(P.valueOf(a.property("age")).GT(30))

	 *

	 */
	public static RElement<RElement<?>> evalPredicate(Concatenator P) {
		RElement<RElement<?>> ret = RFactory.resultOf(P);
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
try to match a pattern against the graph. If a match is found return true else return false

	 *
Use Factory Class X to create a Pattern Expressions

	 *
e.g. RETURN.existsPattern(X.node(n)...)

	 *

	 */
	public static RElement<RElement<?>> existsPattern(IElement X) {
		RElement<RElement<?>> ret = RFactory.existsPattern(X);
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
return the result of a collection expression

	 *
Use Factory Class C to create a Collection Expressions

	 *
e.g. RETURN.collection(C.COLLECT().property("name").from(nds))

	 *

	 */
	public static RElement<RElement<?>> collection(ICollectExpression C) {
		RElement<RElement<?>> ret = RFactory.resultOf(C);
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
return a collection

	 *
e.g. RETURN.collection(p.nodes())

	 *
or RETURN.collection(n.labels())

	 *

	 */
	public static RElement<RElement<?>> collection(JcCollection collection) {
		RElement<RElement<?>> ret = RFactory.resultOf(collection);
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
return the result of performing an aggregate function like sum(...), avg(...), ...

	 *
e.g. RETURN.aggregate().sum(n.property(amount))

	 *

	 */
	public static AggregateDistinct aggregate() {
		AggregateDistinct ret = RFactory.aggregate();
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
return the size of a collection

	 *
e.g. RETURN.count().value(p.nodes())

	 *

	 */
	public static RCount count() {
		RCount ret = RFactory.count();
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}

	/**
	 *
JCYPHER

	 *
return unique results

	 *
e.g. RETURN.DISTINCT().collection(p.nodes())

	 *

	 */
	public static RDistinct DISTINCT() {
		RDistinct ret = RFactory.DISTINCT();
		ASTNode an = APIObjectAccess.getAstNode(ret);
		an.setClauseType(ClauseType.RETURN);
		return ret;
	}
}


text:
"use strict";

var jsdom = require("../..").jsdom;

// These tests are mostly random regression tests, not systematic parsing tests. They are compiled from the bug tracker.

exports["unclosed  (GH-605)"] = function (t) {
  var doc = jsdom("

first tdsecond td

");

  var tds = doc.getElementsByTagName("td");

  t.equal(tds.length, 2);
  t.equal(tds[0].innerHTML, 'first td');
  t.equal(tds[1].innerHTML, 'second td');

  t.done();
};

exports["multiline attributes (GH-585)"] = function (t) {
  var doc = jsdom("<a data-title='hello \nworld' href='example.org'>link");

  var as = doc.getElementsByTagName("a");

  t.equal(as.length, 1);
  t.equal(as[0].innerHTML, "link");
  t.equal(as[0].getAttribute("data-title"), "hello \nworld");
  t.equal(as[0].getAttribute("href"), "example.org");

  t.done();
};

exports["innerHTML of ");

  var scripts = doc.getElementsByTagName("script");

  t.equal(scripts.length, 1);
  t.equal(scripts[0].innerHTML, "script innerHTML");

  t.done();
};

exports["attributes containing '<' and '>' (GH-494)"] = function (t) {
  var doc = jsdom("<p title='<'>stuff

'>more

just testing
");

  var ps = doc.getElementsByTagName("p");

  t.equal(ps.length, 3);
  t.equal(ps[0].getAttribute("title"), "<");
  t.equal(ps[1].getAttribute("title"), ">");

  t.done();
};

exports["empty attributes (GH-488)"] = function (t) {
  var doc = jsdom("

");

  var divs = doc.getElementsByTagName("div");

  t.equal(divs.length, 1);
  t.equal(divs[0].getAttribute("ng-app"), "");

  t.done();
};

exports["omitting optional closing tags (GH-482)"] = function (t) {
  var doc = jsdom("
First
Second
Third");

  var ps = doc.getElementsByTagName("p");

  t.equal(ps.length, 3);
  t.equal(ps[0].innerHTML, "First");
  t.equal(ps[1].innerHTML, "Second");
  t.equal(ps[2].innerHTML, "Third");

  t.done();
};

exports["crazy attribute names (GH-368)"] = function (t) {
  var doc = jsdom("<p <='' FAIL>stuff
");

  var ps = doc.getElementsByTagName("p");

  t.equal(ps.length, 1);
  t.equal(ps[0].innerHTML, "stuff");
  t.equal(ps[0].getAttribute("<"), "");
  t.equal(ps[0].getAttribute("fail"), "");

  t.done();
};

exports["attribute named 'constructor' (GH-625)"] = function (t) {
  var doc = jsdom("<element constructor='Hello'></element>");

  var els = doc.getElementsByTagName("element");

  t.equal(els.length, 1);
  t.equal(els[0].getAttribute("constructor"), "Hello");
  t.equal(els[0].attributes.length, 1);
  t.equal(els[0].outerHTML, "<element constructor=\"Hello\"></element>");

  t.done();
};

exports["CDATA should parse as bogus comments (GH-618)"] = function (t) {
  var doc = jsdom("
<![CDATA[test]]>
");

  var div = doc.getElementsByTagName("div")[0];

  t.ok(div);
  t.equal(div.childNodes.length, 1);

  var comment = div.childNodes[0];
  t.equal(comment.nodeType, comment.COMMENT_NODE);
  t.equal(comment.nodeValue, "[CDATA[test]]");

  t.equal(doc.documentElement.outerHTML, "

");

  t.done();
};

exports["innerHTML behavior in


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

{% block page_title %}
  Confirming your mortgage
{% endblock %}

{% block content %}

    {% include "includes/phase_banner_beta.html" %}

 Signing mortgage deed

This can take a few minutes - please don't close or refresh the page.

		{% include "includes/john.html" %}

{% endblock %}

{% block body_end %}
  {{ super() }}

  {% include "dialogs/all.html" %}
{% endblock %}


text:
service glusterd restart
chkconfig glusterd on